From ac46df8daea09899ce30dc8fd70986e258c746bf Mon Sep 17 00:00:00 2001 From: "Matt A. Tobin" Date: Fri, 9 Feb 2018 06:46:43 -0500 Subject: Move Add-on SDK source to toolkit/jetpack --- .../source/test/addons/addon-manager/lib/main.js | 8 - .../test/addons/addon-manager/lib/test-main.js | 12 - .../source/test/addons/addon-manager/package.json | 7 - addon-sdk/source/test/addons/author-email/main.js | 14 - .../source/test/addons/author-email/package.json | 6 - .../source/test/addons/child_process/index.js | 39 - .../source/test/addons/child_process/package.json | 5 - .../source/test/addons/chrome/chrome.manifest | 5 - .../addons/chrome/chrome/content/new-window.xul | 4 - .../test/addons/chrome/chrome/content/panel.html | 10 - .../chrome/locale/en-US/description.properties | 1 - .../chrome/locale/ja-JP/description.properties | 1 - .../test/addons/chrome/chrome/skin/style.css | 4 - addon-sdk/source/test/addons/chrome/data/panel.js | 10 - addon-sdk/source/test/addons/chrome/main.js | 97 - addon-sdk/source/test/addons/chrome/package.json | 5 - .../test/addons/content-permissions/httpd.js | 5211 ------------------- .../source/test/addons/content-permissions/main.js | 89 - .../test/addons/content-permissions/package.json | 8 - .../content-script-messages-latency/httpd.js | 5211 ------------------- .../addons/content-script-messages-latency/main.js | 90 - .../content-script-messages-latency/package.json | 6 - addon-sdk/source/test/addons/contributors/main.js | 19 - .../source/test/addons/contributors/package.json | 6 - addon-sdk/source/test/addons/curly-id/lib/main.js | 29 - addon-sdk/source/test/addons/curly-id/package.json | 13 - addon-sdk/source/test/addons/developers/main.js | 19 - .../source/test/addons/developers/package.json | 8 - .../e10s-content/data/test-contentScriptFile.js | 5 - .../addons/e10s-content/data/test-page-worker.html | 13 - .../addons/e10s-content/data/test-page-worker.js | 29 - .../source/test/addons/e10s-content/data/test.html | 13 - .../test/addons/e10s-content/lib/fixtures.js | 8 - .../source/test/addons/e10s-content/lib/httpd.js | 5212 -------------------- .../source/test/addons/e10s-content/lib/main.js | 22 - .../addons/e10s-content/lib/test-content-script.js | 845 ---- .../addons/e10s-content/lib/test-content-worker.js | 1127 ----- .../addons/e10s-content/lib/test-page-worker.js | 524 -- .../source/test/addons/e10s-content/package.json | 11 - .../addons/e10s-l10n/data/test-localization.html | 29 - .../test/addons/e10s-l10n/locale/en.properties | 38 - .../test/addons/e10s-l10n/locale/eo.properties | 5 - .../test/addons/e10s-l10n/locale/fr-FR.properties | 14 - addon-sdk/source/test/addons/e10s-l10n/main.js | 289 -- .../source/test/addons/e10s-l10n/package.json | 5 - addon-sdk/source/test/addons/e10s-remote/main.js | 578 --- .../source/test/addons/e10s-remote/package.json | 9 - .../test/addons/e10s-remote/remote-module.js | 129 - addon-sdk/source/test/addons/e10s-remote/utils.js | 110 - addon-sdk/source/test/addons/e10s-tabs/lib/main.js | 23 - .../e10s-tabs/lib/private-browsing/helper.js | 91 - .../test/addons/e10s-tabs/lib/test-tab-events.js | 238 - .../test/addons/e10s-tabs/lib/test-tab-observer.js | 46 - .../test/addons/e10s-tabs/lib/test-tab-utils.js | 67 - .../source/test/addons/e10s-tabs/lib/test-tab.js | 87 - .../source/test/addons/e10s-tabs/package.json | 11 - addon-sdk/source/test/addons/e10s/lib/main.js | 65 - addon-sdk/source/test/addons/e10s/package.json | 10 - .../test/addons/embedded-webextension/main.js | 159 - .../test/addons/embedded-webextension/package.json | 6 - .../webextension/background-page.js | 10 - .../webextension/content-script.js | 10 - .../webextension/manifest.json | 18 - addon-sdk/source/test/addons/jetpack-addon.ini | 48 - .../l10n-properties/app-extension/application.ini | 11 - .../l10n-properties/app-extension/bootstrap.js | 339 -- .../l10n-properties/app-extension/install.rdf | 33 - .../app-extension/locale/en-GB.properties | 28 - .../app-extension/locale/en-US.properties | 22 - .../app-extension/locale/eo.properties | 5 - .../app-extension/locale/fr-FR.properties | 14 - .../l10n-properties/data/test-localization.html | 24 - .../source/test/addons/l10n-properties/main.js | 202 - .../test/addons/l10n-properties/package.json | 6 - .../test/addons/l10n/data/test-localization.html | 29 - .../source/test/addons/l10n/locale/en.properties | 38 - .../source/test/addons/l10n/locale/eo.properties | 5 - .../test/addons/l10n/locale/fr-FR.properties | 14 - addon-sdk/source/test/addons/l10n/main.js | 289 -- addon-sdk/source/test/addons/l10n/package.json | 5 - .../source/test/addons/layout-change/lib/main.js | 15 - .../layout-change/lib/test-cuddlefish-loader.js | 164 - .../layout-change/lib/test-toolkit-loader.js | 10 - .../source/test/addons/layout-change/package.json | 7 - addon-sdk/source/test/addons/main/main.js | 37 - addon-sdk/source/test/addons/main/package.json | 5 - .../test/addons/name-in-numbers-plus/index.js | 12 - .../test/addons/name-in-numbers-plus/package.json | 6 - .../source/test/addons/name-in-numbers/index.js | 12 - .../test/addons/name-in-numbers/package.json | 6 - addon-sdk/source/test/addons/packaging/main.js | 57 - .../source/test/addons/packaging/package.json | 6 - addon-sdk/source/test/addons/packed/main.js | 20 - addon-sdk/source/test/addons/packed/package.json | 6 - .../addons/page-mod-debugger-post/data/index.html | 11 - .../addons/page-mod-debugger-post/data/script.js | 16 - .../test/addons/page-mod-debugger-post/main.js | 136 - .../addons/page-mod-debugger-post/package.json | 6 - .../addons/page-mod-debugger-pre/data/index.html | 11 - .../addons/page-mod-debugger-pre/data/script.js | 16 - .../test/addons/page-mod-debugger-pre/main.js | 134 - .../test/addons/page-mod-debugger-pre/package.json | 6 - .../source/test/addons/page-worker/data/page.html | 9 - .../source/test/addons/page-worker/data/page.js | 13 - addon-sdk/source/test/addons/page-worker/main.js | 53 - .../source/test/addons/page-worker/package.json | 3 - .../test/addons/places/lib/favicon-helpers.js | 54 - addon-sdk/source/test/addons/places/lib/httpd.js | 5211 ------------------- addon-sdk/source/test/addons/places/lib/main.js | 27 - .../source/test/addons/places/lib/places-helper.js | 239 - .../addons/places/lib/test-places-bookmarks.js | 948 ---- .../test/addons/places/lib/test-places-events.js | 328 -- .../test/addons/places/lib/test-places-favicon.js | 242 - .../test/addons/places/lib/test-places-history.js | 244 - .../test/addons/places/lib/test-places-host.js | 301 -- .../test/addons/places/lib/test-places-utils.js | 78 - addon-sdk/source/test/addons/places/package.json | 5 - .../test/addons/predefined-id-with-at/lib/main.js | 32 - .../test/addons/predefined-id-with-at/package.json | 13 - .../test/addons/preferences-branch/lib/main.js | 28 - .../test/addons/preferences-branch/package.json | 14 - .../test/addons/private-browsing-supported/main.js | 28 - .../addons/private-browsing-supported/package.json | 8 - .../private-browsing-supported/sidebar/utils.js | 67 - .../private-browsing-supported/test-page-mod.js | 119 - .../private-browsing-supported/test-panel.js | 99 - .../test-private-browsing.js | 111 - .../private-browsing-supported/test-selection.js | 447 -- .../private-browsing-supported/test-sidebar.js | 212 - .../addons/private-browsing-supported/test-tabs.js | 34 - .../private-browsing-supported/test-window-tabs.js | 75 - .../private-browsing-supported/test-windows.js | 240 - addon-sdk/source/test/addons/remote/main.js | 578 --- addon-sdk/source/test/addons/remote/package.json | 8 - .../source/test/addons/remote/remote-module.js | 129 - addon-sdk/source/test/addons/remote/utils.js | 110 - addon-sdk/source/test/addons/require/list.js | 6 - addon-sdk/source/test/addons/require/main.js | 87 - addon-sdk/source/test/addons/require/multiple/a.js | 5 - addon-sdk/source/test/addons/require/multiple/b.js | 5 - addon-sdk/source/test/addons/require/package.json | 8 - .../test/addons/require/packages/tabs/main.js | 5 - .../test/addons/require/packages/tabs/package.json | 3 - .../test/addons/require/packages/tabs/page-mod.js | 5 - .../source/test/addons/require/same-folder.js | 5 - .../test/addons/require/sub-folder/module.js | 5 - addon-sdk/source/test/addons/require/tabs.js | 5 - addon-sdk/source/test/addons/self/data/data.md | 1 - addon-sdk/source/test/addons/self/main.js | 23 - addon-sdk/source/test/addons/self/package.json | 5 - .../addons/simple-prefs-l10n/locale/en.properties | 5 - .../source/test/addons/simple-prefs-l10n/main.js | 65 - .../test/addons/simple-prefs-l10n/package.json | 10 - .../app-extension/application.ini | 11 - .../app-extension/bootstrap.js | 339 -- .../app-extension/defaults/preferences/prefs.js | 7 - .../app-extension/install.rdf | 34 - .../app-extension/options.xul | 5 - .../addons/simple-prefs-regression/lib/main.js | 94 - .../addons/simple-prefs-regression/package.json | 24 - .../source/test/addons/simple-prefs/lib/main.js | 109 - .../source/test/addons/simple-prefs/package.json | 32 - .../source/test/addons/standard-id/lib/main.js | 30 - .../source/test/addons/standard-id/package.json | 13 - .../test/addons/tab-close-on-startup/main.js | 31 - .../test/addons/tab-close-on-startup/package.json | 5 - .../test/addons/toolkit-require-reload/main.js | 77 - .../addons/toolkit-require-reload/package.json | 5 - addon-sdk/source/test/addons/translators/main.js | 20 - .../source/test/addons/translators/package.json | 8 - .../test/addons/unsafe-content-script/main.js | 68 - .../test/addons/unsafe-content-script/package.json | 8 - addon-sdk/source/test/buffers/test-read-types.js | 368 -- addon-sdk/source/test/buffers/test-write-types.js | 602 --- .../source/test/commonjs-test-adapter/asserts.js | 54 - addon-sdk/source/test/context-menu/framescript.js | 44 - addon-sdk/source/test/context-menu/test-helper.js | 539 -- addon-sdk/source/test/context-menu/util.js | 141 - addon-sdk/source/test/event/helpers.js | 112 - addon-sdk/source/test/fixtures.js | 41 - .../addon-install-unit-test@mozilla.com.xpi | Bin 5670 -> 0 bytes .../test/fixtures/addon-sdk/data/border-style.css | 4 - .../addon-sdk/data/test-contentScriptFile.js | 5 - .../fixtures/addon-sdk/data/test-page-worker.html | 13 - .../fixtures/addon-sdk/data/test-page-worker.js | 29 - .../source/test/fixtures/addon-sdk/data/test.html | 13 - addon-sdk/source/test/fixtures/addon/bootstrap.js | 9 - addon-sdk/source/test/fixtures/addon/index.js | 4 - addon-sdk/source/test/fixtures/addon/package.json | 5 - .../fixtures/bootstrap-addon/META-INF/manifest.mf | 17 - .../fixtures/bootstrap-addon/META-INF/mozilla.rsa | Bin 4191 -> 0 bytes .../fixtures/bootstrap-addon/META-INF/mozilla.sf | 4 - .../test/fixtures/bootstrap-addon/bootstrap.js | 10 - .../test/fixtures/bootstrap-addon/install.rdf | 27 - .../test/fixtures/bootstrap-addon/options.xul | 3 - addon-sdk/source/test/fixtures/bootstrap/utils.js | 52 - addon-sdk/source/test/fixtures/border-style.css | 4 - .../source/test/fixtures/child-process-scripts.js | 81 - .../fixtures/chrome-worker/addEventListener.js | 6 - .../source/test/fixtures/chrome-worker/jsctypes.js | 6 - .../source/test/fixtures/chrome-worker/onerror.js | 6 - .../test/fixtures/chrome-worker/onmessage.js | 8 - .../test/fixtures/chrome-worker/setTimeout.js | 8 - .../source/test/fixtures/chrome-worker/xhr.js | 11 - addon-sdk/source/test/fixtures/create_xpi.py | 15 - addon-sdk/source/test/fixtures/es5.js | 8 - addon-sdk/source/test/fixtures/include-file.css | 4 - addon-sdk/source/test/fixtures/index.html | 18 - .../source/test/fixtures/jsm-package/Test.jsm | 11 - .../source/test/fixtures/jsm-package/index.js | 46 - .../source/test/fixtures/jsm-package/package.json | 3 - addon-sdk/source/test/fixtures/loader/cycles/a.js | 7 - addon-sdk/source/test/fixtures/loader/cycles/b.js | 7 - addon-sdk/source/test/fixtures/loader/cycles/c.js | 7 - .../source/test/fixtures/loader/cycles/main.js | 14 - .../source/test/fixtures/loader/errors/boomer.js | 7 - .../source/test/fixtures/loader/errors/main.js | 9 - .../test/fixtures/loader/exceptions/boomer.js | 9 - .../source/test/fixtures/loader/exceptions/main.js | 11 - .../source/test/fixtures/loader/globals/main.js | 7 - .../source/test/fixtures/loader/json/invalid.json | 3 - .../source/test/fixtures/loader/json/manifest.json | 14 - .../source/test/fixtures/loader/json/mutation.json | 1 - .../test/fixtures/loader/json/nodotjson.json.js | 8 - .../source/test/fixtures/loader/json/test.json | 3 - .../source/test/fixtures/loader/json/test.json.js | 7 - addon-sdk/source/test/fixtures/loader/lazy/main.js | 9 - .../test/fixtures/loader/missing-twice/file.json | 1 - .../test/fixtures/loader/missing-twice/main.js | 32 - .../source/test/fixtures/loader/missing/main.js | 10 - addon-sdk/source/test/fixtures/loader/self/main.js | 8 - .../test/fixtures/loader/syntax-error/error.js | 11 - .../test/fixtures/loader/syntax-error/main.js | 10 - .../test/fixtures/loader/unsupported/fennec.js | 10 - .../test/fixtures/loader/unsupported/firefox.js | 10 - addon-sdk/source/test/fixtures/mofo_logo.SVG | 45 - addon-sdk/source/test/fixtures/moz.build | 22 - addon-sdk/source/test/fixtures/moz_favicon.ico | Bin 1406 -> 0 bytes .../test/fixtures/native-addon-test/dir/a.js | 5 - .../test/fixtures/native-addon-test/dir/a/index.js | 5 - .../test/fixtures/native-addon-test/dir/b.js | 6 - .../test/fixtures/native-addon-test/dir/c.js | 6 - .../test/fixtures/native-addon-test/dir/dummy.js | 6 - .../test/fixtures/native-addon-test/dir/test.jsm | 6 - .../fixtures/native-addon-test/expectedmap.json | 25 - .../test/fixtures/native-addon-test/index.js | 37 - .../fixtures/native-addon-test/newmodule/index.js | 5 - .../native-addon-test/newmodule/lib/file.js | 5 - .../native-addon-test/newmodule/package.json | 3 - .../test/fixtures/native-addon-test/package.json | 10 - .../test/fixtures/native-addon-test/utils/index.js | 7 - .../test/fixtures/native-overrides-test/ignore.js | 6 - .../test/fixtures/native-overrides-test/index.js | 19 - .../fixtures/native-overrides-test/lib/ignore.js | 6 - .../fixtures/native-overrides-test/lib/internal.js | 6 - .../fixtures/native-overrides-test/lib/tabs.js | 6 - .../fixtures/native-overrides-test/package.json | 18 - .../fixtures/preferences/curly-id/package.json | 14 - .../fixtures/preferences/no-prefs/package.json | 6 - .../preferences/preferences-branch/package.json | 14 - .../fixtures/preferences/simple-prefs/package.json | 75 - .../test/fixtures/sandbox-complex-character.js | 5 - addon-sdk/source/test/fixtures/sandbox-normal.js | 7 - .../test/fixtures/test-addon-extras-window.html | 21 - .../source/test/fixtures/test-addon-extras.html | 31 - .../source/test/fixtures/test-contentScriptFile.js | 5 - .../source/test/fixtures/test-context-menu.js | 5 - .../test/fixtures/test-iframe-postmessage.html | 23 - addon-sdk/source/test/fixtures/test-iframe.html | 12 - addon-sdk/source/test/fixtures/test-iframe.js | 16 - .../source/test/fixtures/test-message-manager.js | 6 - addon-sdk/source/test/fixtures/test-net-url.txt | 1 - addon-sdk/source/test/fixtures/test-page-mod.html | 12 - .../test/fixtures/test-sidebar-addon-global.html | 15 - .../test/fixtures/test-trusted-document.html | 20 - addon-sdk/source/test/fixtures/test.html | 25 - addon-sdk/source/test/fixtures/testLocalXhr.json | 1 - .../test/framescript-manager/frame-script.js | 13 - addon-sdk/source/test/framescript-manager/pong.js | 7 - .../source/test/framescript-util/frame-script.js | 21 - addon-sdk/source/test/jetpack-package.ini | 179 - addon-sdk/source/test/leak/jetpack-package.ini | 7 - addon-sdk/source/test/leak/leak-utils.js | 80 - .../test/leak/test-leak-event-dom-closed-window.js | 29 - addon-sdk/source/test/leak/test-leak-tab-events.js | 46 - .../source/test/leak/test-leak-window-events.js | 65 - addon-sdk/source/test/lib/httpd.js | 5212 -------------------- addon-sdk/source/test/loader/b2g.js | 41 - addon-sdk/source/test/loader/fixture.js | 7 - addon-sdk/source/test/loader/user-global.js | 11 - addon-sdk/source/test/modules/add.js | 9 - addon-sdk/source/test/modules/async1.js | 14 - addon-sdk/source/test/modules/async2.js | 8 - .../source/test/modules/badExportAndReturn.js | 10 - addon-sdk/source/test/modules/badFirst.js | 9 - addon-sdk/source/test/modules/badSecond.js | 8 - addon-sdk/source/test/modules/blue.js | 9 - addon-sdk/source/test/modules/castor.js | 10 - addon-sdk/source/test/modules/cheetah.js | 9 - addon-sdk/source/test/modules/color.js | 7 - addon-sdk/source/test/modules/dupe.js | 15 - addon-sdk/source/test/modules/dupeNested.js | 15 - addon-sdk/source/test/modules/dupeSetExports.js | 8 - addon-sdk/source/test/modules/exportsEquals.js | 5 - addon-sdk/source/test/modules/green.js | 10 - addon-sdk/source/test/modules/lion.js | 7 - addon-sdk/source/test/modules/orange.js | 10 - addon-sdk/source/test/modules/pollux.js | 10 - addon-sdk/source/test/modules/red.js | 16 - addon-sdk/source/test/modules/setExports.js | 5 - addon-sdk/source/test/modules/subtract.js | 9 - addon-sdk/source/test/modules/tiger.js | 8 - addon-sdk/source/test/modules/traditional1.js | 12 - addon-sdk/source/test/modules/traditional2.js | 6 - addon-sdk/source/test/modules/types/cat.js | 5 - addon-sdk/source/test/page-mod/helpers.js | 117 - addon-sdk/source/test/path/test-path.js | 430 -- addon-sdk/source/test/preferences/common.json | 16 - addon-sdk/source/test/preferences/e10s-off.json | 5 - addon-sdk/source/test/preferences/e10s-on.json | 3 - addon-sdk/source/test/preferences/firefox.json | 11 - .../source/test/preferences/no-connections.json | 41 - .../test/preferences/test-e10s-preferences.js | 15 - .../source/test/preferences/test-preferences.js | 15 - addon-sdk/source/test/preferences/test.json | 46 - addon-sdk/source/test/private-browsing/helper.js | 58 - addon-sdk/source/test/private-browsing/tabs.js | 25 - addon-sdk/source/test/private-browsing/windows.js | 115 - .../source/test/querystring/test-querystring.js | 205 - addon-sdk/source/test/sidebar/utils.js | 74 - addon-sdk/source/test/tabs/test-fennec-tabs.js | 595 --- addon-sdk/source/test/tabs/test-firefox-tabs.js | 1305 ----- addon-sdk/source/test/tabs/utils.js | 24 - addon-sdk/source/test/test-addon-bootstrap.js | 97 - addon-sdk/source/test/test-addon-extras.js | 70 - addon-sdk/source/test/test-addon-installer.js | 230 - addon-sdk/source/test/test-addon-window.js | 22 - addon-sdk/source/test/test-api-utils.js | 316 -- addon-sdk/source/test/test-array.js | 103 - addon-sdk/source/test/test-base64.js | 100 - addon-sdk/source/test/test-bootstrap.js | 19 - addon-sdk/source/test/test-browser-events.js | 102 - addon-sdk/source/test/test-buffer.js | 563 --- addon-sdk/source/test/test-byte-streams.js | 169 - addon-sdk/source/test/test-child_process.js | 545 -- addon-sdk/source/test/test-chrome.js | 84 - addon-sdk/source/test/test-clipboard.js | 170 - addon-sdk/source/test/test-collection.js | 128 - .../source/test/test-commonjs-test-adapter.js | 11 - addon-sdk/source/test/test-content-events.js | 92 - addon-sdk/source/test/test-content-script.js | 845 ---- addon-sdk/source/test/test-content-sync-worker.js | 965 ---- addon-sdk/source/test/test-content-worker.js | 1129 ----- addon-sdk/source/test/test-context-menu.html | 98 - addon-sdk/source/test/test-context-menu.js | 3763 -------------- addon-sdk/source/test/test-context-menu@2.js | 1350 ----- addon-sdk/source/test/test-cuddlefish.js | 78 - addon-sdk/source/test/test-deprecate.js | 160 - addon-sdk/source/test/test-dev-panel.js | 426 -- addon-sdk/source/test/test-diffpatcher.js | 8 - addon-sdk/source/test/test-dispatcher.js | 76 - addon-sdk/source/test/test-disposable.js | 393 -- addon-sdk/source/test/test-dom.js | 88 - addon-sdk/source/test/test-environment.js | 49 - addon-sdk/source/test/test-event-core.js | 347 -- addon-sdk/source/test/test-event-dom.js | 92 - addon-sdk/source/test/test-event-target.js | 222 - addon-sdk/source/test/test-event-utils.js | 285 -- addon-sdk/source/test/test-file.js | 271 - addon-sdk/source/test/test-frame-utils.js | 59 - addon-sdk/source/test/test-framescript-manager.js | 32 - addon-sdk/source/test/test-framescript-util.js | 45 - addon-sdk/source/test/test-fs.js | 621 --- addon-sdk/source/test/test-functional.js | 463 -- addon-sdk/source/test/test-globals.js | 30 - addon-sdk/source/test/test-heritage.js | 301 -- addon-sdk/source/test/test-hidden-frame.js | 71 - addon-sdk/source/test/test-host-events.js | 99 - addon-sdk/source/test/test-hotkeys.js | 183 - addon-sdk/source/test/test-httpd.js | 73 - addon-sdk/source/test/test-indexed-db.js | 182 - addon-sdk/source/test/test-jetpack-id.js | 64 - addon-sdk/source/test/test-keyboard-observer.js | 36 - addon-sdk/source/test/test-keyboard-utils.js | 61 - addon-sdk/source/test/test-l10n-locale.js | 169 - addon-sdk/source/test/test-l10n-plural-rules.js | 85 - addon-sdk/source/test/test-lang-type.js | 166 - addon-sdk/source/test/test-libxul.js | 18 - addon-sdk/source/test/test-list.js | 58 - addon-sdk/source/test/test-loader.js | 657 --- addon-sdk/source/test/test-match-pattern.js | 137 - addon-sdk/source/test/test-method.js | 7 - addon-sdk/source/test/test-module.js | 36 - addon-sdk/source/test/test-modules.js | 150 - .../source/test/test-mozilla-toolkit-versioning.js | 59 - addon-sdk/source/test/test-mpl2-license-header.js | 105 - addon-sdk/source/test/test-namespace.js | 120 - addon-sdk/source/test/test-native-loader.js | 423 -- addon-sdk/source/test/test-native-options.js | 183 - addon-sdk/source/test/test-net-url.js | 137 - addon-sdk/source/test/test-node-os.js | 33 - addon-sdk/source/test/test-notifications.js | 94 - addon-sdk/source/test/test-object.js | 36 - addon-sdk/source/test/test-observers.js | 183 - addon-sdk/source/test/test-page-mod-debug.js | 66 - addon-sdk/source/test/test-page-mod.js | 2214 --------- addon-sdk/source/test/test-page-worker.js | 558 --- addon-sdk/source/test/test-panel.js | 1426 ------ addon-sdk/source/test/test-passwords-utils.js | 141 - addon-sdk/source/test/test-passwords.js | 280 -- addon-sdk/source/test/test-path.js | 6 - addon-sdk/source/test/test-plain-text-console.js | 278 -- addon-sdk/source/test/test-preferences-service.js | 155 - addon-sdk/source/test/test-preferences-target.js | 42 - addon-sdk/source/test/test-private-browsing.js | 88 - addon-sdk/source/test/test-promise.js | 461 -- addon-sdk/source/test/test-querystring.js | 6 - addon-sdk/source/test/test-reference.js | 99 - addon-sdk/source/test/test-request.js | 548 -- addon-sdk/source/test/test-require.js | 67 - addon-sdk/source/test/test-rules.js | 79 - addon-sdk/source/test/test-sandbox.js | 161 - addon-sdk/source/test/test-selection.js | 985 ---- addon-sdk/source/test/test-self.js | 79 - addon-sdk/source/test/test-sequence.js | 1245 ----- addon-sdk/source/test/test-set-exports.js | 37 - addon-sdk/source/test/test-shared-require.js | 36 - addon-sdk/source/test/test-simple-prefs.js | 331 -- addon-sdk/source/test/test-simple-storage.js | 322 -- addon-sdk/source/test/test-system-events.js | 278 -- addon-sdk/source/test/test-system-input-output.js | 319 -- addon-sdk/source/test/test-system-runtime.js | 25 - addon-sdk/source/test/test-system-startup.js | 19 - addon-sdk/source/test/test-system.js | 37 - addon-sdk/source/test/test-tab-events.js | 238 - addon-sdk/source/test/test-tab-observer.js | 45 - addon-sdk/source/test/test-tab-utils.js | 69 - addon-sdk/source/test/test-tab.js | 228 - addon-sdk/source/test/test-tabs-common.js | 654 --- addon-sdk/source/test/test-tabs.js | 20 - addon-sdk/source/test/test-test-addon-file.js | 16 - addon-sdk/source/test/test-test-assert.js | 218 - addon-sdk/source/test/test-test-loader.js | 59 - addon-sdk/source/test/test-test-memory.js | 25 - addon-sdk/source/test/test-test-utils-async.js | 86 - addon-sdk/source/test/test-test-utils-generator.js | 76 - addon-sdk/source/test/test-test-utils-sync.js | 84 - addon-sdk/source/test/test-test-utils.js | 81 - addon-sdk/source/test/test-text-streams.js | 154 - addon-sdk/source/test/test-timer.js | 229 - addon-sdk/source/test/test-traceback.js | 139 - addon-sdk/source/test/test-ui-action-button.js | 1182 ----- addon-sdk/source/test/test-ui-frame.js | 252 - addon-sdk/source/test/test-ui-id.js | 43 - .../test/test-ui-sidebar-private-browsing.js | 203 - addon-sdk/source/test/test-ui-sidebar.js | 1579 ------ addon-sdk/source/test/test-ui-toggle-button.js | 1386 ------ addon-sdk/source/test/test-ui-toolbar.js | 511 -- addon-sdk/source/test/test-unit-test-finder.js | 57 - addon-sdk/source/test/test-unit-test.js | 270 - addon-sdk/source/test/test-unload.js | 71 - addon-sdk/source/test/test-unsupported-skip.js | 24 - addon-sdk/source/test/test-uri-resource.js | 43 - addon-sdk/source/test/test-url.js | 502 -- addon-sdk/source/test/test-uuid.js | 26 - addon-sdk/source/test/test-weak-set.js | 146 - addon-sdk/source/test/test-window-events.js | 63 - addon-sdk/source/test/test-window-observer.js | 61 - .../test/test-window-utils-private-browsing.js | 210 - addon-sdk/source/test/test-window-utils.js | 266 - addon-sdk/source/test/test-window-utils2.js | 112 - addon-sdk/source/test/test-windows-common.js | 104 - addon-sdk/source/test/test-windows.js | 24 - addon-sdk/source/test/test-xhr.js | 89 - addon-sdk/source/test/test-xpcom.js | 232 - addon-sdk/source/test/test-xul-app.js | 145 - addon-sdk/source/test/traits/assert.js | 101 - addon-sdk/source/test/traits/utils.js | 56 - addon-sdk/source/test/util.js | 90 - .../source/test/windows/test-fennec-windows.js | 48 - .../source/test/windows/test-firefox-windows.js | 621 --- addon-sdk/source/test/zip/utils.js | 126 - 482 files changed, 86139 deletions(-) delete mode 100644 addon-sdk/source/test/addons/addon-manager/lib/main.js delete mode 100644 addon-sdk/source/test/addons/addon-manager/lib/test-main.js delete mode 100644 addon-sdk/source/test/addons/addon-manager/package.json delete mode 100644 addon-sdk/source/test/addons/author-email/main.js delete mode 100644 addon-sdk/source/test/addons/author-email/package.json delete mode 100644 addon-sdk/source/test/addons/child_process/index.js delete mode 100644 addon-sdk/source/test/addons/child_process/package.json delete mode 100644 addon-sdk/source/test/addons/chrome/chrome.manifest delete mode 100644 addon-sdk/source/test/addons/chrome/chrome/content/new-window.xul delete mode 100644 addon-sdk/source/test/addons/chrome/chrome/content/panel.html delete mode 100644 addon-sdk/source/test/addons/chrome/chrome/locale/en-US/description.properties delete mode 100644 addon-sdk/source/test/addons/chrome/chrome/locale/ja-JP/description.properties delete mode 100644 addon-sdk/source/test/addons/chrome/chrome/skin/style.css delete mode 100644 addon-sdk/source/test/addons/chrome/data/panel.js delete mode 100644 addon-sdk/source/test/addons/chrome/main.js delete mode 100644 addon-sdk/source/test/addons/chrome/package.json delete mode 100644 addon-sdk/source/test/addons/content-permissions/httpd.js delete mode 100644 addon-sdk/source/test/addons/content-permissions/main.js delete mode 100644 addon-sdk/source/test/addons/content-permissions/package.json delete mode 100644 addon-sdk/source/test/addons/content-script-messages-latency/httpd.js delete mode 100644 addon-sdk/source/test/addons/content-script-messages-latency/main.js delete mode 100644 addon-sdk/source/test/addons/content-script-messages-latency/package.json delete mode 100644 addon-sdk/source/test/addons/contributors/main.js delete mode 100644 addon-sdk/source/test/addons/contributors/package.json delete mode 100644 addon-sdk/source/test/addons/curly-id/lib/main.js delete mode 100644 addon-sdk/source/test/addons/curly-id/package.json delete mode 100644 addon-sdk/source/test/addons/developers/main.js delete mode 100644 addon-sdk/source/test/addons/developers/package.json delete mode 100644 addon-sdk/source/test/addons/e10s-content/data/test-contentScriptFile.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/data/test-page-worker.html delete mode 100644 addon-sdk/source/test/addons/e10s-content/data/test-page-worker.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/data/test.html delete mode 100644 addon-sdk/source/test/addons/e10s-content/lib/fixtures.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/lib/httpd.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/lib/main.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/lib/test-content-script.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/lib/test-content-worker.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/lib/test-page-worker.js delete mode 100644 addon-sdk/source/test/addons/e10s-content/package.json delete mode 100644 addon-sdk/source/test/addons/e10s-l10n/data/test-localization.html delete mode 100644 addon-sdk/source/test/addons/e10s-l10n/locale/en.properties delete mode 100644 addon-sdk/source/test/addons/e10s-l10n/locale/eo.properties delete mode 100644 addon-sdk/source/test/addons/e10s-l10n/locale/fr-FR.properties delete mode 100644 addon-sdk/source/test/addons/e10s-l10n/main.js delete mode 100644 addon-sdk/source/test/addons/e10s-l10n/package.json delete mode 100644 addon-sdk/source/test/addons/e10s-remote/main.js delete mode 100644 addon-sdk/source/test/addons/e10s-remote/package.json delete mode 100644 addon-sdk/source/test/addons/e10s-remote/remote-module.js delete mode 100644 addon-sdk/source/test/addons/e10s-remote/utils.js delete mode 100644 addon-sdk/source/test/addons/e10s-tabs/lib/main.js delete mode 100644 addon-sdk/source/test/addons/e10s-tabs/lib/private-browsing/helper.js delete mode 100644 addon-sdk/source/test/addons/e10s-tabs/lib/test-tab-events.js delete mode 100644 addon-sdk/source/test/addons/e10s-tabs/lib/test-tab-observer.js delete mode 100644 addon-sdk/source/test/addons/e10s-tabs/lib/test-tab-utils.js delete mode 100644 addon-sdk/source/test/addons/e10s-tabs/lib/test-tab.js delete mode 100644 addon-sdk/source/test/addons/e10s-tabs/package.json delete mode 100644 addon-sdk/source/test/addons/e10s/lib/main.js delete mode 100644 addon-sdk/source/test/addons/e10s/package.json delete mode 100644 addon-sdk/source/test/addons/embedded-webextension/main.js delete mode 100644 addon-sdk/source/test/addons/embedded-webextension/package.json delete mode 100644 addon-sdk/source/test/addons/embedded-webextension/webextension/background-page.js delete mode 100644 addon-sdk/source/test/addons/embedded-webextension/webextension/content-script.js delete mode 100644 addon-sdk/source/test/addons/embedded-webextension/webextension/manifest.json delete mode 100644 addon-sdk/source/test/addons/jetpack-addon.ini delete mode 100644 addon-sdk/source/test/addons/l10n-properties/app-extension/application.ini delete mode 100644 addon-sdk/source/test/addons/l10n-properties/app-extension/bootstrap.js delete mode 100644 addon-sdk/source/test/addons/l10n-properties/app-extension/install.rdf delete mode 100644 addon-sdk/source/test/addons/l10n-properties/app-extension/locale/en-GB.properties delete mode 100644 addon-sdk/source/test/addons/l10n-properties/app-extension/locale/en-US.properties delete mode 100644 addon-sdk/source/test/addons/l10n-properties/app-extension/locale/eo.properties delete mode 100644 addon-sdk/source/test/addons/l10n-properties/app-extension/locale/fr-FR.properties delete mode 100644 addon-sdk/source/test/addons/l10n-properties/data/test-localization.html delete mode 100644 addon-sdk/source/test/addons/l10n-properties/main.js delete mode 100644 addon-sdk/source/test/addons/l10n-properties/package.json delete mode 100644 addon-sdk/source/test/addons/l10n/data/test-localization.html delete mode 100644 addon-sdk/source/test/addons/l10n/locale/en.properties delete mode 100644 addon-sdk/source/test/addons/l10n/locale/eo.properties delete mode 100644 addon-sdk/source/test/addons/l10n/locale/fr-FR.properties delete mode 100644 addon-sdk/source/test/addons/l10n/main.js delete mode 100644 addon-sdk/source/test/addons/l10n/package.json delete mode 100644 addon-sdk/source/test/addons/layout-change/lib/main.js delete mode 100644 addon-sdk/source/test/addons/layout-change/lib/test-cuddlefish-loader.js delete mode 100644 addon-sdk/source/test/addons/layout-change/lib/test-toolkit-loader.js delete mode 100644 addon-sdk/source/test/addons/layout-change/package.json delete mode 100644 addon-sdk/source/test/addons/main/main.js delete mode 100644 addon-sdk/source/test/addons/main/package.json delete mode 100644 addon-sdk/source/test/addons/name-in-numbers-plus/index.js delete mode 100644 addon-sdk/source/test/addons/name-in-numbers-plus/package.json delete mode 100644 addon-sdk/source/test/addons/name-in-numbers/index.js delete mode 100644 addon-sdk/source/test/addons/name-in-numbers/package.json delete mode 100644 addon-sdk/source/test/addons/packaging/main.js delete mode 100644 addon-sdk/source/test/addons/packaging/package.json delete mode 100644 addon-sdk/source/test/addons/packed/main.js delete mode 100644 addon-sdk/source/test/addons/packed/package.json delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-post/data/index.html delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-post/data/script.js delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-post/main.js delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-post/package.json delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-pre/data/index.html delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-pre/data/script.js delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-pre/main.js delete mode 100644 addon-sdk/source/test/addons/page-mod-debugger-pre/package.json delete mode 100644 addon-sdk/source/test/addons/page-worker/data/page.html delete mode 100644 addon-sdk/source/test/addons/page-worker/data/page.js delete mode 100644 addon-sdk/source/test/addons/page-worker/main.js delete mode 100644 addon-sdk/source/test/addons/page-worker/package.json delete mode 100644 addon-sdk/source/test/addons/places/lib/favicon-helpers.js delete mode 100644 addon-sdk/source/test/addons/places/lib/httpd.js delete mode 100644 addon-sdk/source/test/addons/places/lib/main.js delete mode 100644 addon-sdk/source/test/addons/places/lib/places-helper.js delete mode 100644 addon-sdk/source/test/addons/places/lib/test-places-bookmarks.js delete mode 100644 addon-sdk/source/test/addons/places/lib/test-places-events.js delete mode 100644 addon-sdk/source/test/addons/places/lib/test-places-favicon.js delete mode 100644 addon-sdk/source/test/addons/places/lib/test-places-history.js delete mode 100644 addon-sdk/source/test/addons/places/lib/test-places-host.js delete mode 100644 addon-sdk/source/test/addons/places/lib/test-places-utils.js delete mode 100644 addon-sdk/source/test/addons/places/package.json delete mode 100644 addon-sdk/source/test/addons/predefined-id-with-at/lib/main.js delete mode 100644 addon-sdk/source/test/addons/predefined-id-with-at/package.json delete mode 100644 addon-sdk/source/test/addons/preferences-branch/lib/main.js delete mode 100644 addon-sdk/source/test/addons/preferences-branch/package.json delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/main.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/package.json delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/sidebar/utils.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-page-mod.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-panel.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-private-browsing.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-selection.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-sidebar.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-tabs.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-window-tabs.js delete mode 100644 addon-sdk/source/test/addons/private-browsing-supported/test-windows.js delete mode 100644 addon-sdk/source/test/addons/remote/main.js delete mode 100644 addon-sdk/source/test/addons/remote/package.json delete mode 100644 addon-sdk/source/test/addons/remote/remote-module.js delete mode 100644 addon-sdk/source/test/addons/remote/utils.js delete mode 100644 addon-sdk/source/test/addons/require/list.js delete mode 100644 addon-sdk/source/test/addons/require/main.js delete mode 100644 addon-sdk/source/test/addons/require/multiple/a.js delete mode 100644 addon-sdk/source/test/addons/require/multiple/b.js delete mode 100644 addon-sdk/source/test/addons/require/package.json delete mode 100644 addon-sdk/source/test/addons/require/packages/tabs/main.js delete mode 100644 addon-sdk/source/test/addons/require/packages/tabs/package.json delete mode 100644 addon-sdk/source/test/addons/require/packages/tabs/page-mod.js delete mode 100644 addon-sdk/source/test/addons/require/same-folder.js delete mode 100644 addon-sdk/source/test/addons/require/sub-folder/module.js delete mode 100644 addon-sdk/source/test/addons/require/tabs.js delete mode 100644 addon-sdk/source/test/addons/self/data/data.md delete mode 100644 addon-sdk/source/test/addons/self/main.js delete mode 100644 addon-sdk/source/test/addons/self/package.json delete mode 100644 addon-sdk/source/test/addons/simple-prefs-l10n/locale/en.properties delete mode 100644 addon-sdk/source/test/addons/simple-prefs-l10n/main.js delete mode 100644 addon-sdk/source/test/addons/simple-prefs-l10n/package.json delete mode 100644 addon-sdk/source/test/addons/simple-prefs-regression/app-extension/application.ini delete mode 100644 addon-sdk/source/test/addons/simple-prefs-regression/app-extension/bootstrap.js delete mode 100644 addon-sdk/source/test/addons/simple-prefs-regression/app-extension/defaults/preferences/prefs.js delete mode 100644 addon-sdk/source/test/addons/simple-prefs-regression/app-extension/install.rdf delete mode 100644 addon-sdk/source/test/addons/simple-prefs-regression/app-extension/options.xul delete mode 100644 addon-sdk/source/test/addons/simple-prefs-regression/lib/main.js delete mode 100644 addon-sdk/source/test/addons/simple-prefs-regression/package.json delete mode 100644 addon-sdk/source/test/addons/simple-prefs/lib/main.js delete mode 100644 addon-sdk/source/test/addons/simple-prefs/package.json delete mode 100644 addon-sdk/source/test/addons/standard-id/lib/main.js delete mode 100644 addon-sdk/source/test/addons/standard-id/package.json delete mode 100644 addon-sdk/source/test/addons/tab-close-on-startup/main.js delete mode 100644 addon-sdk/source/test/addons/tab-close-on-startup/package.json delete mode 100644 addon-sdk/source/test/addons/toolkit-require-reload/main.js delete mode 100644 addon-sdk/source/test/addons/toolkit-require-reload/package.json delete mode 100644 addon-sdk/source/test/addons/translators/main.js delete mode 100644 addon-sdk/source/test/addons/translators/package.json delete mode 100644 addon-sdk/source/test/addons/unsafe-content-script/main.js delete mode 100644 addon-sdk/source/test/addons/unsafe-content-script/package.json delete mode 100644 addon-sdk/source/test/buffers/test-read-types.js delete mode 100644 addon-sdk/source/test/buffers/test-write-types.js delete mode 100644 addon-sdk/source/test/commonjs-test-adapter/asserts.js delete mode 100644 addon-sdk/source/test/context-menu/framescript.js delete mode 100644 addon-sdk/source/test/context-menu/test-helper.js delete mode 100644 addon-sdk/source/test/context-menu/util.js delete mode 100644 addon-sdk/source/test/event/helpers.js delete mode 100644 addon-sdk/source/test/fixtures.js delete mode 100644 addon-sdk/source/test/fixtures/addon-install-unit-test@mozilla.com.xpi delete mode 100644 addon-sdk/source/test/fixtures/addon-sdk/data/border-style.css delete mode 100644 addon-sdk/source/test/fixtures/addon-sdk/data/test-contentScriptFile.js delete mode 100644 addon-sdk/source/test/fixtures/addon-sdk/data/test-page-worker.html delete mode 100644 addon-sdk/source/test/fixtures/addon-sdk/data/test-page-worker.js delete mode 100644 addon-sdk/source/test/fixtures/addon-sdk/data/test.html delete mode 100644 addon-sdk/source/test/fixtures/addon/bootstrap.js delete mode 100644 addon-sdk/source/test/fixtures/addon/index.js delete mode 100644 addon-sdk/source/test/fixtures/addon/package.json delete mode 100644 addon-sdk/source/test/fixtures/bootstrap-addon/META-INF/manifest.mf delete mode 100644 addon-sdk/source/test/fixtures/bootstrap-addon/META-INF/mozilla.rsa delete mode 100644 addon-sdk/source/test/fixtures/bootstrap-addon/META-INF/mozilla.sf delete mode 100644 addon-sdk/source/test/fixtures/bootstrap-addon/bootstrap.js delete mode 100644 addon-sdk/source/test/fixtures/bootstrap-addon/install.rdf delete mode 100644 addon-sdk/source/test/fixtures/bootstrap-addon/options.xul delete mode 100644 addon-sdk/source/test/fixtures/bootstrap/utils.js delete mode 100644 addon-sdk/source/test/fixtures/border-style.css delete mode 100644 addon-sdk/source/test/fixtures/child-process-scripts.js delete mode 100644 addon-sdk/source/test/fixtures/chrome-worker/addEventListener.js delete mode 100644 addon-sdk/source/test/fixtures/chrome-worker/jsctypes.js delete mode 100644 addon-sdk/source/test/fixtures/chrome-worker/onerror.js delete mode 100644 addon-sdk/source/test/fixtures/chrome-worker/onmessage.js delete mode 100644 addon-sdk/source/test/fixtures/chrome-worker/setTimeout.js delete mode 100644 addon-sdk/source/test/fixtures/chrome-worker/xhr.js delete mode 100644 addon-sdk/source/test/fixtures/create_xpi.py delete mode 100644 addon-sdk/source/test/fixtures/es5.js delete mode 100644 addon-sdk/source/test/fixtures/include-file.css delete mode 100644 addon-sdk/source/test/fixtures/index.html delete mode 100644 addon-sdk/source/test/fixtures/jsm-package/Test.jsm delete mode 100644 addon-sdk/source/test/fixtures/jsm-package/index.js delete mode 100644 addon-sdk/source/test/fixtures/jsm-package/package.json delete mode 100644 addon-sdk/source/test/fixtures/loader/cycles/a.js delete mode 100644 addon-sdk/source/test/fixtures/loader/cycles/b.js delete mode 100644 addon-sdk/source/test/fixtures/loader/cycles/c.js delete mode 100644 addon-sdk/source/test/fixtures/loader/cycles/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/errors/boomer.js delete mode 100644 addon-sdk/source/test/fixtures/loader/errors/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/exceptions/boomer.js delete mode 100644 addon-sdk/source/test/fixtures/loader/exceptions/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/globals/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/json/invalid.json delete mode 100644 addon-sdk/source/test/fixtures/loader/json/manifest.json delete mode 100644 addon-sdk/source/test/fixtures/loader/json/mutation.json delete mode 100644 addon-sdk/source/test/fixtures/loader/json/nodotjson.json.js delete mode 100644 addon-sdk/source/test/fixtures/loader/json/test.json delete mode 100644 addon-sdk/source/test/fixtures/loader/json/test.json.js delete mode 100644 addon-sdk/source/test/fixtures/loader/lazy/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/missing-twice/file.json delete mode 100644 addon-sdk/source/test/fixtures/loader/missing-twice/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/missing/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/self/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/syntax-error/error.js delete mode 100644 addon-sdk/source/test/fixtures/loader/syntax-error/main.js delete mode 100644 addon-sdk/source/test/fixtures/loader/unsupported/fennec.js delete mode 100644 addon-sdk/source/test/fixtures/loader/unsupported/firefox.js delete mode 100644 addon-sdk/source/test/fixtures/mofo_logo.SVG delete mode 100644 addon-sdk/source/test/fixtures/moz.build delete mode 100644 addon-sdk/source/test/fixtures/moz_favicon.ico delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/dir/a.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/dir/a/index.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/dir/b.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/dir/c.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/dir/dummy.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/dir/test.jsm delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/expectedmap.json delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/index.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/newmodule/index.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/newmodule/lib/file.js delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/newmodule/package.json delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/package.json delete mode 100644 addon-sdk/source/test/fixtures/native-addon-test/utils/index.js delete mode 100644 addon-sdk/source/test/fixtures/native-overrides-test/ignore.js delete mode 100644 addon-sdk/source/test/fixtures/native-overrides-test/index.js delete mode 100644 addon-sdk/source/test/fixtures/native-overrides-test/lib/ignore.js delete mode 100644 addon-sdk/source/test/fixtures/native-overrides-test/lib/internal.js delete mode 100644 addon-sdk/source/test/fixtures/native-overrides-test/lib/tabs.js delete mode 100644 addon-sdk/source/test/fixtures/native-overrides-test/package.json delete mode 100644 addon-sdk/source/test/fixtures/preferences/curly-id/package.json delete mode 100644 addon-sdk/source/test/fixtures/preferences/no-prefs/package.json delete mode 100644 addon-sdk/source/test/fixtures/preferences/preferences-branch/package.json delete mode 100644 addon-sdk/source/test/fixtures/preferences/simple-prefs/package.json delete mode 100644 addon-sdk/source/test/fixtures/sandbox-complex-character.js delete mode 100644 addon-sdk/source/test/fixtures/sandbox-normal.js delete mode 100644 addon-sdk/source/test/fixtures/test-addon-extras-window.html delete mode 100644 addon-sdk/source/test/fixtures/test-addon-extras.html delete mode 100644 addon-sdk/source/test/fixtures/test-contentScriptFile.js delete mode 100644 addon-sdk/source/test/fixtures/test-context-menu.js delete mode 100644 addon-sdk/source/test/fixtures/test-iframe-postmessage.html delete mode 100644 addon-sdk/source/test/fixtures/test-iframe.html delete mode 100644 addon-sdk/source/test/fixtures/test-iframe.js delete mode 100644 addon-sdk/source/test/fixtures/test-message-manager.js delete mode 100644 addon-sdk/source/test/fixtures/test-net-url.txt delete mode 100644 addon-sdk/source/test/fixtures/test-page-mod.html delete mode 100644 addon-sdk/source/test/fixtures/test-sidebar-addon-global.html delete mode 100644 addon-sdk/source/test/fixtures/test-trusted-document.html delete mode 100644 addon-sdk/source/test/fixtures/test.html delete mode 100644 addon-sdk/source/test/fixtures/testLocalXhr.json delete mode 100644 addon-sdk/source/test/framescript-manager/frame-script.js delete mode 100644 addon-sdk/source/test/framescript-manager/pong.js delete mode 100644 addon-sdk/source/test/framescript-util/frame-script.js delete mode 100644 addon-sdk/source/test/jetpack-package.ini delete mode 100644 addon-sdk/source/test/leak/jetpack-package.ini delete mode 100644 addon-sdk/source/test/leak/leak-utils.js delete mode 100644 addon-sdk/source/test/leak/test-leak-event-dom-closed-window.js delete mode 100644 addon-sdk/source/test/leak/test-leak-tab-events.js delete mode 100644 addon-sdk/source/test/leak/test-leak-window-events.js delete mode 100644 addon-sdk/source/test/lib/httpd.js delete mode 100644 addon-sdk/source/test/loader/b2g.js delete mode 100644 addon-sdk/source/test/loader/fixture.js delete mode 100644 addon-sdk/source/test/loader/user-global.js delete mode 100644 addon-sdk/source/test/modules/add.js delete mode 100644 addon-sdk/source/test/modules/async1.js delete mode 100644 addon-sdk/source/test/modules/async2.js delete mode 100644 addon-sdk/source/test/modules/badExportAndReturn.js delete mode 100644 addon-sdk/source/test/modules/badFirst.js delete mode 100644 addon-sdk/source/test/modules/badSecond.js delete mode 100644 addon-sdk/source/test/modules/blue.js delete mode 100644 addon-sdk/source/test/modules/castor.js delete mode 100644 addon-sdk/source/test/modules/cheetah.js delete mode 100644 addon-sdk/source/test/modules/color.js delete mode 100644 addon-sdk/source/test/modules/dupe.js delete mode 100644 addon-sdk/source/test/modules/dupeNested.js delete mode 100644 addon-sdk/source/test/modules/dupeSetExports.js delete mode 100644 addon-sdk/source/test/modules/exportsEquals.js delete mode 100644 addon-sdk/source/test/modules/green.js delete mode 100644 addon-sdk/source/test/modules/lion.js delete mode 100644 addon-sdk/source/test/modules/orange.js delete mode 100644 addon-sdk/source/test/modules/pollux.js delete mode 100644 addon-sdk/source/test/modules/red.js delete mode 100644 addon-sdk/source/test/modules/setExports.js delete mode 100644 addon-sdk/source/test/modules/subtract.js delete mode 100644 addon-sdk/source/test/modules/tiger.js delete mode 100644 addon-sdk/source/test/modules/traditional1.js delete mode 100644 addon-sdk/source/test/modules/traditional2.js delete mode 100644 addon-sdk/source/test/modules/types/cat.js delete mode 100644 addon-sdk/source/test/page-mod/helpers.js delete mode 100644 addon-sdk/source/test/path/test-path.js delete mode 100644 addon-sdk/source/test/preferences/common.json delete mode 100644 addon-sdk/source/test/preferences/e10s-off.json delete mode 100644 addon-sdk/source/test/preferences/e10s-on.json delete mode 100644 addon-sdk/source/test/preferences/firefox.json delete mode 100644 addon-sdk/source/test/preferences/no-connections.json delete mode 100644 addon-sdk/source/test/preferences/test-e10s-preferences.js delete mode 100644 addon-sdk/source/test/preferences/test-preferences.js delete mode 100644 addon-sdk/source/test/preferences/test.json delete mode 100644 addon-sdk/source/test/private-browsing/helper.js delete mode 100644 addon-sdk/source/test/private-browsing/tabs.js delete mode 100644 addon-sdk/source/test/private-browsing/windows.js delete mode 100644 addon-sdk/source/test/querystring/test-querystring.js delete mode 100644 addon-sdk/source/test/sidebar/utils.js delete mode 100644 addon-sdk/source/test/tabs/test-fennec-tabs.js delete mode 100644 addon-sdk/source/test/tabs/test-firefox-tabs.js delete mode 100644 addon-sdk/source/test/tabs/utils.js delete mode 100644 addon-sdk/source/test/test-addon-bootstrap.js delete mode 100644 addon-sdk/source/test/test-addon-extras.js delete mode 100644 addon-sdk/source/test/test-addon-installer.js delete mode 100644 addon-sdk/source/test/test-addon-window.js delete mode 100644 addon-sdk/source/test/test-api-utils.js delete mode 100644 addon-sdk/source/test/test-array.js delete mode 100644 addon-sdk/source/test/test-base64.js delete mode 100644 addon-sdk/source/test/test-bootstrap.js delete mode 100644 addon-sdk/source/test/test-browser-events.js delete mode 100644 addon-sdk/source/test/test-buffer.js delete mode 100644 addon-sdk/source/test/test-byte-streams.js delete mode 100644 addon-sdk/source/test/test-child_process.js delete mode 100644 addon-sdk/source/test/test-chrome.js delete mode 100644 addon-sdk/source/test/test-clipboard.js delete mode 100644 addon-sdk/source/test/test-collection.js delete mode 100644 addon-sdk/source/test/test-commonjs-test-adapter.js delete mode 100644 addon-sdk/source/test/test-content-events.js delete mode 100644 addon-sdk/source/test/test-content-script.js delete mode 100644 addon-sdk/source/test/test-content-sync-worker.js delete mode 100644 addon-sdk/source/test/test-content-worker.js delete mode 100644 addon-sdk/source/test/test-context-menu.html delete mode 100644 addon-sdk/source/test/test-context-menu.js delete mode 100644 addon-sdk/source/test/test-context-menu@2.js delete mode 100644 addon-sdk/source/test/test-cuddlefish.js delete mode 100644 addon-sdk/source/test/test-deprecate.js delete mode 100644 addon-sdk/source/test/test-dev-panel.js delete mode 100644 addon-sdk/source/test/test-diffpatcher.js delete mode 100644 addon-sdk/source/test/test-dispatcher.js delete mode 100644 addon-sdk/source/test/test-disposable.js delete mode 100644 addon-sdk/source/test/test-dom.js delete mode 100644 addon-sdk/source/test/test-environment.js delete mode 100644 addon-sdk/source/test/test-event-core.js delete mode 100644 addon-sdk/source/test/test-event-dom.js delete mode 100644 addon-sdk/source/test/test-event-target.js delete mode 100644 addon-sdk/source/test/test-event-utils.js delete mode 100644 addon-sdk/source/test/test-file.js delete mode 100644 addon-sdk/source/test/test-frame-utils.js delete mode 100644 addon-sdk/source/test/test-framescript-manager.js delete mode 100644 addon-sdk/source/test/test-framescript-util.js delete mode 100644 addon-sdk/source/test/test-fs.js delete mode 100644 addon-sdk/source/test/test-functional.js delete mode 100644 addon-sdk/source/test/test-globals.js delete mode 100644 addon-sdk/source/test/test-heritage.js delete mode 100644 addon-sdk/source/test/test-hidden-frame.js delete mode 100644 addon-sdk/source/test/test-host-events.js delete mode 100644 addon-sdk/source/test/test-hotkeys.js delete mode 100644 addon-sdk/source/test/test-httpd.js delete mode 100644 addon-sdk/source/test/test-indexed-db.js delete mode 100644 addon-sdk/source/test/test-jetpack-id.js delete mode 100644 addon-sdk/source/test/test-keyboard-observer.js delete mode 100644 addon-sdk/source/test/test-keyboard-utils.js delete mode 100644 addon-sdk/source/test/test-l10n-locale.js delete mode 100644 addon-sdk/source/test/test-l10n-plural-rules.js delete mode 100644 addon-sdk/source/test/test-lang-type.js delete mode 100644 addon-sdk/source/test/test-libxul.js delete mode 100644 addon-sdk/source/test/test-list.js delete mode 100644 addon-sdk/source/test/test-loader.js delete mode 100644 addon-sdk/source/test/test-match-pattern.js delete mode 100644 addon-sdk/source/test/test-method.js delete mode 100644 addon-sdk/source/test/test-module.js delete mode 100644 addon-sdk/source/test/test-modules.js delete mode 100644 addon-sdk/source/test/test-mozilla-toolkit-versioning.js delete mode 100644 addon-sdk/source/test/test-mpl2-license-header.js delete mode 100644 addon-sdk/source/test/test-namespace.js delete mode 100644 addon-sdk/source/test/test-native-loader.js delete mode 100644 addon-sdk/source/test/test-native-options.js delete mode 100644 addon-sdk/source/test/test-net-url.js delete mode 100644 addon-sdk/source/test/test-node-os.js delete mode 100644 addon-sdk/source/test/test-notifications.js delete mode 100644 addon-sdk/source/test/test-object.js delete mode 100644 addon-sdk/source/test/test-observers.js delete mode 100644 addon-sdk/source/test/test-page-mod-debug.js delete mode 100644 addon-sdk/source/test/test-page-mod.js delete mode 100644 addon-sdk/source/test/test-page-worker.js delete mode 100644 addon-sdk/source/test/test-panel.js delete mode 100644 addon-sdk/source/test/test-passwords-utils.js delete mode 100644 addon-sdk/source/test/test-passwords.js delete mode 100644 addon-sdk/source/test/test-path.js delete mode 100644 addon-sdk/source/test/test-plain-text-console.js delete mode 100644 addon-sdk/source/test/test-preferences-service.js delete mode 100644 addon-sdk/source/test/test-preferences-target.js delete mode 100644 addon-sdk/source/test/test-private-browsing.js delete mode 100644 addon-sdk/source/test/test-promise.js delete mode 100644 addon-sdk/source/test/test-querystring.js delete mode 100644 addon-sdk/source/test/test-reference.js delete mode 100644 addon-sdk/source/test/test-request.js delete mode 100644 addon-sdk/source/test/test-require.js delete mode 100644 addon-sdk/source/test/test-rules.js delete mode 100644 addon-sdk/source/test/test-sandbox.js delete mode 100644 addon-sdk/source/test/test-selection.js delete mode 100644 addon-sdk/source/test/test-self.js delete mode 100644 addon-sdk/source/test/test-sequence.js delete mode 100644 addon-sdk/source/test/test-set-exports.js delete mode 100644 addon-sdk/source/test/test-shared-require.js delete mode 100644 addon-sdk/source/test/test-simple-prefs.js delete mode 100644 addon-sdk/source/test/test-simple-storage.js delete mode 100644 addon-sdk/source/test/test-system-events.js delete mode 100644 addon-sdk/source/test/test-system-input-output.js delete mode 100644 addon-sdk/source/test/test-system-runtime.js delete mode 100644 addon-sdk/source/test/test-system-startup.js delete mode 100644 addon-sdk/source/test/test-system.js delete mode 100644 addon-sdk/source/test/test-tab-events.js delete mode 100644 addon-sdk/source/test/test-tab-observer.js delete mode 100644 addon-sdk/source/test/test-tab-utils.js delete mode 100644 addon-sdk/source/test/test-tab.js delete mode 100644 addon-sdk/source/test/test-tabs-common.js delete mode 100644 addon-sdk/source/test/test-tabs.js delete mode 100644 addon-sdk/source/test/test-test-addon-file.js delete mode 100644 addon-sdk/source/test/test-test-assert.js delete mode 100644 addon-sdk/source/test/test-test-loader.js delete mode 100644 addon-sdk/source/test/test-test-memory.js delete mode 100644 addon-sdk/source/test/test-test-utils-async.js delete mode 100644 addon-sdk/source/test/test-test-utils-generator.js delete mode 100644 addon-sdk/source/test/test-test-utils-sync.js delete mode 100644 addon-sdk/source/test/test-test-utils.js delete mode 100644 addon-sdk/source/test/test-text-streams.js delete mode 100644 addon-sdk/source/test/test-timer.js delete mode 100644 addon-sdk/source/test/test-traceback.js delete mode 100644 addon-sdk/source/test/test-ui-action-button.js delete mode 100644 addon-sdk/source/test/test-ui-frame.js delete mode 100644 addon-sdk/source/test/test-ui-id.js delete mode 100644 addon-sdk/source/test/test-ui-sidebar-private-browsing.js delete mode 100644 addon-sdk/source/test/test-ui-sidebar.js delete mode 100644 addon-sdk/source/test/test-ui-toggle-button.js delete mode 100644 addon-sdk/source/test/test-ui-toolbar.js delete mode 100644 addon-sdk/source/test/test-unit-test-finder.js delete mode 100644 addon-sdk/source/test/test-unit-test.js delete mode 100644 addon-sdk/source/test/test-unload.js delete mode 100644 addon-sdk/source/test/test-unsupported-skip.js delete mode 100644 addon-sdk/source/test/test-uri-resource.js delete mode 100644 addon-sdk/source/test/test-url.js delete mode 100644 addon-sdk/source/test/test-uuid.js delete mode 100644 addon-sdk/source/test/test-weak-set.js delete mode 100644 addon-sdk/source/test/test-window-events.js delete mode 100644 addon-sdk/source/test/test-window-observer.js delete mode 100644 addon-sdk/source/test/test-window-utils-private-browsing.js delete mode 100644 addon-sdk/source/test/test-window-utils.js delete mode 100644 addon-sdk/source/test/test-window-utils2.js delete mode 100644 addon-sdk/source/test/test-windows-common.js delete mode 100644 addon-sdk/source/test/test-windows.js delete mode 100644 addon-sdk/source/test/test-xhr.js delete mode 100644 addon-sdk/source/test/test-xpcom.js delete mode 100644 addon-sdk/source/test/test-xul-app.js delete mode 100644 addon-sdk/source/test/traits/assert.js delete mode 100644 addon-sdk/source/test/traits/utils.js delete mode 100644 addon-sdk/source/test/util.js delete mode 100644 addon-sdk/source/test/windows/test-fennec-windows.js delete mode 100644 addon-sdk/source/test/windows/test-firefox-windows.js delete mode 100644 addon-sdk/source/test/zip/utils.js (limited to 'addon-sdk/source/test') diff --git a/addon-sdk/source/test/addons/addon-manager/lib/main.js b/addon-sdk/source/test/addons/addon-manager/lib/main.js deleted file mode 100644 index 043424f59..000000000 --- a/addon-sdk/source/test/addons/addon-manager/lib/main.js +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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"; - -module.exports = require("./test-main.js"); - -require('sdk/test/runner').runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/addon-manager/lib/test-main.js b/addon-sdk/source/test/addons/addon-manager/lib/test-main.js deleted file mode 100644 index 7204c4a40..000000000 --- a/addon-sdk/source/test/addons/addon-manager/lib/test-main.js +++ /dev/null @@ -1,12 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { id } = require("sdk/self"); -const { getAddonByID } = require("sdk/addon/manager"); - -exports["test getAddonByID"] = function*(assert) { - let addon = yield getAddonByID(id); - assert.equal(addon.id, id, "getAddonByID works"); -} diff --git a/addon-sdk/source/test/addons/addon-manager/package.json b/addon-sdk/source/test/addons/addon-manager/package.json deleted file mode 100644 index 2ed748498..000000000 --- a/addon-sdk/source/test/addons/addon-manager/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "id": "test-addon-manager@jetpack", - "main": "./lib/main.js", - "name": "test-addon-manager", - "version": "0.0.1", - "author": "Erik Vold" -} diff --git a/addon-sdk/source/test/addons/author-email/main.js b/addon-sdk/source/test/addons/author-email/main.js deleted file mode 100644 index 34786475a..000000000 --- a/addon-sdk/source/test/addons/author-email/main.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'; - -const { id } = require('sdk/self'); -const { getAddonByID } = require('sdk/addon/manager'); - -exports.testContributors = function*(assert) { - let addon = yield getAddonByID(id); - assert.equal(addon.creator.name, 'test ', '< and > characters work'); -} - -require('sdk/test/runner').runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/author-email/package.json b/addon-sdk/source/test/addons/author-email/package.json deleted file mode 100644 index 2654ec431..000000000 --- a/addon-sdk/source/test/addons/author-email/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "id": "test-addon-author-email@jetpack", - "author": "test ", - "version": "0.0.1", - "main": "./main.js" -} diff --git a/addon-sdk/source/test/addons/child_process/index.js b/addon-sdk/source/test/addons/child_process/index.js deleted file mode 100644 index bf69e0380..000000000 --- a/addon-sdk/source/test/addons/child_process/index.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/. */ - -"use strict"; - -/** - * Ensures using child_process and underlying subprocess.jsm - * works within an addon - */ - -const { exec } = require("sdk/system/child_process"); -const { platform, pathFor } = require("sdk/system"); -const PROFILE_DIR = pathFor("ProfD"); -const isWindows = platform.toLowerCase().indexOf("win") === 0; -const app = require("sdk/system/xul-app"); - -// Once Bug 903018 is resolved, just move the application testing to -// module.metadata.engines -if (app.is("Firefox")) { - exports["test child_process in an addon"] = (assert, done) => { - exec(isWindows ? "DIR /A-D" : "ls -al", { - cwd: PROFILE_DIR - }, (err, stdout, stderr) => { - assert.equal(err, null, "no errors"); - assert.equal(stderr, "", "stderr is empty"); - assert.ok(/extensions\.ini/.test(stdout), "stdout output of `ls -al` finds files"); - - if (isWindows) - assert.ok(!//.test(stdout), "passing args works"); - else - assert.ok(/d(r[-|w][-|x]){3}/.test(stdout), "passing args works"); - done(); - }); - }; -} else { - exports["test unsupported"] = (assert) => assert.pass("This application is unsupported."); -} -require("sdk/test/runner").runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/child_process/package.json b/addon-sdk/source/test/addons/child_process/package.json deleted file mode 100644 index 3b882d0c4..000000000 --- a/addon-sdk/source/test/addons/child_process/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "test-child-process@jetpack", - "main": "./index.js", - "version": "0.0.1" -} diff --git a/addon-sdk/source/test/addons/chrome/chrome.manifest b/addon-sdk/source/test/addons/chrome/chrome.manifest deleted file mode 100644 index 35e59a107..000000000 --- a/addon-sdk/source/test/addons/chrome/chrome.manifest +++ /dev/null @@ -1,5 +0,0 @@ -content test chrome/content/ -skin test classic/1.0 chrome/skin/ - -locale test en-US chrome/locale/en-US/ -locale test ja-JP chrome/locale/ja-JP/ diff --git a/addon-sdk/source/test/addons/chrome/chrome/content/new-window.xul b/addon-sdk/source/test/addons/chrome/chrome/content/new-window.xul deleted file mode 100644 index 25e219b80..000000000 --- a/addon-sdk/source/test/addons/chrome/chrome/content/new-window.xul +++ /dev/null @@ -1,4 +0,0 @@ - - - diff --git a/addon-sdk/source/test/addons/chrome/chrome/content/panel.html b/addon-sdk/source/test/addons/chrome/chrome/content/panel.html deleted file mode 100644 index 595cc7455..000000000 --- a/addon-sdk/source/test/addons/chrome/chrome/content/panel.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/addon-sdk/source/test/addons/chrome/chrome/locale/en-US/description.properties b/addon-sdk/source/test/addons/chrome/chrome/locale/en-US/description.properties deleted file mode 100644 index 148e2a127..000000000 --- a/addon-sdk/source/test/addons/chrome/chrome/locale/en-US/description.properties +++ /dev/null @@ -1 +0,0 @@ -test=Test diff --git a/addon-sdk/source/test/addons/chrome/chrome/locale/ja-JP/description.properties b/addon-sdk/source/test/addons/chrome/chrome/locale/ja-JP/description.properties deleted file mode 100644 index cf01ac85b..000000000 --- a/addon-sdk/source/test/addons/chrome/chrome/locale/ja-JP/description.properties +++ /dev/null @@ -1 +0,0 @@ -test=テスト diff --git a/addon-sdk/source/test/addons/chrome/chrome/skin/style.css b/addon-sdk/source/test/addons/chrome/chrome/skin/style.css deleted file mode 100644 index 22abf3596..000000000 --- a/addon-sdk/source/test/addons/chrome/chrome/skin/style.css +++ /dev/null @@ -1,4 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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{} diff --git a/addon-sdk/source/test/addons/chrome/data/panel.js b/addon-sdk/source/test/addons/chrome/data/panel.js deleted file mode 100644 index c38eca852..000000000 --- a/addon-sdk/source/test/addons/chrome/data/panel.js +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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'; - -self.port.on('echo', _ => { - self.port.emit('echo', ''); -}); - -self.port.emit('start', ''); diff --git a/addon-sdk/source/test/addons/chrome/main.js b/addon-sdk/source/test/addons/chrome/main.js deleted file mode 100644 index 84b822458..000000000 --- a/addon-sdk/source/test/addons/chrome/main.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' - -const { Cu, Cc, Ci } = require('chrome'); -const Request = require('sdk/request').Request; -const { WindowTracker } = require('sdk/deprecated/window-utils'); -const { close, open } = require('sdk/window/helpers'); -const { data } = require('sdk/self'); -const { Panel } = require('sdk/panel'); - -const XUL_URL = 'chrome://test/content/new-window.xul' - -const { Services } = Cu.import('resource://gre/modules/Services.jsm', {}); -const { NetUtil } = Cu.import('resource://gre/modules/NetUtil.jsm', {}); - -exports.testChromeSkin = function(assert, done) { - let skinURL = 'chrome://test/skin/style.css'; - - Request({ - url: skinURL, - overrideMimeType: 'text/plain', - onComplete: function (response) { - assert.ok(/test\{\}\s*$/.test(response.text), 'chrome.manifest skin folder was registered!'); - done(); - } - }).get(); - - assert.pass('requesting ' + skinURL); -} - -exports.testChromeContent = function(assert, done) { - let wt = WindowTracker({ - onTrack: function(window) { - if (window.document.documentElement.getAttribute('windowtype') === 'test:window') { - assert.pass('test xul window was opened'); - wt.unload(); - - close(window).then(done, assert.fail); - } - } - }); - - open(XUL_URL).then( - assert.pass.bind(assert, 'opened ' + XUL_URL), - assert.fail); - - assert.pass('opening ' + XUL_URL); -} - -exports.testChromeLocale = function(assert) { - let jpLocalePath = Cc['@mozilla.org/chrome/chrome-registry;1']. - getService(Ci.nsIChromeRegistry). - convertChromeURL(NetUtil.newURI('chrome://test/locale/description.properties')). - spec.replace(/(en\-US|ja\-JP)/, 'ja-JP'); - let enLocalePath = jpLocalePath.replace(/ja\-JP/, 'en-US'); - - let jpStringBundle = Services.strings.createBundle(jpLocalePath); - assert.equal(jpStringBundle.GetStringFromName('test'), - 'テスト', - 'locales ja-JP folder was copied correctly'); - - let enStringBundle = Services.strings.createBundle(enLocalePath); - assert.equal(enStringBundle.GetStringFromName('test'), - 'Test', - 'locales en-US folder was copied correctly'); -} - -exports.testChromeInPanel = function*(assert) { - let panel = Panel({ - contentURL: 'chrome://test/content/panel.html', - contentScriptWhen: 'end', - contentScriptFile: data.url('panel.js') - }); - - yield new Promise(resolve => panel.port.once('start', resolve)); - assert.pass('start was emitted'); - - yield new Promise(resolve => { - panel.once('show', resolve); - panel.show(); - }); - assert.pass('panel shown'); - - yield new Promise(resolve => { - panel.port.once('echo', resolve); - panel.port.emit('echo'); - }); - - assert.pass('got echo'); - - panel.destroy(); - assert.pass('panel is destroyed'); -} - -require('sdk/test/runner').runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/chrome/package.json b/addon-sdk/source/test/addons/chrome/package.json deleted file mode 100644 index 82c6db899..000000000 --- a/addon-sdk/source/test/addons/chrome/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "test-chrome@jetpack", - "main": "./main.js", - "version": "0.0.1" -} diff --git a/addon-sdk/source/test/addons/content-permissions/httpd.js b/addon-sdk/source/test/addons/content-permissions/httpd.js deleted file mode 100644 index 964dc9bbd..000000000 --- a/addon-sdk/source/test/addons/content-permissions/httpd.js +++ /dev/null @@ -1,5211 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -* NOTE: do not edit this file, this is copied from: -* https://github.com/mozilla/addon-sdk/blob/master/test/lib/httpd.js -*/ - -module.metadata = { - "stability": "experimental" -}; - -const { components, CC, Cc, Ci, Cr, Cu } = require("chrome"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - - -const PR_UINT32_MAX = Math.pow(2, 32) - 1; - -/** True if debugging output is enabled, false otherwise. */ -var DEBUG = false; // non-const *only* so tweakable in server tests - -/** True if debugging output should be timestamped. */ -var DEBUG_TIMESTAMP = false; // non-const so tweakable in server tests - -var gGlobalObject = Cc["@mozilla.org/systemprincipal;1"].createInstance(); - -/** -* Asserts that the given condition holds. If it doesn't, the given message is -* dumped, a stack trace is printed, and an exception is thrown to attempt to -* stop execution (which unfortunately must rely upon the exception not being -* accidentally swallowed by the code that uses it). -*/ -function NS_ASSERT(cond, msg) -{ - if (DEBUG && !cond) - { - dumpn("###!!!"); - dumpn("###!!! ASSERTION" + (msg ? ": " + msg : "!")); - dumpn("###!!! Stack follows:"); - - var stack = new Error().stack.split(/\n/); - dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n")); - - throw Cr.NS_ERROR_ABORT; - } -} - -/** Constructs an HTTP error object. */ -function HttpError(code, description) -{ - this.code = code; - this.description = description; -} -HttpError.prototype = -{ - toString: function() - { - return this.code + " " + this.description; - } -}; - -/** -* Errors thrown to trigger specific HTTP server responses. -*/ -const HTTP_400 = new HttpError(400, "Bad Request"); -const HTTP_401 = new HttpError(401, "Unauthorized"); -const HTTP_402 = new HttpError(402, "Payment Required"); -const HTTP_403 = new HttpError(403, "Forbidden"); -const HTTP_404 = new HttpError(404, "Not Found"); -const HTTP_405 = new HttpError(405, "Method Not Allowed"); -const HTTP_406 = new HttpError(406, "Not Acceptable"); -const HTTP_407 = new HttpError(407, "Proxy Authentication Required"); -const HTTP_408 = new HttpError(408, "Request Timeout"); -const HTTP_409 = new HttpError(409, "Conflict"); -const HTTP_410 = new HttpError(410, "Gone"); -const HTTP_411 = new HttpError(411, "Length Required"); -const HTTP_412 = new HttpError(412, "Precondition Failed"); -const HTTP_413 = new HttpError(413, "Request Entity Too Large"); -const HTTP_414 = new HttpError(414, "Request-URI Too Long"); -const HTTP_415 = new HttpError(415, "Unsupported Media Type"); -const HTTP_417 = new HttpError(417, "Expectation Failed"); - -const HTTP_500 = new HttpError(500, "Internal Server Error"); -const HTTP_501 = new HttpError(501, "Not Implemented"); -const HTTP_502 = new HttpError(502, "Bad Gateway"); -const HTTP_503 = new HttpError(503, "Service Unavailable"); -const HTTP_504 = new HttpError(504, "Gateway Timeout"); -const HTTP_505 = new HttpError(505, "HTTP Version Not Supported"); - -/** Creates a hash with fields corresponding to the values in arr. */ -function array2obj(arr) -{ - var obj = {}; - for (var i = 0; i < arr.length; i++) - obj[arr[i]] = arr[i]; - return obj; -} - -/** Returns an array of the integers x through y, inclusive. */ -function range(x, y) -{ - var arr = []; - for (var i = x; i <= y; i++) - arr.push(i); - return arr; -} - -/** An object (hash) whose fields are the numbers of all HTTP error codes. */ -const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505))); - - -/** -* The character used to distinguish hidden files from non-hidden files, a la -* the leading dot in Apache. Since that mechanism also hides files from -* easy display in LXR, ls output, etc. however, we choose instead to use a -* suffix character. If a requested file ends with it, we append another -* when getting the file on the server. If it doesn't, we just look up that -* file. Therefore, any file whose name ends with exactly one of the character -* is "hidden" and available for use by the server. -*/ -const HIDDEN_CHAR = "^"; - -/** -* The file name suffix indicating the file containing overridden headers for -* a requested file. -*/ -const HEADERS_SUFFIX = HIDDEN_CHAR + "headers" + HIDDEN_CHAR; - -/** Type used to denote SJS scripts for CGI-like functionality. */ -const SJS_TYPE = "sjs"; - -/** Base for relative timestamps produced by dumpn(). */ -var firstStamp = 0; - -/** dump(str) with a trailing "\n" -- only outputs if DEBUG. */ -function dumpn(str) -{ - if (DEBUG) - { - var prefix = "HTTPD-INFO | "; - if (DEBUG_TIMESTAMP) - { - if (firstStamp === 0) - firstStamp = Date.now(); - - var elapsed = Date.now() - firstStamp; // milliseconds - var min = Math.floor(elapsed / 60000); - var sec = (elapsed % 60000) / 1000; - - if (sec < 10) - prefix += min + ":0" + sec.toFixed(3) + " | "; - else - prefix += min + ":" + sec.toFixed(3) + " | "; - } - - dump(prefix + str + "\n"); - } -} - -/** Dumps the current JS stack if DEBUG. */ -function dumpStack() -{ - // peel off the frames for dumpStack() and Error() - var stack = new Error().stack.split(/\n/).slice(2); - stack.forEach(dumpn); -} - - -/** The XPCOM thread manager. */ -var gThreadManager = null; - -/** The XPCOM prefs service. */ -var gRootPrefBranch = null; -function getRootPrefBranch() -{ - if (!gRootPrefBranch) - { - gRootPrefBranch = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); - } - return gRootPrefBranch; -} - -/** -* JavaScript constructors for commonly-used classes; precreating these is a -* speedup over doing the same from base principles. See the docs at -* http://developer.mozilla.org/en/docs/components.Constructor for details. -*/ -const ServerSocket = CC("@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "init"); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", - "init"); -const Pipe = CC("@mozilla.org/pipe;1", - "nsIPipe", - "init"); -const FileInputStream = CC("@mozilla.org/network/file-input-stream;1", - "nsIFileInputStream", - "init"); -const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1", - "nsIConverterInputStream", - "init"); -const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1", - "nsIWritablePropertyBag2"); -const SupportsString = CC("@mozilla.org/supports-string;1", - "nsISupportsString"); - -/* These two are non-const only so a test can overwrite them. */ -var BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); -var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1", - "nsIBinaryOutputStream", - "setOutputStream"); - -/** -* Returns the RFC 822/1123 representation of a date. -* -* @param date : Number -* the date, in milliseconds from midnight (00:00:00), January 1, 1970 GMT -* @returns string -* the representation of the given date -*/ -function toDateString(date) -{ - // - // rfc1123-date = wkday "," SP date1 SP time SP "GMT" - // date1 = 2DIGIT SP month SP 4DIGIT - // ; day month year (e.g., 02 Jun 1982) - // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT - // ; 00:00:00 - 23:59:59 - // wkday = "Mon" | "Tue" | "Wed" - // | "Thu" | "Fri" | "Sat" | "Sun" - // month = "Jan" | "Feb" | "Mar" | "Apr" - // | "May" | "Jun" | "Jul" | "Aug" - // | "Sep" | "Oct" | "Nov" | "Dec" - // - - const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - - /** -* Processes a date and returns the encoded UTC time as a string according to -* the format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toTime(date) - { - var hrs = date.getUTCHours(); - var rv = (hrs < 10) ? "0" + hrs : hrs; - - var mins = date.getUTCMinutes(); - rv += ":"; - rv += (mins < 10) ? "0" + mins : mins; - - var secs = date.getUTCSeconds(); - rv += ":"; - rv += (secs < 10) ? "0" + secs : secs; - - return rv; - } - - /** -* Processes a date and returns the encoded UTC date as a string according to -* the date1 format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toDate1(date) - { - var day = date.getUTCDate(); - var month = date.getUTCMonth(); - var year = date.getUTCFullYear(); - - var rv = (day < 10) ? "0" + day : day; - rv += " " + monthStrings[month]; - rv += " " + year; - - return rv; - } - - date = new Date(date); - - const fmtString = "%wkday%, %date1% %time% GMT"; - var rv = fmtString.replace("%wkday%", wkdayStrings[date.getUTCDay()]); - rv = rv.replace("%time%", toTime(date)); - return rv.replace("%date1%", toDate1(date)); -} - -/** -* Prints out a human-readable representation of the object o and its fields, -* omitting those whose names begin with "_" if showMembers != true (to ignore -* "private" properties exposed via getters/setters). -*/ -function printObj(o, showMembers) -{ - var s = "******************************\n"; - s += "o = {\n"; - for (var i in o) - { - if (typeof(i) != "string" || - (showMembers || (i.length > 0 && i[0] != "_"))) - s+= " " + i + ": " + o[i] + ",\n"; - } - s += " };\n"; - s += "******************************"; - dumpn(s); -} - -/** -* Instantiates a new HTTP server. -*/ -function nsHttpServer() -{ - if (!gThreadManager) - gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService(); - - /** The port on which this server listens. */ - this._port = undefined; - - /** The socket associated with this. */ - this._socket = null; - - /** The handler used to process requests to this server. */ - this._handler = new ServerHandler(this); - - /** Naming information for this server. */ - this._identity = new ServerIdentity(); - - /** -* Indicates when the server is to be shut down at the end of the request. -*/ - this._doQuit = false; - - /** -* True if the socket in this is closed (and closure notifications have been -* sent and processed if the socket was ever opened), false otherwise. -*/ - this._socketClosed = true; - - /** -* Used for tracking existing connections and ensuring that all connections -* are properly cleaned up before server shutdown; increases by 1 for every -* new incoming connection. -*/ - this._connectionGen = 0; - - /** -* Hash of all open connections, indexed by connection number at time of -* creation. -*/ - this._connections = {}; -} -nsHttpServer.prototype = -{ - classID: components.ID("{54ef6f81-30af-4b1d-ac55-8ba811293e41}"), - - // NSISERVERSOCKETLISTENER - - /** -* Processes an incoming request coming in on the given socket and contained -* in the given transport. -* -* @param socket : nsIServerSocket -* the socket through which the request was served -* @param trans : nsISocketTransport -* the transport for the request/response -* @see nsIServerSocketListener.onSocketAccepted -*/ - onSocketAccepted: function(socket, trans) - { - dumpn("*** onSocketAccepted(socket=" + socket + ", trans=" + trans + ")"); - - dumpn(">>> new connection on " + trans.host + ":" + trans.port); - - const SEGMENT_SIZE = 8192; - const SEGMENT_COUNT = 1024; - try - { - var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT) - .QueryInterface(Ci.nsIAsyncInputStream); - var output = trans.openOutputStream(0, 0, 0); - } - catch (e) - { - dumpn("*** error opening transport streams: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - var connectionNumber = ++this._connectionGen; - - try - { - var conn = new Connection(input, output, this, socket.port, trans.port, - connectionNumber); - var reader = new RequestReader(conn); - - // XXX add request timeout functionality here! - - // Note: must use main thread here, or we might get a GC that will cause - // threadsafety assertions. We really need to fix XPConnect so that - // you can actually do things in multi-threaded JS. :-( - input.asyncWait(reader, 0, 0, gThreadManager.mainThread); - } - catch (e) - { - // Assume this connection can't be salvaged and bail on it completely; - // don't attempt to close it so that we can assert that any connection - // being closed is in this._connections. - dumpn("*** error in initial request-processing stages: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - this._connections[connectionNumber] = conn; - dumpn("*** starting connection " + connectionNumber); - }, - - /** -* Called when the socket associated with this is closed. -* -* @param socket : nsIServerSocket -* the socket being closed -* @param status : nsresult -* the reason the socket stopped listening (NS_BINDING_ABORTED if the server -* was stopped using nsIHttpServer.stop) -* @see nsIServerSocketListener.onStopListening -*/ - onStopListening: function(socket, status) - { - dumpn(">>> shutting down server on port " + socket.port); - this._socketClosed = true; - if (!this._hasOpenConnections()) - { - dumpn("*** no open connections, notifying async from onStopListening"); - - // Notify asynchronously so that any pending teardown in stop() has a - // chance to run first. - var self = this; - var stopEvent = - { - run: function() - { - dumpn("*** _notifyStopped async callback"); - self._notifyStopped(); - } - }; - gThreadManager.currentThread - .dispatch(stopEvent, Ci.nsIThread.DISPATCH_NORMAL); - } - }, - - // NSIHTTPSERVER - - // - // see nsIHttpServer.start - // - start: function(port) - { - this._start(port, "localhost") - }, - - _start: function(port, host) - { - if (this._socket) - throw Cr.NS_ERROR_ALREADY_INITIALIZED; - - this._port = port; - this._doQuit = this._socketClosed = false; - - this._host = host; - - // The listen queue needs to be long enough to handle - // network.http.max-persistent-connections-per-server concurrent connections, - // plus a safety margin in case some other process is talking to - // the server as well. - var prefs = getRootPrefBranch(); - var maxConnections; - try { - // Bug 776860: The original pref was removed in favor of this new one: - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server") + 5; - } - catch(e) { - maxConnections = prefs.getIntPref("network.http.max-connections-per-server") + 5; - } - - try - { - var loopback = true; - if (this._host != "127.0.0.1" && this._host != "localhost") { - var loopback = false; - } - - var socket = new ServerSocket(this._port, - loopback, // true = localhost, false = everybody - maxConnections); - dumpn(">>> listening on port " + socket.port + ", " + maxConnections + - " pending connections"); - socket.asyncListen(this); - this._identity._initialize(socket.port, host, true); - this._socket = socket; - } - catch (e) - { - dumpn("!!! could not start server on port " + port + ": " + e); - throw Cr.NS_ERROR_NOT_AVAILABLE; - } - }, - - // - // see nsIHttpServer.stop - // - stop: function(callback) - { - if (!callback) - throw Cr.NS_ERROR_NULL_POINTER; - if (!this._socket) - throw Cr.NS_ERROR_UNEXPECTED; - - this._stopCallback = typeof callback === "function" - ? callback - : function() { callback.onStopped(); }; - - dumpn(">>> stopping listening on port " + this._socket.port); - this._socket.close(); - this._socket = null; - - // We can't have this identity any more, and the port on which we're running - // this server now could be meaningless the next time around. - this._identity._teardown(); - - this._doQuit = false; - - // socket-close notification and pending request completion happen async - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (file && (!file.exists() || file.isDirectory())) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handler.registerFile(path, file); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // XXX true path validation! - if (path.charAt(0) != "/" || - path.charAt(path.length - 1) != "/" || - (directory && - (!directory.exists() || !directory.isDirectory()))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX determine behavior of nonexistent /foo/bar when a /foo/bar/ mapping - // exists! - - this._handler.registerDirectory(path, directory); - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - this._handler.registerPathHandler(path, handler); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - this._handler.registerPrefixHandler(prefix, handler); - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(code, handler) - { - this._handler.registerErrorHandler(code, handler); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - this._handler.setIndexHandler(handler); - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - this._handler.registerContentType(ext, type); - }, - - // - // see nsIHttpServer.serverIdentity - // - get identity() - { - return this._identity; - }, - - // - // see nsIHttpServer.getState - // - getState: function(path, k) - { - return this._handler._getState(path, k); - }, - - // - // see nsIHttpServer.setState - // - setState: function(path, k, v) - { - return this._handler._setState(path, k, v); - }, - - // - // see nsIHttpServer.getSharedState - // - getSharedState: function(k) - { - return this._handler._getSharedState(k); - }, - - // - // see nsIHttpServer.setSharedState - // - setSharedState: function(k, v) - { - return this._handler._setSharedState(k, v); - }, - - // - // see nsIHttpServer.getObjectState - // - getObjectState: function(k) - { - return this._handler._getObjectState(k); - }, - - // - // see nsIHttpServer.setObjectState - // - setObjectState: function(k, v) - { - return this._handler._setObjectState(k, v); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIServerSocketListener) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NON-XPCOM PUBLIC API - - /** -* Returns true iff this server is not running (and is not in the process of -* serving any requests still to be processed when the server was last -* stopped after being run). -*/ - isStopped: function() - { - return this._socketClosed && !this._hasOpenConnections(); - }, - - // PRIVATE IMPLEMENTATION - - /** True if this server has any open connections to it, false otherwise. */ - _hasOpenConnections: function() - { - // - // If we have any open connections, they're tracked as numeric properties on - // |this._connections|. The non-standard __count__ property could be used - // to check whether there are any properties, but standard-wise, even - // looking forward to ES5, there's no less ugly yet still O(1) way to do - // this. - // - for (var n in this._connections) - return true; - return false; - }, - - /** Calls the server-stopped callback provided when stop() was called. */ - _notifyStopped: function() - { - NS_ASSERT(this._stopCallback !== null, "double-notifying?"); - NS_ASSERT(!this._hasOpenConnections(), "should be done serving by now"); - - // - // NB: We have to grab this now, null out the member, *then* call the - // callback here, or otherwise the callback could (indirectly) futz with - // this._stopCallback by starting and immediately stopping this, at - // which point we'd be nulling out a field we no longer have a right to - // modify. - // - var callback = this._stopCallback; - this._stopCallback = null; - try - { - callback(); - } - catch (e) - { - // not throwing because this is specified as being usually (but not - // always) asynchronous - dump("!!! error running onStopped callback: " + e + "\n"); - } - }, - - /** -* Notifies this server that the given connection has been closed. -* -* @param connection : Connection -* the connection that was closed -*/ - _connectionClosed: function(connection) - { - NS_ASSERT(connection.number in this._connections, - "closing a connection " + this + " that we never added to the " + - "set of open connections?"); - NS_ASSERT(this._connections[connection.number] === connection, - "connection number mismatch? " + - this._connections[connection.number]); - delete this._connections[connection.number]; - - // Fire a pending server-stopped notification if it's our responsibility. - if (!this._hasOpenConnections() && this._socketClosed) - this._notifyStopped(); - }, - - /** -* Requests that the server be shut down when possible. -*/ - _requestQuit: function() - { - dumpn(">>> requesting a quit"); - dumpStack(); - this._doQuit = true; - } -}; - - -// -// RFC 2396 section 3.2.2: -// -// host = hostname | IPv4address -// hostname = *( domainlabel "." ) toplabel [ "." ] -// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum -// toplabel = alpha | alpha *( alphanum | "-" ) alphanum -// IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit -// - -const HOST_REGEX = - new RegExp("^(?:" + - // *( domainlabel "." ) - "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" + - // toplabel - "[a-z](?:[a-z0-9-]*[a-z0-9])?" + - "|" + - // IPv4 address - "\\d+\\.\\d+\\.\\d+\\.\\d+" + - ")$", - "i"); - - -/** -* Represents the identity of a server. An identity consists of a set of -* (scheme, host, port) tuples denoted as locations (allowing a single server to -* serve multiple sites or to be used behind both HTTP and HTTPS proxies for any -* host/port). Any incoming request must be to one of these locations, or it -* will be rejected with an HTTP 400 error. One location, denoted as the -* primary location, is the location assigned in contexts where a location -* cannot otherwise be endogenously derived, such as for HTTP/1.0 requests. -* -* A single identity may contain at most one location per unique host/port pair; -* other than that, no restrictions are placed upon what locations may -* constitute an identity. -*/ -function ServerIdentity() -{ - /** The scheme of the primary location. */ - this._primaryScheme = "http"; - - /** The hostname of the primary location. */ - this._primaryHost = "127.0.0.1" - - /** The port number of the primary location. */ - this._primaryPort = -1; - - /** -* The current port number for the corresponding server, stored so that a new -* primary location can always be set if the current one is removed. -*/ - this._defaultPort = -1; - - /** -* Maps hosts to maps of ports to schemes, e.g. the following would represent -* https://example.com:789/ and http://example.org/: -* -* { -* "xexample.com": { 789: "https" }, -* "xexample.org": { 80: "http" } -* } -* -* Note the "x" prefix on hostnames, which prevents collisions with special -* JS names like "prototype". -*/ - this._locations = { "xlocalhost": {} }; -} -ServerIdentity.prototype = -{ - // NSIHTTPSERVERIDENTITY - - // - // see nsIHttpServerIdentity.primaryScheme - // - get primaryScheme() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryScheme; - }, - - // - // see nsIHttpServerIdentity.primaryHost - // - get primaryHost() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryHost; - }, - - // - // see nsIHttpServerIdentity.primaryPort - // - get primaryPort() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryPort; - }, - - // - // see nsIHttpServerIdentity.add - // - add: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - this._locations["x" + host] = entry = {}; - - entry[port] = scheme; - }, - - // - // see nsIHttpServerIdentity.remove - // - remove: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return false; - - var present = port in entry; - delete entry[port]; - - if (this._primaryScheme == scheme && - this._primaryHost == host && - this._primaryPort == port && - this._defaultPort !== -1) - { - // Always keep at least one identity in existence at any time, unless - // we're in the process of shutting down (the last condition above). - this._primaryPort = -1; - this._initialize(this._defaultPort, host, false); - } - - return present; - }, - - // - // see nsIHttpServerIdentity.has - // - has: function(scheme, host, port) - { - this._validate(scheme, host, port); - - return "x" + host in this._locations && - scheme === this._locations["x" + host][port]; - }, - - // - // see nsIHttpServerIdentity.has - // - getScheme: function(host, port) - { - this._validate("http", host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return ""; - - return entry[port] || ""; - }, - - // - // see nsIHttpServerIdentity.setPrimary - // - setPrimary: function(scheme, host, port) - { - this._validate(scheme, host, port); - - this.add(scheme, host, port); - - this._primaryScheme = scheme; - this._primaryHost = host; - this._primaryPort = port; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpServerIdentity) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Initializes the primary name for the corresponding server, based on the -* provided port number. -*/ - _initialize: function(port, host, addSecondaryDefault) - { - this._host = host; - if (this._primaryPort !== -1) - this.add("http", host, port); - else - this.setPrimary("http", "localhost", port); - this._defaultPort = port; - - // Only add this if we're being called at server startup - if (addSecondaryDefault && host != "127.0.0.1") - this.add("http", "127.0.0.1", port); - }, - - /** -* Called at server shutdown time, unsets the primary location only if it was -* the default-assigned location and removes the default location from the -* set of locations used. -*/ - _teardown: function() - { - if (this._host != "127.0.0.1") { - // Not the default primary location, nothing special to do here - this.remove("http", "127.0.0.1", this._defaultPort); - } - - // This is a *very* tricky bit of reasoning here; make absolutely sure the - // tests for this code pass before you commit changes to it. - if (this._primaryScheme == "http" && - this._primaryHost == this._host && - this._primaryPort == this._defaultPort) - { - // Make sure we don't trigger the readding logic in .remove(), then remove - // the default location. - var port = this._defaultPort; - this._defaultPort = -1; - this.remove("http", this._host, port); - - // Ensure a server start triggers the setPrimary() path in ._initialize() - this._primaryPort = -1; - } - else - { - // No reason not to remove directly as it's not our primary location - this.remove("http", this._host, this._defaultPort); - } - }, - - /** -* Ensures scheme, host, and port are all valid with respect to RFC 2396. -* -* @throws NS_ERROR_ILLEGAL_VALUE -* if any argument doesn't match the corresponding production -*/ - _validate: function(scheme, host, port) - { - if (scheme !== "http" && scheme !== "https") - { - dumpn("*** server only supports http/https schemes: '" + scheme + "'"); - dumpStack(); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (!HOST_REGEX.test(host)) - { - dumpn("*** unexpected host: '" + host + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (port < 0 || port > 65535) - { - dumpn("*** unexpected port: '" + port + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - } -}; - - -/** -* Represents a connection to the server (and possibly in the future the thread -* on which the connection is processed). -* -* @param input : nsIInputStream -* stream from which incoming data on the connection is read -* @param output : nsIOutputStream -* stream to write data out the connection -* @param server : nsHttpServer -* the server handling the connection -* @param port : int -* the port on which the server is running -* @param outgoingPort : int -* the outgoing port used by this connection -* @param number : uint -* a serial number used to uniquely identify this connection -*/ -function Connection(input, output, server, port, outgoingPort, number) -{ - dumpn("*** opening new connection " + number + " on port " + outgoingPort); - - /** Stream of incoming data. */ - this.input = input; - - /** Stream for outgoing data. */ - this.output = output; - - /** The server associated with this request. */ - this.server = server; - - /** The port on which the server is running. */ - this.port = port; - - /** The outgoing poort used by this connection. */ - this._outgoingPort = outgoingPort; - - /** The serial number of this connection. */ - this.number = number; - - /** -* The request for which a response is being generated, null if the -* incoming request has not been fully received or if it had errors. -*/ - this.request = null; - - /** State variables for debugging. */ - this._closed = this._processed = false; -} -Connection.prototype = -{ - /** Closes this connection's input/output streams. */ - close: function() - { - dumpn("*** closing connection " + this.number + - " on port " + this._outgoingPort); - - this.input.close(); - this.output.close(); - this._closed = true; - - var server = this.server; - server._connectionClosed(this); - - // If an error triggered a server shutdown, act on it now - if (server._doQuit) - server.stop(function() { /* not like we can do anything better */ }); - }, - - /** -* Initiates processing of this connection, using the data in the given -* request. -* -* @param request : Request -* the request which should be processed -*/ - process: function(request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - - this.request = request; - this.server._handler.handleResponse(this); - }, - - /** -* Initiates processing of this connection, generating a response with the -* given HTTP error code. -* -* @param code : uint -* an HTTP code, so in the range [0, 1000) -* @param request : Request -* incomplete data about the incoming request (since there were errors -* during its processing -*/ - processError: function(code, request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - this.request = request; - this.server._handler.handleError(code, this); - }, - - /** Converts this to a string for debugging purposes. */ - toString: function() - { - return ""; - } -}; - - - -/** Returns an array of count bytes from the given input stream. */ -function readBytes(inputStream, count) -{ - return new BinaryInputStream(inputStream).readByteArray(count); -} - - - -/** Request reader processing states; see RequestReader for details. */ -const READER_IN_REQUEST_LINE = 0; -const READER_IN_HEADERS = 1; -const READER_IN_BODY = 2; -const READER_FINISHED = 3; - - -/** -* Reads incoming request data asynchronously, does any necessary preprocessing, -* and forwards it to the request handler. Processing occurs in three states: -* -* READER_IN_REQUEST_LINE Reading the request's status line -* READER_IN_HEADERS Reading headers in the request -* READER_IN_BODY Reading the body of the request -* READER_FINISHED Entire request has been read and processed -* -* During the first two stages, initial metadata about the request is gathered -* into a Request object. Once the status line and headers have been processed, -* we start processing the body of the request into the Request. Finally, when -* the entire body has been read, we create a Response and hand it off to the -* ServerHandler to be given to the appropriate request handler. -* -* @param connection : Connection -* the connection for the request being read -*/ -function RequestReader(connection) -{ - /** Connection metadata for this request. */ - this._connection = connection; - - /** -* A container providing line-by-line access to the raw bytes that make up the -* data which has been read from the connection but has not yet been acted -* upon (by passing it to the request handler or by extracting request -* metadata from it). -*/ - this._data = new LineData(); - - /** -* The amount of data remaining to be read from the body of this request. -* After all headers in the request have been read this is the value in the -* Content-Length header, but as the body is read its value decreases to zero. -*/ - this._contentLength = 0; - - /** The current state of parsing the incoming request. */ - this._state = READER_IN_REQUEST_LINE; - - /** Metadata constructed from the incoming request for the request handler. */ - this._metadata = new Request(connection.port); - - /** -* Used to preserve state if we run out of line data midway through a -* multi-line header. _lastHeaderName stores the name of the header, while -* _lastHeaderValue stores the value we've seen so far for the header. -* -* These fields are always either both undefined or both strings. -*/ - this._lastHeaderName = this._lastHeaderValue = undefined; -} -RequestReader.prototype = -{ - // NSIINPUTSTREAMCALLBACK - - /** -* Called when more data from the incoming request is available. This method -* then reads the available data from input and deals with that data as -* necessary, depending upon the syntax of already-downloaded data. -* -* @param input : nsIAsyncInputStream -* the stream of incoming data from the connection -*/ - onInputStreamReady: function(input) - { - dumpn("*** onInputStreamReady(input=" + input + ") on thread " + - gThreadManager.currentThread + " (main is " + - gThreadManager.mainThread + ")"); - dumpn("*** this._state == " + this._state); - - // Handle cases where we get more data after a request error has been - // discovered but *before* we can close the connection. - var data = this._data; - if (!data) - return; - - try - { - data.appendBytes(readBytes(input, input.available())); - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** WARNING: unexpected error when reading from socket; will " + - "be treated as if the input stream had been closed"); - dumpn("*** WARNING: actual error was: " + e); - } - - // We've lost a race -- input has been closed, but we're still expecting - // to read more data. available() will throw in this case, and since - // we're dead in the water now, destroy the connection. - dumpn("*** onInputStreamReady called on a closed input, destroying " + - "connection"); - this._connection.close(); - return; - } - - switch (this._state) - { - default: - NS_ASSERT(false, "invalid state: " + this._state); - break; - - case READER_IN_REQUEST_LINE: - if (!this._processRequestLine()) - break; - /* fall through */ - - case READER_IN_HEADERS: - if (!this._processHeaders()) - break; - /* fall through */ - - case READER_IN_BODY: - this._processBody(); - } - - if (this._state != READER_FINISHED) - input.asyncWait(this, 0, 0, gThreadManager.currentThread); - }, - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIInputStreamCallback) || - aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE API - - /** -* Processes unprocessed, downloaded data as a request line. -* -* @returns boolean -* true iff the request line has been fully processed -*/ - _processRequestLine: function() - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - // Servers SHOULD ignore any empty line(s) received where a Request-Line - // is expected (section 4.1). - var data = this._data; - var line = {}; - var readSuccess; - while ((readSuccess = data.readLine(line)) && line.value == "") - dumpn("*** ignoring beginning blank line..."); - - // if we don't have a full line, wait until we do - if (!readSuccess) - return false; - - // we have the first non-blank line - try - { - this._parseRequestLine(line.value); - this._state = READER_IN_HEADERS; - return true; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing request headers. -* -* @returns boolean -* true iff header data in the request has been fully processed -*/ - _processHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - // XXX things to fix here: - // - // - need to support RFC 2047-encoded non-US-ASCII characters - - try - { - var done = this._parseHeaders(); - if (done) - { - var request = this._metadata; - - // XXX this is wrong for requests with transfer-encodings applied to - // them, particularly chunked (which by its nature can have no - // meaningful Content-Length header)! - this._contentLength = request.hasHeader("Content-Length") - ? parseInt(request.getHeader("Content-Length"), 10) - : 0; - dumpn("_processHeaders, Content-length=" + this._contentLength); - - this._state = READER_IN_BODY; - } - return done; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing the request body. -* -* @returns boolean -* true iff the request body has been fully processed -*/ - _processBody: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - // XXX handle chunked transfer-coding request bodies! - - try - { - if (this._contentLength > 0) - { - var data = this._data.purge(); - var count = Math.min(data.length, this._contentLength); - dumpn("*** loading data=" + data + " len=" + data.length + - " excess=" + (data.length - count)); - - var bos = new BinaryOutputStream(this._metadata._bodyOutputStream); - bos.writeByteArray(data, count); - this._contentLength -= count; - } - - dumpn("*** remaining body data len=" + this._contentLength); - if (this._contentLength == 0) - { - this._validateRequest(); - this._state = READER_FINISHED; - this._handleResponse(); - return true; - } - - return false; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Does various post-header checks on the data in this request. -* -* @throws : HttpError -* if the request was malformed in some way -*/ - _validateRequest: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - dumpn("*** _validateRequest"); - - var metadata = this._metadata; - var headers = metadata._headers; - - // 19.6.1.1 -- servers MUST report 400 to HTTP/1.1 requests w/o Host header - var identity = this._connection.server.identity; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - { - if (!headers.hasHeader("Host")) - { - dumpn("*** malformed HTTP/1.1 or greater request with no Host header!"); - throw HTTP_400; - } - - // If the Request-URI wasn't absolute, then we need to determine our host. - // We have to determine what scheme was used to access us based on the - // server identity data at this point, because the request just doesn't - // contain enough data on its own to do this, sadly. - if (!metadata._host) - { - var host, port; - var hostPort = headers.getHeader("Host"); - var colon = hostPort.indexOf(":"); - if (colon < 0) - { - host = hostPort; - port = ""; - } - else - { - host = hostPort.substring(0, colon); - port = hostPort.substring(colon + 1); - } - - // NB: We allow an empty port here because, oddly, a colon may be - // present even without a port number, e.g. "example.com:"; in this - // case the default port applies. - if (!HOST_REGEX.test(host) || !/^\d*$/.test(port)) - { - dumpn("*** malformed hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - // If we're not given a port, we're stuck, because we don't know what - // scheme to use to look up the correct port here, in general. Since - // the HTTPS case requires a tunnel/proxy and thus requires that the - // requested URI be absolute (and thus contain the necessary - // information), let's assume HTTP will prevail and use that. - port = +port || 80; - - var scheme = identity.getScheme(host, port); - if (!scheme) - { - dumpn("*** unrecognized hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - } - } - else - { - NS_ASSERT(metadata._host === undefined, - "HTTP/1.0 doesn't allow absolute paths in the request line!"); - - metadata._scheme = identity.primaryScheme; - metadata._host = identity.primaryHost; - metadata._port = identity.primaryPort; - } - - NS_ASSERT(identity.has(metadata._scheme, metadata._host, metadata._port), - "must have a location we recognize by now!"); - }, - - /** -* Handles responses in case of error, either in the server or in the request. -* -* @param e -* the specific error encountered, which is an HttpError in the case where -* the request is in some way invalid or cannot be fulfilled; if this isn't -* an HttpError we're going to be paranoid and shut down, because that -* shouldn't happen, ever -*/ - _handleError: function(e) - { - // Don't fall back into normal processing! - this._state = READER_FINISHED; - - var server = this._connection.server; - if (e instanceof HttpError) - { - var code = e.code; - } - else - { - dumpn("!!! UNEXPECTED ERROR: " + e + - (e.lineNumber ? ", line " + e.lineNumber : "")); - - // no idea what happened -- be paranoid and shut down - code = 500; - server._requestQuit(); - } - - // make attempted reuse of data an error - this._data = null; - - this._connection.processError(code, this._metadata); - }, - - /** -* Now that we've read the request line and headers, we can actually hand off -* the request to be handled. -* -* This method is called once per request, after the request line and all -* headers and the body, if any, have been received. -*/ - _handleResponse: function() - { - NS_ASSERT(this._state == READER_FINISHED); - - // We don't need the line-based data any more, so make attempted reuse an - // error. - this._data = null; - - this._connection.process(this._metadata); - }, - - - // PARSING - - /** -* Parses the request line for the HTTP request associated with this. -* -* @param line : string -* the request line -*/ - _parseRequestLine: function(line) - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - dumpn("*** _parseRequestLine('" + line + "')"); - - var metadata = this._metadata; - - // clients and servers SHOULD accept any amount of SP or HT characters - // between fields, even though only a single SP is required (section 19.3) - var request = line.split(/[ \t]+/); - if (!request || request.length != 3) - throw HTTP_400; - - metadata._method = request[0]; - - // get the HTTP version - var ver = request[2]; - var match = ver.match(/^HTTP\/(\d+\.\d+)$/); - if (!match) - throw HTTP_400; - - // determine HTTP version - try - { - metadata._httpVersion = new nsHttpVersion(match[1]); - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_0)) - throw "unsupported HTTP version"; - } - catch (e) - { - // we support HTTP/1.0 and HTTP/1.1 only - throw HTTP_501; - } - - - var fullPath = request[1]; - var serverIdentity = this._connection.server.identity; - - var scheme, host, port; - - if (fullPath.charAt(0) != "/") - { - // No absolute paths in the request line in HTTP prior to 1.1 - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - throw HTTP_400; - - try - { - var uri = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService) - .newURI(fullPath, null, null); - fullPath = uri.path; - scheme = uri.scheme; - host = metadata._host = uri.asciiHost; - port = uri.port; - if (port === -1) - { - if (scheme === "http") - port = 80; - else if (scheme === "https") - port = 443; - else - throw HTTP_400; - } - } - catch (e) - { - // If the host is not a valid host on the server, the response MUST be a - // 400 (Bad Request) error message (section 5.2). Alternately, the URI - // is malformed. - throw HTTP_400; - } - - if (!serverIdentity.has(scheme, host, port) || fullPath.charAt(0) != "/") - throw HTTP_400; - } - - var splitter = fullPath.indexOf("?"); - if (splitter < 0) - { - // _queryString already set in ctor - metadata._path = fullPath; - } - else - { - metadata._path = fullPath.substring(0, splitter); - metadata._queryString = fullPath.substring(splitter + 1); - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - }, - - /** -* Parses all available HTTP headers in this until the header-ending CRLFCRLF, -* adding them to the store of headers in the request. -* -* @throws -* HTTP_400 if the headers are malformed -* @returns boolean -* true if all headers have now been processed, false otherwise -*/ - _parseHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - dumpn("*** _parseHeaders"); - - var data = this._data; - - var headers = this._metadata._headers; - var lastName = this._lastHeaderName; - var lastVal = this._lastHeaderValue; - - var line = {}; - while (true) - { - NS_ASSERT(!((lastVal === undefined) ^ (lastName === undefined)), - lastName === undefined ? - "lastVal without lastName? lastVal: '" + lastVal + "'" : - "lastName without lastVal? lastName: '" + lastName + "'"); - - if (!data.readLine(line)) - { - // save any data we have from the header we might still be processing - this._lastHeaderName = lastName; - this._lastHeaderValue = lastVal; - return false; - } - - var lineText = line.value; - var firstChar = lineText.charAt(0); - - // blank line means end of headers - if (lineText == "") - { - // we're finished with the previous header - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - else - { - // no headers in request -- valid for HTTP/1.0 requests - } - - // either way, we're done processing headers - this._state = READER_IN_BODY; - return true; - } - else if (firstChar == " " || firstChar == "\t") - { - // multi-line header if we've already seen a header line - if (!lastName) - { - // we don't have a header to continue! - throw HTTP_400; - } - - // append this line's text to the value; starts with SP/HT, so no need - // for separating whitespace - lastVal += lineText; - } - else - { - // we have a new header, so set the old one (if one existed) - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - - var colon = lineText.indexOf(":"); // first colon must be splitter - if (colon < 1) - { - // no colon or missing header field-name - throw HTTP_400; - } - - // set header name, value (to be set in the next loop, usually) - lastName = lineText.substring(0, colon); - lastVal = lineText.substring(colon + 1); - } // empty, continuation, start of header - } // while (true) - } -}; - - -/** The character codes for CR and LF. */ -const CR = 0x0D, LF = 0x0A; - -/** -* Calculates the number of characters before the first CRLF pair in array, or -* -1 if the array contains no CRLF pair. -* -* @param array : Array -* an array of numbers in the range [0, 256), each representing a single -* character; the first CRLF is the lowest index i where -* |array[i] == "\r".charCodeAt(0)| and |array[i+1] == "\n".charCodeAt(0)|, -* if such an |i| exists, and -1 otherwise -* @returns int -* the index of the first CRLF if any were present, -1 otherwise -*/ -function findCRLF(array) -{ - for (var i = array.indexOf(CR); i >= 0; i = array.indexOf(CR, i + 1)) - { - if (array[i + 1] == LF) - return i; - } - return -1; -} - - -/** -* A container which provides line-by-line access to the arrays of bytes with -* which it is seeded. -*/ -function LineData() -{ - /** An array of queued bytes from which to get line-based characters. */ - this._data = []; -} -LineData.prototype = -{ - /** -* Appends the bytes in the given array to the internal data cache maintained -* by this. -*/ - appendBytes: function(bytes) - { - Array.prototype.push.apply(this._data, bytes); - }, - - /** -* Removes and returns a line of data, delimited by CRLF, from this. -* -* @param out -* an object whose "value" property will be set to the first line of text -* present in this, sans CRLF, if this contains a full CRLF-delimited line -* of text; if this doesn't contain enough data, the value of the property -* is undefined -* @returns boolean -* true if a full line of data could be read from the data in this, false -* otherwise -*/ - readLine: function(out) - { - var data = this._data; - var length = findCRLF(data); - if (length < 0) - return false; - - // - // We have the index of the CR, so remove all the characters, including - // CRLF, from the array with splice, and convert the removed array into the - // corresponding string, from which we then strip the trailing CRLF. - // - // Getting the line in this matter acknowledges that substring is an O(1) - // operation in SpiderMonkey because strings are immutable, whereas two - // splices, both from the beginning of the data, are less likely to be as - // cheap as a single splice plus two extra character conversions. - // - var line = String.fromCharCode.apply(null, data.splice(0, length + 2)); - out.value = line.substring(0, length); - - return true; - }, - - /** -* Removes the bytes currently within this and returns them in an array. -* -* @returns Array -* the bytes within this when this method is called -*/ - purge: function() - { - var data = this._data; - this._data = []; - return data; - } -}; - - - -/** -* Creates a request-handling function for an nsIHttpRequestHandler object. -*/ -function createHandlerFunc(handler) -{ - return function(metadata, response) { handler.handle(metadata, response); }; -} - - -/** -* The default handler for directories; writes an HTML response containing a -* slightly-formatted directory listing. -*/ -function defaultIndexHandler(metadata, response) -{ - response.setHeader("Content-Type", "text/html", false); - - var path = htmlEscape(decodeURI(metadata.path)); - - // - // Just do a very basic bit of directory listings -- no need for too much - // fanciness, especially since we don't have a style sheet in which we can - // stick rules (don't want to pollute the default path-space). - // - - var body = '\ -\ -' + path + '\ -\ -\ -

' + path + '

\ -
    '; - - var directory = metadata.getProperty("directory").QueryInterface(Ci.nsILocalFile); - NS_ASSERT(directory && directory.isDirectory()); - - var fileList = []; - var files = directory.directoryEntries; - while (files.hasMoreElements()) - { - var f = files.getNext().QueryInterface(Ci.nsIFile); - var name = f.leafName; - if (!f.isHidden() && - (name.charAt(name.length - 1) != HIDDEN_CHAR || - name.charAt(name.length - 2) == HIDDEN_CHAR)) - fileList.push(f); - } - - fileList.sort(fileSort); - - for (var i = 0; i < fileList.length; i++) - { - var file = fileList[i]; - try - { - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - var sep = file.isDirectory() ? "/" : ""; - - // Note: using " to delimit the attribute here because encodeURIComponent - // passes through '. - var item = '
  1. ' + - htmlEscape(name) + sep + - '
  2. '; - - body += item; - } - catch (e) { /* some file system error, ignore the file */ } - } - - body += '
\ -\ -'; - - response.bodyOutputStream.write(body, body.length); -} - -/** -* Sorts a and b (nsIFile objects) into an aesthetically pleasing order. -*/ -function fileSort(a, b) -{ - var dira = a.isDirectory(), dirb = b.isDirectory(); - - if (dira && !dirb) - return -1; - if (dirb && !dira) - return 1; - - var namea = a.leafName.toLowerCase(), nameb = b.leafName.toLowerCase(); - return nameb > namea ? -1 : 1; -} - - -/** -* Converts an externally-provided path into an internal path for use in -* determining file mappings. -* -* @param path -* the path to convert -* @param encoded -* true if the given path should be passed through decodeURI prior to -* conversion -* @throws URIError -* if path is incorrectly encoded -*/ -function toInternalPath(path, encoded) -{ - if (encoded) - path = decodeURI(path); - - var comps = path.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - if (comp.charAt(comp.length - 1) == HIDDEN_CHAR) - comps[i] = comp + HIDDEN_CHAR; - } - return comps.join("/"); -} - - -/** -* Adds custom-specified headers for the given file to the given response, if -* any such headers are specified. -* -* @param file -* the file on the disk which is to be written -* @param metadata -* metadata about the incoming request -* @param response -* the Response to which any specified headers/data should be written -* @throws HTTP_500 -* if an error occurred while processing custom-specified headers -*/ -function maybeAddHeaders(file, metadata, response) -{ - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - - var headerFile = file.parent; - headerFile.append(name + HEADERS_SUFFIX); - - if (!headerFile.exists()) - return; - - const PR_RDONLY = 0x01; - var fis = new FileInputStream(headerFile, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0); - lis.QueryInterface(Ci.nsIUnicharLineInputStream); - - var line = {value: ""}; - var more = lis.readLine(line); - - if (!more && line.value == "") - return; - - - // request line - - var status = line.value; - if (status.indexOf("HTTP ") == 0) - { - status = status.substring(5); - var space = status.indexOf(" "); - var code, description; - if (space < 0) - { - code = status; - description = ""; - } - else - { - code = status.substring(0, space); - description = status.substring(space + 1, status.length); - } - - response.setStatusLine(metadata.httpVersion, parseInt(code, 10), description); - - line.value = ""; - more = lis.readLine(line); - } - - // headers - while (more || line.value != "") - { - var header = line.value; - var colon = header.indexOf(":"); - - response.setHeader(header.substring(0, colon), - header.substring(colon + 1, header.length), - false); // allow overriding server-set headers - - line.value = ""; - more = lis.readLine(line); - } - } - catch (e) - { - dumpn("WARNING: error in headers for " + metadata.path + ": " + e); - throw HTTP_500; - } - finally - { - fis.close(); - } -} - - -/** -* An object which handles requests for a server, executing default and -* overridden behaviors as instructed by the code which uses and manipulates it. -* Default behavior includes the paths / and /trace (diagnostics), with some -* support for HTTP error pages for various codes and fallback to HTTP 500 if -* those codes fail for any reason. -* -* @param server : nsHttpServer -* the server in which this handler is being used -*/ -function ServerHandler(server) -{ - // FIELDS - - /** -* The nsHttpServer instance associated with this handler. -*/ - this._server = server; - - /** -* A FileMap object containing the set of path->nsILocalFile mappings for -* all directory mappings set in the server (e.g., "/" for /var/www/html/, -* "/foo/bar/" for /local/path/, and "/foo/bar/baz/" for /local/path2). -* -* Note carefully: the leading and trailing "/" in each path (not file) are -* removed before insertion to simplify the code which uses this. You have -* been warned! -*/ - this._pathDirectoryMap = new FileMap(); - - /** -* Custom request handlers for the server in which this resides. Path-handler -* pairs are stored as property-value pairs in this property. -* -* @see ServerHandler.prototype._defaultPaths -*/ - this._overridePaths = {}; - - /** -* Custom request handlers for the server in which this resides. Prefix-handler -* pairs are stored as property-value pairs in this property. -*/ - this._overridePrefixes = {}; - - /** -* Custom request handlers for the error handlers in the server in which this -* resides. Path-handler pairs are stored as property-value pairs in this -* property. -* -* @see ServerHandler.prototype._defaultErrors -*/ - this._overrideErrors = {}; - - /** -* Maps file extensions to their MIME types in the server, overriding any -* mapping that might or might not exist in the MIME service. -*/ - this._mimeMappings = {}; - - /** -* The default handler for requests for directories, used to serve directories -* when no index file is present. -*/ - this._indexHandler = defaultIndexHandler; - - /** Per-path state storage for the server. */ - this._state = {}; - - /** Entire-server state storage. */ - this._sharedState = {}; - - /** Entire-server state storage for nsISupports values. */ - this._objectState = {}; -} -ServerHandler.prototype = -{ - // PUBLIC API - - /** -* Handles a request to this server, responding to the request appropriately -* and initiating server shutdown if necessary. -* -* This method never throws an exception. -* -* @param connection : Connection -* the connection for this request -*/ - handleResponse: function(connection) - { - var request = connection.request; - var response = new Response(connection); - - var path = request.path; - dumpn("*** path == " + path); - - try - { - try - { - if (path in this._overridePaths) - { - // explicit paths first, then files based on existing directory mappings, - // then (if the file doesn't exist) built-in server default paths - dumpn("calling override for " + path); - this._overridePaths[path](request, response); - } - else - { - let longestPrefix = ""; - for (let prefix in this._overridePrefixes) - { - if (prefix.length > longestPrefix.length && path.startsWith(prefix)) - { - longestPrefix = prefix; - } - } - if (longestPrefix.length > 0) - { - dumpn("calling prefix override for " + longestPrefix); - this._overridePrefixes[longestPrefix](request, response); - } - else - { - this._handleDefault(request, response); - } - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - if (!(e instanceof HttpError)) - { - dumpn("*** unexpected error: e == " + e); - throw HTTP_500; - } - if (e.code !== 404) - throw e; - - dumpn("*** default: " + (path in this._defaultPaths)); - - response = new Response(connection); - if (path in this._defaultPaths) - this._defaultPaths[path](request, response); - else - throw HTTP_404; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - var errorCode = "internal"; - - try - { - if (!(e instanceof HttpError)) - throw e; - - errorCode = e.code; - dumpn("*** errorCode == " + errorCode); - - response = new Response(connection); - if (e.customErrorHandling) - e.customErrorHandling(response); - this._handleError(errorCode, request, response); - return; - } - catch (e2) - { - dumpn("*** error handling " + errorCode + " error: " + - "e2 == " + e2 + ", shutting down server"); - - connection.server._requestQuit(); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (!file) - { - dumpn("*** unregistering '" + path + "' mapping"); - delete this._overridePaths[path]; - return; - } - - dumpn("*** registering '" + path + "' as mapping to " + file.path); - file = file.clone(); - - var self = this; - this._overridePaths[path] = - function(request, response) - { - if (!file.exists()) - throw HTTP_404; - - response.setStatusLine(request.httpVersion, 200, "OK"); - self._writeFileResponse(request, file, response, 0, file.fileSize); - }; - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - // XXX true path validation! - if (path.charAt(0) != "/") - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePaths, path); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - // XXX true prefix validation! - if (!(prefix.startsWith("/") && prefix.endsWith("/"))) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePrefixes, prefix); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // strip off leading and trailing '/' so that we can use lastIndexOf when - // determining exactly how a path maps onto a mapped directory -- - // conditional is required here to deal with "/".substring(1, 0) being - // converted to "/".substring(0, 1) per the JS specification - var key = path.length == 1 ? "" : path.substring(1, path.length - 1); - - // the path-to-directory mapping code requires that the first character not - // be "/", or it will go into an infinite loop - if (key.charAt(0) == "/") - throw Cr.NS_ERROR_INVALID_ARG; - - key = toInternalPath(key, false); - - if (directory) - { - dumpn("*** mapping '" + path + "' to the location " + directory.path); - this._pathDirectoryMap.put(key, directory); - } - else - { - dumpn("*** removing mapping for '" + path + "'"); - this._pathDirectoryMap.put(key, null); - } - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(err, handler) - { - if (!(err in HTTP_ERROR_CODES)) - dumpn("*** WARNING: registering non-HTTP/1.1 error code " + - "(" + err + ") handler -- was this intentional?"); - - this._handlerToField(handler, this._overrideErrors, err); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - if (!handler) - handler = defaultIndexHandler; - else if (typeof(handler) != "function") - handler = createHandlerFunc(handler); - - this._indexHandler = handler; - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - if (!type) - delete this._mimeMappings[ext]; - else - this._mimeMappings[ext] = headerUtils.normalizeFieldValue(type); - }, - - // PRIVATE API - - /** -* Sets or remove (if handler is null) a handler in an object with a key. -* -* @param handler -* a handler, either function or an nsIHttpRequestHandler -* @param dict -* The object to attach the handler to. -* @param key -* The field name of the handler. -*/ - _handlerToField: function(handler, dict, key) - { - // for convenience, handler can be a function if this is run from xpcshell - if (typeof(handler) == "function") - dict[key] = handler; - else if (handler) - dict[key] = createHandlerFunc(handler); - else - delete dict[key]; - }, - - /** -* Handles a request which maps to a file in the local filesystem (if a base -* path has already been set; otherwise the 404 error is thrown). -* -* @param metadata : Request -* metadata for the incoming request -* @param response : Response -* an uninitialized Response to the given request, to be initialized by a -* request handler -* @throws HTTP_### -* if an HTTP error occurred (usually HTTP_404); note that in this case the -* calling code must handle post-processing of the response -*/ - _handleDefault: function(metadata, response) - { - dumpn("*** _handleDefault()"); - - response.setStatusLine(metadata.httpVersion, 200, "OK"); - - var path = metadata.path; - NS_ASSERT(path.charAt(0) == "/", "invalid path: <" + path + ">"); - - // determine the actual on-disk file; this requires finding the deepest - // path-to-directory mapping in the requested URL - var file = this._getFileForPath(path); - - // the "file" might be a directory, in which case we either serve the - // contained index.html or make the index handler write the response - if (file.exists() && file.isDirectory()) - { - file.append("index.html"); // make configurable? - if (!file.exists() || file.isDirectory()) - { - metadata._ensurePropertyBag(); - metadata._bag.setPropertyAsInterface("directory", file.parent); - this._indexHandler(metadata, response); - return; - } - } - - // alternately, the file might not exist - if (!file.exists()) - throw HTTP_404; - - var start, end; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1) && - metadata.hasHeader("Range") && - this._getTypeFromFile(file) !== SJS_TYPE) - { - var rangeMatch = metadata.getHeader("Range").match(/^bytes=(\d+)?-(\d+)?$/); - if (!rangeMatch) - throw HTTP_400; - - if (rangeMatch[1] !== undefined) - start = parseInt(rangeMatch[1], 10); - - if (rangeMatch[2] !== undefined) - end = parseInt(rangeMatch[2], 10); - - if (start === undefined && end === undefined) - throw HTTP_400; - - // No start given, so the end is really the count of bytes from the - // end of the file. - if (start === undefined) - { - start = Math.max(0, file.fileSize - end); - end = file.fileSize - 1; - } - - // start and end are inclusive - if (end === undefined || end >= file.fileSize) - end = file.fileSize - 1; - - if (start !== undefined && start >= file.fileSize) { - var HTTP_416 = new HttpError(416, "Requested Range Not Satisfiable"); - HTTP_416.customErrorHandling = function(errorResponse) - { - maybeAddHeaders(file, metadata, errorResponse); - }; - throw HTTP_416; - } - - if (end < start) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - start = 0; - end = file.fileSize - 1; - } - else - { - response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); - var contentRange = "bytes " + start + "-" + end + "/" + file.fileSize; - response.setHeader("Content-Range", contentRange); - } - } - else - { - start = 0; - end = file.fileSize - 1; - } - - // finally... - dumpn("*** handling '" + path + "' as mapping to " + file.path + " from " + - start + " to " + end + " inclusive"); - this._writeFileResponse(metadata, file, response, start, end - start + 1); - }, - - /** -* Writes an HTTP response for the given file, including setting headers for -* file metadata. -* -* @param metadata : Request -* the Request for which a response is being generated -* @param file : nsILocalFile -* the file which is to be sent in the response -* @param response : Response -* the response to which the file should be written -* @param offset: uint -* the byte offset to skip to when writing -* @param count: uint -* the number of bytes to write -*/ - _writeFileResponse: function(metadata, file, response, offset, count) - { - const PR_RDONLY = 0x01; - - var type = this._getTypeFromFile(file); - if (type === SJS_TYPE) - { - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var sis = new ScriptableInputStream(fis); - var s = Cu.Sandbox(gGlobalObject); - s.importFunction(dump, "dump"); - - // Define a basic key-value state-preservation API across requests, with - // keys initially corresponding to the empty string. - var self = this; - var path = metadata.path; - s.importFunction(function getState(k) - { - return self._getState(path, k); - }); - s.importFunction(function setState(k, v) - { - self._setState(path, k, v); - }); - s.importFunction(function getSharedState(k) - { - return self._getSharedState(k); - }); - s.importFunction(function setSharedState(k, v) - { - self._setSharedState(k, v); - }); - s.importFunction(function getObjectState(k, callback) - { - callback(self._getObjectState(k)); - }); - s.importFunction(function setObjectState(k, v) - { - self._setObjectState(k, v); - }); - s.importFunction(function registerPathHandler(p, h) - { - self.registerPathHandler(p, h); - }); - - // Make it possible for sjs files to access their location - this._setState(path, "__LOCATION__", file.path); - - try - { - // Alas, the line number in errors dumped to console when calling the - // request handler is simply an offset from where we load the SJS file. - // Work around this in a reasonably non-fragile way by dynamically - // getting the line number where we evaluate the SJS file. Don't - // separate these two lines! - var line = new Error().lineNumber; - Cu.evalInSandbox(sis.read(file.fileSize), s); - } - catch (e) - { - dumpn("*** syntax error in SJS at " + file.path + ": " + e); - throw HTTP_500; - } - - try - { - s.handleRequest(metadata, response); - } - catch (e) - { - dump("*** error running SJS at " + file.path + ": " + - e + " on line " + - (e instanceof Error - ? e.lineNumber + " in httpd.js" - : (e.lineNumber - line)) + "\n"); - throw HTTP_500; - } - } - finally - { - fis.close(); - } - } - else - { - try - { - response.setHeader("Last-Modified", - toDateString(file.lastModifiedTime), - false); - } - catch (e) { /* lastModifiedTime threw, ignore */ } - - response.setHeader("Content-Type", type, false); - maybeAddHeaders(file, metadata, response); - response.setHeader("Content-Length", "" + count, false); - - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - offset = offset || 0; - count = count || file.fileSize; - NS_ASSERT(offset === 0 || offset < file.fileSize, "bad offset"); - NS_ASSERT(count >= 0, "bad count"); - NS_ASSERT(offset + count <= file.fileSize, "bad total data size"); - - try - { - if (offset !== 0) - { - // Seek (or read, if seeking isn't supported) to the correct offset so - // the data sent to the client matches the requested range. - if (fis instanceof Ci.nsISeekableStream) - fis.seek(Ci.nsISeekableStream.NS_SEEK_SET, offset); - else - new ScriptableInputStream(fis).read(offset); - } - } - catch (e) - { - fis.close(); - throw e; - } - - let writeMore = function writeMore() - { - gThreadManager.currentThread - .dispatch(writeData, Ci.nsIThread.DISPATCH_NORMAL); - } - - var input = new BinaryInputStream(fis); - var output = new BinaryOutputStream(response.bodyOutputStream); - var writeData = - { - run: function() - { - var chunkSize = Math.min(65536, count); - count -= chunkSize; - NS_ASSERT(count >= 0, "underflow"); - - try - { - var data = input.readByteArray(chunkSize); - NS_ASSERT(data.length === chunkSize, - "incorrect data returned? got " + data.length + - ", expected " + chunkSize); - output.writeByteArray(data, data.length); - if (count === 0) - { - fis.close(); - response.finish(); - } - else - { - writeMore(); - } - } - catch (e) - { - try - { - fis.close(); - } - finally - { - response.finish(); - } - throw e; - } - } - }; - - writeMore(); - - // Now that we know copying will start, flag the response as async. - response.processAsync(); - } - }, - - /** -* Get the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getState: function(path, k) - { - var state = this._state; - if (path in state && k in state[path]) - return state[path][k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setState: function(path, k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - var state = this._state; - if (!(path in state)) - state[path] = {}; - state[path][k] = v; - }, - - /** -* Get the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getSharedState: function(k) - { - var state = this._sharedState; - if (k in state) - return state[k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setSharedState: function(k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - this._sharedState[k] = v; - }, - - /** -* Returns the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be returned -* @returns nsISupports -* the corresponding object, or null if none was present -*/ - _getObjectState: function(k) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - return this._objectState[k] || null; - }, - - /** -* Sets the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be set -* @param v : nsISupports -* the object to be associated with the given key; may be null -*/ - _setObjectState: function(k, v) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - if (typeof v !== "object") - throw new Error("non-object value passed"); - if (v && !("QueryInterface" in v)) - { - throw new Error("must pass an nsISupports; use wrappedJSObject to ease " + - "pain when using the server from JS"); - } - - this._objectState[k] = v; - }, - - /** -* Gets a content-type for the given file, first by checking for any custom -* MIME-types registered with this handler for the file's extension, second by -* asking the global MIME service for a content-type, and finally by failing -* over to application/octet-stream. -* -* @param file : nsIFile -* the nsIFile for which to get a file type -* @returns string -* the best content-type which can be determined for the file -*/ - _getTypeFromFile: function(file) - { - try - { - var name = file.leafName; - var dot = name.lastIndexOf("."); - if (dot > 0) - { - var ext = name.slice(dot + 1); - if (ext in this._mimeMappings) - return this._mimeMappings[ext]; - } - return Cc["@mozilla.org/uriloader/external-helper-app-service;1"] - .getService(Ci.nsIMIMEService) - .getTypeFromFile(file); - } - catch (e) - { - return "application/octet-stream"; - } - }, - - /** -* Returns the nsILocalFile which corresponds to the path, as determined using -* all registered path->directory mappings and any paths which are explicitly -* overridden. -* -* @param path : string -* the server path for which a file should be retrieved, e.g. "/foo/bar" -* @throws HttpError -* when the correct action is the corresponding HTTP error (i.e., because no -* mapping was found for a directory in path, the referenced file doesn't -* exist, etc.) -* @returns nsILocalFile -* the file to be sent as the response to a request for the path -*/ - _getFileForPath: function(path) - { - // decode and add underscores as necessary - try - { - path = toInternalPath(path, true); - } - catch (e) - { - throw HTTP_400; // malformed path - } - - // next, get the directory which contains this path - var pathMap = this._pathDirectoryMap; - - // An example progression of tmp for a path "/foo/bar/baz/" might be: - // "foo/bar/baz/", "foo/bar/baz", "foo/bar", "foo", "" - var tmp = path.substring(1); - while (true) - { - // do we have a match for current head of the path? - var file = pathMap.get(tmp); - if (file) - { - // XXX hack; basically disable showing mapping for /foo/bar/ when the - // requested path was /foo/bar, because relative links on the page - // will all be incorrect -- we really need the ability to easily - // redirect here instead - if (tmp == path.substring(1) && - tmp.length != 0 && - tmp.charAt(tmp.length - 1) != "/") - file = null; - else - break; - } - - // if we've finished trying all prefixes, exit - if (tmp == "") - break; - - tmp = tmp.substring(0, tmp.lastIndexOf("/")); - } - - // no mapping applies, so 404 - if (!file) - throw HTTP_404; - - - // last, get the file for the path within the determined directory - var parentFolder = file.parent; - var dirIsRoot = (parentFolder == null); - - // Strategy here is to append components individually, making sure we - // never move above the given directory; this allows paths such as - // "/foo/../bar" but prevents paths such as "/../base-sibling"; - // this component-wise approach also means the code works even on platforms - // which don't use "/" as the directory separator, such as Windows - var leafPath = path.substring(tmp.length + 1); - var comps = leafPath.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - - if (comp == "..") - file = file.parent; - else if (comp == "." || comp == "") - continue; - else - file.append(comp); - - if (!dirIsRoot && file.equals(parentFolder)) - throw HTTP_403; - } - - return file; - }, - - /** -* Writes the error page for the given HTTP error code over the given -* connection. -* -* @param errorCode : uint -* the HTTP error code to be used -* @param connection : Connection -* the connection on which the error occurred -*/ - handleError: function(errorCode, connection) - { - var response = new Response(connection); - - dumpn("*** error in request: " + errorCode); - - this._handleError(errorCode, new Request(connection.port), response); - }, - - /** -* Handles a request which generates the given error code, using the -* user-defined error handler if one has been set, gracefully falling back to -* the x00 status code if the code has no handler, and failing to status code -* 500 if all else fails. -* -* @param errorCode : uint -* the HTTP error which is to be returned -* @param metadata : Request -* metadata for the request, which will often be incomplete since this is an -* error -* @param response : Response -* an uninitialized Response should be initialized when this method -* completes with information which represents the desired error code in the -* ideal case or a fallback code in abnormal circumstances (i.e., 500 is a -* fallback for 505, per HTTP specs) -*/ - _handleError: function(errorCode, metadata, response) - { - if (!metadata) - throw Cr.NS_ERROR_NULL_POINTER; - - var errorX00 = errorCode - (errorCode % 100); - - try - { - if (!(errorCode in HTTP_ERROR_CODES)) - dumpn("*** WARNING: requested invalid error: " + errorCode); - - // RFC 2616 says that we should try to handle an error by its class if we - // can't otherwise handle it -- if that fails, we revert to handling it as - // a 500 internal server error, and if that fails we throw and shut down - // the server - - // actually handle the error - try - { - if (errorCode in this._overrideErrors) - this._overrideErrors[errorCode](metadata, response); - else - this._defaultErrors[errorCode](metadata, response); - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - // don't retry the handler that threw - if (errorX00 == errorCode) - throw HTTP_500; - - dumpn("*** error in handling for error code " + errorCode + ", " + - "falling back to " + errorX00 + "..."); - response = new Response(response._connection); - if (errorX00 in this._overrideErrors) - this._overrideErrors[errorX00](metadata, response); - else if (errorX00 in this._defaultErrors) - this._defaultErrors[errorX00](metadata, response); - else - throw HTTP_500; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(); - return; - } - - // we've tried everything possible for a meaningful error -- now try 500 - dumpn("*** error in handling for error code " + errorX00 + ", falling " + - "back to 500..."); - - try - { - response = new Response(response._connection); - if (500 in this._overrideErrors) - this._overrideErrors[500](metadata, response); - else - this._defaultErrors[500](metadata, response); - } - catch (e2) - { - dumpn("*** multiple errors in default error handlers!"); - dumpn("*** e == " + e + ", e2 == " + e2); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // FIELDS - - /** -* This object contains the default handlers for the various HTTP error codes. -*/ - _defaultErrors: - { - 400: function(metadata, response) - { - // none of the data in metadata is reliable, so hard-code everything here - response.setStatusLine("1.1", 400, "Bad Request"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Bad request\n"; - response.bodyOutputStream.write(body, body.length); - }, - 403: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 403, "Forbidden"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -403 Forbidden\ -\ -

403 Forbidden

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 404: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 404, "Not Found"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -404 Not Found\ -\ -

404 Not Found

\ -

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

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 416: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 416, - "Requested Range Not Satisfiable"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -\ -416 Requested Range Not Satisfiable\ -\ -

416 Requested Range Not Satisfiable

\ -

The byte range was not valid for the\ -requested resource.\ -

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 500: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 500, - "Internal Server Error"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -500 Internal Server Error\ -\ -

500 Internal Server Error

\ -

Something's broken in this server and\ -needs to be fixed.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 501: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 501, "Not Implemented"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -501 Not Implemented\ -\ -

501 Not Implemented

\ -

This server is not (yet) Apache.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 505: function(metadata, response) - { - response.setStatusLine("1.1", 505, "HTTP Version Not Supported"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -505 HTTP Version Not Supported\ -\ -

505 HTTP Version Not Supported

\ -

This server only supports HTTP/1.0 and HTTP/1.1\ -connections.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - } - }, - - /** -* Contains handlers for the default set of URIs contained in this server. -*/ - _defaultPaths: - { - "/": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -httpd.js\ -\ -

httpd.js

\ -

If you're seeing this page, httpd.js is up and\ -serving requests! Now set a base path and serve some\ -files!

\ -\ -"; - - response.bodyOutputStream.write(body, body.length); - }, - - "/trace": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Request-URI: " + - metadata.scheme + "://" + metadata.host + ":" + metadata.port + - metadata.path + "\n\n"; - body += "Request (semantically equivalent, slightly reformatted):\n\n"; - body += metadata.method + " " + metadata.path; - - if (metadata.queryString) - body += "?" + metadata.queryString; - - body += " HTTP/" + metadata.httpVersion + "\r\n"; - - var headEnum = metadata.headers; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - body += fieldName + ": " + metadata.getHeader(fieldName) + "\r\n"; - } - - response.bodyOutputStream.write(body, body.length); - } - } -}; - - -/** -* Maps absolute paths to files on the local file system (as nsILocalFiles). -*/ -function FileMap() -{ - /** Hash which will map paths to nsILocalFiles. */ - this._map = {}; -} -FileMap.prototype = -{ - // PUBLIC API - - /** -* Maps key to a clone of the nsILocalFile value if value is non-null; -* otherwise, removes any extant mapping for key. -* -* @param key : string -* string to which a clone of value is mapped -* @param value : nsILocalFile -* the file to map to key, or null to remove a mapping -*/ - put: function(key, value) - { - if (value) - this._map[key] = value.clone(); - else - delete this._map[key]; - }, - - /** -* Returns a clone of the nsILocalFile mapped to key, or null if no such -* mapping exists. -* -* @param key : string -* key to which the returned file maps -* @returns nsILocalFile -* a clone of the mapped file, or null if no mapping exists -*/ - get: function(key) - { - var val = this._map[key]; - return val ? val.clone() : null; - } -}; - - -// Response CONSTANTS - -// token = * -// CHAR = -// CTL = -// separators = "(" | ")" | "<" | ">" | "@" -// | "," | ";" | ":" | "\" | <"> -// | "/" | "[" | "]" | "?" | "=" -// | "{" | "}" | SP | HT -const IS_TOKEN_ARRAY = - [0, 0, 0, 0, 0, 0, 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 0, 0, 0, 0, 0, 0, 0, 0, // 24 - - 0, 1, 0, 1, 1, 1, 1, 1, // 32 - 0, 0, 1, 1, 0, 1, 1, 0, // 40 - 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 1, 1, 0, 0, 0, 0, 0, 0, // 56 - - 0, 1, 1, 1, 1, 1, 1, 1, // 64 - 1, 1, 1, 1, 1, 1, 1, 1, // 72 - 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 1, 1, 1, 0, 0, 0, 1, 1, // 88 - - 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 1, 1, 1, 1, 1, 1, 1, 1, // 104 - 1, 1, 1, 1, 1, 1, 1, 1, // 112 - 1, 1, 1, 0, 1, 0, 1]; // 120 - - -/** -* Determines whether the given character code is a CTL. -* -* @param code : uint -* the character code -* @returns boolean -* true if code is a CTL, false otherwise -*/ -function isCTL(code) -{ - return (code >= 0 && code <= 31) || (code == 127); -} - -/** -* Represents a response to an HTTP request, encapsulating all details of that -* response. This includes all headers, the HTTP version, status code and -* explanation, and the entity itself. -* -* @param connection : Connection -* the connection over which this response is to be written -*/ -function Response(connection) -{ - /** The connection over which this response will be written. */ - this._connection = connection; - - /** -* The HTTP version of this response; defaults to 1.1 if not set by the -* handler. -*/ - this._httpVersion = nsHttpVersion.HTTP_1_1; - - /** -* The HTTP code of this response; defaults to 200. -*/ - this._httpCode = 200; - - /** -* The description of the HTTP code in this response; defaults to "OK". -*/ - this._httpDescription = "OK"; - - /** -* An nsIHttpHeaders object in which the headers in this response should be -* stored. This property is null after the status line and headers have been -* written to the network, and it may be modified up until it is cleared, -* except if this._finished is set first (in which case headers are written -* asynchronously in response to a finish() call not preceded by -* flushHeaders()). -*/ - this._headers = new nsHttpHeaders(); - - /** -* Set to true when this response is ended (completely constructed if possible -* and the connection closed); further actions on this will then fail. -*/ - this._ended = false; - - /** -* A stream used to hold data written to the body of this response. -*/ - this._bodyOutputStream = null; - - /** -* A stream containing all data that has been written to the body of this -* response so far. (Async handlers make the data contained in this -* unreliable as a way of determining content length in general, but auxiliary -* saved information can sometimes be used to guarantee reliability.) -*/ - this._bodyInputStream = null; - - /** -* A stream copier which copies data to the network. It is initially null -* until replaced with a copier for response headers; when headers have been -* fully sent it is replaced with a copier for the response body, remaining -* so for the duration of response processing. -*/ - this._asyncCopier = null; - - /** -* True if this response has been designated as being processed -* asynchronously rather than for the duration of a single call to -* nsIHttpRequestHandler.handle. -*/ - this._processAsync = false; - - /** -* True iff finish() has been called on this, signaling that no more changes -* to this may be made. -*/ - this._finished = false; - - /** -* True iff powerSeized() has been called on this, signaling that this -* response is to be handled manually by the response handler (which may then -* send arbitrary data in response, even non-HTTP responses). -*/ - this._powerSeized = false; -} -Response.prototype = -{ - // PUBLIC CONSTRUCTION API - - // - // see nsIHttpResponse.bodyOutputStream - // - get bodyOutputStream() - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - if (!this._bodyOutputStream) - { - var pipe = new Pipe(true, false, Response.SEGMENT_SIZE, PR_UINT32_MAX, - null); - this._bodyOutputStream = pipe.outputStream; - this._bodyInputStream = pipe.inputStream; - if (this._processAsync || this._powerSeized) - this._startAsyncProcessor(); - } - - return this._bodyOutputStream; - }, - - // - // see nsIHttpResponse.write - // - write: function(data) - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - var dataAsString = String(data); - this.bodyOutputStream.write(dataAsString, dataAsString.length); - }, - - // - // see nsIHttpResponse.setStatusLine - // - setStatusLine: function(httpVersion, code, description) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - if (!(code >= 0 && code < 1000)) - throw Cr.NS_ERROR_INVALID_ARG; - - try - { - var httpVer; - // avoid version construction for the most common cases - if (!httpVersion || httpVersion == "1.1") - httpVer = nsHttpVersion.HTTP_1_1; - else if (httpVersion == "1.0") - httpVer = nsHttpVersion.HTTP_1_0; - else - httpVer = new nsHttpVersion(httpVersion); - } - catch (e) - { - throw Cr.NS_ERROR_INVALID_ARG; - } - - // Reason-Phrase = * - // TEXT = - // - // XXX this ends up disallowing octets which aren't Unicode, I think -- not - // much to do if description is IDL'd as string - if (!description) - description = ""; - for (var i = 0; i < description.length; i++) - if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t") - throw Cr.NS_ERROR_INVALID_ARG; - - // set the values only after validation to preserve atomicity - this._httpDescription = description; - this._httpCode = code; - this._httpVersion = httpVer; - }, - - // - // see nsIHttpResponse.setHeader - // - setHeader: function(name, value, merge) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - this._headers.setHeader(name, value, merge); - }, - - // - // see nsIHttpResponse.processAsync - // - processAsync: function() - { - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._processAsync) - return; - this._ensureAlive(); - - dumpn("*** processing connection " + this._connection.number + " async"); - this._processAsync = true; - - /* -* Either the bodyOutputStream getter or this method is responsible for -* starting the asynchronous processor and catching writes of data to the -* response body of async responses as they happen, for the purpose of -* forwarding those writes to the actual connection's output stream. -* If bodyOutputStream is accessed first, calling this method will create -* the processor (when it first is clear that body data is to be written -* immediately, not buffered). If this method is called first, accessing -* bodyOutputStream will create the processor. If only this method is -* called, we'll write nothing, neither headers nor the nonexistent body, -* until finish() is called. Since that delay is easily avoided by simply -* getting bodyOutputStream or calling write(""), we don't worry about it. -*/ - if (this._bodyOutputStream && !this._asyncCopier) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.seizePower - // - seizePower: function() - { - if (this._processAsync) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - return; - this._ensureAlive(); - - dumpn("*** forcefully seizing power over connection " + - this._connection.number + "..."); - - // Purge any already-written data without sending it. We could as easily - // swap out the streams entirely, but that makes it possible to acquire and - // unknowingly use a stale reference, so we require there only be one of - // each stream ever for any response to avoid this complication. - if (this._asyncCopier) - this._asyncCopier.cancel(Cr.NS_BINDING_ABORTED); - this._asyncCopier = null; - if (this._bodyOutputStream) - { - var input = new BinaryInputStream(this._bodyInputStream); - var avail; - while ((avail = input.available()) > 0) - input.readByteArray(avail); - } - - this._powerSeized = true; - if (this._bodyOutputStream) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.finish - // - finish: function() - { - if (!this._processAsync && !this._powerSeized) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._finished) - return; - - dumpn("*** finishing connection " + this._connection.number); - this._startAsyncProcessor(); // in case bodyOutputStream was never accessed - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - this._finished = true; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpResponse) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // POST-CONSTRUCTION API (not exposed externally) - - /** -* The HTTP version number of this, as a string (e.g. "1.1"). -*/ - get httpVersion() - { - this._ensureAlive(); - return this._httpVersion.toString(); - }, - - /** -* The HTTP status code of this response, as a string of three characters per -* RFC 2616. -*/ - get httpCode() - { - this._ensureAlive(); - - var codeString = (this._httpCode < 10 ? "0" : "") + - (this._httpCode < 100 ? "0" : "") + - this._httpCode; - return codeString; - }, - - /** -* The description of the HTTP status code of this response, or "" if none is -* set. -*/ - get httpDescription() - { - this._ensureAlive(); - - return this._httpDescription; - }, - - /** -* The headers in this response, as an nsHttpHeaders object. -*/ - get headers() - { - this._ensureAlive(); - - return this._headers; - }, - - // - // see nsHttpHeaders.getHeader - // - getHeader: function(name) - { - this._ensureAlive(); - - return this._headers.getHeader(name); - }, - - /** -* Determines whether this response may be abandoned in favor of a newly -* constructed response. A response may be abandoned only if it is not being -* sent asynchronously and if raw control over it has not been taken from the -* server. -* -* @returns boolean -* true iff no data has been written to the network -*/ - partiallySent: function() - { - dumpn("*** partiallySent()"); - return this._processAsync || this._powerSeized; - }, - - /** -* If necessary, kicks off the remaining request processing needed to be done -* after a request handler performs its initial work upon this response. -*/ - complete: function() - { - dumpn("*** complete()"); - if (this._processAsync || this._powerSeized) - { - NS_ASSERT(this._processAsync ^ this._powerSeized, - "can't both send async and relinquish power"); - return; - } - - NS_ASSERT(!this.partiallySent(), "completing a partially-sent response?"); - - this._startAsyncProcessor(); - - // Now make sure we finish processing this request! - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - }, - - /** -* Abruptly ends processing of this response, usually due to an error in an -* incoming request but potentially due to a bad error handler. Since we -* cannot handle the error in the usual way (giving an HTTP error page in -* response) because data may already have been sent (or because the response -* might be expected to have been generated asynchronously or completely from -* scratch by the handler), we stop processing this response and abruptly -* close the connection. -* -* @param e : Error -* the exception which precipitated this abort, or null if no such exception -* was generated -*/ - abort: function(e) - { - dumpn("*** abort(<" + e + ">)"); - - // This response will be ended by the processor if one was created. - var copier = this._asyncCopier; - if (copier) - { - // We dispatch asynchronously here so that any pending writes of data to - // the connection will be deterministically written. This makes it easier - // to specify exact behavior, and it makes observable behavior more - // predictable for clients. Note that the correctness of this depends on - // callbacks in response to _waitToReadData in WriteThroughCopier - // happening asynchronously with respect to the actual writing of data to - // bodyOutputStream, as they currently do; if they happened synchronously, - // an event which ran before this one could write more data to the - // response body before we get around to canceling the copier. We have - // tests for this in test_seizepower.js, however, and I can't think of a - // way to handle both cases without removing bodyOutputStream access and - // moving its effective write(data, length) method onto Response, which - // would be slower and require more code than this anyway. - gThreadManager.currentThread.dispatch({ - run: function() - { - dumpn("*** canceling copy asynchronously..."); - copier.cancel(Cr.NS_ERROR_UNEXPECTED); - } - }, Ci.nsIThread.DISPATCH_NORMAL); - } - else - { - this.end(); - } - }, - - /** -* Closes this response's network connection, marks the response as finished, -* and notifies the server handler that the request is done being processed. -*/ - end: function() - { - NS_ASSERT(!this._ended, "ending this response twice?!?!"); - - this._connection.close(); - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - - this._finished = true; - this._ended = true; - }, - - // PRIVATE IMPLEMENTATION - - /** -* Sends the status line and headers of this response if they haven't been -* sent and initiates the process of copying data written to this response's -* body to the network. -*/ - _startAsyncProcessor: function() - { - dumpn("*** _startAsyncProcessor()"); - - // Handle cases where we're being called a second time. The former case - // happens when this is triggered both by complete() and by processAsync(), - // while the latter happens when processAsync() in conjunction with sent - // data causes abort() to be called. - if (this._asyncCopier || this._ended) - { - dumpn("*** ignoring second call to _startAsyncProcessor"); - return; - } - - // Send headers if they haven't been sent already and should be sent, then - // asynchronously continue to send the body. - if (this._headers && !this._powerSeized) - { - this._sendHeaders(); - return; - } - - this._headers = null; - this._sendBody(); - }, - - /** -* Signals that all modifications to the response status line and headers are -* complete and then sends that data over the network to the client. Once -* this method completes, a different response to the request that resulted -* in this response cannot be sent -- the only possible action in case of -* error is to abort the response and close the connection. -*/ - _sendHeaders: function() - { - dumpn("*** _sendHeaders()"); - - NS_ASSERT(this._headers); - NS_ASSERT(!this._powerSeized); - - // request-line - var statusLine = "HTTP/" + this.httpVersion + " " + - this.httpCode + " " + - this.httpDescription + "\r\n"; - - // header post-processing - - var headers = this._headers; - headers.setHeader("Connection", "close", false); - headers.setHeader("Server", "httpd.js", false); - if (!headers.hasHeader("Date")) - headers.setHeader("Date", toDateString(Date.now()), false); - - // Any response not being processed asynchronously must have an associated - // Content-Length header for reasons of backwards compatibility with the - // initial server, which fully buffered every response before sending it. - // Beyond that, however, it's good to do this anyway because otherwise it's - // impossible to test behaviors that depend on the presence or absence of a - // Content-Length header. - if (!this._processAsync) - { - dumpn("*** non-async response, set Content-Length"); - - var bodyStream = this._bodyInputStream; - var avail = bodyStream ? bodyStream.available() : 0; - - // XXX assumes stream will always report the full amount of data available - headers.setHeader("Content-Length", "" + avail, false); - } - - - // construct and send response - dumpn("*** header post-processing completed, sending response head..."); - - // request-line - var preambleData = [statusLine]; - - // headers - var headEnum = headers.enumerator; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - var values = headers.getHeaderValues(fieldName); - for (var i = 0, sz = values.length; i < sz; i++) - preambleData.push(fieldName + ": " + values[i] + "\r\n"); - } - - // end request-line/headers - preambleData.push("\r\n"); - - var preamble = preambleData.join(""); - - var responseHeadPipe = new Pipe(true, false, 0, PR_UINT32_MAX, null); - responseHeadPipe.outputStream.write(preamble, preamble.length); - - var response = this; - var copyObserver = - { - onStartRequest: function(request, cx) - { - dumpn("*** preamble copying started"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** preamble copying complete " + - "[status=0x" + statusCode.toString(16) + "]"); - - if (!components.isSuccessCode(statusCode)) - { - dumpn("!!! header copying problems: non-success statusCode, " + - "ending response"); - - response.end(); - } - else - { - response._sendBody(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - var headerCopier = this._asyncCopier = - new WriteThroughCopier(responseHeadPipe.inputStream, - this._connection.output, - copyObserver, null); - - responseHeadPipe.outputStream.close(); - - // Forbid setting any more headers or modifying the request line. - this._headers = null; - }, - - /** -* Asynchronously writes the body of the response (or the entire response, if -* seizePower() has been called) to the network. -*/ - _sendBody: function() - { - dumpn("*** _sendBody"); - - NS_ASSERT(!this._headers, "still have headers around but sending body?"); - - // If no body data was written, we're done - if (!this._bodyInputStream) - { - dumpn("*** empty body, response finished"); - this.end(); - return; - } - - var response = this; - var copyObserver = - { - onStartRequest: function(request, context) - { - dumpn("*** onStartRequest"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** onStopRequest [status=0x" + statusCode.toString(16) + "]"); - - if (statusCode === Cr.NS_BINDING_ABORTED) - { - dumpn("*** terminating copy observer without ending the response"); - } - else - { - if (!components.isSuccessCode(statusCode)) - dumpn("*** WARNING: non-success statusCode in onStopRequest"); - - response.end(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - dumpn("*** starting async copier of body data..."); - this._asyncCopier = - new WriteThroughCopier(this._bodyInputStream, this._connection.output, - copyObserver, null); - }, - - /** Ensures that this hasn't been ended. */ - _ensureAlive: function() - { - NS_ASSERT(!this._ended, "not handling response lifetime correctly"); - } -}; - -/** -* Size of the segments in the buffer used in storing response data and writing -* it to the socket. -*/ -Response.SEGMENT_SIZE = 8192; - -/** Serves double duty in WriteThroughCopier implementation. */ -function notImplemented() -{ - throw Cr.NS_ERROR_NOT_IMPLEMENTED; -} - -/** Returns true iff the given exception represents stream closure. */ -function streamClosed(e) -{ - return e === Cr.NS_BASE_STREAM_CLOSED || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_CLOSED); -} - -/** Returns true iff the given exception represents a blocked stream. */ -function wouldBlock(e) -{ - return e === Cr.NS_BASE_STREAM_WOULD_BLOCK || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_WOULD_BLOCK); -} - -/** -* Copies data from source to sink as it becomes available, when that data can -* be written to sink without blocking. -* -* @param source : nsIAsyncInputStream -* the stream from which data is to be read -* @param sink : nsIAsyncOutputStream -* the stream to which data is to be copied -* @param observer : nsIRequestObserver -* an observer which will be notified when the copy starts and finishes -* @param context : nsISupports -* context passed to observer when notified of start/stop -* @throws NS_ERROR_NULL_POINTER -* if source, sink, or observer are null -*/ -function WriteThroughCopier(source, sink, observer, context) -{ - if (!source || !sink || !observer) - throw Cr.NS_ERROR_NULL_POINTER; - - /** Stream from which data is being read. */ - this._source = source; - - /** Stream to which data is being written. */ - this._sink = sink; - - /** Observer watching this copy. */ - this._observer = observer; - - /** Context for the observer watching this. */ - this._context = context; - - /** -* True iff this is currently being canceled (cancel has been called, the -* callback may not yet have been made). -*/ - this._canceled = false; - - /** -* False until all data has been read from input and written to output, at -* which point this copy is completed and cancel() is asynchronously called. -*/ - this._completed = false; - - /** Required by nsIRequest, meaningless. */ - this.loadFlags = 0; - /** Required by nsIRequest, meaningless. */ - this.loadGroup = null; - /** Required by nsIRequest, meaningless. */ - this.name = "response-body-copy"; - - /** Status of this request. */ - this.status = Cr.NS_OK; - - /** Arrays of byte strings waiting to be written to output. */ - this._pendingData = []; - - // start copying - try - { - observer.onStartRequest(this, context); - this._waitToReadData(); - this._waitForSinkClosure(); - } - catch (e) - { - dumpn("!!! error starting copy: " + e + - ("lineNumber" in e ? ", line " + e.lineNumber : "")); - dumpn(e.stack); - this.cancel(Cr.NS_ERROR_UNEXPECTED); - } -} -WriteThroughCopier.prototype = -{ - /* nsISupports implementation */ - - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIInputStreamCallback) || - iid.equals(Ci.nsIOutputStreamCallback) || - iid.equals(Ci.nsIRequest) || - iid.equals(Ci.nsISupports)) - { - return this; - } - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NSIINPUTSTREAMCALLBACK - - /** -* Receives a more-data-in-input notification and writes the corresponding -* data to the output. -* -* @param input : nsIAsyncInputStream -* the input stream on whose data we have been waiting -*/ - onInputStreamReady: function(input) - { - if (this._source === null) - return; - - dumpn("*** onInputStreamReady"); - - // - // Ordinarily we'll read a non-zero amount of data from input, queue it up - // to be written and then wait for further callbacks. The complications in - // this method are the cases where we deviate from that behavior when errors - // occur or when copying is drawing to a finish. - // - // The edge cases when reading data are: - // - // Zero data is read - // If zero data was read, we're at the end of available data, so we can - // should stop reading and move on to writing out what we have (or, if - // we've already done that, onto notifying of completion). - // A stream-closed exception is thrown - // This is effectively a less kind version of zero data being read; the - // only difference is that we notify of completion with that result - // rather than with NS_OK. - // Some other exception is thrown - // This is the least kind result. We don't know what happened, so we - // act as though the stream closed except that we notify of completion - // with the result NS_ERROR_UNEXPECTED. - // - - var bytesWanted = 0, bytesConsumed = -1; - try - { - input = new BinaryInputStream(input); - - bytesWanted = Math.min(input.available(), Response.SEGMENT_SIZE); - dumpn("*** input wanted: " + bytesWanted); - - if (bytesWanted > 0) - { - var data = input.readByteArray(bytesWanted); - bytesConsumed = data.length; - this._pendingData.push(String.fromCharCode.apply(String, data)); - } - - dumpn("*** " + bytesConsumed + " bytes read"); - - // Handle the zero-data edge case in the same place as all other edge - // cases are handled. - if (bytesWanted === 0) - throw Cr.NS_BASE_STREAM_CLOSED; - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** input stream closed"); - e = bytesWanted === 0 ? Cr.NS_OK : Cr.NS_ERROR_UNEXPECTED; - } - else - { - dumpn("!!! unexpected error reading from input, canceling: " + e); - e = Cr.NS_ERROR_UNEXPECTED; - } - - this._doneReadingSource(e); - return; - } - - var pendingData = this._pendingData; - - NS_ASSERT(bytesConsumed > 0); - NS_ASSERT(pendingData.length > 0, "no pending data somehow?"); - NS_ASSERT(pendingData[pendingData.length - 1].length > 0, - "buffered zero bytes of data?"); - - NS_ASSERT(this._source !== null); - - // Reading has gone great, and we've gotten data to write now. What if we - // don't have a place to write that data, because output went away just - // before this read? Drop everything on the floor, including new data, and - // cancel at this point. - if (this._sink === null) - { - pendingData.length = 0; - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we've read the data, and we know we have a place to write it. We - // need to queue up the data to be written, but *only* if none is queued - // already -- if data's already queued, the code that actually writes the - // data will make sure to wait on unconsumed pending data. - try - { - if (pendingData.length === 1) - this._waitToWriteData(); - } - catch (e) - { - dumpn("!!! error waiting to write data just read, swallowing and " + - "writing only what we already have: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Whee! We successfully read some data, and it's successfully queued up to - // be written. All that remains now is to wait for more data to read. - try - { - this._waitToReadData(); - } - catch (e) - { - dumpn("!!! error waiting to read more data: " + e); - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - } - }, - - - // NSIOUTPUTSTREAMCALLBACK - - /** -* Callback when data may be written to the output stream without blocking, or -* when the output stream has been closed. -* -* @param output : nsIAsyncOutputStream -* the output stream on whose writability we've been waiting, also known as -* this._sink -*/ - onOutputStreamReady: function(output) - { - if (this._sink === null) - return; - - dumpn("*** onOutputStreamReady"); - - var pendingData = this._pendingData; - if (pendingData.length === 0) - { - // There's no pending data to write. The only way this can happen is if - // we're waiting on the output stream's closure, so we can respond to a - // copying failure as quickly as possible (rather than waiting for data to - // be available to read and then fail to be copied). Therefore, we must - // be done now -- don't bother to attempt to write anything and wrap - // things up. - dumpn("!!! output stream closed prematurely, ending copy"); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - - NS_ASSERT(pendingData[0].length > 0, "queued up an empty quantum?"); - - // - // Write out the first pending quantum of data. The possible errors here - // are: - // - // The write might fail because we can't write that much data - // Okay, we've written what we can now, so re-queue what's left and - // finish writing it out later. - // The write failed because the stream was closed - // Discard pending data that we can no longer write, stop reading, and - // signal that copying finished. - // Some other error occurred. - // Same as if the stream were closed, but notify with the status - // NS_ERROR_UNEXPECTED so the observer knows something was wonky. - // - - try - { - var quantum = pendingData[0]; - - // XXX |quantum| isn't guaranteed to be ASCII, so we're relying on - // undefined behavior! We're only using this because writeByteArray - // is unusably broken for asynchronous output streams; see bug 532834 - // for details. - var bytesWritten = output.write(quantum, quantum.length); - if (bytesWritten === quantum.length) - pendingData.shift(); - else - pendingData[0] = quantum.substring(bytesWritten); - - dumpn("*** wrote " + bytesWritten + " bytes of data"); - } - catch (e) - { - if (wouldBlock(e)) - { - NS_ASSERT(pendingData.length > 0, - "stream-blocking exception with no data to write?"); - NS_ASSERT(pendingData[0].length > 0, - "stream-blocking exception with empty quantum?"); - this._waitToWriteData(); - return; - } - - if (streamClosed(e)) - dumpn("!!! output stream prematurely closed, signaling error..."); - else - dumpn("!!! unknown error: " + e + ", quantum=" + quantum); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // The day is ours! Quantum written, now let's see if we have more data - // still to write. - try - { - if (pendingData.length > 0) - { - this._waitToWriteData(); - return; - } - } - catch (e) - { - dumpn("!!! unexpected error waiting to write pending data: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we have no more pending data to write -- but might we get more in - // the future? - if (this._source !== null) - { - /* -* If we might, then wait for the output stream to be closed. (We wait -* only for closure because we have no data to write -- and if we waited -* for a specific amount of data, we would get repeatedly notified for no -* reason if over time the output stream permitted more and more data to -* be written to it without blocking.) -*/ - this._waitForSinkClosure(); - } - else - { - /* -* On the other hand, if we can't have more data because the input -* stream's gone away, then it's time to notify of copy completion. -* Victory! -*/ - this._sink = null; - this._cancelOrDispatchCancelCallback(Cr.NS_OK); - } - }, - - - // NSIREQUEST - - /** Returns true if the cancel observer hasn't been notified yet. */ - isPending: function() - { - return !this._completed; - }, - - /** Not implemented, don't use! */ - suspend: notImplemented, - /** Not implemented, don't use! */ - resume: notImplemented, - - /** -* Cancels data reading from input, asynchronously writes out any pending -* data, and causes the observer to be notified with the given error code when -* all writing has finished. -* -* @param status : nsresult -* the status to pass to the observer when data copying has been canceled -*/ - cancel: function(status) - { - dumpn("*** cancel(" + status.toString(16) + ")"); - - if (this._canceled) - { - dumpn("*** suppressing a late cancel"); - return; - } - - this._canceled = true; - this.status = status; - - // We could be in the middle of absolutely anything at this point. Both - // input and output might still be around, we might have pending data to - // write, and in general we know nothing about the state of the world. We - // therefore must assume everything's in progress and take everything to its - // final steady state (or so far as it can go before we need to finish - // writing out remaining data). - - this._doneReadingSource(status); - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Stop reading input if we haven't already done so, passing e as the status -* when closing the stream, and kick off a copy-completion notice if no more -* data remains to be written. -* -* @param e : nsresult -* the status to be used when closing the input stream -*/ - _doneReadingSource: function(e) - { - dumpn("*** _doneReadingSource(0x" + e.toString(16) + ")"); - - this._finishSource(e); - if (this._pendingData.length === 0) - this._sink = null; - else - NS_ASSERT(this._sink !== null, "null output?"); - - // If we've written out all data read up to this point, then it's time to - // signal completion. - if (this._sink === null) - { - NS_ASSERT(this._pendingData.length === 0, "pending data still?"); - this._cancelOrDispatchCancelCallback(e); - } - }, - - /** -* Stop writing output if we haven't already done so, discard any data that -* remained to be sent, close off input if it wasn't already closed, and kick -* off a copy-completion notice. -* -* @param e : nsresult -* the status to be used when closing input if it wasn't already closed -*/ - _doneWritingToSink: function(e) - { - dumpn("*** _doneWritingToSink(0x" + e.toString(16) + ")"); - - this._pendingData.length = 0; - this._sink = null; - this._doneReadingSource(e); - }, - - /** -* Completes processing of this copy: either by canceling the copy if it -* hasn't already been canceled using the provided status, or by dispatching -* the cancel callback event (with the originally provided status, of course) -* if it already has been canceled. -* -* @param status : nsresult -* the status code to use to cancel this, if this hasn't already been -* canceled -*/ - _cancelOrDispatchCancelCallback: function(status) - { - dumpn("*** _cancelOrDispatchCancelCallback(" + status + ")"); - - NS_ASSERT(this._source === null, "should have finished input"); - NS_ASSERT(this._sink === null, "should have finished output"); - NS_ASSERT(this._pendingData.length === 0, "should have no pending data"); - - if (!this._canceled) - { - this.cancel(status); - return; - } - - var self = this; - var event = - { - run: function() - { - dumpn("*** onStopRequest async callback"); - - self._completed = true; - try - { - self._observer.onStopRequest(self, self._context, self.status); - } - catch (e) - { - NS_ASSERT(false, - "how are we throwing an exception here? we control " + - "all the callers! " + e); - } - } - }; - - gThreadManager.currentThread.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); - }, - - /** -* Kicks off another wait for more data to be available from the input stream. -*/ - _waitToReadData: function() - { - dumpn("*** _waitToReadData"); - this._source.asyncWait(this, 0, Response.SEGMENT_SIZE, - gThreadManager.mainThread); - }, - - /** -* Kicks off another wait until data can be written to the output stream. -*/ - _waitToWriteData: function() - { - dumpn("*** _waitToWriteData"); - - var pendingData = this._pendingData; - NS_ASSERT(pendingData.length > 0, "no pending data to write?"); - NS_ASSERT(pendingData[0].length > 0, "buffered an empty write?"); - - this._sink.asyncWait(this, 0, pendingData[0].length, - gThreadManager.mainThread); - }, - - /** -* Kicks off a wait for the sink to which data is being copied to be closed. -* We wait for stream closure when we don't have any data to be copied, rather -* than waiting to write a specific amount of data. We can't wait to write -* data because the sink might be infinitely writable, and if no data appears -* in the source for a long time we might have to spin quite a bit waiting to -* write, waiting to write again, &c. Waiting on stream closure instead means -* we'll get just one notification if the sink dies. Note that when data -* starts arriving from the sink we'll resume waiting for data to be written, -* dropping this closure-only callback entirely. -*/ - _waitForSinkClosure: function() - { - dumpn("*** _waitForSinkClosure"); - - this._sink.asyncWait(this, Ci.nsIAsyncOutputStream.WAIT_CLOSURE_ONLY, 0, - gThreadManager.mainThread); - }, - - /** -* Closes input with the given status, if it hasn't already been closed; -* otherwise a no-op. -* -* @param status : nsresult -* status code use to close the source stream if necessary -*/ - _finishSource: function(status) - { - dumpn("*** _finishSource(" + status.toString(16) + ")"); - - if (this._source !== null) - { - this._source.closeWithStatus(status); - this._source = null; - } - } -}; - - -/** -* A container for utility functions used with HTTP headers. -*/ -const headerUtils = -{ - /** -* Normalizes fieldName (by converting it to lowercase) and ensures it is a -* valid header field name (although not necessarily one specified in RFC -* 2616). -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not match the field-name production in RFC 2616 -* @returns string -* fieldName converted to lowercase if it is a valid header, for characters -* where case conversion is possible -*/ - normalizeFieldName: function(fieldName) - { - if (fieldName == "") - throw Cr.NS_ERROR_INVALID_ARG; - - for (var i = 0, sz = fieldName.length; i < sz; i++) - { - if (!IS_TOKEN_ARRAY[fieldName.charCodeAt(i)]) - { - dumpn(fieldName + " is not a valid header field name!"); - throw Cr.NS_ERROR_INVALID_ARG; - } - } - - return fieldName.toLowerCase(); - }, - - /** -* Ensures that fieldValue is a valid header field value (although not -* necessarily as specified in RFC 2616 if the corresponding field name is -* part of the HTTP protocol), normalizes the value if it is, and -* returns the normalized value. -* -* @param fieldValue : string -* a value to be normalized as an HTTP header field value -* @throws NS_ERROR_INVALID_ARG -* if fieldValue does not match the field-value production in RFC 2616 -* @returns string -* fieldValue as a normalized HTTP header field value -*/ - normalizeFieldValue: function(fieldValue) - { - // field-value = *( field-content | LWS ) - // field-content = - // TEXT = - // LWS = [CRLF] 1*( SP | HT ) - // - // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - // qdtext = > - // quoted-pair = "\" CHAR - // CHAR = - - // Any LWS that occurs between field-content MAY be replaced with a single - // SP before interpreting the field value or forwarding the message - // downstream (section 4.2); we replace 1*LWS with a single SP - var val = fieldValue.replace(/(?:(?:\r\n)?[ \t]+)+/g, " "); - - // remove leading/trailing LWS (which has been converted to SP) - val = val.replace(/^ +/, "").replace(/ +$/, ""); - - // that should have taken care of all CTLs, so val should contain no CTLs - for (var i = 0, len = val.length; i < len; i++) - if (isCTL(val.charCodeAt(i))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX disallows quoted-pair where CHAR is a CTL -- will not invalidly - // normalize, however, so this can be construed as a tightening of the - // spec and not entirely as a bug - return val; - } -}; - - - -/** -* Converts the given string into a string which is safe for use in an HTML -* context. -* -* @param str : string -* the string to make HTML-safe -* @returns string -* an HTML-safe version of str -*/ -function htmlEscape(str) -{ - // this is naive, but it'll work - var s = ""; - for (var i = 0; i < str.length; i++) - s += "&#" + str.charCodeAt(i) + ";"; - return s; -} - - -/** -* Constructs an object representing an HTTP version (see section 3.1). -* -* @param versionString -* a string of the form "#.#", where # is an non-negative decimal integer with -* or without leading zeros -* @throws -* if versionString does not specify a valid HTTP version number -*/ -function nsHttpVersion(versionString) -{ - var matches = /^(\d+)\.(\d+)$/.exec(versionString); - if (!matches) - throw "Not a valid HTTP version!"; - - /** The major version number of this, as a number. */ - this.major = parseInt(matches[1], 10); - - /** The minor version number of this, as a number. */ - this.minor = parseInt(matches[2], 10); - - if (isNaN(this.major) || isNaN(this.minor) || - this.major < 0 || this.minor < 0) - throw "Not a valid HTTP version!"; -} -nsHttpVersion.prototype = -{ - /** -* Returns the standard string representation of the HTTP version represented -* by this (e.g., "1.1"). -*/ - toString: function () - { - return this.major + "." + this.minor; - }, - - /** -* Returns true if this represents the same HTTP version as otherVersion, -* false otherwise. -* -* @param otherVersion : nsHttpVersion -* the version to compare against this -*/ - equals: function (otherVersion) - { - return this.major == otherVersion.major && - this.minor == otherVersion.minor; - }, - - /** True if this >= otherVersion, false otherwise. */ - atLeast: function(otherVersion) - { - return this.major > otherVersion.major || - (this.major == otherVersion.major && - this.minor >= otherVersion.minor); - } -}; - -nsHttpVersion.HTTP_1_0 = new nsHttpVersion("1.0"); -nsHttpVersion.HTTP_1_1 = new nsHttpVersion("1.1"); - - -/** -* An object which stores HTTP headers for a request or response. -* -* Note that since headers are case-insensitive, this object converts headers to -* lowercase before storing them. This allows the getHeader and hasHeader -* methods to work correctly for any case of a header, but it means that the -* values returned by .enumerator may not be equal case-sensitively to the -* values passed to setHeader when adding headers to this. -*/ -function nsHttpHeaders() -{ - /** -* A hash of headers, with header field names as the keys and header field -* values as the values. Header field names are case-insensitive, but upon -* insertion here they are converted to lowercase. Header field values are -* normalized upon insertion to contain no leading or trailing whitespace. -* -* Note also that per RFC 2616, section 4.2, two headers with the same name in -* a message may be treated as one header with the same field name and a field -* value consisting of the separate field values joined together with a "," in -* their original order. This hash stores multiple headers with the same name -* in this manner. -*/ - this._headers = {}; -} -nsHttpHeaders.prototype = -{ - /** -* Sets the header represented by name and value in this. -* -* @param name : string -* the header name -* @param value : string -* the header value -* @throws NS_ERROR_INVALID_ARG -* if name or value is not a valid header component -*/ - setHeader: function(fieldName, fieldValue, merge) - { - var name = headerUtils.normalizeFieldName(fieldName); - var value = headerUtils.normalizeFieldValue(fieldValue); - - // The following three headers are stored as arrays because their real-world - // syntax prevents joining individual headers into a single header using - // ",". See also - if (merge && name in this._headers) - { - if (name === "www-authenticate" || - name === "proxy-authenticate" || - name === "set-cookie") - { - this._headers[name].push(value); - } - else - { - this._headers[name][0] += "," + value; - NS_ASSERT(this._headers[name].length === 1, - "how'd a non-special header have multiple values?") - } - } - else - { - this._headers[name] = [value]; - } - }, - - /** -* Returns the value for the header specified by this. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns string -* the field value for the given header, possibly with non-semantic changes -* (i.e., leading/trailing whitespace stripped, whitespace runs replaced -* with spaces, etc.) at the option of the implementation; multiple -* instances of the header will be combined with a comma, except for -* the three headers noted in the description of getHeaderValues -*/ - getHeader: function(fieldName) - { - return this.getHeaderValues(fieldName).join("\n"); - }, - - /** -* Returns the value for the header specified by fieldName as an array. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns [string] -* an array of all the header values in this for the given -* header name. Header values will generally be collapsed -* into a single header by joining all header values together -* with commas, but certain headers (Proxy-Authenticate, -* WWW-Authenticate, and Set-Cookie) violate the HTTP spec -* and cannot be collapsed in this manner. For these headers -* only, the returned array may contain multiple elements if -* that header has been added more than once. -*/ - getHeaderValues: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - - if (name in this._headers) - return this._headers[name]; - else - throw Cr.NS_ERROR_NOT_AVAILABLE; - }, - - /** -* Returns true if a header with the given field name exists in this, false -* otherwise. -* -* @param fieldName : string -* the field name whose existence is to be determined in this -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @returns boolean -* true if the header's present, false otherwise -*/ - hasHeader: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - return (name in this._headers); - }, - - /** -* Returns a new enumerator over the field names of the headers in this, as -* nsISupportsStrings. The names returned will be in lowercase, regardless of -* how they were input using setHeader (header names are case-insensitive per -* RFC 2616). -*/ - get enumerator() - { - var headers = []; - for (var i in this._headers) - { - var supports = new SupportsString(); - supports.data = i; - headers.push(supports); - } - - return new nsSimpleEnumerator(headers); - } -}; - - -/** -* Constructs an nsISimpleEnumerator for the given array of items. -* -* @param items : Array -* the items, which must all implement nsISupports -*/ -function nsSimpleEnumerator(items) -{ - this._items = items; - this._nextIndex = 0; -} -nsSimpleEnumerator.prototype = -{ - hasMoreElements: function() - { - return this._nextIndex < this._items.length; - }, - getNext: function() - { - if (!this.hasMoreElements()) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - return this._items[this._nextIndex++]; - }, - QueryInterface: function(aIID) - { - if (Ci.nsISimpleEnumerator.equals(aIID) || - Ci.nsISupports.equals(aIID)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } -}; - - -/** -* A representation of the data in an HTTP request. -* -* @param port : uint -* the port on which the server receiving this request runs -*/ -function Request(port) -{ - /** Method of this request, e.g. GET or POST. */ - this._method = ""; - - /** Path of the requested resource; empty paths are converted to '/'. */ - this._path = ""; - - /** Query string, if any, associated with this request (not including '?'). */ - this._queryString = ""; - - /** Scheme of requested resource, usually http, always lowercase. */ - this._scheme = "http"; - - /** Hostname on which the requested resource resides. */ - this._host = undefined; - - /** Port number over which the request was received. */ - this._port = port; - - var bodyPipe = new Pipe(false, false, 0, PR_UINT32_MAX, null); - - /** Stream from which data in this request's body may be read. */ - this._bodyInputStream = bodyPipe.inputStream; - - /** Stream to which data in this request's body is written. */ - this._bodyOutputStream = bodyPipe.outputStream; - - /** -* The headers in this request. -*/ - this._headers = new nsHttpHeaders(); - - /** -* For the addition of ad-hoc properties and new functionality without having -* to change nsIHttpRequest every time; currently lazily created, as its only -* use is in directory listings. -*/ - this._bag = null; -} -Request.prototype = -{ - // SERVER METADATA - - // - // see nsIHttpRequest.scheme - // - get scheme() - { - return this._scheme; - }, - - // - // see nsIHttpRequest.host - // - get host() - { - return this._host; - }, - - // - // see nsIHttpRequest.port - // - get port() - { - return this._port; - }, - - // REQUEST LINE - - // - // see nsIHttpRequest.method - // - get method() - { - return this._method; - }, - - // - // see nsIHttpRequest.httpVersion - // - get httpVersion() - { - return this._httpVersion.toString(); - }, - - // - // see nsIHttpRequest.path - // - get path() - { - return this._path; - }, - - // - // see nsIHttpRequest.queryString - // - get queryString() - { - return this._queryString; - }, - - // HEADERS - - // - // see nsIHttpRequest.getHeader - // - getHeader: function(name) - { - return this._headers.getHeader(name); - }, - - // - // see nsIHttpRequest.hasHeader - // - hasHeader: function(name) - { - return this._headers.hasHeader(name); - }, - - // - // see nsIHttpRequest.headers - // - get headers() - { - return this._headers.enumerator; - }, - - // - // see nsIPropertyBag.enumerator - // - get enumerator() - { - this._ensurePropertyBag(); - return this._bag.enumerator; - }, - - // - // see nsIHttpRequest.headers - // - get bodyInputStream() - { - return this._bodyInputStream; - }, - - // - // see nsIPropertyBag.getProperty - // - getProperty: function(name) - { - this._ensurePropertyBag(); - return this._bag.getProperty(name); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpRequest) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** Ensures a property bag has been created for ad-hoc behaviors. */ - _ensurePropertyBag: function() - { - if (!this._bag) - this._bag = new WritablePropertyBag(); - } -}; - - -// XPCOM trappings -if ("XPCOMUtils" in this && // Firefox 3.6 doesn't load XPCOMUtils in this scope for some reason... - "generateNSGetFactory" in XPCOMUtils) { - var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsHttpServer]); -} - - - -/** -* Creates a new HTTP server listening for loopback traffic on the given port, -* starts it, and runs the server until the server processes a shutdown request, -* spinning an event loop so that events posted by the server's socket are -* processed. -* -* This method is primarily intended for use in running this script from within -* xpcshell and running a functional HTTP server without having to deal with -* non-essential details. -* -* Note that running multiple servers using variants of this method probably -* doesn't work, simply due to how the internal event loop is spun and stopped. -* -* @note -* This method only works with Mozilla 1.9 (i.e., Firefox 3 or trunk code); -* you should use this server as a component in Mozilla 1.8. -* @param port -* the port on which the server will run, or -1 if there exists no preference -* for a specific port; note that attempting to use some values for this -* parameter (particularly those below 1024) may cause this method to throw or -* may result in the server being prematurely shut down -* @param basePath -* a local directory from which requests will be served (i.e., if this is -* "/home/jwalden/" then a request to /index.html will load -* /home/jwalden/index.html); if this is omitted, only the default URLs in -* this server implementation will be functional -*/ -function server(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - // if you're running this, you probably want to see debugging info - DEBUG = true; - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", SJS_TYPE); - srv.start(port); - - var thread = gThreadManager.currentThread; - while (!srv.isStopped()) - thread.processNextEvent(true); - - // get rid of any pending requests - while (thread.hasPendingEvents()) - thread.processNextEvent(true); - - DEBUG = false; -} - -function startServerAsync(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", "sjs"); - srv.start(port); - return srv; -} - -exports.nsHttpServer = nsHttpServer; -exports.ScriptableInputStream = ScriptableInputStream; -exports.server = server; -exports.startServerAsync = startServerAsync; diff --git a/addon-sdk/source/test/addons/content-permissions/main.js b/addon-sdk/source/test/addons/content-permissions/main.js deleted file mode 100644 index b476ccb74..000000000 --- a/addon-sdk/source/test/addons/content-permissions/main.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 { PageMod } = require("sdk/page-mod"); -const tabs = require("sdk/tabs"); -const { startServerAsync } = require("./httpd"); - -const serverPort = 8099; -const TEST_TAB_URL = "about:mozilla"; - -exports.testCrossDomainIframe = function(assert, done) { - let server = startServerAsync(serverPort); - server.registerPathHandler("/iframe", function handle(request, response) { - response.write("foo"); - }); - - let pageMod = PageMod({ - include: TEST_TAB_URL, - contentScript: "new " + function ContentScriptScope() { - self.on("message", function (url) { - let iframe = document.createElement("iframe"); - iframe.addEventListener("load", function onload() { - iframe.removeEventListener("load", onload, false); - self.postMessage(iframe.contentWindow.document.body.innerHTML); - }, false); - iframe.setAttribute("src", url); - document.documentElement.appendChild(iframe); - }); - }, - onAttach: function(w) { - w.on("message", function (body) { - assert.equal(body, "foo", "received iframe html content"); - pageMod.destroy(); - w.tab.close(function() { - server.stop(done); - }); - }); - - w.postMessage("http://localhost:" + serverPort + "/iframe"); - } - }); - - tabs.open({ - url: TEST_TAB_URL, - inBackground: true - }); -}; - -exports.testCrossDomainXHR = function(assert, done) { - let server = startServerAsync(serverPort); - server.registerPathHandler("/xhr", function handle(request, response) { - response.write("foo"); - }); - - let pageMod = PageMod({ - include: TEST_TAB_URL, - contentScript: "new " + function ContentScriptScope() { - self.on("message", function (url) { - let request = new XMLHttpRequest(); - request.overrideMimeType("text/plain"); - request.open("GET", url, true); - request.onload = function () { - self.postMessage(request.responseText); - }; - request.send(null); - }); - }, - onAttach: function(w) { - w.on("message", function (body) { - assert.equal(body, "foo", "received XHR content"); - pageMod.destroy(); - w.tab.close(function() { - server.stop(done); - }); - }); - - w.postMessage("http://localhost:" + serverPort + "/xhr"); - } - }); - - tabs.open({ - url: TEST_TAB_URL, - inBackground: true - }); -}; - -require("sdk/test/runner").runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/content-permissions/package.json b/addon-sdk/source/test/addons/content-permissions/package.json deleted file mode 100644 index 6e75d2044..000000000 --- a/addon-sdk/source/test/addons/content-permissions/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "content-permissions@jetpack", - "permissions": { - "cross-domain-content": ["http://localhost:8099"] - }, - "main": "./main.js", - "version": "0.0.1" -} diff --git a/addon-sdk/source/test/addons/content-script-messages-latency/httpd.js b/addon-sdk/source/test/addons/content-script-messages-latency/httpd.js deleted file mode 100644 index 964dc9bbd..000000000 --- a/addon-sdk/source/test/addons/content-script-messages-latency/httpd.js +++ /dev/null @@ -1,5211 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -* NOTE: do not edit this file, this is copied from: -* https://github.com/mozilla/addon-sdk/blob/master/test/lib/httpd.js -*/ - -module.metadata = { - "stability": "experimental" -}; - -const { components, CC, Cc, Ci, Cr, Cu } = require("chrome"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - - -const PR_UINT32_MAX = Math.pow(2, 32) - 1; - -/** True if debugging output is enabled, false otherwise. */ -var DEBUG = false; // non-const *only* so tweakable in server tests - -/** True if debugging output should be timestamped. */ -var DEBUG_TIMESTAMP = false; // non-const so tweakable in server tests - -var gGlobalObject = Cc["@mozilla.org/systemprincipal;1"].createInstance(); - -/** -* Asserts that the given condition holds. If it doesn't, the given message is -* dumped, a stack trace is printed, and an exception is thrown to attempt to -* stop execution (which unfortunately must rely upon the exception not being -* accidentally swallowed by the code that uses it). -*/ -function NS_ASSERT(cond, msg) -{ - if (DEBUG && !cond) - { - dumpn("###!!!"); - dumpn("###!!! ASSERTION" + (msg ? ": " + msg : "!")); - dumpn("###!!! Stack follows:"); - - var stack = new Error().stack.split(/\n/); - dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n")); - - throw Cr.NS_ERROR_ABORT; - } -} - -/** Constructs an HTTP error object. */ -function HttpError(code, description) -{ - this.code = code; - this.description = description; -} -HttpError.prototype = -{ - toString: function() - { - return this.code + " " + this.description; - } -}; - -/** -* Errors thrown to trigger specific HTTP server responses. -*/ -const HTTP_400 = new HttpError(400, "Bad Request"); -const HTTP_401 = new HttpError(401, "Unauthorized"); -const HTTP_402 = new HttpError(402, "Payment Required"); -const HTTP_403 = new HttpError(403, "Forbidden"); -const HTTP_404 = new HttpError(404, "Not Found"); -const HTTP_405 = new HttpError(405, "Method Not Allowed"); -const HTTP_406 = new HttpError(406, "Not Acceptable"); -const HTTP_407 = new HttpError(407, "Proxy Authentication Required"); -const HTTP_408 = new HttpError(408, "Request Timeout"); -const HTTP_409 = new HttpError(409, "Conflict"); -const HTTP_410 = new HttpError(410, "Gone"); -const HTTP_411 = new HttpError(411, "Length Required"); -const HTTP_412 = new HttpError(412, "Precondition Failed"); -const HTTP_413 = new HttpError(413, "Request Entity Too Large"); -const HTTP_414 = new HttpError(414, "Request-URI Too Long"); -const HTTP_415 = new HttpError(415, "Unsupported Media Type"); -const HTTP_417 = new HttpError(417, "Expectation Failed"); - -const HTTP_500 = new HttpError(500, "Internal Server Error"); -const HTTP_501 = new HttpError(501, "Not Implemented"); -const HTTP_502 = new HttpError(502, "Bad Gateway"); -const HTTP_503 = new HttpError(503, "Service Unavailable"); -const HTTP_504 = new HttpError(504, "Gateway Timeout"); -const HTTP_505 = new HttpError(505, "HTTP Version Not Supported"); - -/** Creates a hash with fields corresponding to the values in arr. */ -function array2obj(arr) -{ - var obj = {}; - for (var i = 0; i < arr.length; i++) - obj[arr[i]] = arr[i]; - return obj; -} - -/** Returns an array of the integers x through y, inclusive. */ -function range(x, y) -{ - var arr = []; - for (var i = x; i <= y; i++) - arr.push(i); - return arr; -} - -/** An object (hash) whose fields are the numbers of all HTTP error codes. */ -const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505))); - - -/** -* The character used to distinguish hidden files from non-hidden files, a la -* the leading dot in Apache. Since that mechanism also hides files from -* easy display in LXR, ls output, etc. however, we choose instead to use a -* suffix character. If a requested file ends with it, we append another -* when getting the file on the server. If it doesn't, we just look up that -* file. Therefore, any file whose name ends with exactly one of the character -* is "hidden" and available for use by the server. -*/ -const HIDDEN_CHAR = "^"; - -/** -* The file name suffix indicating the file containing overridden headers for -* a requested file. -*/ -const HEADERS_SUFFIX = HIDDEN_CHAR + "headers" + HIDDEN_CHAR; - -/** Type used to denote SJS scripts for CGI-like functionality. */ -const SJS_TYPE = "sjs"; - -/** Base for relative timestamps produced by dumpn(). */ -var firstStamp = 0; - -/** dump(str) with a trailing "\n" -- only outputs if DEBUG. */ -function dumpn(str) -{ - if (DEBUG) - { - var prefix = "HTTPD-INFO | "; - if (DEBUG_TIMESTAMP) - { - if (firstStamp === 0) - firstStamp = Date.now(); - - var elapsed = Date.now() - firstStamp; // milliseconds - var min = Math.floor(elapsed / 60000); - var sec = (elapsed % 60000) / 1000; - - if (sec < 10) - prefix += min + ":0" + sec.toFixed(3) + " | "; - else - prefix += min + ":" + sec.toFixed(3) + " | "; - } - - dump(prefix + str + "\n"); - } -} - -/** Dumps the current JS stack if DEBUG. */ -function dumpStack() -{ - // peel off the frames for dumpStack() and Error() - var stack = new Error().stack.split(/\n/).slice(2); - stack.forEach(dumpn); -} - - -/** The XPCOM thread manager. */ -var gThreadManager = null; - -/** The XPCOM prefs service. */ -var gRootPrefBranch = null; -function getRootPrefBranch() -{ - if (!gRootPrefBranch) - { - gRootPrefBranch = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); - } - return gRootPrefBranch; -} - -/** -* JavaScript constructors for commonly-used classes; precreating these is a -* speedup over doing the same from base principles. See the docs at -* http://developer.mozilla.org/en/docs/components.Constructor for details. -*/ -const ServerSocket = CC("@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "init"); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", - "init"); -const Pipe = CC("@mozilla.org/pipe;1", - "nsIPipe", - "init"); -const FileInputStream = CC("@mozilla.org/network/file-input-stream;1", - "nsIFileInputStream", - "init"); -const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1", - "nsIConverterInputStream", - "init"); -const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1", - "nsIWritablePropertyBag2"); -const SupportsString = CC("@mozilla.org/supports-string;1", - "nsISupportsString"); - -/* These two are non-const only so a test can overwrite them. */ -var BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); -var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1", - "nsIBinaryOutputStream", - "setOutputStream"); - -/** -* Returns the RFC 822/1123 representation of a date. -* -* @param date : Number -* the date, in milliseconds from midnight (00:00:00), January 1, 1970 GMT -* @returns string -* the representation of the given date -*/ -function toDateString(date) -{ - // - // rfc1123-date = wkday "," SP date1 SP time SP "GMT" - // date1 = 2DIGIT SP month SP 4DIGIT - // ; day month year (e.g., 02 Jun 1982) - // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT - // ; 00:00:00 - 23:59:59 - // wkday = "Mon" | "Tue" | "Wed" - // | "Thu" | "Fri" | "Sat" | "Sun" - // month = "Jan" | "Feb" | "Mar" | "Apr" - // | "May" | "Jun" | "Jul" | "Aug" - // | "Sep" | "Oct" | "Nov" | "Dec" - // - - const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - - /** -* Processes a date and returns the encoded UTC time as a string according to -* the format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toTime(date) - { - var hrs = date.getUTCHours(); - var rv = (hrs < 10) ? "0" + hrs : hrs; - - var mins = date.getUTCMinutes(); - rv += ":"; - rv += (mins < 10) ? "0" + mins : mins; - - var secs = date.getUTCSeconds(); - rv += ":"; - rv += (secs < 10) ? "0" + secs : secs; - - return rv; - } - - /** -* Processes a date and returns the encoded UTC date as a string according to -* the date1 format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toDate1(date) - { - var day = date.getUTCDate(); - var month = date.getUTCMonth(); - var year = date.getUTCFullYear(); - - var rv = (day < 10) ? "0" + day : day; - rv += " " + monthStrings[month]; - rv += " " + year; - - return rv; - } - - date = new Date(date); - - const fmtString = "%wkday%, %date1% %time% GMT"; - var rv = fmtString.replace("%wkday%", wkdayStrings[date.getUTCDay()]); - rv = rv.replace("%time%", toTime(date)); - return rv.replace("%date1%", toDate1(date)); -} - -/** -* Prints out a human-readable representation of the object o and its fields, -* omitting those whose names begin with "_" if showMembers != true (to ignore -* "private" properties exposed via getters/setters). -*/ -function printObj(o, showMembers) -{ - var s = "******************************\n"; - s += "o = {\n"; - for (var i in o) - { - if (typeof(i) != "string" || - (showMembers || (i.length > 0 && i[0] != "_"))) - s+= " " + i + ": " + o[i] + ",\n"; - } - s += " };\n"; - s += "******************************"; - dumpn(s); -} - -/** -* Instantiates a new HTTP server. -*/ -function nsHttpServer() -{ - if (!gThreadManager) - gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService(); - - /** The port on which this server listens. */ - this._port = undefined; - - /** The socket associated with this. */ - this._socket = null; - - /** The handler used to process requests to this server. */ - this._handler = new ServerHandler(this); - - /** Naming information for this server. */ - this._identity = new ServerIdentity(); - - /** -* Indicates when the server is to be shut down at the end of the request. -*/ - this._doQuit = false; - - /** -* True if the socket in this is closed (and closure notifications have been -* sent and processed if the socket was ever opened), false otherwise. -*/ - this._socketClosed = true; - - /** -* Used for tracking existing connections and ensuring that all connections -* are properly cleaned up before server shutdown; increases by 1 for every -* new incoming connection. -*/ - this._connectionGen = 0; - - /** -* Hash of all open connections, indexed by connection number at time of -* creation. -*/ - this._connections = {}; -} -nsHttpServer.prototype = -{ - classID: components.ID("{54ef6f81-30af-4b1d-ac55-8ba811293e41}"), - - // NSISERVERSOCKETLISTENER - - /** -* Processes an incoming request coming in on the given socket and contained -* in the given transport. -* -* @param socket : nsIServerSocket -* the socket through which the request was served -* @param trans : nsISocketTransport -* the transport for the request/response -* @see nsIServerSocketListener.onSocketAccepted -*/ - onSocketAccepted: function(socket, trans) - { - dumpn("*** onSocketAccepted(socket=" + socket + ", trans=" + trans + ")"); - - dumpn(">>> new connection on " + trans.host + ":" + trans.port); - - const SEGMENT_SIZE = 8192; - const SEGMENT_COUNT = 1024; - try - { - var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT) - .QueryInterface(Ci.nsIAsyncInputStream); - var output = trans.openOutputStream(0, 0, 0); - } - catch (e) - { - dumpn("*** error opening transport streams: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - var connectionNumber = ++this._connectionGen; - - try - { - var conn = new Connection(input, output, this, socket.port, trans.port, - connectionNumber); - var reader = new RequestReader(conn); - - // XXX add request timeout functionality here! - - // Note: must use main thread here, or we might get a GC that will cause - // threadsafety assertions. We really need to fix XPConnect so that - // you can actually do things in multi-threaded JS. :-( - input.asyncWait(reader, 0, 0, gThreadManager.mainThread); - } - catch (e) - { - // Assume this connection can't be salvaged and bail on it completely; - // don't attempt to close it so that we can assert that any connection - // being closed is in this._connections. - dumpn("*** error in initial request-processing stages: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - this._connections[connectionNumber] = conn; - dumpn("*** starting connection " + connectionNumber); - }, - - /** -* Called when the socket associated with this is closed. -* -* @param socket : nsIServerSocket -* the socket being closed -* @param status : nsresult -* the reason the socket stopped listening (NS_BINDING_ABORTED if the server -* was stopped using nsIHttpServer.stop) -* @see nsIServerSocketListener.onStopListening -*/ - onStopListening: function(socket, status) - { - dumpn(">>> shutting down server on port " + socket.port); - this._socketClosed = true; - if (!this._hasOpenConnections()) - { - dumpn("*** no open connections, notifying async from onStopListening"); - - // Notify asynchronously so that any pending teardown in stop() has a - // chance to run first. - var self = this; - var stopEvent = - { - run: function() - { - dumpn("*** _notifyStopped async callback"); - self._notifyStopped(); - } - }; - gThreadManager.currentThread - .dispatch(stopEvent, Ci.nsIThread.DISPATCH_NORMAL); - } - }, - - // NSIHTTPSERVER - - // - // see nsIHttpServer.start - // - start: function(port) - { - this._start(port, "localhost") - }, - - _start: function(port, host) - { - if (this._socket) - throw Cr.NS_ERROR_ALREADY_INITIALIZED; - - this._port = port; - this._doQuit = this._socketClosed = false; - - this._host = host; - - // The listen queue needs to be long enough to handle - // network.http.max-persistent-connections-per-server concurrent connections, - // plus a safety margin in case some other process is talking to - // the server as well. - var prefs = getRootPrefBranch(); - var maxConnections; - try { - // Bug 776860: The original pref was removed in favor of this new one: - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server") + 5; - } - catch(e) { - maxConnections = prefs.getIntPref("network.http.max-connections-per-server") + 5; - } - - try - { - var loopback = true; - if (this._host != "127.0.0.1" && this._host != "localhost") { - var loopback = false; - } - - var socket = new ServerSocket(this._port, - loopback, // true = localhost, false = everybody - maxConnections); - dumpn(">>> listening on port " + socket.port + ", " + maxConnections + - " pending connections"); - socket.asyncListen(this); - this._identity._initialize(socket.port, host, true); - this._socket = socket; - } - catch (e) - { - dumpn("!!! could not start server on port " + port + ": " + e); - throw Cr.NS_ERROR_NOT_AVAILABLE; - } - }, - - // - // see nsIHttpServer.stop - // - stop: function(callback) - { - if (!callback) - throw Cr.NS_ERROR_NULL_POINTER; - if (!this._socket) - throw Cr.NS_ERROR_UNEXPECTED; - - this._stopCallback = typeof callback === "function" - ? callback - : function() { callback.onStopped(); }; - - dumpn(">>> stopping listening on port " + this._socket.port); - this._socket.close(); - this._socket = null; - - // We can't have this identity any more, and the port on which we're running - // this server now could be meaningless the next time around. - this._identity._teardown(); - - this._doQuit = false; - - // socket-close notification and pending request completion happen async - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (file && (!file.exists() || file.isDirectory())) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handler.registerFile(path, file); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // XXX true path validation! - if (path.charAt(0) != "/" || - path.charAt(path.length - 1) != "/" || - (directory && - (!directory.exists() || !directory.isDirectory()))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX determine behavior of nonexistent /foo/bar when a /foo/bar/ mapping - // exists! - - this._handler.registerDirectory(path, directory); - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - this._handler.registerPathHandler(path, handler); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - this._handler.registerPrefixHandler(prefix, handler); - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(code, handler) - { - this._handler.registerErrorHandler(code, handler); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - this._handler.setIndexHandler(handler); - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - this._handler.registerContentType(ext, type); - }, - - // - // see nsIHttpServer.serverIdentity - // - get identity() - { - return this._identity; - }, - - // - // see nsIHttpServer.getState - // - getState: function(path, k) - { - return this._handler._getState(path, k); - }, - - // - // see nsIHttpServer.setState - // - setState: function(path, k, v) - { - return this._handler._setState(path, k, v); - }, - - // - // see nsIHttpServer.getSharedState - // - getSharedState: function(k) - { - return this._handler._getSharedState(k); - }, - - // - // see nsIHttpServer.setSharedState - // - setSharedState: function(k, v) - { - return this._handler._setSharedState(k, v); - }, - - // - // see nsIHttpServer.getObjectState - // - getObjectState: function(k) - { - return this._handler._getObjectState(k); - }, - - // - // see nsIHttpServer.setObjectState - // - setObjectState: function(k, v) - { - return this._handler._setObjectState(k, v); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIServerSocketListener) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NON-XPCOM PUBLIC API - - /** -* Returns true iff this server is not running (and is not in the process of -* serving any requests still to be processed when the server was last -* stopped after being run). -*/ - isStopped: function() - { - return this._socketClosed && !this._hasOpenConnections(); - }, - - // PRIVATE IMPLEMENTATION - - /** True if this server has any open connections to it, false otherwise. */ - _hasOpenConnections: function() - { - // - // If we have any open connections, they're tracked as numeric properties on - // |this._connections|. The non-standard __count__ property could be used - // to check whether there are any properties, but standard-wise, even - // looking forward to ES5, there's no less ugly yet still O(1) way to do - // this. - // - for (var n in this._connections) - return true; - return false; - }, - - /** Calls the server-stopped callback provided when stop() was called. */ - _notifyStopped: function() - { - NS_ASSERT(this._stopCallback !== null, "double-notifying?"); - NS_ASSERT(!this._hasOpenConnections(), "should be done serving by now"); - - // - // NB: We have to grab this now, null out the member, *then* call the - // callback here, or otherwise the callback could (indirectly) futz with - // this._stopCallback by starting and immediately stopping this, at - // which point we'd be nulling out a field we no longer have a right to - // modify. - // - var callback = this._stopCallback; - this._stopCallback = null; - try - { - callback(); - } - catch (e) - { - // not throwing because this is specified as being usually (but not - // always) asynchronous - dump("!!! error running onStopped callback: " + e + "\n"); - } - }, - - /** -* Notifies this server that the given connection has been closed. -* -* @param connection : Connection -* the connection that was closed -*/ - _connectionClosed: function(connection) - { - NS_ASSERT(connection.number in this._connections, - "closing a connection " + this + " that we never added to the " + - "set of open connections?"); - NS_ASSERT(this._connections[connection.number] === connection, - "connection number mismatch? " + - this._connections[connection.number]); - delete this._connections[connection.number]; - - // Fire a pending server-stopped notification if it's our responsibility. - if (!this._hasOpenConnections() && this._socketClosed) - this._notifyStopped(); - }, - - /** -* Requests that the server be shut down when possible. -*/ - _requestQuit: function() - { - dumpn(">>> requesting a quit"); - dumpStack(); - this._doQuit = true; - } -}; - - -// -// RFC 2396 section 3.2.2: -// -// host = hostname | IPv4address -// hostname = *( domainlabel "." ) toplabel [ "." ] -// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum -// toplabel = alpha | alpha *( alphanum | "-" ) alphanum -// IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit -// - -const HOST_REGEX = - new RegExp("^(?:" + - // *( domainlabel "." ) - "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" + - // toplabel - "[a-z](?:[a-z0-9-]*[a-z0-9])?" + - "|" + - // IPv4 address - "\\d+\\.\\d+\\.\\d+\\.\\d+" + - ")$", - "i"); - - -/** -* Represents the identity of a server. An identity consists of a set of -* (scheme, host, port) tuples denoted as locations (allowing a single server to -* serve multiple sites or to be used behind both HTTP and HTTPS proxies for any -* host/port). Any incoming request must be to one of these locations, or it -* will be rejected with an HTTP 400 error. One location, denoted as the -* primary location, is the location assigned in contexts where a location -* cannot otherwise be endogenously derived, such as for HTTP/1.0 requests. -* -* A single identity may contain at most one location per unique host/port pair; -* other than that, no restrictions are placed upon what locations may -* constitute an identity. -*/ -function ServerIdentity() -{ - /** The scheme of the primary location. */ - this._primaryScheme = "http"; - - /** The hostname of the primary location. */ - this._primaryHost = "127.0.0.1" - - /** The port number of the primary location. */ - this._primaryPort = -1; - - /** -* The current port number for the corresponding server, stored so that a new -* primary location can always be set if the current one is removed. -*/ - this._defaultPort = -1; - - /** -* Maps hosts to maps of ports to schemes, e.g. the following would represent -* https://example.com:789/ and http://example.org/: -* -* { -* "xexample.com": { 789: "https" }, -* "xexample.org": { 80: "http" } -* } -* -* Note the "x" prefix on hostnames, which prevents collisions with special -* JS names like "prototype". -*/ - this._locations = { "xlocalhost": {} }; -} -ServerIdentity.prototype = -{ - // NSIHTTPSERVERIDENTITY - - // - // see nsIHttpServerIdentity.primaryScheme - // - get primaryScheme() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryScheme; - }, - - // - // see nsIHttpServerIdentity.primaryHost - // - get primaryHost() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryHost; - }, - - // - // see nsIHttpServerIdentity.primaryPort - // - get primaryPort() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryPort; - }, - - // - // see nsIHttpServerIdentity.add - // - add: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - this._locations["x" + host] = entry = {}; - - entry[port] = scheme; - }, - - // - // see nsIHttpServerIdentity.remove - // - remove: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return false; - - var present = port in entry; - delete entry[port]; - - if (this._primaryScheme == scheme && - this._primaryHost == host && - this._primaryPort == port && - this._defaultPort !== -1) - { - // Always keep at least one identity in existence at any time, unless - // we're in the process of shutting down (the last condition above). - this._primaryPort = -1; - this._initialize(this._defaultPort, host, false); - } - - return present; - }, - - // - // see nsIHttpServerIdentity.has - // - has: function(scheme, host, port) - { - this._validate(scheme, host, port); - - return "x" + host in this._locations && - scheme === this._locations["x" + host][port]; - }, - - // - // see nsIHttpServerIdentity.has - // - getScheme: function(host, port) - { - this._validate("http", host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return ""; - - return entry[port] || ""; - }, - - // - // see nsIHttpServerIdentity.setPrimary - // - setPrimary: function(scheme, host, port) - { - this._validate(scheme, host, port); - - this.add(scheme, host, port); - - this._primaryScheme = scheme; - this._primaryHost = host; - this._primaryPort = port; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpServerIdentity) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Initializes the primary name for the corresponding server, based on the -* provided port number. -*/ - _initialize: function(port, host, addSecondaryDefault) - { - this._host = host; - if (this._primaryPort !== -1) - this.add("http", host, port); - else - this.setPrimary("http", "localhost", port); - this._defaultPort = port; - - // Only add this if we're being called at server startup - if (addSecondaryDefault && host != "127.0.0.1") - this.add("http", "127.0.0.1", port); - }, - - /** -* Called at server shutdown time, unsets the primary location only if it was -* the default-assigned location and removes the default location from the -* set of locations used. -*/ - _teardown: function() - { - if (this._host != "127.0.0.1") { - // Not the default primary location, nothing special to do here - this.remove("http", "127.0.0.1", this._defaultPort); - } - - // This is a *very* tricky bit of reasoning here; make absolutely sure the - // tests for this code pass before you commit changes to it. - if (this._primaryScheme == "http" && - this._primaryHost == this._host && - this._primaryPort == this._defaultPort) - { - // Make sure we don't trigger the readding logic in .remove(), then remove - // the default location. - var port = this._defaultPort; - this._defaultPort = -1; - this.remove("http", this._host, port); - - // Ensure a server start triggers the setPrimary() path in ._initialize() - this._primaryPort = -1; - } - else - { - // No reason not to remove directly as it's not our primary location - this.remove("http", this._host, this._defaultPort); - } - }, - - /** -* Ensures scheme, host, and port are all valid with respect to RFC 2396. -* -* @throws NS_ERROR_ILLEGAL_VALUE -* if any argument doesn't match the corresponding production -*/ - _validate: function(scheme, host, port) - { - if (scheme !== "http" && scheme !== "https") - { - dumpn("*** server only supports http/https schemes: '" + scheme + "'"); - dumpStack(); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (!HOST_REGEX.test(host)) - { - dumpn("*** unexpected host: '" + host + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (port < 0 || port > 65535) - { - dumpn("*** unexpected port: '" + port + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - } -}; - - -/** -* Represents a connection to the server (and possibly in the future the thread -* on which the connection is processed). -* -* @param input : nsIInputStream -* stream from which incoming data on the connection is read -* @param output : nsIOutputStream -* stream to write data out the connection -* @param server : nsHttpServer -* the server handling the connection -* @param port : int -* the port on which the server is running -* @param outgoingPort : int -* the outgoing port used by this connection -* @param number : uint -* a serial number used to uniquely identify this connection -*/ -function Connection(input, output, server, port, outgoingPort, number) -{ - dumpn("*** opening new connection " + number + " on port " + outgoingPort); - - /** Stream of incoming data. */ - this.input = input; - - /** Stream for outgoing data. */ - this.output = output; - - /** The server associated with this request. */ - this.server = server; - - /** The port on which the server is running. */ - this.port = port; - - /** The outgoing poort used by this connection. */ - this._outgoingPort = outgoingPort; - - /** The serial number of this connection. */ - this.number = number; - - /** -* The request for which a response is being generated, null if the -* incoming request has not been fully received or if it had errors. -*/ - this.request = null; - - /** State variables for debugging. */ - this._closed = this._processed = false; -} -Connection.prototype = -{ - /** Closes this connection's input/output streams. */ - close: function() - { - dumpn("*** closing connection " + this.number + - " on port " + this._outgoingPort); - - this.input.close(); - this.output.close(); - this._closed = true; - - var server = this.server; - server._connectionClosed(this); - - // If an error triggered a server shutdown, act on it now - if (server._doQuit) - server.stop(function() { /* not like we can do anything better */ }); - }, - - /** -* Initiates processing of this connection, using the data in the given -* request. -* -* @param request : Request -* the request which should be processed -*/ - process: function(request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - - this.request = request; - this.server._handler.handleResponse(this); - }, - - /** -* Initiates processing of this connection, generating a response with the -* given HTTP error code. -* -* @param code : uint -* an HTTP code, so in the range [0, 1000) -* @param request : Request -* incomplete data about the incoming request (since there were errors -* during its processing -*/ - processError: function(code, request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - this.request = request; - this.server._handler.handleError(code, this); - }, - - /** Converts this to a string for debugging purposes. */ - toString: function() - { - return ""; - } -}; - - - -/** Returns an array of count bytes from the given input stream. */ -function readBytes(inputStream, count) -{ - return new BinaryInputStream(inputStream).readByteArray(count); -} - - - -/** Request reader processing states; see RequestReader for details. */ -const READER_IN_REQUEST_LINE = 0; -const READER_IN_HEADERS = 1; -const READER_IN_BODY = 2; -const READER_FINISHED = 3; - - -/** -* Reads incoming request data asynchronously, does any necessary preprocessing, -* and forwards it to the request handler. Processing occurs in three states: -* -* READER_IN_REQUEST_LINE Reading the request's status line -* READER_IN_HEADERS Reading headers in the request -* READER_IN_BODY Reading the body of the request -* READER_FINISHED Entire request has been read and processed -* -* During the first two stages, initial metadata about the request is gathered -* into a Request object. Once the status line and headers have been processed, -* we start processing the body of the request into the Request. Finally, when -* the entire body has been read, we create a Response and hand it off to the -* ServerHandler to be given to the appropriate request handler. -* -* @param connection : Connection -* the connection for the request being read -*/ -function RequestReader(connection) -{ - /** Connection metadata for this request. */ - this._connection = connection; - - /** -* A container providing line-by-line access to the raw bytes that make up the -* data which has been read from the connection but has not yet been acted -* upon (by passing it to the request handler or by extracting request -* metadata from it). -*/ - this._data = new LineData(); - - /** -* The amount of data remaining to be read from the body of this request. -* After all headers in the request have been read this is the value in the -* Content-Length header, but as the body is read its value decreases to zero. -*/ - this._contentLength = 0; - - /** The current state of parsing the incoming request. */ - this._state = READER_IN_REQUEST_LINE; - - /** Metadata constructed from the incoming request for the request handler. */ - this._metadata = new Request(connection.port); - - /** -* Used to preserve state if we run out of line data midway through a -* multi-line header. _lastHeaderName stores the name of the header, while -* _lastHeaderValue stores the value we've seen so far for the header. -* -* These fields are always either both undefined or both strings. -*/ - this._lastHeaderName = this._lastHeaderValue = undefined; -} -RequestReader.prototype = -{ - // NSIINPUTSTREAMCALLBACK - - /** -* Called when more data from the incoming request is available. This method -* then reads the available data from input and deals with that data as -* necessary, depending upon the syntax of already-downloaded data. -* -* @param input : nsIAsyncInputStream -* the stream of incoming data from the connection -*/ - onInputStreamReady: function(input) - { - dumpn("*** onInputStreamReady(input=" + input + ") on thread " + - gThreadManager.currentThread + " (main is " + - gThreadManager.mainThread + ")"); - dumpn("*** this._state == " + this._state); - - // Handle cases where we get more data after a request error has been - // discovered but *before* we can close the connection. - var data = this._data; - if (!data) - return; - - try - { - data.appendBytes(readBytes(input, input.available())); - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** WARNING: unexpected error when reading from socket; will " + - "be treated as if the input stream had been closed"); - dumpn("*** WARNING: actual error was: " + e); - } - - // We've lost a race -- input has been closed, but we're still expecting - // to read more data. available() will throw in this case, and since - // we're dead in the water now, destroy the connection. - dumpn("*** onInputStreamReady called on a closed input, destroying " + - "connection"); - this._connection.close(); - return; - } - - switch (this._state) - { - default: - NS_ASSERT(false, "invalid state: " + this._state); - break; - - case READER_IN_REQUEST_LINE: - if (!this._processRequestLine()) - break; - /* fall through */ - - case READER_IN_HEADERS: - if (!this._processHeaders()) - break; - /* fall through */ - - case READER_IN_BODY: - this._processBody(); - } - - if (this._state != READER_FINISHED) - input.asyncWait(this, 0, 0, gThreadManager.currentThread); - }, - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIInputStreamCallback) || - aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE API - - /** -* Processes unprocessed, downloaded data as a request line. -* -* @returns boolean -* true iff the request line has been fully processed -*/ - _processRequestLine: function() - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - // Servers SHOULD ignore any empty line(s) received where a Request-Line - // is expected (section 4.1). - var data = this._data; - var line = {}; - var readSuccess; - while ((readSuccess = data.readLine(line)) && line.value == "") - dumpn("*** ignoring beginning blank line..."); - - // if we don't have a full line, wait until we do - if (!readSuccess) - return false; - - // we have the first non-blank line - try - { - this._parseRequestLine(line.value); - this._state = READER_IN_HEADERS; - return true; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing request headers. -* -* @returns boolean -* true iff header data in the request has been fully processed -*/ - _processHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - // XXX things to fix here: - // - // - need to support RFC 2047-encoded non-US-ASCII characters - - try - { - var done = this._parseHeaders(); - if (done) - { - var request = this._metadata; - - // XXX this is wrong for requests with transfer-encodings applied to - // them, particularly chunked (which by its nature can have no - // meaningful Content-Length header)! - this._contentLength = request.hasHeader("Content-Length") - ? parseInt(request.getHeader("Content-Length"), 10) - : 0; - dumpn("_processHeaders, Content-length=" + this._contentLength); - - this._state = READER_IN_BODY; - } - return done; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing the request body. -* -* @returns boolean -* true iff the request body has been fully processed -*/ - _processBody: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - // XXX handle chunked transfer-coding request bodies! - - try - { - if (this._contentLength > 0) - { - var data = this._data.purge(); - var count = Math.min(data.length, this._contentLength); - dumpn("*** loading data=" + data + " len=" + data.length + - " excess=" + (data.length - count)); - - var bos = new BinaryOutputStream(this._metadata._bodyOutputStream); - bos.writeByteArray(data, count); - this._contentLength -= count; - } - - dumpn("*** remaining body data len=" + this._contentLength); - if (this._contentLength == 0) - { - this._validateRequest(); - this._state = READER_FINISHED; - this._handleResponse(); - return true; - } - - return false; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Does various post-header checks on the data in this request. -* -* @throws : HttpError -* if the request was malformed in some way -*/ - _validateRequest: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - dumpn("*** _validateRequest"); - - var metadata = this._metadata; - var headers = metadata._headers; - - // 19.6.1.1 -- servers MUST report 400 to HTTP/1.1 requests w/o Host header - var identity = this._connection.server.identity; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - { - if (!headers.hasHeader("Host")) - { - dumpn("*** malformed HTTP/1.1 or greater request with no Host header!"); - throw HTTP_400; - } - - // If the Request-URI wasn't absolute, then we need to determine our host. - // We have to determine what scheme was used to access us based on the - // server identity data at this point, because the request just doesn't - // contain enough data on its own to do this, sadly. - if (!metadata._host) - { - var host, port; - var hostPort = headers.getHeader("Host"); - var colon = hostPort.indexOf(":"); - if (colon < 0) - { - host = hostPort; - port = ""; - } - else - { - host = hostPort.substring(0, colon); - port = hostPort.substring(colon + 1); - } - - // NB: We allow an empty port here because, oddly, a colon may be - // present even without a port number, e.g. "example.com:"; in this - // case the default port applies. - if (!HOST_REGEX.test(host) || !/^\d*$/.test(port)) - { - dumpn("*** malformed hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - // If we're not given a port, we're stuck, because we don't know what - // scheme to use to look up the correct port here, in general. Since - // the HTTPS case requires a tunnel/proxy and thus requires that the - // requested URI be absolute (and thus contain the necessary - // information), let's assume HTTP will prevail and use that. - port = +port || 80; - - var scheme = identity.getScheme(host, port); - if (!scheme) - { - dumpn("*** unrecognized hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - } - } - else - { - NS_ASSERT(metadata._host === undefined, - "HTTP/1.0 doesn't allow absolute paths in the request line!"); - - metadata._scheme = identity.primaryScheme; - metadata._host = identity.primaryHost; - metadata._port = identity.primaryPort; - } - - NS_ASSERT(identity.has(metadata._scheme, metadata._host, metadata._port), - "must have a location we recognize by now!"); - }, - - /** -* Handles responses in case of error, either in the server or in the request. -* -* @param e -* the specific error encountered, which is an HttpError in the case where -* the request is in some way invalid or cannot be fulfilled; if this isn't -* an HttpError we're going to be paranoid and shut down, because that -* shouldn't happen, ever -*/ - _handleError: function(e) - { - // Don't fall back into normal processing! - this._state = READER_FINISHED; - - var server = this._connection.server; - if (e instanceof HttpError) - { - var code = e.code; - } - else - { - dumpn("!!! UNEXPECTED ERROR: " + e + - (e.lineNumber ? ", line " + e.lineNumber : "")); - - // no idea what happened -- be paranoid and shut down - code = 500; - server._requestQuit(); - } - - // make attempted reuse of data an error - this._data = null; - - this._connection.processError(code, this._metadata); - }, - - /** -* Now that we've read the request line and headers, we can actually hand off -* the request to be handled. -* -* This method is called once per request, after the request line and all -* headers and the body, if any, have been received. -*/ - _handleResponse: function() - { - NS_ASSERT(this._state == READER_FINISHED); - - // We don't need the line-based data any more, so make attempted reuse an - // error. - this._data = null; - - this._connection.process(this._metadata); - }, - - - // PARSING - - /** -* Parses the request line for the HTTP request associated with this. -* -* @param line : string -* the request line -*/ - _parseRequestLine: function(line) - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - dumpn("*** _parseRequestLine('" + line + "')"); - - var metadata = this._metadata; - - // clients and servers SHOULD accept any amount of SP or HT characters - // between fields, even though only a single SP is required (section 19.3) - var request = line.split(/[ \t]+/); - if (!request || request.length != 3) - throw HTTP_400; - - metadata._method = request[0]; - - // get the HTTP version - var ver = request[2]; - var match = ver.match(/^HTTP\/(\d+\.\d+)$/); - if (!match) - throw HTTP_400; - - // determine HTTP version - try - { - metadata._httpVersion = new nsHttpVersion(match[1]); - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_0)) - throw "unsupported HTTP version"; - } - catch (e) - { - // we support HTTP/1.0 and HTTP/1.1 only - throw HTTP_501; - } - - - var fullPath = request[1]; - var serverIdentity = this._connection.server.identity; - - var scheme, host, port; - - if (fullPath.charAt(0) != "/") - { - // No absolute paths in the request line in HTTP prior to 1.1 - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - throw HTTP_400; - - try - { - var uri = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService) - .newURI(fullPath, null, null); - fullPath = uri.path; - scheme = uri.scheme; - host = metadata._host = uri.asciiHost; - port = uri.port; - if (port === -1) - { - if (scheme === "http") - port = 80; - else if (scheme === "https") - port = 443; - else - throw HTTP_400; - } - } - catch (e) - { - // If the host is not a valid host on the server, the response MUST be a - // 400 (Bad Request) error message (section 5.2). Alternately, the URI - // is malformed. - throw HTTP_400; - } - - if (!serverIdentity.has(scheme, host, port) || fullPath.charAt(0) != "/") - throw HTTP_400; - } - - var splitter = fullPath.indexOf("?"); - if (splitter < 0) - { - // _queryString already set in ctor - metadata._path = fullPath; - } - else - { - metadata._path = fullPath.substring(0, splitter); - metadata._queryString = fullPath.substring(splitter + 1); - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - }, - - /** -* Parses all available HTTP headers in this until the header-ending CRLFCRLF, -* adding them to the store of headers in the request. -* -* @throws -* HTTP_400 if the headers are malformed -* @returns boolean -* true if all headers have now been processed, false otherwise -*/ - _parseHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - dumpn("*** _parseHeaders"); - - var data = this._data; - - var headers = this._metadata._headers; - var lastName = this._lastHeaderName; - var lastVal = this._lastHeaderValue; - - var line = {}; - while (true) - { - NS_ASSERT(!((lastVal === undefined) ^ (lastName === undefined)), - lastName === undefined ? - "lastVal without lastName? lastVal: '" + lastVal + "'" : - "lastName without lastVal? lastName: '" + lastName + "'"); - - if (!data.readLine(line)) - { - // save any data we have from the header we might still be processing - this._lastHeaderName = lastName; - this._lastHeaderValue = lastVal; - return false; - } - - var lineText = line.value; - var firstChar = lineText.charAt(0); - - // blank line means end of headers - if (lineText == "") - { - // we're finished with the previous header - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - else - { - // no headers in request -- valid for HTTP/1.0 requests - } - - // either way, we're done processing headers - this._state = READER_IN_BODY; - return true; - } - else if (firstChar == " " || firstChar == "\t") - { - // multi-line header if we've already seen a header line - if (!lastName) - { - // we don't have a header to continue! - throw HTTP_400; - } - - // append this line's text to the value; starts with SP/HT, so no need - // for separating whitespace - lastVal += lineText; - } - else - { - // we have a new header, so set the old one (if one existed) - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - - var colon = lineText.indexOf(":"); // first colon must be splitter - if (colon < 1) - { - // no colon or missing header field-name - throw HTTP_400; - } - - // set header name, value (to be set in the next loop, usually) - lastName = lineText.substring(0, colon); - lastVal = lineText.substring(colon + 1); - } // empty, continuation, start of header - } // while (true) - } -}; - - -/** The character codes for CR and LF. */ -const CR = 0x0D, LF = 0x0A; - -/** -* Calculates the number of characters before the first CRLF pair in array, or -* -1 if the array contains no CRLF pair. -* -* @param array : Array -* an array of numbers in the range [0, 256), each representing a single -* character; the first CRLF is the lowest index i where -* |array[i] == "\r".charCodeAt(0)| and |array[i+1] == "\n".charCodeAt(0)|, -* if such an |i| exists, and -1 otherwise -* @returns int -* the index of the first CRLF if any were present, -1 otherwise -*/ -function findCRLF(array) -{ - for (var i = array.indexOf(CR); i >= 0; i = array.indexOf(CR, i + 1)) - { - if (array[i + 1] == LF) - return i; - } - return -1; -} - - -/** -* A container which provides line-by-line access to the arrays of bytes with -* which it is seeded. -*/ -function LineData() -{ - /** An array of queued bytes from which to get line-based characters. */ - this._data = []; -} -LineData.prototype = -{ - /** -* Appends the bytes in the given array to the internal data cache maintained -* by this. -*/ - appendBytes: function(bytes) - { - Array.prototype.push.apply(this._data, bytes); - }, - - /** -* Removes and returns a line of data, delimited by CRLF, from this. -* -* @param out -* an object whose "value" property will be set to the first line of text -* present in this, sans CRLF, if this contains a full CRLF-delimited line -* of text; if this doesn't contain enough data, the value of the property -* is undefined -* @returns boolean -* true if a full line of data could be read from the data in this, false -* otherwise -*/ - readLine: function(out) - { - var data = this._data; - var length = findCRLF(data); - if (length < 0) - return false; - - // - // We have the index of the CR, so remove all the characters, including - // CRLF, from the array with splice, and convert the removed array into the - // corresponding string, from which we then strip the trailing CRLF. - // - // Getting the line in this matter acknowledges that substring is an O(1) - // operation in SpiderMonkey because strings are immutable, whereas two - // splices, both from the beginning of the data, are less likely to be as - // cheap as a single splice plus two extra character conversions. - // - var line = String.fromCharCode.apply(null, data.splice(0, length + 2)); - out.value = line.substring(0, length); - - return true; - }, - - /** -* Removes the bytes currently within this and returns them in an array. -* -* @returns Array -* the bytes within this when this method is called -*/ - purge: function() - { - var data = this._data; - this._data = []; - return data; - } -}; - - - -/** -* Creates a request-handling function for an nsIHttpRequestHandler object. -*/ -function createHandlerFunc(handler) -{ - return function(metadata, response) { handler.handle(metadata, response); }; -} - - -/** -* The default handler for directories; writes an HTML response containing a -* slightly-formatted directory listing. -*/ -function defaultIndexHandler(metadata, response) -{ - response.setHeader("Content-Type", "text/html", false); - - var path = htmlEscape(decodeURI(metadata.path)); - - // - // Just do a very basic bit of directory listings -- no need for too much - // fanciness, especially since we don't have a style sheet in which we can - // stick rules (don't want to pollute the default path-space). - // - - var body = '\ -\ -' + path + '\ -\ -\ -

' + path + '

\ -
    '; - - var directory = metadata.getProperty("directory").QueryInterface(Ci.nsILocalFile); - NS_ASSERT(directory && directory.isDirectory()); - - var fileList = []; - var files = directory.directoryEntries; - while (files.hasMoreElements()) - { - var f = files.getNext().QueryInterface(Ci.nsIFile); - var name = f.leafName; - if (!f.isHidden() && - (name.charAt(name.length - 1) != HIDDEN_CHAR || - name.charAt(name.length - 2) == HIDDEN_CHAR)) - fileList.push(f); - } - - fileList.sort(fileSort); - - for (var i = 0; i < fileList.length; i++) - { - var file = fileList[i]; - try - { - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - var sep = file.isDirectory() ? "/" : ""; - - // Note: using " to delimit the attribute here because encodeURIComponent - // passes through '. - var item = '
  1. ' + - htmlEscape(name) + sep + - '
  2. '; - - body += item; - } - catch (e) { /* some file system error, ignore the file */ } - } - - body += '
\ -\ -'; - - response.bodyOutputStream.write(body, body.length); -} - -/** -* Sorts a and b (nsIFile objects) into an aesthetically pleasing order. -*/ -function fileSort(a, b) -{ - var dira = a.isDirectory(), dirb = b.isDirectory(); - - if (dira && !dirb) - return -1; - if (dirb && !dira) - return 1; - - var namea = a.leafName.toLowerCase(), nameb = b.leafName.toLowerCase(); - return nameb > namea ? -1 : 1; -} - - -/** -* Converts an externally-provided path into an internal path for use in -* determining file mappings. -* -* @param path -* the path to convert -* @param encoded -* true if the given path should be passed through decodeURI prior to -* conversion -* @throws URIError -* if path is incorrectly encoded -*/ -function toInternalPath(path, encoded) -{ - if (encoded) - path = decodeURI(path); - - var comps = path.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - if (comp.charAt(comp.length - 1) == HIDDEN_CHAR) - comps[i] = comp + HIDDEN_CHAR; - } - return comps.join("/"); -} - - -/** -* Adds custom-specified headers for the given file to the given response, if -* any such headers are specified. -* -* @param file -* the file on the disk which is to be written -* @param metadata -* metadata about the incoming request -* @param response -* the Response to which any specified headers/data should be written -* @throws HTTP_500 -* if an error occurred while processing custom-specified headers -*/ -function maybeAddHeaders(file, metadata, response) -{ - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - - var headerFile = file.parent; - headerFile.append(name + HEADERS_SUFFIX); - - if (!headerFile.exists()) - return; - - const PR_RDONLY = 0x01; - var fis = new FileInputStream(headerFile, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0); - lis.QueryInterface(Ci.nsIUnicharLineInputStream); - - var line = {value: ""}; - var more = lis.readLine(line); - - if (!more && line.value == "") - return; - - - // request line - - var status = line.value; - if (status.indexOf("HTTP ") == 0) - { - status = status.substring(5); - var space = status.indexOf(" "); - var code, description; - if (space < 0) - { - code = status; - description = ""; - } - else - { - code = status.substring(0, space); - description = status.substring(space + 1, status.length); - } - - response.setStatusLine(metadata.httpVersion, parseInt(code, 10), description); - - line.value = ""; - more = lis.readLine(line); - } - - // headers - while (more || line.value != "") - { - var header = line.value; - var colon = header.indexOf(":"); - - response.setHeader(header.substring(0, colon), - header.substring(colon + 1, header.length), - false); // allow overriding server-set headers - - line.value = ""; - more = lis.readLine(line); - } - } - catch (e) - { - dumpn("WARNING: error in headers for " + metadata.path + ": " + e); - throw HTTP_500; - } - finally - { - fis.close(); - } -} - - -/** -* An object which handles requests for a server, executing default and -* overridden behaviors as instructed by the code which uses and manipulates it. -* Default behavior includes the paths / and /trace (diagnostics), with some -* support for HTTP error pages for various codes and fallback to HTTP 500 if -* those codes fail for any reason. -* -* @param server : nsHttpServer -* the server in which this handler is being used -*/ -function ServerHandler(server) -{ - // FIELDS - - /** -* The nsHttpServer instance associated with this handler. -*/ - this._server = server; - - /** -* A FileMap object containing the set of path->nsILocalFile mappings for -* all directory mappings set in the server (e.g., "/" for /var/www/html/, -* "/foo/bar/" for /local/path/, and "/foo/bar/baz/" for /local/path2). -* -* Note carefully: the leading and trailing "/" in each path (not file) are -* removed before insertion to simplify the code which uses this. You have -* been warned! -*/ - this._pathDirectoryMap = new FileMap(); - - /** -* Custom request handlers for the server in which this resides. Path-handler -* pairs are stored as property-value pairs in this property. -* -* @see ServerHandler.prototype._defaultPaths -*/ - this._overridePaths = {}; - - /** -* Custom request handlers for the server in which this resides. Prefix-handler -* pairs are stored as property-value pairs in this property. -*/ - this._overridePrefixes = {}; - - /** -* Custom request handlers for the error handlers in the server in which this -* resides. Path-handler pairs are stored as property-value pairs in this -* property. -* -* @see ServerHandler.prototype._defaultErrors -*/ - this._overrideErrors = {}; - - /** -* Maps file extensions to their MIME types in the server, overriding any -* mapping that might or might not exist in the MIME service. -*/ - this._mimeMappings = {}; - - /** -* The default handler for requests for directories, used to serve directories -* when no index file is present. -*/ - this._indexHandler = defaultIndexHandler; - - /** Per-path state storage for the server. */ - this._state = {}; - - /** Entire-server state storage. */ - this._sharedState = {}; - - /** Entire-server state storage for nsISupports values. */ - this._objectState = {}; -} -ServerHandler.prototype = -{ - // PUBLIC API - - /** -* Handles a request to this server, responding to the request appropriately -* and initiating server shutdown if necessary. -* -* This method never throws an exception. -* -* @param connection : Connection -* the connection for this request -*/ - handleResponse: function(connection) - { - var request = connection.request; - var response = new Response(connection); - - var path = request.path; - dumpn("*** path == " + path); - - try - { - try - { - if (path in this._overridePaths) - { - // explicit paths first, then files based on existing directory mappings, - // then (if the file doesn't exist) built-in server default paths - dumpn("calling override for " + path); - this._overridePaths[path](request, response); - } - else - { - let longestPrefix = ""; - for (let prefix in this._overridePrefixes) - { - if (prefix.length > longestPrefix.length && path.startsWith(prefix)) - { - longestPrefix = prefix; - } - } - if (longestPrefix.length > 0) - { - dumpn("calling prefix override for " + longestPrefix); - this._overridePrefixes[longestPrefix](request, response); - } - else - { - this._handleDefault(request, response); - } - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - if (!(e instanceof HttpError)) - { - dumpn("*** unexpected error: e == " + e); - throw HTTP_500; - } - if (e.code !== 404) - throw e; - - dumpn("*** default: " + (path in this._defaultPaths)); - - response = new Response(connection); - if (path in this._defaultPaths) - this._defaultPaths[path](request, response); - else - throw HTTP_404; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - var errorCode = "internal"; - - try - { - if (!(e instanceof HttpError)) - throw e; - - errorCode = e.code; - dumpn("*** errorCode == " + errorCode); - - response = new Response(connection); - if (e.customErrorHandling) - e.customErrorHandling(response); - this._handleError(errorCode, request, response); - return; - } - catch (e2) - { - dumpn("*** error handling " + errorCode + " error: " + - "e2 == " + e2 + ", shutting down server"); - - connection.server._requestQuit(); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (!file) - { - dumpn("*** unregistering '" + path + "' mapping"); - delete this._overridePaths[path]; - return; - } - - dumpn("*** registering '" + path + "' as mapping to " + file.path); - file = file.clone(); - - var self = this; - this._overridePaths[path] = - function(request, response) - { - if (!file.exists()) - throw HTTP_404; - - response.setStatusLine(request.httpVersion, 200, "OK"); - self._writeFileResponse(request, file, response, 0, file.fileSize); - }; - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - // XXX true path validation! - if (path.charAt(0) != "/") - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePaths, path); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - // XXX true prefix validation! - if (!(prefix.startsWith("/") && prefix.endsWith("/"))) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePrefixes, prefix); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // strip off leading and trailing '/' so that we can use lastIndexOf when - // determining exactly how a path maps onto a mapped directory -- - // conditional is required here to deal with "/".substring(1, 0) being - // converted to "/".substring(0, 1) per the JS specification - var key = path.length == 1 ? "" : path.substring(1, path.length - 1); - - // the path-to-directory mapping code requires that the first character not - // be "/", or it will go into an infinite loop - if (key.charAt(0) == "/") - throw Cr.NS_ERROR_INVALID_ARG; - - key = toInternalPath(key, false); - - if (directory) - { - dumpn("*** mapping '" + path + "' to the location " + directory.path); - this._pathDirectoryMap.put(key, directory); - } - else - { - dumpn("*** removing mapping for '" + path + "'"); - this._pathDirectoryMap.put(key, null); - } - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(err, handler) - { - if (!(err in HTTP_ERROR_CODES)) - dumpn("*** WARNING: registering non-HTTP/1.1 error code " + - "(" + err + ") handler -- was this intentional?"); - - this._handlerToField(handler, this._overrideErrors, err); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - if (!handler) - handler = defaultIndexHandler; - else if (typeof(handler) != "function") - handler = createHandlerFunc(handler); - - this._indexHandler = handler; - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - if (!type) - delete this._mimeMappings[ext]; - else - this._mimeMappings[ext] = headerUtils.normalizeFieldValue(type); - }, - - // PRIVATE API - - /** -* Sets or remove (if handler is null) a handler in an object with a key. -* -* @param handler -* a handler, either function or an nsIHttpRequestHandler -* @param dict -* The object to attach the handler to. -* @param key -* The field name of the handler. -*/ - _handlerToField: function(handler, dict, key) - { - // for convenience, handler can be a function if this is run from xpcshell - if (typeof(handler) == "function") - dict[key] = handler; - else if (handler) - dict[key] = createHandlerFunc(handler); - else - delete dict[key]; - }, - - /** -* Handles a request which maps to a file in the local filesystem (if a base -* path has already been set; otherwise the 404 error is thrown). -* -* @param metadata : Request -* metadata for the incoming request -* @param response : Response -* an uninitialized Response to the given request, to be initialized by a -* request handler -* @throws HTTP_### -* if an HTTP error occurred (usually HTTP_404); note that in this case the -* calling code must handle post-processing of the response -*/ - _handleDefault: function(metadata, response) - { - dumpn("*** _handleDefault()"); - - response.setStatusLine(metadata.httpVersion, 200, "OK"); - - var path = metadata.path; - NS_ASSERT(path.charAt(0) == "/", "invalid path: <" + path + ">"); - - // determine the actual on-disk file; this requires finding the deepest - // path-to-directory mapping in the requested URL - var file = this._getFileForPath(path); - - // the "file" might be a directory, in which case we either serve the - // contained index.html or make the index handler write the response - if (file.exists() && file.isDirectory()) - { - file.append("index.html"); // make configurable? - if (!file.exists() || file.isDirectory()) - { - metadata._ensurePropertyBag(); - metadata._bag.setPropertyAsInterface("directory", file.parent); - this._indexHandler(metadata, response); - return; - } - } - - // alternately, the file might not exist - if (!file.exists()) - throw HTTP_404; - - var start, end; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1) && - metadata.hasHeader("Range") && - this._getTypeFromFile(file) !== SJS_TYPE) - { - var rangeMatch = metadata.getHeader("Range").match(/^bytes=(\d+)?-(\d+)?$/); - if (!rangeMatch) - throw HTTP_400; - - if (rangeMatch[1] !== undefined) - start = parseInt(rangeMatch[1], 10); - - if (rangeMatch[2] !== undefined) - end = parseInt(rangeMatch[2], 10); - - if (start === undefined && end === undefined) - throw HTTP_400; - - // No start given, so the end is really the count of bytes from the - // end of the file. - if (start === undefined) - { - start = Math.max(0, file.fileSize - end); - end = file.fileSize - 1; - } - - // start and end are inclusive - if (end === undefined || end >= file.fileSize) - end = file.fileSize - 1; - - if (start !== undefined && start >= file.fileSize) { - var HTTP_416 = new HttpError(416, "Requested Range Not Satisfiable"); - HTTP_416.customErrorHandling = function(errorResponse) - { - maybeAddHeaders(file, metadata, errorResponse); - }; - throw HTTP_416; - } - - if (end < start) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - start = 0; - end = file.fileSize - 1; - } - else - { - response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); - var contentRange = "bytes " + start + "-" + end + "/" + file.fileSize; - response.setHeader("Content-Range", contentRange); - } - } - else - { - start = 0; - end = file.fileSize - 1; - } - - // finally... - dumpn("*** handling '" + path + "' as mapping to " + file.path + " from " + - start + " to " + end + " inclusive"); - this._writeFileResponse(metadata, file, response, start, end - start + 1); - }, - - /** -* Writes an HTTP response for the given file, including setting headers for -* file metadata. -* -* @param metadata : Request -* the Request for which a response is being generated -* @param file : nsILocalFile -* the file which is to be sent in the response -* @param response : Response -* the response to which the file should be written -* @param offset: uint -* the byte offset to skip to when writing -* @param count: uint -* the number of bytes to write -*/ - _writeFileResponse: function(metadata, file, response, offset, count) - { - const PR_RDONLY = 0x01; - - var type = this._getTypeFromFile(file); - if (type === SJS_TYPE) - { - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var sis = new ScriptableInputStream(fis); - var s = Cu.Sandbox(gGlobalObject); - s.importFunction(dump, "dump"); - - // Define a basic key-value state-preservation API across requests, with - // keys initially corresponding to the empty string. - var self = this; - var path = metadata.path; - s.importFunction(function getState(k) - { - return self._getState(path, k); - }); - s.importFunction(function setState(k, v) - { - self._setState(path, k, v); - }); - s.importFunction(function getSharedState(k) - { - return self._getSharedState(k); - }); - s.importFunction(function setSharedState(k, v) - { - self._setSharedState(k, v); - }); - s.importFunction(function getObjectState(k, callback) - { - callback(self._getObjectState(k)); - }); - s.importFunction(function setObjectState(k, v) - { - self._setObjectState(k, v); - }); - s.importFunction(function registerPathHandler(p, h) - { - self.registerPathHandler(p, h); - }); - - // Make it possible for sjs files to access their location - this._setState(path, "__LOCATION__", file.path); - - try - { - // Alas, the line number in errors dumped to console when calling the - // request handler is simply an offset from where we load the SJS file. - // Work around this in a reasonably non-fragile way by dynamically - // getting the line number where we evaluate the SJS file. Don't - // separate these two lines! - var line = new Error().lineNumber; - Cu.evalInSandbox(sis.read(file.fileSize), s); - } - catch (e) - { - dumpn("*** syntax error in SJS at " + file.path + ": " + e); - throw HTTP_500; - } - - try - { - s.handleRequest(metadata, response); - } - catch (e) - { - dump("*** error running SJS at " + file.path + ": " + - e + " on line " + - (e instanceof Error - ? e.lineNumber + " in httpd.js" - : (e.lineNumber - line)) + "\n"); - throw HTTP_500; - } - } - finally - { - fis.close(); - } - } - else - { - try - { - response.setHeader("Last-Modified", - toDateString(file.lastModifiedTime), - false); - } - catch (e) { /* lastModifiedTime threw, ignore */ } - - response.setHeader("Content-Type", type, false); - maybeAddHeaders(file, metadata, response); - response.setHeader("Content-Length", "" + count, false); - - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - offset = offset || 0; - count = count || file.fileSize; - NS_ASSERT(offset === 0 || offset < file.fileSize, "bad offset"); - NS_ASSERT(count >= 0, "bad count"); - NS_ASSERT(offset + count <= file.fileSize, "bad total data size"); - - try - { - if (offset !== 0) - { - // Seek (or read, if seeking isn't supported) to the correct offset so - // the data sent to the client matches the requested range. - if (fis instanceof Ci.nsISeekableStream) - fis.seek(Ci.nsISeekableStream.NS_SEEK_SET, offset); - else - new ScriptableInputStream(fis).read(offset); - } - } - catch (e) - { - fis.close(); - throw e; - } - - let writeMore = function writeMore() - { - gThreadManager.currentThread - .dispatch(writeData, Ci.nsIThread.DISPATCH_NORMAL); - } - - var input = new BinaryInputStream(fis); - var output = new BinaryOutputStream(response.bodyOutputStream); - var writeData = - { - run: function() - { - var chunkSize = Math.min(65536, count); - count -= chunkSize; - NS_ASSERT(count >= 0, "underflow"); - - try - { - var data = input.readByteArray(chunkSize); - NS_ASSERT(data.length === chunkSize, - "incorrect data returned? got " + data.length + - ", expected " + chunkSize); - output.writeByteArray(data, data.length); - if (count === 0) - { - fis.close(); - response.finish(); - } - else - { - writeMore(); - } - } - catch (e) - { - try - { - fis.close(); - } - finally - { - response.finish(); - } - throw e; - } - } - }; - - writeMore(); - - // Now that we know copying will start, flag the response as async. - response.processAsync(); - } - }, - - /** -* Get the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getState: function(path, k) - { - var state = this._state; - if (path in state && k in state[path]) - return state[path][k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setState: function(path, k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - var state = this._state; - if (!(path in state)) - state[path] = {}; - state[path][k] = v; - }, - - /** -* Get the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getSharedState: function(k) - { - var state = this._sharedState; - if (k in state) - return state[k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setSharedState: function(k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - this._sharedState[k] = v; - }, - - /** -* Returns the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be returned -* @returns nsISupports -* the corresponding object, or null if none was present -*/ - _getObjectState: function(k) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - return this._objectState[k] || null; - }, - - /** -* Sets the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be set -* @param v : nsISupports -* the object to be associated with the given key; may be null -*/ - _setObjectState: function(k, v) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - if (typeof v !== "object") - throw new Error("non-object value passed"); - if (v && !("QueryInterface" in v)) - { - throw new Error("must pass an nsISupports; use wrappedJSObject to ease " + - "pain when using the server from JS"); - } - - this._objectState[k] = v; - }, - - /** -* Gets a content-type for the given file, first by checking for any custom -* MIME-types registered with this handler for the file's extension, second by -* asking the global MIME service for a content-type, and finally by failing -* over to application/octet-stream. -* -* @param file : nsIFile -* the nsIFile for which to get a file type -* @returns string -* the best content-type which can be determined for the file -*/ - _getTypeFromFile: function(file) - { - try - { - var name = file.leafName; - var dot = name.lastIndexOf("."); - if (dot > 0) - { - var ext = name.slice(dot + 1); - if (ext in this._mimeMappings) - return this._mimeMappings[ext]; - } - return Cc["@mozilla.org/uriloader/external-helper-app-service;1"] - .getService(Ci.nsIMIMEService) - .getTypeFromFile(file); - } - catch (e) - { - return "application/octet-stream"; - } - }, - - /** -* Returns the nsILocalFile which corresponds to the path, as determined using -* all registered path->directory mappings and any paths which are explicitly -* overridden. -* -* @param path : string -* the server path for which a file should be retrieved, e.g. "/foo/bar" -* @throws HttpError -* when the correct action is the corresponding HTTP error (i.e., because no -* mapping was found for a directory in path, the referenced file doesn't -* exist, etc.) -* @returns nsILocalFile -* the file to be sent as the response to a request for the path -*/ - _getFileForPath: function(path) - { - // decode and add underscores as necessary - try - { - path = toInternalPath(path, true); - } - catch (e) - { - throw HTTP_400; // malformed path - } - - // next, get the directory which contains this path - var pathMap = this._pathDirectoryMap; - - // An example progression of tmp for a path "/foo/bar/baz/" might be: - // "foo/bar/baz/", "foo/bar/baz", "foo/bar", "foo", "" - var tmp = path.substring(1); - while (true) - { - // do we have a match for current head of the path? - var file = pathMap.get(tmp); - if (file) - { - // XXX hack; basically disable showing mapping for /foo/bar/ when the - // requested path was /foo/bar, because relative links on the page - // will all be incorrect -- we really need the ability to easily - // redirect here instead - if (tmp == path.substring(1) && - tmp.length != 0 && - tmp.charAt(tmp.length - 1) != "/") - file = null; - else - break; - } - - // if we've finished trying all prefixes, exit - if (tmp == "") - break; - - tmp = tmp.substring(0, tmp.lastIndexOf("/")); - } - - // no mapping applies, so 404 - if (!file) - throw HTTP_404; - - - // last, get the file for the path within the determined directory - var parentFolder = file.parent; - var dirIsRoot = (parentFolder == null); - - // Strategy here is to append components individually, making sure we - // never move above the given directory; this allows paths such as - // "/foo/../bar" but prevents paths such as "/../base-sibling"; - // this component-wise approach also means the code works even on platforms - // which don't use "/" as the directory separator, such as Windows - var leafPath = path.substring(tmp.length + 1); - var comps = leafPath.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - - if (comp == "..") - file = file.parent; - else if (comp == "." || comp == "") - continue; - else - file.append(comp); - - if (!dirIsRoot && file.equals(parentFolder)) - throw HTTP_403; - } - - return file; - }, - - /** -* Writes the error page for the given HTTP error code over the given -* connection. -* -* @param errorCode : uint -* the HTTP error code to be used -* @param connection : Connection -* the connection on which the error occurred -*/ - handleError: function(errorCode, connection) - { - var response = new Response(connection); - - dumpn("*** error in request: " + errorCode); - - this._handleError(errorCode, new Request(connection.port), response); - }, - - /** -* Handles a request which generates the given error code, using the -* user-defined error handler if one has been set, gracefully falling back to -* the x00 status code if the code has no handler, and failing to status code -* 500 if all else fails. -* -* @param errorCode : uint -* the HTTP error which is to be returned -* @param metadata : Request -* metadata for the request, which will often be incomplete since this is an -* error -* @param response : Response -* an uninitialized Response should be initialized when this method -* completes with information which represents the desired error code in the -* ideal case or a fallback code in abnormal circumstances (i.e., 500 is a -* fallback for 505, per HTTP specs) -*/ - _handleError: function(errorCode, metadata, response) - { - if (!metadata) - throw Cr.NS_ERROR_NULL_POINTER; - - var errorX00 = errorCode - (errorCode % 100); - - try - { - if (!(errorCode in HTTP_ERROR_CODES)) - dumpn("*** WARNING: requested invalid error: " + errorCode); - - // RFC 2616 says that we should try to handle an error by its class if we - // can't otherwise handle it -- if that fails, we revert to handling it as - // a 500 internal server error, and if that fails we throw and shut down - // the server - - // actually handle the error - try - { - if (errorCode in this._overrideErrors) - this._overrideErrors[errorCode](metadata, response); - else - this._defaultErrors[errorCode](metadata, response); - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - // don't retry the handler that threw - if (errorX00 == errorCode) - throw HTTP_500; - - dumpn("*** error in handling for error code " + errorCode + ", " + - "falling back to " + errorX00 + "..."); - response = new Response(response._connection); - if (errorX00 in this._overrideErrors) - this._overrideErrors[errorX00](metadata, response); - else if (errorX00 in this._defaultErrors) - this._defaultErrors[errorX00](metadata, response); - else - throw HTTP_500; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(); - return; - } - - // we've tried everything possible for a meaningful error -- now try 500 - dumpn("*** error in handling for error code " + errorX00 + ", falling " + - "back to 500..."); - - try - { - response = new Response(response._connection); - if (500 in this._overrideErrors) - this._overrideErrors[500](metadata, response); - else - this._defaultErrors[500](metadata, response); - } - catch (e2) - { - dumpn("*** multiple errors in default error handlers!"); - dumpn("*** e == " + e + ", e2 == " + e2); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // FIELDS - - /** -* This object contains the default handlers for the various HTTP error codes. -*/ - _defaultErrors: - { - 400: function(metadata, response) - { - // none of the data in metadata is reliable, so hard-code everything here - response.setStatusLine("1.1", 400, "Bad Request"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Bad request\n"; - response.bodyOutputStream.write(body, body.length); - }, - 403: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 403, "Forbidden"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -403 Forbidden\ -\ -

403 Forbidden

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 404: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 404, "Not Found"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -404 Not Found\ -\ -

404 Not Found

\ -

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

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 416: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 416, - "Requested Range Not Satisfiable"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -\ -416 Requested Range Not Satisfiable\ -\ -

416 Requested Range Not Satisfiable

\ -

The byte range was not valid for the\ -requested resource.\ -

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 500: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 500, - "Internal Server Error"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -500 Internal Server Error\ -\ -

500 Internal Server Error

\ -

Something's broken in this server and\ -needs to be fixed.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 501: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 501, "Not Implemented"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -501 Not Implemented\ -\ -

501 Not Implemented

\ -

This server is not (yet) Apache.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 505: function(metadata, response) - { - response.setStatusLine("1.1", 505, "HTTP Version Not Supported"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -505 HTTP Version Not Supported\ -\ -

505 HTTP Version Not Supported

\ -

This server only supports HTTP/1.0 and HTTP/1.1\ -connections.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - } - }, - - /** -* Contains handlers for the default set of URIs contained in this server. -*/ - _defaultPaths: - { - "/": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -httpd.js\ -\ -

httpd.js

\ -

If you're seeing this page, httpd.js is up and\ -serving requests! Now set a base path and serve some\ -files!

\ -\ -"; - - response.bodyOutputStream.write(body, body.length); - }, - - "/trace": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Request-URI: " + - metadata.scheme + "://" + metadata.host + ":" + metadata.port + - metadata.path + "\n\n"; - body += "Request (semantically equivalent, slightly reformatted):\n\n"; - body += metadata.method + " " + metadata.path; - - if (metadata.queryString) - body += "?" + metadata.queryString; - - body += " HTTP/" + metadata.httpVersion + "\r\n"; - - var headEnum = metadata.headers; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - body += fieldName + ": " + metadata.getHeader(fieldName) + "\r\n"; - } - - response.bodyOutputStream.write(body, body.length); - } - } -}; - - -/** -* Maps absolute paths to files on the local file system (as nsILocalFiles). -*/ -function FileMap() -{ - /** Hash which will map paths to nsILocalFiles. */ - this._map = {}; -} -FileMap.prototype = -{ - // PUBLIC API - - /** -* Maps key to a clone of the nsILocalFile value if value is non-null; -* otherwise, removes any extant mapping for key. -* -* @param key : string -* string to which a clone of value is mapped -* @param value : nsILocalFile -* the file to map to key, or null to remove a mapping -*/ - put: function(key, value) - { - if (value) - this._map[key] = value.clone(); - else - delete this._map[key]; - }, - - /** -* Returns a clone of the nsILocalFile mapped to key, or null if no such -* mapping exists. -* -* @param key : string -* key to which the returned file maps -* @returns nsILocalFile -* a clone of the mapped file, or null if no mapping exists -*/ - get: function(key) - { - var val = this._map[key]; - return val ? val.clone() : null; - } -}; - - -// Response CONSTANTS - -// token = * -// CHAR = -// CTL = -// separators = "(" | ")" | "<" | ">" | "@" -// | "," | ";" | ":" | "\" | <"> -// | "/" | "[" | "]" | "?" | "=" -// | "{" | "}" | SP | HT -const IS_TOKEN_ARRAY = - [0, 0, 0, 0, 0, 0, 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 0, 0, 0, 0, 0, 0, 0, 0, // 24 - - 0, 1, 0, 1, 1, 1, 1, 1, // 32 - 0, 0, 1, 1, 0, 1, 1, 0, // 40 - 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 1, 1, 0, 0, 0, 0, 0, 0, // 56 - - 0, 1, 1, 1, 1, 1, 1, 1, // 64 - 1, 1, 1, 1, 1, 1, 1, 1, // 72 - 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 1, 1, 1, 0, 0, 0, 1, 1, // 88 - - 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 1, 1, 1, 1, 1, 1, 1, 1, // 104 - 1, 1, 1, 1, 1, 1, 1, 1, // 112 - 1, 1, 1, 0, 1, 0, 1]; // 120 - - -/** -* Determines whether the given character code is a CTL. -* -* @param code : uint -* the character code -* @returns boolean -* true if code is a CTL, false otherwise -*/ -function isCTL(code) -{ - return (code >= 0 && code <= 31) || (code == 127); -} - -/** -* Represents a response to an HTTP request, encapsulating all details of that -* response. This includes all headers, the HTTP version, status code and -* explanation, and the entity itself. -* -* @param connection : Connection -* the connection over which this response is to be written -*/ -function Response(connection) -{ - /** The connection over which this response will be written. */ - this._connection = connection; - - /** -* The HTTP version of this response; defaults to 1.1 if not set by the -* handler. -*/ - this._httpVersion = nsHttpVersion.HTTP_1_1; - - /** -* The HTTP code of this response; defaults to 200. -*/ - this._httpCode = 200; - - /** -* The description of the HTTP code in this response; defaults to "OK". -*/ - this._httpDescription = "OK"; - - /** -* An nsIHttpHeaders object in which the headers in this response should be -* stored. This property is null after the status line and headers have been -* written to the network, and it may be modified up until it is cleared, -* except if this._finished is set first (in which case headers are written -* asynchronously in response to a finish() call not preceded by -* flushHeaders()). -*/ - this._headers = new nsHttpHeaders(); - - /** -* Set to true when this response is ended (completely constructed if possible -* and the connection closed); further actions on this will then fail. -*/ - this._ended = false; - - /** -* A stream used to hold data written to the body of this response. -*/ - this._bodyOutputStream = null; - - /** -* A stream containing all data that has been written to the body of this -* response so far. (Async handlers make the data contained in this -* unreliable as a way of determining content length in general, but auxiliary -* saved information can sometimes be used to guarantee reliability.) -*/ - this._bodyInputStream = null; - - /** -* A stream copier which copies data to the network. It is initially null -* until replaced with a copier for response headers; when headers have been -* fully sent it is replaced with a copier for the response body, remaining -* so for the duration of response processing. -*/ - this._asyncCopier = null; - - /** -* True if this response has been designated as being processed -* asynchronously rather than for the duration of a single call to -* nsIHttpRequestHandler.handle. -*/ - this._processAsync = false; - - /** -* True iff finish() has been called on this, signaling that no more changes -* to this may be made. -*/ - this._finished = false; - - /** -* True iff powerSeized() has been called on this, signaling that this -* response is to be handled manually by the response handler (which may then -* send arbitrary data in response, even non-HTTP responses). -*/ - this._powerSeized = false; -} -Response.prototype = -{ - // PUBLIC CONSTRUCTION API - - // - // see nsIHttpResponse.bodyOutputStream - // - get bodyOutputStream() - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - if (!this._bodyOutputStream) - { - var pipe = new Pipe(true, false, Response.SEGMENT_SIZE, PR_UINT32_MAX, - null); - this._bodyOutputStream = pipe.outputStream; - this._bodyInputStream = pipe.inputStream; - if (this._processAsync || this._powerSeized) - this._startAsyncProcessor(); - } - - return this._bodyOutputStream; - }, - - // - // see nsIHttpResponse.write - // - write: function(data) - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - var dataAsString = String(data); - this.bodyOutputStream.write(dataAsString, dataAsString.length); - }, - - // - // see nsIHttpResponse.setStatusLine - // - setStatusLine: function(httpVersion, code, description) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - if (!(code >= 0 && code < 1000)) - throw Cr.NS_ERROR_INVALID_ARG; - - try - { - var httpVer; - // avoid version construction for the most common cases - if (!httpVersion || httpVersion == "1.1") - httpVer = nsHttpVersion.HTTP_1_1; - else if (httpVersion == "1.0") - httpVer = nsHttpVersion.HTTP_1_0; - else - httpVer = new nsHttpVersion(httpVersion); - } - catch (e) - { - throw Cr.NS_ERROR_INVALID_ARG; - } - - // Reason-Phrase = * - // TEXT = - // - // XXX this ends up disallowing octets which aren't Unicode, I think -- not - // much to do if description is IDL'd as string - if (!description) - description = ""; - for (var i = 0; i < description.length; i++) - if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t") - throw Cr.NS_ERROR_INVALID_ARG; - - // set the values only after validation to preserve atomicity - this._httpDescription = description; - this._httpCode = code; - this._httpVersion = httpVer; - }, - - // - // see nsIHttpResponse.setHeader - // - setHeader: function(name, value, merge) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - this._headers.setHeader(name, value, merge); - }, - - // - // see nsIHttpResponse.processAsync - // - processAsync: function() - { - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._processAsync) - return; - this._ensureAlive(); - - dumpn("*** processing connection " + this._connection.number + " async"); - this._processAsync = true; - - /* -* Either the bodyOutputStream getter or this method is responsible for -* starting the asynchronous processor and catching writes of data to the -* response body of async responses as they happen, for the purpose of -* forwarding those writes to the actual connection's output stream. -* If bodyOutputStream is accessed first, calling this method will create -* the processor (when it first is clear that body data is to be written -* immediately, not buffered). If this method is called first, accessing -* bodyOutputStream will create the processor. If only this method is -* called, we'll write nothing, neither headers nor the nonexistent body, -* until finish() is called. Since that delay is easily avoided by simply -* getting bodyOutputStream or calling write(""), we don't worry about it. -*/ - if (this._bodyOutputStream && !this._asyncCopier) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.seizePower - // - seizePower: function() - { - if (this._processAsync) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - return; - this._ensureAlive(); - - dumpn("*** forcefully seizing power over connection " + - this._connection.number + "..."); - - // Purge any already-written data without sending it. We could as easily - // swap out the streams entirely, but that makes it possible to acquire and - // unknowingly use a stale reference, so we require there only be one of - // each stream ever for any response to avoid this complication. - if (this._asyncCopier) - this._asyncCopier.cancel(Cr.NS_BINDING_ABORTED); - this._asyncCopier = null; - if (this._bodyOutputStream) - { - var input = new BinaryInputStream(this._bodyInputStream); - var avail; - while ((avail = input.available()) > 0) - input.readByteArray(avail); - } - - this._powerSeized = true; - if (this._bodyOutputStream) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.finish - // - finish: function() - { - if (!this._processAsync && !this._powerSeized) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._finished) - return; - - dumpn("*** finishing connection " + this._connection.number); - this._startAsyncProcessor(); // in case bodyOutputStream was never accessed - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - this._finished = true; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpResponse) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // POST-CONSTRUCTION API (not exposed externally) - - /** -* The HTTP version number of this, as a string (e.g. "1.1"). -*/ - get httpVersion() - { - this._ensureAlive(); - return this._httpVersion.toString(); - }, - - /** -* The HTTP status code of this response, as a string of three characters per -* RFC 2616. -*/ - get httpCode() - { - this._ensureAlive(); - - var codeString = (this._httpCode < 10 ? "0" : "") + - (this._httpCode < 100 ? "0" : "") + - this._httpCode; - return codeString; - }, - - /** -* The description of the HTTP status code of this response, or "" if none is -* set. -*/ - get httpDescription() - { - this._ensureAlive(); - - return this._httpDescription; - }, - - /** -* The headers in this response, as an nsHttpHeaders object. -*/ - get headers() - { - this._ensureAlive(); - - return this._headers; - }, - - // - // see nsHttpHeaders.getHeader - // - getHeader: function(name) - { - this._ensureAlive(); - - return this._headers.getHeader(name); - }, - - /** -* Determines whether this response may be abandoned in favor of a newly -* constructed response. A response may be abandoned only if it is not being -* sent asynchronously and if raw control over it has not been taken from the -* server. -* -* @returns boolean -* true iff no data has been written to the network -*/ - partiallySent: function() - { - dumpn("*** partiallySent()"); - return this._processAsync || this._powerSeized; - }, - - /** -* If necessary, kicks off the remaining request processing needed to be done -* after a request handler performs its initial work upon this response. -*/ - complete: function() - { - dumpn("*** complete()"); - if (this._processAsync || this._powerSeized) - { - NS_ASSERT(this._processAsync ^ this._powerSeized, - "can't both send async and relinquish power"); - return; - } - - NS_ASSERT(!this.partiallySent(), "completing a partially-sent response?"); - - this._startAsyncProcessor(); - - // Now make sure we finish processing this request! - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - }, - - /** -* Abruptly ends processing of this response, usually due to an error in an -* incoming request but potentially due to a bad error handler. Since we -* cannot handle the error in the usual way (giving an HTTP error page in -* response) because data may already have been sent (or because the response -* might be expected to have been generated asynchronously or completely from -* scratch by the handler), we stop processing this response and abruptly -* close the connection. -* -* @param e : Error -* the exception which precipitated this abort, or null if no such exception -* was generated -*/ - abort: function(e) - { - dumpn("*** abort(<" + e + ">)"); - - // This response will be ended by the processor if one was created. - var copier = this._asyncCopier; - if (copier) - { - // We dispatch asynchronously here so that any pending writes of data to - // the connection will be deterministically written. This makes it easier - // to specify exact behavior, and it makes observable behavior more - // predictable for clients. Note that the correctness of this depends on - // callbacks in response to _waitToReadData in WriteThroughCopier - // happening asynchronously with respect to the actual writing of data to - // bodyOutputStream, as they currently do; if they happened synchronously, - // an event which ran before this one could write more data to the - // response body before we get around to canceling the copier. We have - // tests for this in test_seizepower.js, however, and I can't think of a - // way to handle both cases without removing bodyOutputStream access and - // moving its effective write(data, length) method onto Response, which - // would be slower and require more code than this anyway. - gThreadManager.currentThread.dispatch({ - run: function() - { - dumpn("*** canceling copy asynchronously..."); - copier.cancel(Cr.NS_ERROR_UNEXPECTED); - } - }, Ci.nsIThread.DISPATCH_NORMAL); - } - else - { - this.end(); - } - }, - - /** -* Closes this response's network connection, marks the response as finished, -* and notifies the server handler that the request is done being processed. -*/ - end: function() - { - NS_ASSERT(!this._ended, "ending this response twice?!?!"); - - this._connection.close(); - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - - this._finished = true; - this._ended = true; - }, - - // PRIVATE IMPLEMENTATION - - /** -* Sends the status line and headers of this response if they haven't been -* sent and initiates the process of copying data written to this response's -* body to the network. -*/ - _startAsyncProcessor: function() - { - dumpn("*** _startAsyncProcessor()"); - - // Handle cases where we're being called a second time. The former case - // happens when this is triggered both by complete() and by processAsync(), - // while the latter happens when processAsync() in conjunction with sent - // data causes abort() to be called. - if (this._asyncCopier || this._ended) - { - dumpn("*** ignoring second call to _startAsyncProcessor"); - return; - } - - // Send headers if they haven't been sent already and should be sent, then - // asynchronously continue to send the body. - if (this._headers && !this._powerSeized) - { - this._sendHeaders(); - return; - } - - this._headers = null; - this._sendBody(); - }, - - /** -* Signals that all modifications to the response status line and headers are -* complete and then sends that data over the network to the client. Once -* this method completes, a different response to the request that resulted -* in this response cannot be sent -- the only possible action in case of -* error is to abort the response and close the connection. -*/ - _sendHeaders: function() - { - dumpn("*** _sendHeaders()"); - - NS_ASSERT(this._headers); - NS_ASSERT(!this._powerSeized); - - // request-line - var statusLine = "HTTP/" + this.httpVersion + " " + - this.httpCode + " " + - this.httpDescription + "\r\n"; - - // header post-processing - - var headers = this._headers; - headers.setHeader("Connection", "close", false); - headers.setHeader("Server", "httpd.js", false); - if (!headers.hasHeader("Date")) - headers.setHeader("Date", toDateString(Date.now()), false); - - // Any response not being processed asynchronously must have an associated - // Content-Length header for reasons of backwards compatibility with the - // initial server, which fully buffered every response before sending it. - // Beyond that, however, it's good to do this anyway because otherwise it's - // impossible to test behaviors that depend on the presence or absence of a - // Content-Length header. - if (!this._processAsync) - { - dumpn("*** non-async response, set Content-Length"); - - var bodyStream = this._bodyInputStream; - var avail = bodyStream ? bodyStream.available() : 0; - - // XXX assumes stream will always report the full amount of data available - headers.setHeader("Content-Length", "" + avail, false); - } - - - // construct and send response - dumpn("*** header post-processing completed, sending response head..."); - - // request-line - var preambleData = [statusLine]; - - // headers - var headEnum = headers.enumerator; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - var values = headers.getHeaderValues(fieldName); - for (var i = 0, sz = values.length; i < sz; i++) - preambleData.push(fieldName + ": " + values[i] + "\r\n"); - } - - // end request-line/headers - preambleData.push("\r\n"); - - var preamble = preambleData.join(""); - - var responseHeadPipe = new Pipe(true, false, 0, PR_UINT32_MAX, null); - responseHeadPipe.outputStream.write(preamble, preamble.length); - - var response = this; - var copyObserver = - { - onStartRequest: function(request, cx) - { - dumpn("*** preamble copying started"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** preamble copying complete " + - "[status=0x" + statusCode.toString(16) + "]"); - - if (!components.isSuccessCode(statusCode)) - { - dumpn("!!! header copying problems: non-success statusCode, " + - "ending response"); - - response.end(); - } - else - { - response._sendBody(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - var headerCopier = this._asyncCopier = - new WriteThroughCopier(responseHeadPipe.inputStream, - this._connection.output, - copyObserver, null); - - responseHeadPipe.outputStream.close(); - - // Forbid setting any more headers or modifying the request line. - this._headers = null; - }, - - /** -* Asynchronously writes the body of the response (or the entire response, if -* seizePower() has been called) to the network. -*/ - _sendBody: function() - { - dumpn("*** _sendBody"); - - NS_ASSERT(!this._headers, "still have headers around but sending body?"); - - // If no body data was written, we're done - if (!this._bodyInputStream) - { - dumpn("*** empty body, response finished"); - this.end(); - return; - } - - var response = this; - var copyObserver = - { - onStartRequest: function(request, context) - { - dumpn("*** onStartRequest"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** onStopRequest [status=0x" + statusCode.toString(16) + "]"); - - if (statusCode === Cr.NS_BINDING_ABORTED) - { - dumpn("*** terminating copy observer without ending the response"); - } - else - { - if (!components.isSuccessCode(statusCode)) - dumpn("*** WARNING: non-success statusCode in onStopRequest"); - - response.end(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - dumpn("*** starting async copier of body data..."); - this._asyncCopier = - new WriteThroughCopier(this._bodyInputStream, this._connection.output, - copyObserver, null); - }, - - /** Ensures that this hasn't been ended. */ - _ensureAlive: function() - { - NS_ASSERT(!this._ended, "not handling response lifetime correctly"); - } -}; - -/** -* Size of the segments in the buffer used in storing response data and writing -* it to the socket. -*/ -Response.SEGMENT_SIZE = 8192; - -/** Serves double duty in WriteThroughCopier implementation. */ -function notImplemented() -{ - throw Cr.NS_ERROR_NOT_IMPLEMENTED; -} - -/** Returns true iff the given exception represents stream closure. */ -function streamClosed(e) -{ - return e === Cr.NS_BASE_STREAM_CLOSED || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_CLOSED); -} - -/** Returns true iff the given exception represents a blocked stream. */ -function wouldBlock(e) -{ - return e === Cr.NS_BASE_STREAM_WOULD_BLOCK || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_WOULD_BLOCK); -} - -/** -* Copies data from source to sink as it becomes available, when that data can -* be written to sink without blocking. -* -* @param source : nsIAsyncInputStream -* the stream from which data is to be read -* @param sink : nsIAsyncOutputStream -* the stream to which data is to be copied -* @param observer : nsIRequestObserver -* an observer which will be notified when the copy starts and finishes -* @param context : nsISupports -* context passed to observer when notified of start/stop -* @throws NS_ERROR_NULL_POINTER -* if source, sink, or observer are null -*/ -function WriteThroughCopier(source, sink, observer, context) -{ - if (!source || !sink || !observer) - throw Cr.NS_ERROR_NULL_POINTER; - - /** Stream from which data is being read. */ - this._source = source; - - /** Stream to which data is being written. */ - this._sink = sink; - - /** Observer watching this copy. */ - this._observer = observer; - - /** Context for the observer watching this. */ - this._context = context; - - /** -* True iff this is currently being canceled (cancel has been called, the -* callback may not yet have been made). -*/ - this._canceled = false; - - /** -* False until all data has been read from input and written to output, at -* which point this copy is completed and cancel() is asynchronously called. -*/ - this._completed = false; - - /** Required by nsIRequest, meaningless. */ - this.loadFlags = 0; - /** Required by nsIRequest, meaningless. */ - this.loadGroup = null; - /** Required by nsIRequest, meaningless. */ - this.name = "response-body-copy"; - - /** Status of this request. */ - this.status = Cr.NS_OK; - - /** Arrays of byte strings waiting to be written to output. */ - this._pendingData = []; - - // start copying - try - { - observer.onStartRequest(this, context); - this._waitToReadData(); - this._waitForSinkClosure(); - } - catch (e) - { - dumpn("!!! error starting copy: " + e + - ("lineNumber" in e ? ", line " + e.lineNumber : "")); - dumpn(e.stack); - this.cancel(Cr.NS_ERROR_UNEXPECTED); - } -} -WriteThroughCopier.prototype = -{ - /* nsISupports implementation */ - - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIInputStreamCallback) || - iid.equals(Ci.nsIOutputStreamCallback) || - iid.equals(Ci.nsIRequest) || - iid.equals(Ci.nsISupports)) - { - return this; - } - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NSIINPUTSTREAMCALLBACK - - /** -* Receives a more-data-in-input notification and writes the corresponding -* data to the output. -* -* @param input : nsIAsyncInputStream -* the input stream on whose data we have been waiting -*/ - onInputStreamReady: function(input) - { - if (this._source === null) - return; - - dumpn("*** onInputStreamReady"); - - // - // Ordinarily we'll read a non-zero amount of data from input, queue it up - // to be written and then wait for further callbacks. The complications in - // this method are the cases where we deviate from that behavior when errors - // occur or when copying is drawing to a finish. - // - // The edge cases when reading data are: - // - // Zero data is read - // If zero data was read, we're at the end of available data, so we can - // should stop reading and move on to writing out what we have (or, if - // we've already done that, onto notifying of completion). - // A stream-closed exception is thrown - // This is effectively a less kind version of zero data being read; the - // only difference is that we notify of completion with that result - // rather than with NS_OK. - // Some other exception is thrown - // This is the least kind result. We don't know what happened, so we - // act as though the stream closed except that we notify of completion - // with the result NS_ERROR_UNEXPECTED. - // - - var bytesWanted = 0, bytesConsumed = -1; - try - { - input = new BinaryInputStream(input); - - bytesWanted = Math.min(input.available(), Response.SEGMENT_SIZE); - dumpn("*** input wanted: " + bytesWanted); - - if (bytesWanted > 0) - { - var data = input.readByteArray(bytesWanted); - bytesConsumed = data.length; - this._pendingData.push(String.fromCharCode.apply(String, data)); - } - - dumpn("*** " + bytesConsumed + " bytes read"); - - // Handle the zero-data edge case in the same place as all other edge - // cases are handled. - if (bytesWanted === 0) - throw Cr.NS_BASE_STREAM_CLOSED; - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** input stream closed"); - e = bytesWanted === 0 ? Cr.NS_OK : Cr.NS_ERROR_UNEXPECTED; - } - else - { - dumpn("!!! unexpected error reading from input, canceling: " + e); - e = Cr.NS_ERROR_UNEXPECTED; - } - - this._doneReadingSource(e); - return; - } - - var pendingData = this._pendingData; - - NS_ASSERT(bytesConsumed > 0); - NS_ASSERT(pendingData.length > 0, "no pending data somehow?"); - NS_ASSERT(pendingData[pendingData.length - 1].length > 0, - "buffered zero bytes of data?"); - - NS_ASSERT(this._source !== null); - - // Reading has gone great, and we've gotten data to write now. What if we - // don't have a place to write that data, because output went away just - // before this read? Drop everything on the floor, including new data, and - // cancel at this point. - if (this._sink === null) - { - pendingData.length = 0; - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we've read the data, and we know we have a place to write it. We - // need to queue up the data to be written, but *only* if none is queued - // already -- if data's already queued, the code that actually writes the - // data will make sure to wait on unconsumed pending data. - try - { - if (pendingData.length === 1) - this._waitToWriteData(); - } - catch (e) - { - dumpn("!!! error waiting to write data just read, swallowing and " + - "writing only what we already have: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Whee! We successfully read some data, and it's successfully queued up to - // be written. All that remains now is to wait for more data to read. - try - { - this._waitToReadData(); - } - catch (e) - { - dumpn("!!! error waiting to read more data: " + e); - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - } - }, - - - // NSIOUTPUTSTREAMCALLBACK - - /** -* Callback when data may be written to the output stream without blocking, or -* when the output stream has been closed. -* -* @param output : nsIAsyncOutputStream -* the output stream on whose writability we've been waiting, also known as -* this._sink -*/ - onOutputStreamReady: function(output) - { - if (this._sink === null) - return; - - dumpn("*** onOutputStreamReady"); - - var pendingData = this._pendingData; - if (pendingData.length === 0) - { - // There's no pending data to write. The only way this can happen is if - // we're waiting on the output stream's closure, so we can respond to a - // copying failure as quickly as possible (rather than waiting for data to - // be available to read and then fail to be copied). Therefore, we must - // be done now -- don't bother to attempt to write anything and wrap - // things up. - dumpn("!!! output stream closed prematurely, ending copy"); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - - NS_ASSERT(pendingData[0].length > 0, "queued up an empty quantum?"); - - // - // Write out the first pending quantum of data. The possible errors here - // are: - // - // The write might fail because we can't write that much data - // Okay, we've written what we can now, so re-queue what's left and - // finish writing it out later. - // The write failed because the stream was closed - // Discard pending data that we can no longer write, stop reading, and - // signal that copying finished. - // Some other error occurred. - // Same as if the stream were closed, but notify with the status - // NS_ERROR_UNEXPECTED so the observer knows something was wonky. - // - - try - { - var quantum = pendingData[0]; - - // XXX |quantum| isn't guaranteed to be ASCII, so we're relying on - // undefined behavior! We're only using this because writeByteArray - // is unusably broken for asynchronous output streams; see bug 532834 - // for details. - var bytesWritten = output.write(quantum, quantum.length); - if (bytesWritten === quantum.length) - pendingData.shift(); - else - pendingData[0] = quantum.substring(bytesWritten); - - dumpn("*** wrote " + bytesWritten + " bytes of data"); - } - catch (e) - { - if (wouldBlock(e)) - { - NS_ASSERT(pendingData.length > 0, - "stream-blocking exception with no data to write?"); - NS_ASSERT(pendingData[0].length > 0, - "stream-blocking exception with empty quantum?"); - this._waitToWriteData(); - return; - } - - if (streamClosed(e)) - dumpn("!!! output stream prematurely closed, signaling error..."); - else - dumpn("!!! unknown error: " + e + ", quantum=" + quantum); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // The day is ours! Quantum written, now let's see if we have more data - // still to write. - try - { - if (pendingData.length > 0) - { - this._waitToWriteData(); - return; - } - } - catch (e) - { - dumpn("!!! unexpected error waiting to write pending data: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we have no more pending data to write -- but might we get more in - // the future? - if (this._source !== null) - { - /* -* If we might, then wait for the output stream to be closed. (We wait -* only for closure because we have no data to write -- and if we waited -* for a specific amount of data, we would get repeatedly notified for no -* reason if over time the output stream permitted more and more data to -* be written to it without blocking.) -*/ - this._waitForSinkClosure(); - } - else - { - /* -* On the other hand, if we can't have more data because the input -* stream's gone away, then it's time to notify of copy completion. -* Victory! -*/ - this._sink = null; - this._cancelOrDispatchCancelCallback(Cr.NS_OK); - } - }, - - - // NSIREQUEST - - /** Returns true if the cancel observer hasn't been notified yet. */ - isPending: function() - { - return !this._completed; - }, - - /** Not implemented, don't use! */ - suspend: notImplemented, - /** Not implemented, don't use! */ - resume: notImplemented, - - /** -* Cancels data reading from input, asynchronously writes out any pending -* data, and causes the observer to be notified with the given error code when -* all writing has finished. -* -* @param status : nsresult -* the status to pass to the observer when data copying has been canceled -*/ - cancel: function(status) - { - dumpn("*** cancel(" + status.toString(16) + ")"); - - if (this._canceled) - { - dumpn("*** suppressing a late cancel"); - return; - } - - this._canceled = true; - this.status = status; - - // We could be in the middle of absolutely anything at this point. Both - // input and output might still be around, we might have pending data to - // write, and in general we know nothing about the state of the world. We - // therefore must assume everything's in progress and take everything to its - // final steady state (or so far as it can go before we need to finish - // writing out remaining data). - - this._doneReadingSource(status); - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Stop reading input if we haven't already done so, passing e as the status -* when closing the stream, and kick off a copy-completion notice if no more -* data remains to be written. -* -* @param e : nsresult -* the status to be used when closing the input stream -*/ - _doneReadingSource: function(e) - { - dumpn("*** _doneReadingSource(0x" + e.toString(16) + ")"); - - this._finishSource(e); - if (this._pendingData.length === 0) - this._sink = null; - else - NS_ASSERT(this._sink !== null, "null output?"); - - // If we've written out all data read up to this point, then it's time to - // signal completion. - if (this._sink === null) - { - NS_ASSERT(this._pendingData.length === 0, "pending data still?"); - this._cancelOrDispatchCancelCallback(e); - } - }, - - /** -* Stop writing output if we haven't already done so, discard any data that -* remained to be sent, close off input if it wasn't already closed, and kick -* off a copy-completion notice. -* -* @param e : nsresult -* the status to be used when closing input if it wasn't already closed -*/ - _doneWritingToSink: function(e) - { - dumpn("*** _doneWritingToSink(0x" + e.toString(16) + ")"); - - this._pendingData.length = 0; - this._sink = null; - this._doneReadingSource(e); - }, - - /** -* Completes processing of this copy: either by canceling the copy if it -* hasn't already been canceled using the provided status, or by dispatching -* the cancel callback event (with the originally provided status, of course) -* if it already has been canceled. -* -* @param status : nsresult -* the status code to use to cancel this, if this hasn't already been -* canceled -*/ - _cancelOrDispatchCancelCallback: function(status) - { - dumpn("*** _cancelOrDispatchCancelCallback(" + status + ")"); - - NS_ASSERT(this._source === null, "should have finished input"); - NS_ASSERT(this._sink === null, "should have finished output"); - NS_ASSERT(this._pendingData.length === 0, "should have no pending data"); - - if (!this._canceled) - { - this.cancel(status); - return; - } - - var self = this; - var event = - { - run: function() - { - dumpn("*** onStopRequest async callback"); - - self._completed = true; - try - { - self._observer.onStopRequest(self, self._context, self.status); - } - catch (e) - { - NS_ASSERT(false, - "how are we throwing an exception here? we control " + - "all the callers! " + e); - } - } - }; - - gThreadManager.currentThread.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); - }, - - /** -* Kicks off another wait for more data to be available from the input stream. -*/ - _waitToReadData: function() - { - dumpn("*** _waitToReadData"); - this._source.asyncWait(this, 0, Response.SEGMENT_SIZE, - gThreadManager.mainThread); - }, - - /** -* Kicks off another wait until data can be written to the output stream. -*/ - _waitToWriteData: function() - { - dumpn("*** _waitToWriteData"); - - var pendingData = this._pendingData; - NS_ASSERT(pendingData.length > 0, "no pending data to write?"); - NS_ASSERT(pendingData[0].length > 0, "buffered an empty write?"); - - this._sink.asyncWait(this, 0, pendingData[0].length, - gThreadManager.mainThread); - }, - - /** -* Kicks off a wait for the sink to which data is being copied to be closed. -* We wait for stream closure when we don't have any data to be copied, rather -* than waiting to write a specific amount of data. We can't wait to write -* data because the sink might be infinitely writable, and if no data appears -* in the source for a long time we might have to spin quite a bit waiting to -* write, waiting to write again, &c. Waiting on stream closure instead means -* we'll get just one notification if the sink dies. Note that when data -* starts arriving from the sink we'll resume waiting for data to be written, -* dropping this closure-only callback entirely. -*/ - _waitForSinkClosure: function() - { - dumpn("*** _waitForSinkClosure"); - - this._sink.asyncWait(this, Ci.nsIAsyncOutputStream.WAIT_CLOSURE_ONLY, 0, - gThreadManager.mainThread); - }, - - /** -* Closes input with the given status, if it hasn't already been closed; -* otherwise a no-op. -* -* @param status : nsresult -* status code use to close the source stream if necessary -*/ - _finishSource: function(status) - { - dumpn("*** _finishSource(" + status.toString(16) + ")"); - - if (this._source !== null) - { - this._source.closeWithStatus(status); - this._source = null; - } - } -}; - - -/** -* A container for utility functions used with HTTP headers. -*/ -const headerUtils = -{ - /** -* Normalizes fieldName (by converting it to lowercase) and ensures it is a -* valid header field name (although not necessarily one specified in RFC -* 2616). -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not match the field-name production in RFC 2616 -* @returns string -* fieldName converted to lowercase if it is a valid header, for characters -* where case conversion is possible -*/ - normalizeFieldName: function(fieldName) - { - if (fieldName == "") - throw Cr.NS_ERROR_INVALID_ARG; - - for (var i = 0, sz = fieldName.length; i < sz; i++) - { - if (!IS_TOKEN_ARRAY[fieldName.charCodeAt(i)]) - { - dumpn(fieldName + " is not a valid header field name!"); - throw Cr.NS_ERROR_INVALID_ARG; - } - } - - return fieldName.toLowerCase(); - }, - - /** -* Ensures that fieldValue is a valid header field value (although not -* necessarily as specified in RFC 2616 if the corresponding field name is -* part of the HTTP protocol), normalizes the value if it is, and -* returns the normalized value. -* -* @param fieldValue : string -* a value to be normalized as an HTTP header field value -* @throws NS_ERROR_INVALID_ARG -* if fieldValue does not match the field-value production in RFC 2616 -* @returns string -* fieldValue as a normalized HTTP header field value -*/ - normalizeFieldValue: function(fieldValue) - { - // field-value = *( field-content | LWS ) - // field-content = - // TEXT = - // LWS = [CRLF] 1*( SP | HT ) - // - // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - // qdtext = > - // quoted-pair = "\" CHAR - // CHAR = - - // Any LWS that occurs between field-content MAY be replaced with a single - // SP before interpreting the field value or forwarding the message - // downstream (section 4.2); we replace 1*LWS with a single SP - var val = fieldValue.replace(/(?:(?:\r\n)?[ \t]+)+/g, " "); - - // remove leading/trailing LWS (which has been converted to SP) - val = val.replace(/^ +/, "").replace(/ +$/, ""); - - // that should have taken care of all CTLs, so val should contain no CTLs - for (var i = 0, len = val.length; i < len; i++) - if (isCTL(val.charCodeAt(i))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX disallows quoted-pair where CHAR is a CTL -- will not invalidly - // normalize, however, so this can be construed as a tightening of the - // spec and not entirely as a bug - return val; - } -}; - - - -/** -* Converts the given string into a string which is safe for use in an HTML -* context. -* -* @param str : string -* the string to make HTML-safe -* @returns string -* an HTML-safe version of str -*/ -function htmlEscape(str) -{ - // this is naive, but it'll work - var s = ""; - for (var i = 0; i < str.length; i++) - s += "&#" + str.charCodeAt(i) + ";"; - return s; -} - - -/** -* Constructs an object representing an HTTP version (see section 3.1). -* -* @param versionString -* a string of the form "#.#", where # is an non-negative decimal integer with -* or without leading zeros -* @throws -* if versionString does not specify a valid HTTP version number -*/ -function nsHttpVersion(versionString) -{ - var matches = /^(\d+)\.(\d+)$/.exec(versionString); - if (!matches) - throw "Not a valid HTTP version!"; - - /** The major version number of this, as a number. */ - this.major = parseInt(matches[1], 10); - - /** The minor version number of this, as a number. */ - this.minor = parseInt(matches[2], 10); - - if (isNaN(this.major) || isNaN(this.minor) || - this.major < 0 || this.minor < 0) - throw "Not a valid HTTP version!"; -} -nsHttpVersion.prototype = -{ - /** -* Returns the standard string representation of the HTTP version represented -* by this (e.g., "1.1"). -*/ - toString: function () - { - return this.major + "." + this.minor; - }, - - /** -* Returns true if this represents the same HTTP version as otherVersion, -* false otherwise. -* -* @param otherVersion : nsHttpVersion -* the version to compare against this -*/ - equals: function (otherVersion) - { - return this.major == otherVersion.major && - this.minor == otherVersion.minor; - }, - - /** True if this >= otherVersion, false otherwise. */ - atLeast: function(otherVersion) - { - return this.major > otherVersion.major || - (this.major == otherVersion.major && - this.minor >= otherVersion.minor); - } -}; - -nsHttpVersion.HTTP_1_0 = new nsHttpVersion("1.0"); -nsHttpVersion.HTTP_1_1 = new nsHttpVersion("1.1"); - - -/** -* An object which stores HTTP headers for a request or response. -* -* Note that since headers are case-insensitive, this object converts headers to -* lowercase before storing them. This allows the getHeader and hasHeader -* methods to work correctly for any case of a header, but it means that the -* values returned by .enumerator may not be equal case-sensitively to the -* values passed to setHeader when adding headers to this. -*/ -function nsHttpHeaders() -{ - /** -* A hash of headers, with header field names as the keys and header field -* values as the values. Header field names are case-insensitive, but upon -* insertion here they are converted to lowercase. Header field values are -* normalized upon insertion to contain no leading or trailing whitespace. -* -* Note also that per RFC 2616, section 4.2, two headers with the same name in -* a message may be treated as one header with the same field name and a field -* value consisting of the separate field values joined together with a "," in -* their original order. This hash stores multiple headers with the same name -* in this manner. -*/ - this._headers = {}; -} -nsHttpHeaders.prototype = -{ - /** -* Sets the header represented by name and value in this. -* -* @param name : string -* the header name -* @param value : string -* the header value -* @throws NS_ERROR_INVALID_ARG -* if name or value is not a valid header component -*/ - setHeader: function(fieldName, fieldValue, merge) - { - var name = headerUtils.normalizeFieldName(fieldName); - var value = headerUtils.normalizeFieldValue(fieldValue); - - // The following three headers are stored as arrays because their real-world - // syntax prevents joining individual headers into a single header using - // ",". See also - if (merge && name in this._headers) - { - if (name === "www-authenticate" || - name === "proxy-authenticate" || - name === "set-cookie") - { - this._headers[name].push(value); - } - else - { - this._headers[name][0] += "," + value; - NS_ASSERT(this._headers[name].length === 1, - "how'd a non-special header have multiple values?") - } - } - else - { - this._headers[name] = [value]; - } - }, - - /** -* Returns the value for the header specified by this. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns string -* the field value for the given header, possibly with non-semantic changes -* (i.e., leading/trailing whitespace stripped, whitespace runs replaced -* with spaces, etc.) at the option of the implementation; multiple -* instances of the header will be combined with a comma, except for -* the three headers noted in the description of getHeaderValues -*/ - getHeader: function(fieldName) - { - return this.getHeaderValues(fieldName).join("\n"); - }, - - /** -* Returns the value for the header specified by fieldName as an array. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns [string] -* an array of all the header values in this for the given -* header name. Header values will generally be collapsed -* into a single header by joining all header values together -* with commas, but certain headers (Proxy-Authenticate, -* WWW-Authenticate, and Set-Cookie) violate the HTTP spec -* and cannot be collapsed in this manner. For these headers -* only, the returned array may contain multiple elements if -* that header has been added more than once. -*/ - getHeaderValues: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - - if (name in this._headers) - return this._headers[name]; - else - throw Cr.NS_ERROR_NOT_AVAILABLE; - }, - - /** -* Returns true if a header with the given field name exists in this, false -* otherwise. -* -* @param fieldName : string -* the field name whose existence is to be determined in this -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @returns boolean -* true if the header's present, false otherwise -*/ - hasHeader: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - return (name in this._headers); - }, - - /** -* Returns a new enumerator over the field names of the headers in this, as -* nsISupportsStrings. The names returned will be in lowercase, regardless of -* how they were input using setHeader (header names are case-insensitive per -* RFC 2616). -*/ - get enumerator() - { - var headers = []; - for (var i in this._headers) - { - var supports = new SupportsString(); - supports.data = i; - headers.push(supports); - } - - return new nsSimpleEnumerator(headers); - } -}; - - -/** -* Constructs an nsISimpleEnumerator for the given array of items. -* -* @param items : Array -* the items, which must all implement nsISupports -*/ -function nsSimpleEnumerator(items) -{ - this._items = items; - this._nextIndex = 0; -} -nsSimpleEnumerator.prototype = -{ - hasMoreElements: function() - { - return this._nextIndex < this._items.length; - }, - getNext: function() - { - if (!this.hasMoreElements()) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - return this._items[this._nextIndex++]; - }, - QueryInterface: function(aIID) - { - if (Ci.nsISimpleEnumerator.equals(aIID) || - Ci.nsISupports.equals(aIID)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } -}; - - -/** -* A representation of the data in an HTTP request. -* -* @param port : uint -* the port on which the server receiving this request runs -*/ -function Request(port) -{ - /** Method of this request, e.g. GET or POST. */ - this._method = ""; - - /** Path of the requested resource; empty paths are converted to '/'. */ - this._path = ""; - - /** Query string, if any, associated with this request (not including '?'). */ - this._queryString = ""; - - /** Scheme of requested resource, usually http, always lowercase. */ - this._scheme = "http"; - - /** Hostname on which the requested resource resides. */ - this._host = undefined; - - /** Port number over which the request was received. */ - this._port = port; - - var bodyPipe = new Pipe(false, false, 0, PR_UINT32_MAX, null); - - /** Stream from which data in this request's body may be read. */ - this._bodyInputStream = bodyPipe.inputStream; - - /** Stream to which data in this request's body is written. */ - this._bodyOutputStream = bodyPipe.outputStream; - - /** -* The headers in this request. -*/ - this._headers = new nsHttpHeaders(); - - /** -* For the addition of ad-hoc properties and new functionality without having -* to change nsIHttpRequest every time; currently lazily created, as its only -* use is in directory listings. -*/ - this._bag = null; -} -Request.prototype = -{ - // SERVER METADATA - - // - // see nsIHttpRequest.scheme - // - get scheme() - { - return this._scheme; - }, - - // - // see nsIHttpRequest.host - // - get host() - { - return this._host; - }, - - // - // see nsIHttpRequest.port - // - get port() - { - return this._port; - }, - - // REQUEST LINE - - // - // see nsIHttpRequest.method - // - get method() - { - return this._method; - }, - - // - // see nsIHttpRequest.httpVersion - // - get httpVersion() - { - return this._httpVersion.toString(); - }, - - // - // see nsIHttpRequest.path - // - get path() - { - return this._path; - }, - - // - // see nsIHttpRequest.queryString - // - get queryString() - { - return this._queryString; - }, - - // HEADERS - - // - // see nsIHttpRequest.getHeader - // - getHeader: function(name) - { - return this._headers.getHeader(name); - }, - - // - // see nsIHttpRequest.hasHeader - // - hasHeader: function(name) - { - return this._headers.hasHeader(name); - }, - - // - // see nsIHttpRequest.headers - // - get headers() - { - return this._headers.enumerator; - }, - - // - // see nsIPropertyBag.enumerator - // - get enumerator() - { - this._ensurePropertyBag(); - return this._bag.enumerator; - }, - - // - // see nsIHttpRequest.headers - // - get bodyInputStream() - { - return this._bodyInputStream; - }, - - // - // see nsIPropertyBag.getProperty - // - getProperty: function(name) - { - this._ensurePropertyBag(); - return this._bag.getProperty(name); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpRequest) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** Ensures a property bag has been created for ad-hoc behaviors. */ - _ensurePropertyBag: function() - { - if (!this._bag) - this._bag = new WritablePropertyBag(); - } -}; - - -// XPCOM trappings -if ("XPCOMUtils" in this && // Firefox 3.6 doesn't load XPCOMUtils in this scope for some reason... - "generateNSGetFactory" in XPCOMUtils) { - var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsHttpServer]); -} - - - -/** -* Creates a new HTTP server listening for loopback traffic on the given port, -* starts it, and runs the server until the server processes a shutdown request, -* spinning an event loop so that events posted by the server's socket are -* processed. -* -* This method is primarily intended for use in running this script from within -* xpcshell and running a functional HTTP server without having to deal with -* non-essential details. -* -* Note that running multiple servers using variants of this method probably -* doesn't work, simply due to how the internal event loop is spun and stopped. -* -* @note -* This method only works with Mozilla 1.9 (i.e., Firefox 3 or trunk code); -* you should use this server as a component in Mozilla 1.8. -* @param port -* the port on which the server will run, or -1 if there exists no preference -* for a specific port; note that attempting to use some values for this -* parameter (particularly those below 1024) may cause this method to throw or -* may result in the server being prematurely shut down -* @param basePath -* a local directory from which requests will be served (i.e., if this is -* "/home/jwalden/" then a request to /index.html will load -* /home/jwalden/index.html); if this is omitted, only the default URLs in -* this server implementation will be functional -*/ -function server(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - // if you're running this, you probably want to see debugging info - DEBUG = true; - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", SJS_TYPE); - srv.start(port); - - var thread = gThreadManager.currentThread; - while (!srv.isStopped()) - thread.processNextEvent(true); - - // get rid of any pending requests - while (thread.hasPendingEvents()) - thread.processNextEvent(true); - - DEBUG = false; -} - -function startServerAsync(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", "sjs"); - srv.start(port); - return srv; -} - -exports.nsHttpServer = nsHttpServer; -exports.ScriptableInputStream = ScriptableInputStream; -exports.server = server; -exports.startServerAsync = startServerAsync; diff --git a/addon-sdk/source/test/addons/content-script-messages-latency/main.js b/addon-sdk/source/test/addons/content-script-messages-latency/main.js deleted file mode 100644 index 39bd7b64b..000000000 --- a/addon-sdk/source/test/addons/content-script-messages-latency/main.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"; - -const { PageMod } = require("sdk/page-mod"); -const tabs = require("sdk/tabs"); -const { startServerAsync } = require("./httpd"); -const { setTimeout } = require("sdk/timers"); - -const serverPort = 8099; - -exports.testContentScriptLatencyRegression = function*(assert) { - let server = startServerAsync(serverPort); - server.registerPathHandler("/", function handle(request, response) { - response.write(` - - - - - slow loading page... - - `); - }); - - server.registerPathHandler("/slow.css", function handle(request, response) { - response.processAsync(); - response.setHeader('Content-Type', 'text/css', false); - setTimeout(_ => { - response.write("body { background: red; }"); - response.finish(); - }, 2000); - }); - - - let pageMod; - - let worker = yield new Promise((resolve) => { - pageMod = PageMod({ - include: "http://localhost:8099/", - attachTo: "top", - contentScriptWhen: "start", - contentScript: "new " + function ContentScriptScope() { - self.port.on("a-port-message", function () { - self.port.emit("document-ready-state", document.readyState); - }); - }, - onAttach: function(w) { - resolve(w); - } - }); - - tabs.open({ - url: "http://localhost:8099/", - inBackground: true - }); - }); - - worker.port.emit("a-port-message"); - - let waitForPortMessage = new Promise((resolve) => { - worker.port.once("document-ready-state", (msg) => { - resolve(msg); - }); - }); - - let documentReadyState = yield waitForPortMessage; - - assert.notEqual( - "complete", documentReadyState, - "content script received the port message when the page was still loading" - ); - - assert.notEqual( - "uninitialized", documentReadyState, - "content script should be frozen if document.readyState is still uninitialized" - ); - - assert.ok( - ["loading", "interactive"].includes(documentReadyState), - "content script message received with document.readyState was interactive or loading" - ); - - // Cleanup. - pageMod.destroy(); - yield new Promise((resolve) => worker.tab.close(resolve)); - yield new Promise((resolve) => server.stop(resolve)); -}; - -require("sdk/test/runner").runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/content-script-messages-latency/package.json b/addon-sdk/source/test/addons/content-script-messages-latency/package.json deleted file mode 100644 index 8280fe18b..000000000 --- a/addon-sdk/source/test/addons/content-script-messages-latency/package.json +++ /dev/null @@ -1,6 +0,0 @@ - -{ - "id": "content-script-messages-latency@jetpack", - "main": "./main.js", - "version": "0.0.1" -} diff --git a/addon-sdk/source/test/addons/contributors/main.js b/addon-sdk/source/test/addons/contributors/main.js deleted file mode 100644 index 3827f277b..000000000 --- a/addon-sdk/source/test/addons/contributors/main.js +++ /dev/null @@ -1,19 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { id } = require('sdk/self'); -const { getAddonByID } = require('sdk/addon/manager'); - -exports.testContributors = function*(assert) { - let addon = yield getAddonByID(id); - let count = 0; - addon.contributors.forEach(({ name }) => { - assert.equal(name, ++count == 1 ? 'A' : 'B', 'The contributors keys are correct'); - }); - assert.equal(count, 2, 'The key count is correct'); - assert.equal(addon.contributors.length, 2, 'The key length is correct'); -} - -require('sdk/test/runner').runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/contributors/package.json b/addon-sdk/source/test/addons/contributors/package.json deleted file mode 100644 index b6f1798d3..000000000 --- a/addon-sdk/source/test/addons/contributors/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "id": "test-contributors@jetpack", - "contributors": [ "A", "B" ], - "main": "./main.js", - "version": "0.0.1" -} diff --git a/addon-sdk/source/test/addons/curly-id/lib/main.js b/addon-sdk/source/test/addons/curly-id/lib/main.js deleted file mode 100644 index 8b3f25645..000000000 --- a/addon-sdk/source/test/addons/curly-id/lib/main.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 simple = require('sdk/simple-prefs'); -const service = require('sdk/preferences/service'); -const { id, preferencesBranch } = require('sdk/self'); -const { getAddonByID } = require('sdk/addon/manager'); - -exports.testCurlyID = function(assert) { - assert.equal(id, '{34a1eae1-c20a-464f-9b0e-000000000000}', 'curly ID is curly'); - assert.equal(simple.prefs.test13, 26, 'test13 is 26'); - - simple.prefs.test14 = '15'; - assert.equal(service.get('extensions.{34a1eae1-c20a-464f-9b0e-000000000000}.test14'), '15', 'test14 is 15'); - assert.equal(service.get('extensions.{34a1eae1-c20a-464f-9b0e-000000000000}.test14'), simple.prefs.test14, 'simple test14 also 15'); -} - -// from `/test/test-self.js`, adapted to `sdk/test/assert` API -exports.testSelfID = function*(assert) { - assert.equal(typeof(id), 'string', 'self.id is a string'); - assert.ok(id.length > 0, 'self.id not empty'); - - let addon = yield getAddonByID(id); - assert.ok(addon, 'found addon with self.id'); -} - -require('sdk/test/runner').runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/curly-id/package.json b/addon-sdk/source/test/addons/curly-id/package.json deleted file mode 100644 index 213844662..000000000 --- a/addon-sdk/source/test/addons/curly-id/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "id": "{34a1eae1-c20a-464f-9b0e-000000000000}", - "fullName": "curly ID test", - "author": "Tomislav Jovanovic", - "preferences": [{ - "name": "test13", - "type": "integer", - "title": "test13", - "value": 26 - }], - "main": "./lib/main.js", - "version": "0.0.1" -} diff --git a/addon-sdk/source/test/addons/developers/main.js b/addon-sdk/source/test/addons/developers/main.js deleted file mode 100644 index d42faf643..000000000 --- a/addon-sdk/source/test/addons/developers/main.js +++ /dev/null @@ -1,19 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { id } = require('sdk/self'); -const { getAddonByID } = require('sdk/addon/manager'); - -exports.testDevelopers = function*(assert) { - let addon = yield getAddonByID(id); - let count = 0; - addon.developers.forEach(({ name }) => { - assert.equal(name, ++count == 1 ? 'A' : 'B', 'The developers keys are correct'); - }); - assert.equal(count, 2, 'The key count is correct'); - assert.equal(addon.developers.length, 2, 'The key length is correct'); -} - -require('sdk/test/runner').runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/developers/package.json b/addon-sdk/source/test/addons/developers/package.json deleted file mode 100644 index 1d2a189ec..000000000 --- a/addon-sdk/source/test/addons/developers/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "id": "test-developers@jetpack", - "title": "Test developers package key", - "author": "Erik Vold", - "developers": [ "A", "B" ], - "main": "./main.js", - "version": "0.0.1" -} diff --git a/addon-sdk/source/test/addons/e10s-content/data/test-contentScriptFile.js b/addon-sdk/source/test/addons/e10s-content/data/test-contentScriptFile.js deleted file mode 100644 index 7dc0e3f24..000000000 --- a/addon-sdk/source/test/addons/e10s-content/data/test-contentScriptFile.js +++ /dev/null @@ -1,5 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -self.postMessage("msg from contentScriptFile"); diff --git a/addon-sdk/source/test/addons/e10s-content/data/test-page-worker.html b/addon-sdk/source/test/addons/e10s-content/data/test-page-worker.html deleted file mode 100644 index 85264034a..000000000 --- a/addon-sdk/source/test/addons/e10s-content/data/test-page-worker.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - Page Worker test - - -

Lorem ipsum dolor sit amet.

- - diff --git a/addon-sdk/source/test/addons/e10s-content/data/test-page-worker.js b/addon-sdk/source/test/addons/e10s-content/data/test-page-worker.js deleted file mode 100644 index 5114fe4e0..000000000 --- a/addon-sdk/source/test/addons/e10s-content/data/test-page-worker.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/. */ - - -// get title directly -self.postMessage(["equal", document.title, "Page Worker test", - "Correct page title accessed directly"]); - -// get

directly -var p = document.getElementById("paragraph"); -self.postMessage(["ok", !!p, "

can be accessed directly"]); -self.postMessage(["equal", p.firstChild.nodeValue, - "Lorem ipsum dolor sit amet.", - "Correct text node expected"]); - -// Modify page -var div = document.createElement("div"); -div.setAttribute("id", "block"); -div.appendChild(document.createTextNode("Test text created")); -document.body.appendChild(div); - -// Check back the modification -div = document.getElementById("block"); -self.postMessage(["ok", !!div, "

can be accessed directly"]); -self.postMessage(["equal", div.firstChild.nodeValue, - "Test text created", "Correct text node expected"]); -self.postMessage(["done"]); - diff --git a/addon-sdk/source/test/addons/e10s-content/data/test.html b/addon-sdk/source/test/addons/e10s-content/data/test.html deleted file mode 100644 index 181e85f9b..000000000 --- a/addon-sdk/source/test/addons/e10s-content/data/test.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - foo - - -

bar

- - diff --git a/addon-sdk/source/test/addons/e10s-content/lib/fixtures.js b/addon-sdk/source/test/addons/e10s-content/lib/fixtures.js deleted file mode 100644 index d3bd49300..000000000 --- a/addon-sdk/source/test/addons/e10s-content/lib/fixtures.js +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { data } = require('sdk/self'); - -exports.url = data.url; diff --git a/addon-sdk/source/test/addons/e10s-content/lib/httpd.js b/addon-sdk/source/test/addons/e10s-content/lib/httpd.js deleted file mode 100644 index e46ca96a0..000000000 --- a/addon-sdk/source/test/addons/e10s-content/lib/httpd.js +++ /dev/null @@ -1,5212 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -* An implementation of an HTTP server both as a loadable script and as an XPCOM -* component. See the accompanying README file for user documentation on -* httpd.js. -*/ - -module.metadata = { - "stability": "experimental" -}; - -const { components, CC, Cc, Ci, Cr, Cu } = require("chrome"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - - -const PR_UINT32_MAX = Math.pow(2, 32) - 1; - -/** True if debugging output is enabled, false otherwise. */ -var DEBUG = false; // non-const *only* so tweakable in server tests - -/** True if debugging output should be timestamped. */ -var DEBUG_TIMESTAMP = false; // non-const so tweakable in server tests - -var gGlobalObject = Cc["@mozilla.org/systemprincipal;1"].createInstance(); - -/** -* Asserts that the given condition holds. If it doesn't, the given message is -* dumped, a stack trace is printed, and an exception is thrown to attempt to -* stop execution (which unfortunately must rely upon the exception not being -* accidentally swallowed by the code that uses it). -*/ -function NS_ASSERT(cond, msg) -{ - if (DEBUG && !cond) - { - dumpn("###!!!"); - dumpn("###!!! ASSERTION" + (msg ? ": " + msg : "!")); - dumpn("###!!! Stack follows:"); - - var stack = new Error().stack.split(/\n/); - dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n")); - - throw Cr.NS_ERROR_ABORT; - } -} - -/** Constructs an HTTP error object. */ -function HttpError(code, description) -{ - this.code = code; - this.description = description; -} -HttpError.prototype = -{ - toString: function() - { - return this.code + " " + this.description; - } -}; - -/** -* Errors thrown to trigger specific HTTP server responses. -*/ -const HTTP_400 = new HttpError(400, "Bad Request"); -const HTTP_401 = new HttpError(401, "Unauthorized"); -const HTTP_402 = new HttpError(402, "Payment Required"); -const HTTP_403 = new HttpError(403, "Forbidden"); -const HTTP_404 = new HttpError(404, "Not Found"); -const HTTP_405 = new HttpError(405, "Method Not Allowed"); -const HTTP_406 = new HttpError(406, "Not Acceptable"); -const HTTP_407 = new HttpError(407, "Proxy Authentication Required"); -const HTTP_408 = new HttpError(408, "Request Timeout"); -const HTTP_409 = new HttpError(409, "Conflict"); -const HTTP_410 = new HttpError(410, "Gone"); -const HTTP_411 = new HttpError(411, "Length Required"); -const HTTP_412 = new HttpError(412, "Precondition Failed"); -const HTTP_413 = new HttpError(413, "Request Entity Too Large"); -const HTTP_414 = new HttpError(414, "Request-URI Too Long"); -const HTTP_415 = new HttpError(415, "Unsupported Media Type"); -const HTTP_417 = new HttpError(417, "Expectation Failed"); - -const HTTP_500 = new HttpError(500, "Internal Server Error"); -const HTTP_501 = new HttpError(501, "Not Implemented"); -const HTTP_502 = new HttpError(502, "Bad Gateway"); -const HTTP_503 = new HttpError(503, "Service Unavailable"); -const HTTP_504 = new HttpError(504, "Gateway Timeout"); -const HTTP_505 = new HttpError(505, "HTTP Version Not Supported"); - -/** Creates a hash with fields corresponding to the values in arr. */ -function array2obj(arr) -{ - var obj = {}; - for (var i = 0; i < arr.length; i++) - obj[arr[i]] = arr[i]; - return obj; -} - -/** Returns an array of the integers x through y, inclusive. */ -function range(x, y) -{ - var arr = []; - for (var i = x; i <= y; i++) - arr.push(i); - return arr; -} - -/** An object (hash) whose fields are the numbers of all HTTP error codes. */ -const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505))); - - -/** -* The character used to distinguish hidden files from non-hidden files, a la -* the leading dot in Apache. Since that mechanism also hides files from -* easy display in LXR, ls output, etc. however, we choose instead to use a -* suffix character. If a requested file ends with it, we append another -* when getting the file on the server. If it doesn't, we just look up that -* file. Therefore, any file whose name ends with exactly one of the character -* is "hidden" and available for use by the server. -*/ -const HIDDEN_CHAR = "^"; - -/** -* The file name suffix indicating the file containing overridden headers for -* a requested file. -*/ -const HEADERS_SUFFIX = HIDDEN_CHAR + "headers" + HIDDEN_CHAR; - -/** Type used to denote SJS scripts for CGI-like functionality. */ -const SJS_TYPE = "sjs"; - -/** Base for relative timestamps produced by dumpn(). */ -var firstStamp = 0; - -/** dump(str) with a trailing "\n" -- only outputs if DEBUG. */ -function dumpn(str) -{ - if (DEBUG) - { - var prefix = "HTTPD-INFO | "; - if (DEBUG_TIMESTAMP) - { - if (firstStamp === 0) - firstStamp = Date.now(); - - var elapsed = Date.now() - firstStamp; // milliseconds - var min = Math.floor(elapsed / 60000); - var sec = (elapsed % 60000) / 1000; - - if (sec < 10) - prefix += min + ":0" + sec.toFixed(3) + " | "; - else - prefix += min + ":" + sec.toFixed(3) + " | "; - } - - dump(prefix + str + "\n"); - } -} - -/** Dumps the current JS stack if DEBUG. */ -function dumpStack() -{ - // peel off the frames for dumpStack() and Error() - var stack = new Error().stack.split(/\n/).slice(2); - stack.forEach(dumpn); -} - - -/** The XPCOM thread manager. */ -var gThreadManager = null; - -/** The XPCOM prefs service. */ -var gRootPrefBranch = null; -function getRootPrefBranch() -{ - if (!gRootPrefBranch) - { - gRootPrefBranch = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); - } - return gRootPrefBranch; -} - -/** -* JavaScript constructors for commonly-used classes; precreating these is a -* speedup over doing the same from base principles. See the docs at -* http://developer.mozilla.org/en/docs/components.Constructor for details. -*/ -const ServerSocket = CC("@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "init"); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", - "init"); -const Pipe = CC("@mozilla.org/pipe;1", - "nsIPipe", - "init"); -const FileInputStream = CC("@mozilla.org/network/file-input-stream;1", - "nsIFileInputStream", - "init"); -const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1", - "nsIConverterInputStream", - "init"); -const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1", - "nsIWritablePropertyBag2"); -const SupportsString = CC("@mozilla.org/supports-string;1", - "nsISupportsString"); - -/* These two are non-const only so a test can overwrite them. */ -var BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); -var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1", - "nsIBinaryOutputStream", - "setOutputStream"); - -/** -* Returns the RFC 822/1123 representation of a date. -* -* @param date : Number -* the date, in milliseconds from midnight (00:00:00), January 1, 1970 GMT -* @returns string -* the representation of the given date -*/ -function toDateString(date) -{ - // - // rfc1123-date = wkday "," SP date1 SP time SP "GMT" - // date1 = 2DIGIT SP month SP 4DIGIT - // ; day month year (e.g., 02 Jun 1982) - // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT - // ; 00:00:00 - 23:59:59 - // wkday = "Mon" | "Tue" | "Wed" - // | "Thu" | "Fri" | "Sat" | "Sun" - // month = "Jan" | "Feb" | "Mar" | "Apr" - // | "May" | "Jun" | "Jul" | "Aug" - // | "Sep" | "Oct" | "Nov" | "Dec" - // - - const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - - /** -* Processes a date and returns the encoded UTC time as a string according to -* the format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toTime(date) - { - var hrs = date.getUTCHours(); - var rv = (hrs < 10) ? "0" + hrs : hrs; - - var mins = date.getUTCMinutes(); - rv += ":"; - rv += (mins < 10) ? "0" + mins : mins; - - var secs = date.getUTCSeconds(); - rv += ":"; - rv += (secs < 10) ? "0" + secs : secs; - - return rv; - } - - /** -* Processes a date and returns the encoded UTC date as a string according to -* the date1 format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toDate1(date) - { - var day = date.getUTCDate(); - var month = date.getUTCMonth(); - var year = date.getUTCFullYear(); - - var rv = (day < 10) ? "0" + day : day; - rv += " " + monthStrings[month]; - rv += " " + year; - - return rv; - } - - date = new Date(date); - - const fmtString = "%wkday%, %date1% %time% GMT"; - var rv = fmtString.replace("%wkday%", wkdayStrings[date.getUTCDay()]); - rv = rv.replace("%time%", toTime(date)); - return rv.replace("%date1%", toDate1(date)); -} - -/** -* Prints out a human-readable representation of the object o and its fields, -* omitting those whose names begin with "_" if showMembers != true (to ignore -* "private" properties exposed via getters/setters). -*/ -function printObj(o, showMembers) -{ - var s = "******************************\n"; - s += "o = {\n"; - for (var i in o) - { - if (typeof(i) != "string" || - (showMembers || (i.length > 0 && i[0] != "_"))) - s+= " " + i + ": " + o[i] + ",\n"; - } - s += " };\n"; - s += "******************************"; - dumpn(s); -} - -/** -* Instantiates a new HTTP server. -*/ -function nsHttpServer() -{ - if (!gThreadManager) - gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService(); - - /** The port on which this server listens. */ - this._port = undefined; - - /** The socket associated with this. */ - this._socket = null; - - /** The handler used to process requests to this server. */ - this._handler = new ServerHandler(this); - - /** Naming information for this server. */ - this._identity = new ServerIdentity(); - - /** -* Indicates when the server is to be shut down at the end of the request. -*/ - this._doQuit = false; - - /** -* True if the socket in this is closed (and closure notifications have been -* sent and processed if the socket was ever opened), false otherwise. -*/ - this._socketClosed = true; - - /** -* Used for tracking existing connections and ensuring that all connections -* are properly cleaned up before server shutdown; increases by 1 for every -* new incoming connection. -*/ - this._connectionGen = 0; - - /** -* Hash of all open connections, indexed by connection number at time of -* creation. -*/ - this._connections = {}; -} -nsHttpServer.prototype = -{ - classID: components.ID("{54ef6f81-30af-4b1d-ac55-8ba811293e41}"), - - // NSISERVERSOCKETLISTENER - - /** -* Processes an incoming request coming in on the given socket and contained -* in the given transport. -* -* @param socket : nsIServerSocket -* the socket through which the request was served -* @param trans : nsISocketTransport -* the transport for the request/response -* @see nsIServerSocketListener.onSocketAccepted -*/ - onSocketAccepted: function(socket, trans) - { - dumpn("*** onSocketAccepted(socket=" + socket + ", trans=" + trans + ")"); - - dumpn(">>> new connection on " + trans.host + ":" + trans.port); - - const SEGMENT_SIZE = 8192; - const SEGMENT_COUNT = 1024; - try - { - var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT) - .QueryInterface(Ci.nsIAsyncInputStream); - var output = trans.openOutputStream(0, 0, 0); - } - catch (e) - { - dumpn("*** error opening transport streams: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - var connectionNumber = ++this._connectionGen; - - try - { - var conn = new Connection(input, output, this, socket.port, trans.port, - connectionNumber); - var reader = new RequestReader(conn); - - // XXX add request timeout functionality here! - - // Note: must use main thread here, or we might get a GC that will cause - // threadsafety assertions. We really need to fix XPConnect so that - // you can actually do things in multi-threaded JS. :-( - input.asyncWait(reader, 0, 0, gThreadManager.mainThread); - } - catch (e) - { - // Assume this connection can't be salvaged and bail on it completely; - // don't attempt to close it so that we can assert that any connection - // being closed is in this._connections. - dumpn("*** error in initial request-processing stages: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - this._connections[connectionNumber] = conn; - dumpn("*** starting connection " + connectionNumber); - }, - - /** -* Called when the socket associated with this is closed. -* -* @param socket : nsIServerSocket -* the socket being closed -* @param status : nsresult -* the reason the socket stopped listening (NS_BINDING_ABORTED if the server -* was stopped using nsIHttpServer.stop) -* @see nsIServerSocketListener.onStopListening -*/ - onStopListening: function(socket, status) - { - dumpn(">>> shutting down server on port " + socket.port); - this._socketClosed = true; - if (!this._hasOpenConnections()) - { - dumpn("*** no open connections, notifying async from onStopListening"); - - // Notify asynchronously so that any pending teardown in stop() has a - // chance to run first. - var self = this; - var stopEvent = - { - run: function() - { - dumpn("*** _notifyStopped async callback"); - self._notifyStopped(); - } - }; - gThreadManager.currentThread - .dispatch(stopEvent, Ci.nsIThread.DISPATCH_NORMAL); - } - }, - - // NSIHTTPSERVER - - // - // see nsIHttpServer.start - // - start: function(port) - { - this._start(port, "localhost") - }, - - _start: function(port, host) - { - if (this._socket) - throw Cr.NS_ERROR_ALREADY_INITIALIZED; - - this._port = port; - this._doQuit = this._socketClosed = false; - - this._host = host; - - // The listen queue needs to be long enough to handle - // network.http.max-persistent-connections-per-server concurrent connections, - // plus a safety margin in case some other process is talking to - // the server as well. - var prefs = getRootPrefBranch(); - var maxConnections; - try { - // Bug 776860: The original pref was removed in favor of this new one: - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server") + 5; - } - catch(e) { - maxConnections = prefs.getIntPref("network.http.max-connections-per-server") + 5; - } - - try - { - var loopback = true; - if (this._host != "127.0.0.1" && this._host != "localhost") { - var loopback = false; - } - - var socket = new ServerSocket(this._port, - loopback, // true = localhost, false = everybody - maxConnections); - dumpn(">>> listening on port " + socket.port + ", " + maxConnections + - " pending connections"); - socket.asyncListen(this); - this._identity._initialize(socket.port, host, true); - this._socket = socket; - } - catch (e) - { - dumpn("!!! could not start server on port " + port + ": " + e); - throw Cr.NS_ERROR_NOT_AVAILABLE; - } - }, - - // - // see nsIHttpServer.stop - // - stop: function(callback) - { - if (!callback) - throw Cr.NS_ERROR_NULL_POINTER; - if (!this._socket) - throw Cr.NS_ERROR_UNEXPECTED; - - this._stopCallback = typeof callback === "function" - ? callback - : function() { callback.onStopped(); }; - - dumpn(">>> stopping listening on port " + this._socket.port); - this._socket.close(); - this._socket = null; - - // We can't have this identity any more, and the port on which we're running - // this server now could be meaningless the next time around. - this._identity._teardown(); - - this._doQuit = false; - - // socket-close notification and pending request completion happen async - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (file && (!file.exists() || file.isDirectory())) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handler.registerFile(path, file); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // XXX true path validation! - if (path.charAt(0) != "/" || - path.charAt(path.length - 1) != "/" || - (directory && - (!directory.exists() || !directory.isDirectory()))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX determine behavior of nonexistent /foo/bar when a /foo/bar/ mapping - // exists! - - this._handler.registerDirectory(path, directory); - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - this._handler.registerPathHandler(path, handler); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - this._handler.registerPrefixHandler(prefix, handler); - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(code, handler) - { - this._handler.registerErrorHandler(code, handler); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - this._handler.setIndexHandler(handler); - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - this._handler.registerContentType(ext, type); - }, - - // - // see nsIHttpServer.serverIdentity - // - get identity() - { - return this._identity; - }, - - // - // see nsIHttpServer.getState - // - getState: function(path, k) - { - return this._handler._getState(path, k); - }, - - // - // see nsIHttpServer.setState - // - setState: function(path, k, v) - { - return this._handler._setState(path, k, v); - }, - - // - // see nsIHttpServer.getSharedState - // - getSharedState: function(k) - { - return this._handler._getSharedState(k); - }, - - // - // see nsIHttpServer.setSharedState - // - setSharedState: function(k, v) - { - return this._handler._setSharedState(k, v); - }, - - // - // see nsIHttpServer.getObjectState - // - getObjectState: function(k) - { - return this._handler._getObjectState(k); - }, - - // - // see nsIHttpServer.setObjectState - // - setObjectState: function(k, v) - { - return this._handler._setObjectState(k, v); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIServerSocketListener) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NON-XPCOM PUBLIC API - - /** -* Returns true iff this server is not running (and is not in the process of -* serving any requests still to be processed when the server was last -* stopped after being run). -*/ - isStopped: function() - { - return this._socketClosed && !this._hasOpenConnections(); - }, - - // PRIVATE IMPLEMENTATION - - /** True if this server has any open connections to it, false otherwise. */ - _hasOpenConnections: function() - { - // - // If we have any open connections, they're tracked as numeric properties on - // |this._connections|. The non-standard __count__ property could be used - // to check whether there are any properties, but standard-wise, even - // looking forward to ES5, there's no less ugly yet still O(1) way to do - // this. - // - for (var n in this._connections) - return true; - return false; - }, - - /** Calls the server-stopped callback provided when stop() was called. */ - _notifyStopped: function() - { - NS_ASSERT(this._stopCallback !== null, "double-notifying?"); - NS_ASSERT(!this._hasOpenConnections(), "should be done serving by now"); - - // - // NB: We have to grab this now, null out the member, *then* call the - // callback here, or otherwise the callback could (indirectly) futz with - // this._stopCallback by starting and immediately stopping this, at - // which point we'd be nulling out a field we no longer have a right to - // modify. - // - var callback = this._stopCallback; - this._stopCallback = null; - try - { - callback(); - } - catch (e) - { - // not throwing because this is specified as being usually (but not - // always) asynchronous - dump("!!! error running onStopped callback: " + e + "\n"); - } - }, - - /** -* Notifies this server that the given connection has been closed. -* -* @param connection : Connection -* the connection that was closed -*/ - _connectionClosed: function(connection) - { - NS_ASSERT(connection.number in this._connections, - "closing a connection " + this + " that we never added to the " + - "set of open connections?"); - NS_ASSERT(this._connections[connection.number] === connection, - "connection number mismatch? " + - this._connections[connection.number]); - delete this._connections[connection.number]; - - // Fire a pending server-stopped notification if it's our responsibility. - if (!this._hasOpenConnections() && this._socketClosed) - this._notifyStopped(); - }, - - /** -* Requests that the server be shut down when possible. -*/ - _requestQuit: function() - { - dumpn(">>> requesting a quit"); - dumpStack(); - this._doQuit = true; - } -}; - - -// -// RFC 2396 section 3.2.2: -// -// host = hostname | IPv4address -// hostname = *( domainlabel "." ) toplabel [ "." ] -// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum -// toplabel = alpha | alpha *( alphanum | "-" ) alphanum -// IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit -// - -const HOST_REGEX = - new RegExp("^(?:" + - // *( domainlabel "." ) - "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" + - // toplabel - "[a-z](?:[a-z0-9-]*[a-z0-9])?" + - "|" + - // IPv4 address - "\\d+\\.\\d+\\.\\d+\\.\\d+" + - ")$", - "i"); - - -/** -* Represents the identity of a server. An identity consists of a set of -* (scheme, host, port) tuples denoted as locations (allowing a single server to -* serve multiple sites or to be used behind both HTTP and HTTPS proxies for any -* host/port). Any incoming request must be to one of these locations, or it -* will be rejected with an HTTP 400 error. One location, denoted as the -* primary location, is the location assigned in contexts where a location -* cannot otherwise be endogenously derived, such as for HTTP/1.0 requests. -* -* A single identity may contain at most one location per unique host/port pair; -* other than that, no restrictions are placed upon what locations may -* constitute an identity. -*/ -function ServerIdentity() -{ - /** The scheme of the primary location. */ - this._primaryScheme = "http"; - - /** The hostname of the primary location. */ - this._primaryHost = "127.0.0.1" - - /** The port number of the primary location. */ - this._primaryPort = -1; - - /** -* The current port number for the corresponding server, stored so that a new -* primary location can always be set if the current one is removed. -*/ - this._defaultPort = -1; - - /** -* Maps hosts to maps of ports to schemes, e.g. the following would represent -* https://example.com:789/ and http://example.org/: -* -* { -* "xexample.com": { 789: "https" }, -* "xexample.org": { 80: "http" } -* } -* -* Note the "x" prefix on hostnames, which prevents collisions with special -* JS names like "prototype". -*/ - this._locations = { "xlocalhost": {} }; -} -ServerIdentity.prototype = -{ - // NSIHTTPSERVERIDENTITY - - // - // see nsIHttpServerIdentity.primaryScheme - // - get primaryScheme() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryScheme; - }, - - // - // see nsIHttpServerIdentity.primaryHost - // - get primaryHost() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryHost; - }, - - // - // see nsIHttpServerIdentity.primaryPort - // - get primaryPort() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryPort; - }, - - // - // see nsIHttpServerIdentity.add - // - add: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - this._locations["x" + host] = entry = {}; - - entry[port] = scheme; - }, - - // - // see nsIHttpServerIdentity.remove - // - remove: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return false; - - var present = port in entry; - delete entry[port]; - - if (this._primaryScheme == scheme && - this._primaryHost == host && - this._primaryPort == port && - this._defaultPort !== -1) - { - // Always keep at least one identity in existence at any time, unless - // we're in the process of shutting down (the last condition above). - this._primaryPort = -1; - this._initialize(this._defaultPort, host, false); - } - - return present; - }, - - // - // see nsIHttpServerIdentity.has - // - has: function(scheme, host, port) - { - this._validate(scheme, host, port); - - return "x" + host in this._locations && - scheme === this._locations["x" + host][port]; - }, - - // - // see nsIHttpServerIdentity.has - // - getScheme: function(host, port) - { - this._validate("http", host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return ""; - - return entry[port] || ""; - }, - - // - // see nsIHttpServerIdentity.setPrimary - // - setPrimary: function(scheme, host, port) - { - this._validate(scheme, host, port); - - this.add(scheme, host, port); - - this._primaryScheme = scheme; - this._primaryHost = host; - this._primaryPort = port; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpServerIdentity) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Initializes the primary name for the corresponding server, based on the -* provided port number. -*/ - _initialize: function(port, host, addSecondaryDefault) - { - this._host = host; - if (this._primaryPort !== -1) - this.add("http", host, port); - else - this.setPrimary("http", "localhost", port); - this._defaultPort = port; - - // Only add this if we're being called at server startup - if (addSecondaryDefault && host != "127.0.0.1") - this.add("http", "127.0.0.1", port); - }, - - /** -* Called at server shutdown time, unsets the primary location only if it was -* the default-assigned location and removes the default location from the -* set of locations used. -*/ - _teardown: function() - { - if (this._host != "127.0.0.1") { - // Not the default primary location, nothing special to do here - this.remove("http", "127.0.0.1", this._defaultPort); - } - - // This is a *very* tricky bit of reasoning here; make absolutely sure the - // tests for this code pass before you commit changes to it. - if (this._primaryScheme == "http" && - this._primaryHost == this._host && - this._primaryPort == this._defaultPort) - { - // Make sure we don't trigger the readding logic in .remove(), then remove - // the default location. - var port = this._defaultPort; - this._defaultPort = -1; - this.remove("http", this._host, port); - - // Ensure a server start triggers the setPrimary() path in ._initialize() - this._primaryPort = -1; - } - else - { - // No reason not to remove directly as it's not our primary location - this.remove("http", this._host, this._defaultPort); - } - }, - - /** -* Ensures scheme, host, and port are all valid with respect to RFC 2396. -* -* @throws NS_ERROR_ILLEGAL_VALUE -* if any argument doesn't match the corresponding production -*/ - _validate: function(scheme, host, port) - { - if (scheme !== "http" && scheme !== "https") - { - dumpn("*** server only supports http/https schemes: '" + scheme + "'"); - dumpStack(); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (!HOST_REGEX.test(host)) - { - dumpn("*** unexpected host: '" + host + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (port < 0 || port > 65535) - { - dumpn("*** unexpected port: '" + port + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - } -}; - - -/** -* Represents a connection to the server (and possibly in the future the thread -* on which the connection is processed). -* -* @param input : nsIInputStream -* stream from which incoming data on the connection is read -* @param output : nsIOutputStream -* stream to write data out the connection -* @param server : nsHttpServer -* the server handling the connection -* @param port : int -* the port on which the server is running -* @param outgoingPort : int -* the outgoing port used by this connection -* @param number : uint -* a serial number used to uniquely identify this connection -*/ -function Connection(input, output, server, port, outgoingPort, number) -{ - dumpn("*** opening new connection " + number + " on port " + outgoingPort); - - /** Stream of incoming data. */ - this.input = input; - - /** Stream for outgoing data. */ - this.output = output; - - /** The server associated with this request. */ - this.server = server; - - /** The port on which the server is running. */ - this.port = port; - - /** The outgoing poort used by this connection. */ - this._outgoingPort = outgoingPort; - - /** The serial number of this connection. */ - this.number = number; - - /** -* The request for which a response is being generated, null if the -* incoming request has not been fully received or if it had errors. -*/ - this.request = null; - - /** State variables for debugging. */ - this._closed = this._processed = false; -} -Connection.prototype = -{ - /** Closes this connection's input/output streams. */ - close: function() - { - dumpn("*** closing connection " + this.number + - " on port " + this._outgoingPort); - - this.input.close(); - this.output.close(); - this._closed = true; - - var server = this.server; - server._connectionClosed(this); - - // If an error triggered a server shutdown, act on it now - if (server._doQuit) - server.stop(function() { /* not like we can do anything better */ }); - }, - - /** -* Initiates processing of this connection, using the data in the given -* request. -* -* @param request : Request -* the request which should be processed -*/ - process: function(request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - - this.request = request; - this.server._handler.handleResponse(this); - }, - - /** -* Initiates processing of this connection, generating a response with the -* given HTTP error code. -* -* @param code : uint -* an HTTP code, so in the range [0, 1000) -* @param request : Request -* incomplete data about the incoming request (since there were errors -* during its processing -*/ - processError: function(code, request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - this.request = request; - this.server._handler.handleError(code, this); - }, - - /** Converts this to a string for debugging purposes. */ - toString: function() - { - return ""; - } -}; - - - -/** Returns an array of count bytes from the given input stream. */ -function readBytes(inputStream, count) -{ - return new BinaryInputStream(inputStream).readByteArray(count); -} - - - -/** Request reader processing states; see RequestReader for details. */ -const READER_IN_REQUEST_LINE = 0; -const READER_IN_HEADERS = 1; -const READER_IN_BODY = 2; -const READER_FINISHED = 3; - - -/** -* Reads incoming request data asynchronously, does any necessary preprocessing, -* and forwards it to the request handler. Processing occurs in three states: -* -* READER_IN_REQUEST_LINE Reading the request's status line -* READER_IN_HEADERS Reading headers in the request -* READER_IN_BODY Reading the body of the request -* READER_FINISHED Entire request has been read and processed -* -* During the first two stages, initial metadata about the request is gathered -* into a Request object. Once the status line and headers have been processed, -* we start processing the body of the request into the Request. Finally, when -* the entire body has been read, we create a Response and hand it off to the -* ServerHandler to be given to the appropriate request handler. -* -* @param connection : Connection -* the connection for the request being read -*/ -function RequestReader(connection) -{ - /** Connection metadata for this request. */ - this._connection = connection; - - /** -* A container providing line-by-line access to the raw bytes that make up the -* data which has been read from the connection but has not yet been acted -* upon (by passing it to the request handler or by extracting request -* metadata from it). -*/ - this._data = new LineData(); - - /** -* The amount of data remaining to be read from the body of this request. -* After all headers in the request have been read this is the value in the -* Content-Length header, but as the body is read its value decreases to zero. -*/ - this._contentLength = 0; - - /** The current state of parsing the incoming request. */ - this._state = READER_IN_REQUEST_LINE; - - /** Metadata constructed from the incoming request for the request handler. */ - this._metadata = new Request(connection.port); - - /** -* Used to preserve state if we run out of line data midway through a -* multi-line header. _lastHeaderName stores the name of the header, while -* _lastHeaderValue stores the value we've seen so far for the header. -* -* These fields are always either both undefined or both strings. -*/ - this._lastHeaderName = this._lastHeaderValue = undefined; -} -RequestReader.prototype = -{ - // NSIINPUTSTREAMCALLBACK - - /** -* Called when more data from the incoming request is available. This method -* then reads the available data from input and deals with that data as -* necessary, depending upon the syntax of already-downloaded data. -* -* @param input : nsIAsyncInputStream -* the stream of incoming data from the connection -*/ - onInputStreamReady: function(input) - { - dumpn("*** onInputStreamReady(input=" + input + ") on thread " + - gThreadManager.currentThread + " (main is " + - gThreadManager.mainThread + ")"); - dumpn("*** this._state == " + this._state); - - // Handle cases where we get more data after a request error has been - // discovered but *before* we can close the connection. - var data = this._data; - if (!data) - return; - - try - { - data.appendBytes(readBytes(input, input.available())); - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** WARNING: unexpected error when reading from socket; will " + - "be treated as if the input stream had been closed"); - dumpn("*** WARNING: actual error was: " + e); - } - - // We've lost a race -- input has been closed, but we're still expecting - // to read more data. available() will throw in this case, and since - // we're dead in the water now, destroy the connection. - dumpn("*** onInputStreamReady called on a closed input, destroying " + - "connection"); - this._connection.close(); - return; - } - - switch (this._state) - { - default: - NS_ASSERT(false, "invalid state: " + this._state); - break; - - case READER_IN_REQUEST_LINE: - if (!this._processRequestLine()) - break; - /* fall through */ - - case READER_IN_HEADERS: - if (!this._processHeaders()) - break; - /* fall through */ - - case READER_IN_BODY: - this._processBody(); - } - - if (this._state != READER_FINISHED) - input.asyncWait(this, 0, 0, gThreadManager.currentThread); - }, - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIInputStreamCallback) || - aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE API - - /** -* Processes unprocessed, downloaded data as a request line. -* -* @returns boolean -* true iff the request line has been fully processed -*/ - _processRequestLine: function() - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - // Servers SHOULD ignore any empty line(s) received where a Request-Line - // is expected (section 4.1). - var data = this._data; - var line = {}; - var readSuccess; - while ((readSuccess = data.readLine(line)) && line.value == "") - dumpn("*** ignoring beginning blank line..."); - - // if we don't have a full line, wait until we do - if (!readSuccess) - return false; - - // we have the first non-blank line - try - { - this._parseRequestLine(line.value); - this._state = READER_IN_HEADERS; - return true; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing request headers. -* -* @returns boolean -* true iff header data in the request has been fully processed -*/ - _processHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - // XXX things to fix here: - // - // - need to support RFC 2047-encoded non-US-ASCII characters - - try - { - var done = this._parseHeaders(); - if (done) - { - var request = this._metadata; - - // XXX this is wrong for requests with transfer-encodings applied to - // them, particularly chunked (which by its nature can have no - // meaningful Content-Length header)! - this._contentLength = request.hasHeader("Content-Length") - ? parseInt(request.getHeader("Content-Length"), 10) - : 0; - dumpn("_processHeaders, Content-length=" + this._contentLength); - - this._state = READER_IN_BODY; - } - return done; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing the request body. -* -* @returns boolean -* true iff the request body has been fully processed -*/ - _processBody: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - // XXX handle chunked transfer-coding request bodies! - - try - { - if (this._contentLength > 0) - { - var data = this._data.purge(); - var count = Math.min(data.length, this._contentLength); - dumpn("*** loading data=" + data + " len=" + data.length + - " excess=" + (data.length - count)); - - var bos = new BinaryOutputStream(this._metadata._bodyOutputStream); - bos.writeByteArray(data, count); - this._contentLength -= count; - } - - dumpn("*** remaining body data len=" + this._contentLength); - if (this._contentLength == 0) - { - this._validateRequest(); - this._state = READER_FINISHED; - this._handleResponse(); - return true; - } - - return false; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Does various post-header checks on the data in this request. -* -* @throws : HttpError -* if the request was malformed in some way -*/ - _validateRequest: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - dumpn("*** _validateRequest"); - - var metadata = this._metadata; - var headers = metadata._headers; - - // 19.6.1.1 -- servers MUST report 400 to HTTP/1.1 requests w/o Host header - var identity = this._connection.server.identity; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - { - if (!headers.hasHeader("Host")) - { - dumpn("*** malformed HTTP/1.1 or greater request with no Host header!"); - throw HTTP_400; - } - - // If the Request-URI wasn't absolute, then we need to determine our host. - // We have to determine what scheme was used to access us based on the - // server identity data at this point, because the request just doesn't - // contain enough data on its own to do this, sadly. - if (!metadata._host) - { - var host, port; - var hostPort = headers.getHeader("Host"); - var colon = hostPort.indexOf(":"); - if (colon < 0) - { - host = hostPort; - port = ""; - } - else - { - host = hostPort.substring(0, colon); - port = hostPort.substring(colon + 1); - } - - // NB: We allow an empty port here because, oddly, a colon may be - // present even without a port number, e.g. "example.com:"; in this - // case the default port applies. - if (!HOST_REGEX.test(host) || !/^\d*$/.test(port)) - { - dumpn("*** malformed hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - // If we're not given a port, we're stuck, because we don't know what - // scheme to use to look up the correct port here, in general. Since - // the HTTPS case requires a tunnel/proxy and thus requires that the - // requested URI be absolute (and thus contain the necessary - // information), let's assume HTTP will prevail and use that. - port = +port || 80; - - var scheme = identity.getScheme(host, port); - if (!scheme) - { - dumpn("*** unrecognized hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - } - } - else - { - NS_ASSERT(metadata._host === undefined, - "HTTP/1.0 doesn't allow absolute paths in the request line!"); - - metadata._scheme = identity.primaryScheme; - metadata._host = identity.primaryHost; - metadata._port = identity.primaryPort; - } - - NS_ASSERT(identity.has(metadata._scheme, metadata._host, metadata._port), - "must have a location we recognize by now!"); - }, - - /** -* Handles responses in case of error, either in the server or in the request. -* -* @param e -* the specific error encountered, which is an HttpError in the case where -* the request is in some way invalid or cannot be fulfilled; if this isn't -* an HttpError we're going to be paranoid and shut down, because that -* shouldn't happen, ever -*/ - _handleError: function(e) - { - // Don't fall back into normal processing! - this._state = READER_FINISHED; - - var server = this._connection.server; - if (e instanceof HttpError) - { - var code = e.code; - } - else - { - dumpn("!!! UNEXPECTED ERROR: " + e + - (e.lineNumber ? ", line " + e.lineNumber : "")); - - // no idea what happened -- be paranoid and shut down - code = 500; - server._requestQuit(); - } - - // make attempted reuse of data an error - this._data = null; - - this._connection.processError(code, this._metadata); - }, - - /** -* Now that we've read the request line and headers, we can actually hand off -* the request to be handled. -* -* This method is called once per request, after the request line and all -* headers and the body, if any, have been received. -*/ - _handleResponse: function() - { - NS_ASSERT(this._state == READER_FINISHED); - - // We don't need the line-based data any more, so make attempted reuse an - // error. - this._data = null; - - this._connection.process(this._metadata); - }, - - - // PARSING - - /** -* Parses the request line for the HTTP request associated with this. -* -* @param line : string -* the request line -*/ - _parseRequestLine: function(line) - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - dumpn("*** _parseRequestLine('" + line + "')"); - - var metadata = this._metadata; - - // clients and servers SHOULD accept any amount of SP or HT characters - // between fields, even though only a single SP is required (section 19.3) - var request = line.split(/[ \t]+/); - if (!request || request.length != 3) - throw HTTP_400; - - metadata._method = request[0]; - - // get the HTTP version - var ver = request[2]; - var match = ver.match(/^HTTP\/(\d+\.\d+)$/); - if (!match) - throw HTTP_400; - - // determine HTTP version - try - { - metadata._httpVersion = new nsHttpVersion(match[1]); - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_0)) - throw "unsupported HTTP version"; - } - catch (e) - { - // we support HTTP/1.0 and HTTP/1.1 only - throw HTTP_501; - } - - - var fullPath = request[1]; - var serverIdentity = this._connection.server.identity; - - var scheme, host, port; - - if (fullPath.charAt(0) != "/") - { - // No absolute paths in the request line in HTTP prior to 1.1 - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - throw HTTP_400; - - try - { - var uri = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService) - .newURI(fullPath, null, null); - fullPath = uri.path; - scheme = uri.scheme; - host = metadata._host = uri.asciiHost; - port = uri.port; - if (port === -1) - { - if (scheme === "http") - port = 80; - else if (scheme === "https") - port = 443; - else - throw HTTP_400; - } - } - catch (e) - { - // If the host is not a valid host on the server, the response MUST be a - // 400 (Bad Request) error message (section 5.2). Alternately, the URI - // is malformed. - throw HTTP_400; - } - - if (!serverIdentity.has(scheme, host, port) || fullPath.charAt(0) != "/") - throw HTTP_400; - } - - var splitter = fullPath.indexOf("?"); - if (splitter < 0) - { - // _queryString already set in ctor - metadata._path = fullPath; - } - else - { - metadata._path = fullPath.substring(0, splitter); - metadata._queryString = fullPath.substring(splitter + 1); - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - }, - - /** -* Parses all available HTTP headers in this until the header-ending CRLFCRLF, -* adding them to the store of headers in the request. -* -* @throws -* HTTP_400 if the headers are malformed -* @returns boolean -* true if all headers have now been processed, false otherwise -*/ - _parseHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - dumpn("*** _parseHeaders"); - - var data = this._data; - - var headers = this._metadata._headers; - var lastName = this._lastHeaderName; - var lastVal = this._lastHeaderValue; - - var line = {}; - while (true) - { - NS_ASSERT(!((lastVal === undefined) ^ (lastName === undefined)), - lastName === undefined ? - "lastVal without lastName? lastVal: '" + lastVal + "'" : - "lastName without lastVal? lastName: '" + lastName + "'"); - - if (!data.readLine(line)) - { - // save any data we have from the header we might still be processing - this._lastHeaderName = lastName; - this._lastHeaderValue = lastVal; - return false; - } - - var lineText = line.value; - var firstChar = lineText.charAt(0); - - // blank line means end of headers - if (lineText == "") - { - // we're finished with the previous header - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - else - { - // no headers in request -- valid for HTTP/1.0 requests - } - - // either way, we're done processing headers - this._state = READER_IN_BODY; - return true; - } - else if (firstChar == " " || firstChar == "\t") - { - // multi-line header if we've already seen a header line - if (!lastName) - { - // we don't have a header to continue! - throw HTTP_400; - } - - // append this line's text to the value; starts with SP/HT, so no need - // for separating whitespace - lastVal += lineText; - } - else - { - // we have a new header, so set the old one (if one existed) - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - - var colon = lineText.indexOf(":"); // first colon must be splitter - if (colon < 1) - { - // no colon or missing header field-name - throw HTTP_400; - } - - // set header name, value (to be set in the next loop, usually) - lastName = lineText.substring(0, colon); - lastVal = lineText.substring(colon + 1); - } // empty, continuation, start of header - } // while (true) - } -}; - - -/** The character codes for CR and LF. */ -const CR = 0x0D, LF = 0x0A; - -/** -* Calculates the number of characters before the first CRLF pair in array, or -* -1 if the array contains no CRLF pair. -* -* @param array : Array -* an array of numbers in the range [0, 256), each representing a single -* character; the first CRLF is the lowest index i where -* |array[i] == "\r".charCodeAt(0)| and |array[i+1] == "\n".charCodeAt(0)|, -* if such an |i| exists, and -1 otherwise -* @returns int -* the index of the first CRLF if any were present, -1 otherwise -*/ -function findCRLF(array) -{ - for (var i = array.indexOf(CR); i >= 0; i = array.indexOf(CR, i + 1)) - { - if (array[i + 1] == LF) - return i; - } - return -1; -} - - -/** -* A container which provides line-by-line access to the arrays of bytes with -* which it is seeded. -*/ -function LineData() -{ - /** An array of queued bytes from which to get line-based characters. */ - this._data = []; -} -LineData.prototype = -{ - /** -* Appends the bytes in the given array to the internal data cache maintained -* by this. -*/ - appendBytes: function(bytes) - { - Array.prototype.push.apply(this._data, bytes); - }, - - /** -* Removes and returns a line of data, delimited by CRLF, from this. -* -* @param out -* an object whose "value" property will be set to the first line of text -* present in this, sans CRLF, if this contains a full CRLF-delimited line -* of text; if this doesn't contain enough data, the value of the property -* is undefined -* @returns boolean -* true if a full line of data could be read from the data in this, false -* otherwise -*/ - readLine: function(out) - { - var data = this._data; - var length = findCRLF(data); - if (length < 0) - return false; - - // - // We have the index of the CR, so remove all the characters, including - // CRLF, from the array with splice, and convert the removed array into the - // corresponding string, from which we then strip the trailing CRLF. - // - // Getting the line in this matter acknowledges that substring is an O(1) - // operation in SpiderMonkey because strings are immutable, whereas two - // splices, both from the beginning of the data, are less likely to be as - // cheap as a single splice plus two extra character conversions. - // - var line = String.fromCharCode.apply(null, data.splice(0, length + 2)); - out.value = line.substring(0, length); - - return true; - }, - - /** -* Removes the bytes currently within this and returns them in an array. -* -* @returns Array -* the bytes within this when this method is called -*/ - purge: function() - { - var data = this._data; - this._data = []; - return data; - } -}; - - - -/** -* Creates a request-handling function for an nsIHttpRequestHandler object. -*/ -function createHandlerFunc(handler) -{ - return function(metadata, response) { handler.handle(metadata, response); }; -} - - -/** -* The default handler for directories; writes an HTML response containing a -* slightly-formatted directory listing. -*/ -function defaultIndexHandler(metadata, response) -{ - response.setHeader("Content-Type", "text/html", false); - - var path = htmlEscape(decodeURI(metadata.path)); - - // - // Just do a very basic bit of directory listings -- no need for too much - // fanciness, especially since we don't have a style sheet in which we can - // stick rules (don't want to pollute the default path-space). - // - - var body = '\ -\ -' + path + '\ -\ -\ -

' + path + '

\ -
    '; - - var directory = metadata.getProperty("directory").QueryInterface(Ci.nsILocalFile); - NS_ASSERT(directory && directory.isDirectory()); - - var fileList = []; - var files = directory.directoryEntries; - while (files.hasMoreElements()) - { - var f = files.getNext().QueryInterface(Ci.nsIFile); - var name = f.leafName; - if (!f.isHidden() && - (name.charAt(name.length - 1) != HIDDEN_CHAR || - name.charAt(name.length - 2) == HIDDEN_CHAR)) - fileList.push(f); - } - - fileList.sort(fileSort); - - for (var i = 0; i < fileList.length; i++) - { - var file = fileList[i]; - try - { - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - var sep = file.isDirectory() ? "/" : ""; - - // Note: using " to delimit the attribute here because encodeURIComponent - // passes through '. - var item = '
  1. ' + - htmlEscape(name) + sep + - '
  2. '; - - body += item; - } - catch (e) { /* some file system error, ignore the file */ } - } - - body += '
\ -\ -'; - - response.bodyOutputStream.write(body, body.length); -} - -/** -* Sorts a and b (nsIFile objects) into an aesthetically pleasing order. -*/ -function fileSort(a, b) -{ - var dira = a.isDirectory(), dirb = b.isDirectory(); - - if (dira && !dirb) - return -1; - if (dirb && !dira) - return 1; - - var namea = a.leafName.toLowerCase(), nameb = b.leafName.toLowerCase(); - return nameb > namea ? -1 : 1; -} - - -/** -* Converts an externally-provided path into an internal path for use in -* determining file mappings. -* -* @param path -* the path to convert -* @param encoded -* true if the given path should be passed through decodeURI prior to -* conversion -* @throws URIError -* if path is incorrectly encoded -*/ -function toInternalPath(path, encoded) -{ - if (encoded) - path = decodeURI(path); - - var comps = path.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - if (comp.charAt(comp.length - 1) == HIDDEN_CHAR) - comps[i] = comp + HIDDEN_CHAR; - } - return comps.join("/"); -} - - -/** -* Adds custom-specified headers for the given file to the given response, if -* any such headers are specified. -* -* @param file -* the file on the disk which is to be written -* @param metadata -* metadata about the incoming request -* @param response -* the Response to which any specified headers/data should be written -* @throws HTTP_500 -* if an error occurred while processing custom-specified headers -*/ -function maybeAddHeaders(file, metadata, response) -{ - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - - var headerFile = file.parent; - headerFile.append(name + HEADERS_SUFFIX); - - if (!headerFile.exists()) - return; - - const PR_RDONLY = 0x01; - var fis = new FileInputStream(headerFile, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0); - lis.QueryInterface(Ci.nsIUnicharLineInputStream); - - var line = {value: ""}; - var more = lis.readLine(line); - - if (!more && line.value == "") - return; - - - // request line - - var status = line.value; - if (status.indexOf("HTTP ") == 0) - { - status = status.substring(5); - var space = status.indexOf(" "); - var code, description; - if (space < 0) - { - code = status; - description = ""; - } - else - { - code = status.substring(0, space); - description = status.substring(space + 1, status.length); - } - - response.setStatusLine(metadata.httpVersion, parseInt(code, 10), description); - - line.value = ""; - more = lis.readLine(line); - } - - // headers - while (more || line.value != "") - { - var header = line.value; - var colon = header.indexOf(":"); - - response.setHeader(header.substring(0, colon), - header.substring(colon + 1, header.length), - false); // allow overriding server-set headers - - line.value = ""; - more = lis.readLine(line); - } - } - catch (e) - { - dumpn("WARNING: error in headers for " + metadata.path + ": " + e); - throw HTTP_500; - } - finally - { - fis.close(); - } -} - - -/** -* An object which handles requests for a server, executing default and -* overridden behaviors as instructed by the code which uses and manipulates it. -* Default behavior includes the paths / and /trace (diagnostics), with some -* support for HTTP error pages for various codes and fallback to HTTP 500 if -* those codes fail for any reason. -* -* @param server : nsHttpServer -* the server in which this handler is being used -*/ -function ServerHandler(server) -{ - // FIELDS - - /** -* The nsHttpServer instance associated with this handler. -*/ - this._server = server; - - /** -* A FileMap object containing the set of path->nsILocalFile mappings for -* all directory mappings set in the server (e.g., "/" for /var/www/html/, -* "/foo/bar/" for /local/path/, and "/foo/bar/baz/" for /local/path2). -* -* Note carefully: the leading and trailing "/" in each path (not file) are -* removed before insertion to simplify the code which uses this. You have -* been warned! -*/ - this._pathDirectoryMap = new FileMap(); - - /** -* Custom request handlers for the server in which this resides. Path-handler -* pairs are stored as property-value pairs in this property. -* -* @see ServerHandler.prototype._defaultPaths -*/ - this._overridePaths = {}; - - /** -* Custom request handlers for the server in which this resides. Prefix-handler -* pairs are stored as property-value pairs in this property. -*/ - this._overridePrefixes = {}; - - /** -* Custom request handlers for the error handlers in the server in which this -* resides. Path-handler pairs are stored as property-value pairs in this -* property. -* -* @see ServerHandler.prototype._defaultErrors -*/ - this._overrideErrors = {}; - - /** -* Maps file extensions to their MIME types in the server, overriding any -* mapping that might or might not exist in the MIME service. -*/ - this._mimeMappings = {}; - - /** -* The default handler for requests for directories, used to serve directories -* when no index file is present. -*/ - this._indexHandler = defaultIndexHandler; - - /** Per-path state storage for the server. */ - this._state = {}; - - /** Entire-server state storage. */ - this._sharedState = {}; - - /** Entire-server state storage for nsISupports values. */ - this._objectState = {}; -} -ServerHandler.prototype = -{ - // PUBLIC API - - /** -* Handles a request to this server, responding to the request appropriately -* and initiating server shutdown if necessary. -* -* This method never throws an exception. -* -* @param connection : Connection -* the connection for this request -*/ - handleResponse: function(connection) - { - var request = connection.request; - var response = new Response(connection); - - var path = request.path; - dumpn("*** path == " + path); - - try - { - try - { - if (path in this._overridePaths) - { - // explicit paths first, then files based on existing directory mappings, - // then (if the file doesn't exist) built-in server default paths - dumpn("calling override for " + path); - this._overridePaths[path](request, response); - } - else - { - let longestPrefix = ""; - for (let prefix in this._overridePrefixes) - { - if (prefix.length > longestPrefix.length && path.startsWith(prefix)) - { - longestPrefix = prefix; - } - } - if (longestPrefix.length > 0) - { - dumpn("calling prefix override for " + longestPrefix); - this._overridePrefixes[longestPrefix](request, response); - } - else - { - this._handleDefault(request, response); - } - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - if (!(e instanceof HttpError)) - { - dumpn("*** unexpected error: e == " + e); - throw HTTP_500; - } - if (e.code !== 404) - throw e; - - dumpn("*** default: " + (path in this._defaultPaths)); - - response = new Response(connection); - if (path in this._defaultPaths) - this._defaultPaths[path](request, response); - else - throw HTTP_404; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - var errorCode = "internal"; - - try - { - if (!(e instanceof HttpError)) - throw e; - - errorCode = e.code; - dumpn("*** errorCode == " + errorCode); - - response = new Response(connection); - if (e.customErrorHandling) - e.customErrorHandling(response); - this._handleError(errorCode, request, response); - return; - } - catch (e2) - { - dumpn("*** error handling " + errorCode + " error: " + - "e2 == " + e2 + ", shutting down server"); - - connection.server._requestQuit(); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (!file) - { - dumpn("*** unregistering '" + path + "' mapping"); - delete this._overridePaths[path]; - return; - } - - dumpn("*** registering '" + path + "' as mapping to " + file.path); - file = file.clone(); - - var self = this; - this._overridePaths[path] = - function(request, response) - { - if (!file.exists()) - throw HTTP_404; - - response.setStatusLine(request.httpVersion, 200, "OK"); - self._writeFileResponse(request, file, response, 0, file.fileSize); - }; - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - // XXX true path validation! - if (path.charAt(0) != "/") - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePaths, path); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - // XXX true prefix validation! - if (!(prefix.startsWith("/") && prefix.endsWith("/"))) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePrefixes, prefix); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // strip off leading and trailing '/' so that we can use lastIndexOf when - // determining exactly how a path maps onto a mapped directory -- - // conditional is required here to deal with "/".substring(1, 0) being - // converted to "/".substring(0, 1) per the JS specification - var key = path.length == 1 ? "" : path.substring(1, path.length - 1); - - // the path-to-directory mapping code requires that the first character not - // be "/", or it will go into an infinite loop - if (key.charAt(0) == "/") - throw Cr.NS_ERROR_INVALID_ARG; - - key = toInternalPath(key, false); - - if (directory) - { - dumpn("*** mapping '" + path + "' to the location " + directory.path); - this._pathDirectoryMap.put(key, directory); - } - else - { - dumpn("*** removing mapping for '" + path + "'"); - this._pathDirectoryMap.put(key, null); - } - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(err, handler) - { - if (!(err in HTTP_ERROR_CODES)) - dumpn("*** WARNING: registering non-HTTP/1.1 error code " + - "(" + err + ") handler -- was this intentional?"); - - this._handlerToField(handler, this._overrideErrors, err); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - if (!handler) - handler = defaultIndexHandler; - else if (typeof(handler) != "function") - handler = createHandlerFunc(handler); - - this._indexHandler = handler; - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - if (!type) - delete this._mimeMappings[ext]; - else - this._mimeMappings[ext] = headerUtils.normalizeFieldValue(type); - }, - - // PRIVATE API - - /** -* Sets or remove (if handler is null) a handler in an object with a key. -* -* @param handler -* a handler, either function or an nsIHttpRequestHandler -* @param dict -* The object to attach the handler to. -* @param key -* The field name of the handler. -*/ - _handlerToField: function(handler, dict, key) - { - // for convenience, handler can be a function if this is run from xpcshell - if (typeof(handler) == "function") - dict[key] = handler; - else if (handler) - dict[key] = createHandlerFunc(handler); - else - delete dict[key]; - }, - - /** -* Handles a request which maps to a file in the local filesystem (if a base -* path has already been set; otherwise the 404 error is thrown). -* -* @param metadata : Request -* metadata for the incoming request -* @param response : Response -* an uninitialized Response to the given request, to be initialized by a -* request handler -* @throws HTTP_### -* if an HTTP error occurred (usually HTTP_404); note that in this case the -* calling code must handle post-processing of the response -*/ - _handleDefault: function(metadata, response) - { - dumpn("*** _handleDefault()"); - - response.setStatusLine(metadata.httpVersion, 200, "OK"); - - var path = metadata.path; - NS_ASSERT(path.charAt(0) == "/", "invalid path: <" + path + ">"); - - // determine the actual on-disk file; this requires finding the deepest - // path-to-directory mapping in the requested URL - var file = this._getFileForPath(path); - - // the "file" might be a directory, in which case we either serve the - // contained index.html or make the index handler write the response - if (file.exists() && file.isDirectory()) - { - file.append("index.html"); // make configurable? - if (!file.exists() || file.isDirectory()) - { - metadata._ensurePropertyBag(); - metadata._bag.setPropertyAsInterface("directory", file.parent); - this._indexHandler(metadata, response); - return; - } - } - - // alternately, the file might not exist - if (!file.exists()) - throw HTTP_404; - - var start, end; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1) && - metadata.hasHeader("Range") && - this._getTypeFromFile(file) !== SJS_TYPE) - { - var rangeMatch = metadata.getHeader("Range").match(/^bytes=(\d+)?-(\d+)?$/); - if (!rangeMatch) - throw HTTP_400; - - if (rangeMatch[1] !== undefined) - start = parseInt(rangeMatch[1], 10); - - if (rangeMatch[2] !== undefined) - end = parseInt(rangeMatch[2], 10); - - if (start === undefined && end === undefined) - throw HTTP_400; - - // No start given, so the end is really the count of bytes from the - // end of the file. - if (start === undefined) - { - start = Math.max(0, file.fileSize - end); - end = file.fileSize - 1; - } - - // start and end are inclusive - if (end === undefined || end >= file.fileSize) - end = file.fileSize - 1; - - if (start !== undefined && start >= file.fileSize) { - var HTTP_416 = new HttpError(416, "Requested Range Not Satisfiable"); - HTTP_416.customErrorHandling = function(errorResponse) - { - maybeAddHeaders(file, metadata, errorResponse); - }; - throw HTTP_416; - } - - if (end < start) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - start = 0; - end = file.fileSize - 1; - } - else - { - response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); - var contentRange = "bytes " + start + "-" + end + "/" + file.fileSize; - response.setHeader("Content-Range", contentRange); - } - } - else - { - start = 0; - end = file.fileSize - 1; - } - - // finally... - dumpn("*** handling '" + path + "' as mapping to " + file.path + " from " + - start + " to " + end + " inclusive"); - this._writeFileResponse(metadata, file, response, start, end - start + 1); - }, - - /** -* Writes an HTTP response for the given file, including setting headers for -* file metadata. -* -* @param metadata : Request -* the Request for which a response is being generated -* @param file : nsILocalFile -* the file which is to be sent in the response -* @param response : Response -* the response to which the file should be written -* @param offset: uint -* the byte offset to skip to when writing -* @param count: uint -* the number of bytes to write -*/ - _writeFileResponse: function(metadata, file, response, offset, count) - { - const PR_RDONLY = 0x01; - - var type = this._getTypeFromFile(file); - if (type === SJS_TYPE) - { - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var sis = new ScriptableInputStream(fis); - var s = Cu.Sandbox(gGlobalObject); - s.importFunction(dump, "dump"); - - // Define a basic key-value state-preservation API across requests, with - // keys initially corresponding to the empty string. - var self = this; - var path = metadata.path; - s.importFunction(function getState(k) - { - return self._getState(path, k); - }); - s.importFunction(function setState(k, v) - { - self._setState(path, k, v); - }); - s.importFunction(function getSharedState(k) - { - return self._getSharedState(k); - }); - s.importFunction(function setSharedState(k, v) - { - self._setSharedState(k, v); - }); - s.importFunction(function getObjectState(k, callback) - { - callback(self._getObjectState(k)); - }); - s.importFunction(function setObjectState(k, v) - { - self._setObjectState(k, v); - }); - s.importFunction(function registerPathHandler(p, h) - { - self.registerPathHandler(p, h); - }); - - // Make it possible for sjs files to access their location - this._setState(path, "__LOCATION__", file.path); - - try - { - // Alas, the line number in errors dumped to console when calling the - // request handler is simply an offset from where we load the SJS file. - // Work around this in a reasonably non-fragile way by dynamically - // getting the line number where we evaluate the SJS file. Don't - // separate these two lines! - var line = new Error().lineNumber; - Cu.evalInSandbox(sis.read(file.fileSize), s); - } - catch (e) - { - dumpn("*** syntax error in SJS at " + file.path + ": " + e); - throw HTTP_500; - } - - try - { - s.handleRequest(metadata, response); - } - catch (e) - { - dump("*** error running SJS at " + file.path + ": " + - e + " on line " + - (e instanceof Error - ? e.lineNumber + " in httpd.js" - : (e.lineNumber - line)) + "\n"); - throw HTTP_500; - } - } - finally - { - fis.close(); - } - } - else - { - try - { - response.setHeader("Last-Modified", - toDateString(file.lastModifiedTime), - false); - } - catch (e) { /* lastModifiedTime threw, ignore */ } - - response.setHeader("Content-Type", type, false); - maybeAddHeaders(file, metadata, response); - response.setHeader("Content-Length", "" + count, false); - - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - offset = offset || 0; - count = count || file.fileSize; - NS_ASSERT(offset === 0 || offset < file.fileSize, "bad offset"); - NS_ASSERT(count >= 0, "bad count"); - NS_ASSERT(offset + count <= file.fileSize, "bad total data size"); - - try - { - if (offset !== 0) - { - // Seek (or read, if seeking isn't supported) to the correct offset so - // the data sent to the client matches the requested range. - if (fis instanceof Ci.nsISeekableStream) - fis.seek(Ci.nsISeekableStream.NS_SEEK_SET, offset); - else - new ScriptableInputStream(fis).read(offset); - } - } - catch (e) - { - fis.close(); - throw e; - } - - let writeMore = function writeMore() - { - gThreadManager.currentThread - .dispatch(writeData, Ci.nsIThread.DISPATCH_NORMAL); - } - - var input = new BinaryInputStream(fis); - var output = new BinaryOutputStream(response.bodyOutputStream); - var writeData = - { - run: function() - { - var chunkSize = Math.min(65536, count); - count -= chunkSize; - NS_ASSERT(count >= 0, "underflow"); - - try - { - var data = input.readByteArray(chunkSize); - NS_ASSERT(data.length === chunkSize, - "incorrect data returned? got " + data.length + - ", expected " + chunkSize); - output.writeByteArray(data, data.length); - if (count === 0) - { - fis.close(); - response.finish(); - } - else - { - writeMore(); - } - } - catch (e) - { - try - { - fis.close(); - } - finally - { - response.finish(); - } - throw e; - } - } - }; - - writeMore(); - - // Now that we know copying will start, flag the response as async. - response.processAsync(); - } - }, - - /** -* Get the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getState: function(path, k) - { - var state = this._state; - if (path in state && k in state[path]) - return state[path][k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setState: function(path, k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - var state = this._state; - if (!(path in state)) - state[path] = {}; - state[path][k] = v; - }, - - /** -* Get the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getSharedState: function(k) - { - var state = this._sharedState; - if (k in state) - return state[k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setSharedState: function(k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - this._sharedState[k] = v; - }, - - /** -* Returns the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be returned -* @returns nsISupports -* the corresponding object, or null if none was present -*/ - _getObjectState: function(k) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - return this._objectState[k] || null; - }, - - /** -* Sets the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be set -* @param v : nsISupports -* the object to be associated with the given key; may be null -*/ - _setObjectState: function(k, v) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - if (typeof v !== "object") - throw new Error("non-object value passed"); - if (v && !("QueryInterface" in v)) - { - throw new Error("must pass an nsISupports; use wrappedJSObject to ease " + - "pain when using the server from JS"); - } - - this._objectState[k] = v; - }, - - /** -* Gets a content-type for the given file, first by checking for any custom -* MIME-types registered with this handler for the file's extension, second by -* asking the global MIME service for a content-type, and finally by failing -* over to application/octet-stream. -* -* @param file : nsIFile -* the nsIFile for which to get a file type -* @returns string -* the best content-type which can be determined for the file -*/ - _getTypeFromFile: function(file) - { - try - { - var name = file.leafName; - var dot = name.lastIndexOf("."); - if (dot > 0) - { - var ext = name.slice(dot + 1); - if (ext in this._mimeMappings) - return this._mimeMappings[ext]; - } - return Cc["@mozilla.org/uriloader/external-helper-app-service;1"] - .getService(Ci.nsIMIMEService) - .getTypeFromFile(file); - } - catch (e) - { - return "application/octet-stream"; - } - }, - - /** -* Returns the nsILocalFile which corresponds to the path, as determined using -* all registered path->directory mappings and any paths which are explicitly -* overridden. -* -* @param path : string -* the server path for which a file should be retrieved, e.g. "/foo/bar" -* @throws HttpError -* when the correct action is the corresponding HTTP error (i.e., because no -* mapping was found for a directory in path, the referenced file doesn't -* exist, etc.) -* @returns nsILocalFile -* the file to be sent as the response to a request for the path -*/ - _getFileForPath: function(path) - { - // decode and add underscores as necessary - try - { - path = toInternalPath(path, true); - } - catch (e) - { - throw HTTP_400; // malformed path - } - - // next, get the directory which contains this path - var pathMap = this._pathDirectoryMap; - - // An example progression of tmp for a path "/foo/bar/baz/" might be: - // "foo/bar/baz/", "foo/bar/baz", "foo/bar", "foo", "" - var tmp = path.substring(1); - while (true) - { - // do we have a match for current head of the path? - var file = pathMap.get(tmp); - if (file) - { - // XXX hack; basically disable showing mapping for /foo/bar/ when the - // requested path was /foo/bar, because relative links on the page - // will all be incorrect -- we really need the ability to easily - // redirect here instead - if (tmp == path.substring(1) && - tmp.length != 0 && - tmp.charAt(tmp.length - 1) != "/") - file = null; - else - break; - } - - // if we've finished trying all prefixes, exit - if (tmp == "") - break; - - tmp = tmp.substring(0, tmp.lastIndexOf("/")); - } - - // no mapping applies, so 404 - if (!file) - throw HTTP_404; - - - // last, get the file for the path within the determined directory - var parentFolder = file.parent; - var dirIsRoot = (parentFolder == null); - - // Strategy here is to append components individually, making sure we - // never move above the given directory; this allows paths such as - // "/foo/../bar" but prevents paths such as "/../base-sibling"; - // this component-wise approach also means the code works even on platforms - // which don't use "/" as the directory separator, such as Windows - var leafPath = path.substring(tmp.length + 1); - var comps = leafPath.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - - if (comp == "..") - file = file.parent; - else if (comp == "." || comp == "") - continue; - else - file.append(comp); - - if (!dirIsRoot && file.equals(parentFolder)) - throw HTTP_403; - } - - return file; - }, - - /** -* Writes the error page for the given HTTP error code over the given -* connection. -* -* @param errorCode : uint -* the HTTP error code to be used -* @param connection : Connection -* the connection on which the error occurred -*/ - handleError: function(errorCode, connection) - { - var response = new Response(connection); - - dumpn("*** error in request: " + errorCode); - - this._handleError(errorCode, new Request(connection.port), response); - }, - - /** -* Handles a request which generates the given error code, using the -* user-defined error handler if one has been set, gracefully falling back to -* the x00 status code if the code has no handler, and failing to status code -* 500 if all else fails. -* -* @param errorCode : uint -* the HTTP error which is to be returned -* @param metadata : Request -* metadata for the request, which will often be incomplete since this is an -* error -* @param response : Response -* an uninitialized Response should be initialized when this method -* completes with information which represents the desired error code in the -* ideal case or a fallback code in abnormal circumstances (i.e., 500 is a -* fallback for 505, per HTTP specs) -*/ - _handleError: function(errorCode, metadata, response) - { - if (!metadata) - throw Cr.NS_ERROR_NULL_POINTER; - - var errorX00 = errorCode - (errorCode % 100); - - try - { - if (!(errorCode in HTTP_ERROR_CODES)) - dumpn("*** WARNING: requested invalid error: " + errorCode); - - // RFC 2616 says that we should try to handle an error by its class if we - // can't otherwise handle it -- if that fails, we revert to handling it as - // a 500 internal server error, and if that fails we throw and shut down - // the server - - // actually handle the error - try - { - if (errorCode in this._overrideErrors) - this._overrideErrors[errorCode](metadata, response); - else - this._defaultErrors[errorCode](metadata, response); - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - // don't retry the handler that threw - if (errorX00 == errorCode) - throw HTTP_500; - - dumpn("*** error in handling for error code " + errorCode + ", " + - "falling back to " + errorX00 + "..."); - response = new Response(response._connection); - if (errorX00 in this._overrideErrors) - this._overrideErrors[errorX00](metadata, response); - else if (errorX00 in this._defaultErrors) - this._defaultErrors[errorX00](metadata, response); - else - throw HTTP_500; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(); - return; - } - - // we've tried everything possible for a meaningful error -- now try 500 - dumpn("*** error in handling for error code " + errorX00 + ", falling " + - "back to 500..."); - - try - { - response = new Response(response._connection); - if (500 in this._overrideErrors) - this._overrideErrors[500](metadata, response); - else - this._defaultErrors[500](metadata, response); - } - catch (e2) - { - dumpn("*** multiple errors in default error handlers!"); - dumpn("*** e == " + e + ", e2 == " + e2); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // FIELDS - - /** -* This object contains the default handlers for the various HTTP error codes. -*/ - _defaultErrors: - { - 400: function(metadata, response) - { - // none of the data in metadata is reliable, so hard-code everything here - response.setStatusLine("1.1", 400, "Bad Request"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Bad request\n"; - response.bodyOutputStream.write(body, body.length); - }, - 403: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 403, "Forbidden"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -403 Forbidden\ -\ -

403 Forbidden

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 404: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 404, "Not Found"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -404 Not Found\ -\ -

404 Not Found

\ -

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

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 416: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 416, - "Requested Range Not Satisfiable"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -\ -416 Requested Range Not Satisfiable\ -\ -

416 Requested Range Not Satisfiable

\ -

The byte range was not valid for the\ -requested resource.\ -

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 500: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 500, - "Internal Server Error"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -500 Internal Server Error\ -\ -

500 Internal Server Error

\ -

Something's broken in this server and\ -needs to be fixed.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 501: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 501, "Not Implemented"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -501 Not Implemented\ -\ -

501 Not Implemented

\ -

This server is not (yet) Apache.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 505: function(metadata, response) - { - response.setStatusLine("1.1", 505, "HTTP Version Not Supported"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -505 HTTP Version Not Supported\ -\ -

505 HTTP Version Not Supported

\ -

This server only supports HTTP/1.0 and HTTP/1.1\ -connections.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - } - }, - - /** -* Contains handlers for the default set of URIs contained in this server. -*/ - _defaultPaths: - { - "/": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -httpd.js\ -\ -

httpd.js

\ -

If you're seeing this page, httpd.js is up and\ -serving requests! Now set a base path and serve some\ -files!

\ -\ -"; - - response.bodyOutputStream.write(body, body.length); - }, - - "/trace": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Request-URI: " + - metadata.scheme + "://" + metadata.host + ":" + metadata.port + - metadata.path + "\n\n"; - body += "Request (semantically equivalent, slightly reformatted):\n\n"; - body += metadata.method + " " + metadata.path; - - if (metadata.queryString) - body += "?" + metadata.queryString; - - body += " HTTP/" + metadata.httpVersion + "\r\n"; - - var headEnum = metadata.headers; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - body += fieldName + ": " + metadata.getHeader(fieldName) + "\r\n"; - } - - response.bodyOutputStream.write(body, body.length); - } - } -}; - - -/** -* Maps absolute paths to files on the local file system (as nsILocalFiles). -*/ -function FileMap() -{ - /** Hash which will map paths to nsILocalFiles. */ - this._map = {}; -} -FileMap.prototype = -{ - // PUBLIC API - - /** -* Maps key to a clone of the nsILocalFile value if value is non-null; -* otherwise, removes any extant mapping for key. -* -* @param key : string -* string to which a clone of value is mapped -* @param value : nsILocalFile -* the file to map to key, or null to remove a mapping -*/ - put: function(key, value) - { - if (value) - this._map[key] = value.clone(); - else - delete this._map[key]; - }, - - /** -* Returns a clone of the nsILocalFile mapped to key, or null if no such -* mapping exists. -* -* @param key : string -* key to which the returned file maps -* @returns nsILocalFile -* a clone of the mapped file, or null if no mapping exists -*/ - get: function(key) - { - var val = this._map[key]; - return val ? val.clone() : null; - } -}; - - -// Response CONSTANTS - -// token = * -// CHAR = -// CTL = -// separators = "(" | ")" | "<" | ">" | "@" -// | "," | ";" | ":" | "\" | <"> -// | "/" | "[" | "]" | "?" | "=" -// | "{" | "}" | SP | HT -const IS_TOKEN_ARRAY = - [0, 0, 0, 0, 0, 0, 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 0, 0, 0, 0, 0, 0, 0, 0, // 24 - - 0, 1, 0, 1, 1, 1, 1, 1, // 32 - 0, 0, 1, 1, 0, 1, 1, 0, // 40 - 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 1, 1, 0, 0, 0, 0, 0, 0, // 56 - - 0, 1, 1, 1, 1, 1, 1, 1, // 64 - 1, 1, 1, 1, 1, 1, 1, 1, // 72 - 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 1, 1, 1, 0, 0, 0, 1, 1, // 88 - - 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 1, 1, 1, 1, 1, 1, 1, 1, // 104 - 1, 1, 1, 1, 1, 1, 1, 1, // 112 - 1, 1, 1, 0, 1, 0, 1]; // 120 - - -/** -* Determines whether the given character code is a CTL. -* -* @param code : uint -* the character code -* @returns boolean -* true if code is a CTL, false otherwise -*/ -function isCTL(code) -{ - return (code >= 0 && code <= 31) || (code == 127); -} - -/** -* Represents a response to an HTTP request, encapsulating all details of that -* response. This includes all headers, the HTTP version, status code and -* explanation, and the entity itself. -* -* @param connection : Connection -* the connection over which this response is to be written -*/ -function Response(connection) -{ - /** The connection over which this response will be written. */ - this._connection = connection; - - /** -* The HTTP version of this response; defaults to 1.1 if not set by the -* handler. -*/ - this._httpVersion = nsHttpVersion.HTTP_1_1; - - /** -* The HTTP code of this response; defaults to 200. -*/ - this._httpCode = 200; - - /** -* The description of the HTTP code in this response; defaults to "OK". -*/ - this._httpDescription = "OK"; - - /** -* An nsIHttpHeaders object in which the headers in this response should be -* stored. This property is null after the status line and headers have been -* written to the network, and it may be modified up until it is cleared, -* except if this._finished is set first (in which case headers are written -* asynchronously in response to a finish() call not preceded by -* flushHeaders()). -*/ - this._headers = new nsHttpHeaders(); - - /** -* Set to true when this response is ended (completely constructed if possible -* and the connection closed); further actions on this will then fail. -*/ - this._ended = false; - - /** -* A stream used to hold data written to the body of this response. -*/ - this._bodyOutputStream = null; - - /** -* A stream containing all data that has been written to the body of this -* response so far. (Async handlers make the data contained in this -* unreliable as a way of determining content length in general, but auxiliary -* saved information can sometimes be used to guarantee reliability.) -*/ - this._bodyInputStream = null; - - /** -* A stream copier which copies data to the network. It is initially null -* until replaced with a copier for response headers; when headers have been -* fully sent it is replaced with a copier for the response body, remaining -* so for the duration of response processing. -*/ - this._asyncCopier = null; - - /** -* True if this response has been designated as being processed -* asynchronously rather than for the duration of a single call to -* nsIHttpRequestHandler.handle. -*/ - this._processAsync = false; - - /** -* True iff finish() has been called on this, signaling that no more changes -* to this may be made. -*/ - this._finished = false; - - /** -* True iff powerSeized() has been called on this, signaling that this -* response is to be handled manually by the response handler (which may then -* send arbitrary data in response, even non-HTTP responses). -*/ - this._powerSeized = false; -} -Response.prototype = -{ - // PUBLIC CONSTRUCTION API - - // - // see nsIHttpResponse.bodyOutputStream - // - get bodyOutputStream() - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - if (!this._bodyOutputStream) - { - var pipe = new Pipe(true, false, Response.SEGMENT_SIZE, PR_UINT32_MAX, - null); - this._bodyOutputStream = pipe.outputStream; - this._bodyInputStream = pipe.inputStream; - if (this._processAsync || this._powerSeized) - this._startAsyncProcessor(); - } - - return this._bodyOutputStream; - }, - - // - // see nsIHttpResponse.write - // - write: function(data) - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - var dataAsString = String(data); - this.bodyOutputStream.write(dataAsString, dataAsString.length); - }, - - // - // see nsIHttpResponse.setStatusLine - // - setStatusLine: function(httpVersion, code, description) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - if (!(code >= 0 && code < 1000)) - throw Cr.NS_ERROR_INVALID_ARG; - - try - { - var httpVer; - // avoid version construction for the most common cases - if (!httpVersion || httpVersion == "1.1") - httpVer = nsHttpVersion.HTTP_1_1; - else if (httpVersion == "1.0") - httpVer = nsHttpVersion.HTTP_1_0; - else - httpVer = new nsHttpVersion(httpVersion); - } - catch (e) - { - throw Cr.NS_ERROR_INVALID_ARG; - } - - // Reason-Phrase = * - // TEXT = - // - // XXX this ends up disallowing octets which aren't Unicode, I think -- not - // much to do if description is IDL'd as string - if (!description) - description = ""; - for (var i = 0; i < description.length; i++) - if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t") - throw Cr.NS_ERROR_INVALID_ARG; - - // set the values only after validation to preserve atomicity - this._httpDescription = description; - this._httpCode = code; - this._httpVersion = httpVer; - }, - - // - // see nsIHttpResponse.setHeader - // - setHeader: function(name, value, merge) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - this._headers.setHeader(name, value, merge); - }, - - // - // see nsIHttpResponse.processAsync - // - processAsync: function() - { - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._processAsync) - return; - this._ensureAlive(); - - dumpn("*** processing connection " + this._connection.number + " async"); - this._processAsync = true; - - /* -* Either the bodyOutputStream getter or this method is responsible for -* starting the asynchronous processor and catching writes of data to the -* response body of async responses as they happen, for the purpose of -* forwarding those writes to the actual connection's output stream. -* If bodyOutputStream is accessed first, calling this method will create -* the processor (when it first is clear that body data is to be written -* immediately, not buffered). If this method is called first, accessing -* bodyOutputStream will create the processor. If only this method is -* called, we'll write nothing, neither headers nor the nonexistent body, -* until finish() is called. Since that delay is easily avoided by simply -* getting bodyOutputStream or calling write(""), we don't worry about it. -*/ - if (this._bodyOutputStream && !this._asyncCopier) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.seizePower - // - seizePower: function() - { - if (this._processAsync) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - return; - this._ensureAlive(); - - dumpn("*** forcefully seizing power over connection " + - this._connection.number + "..."); - - // Purge any already-written data without sending it. We could as easily - // swap out the streams entirely, but that makes it possible to acquire and - // unknowingly use a stale reference, so we require there only be one of - // each stream ever for any response to avoid this complication. - if (this._asyncCopier) - this._asyncCopier.cancel(Cr.NS_BINDING_ABORTED); - this._asyncCopier = null; - if (this._bodyOutputStream) - { - var input = new BinaryInputStream(this._bodyInputStream); - var avail; - while ((avail = input.available()) > 0) - input.readByteArray(avail); - } - - this._powerSeized = true; - if (this._bodyOutputStream) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.finish - // - finish: function() - { - if (!this._processAsync && !this._powerSeized) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._finished) - return; - - dumpn("*** finishing connection " + this._connection.number); - this._startAsyncProcessor(); // in case bodyOutputStream was never accessed - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - this._finished = true; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpResponse) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // POST-CONSTRUCTION API (not exposed externally) - - /** -* The HTTP version number of this, as a string (e.g. "1.1"). -*/ - get httpVersion() - { - this._ensureAlive(); - return this._httpVersion.toString(); - }, - - /** -* The HTTP status code of this response, as a string of three characters per -* RFC 2616. -*/ - get httpCode() - { - this._ensureAlive(); - - var codeString = (this._httpCode < 10 ? "0" : "") + - (this._httpCode < 100 ? "0" : "") + - this._httpCode; - return codeString; - }, - - /** -* The description of the HTTP status code of this response, or "" if none is -* set. -*/ - get httpDescription() - { - this._ensureAlive(); - - return this._httpDescription; - }, - - /** -* The headers in this response, as an nsHttpHeaders object. -*/ - get headers() - { - this._ensureAlive(); - - return this._headers; - }, - - // - // see nsHttpHeaders.getHeader - // - getHeader: function(name) - { - this._ensureAlive(); - - return this._headers.getHeader(name); - }, - - /** -* Determines whether this response may be abandoned in favor of a newly -* constructed response. A response may be abandoned only if it is not being -* sent asynchronously and if raw control over it has not been taken from the -* server. -* -* @returns boolean -* true iff no data has been written to the network -*/ - partiallySent: function() - { - dumpn("*** partiallySent()"); - return this._processAsync || this._powerSeized; - }, - - /** -* If necessary, kicks off the remaining request processing needed to be done -* after a request handler performs its initial work upon this response. -*/ - complete: function() - { - dumpn("*** complete()"); - if (this._processAsync || this._powerSeized) - { - NS_ASSERT(this._processAsync ^ this._powerSeized, - "can't both send async and relinquish power"); - return; - } - - NS_ASSERT(!this.partiallySent(), "completing a partially-sent response?"); - - this._startAsyncProcessor(); - - // Now make sure we finish processing this request! - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - }, - - /** -* Abruptly ends processing of this response, usually due to an error in an -* incoming request but potentially due to a bad error handler. Since we -* cannot handle the error in the usual way (giving an HTTP error page in -* response) because data may already have been sent (or because the response -* might be expected to have been generated asynchronously or completely from -* scratch by the handler), we stop processing this response and abruptly -* close the connection. -* -* @param e : Error -* the exception which precipitated this abort, or null if no such exception -* was generated -*/ - abort: function(e) - { - dumpn("*** abort(<" + e + ">)"); - - // This response will be ended by the processor if one was created. - var copier = this._asyncCopier; - if (copier) - { - // We dispatch asynchronously here so that any pending writes of data to - // the connection will be deterministically written. This makes it easier - // to specify exact behavior, and it makes observable behavior more - // predictable for clients. Note that the correctness of this depends on - // callbacks in response to _waitToReadData in WriteThroughCopier - // happening asynchronously with respect to the actual writing of data to - // bodyOutputStream, as they currently do; if they happened synchronously, - // an event which ran before this one could write more data to the - // response body before we get around to canceling the copier. We have - // tests for this in test_seizepower.js, however, and I can't think of a - // way to handle both cases without removing bodyOutputStream access and - // moving its effective write(data, length) method onto Response, which - // would be slower and require more code than this anyway. - gThreadManager.currentThread.dispatch({ - run: function() - { - dumpn("*** canceling copy asynchronously..."); - copier.cancel(Cr.NS_ERROR_UNEXPECTED); - } - }, Ci.nsIThread.DISPATCH_NORMAL); - } - else - { - this.end(); - } - }, - - /** -* Closes this response's network connection, marks the response as finished, -* and notifies the server handler that the request is done being processed. -*/ - end: function() - { - NS_ASSERT(!this._ended, "ending this response twice?!?!"); - - this._connection.close(); - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - - this._finished = true; - this._ended = true; - }, - - // PRIVATE IMPLEMENTATION - - /** -* Sends the status line and headers of this response if they haven't been -* sent and initiates the process of copying data written to this response's -* body to the network. -*/ - _startAsyncProcessor: function() - { - dumpn("*** _startAsyncProcessor()"); - - // Handle cases where we're being called a second time. The former case - // happens when this is triggered both by complete() and by processAsync(), - // while the latter happens when processAsync() in conjunction with sent - // data causes abort() to be called. - if (this._asyncCopier || this._ended) - { - dumpn("*** ignoring second call to _startAsyncProcessor"); - return; - } - - // Send headers if they haven't been sent already and should be sent, then - // asynchronously continue to send the body. - if (this._headers && !this._powerSeized) - { - this._sendHeaders(); - return; - } - - this._headers = null; - this._sendBody(); - }, - - /** -* Signals that all modifications to the response status line and headers are -* complete and then sends that data over the network to the client. Once -* this method completes, a different response to the request that resulted -* in this response cannot be sent -- the only possible action in case of -* error is to abort the response and close the connection. -*/ - _sendHeaders: function() - { - dumpn("*** _sendHeaders()"); - - NS_ASSERT(this._headers); - NS_ASSERT(!this._powerSeized); - - // request-line - var statusLine = "HTTP/" + this.httpVersion + " " + - this.httpCode + " " + - this.httpDescription + "\r\n"; - - // header post-processing - - var headers = this._headers; - headers.setHeader("Connection", "close", false); - headers.setHeader("Server", "httpd.js", false); - if (!headers.hasHeader("Date")) - headers.setHeader("Date", toDateString(Date.now()), false); - - // Any response not being processed asynchronously must have an associated - // Content-Length header for reasons of backwards compatibility with the - // initial server, which fully buffered every response before sending it. - // Beyond that, however, it's good to do this anyway because otherwise it's - // impossible to test behaviors that depend on the presence or absence of a - // Content-Length header. - if (!this._processAsync) - { - dumpn("*** non-async response, set Content-Length"); - - var bodyStream = this._bodyInputStream; - var avail = bodyStream ? bodyStream.available() : 0; - - // XXX assumes stream will always report the full amount of data available - headers.setHeader("Content-Length", "" + avail, false); - } - - - // construct and send response - dumpn("*** header post-processing completed, sending response head..."); - - // request-line - var preambleData = [statusLine]; - - // headers - var headEnum = headers.enumerator; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - var values = headers.getHeaderValues(fieldName); - for (var i = 0, sz = values.length; i < sz; i++) - preambleData.push(fieldName + ": " + values[i] + "\r\n"); - } - - // end request-line/headers - preambleData.push("\r\n"); - - var preamble = preambleData.join(""); - - var responseHeadPipe = new Pipe(true, false, 0, PR_UINT32_MAX, null); - responseHeadPipe.outputStream.write(preamble, preamble.length); - - var response = this; - var copyObserver = - { - onStartRequest: function(request, cx) - { - dumpn("*** preamble copying started"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** preamble copying complete " + - "[status=0x" + statusCode.toString(16) + "]"); - - if (!components.isSuccessCode(statusCode)) - { - dumpn("!!! header copying problems: non-success statusCode, " + - "ending response"); - - response.end(); - } - else - { - response._sendBody(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - var headerCopier = this._asyncCopier = - new WriteThroughCopier(responseHeadPipe.inputStream, - this._connection.output, - copyObserver, null); - - responseHeadPipe.outputStream.close(); - - // Forbid setting any more headers or modifying the request line. - this._headers = null; - }, - - /** -* Asynchronously writes the body of the response (or the entire response, if -* seizePower() has been called) to the network. -*/ - _sendBody: function() - { - dumpn("*** _sendBody"); - - NS_ASSERT(!this._headers, "still have headers around but sending body?"); - - // If no body data was written, we're done - if (!this._bodyInputStream) - { - dumpn("*** empty body, response finished"); - this.end(); - return; - } - - var response = this; - var copyObserver = - { - onStartRequest: function(request, context) - { - dumpn("*** onStartRequest"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** onStopRequest [status=0x" + statusCode.toString(16) + "]"); - - if (statusCode === Cr.NS_BINDING_ABORTED) - { - dumpn("*** terminating copy observer without ending the response"); - } - else - { - if (!components.isSuccessCode(statusCode)) - dumpn("*** WARNING: non-success statusCode in onStopRequest"); - - response.end(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - dumpn("*** starting async copier of body data..."); - this._asyncCopier = - new WriteThroughCopier(this._bodyInputStream, this._connection.output, - copyObserver, null); - }, - - /** Ensures that this hasn't been ended. */ - _ensureAlive: function() - { - NS_ASSERT(!this._ended, "not handling response lifetime correctly"); - } -}; - -/** -* Size of the segments in the buffer used in storing response data and writing -* it to the socket. -*/ -Response.SEGMENT_SIZE = 8192; - -/** Serves double duty in WriteThroughCopier implementation. */ -function notImplemented() -{ - throw Cr.NS_ERROR_NOT_IMPLEMENTED; -} - -/** Returns true iff the given exception represents stream closure. */ -function streamClosed(e) -{ - return e === Cr.NS_BASE_STREAM_CLOSED || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_CLOSED); -} - -/** Returns true iff the given exception represents a blocked stream. */ -function wouldBlock(e) -{ - return e === Cr.NS_BASE_STREAM_WOULD_BLOCK || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_WOULD_BLOCK); -} - -/** -* Copies data from source to sink as it becomes available, when that data can -* be written to sink without blocking. -* -* @param source : nsIAsyncInputStream -* the stream from which data is to be read -* @param sink : nsIAsyncOutputStream -* the stream to which data is to be copied -* @param observer : nsIRequestObserver -* an observer which will be notified when the copy starts and finishes -* @param context : nsISupports -* context passed to observer when notified of start/stop -* @throws NS_ERROR_NULL_POINTER -* if source, sink, or observer are null -*/ -function WriteThroughCopier(source, sink, observer, context) -{ - if (!source || !sink || !observer) - throw Cr.NS_ERROR_NULL_POINTER; - - /** Stream from which data is being read. */ - this._source = source; - - /** Stream to which data is being written. */ - this._sink = sink; - - /** Observer watching this copy. */ - this._observer = observer; - - /** Context for the observer watching this. */ - this._context = context; - - /** -* True iff this is currently being canceled (cancel has been called, the -* callback may not yet have been made). -*/ - this._canceled = false; - - /** -* False until all data has been read from input and written to output, at -* which point this copy is completed and cancel() is asynchronously called. -*/ - this._completed = false; - - /** Required by nsIRequest, meaningless. */ - this.loadFlags = 0; - /** Required by nsIRequest, meaningless. */ - this.loadGroup = null; - /** Required by nsIRequest, meaningless. */ - this.name = "response-body-copy"; - - /** Status of this request. */ - this.status = Cr.NS_OK; - - /** Arrays of byte strings waiting to be written to output. */ - this._pendingData = []; - - // start copying - try - { - observer.onStartRequest(this, context); - this._waitToReadData(); - this._waitForSinkClosure(); - } - catch (e) - { - dumpn("!!! error starting copy: " + e + - ("lineNumber" in e ? ", line " + e.lineNumber : "")); - dumpn(e.stack); - this.cancel(Cr.NS_ERROR_UNEXPECTED); - } -} -WriteThroughCopier.prototype = -{ - /* nsISupports implementation */ - - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIInputStreamCallback) || - iid.equals(Ci.nsIOutputStreamCallback) || - iid.equals(Ci.nsIRequest) || - iid.equals(Ci.nsISupports)) - { - return this; - } - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NSIINPUTSTREAMCALLBACK - - /** -* Receives a more-data-in-input notification and writes the corresponding -* data to the output. -* -* @param input : nsIAsyncInputStream -* the input stream on whose data we have been waiting -*/ - onInputStreamReady: function(input) - { - if (this._source === null) - return; - - dumpn("*** onInputStreamReady"); - - // - // Ordinarily we'll read a non-zero amount of data from input, queue it up - // to be written and then wait for further callbacks. The complications in - // this method are the cases where we deviate from that behavior when errors - // occur or when copying is drawing to a finish. - // - // The edge cases when reading data are: - // - // Zero data is read - // If zero data was read, we're at the end of available data, so we can - // should stop reading and move on to writing out what we have (or, if - // we've already done that, onto notifying of completion). - // A stream-closed exception is thrown - // This is effectively a less kind version of zero data being read; the - // only difference is that we notify of completion with that result - // rather than with NS_OK. - // Some other exception is thrown - // This is the least kind result. We don't know what happened, so we - // act as though the stream closed except that we notify of completion - // with the result NS_ERROR_UNEXPECTED. - // - - var bytesWanted = 0, bytesConsumed = -1; - try - { - input = new BinaryInputStream(input); - - bytesWanted = Math.min(input.available(), Response.SEGMENT_SIZE); - dumpn("*** input wanted: " + bytesWanted); - - if (bytesWanted > 0) - { - var data = input.readByteArray(bytesWanted); - bytesConsumed = data.length; - this._pendingData.push(String.fromCharCode.apply(String, data)); - } - - dumpn("*** " + bytesConsumed + " bytes read"); - - // Handle the zero-data edge case in the same place as all other edge - // cases are handled. - if (bytesWanted === 0) - throw Cr.NS_BASE_STREAM_CLOSED; - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** input stream closed"); - e = bytesWanted === 0 ? Cr.NS_OK : Cr.NS_ERROR_UNEXPECTED; - } - else - { - dumpn("!!! unexpected error reading from input, canceling: " + e); - e = Cr.NS_ERROR_UNEXPECTED; - } - - this._doneReadingSource(e); - return; - } - - var pendingData = this._pendingData; - - NS_ASSERT(bytesConsumed > 0); - NS_ASSERT(pendingData.length > 0, "no pending data somehow?"); - NS_ASSERT(pendingData[pendingData.length - 1].length > 0, - "buffered zero bytes of data?"); - - NS_ASSERT(this._source !== null); - - // Reading has gone great, and we've gotten data to write now. What if we - // don't have a place to write that data, because output went away just - // before this read? Drop everything on the floor, including new data, and - // cancel at this point. - if (this._sink === null) - { - pendingData.length = 0; - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we've read the data, and we know we have a place to write it. We - // need to queue up the data to be written, but *only* if none is queued - // already -- if data's already queued, the code that actually writes the - // data will make sure to wait on unconsumed pending data. - try - { - if (pendingData.length === 1) - this._waitToWriteData(); - } - catch (e) - { - dumpn("!!! error waiting to write data just read, swallowing and " + - "writing only what we already have: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Whee! We successfully read some data, and it's successfully queued up to - // be written. All that remains now is to wait for more data to read. - try - { - this._waitToReadData(); - } - catch (e) - { - dumpn("!!! error waiting to read more data: " + e); - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - } - }, - - - // NSIOUTPUTSTREAMCALLBACK - - /** -* Callback when data may be written to the output stream without blocking, or -* when the output stream has been closed. -* -* @param output : nsIAsyncOutputStream -* the output stream on whose writability we've been waiting, also known as -* this._sink -*/ - onOutputStreamReady: function(output) - { - if (this._sink === null) - return; - - dumpn("*** onOutputStreamReady"); - - var pendingData = this._pendingData; - if (pendingData.length === 0) - { - // There's no pending data to write. The only way this can happen is if - // we're waiting on the output stream's closure, so we can respond to a - // copying failure as quickly as possible (rather than waiting for data to - // be available to read and then fail to be copied). Therefore, we must - // be done now -- don't bother to attempt to write anything and wrap - // things up. - dumpn("!!! output stream closed prematurely, ending copy"); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - - NS_ASSERT(pendingData[0].length > 0, "queued up an empty quantum?"); - - // - // Write out the first pending quantum of data. The possible errors here - // are: - // - // The write might fail because we can't write that much data - // Okay, we've written what we can now, so re-queue what's left and - // finish writing it out later. - // The write failed because the stream was closed - // Discard pending data that we can no longer write, stop reading, and - // signal that copying finished. - // Some other error occurred. - // Same as if the stream were closed, but notify with the status - // NS_ERROR_UNEXPECTED so the observer knows something was wonky. - // - - try - { - var quantum = pendingData[0]; - - // XXX |quantum| isn't guaranteed to be ASCII, so we're relying on - // undefined behavior! We're only using this because writeByteArray - // is unusably broken for asynchronous output streams; see bug 532834 - // for details. - var bytesWritten = output.write(quantum, quantum.length); - if (bytesWritten === quantum.length) - pendingData.shift(); - else - pendingData[0] = quantum.substring(bytesWritten); - - dumpn("*** wrote " + bytesWritten + " bytes of data"); - } - catch (e) - { - if (wouldBlock(e)) - { - NS_ASSERT(pendingData.length > 0, - "stream-blocking exception with no data to write?"); - NS_ASSERT(pendingData[0].length > 0, - "stream-blocking exception with empty quantum?"); - this._waitToWriteData(); - return; - } - - if (streamClosed(e)) - dumpn("!!! output stream prematurely closed, signaling error..."); - else - dumpn("!!! unknown error: " + e + ", quantum=" + quantum); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // The day is ours! Quantum written, now let's see if we have more data - // still to write. - try - { - if (pendingData.length > 0) - { - this._waitToWriteData(); - return; - } - } - catch (e) - { - dumpn("!!! unexpected error waiting to write pending data: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we have no more pending data to write -- but might we get more in - // the future? - if (this._source !== null) - { - /* -* If we might, then wait for the output stream to be closed. (We wait -* only for closure because we have no data to write -- and if we waited -* for a specific amount of data, we would get repeatedly notified for no -* reason if over time the output stream permitted more and more data to -* be written to it without blocking.) -*/ - this._waitForSinkClosure(); - } - else - { - /* -* On the other hand, if we can't have more data because the input -* stream's gone away, then it's time to notify of copy completion. -* Victory! -*/ - this._sink = null; - this._cancelOrDispatchCancelCallback(Cr.NS_OK); - } - }, - - - // NSIREQUEST - - /** Returns true if the cancel observer hasn't been notified yet. */ - isPending: function() - { - return !this._completed; - }, - - /** Not implemented, don't use! */ - suspend: notImplemented, - /** Not implemented, don't use! */ - resume: notImplemented, - - /** -* Cancels data reading from input, asynchronously writes out any pending -* data, and causes the observer to be notified with the given error code when -* all writing has finished. -* -* @param status : nsresult -* the status to pass to the observer when data copying has been canceled -*/ - cancel: function(status) - { - dumpn("*** cancel(" + status.toString(16) + ")"); - - if (this._canceled) - { - dumpn("*** suppressing a late cancel"); - return; - } - - this._canceled = true; - this.status = status; - - // We could be in the middle of absolutely anything at this point. Both - // input and output might still be around, we might have pending data to - // write, and in general we know nothing about the state of the world. We - // therefore must assume everything's in progress and take everything to its - // final steady state (or so far as it can go before we need to finish - // writing out remaining data). - - this._doneReadingSource(status); - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Stop reading input if we haven't already done so, passing e as the status -* when closing the stream, and kick off a copy-completion notice if no more -* data remains to be written. -* -* @param e : nsresult -* the status to be used when closing the input stream -*/ - _doneReadingSource: function(e) - { - dumpn("*** _doneReadingSource(0x" + e.toString(16) + ")"); - - this._finishSource(e); - if (this._pendingData.length === 0) - this._sink = null; - else - NS_ASSERT(this._sink !== null, "null output?"); - - // If we've written out all data read up to this point, then it's time to - // signal completion. - if (this._sink === null) - { - NS_ASSERT(this._pendingData.length === 0, "pending data still?"); - this._cancelOrDispatchCancelCallback(e); - } - }, - - /** -* Stop writing output if we haven't already done so, discard any data that -* remained to be sent, close off input if it wasn't already closed, and kick -* off a copy-completion notice. -* -* @param e : nsresult -* the status to be used when closing input if it wasn't already closed -*/ - _doneWritingToSink: function(e) - { - dumpn("*** _doneWritingToSink(0x" + e.toString(16) + ")"); - - this._pendingData.length = 0; - this._sink = null; - this._doneReadingSource(e); - }, - - /** -* Completes processing of this copy: either by canceling the copy if it -* hasn't already been canceled using the provided status, or by dispatching -* the cancel callback event (with the originally provided status, of course) -* if it already has been canceled. -* -* @param status : nsresult -* the status code to use to cancel this, if this hasn't already been -* canceled -*/ - _cancelOrDispatchCancelCallback: function(status) - { - dumpn("*** _cancelOrDispatchCancelCallback(" + status + ")"); - - NS_ASSERT(this._source === null, "should have finished input"); - NS_ASSERT(this._sink === null, "should have finished output"); - NS_ASSERT(this._pendingData.length === 0, "should have no pending data"); - - if (!this._canceled) - { - this.cancel(status); - return; - } - - var self = this; - var event = - { - run: function() - { - dumpn("*** onStopRequest async callback"); - - self._completed = true; - try - { - self._observer.onStopRequest(self, self._context, self.status); - } - catch (e) - { - NS_ASSERT(false, - "how are we throwing an exception here? we control " + - "all the callers! " + e); - } - } - }; - - gThreadManager.currentThread.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); - }, - - /** -* Kicks off another wait for more data to be available from the input stream. -*/ - _waitToReadData: function() - { - dumpn("*** _waitToReadData"); - this._source.asyncWait(this, 0, Response.SEGMENT_SIZE, - gThreadManager.mainThread); - }, - - /** -* Kicks off another wait until data can be written to the output stream. -*/ - _waitToWriteData: function() - { - dumpn("*** _waitToWriteData"); - - var pendingData = this._pendingData; - NS_ASSERT(pendingData.length > 0, "no pending data to write?"); - NS_ASSERT(pendingData[0].length > 0, "buffered an empty write?"); - - this._sink.asyncWait(this, 0, pendingData[0].length, - gThreadManager.mainThread); - }, - - /** -* Kicks off a wait for the sink to which data is being copied to be closed. -* We wait for stream closure when we don't have any data to be copied, rather -* than waiting to write a specific amount of data. We can't wait to write -* data because the sink might be infinitely writable, and if no data appears -* in the source for a long time we might have to spin quite a bit waiting to -* write, waiting to write again, &c. Waiting on stream closure instead means -* we'll get just one notification if the sink dies. Note that when data -* starts arriving from the sink we'll resume waiting for data to be written, -* dropping this closure-only callback entirely. -*/ - _waitForSinkClosure: function() - { - dumpn("*** _waitForSinkClosure"); - - this._sink.asyncWait(this, Ci.nsIAsyncOutputStream.WAIT_CLOSURE_ONLY, 0, - gThreadManager.mainThread); - }, - - /** -* Closes input with the given status, if it hasn't already been closed; -* otherwise a no-op. -* -* @param status : nsresult -* status code use to close the source stream if necessary -*/ - _finishSource: function(status) - { - dumpn("*** _finishSource(" + status.toString(16) + ")"); - - if (this._source !== null) - { - this._source.closeWithStatus(status); - this._source = null; - } - } -}; - - -/** -* A container for utility functions used with HTTP headers. -*/ -const headerUtils = -{ - /** -* Normalizes fieldName (by converting it to lowercase) and ensures it is a -* valid header field name (although not necessarily one specified in RFC -* 2616). -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not match the field-name production in RFC 2616 -* @returns string -* fieldName converted to lowercase if it is a valid header, for characters -* where case conversion is possible -*/ - normalizeFieldName: function(fieldName) - { - if (fieldName == "") - throw Cr.NS_ERROR_INVALID_ARG; - - for (var i = 0, sz = fieldName.length; i < sz; i++) - { - if (!IS_TOKEN_ARRAY[fieldName.charCodeAt(i)]) - { - dumpn(fieldName + " is not a valid header field name!"); - throw Cr.NS_ERROR_INVALID_ARG; - } - } - - return fieldName.toLowerCase(); - }, - - /** -* Ensures that fieldValue is a valid header field value (although not -* necessarily as specified in RFC 2616 if the corresponding field name is -* part of the HTTP protocol), normalizes the value if it is, and -* returns the normalized value. -* -* @param fieldValue : string -* a value to be normalized as an HTTP header field value -* @throws NS_ERROR_INVALID_ARG -* if fieldValue does not match the field-value production in RFC 2616 -* @returns string -* fieldValue as a normalized HTTP header field value -*/ - normalizeFieldValue: function(fieldValue) - { - // field-value = *( field-content | LWS ) - // field-content = - // TEXT = - // LWS = [CRLF] 1*( SP | HT ) - // - // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - // qdtext = > - // quoted-pair = "\" CHAR - // CHAR = - - // Any LWS that occurs between field-content MAY be replaced with a single - // SP before interpreting the field value or forwarding the message - // downstream (section 4.2); we replace 1*LWS with a single SP - var val = fieldValue.replace(/(?:(?:\r\n)?[ \t]+)+/g, " "); - - // remove leading/trailing LWS (which has been converted to SP) - val = val.replace(/^ +/, "").replace(/ +$/, ""); - - // that should have taken care of all CTLs, so val should contain no CTLs - for (var i = 0, len = val.length; i < len; i++) - if (isCTL(val.charCodeAt(i))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX disallows quoted-pair where CHAR is a CTL -- will not invalidly - // normalize, however, so this can be construed as a tightening of the - // spec and not entirely as a bug - return val; - } -}; - - - -/** -* Converts the given string into a string which is safe for use in an HTML -* context. -* -* @param str : string -* the string to make HTML-safe -* @returns string -* an HTML-safe version of str -*/ -function htmlEscape(str) -{ - // this is naive, but it'll work - var s = ""; - for (var i = 0; i < str.length; i++) - s += "&#" + str.charCodeAt(i) + ";"; - return s; -} - - -/** -* Constructs an object representing an HTTP version (see section 3.1). -* -* @param versionString -* a string of the form "#.#", where # is an non-negative decimal integer with -* or without leading zeros -* @throws -* if versionString does not specify a valid HTTP version number -*/ -function nsHttpVersion(versionString) -{ - var matches = /^(\d+)\.(\d+)$/.exec(versionString); - if (!matches) - throw "Not a valid HTTP version!"; - - /** The major version number of this, as a number. */ - this.major = parseInt(matches[1], 10); - - /** The minor version number of this, as a number. */ - this.minor = parseInt(matches[2], 10); - - if (isNaN(this.major) || isNaN(this.minor) || - this.major < 0 || this.minor < 0) - throw "Not a valid HTTP version!"; -} -nsHttpVersion.prototype = -{ - /** -* Returns the standard string representation of the HTTP version represented -* by this (e.g., "1.1"). -*/ - toString: function () - { - return this.major + "." + this.minor; - }, - - /** -* Returns true if this represents the same HTTP version as otherVersion, -* false otherwise. -* -* @param otherVersion : nsHttpVersion -* the version to compare against this -*/ - equals: function (otherVersion) - { - return this.major == otherVersion.major && - this.minor == otherVersion.minor; - }, - - /** True if this >= otherVersion, false otherwise. */ - atLeast: function(otherVersion) - { - return this.major > otherVersion.major || - (this.major == otherVersion.major && - this.minor >= otherVersion.minor); - } -}; - -nsHttpVersion.HTTP_1_0 = new nsHttpVersion("1.0"); -nsHttpVersion.HTTP_1_1 = new nsHttpVersion("1.1"); - - -/** -* An object which stores HTTP headers for a request or response. -* -* Note that since headers are case-insensitive, this object converts headers to -* lowercase before storing them. This allows the getHeader and hasHeader -* methods to work correctly for any case of a header, but it means that the -* values returned by .enumerator may not be equal case-sensitively to the -* values passed to setHeader when adding headers to this. -*/ -function nsHttpHeaders() -{ - /** -* A hash of headers, with header field names as the keys and header field -* values as the values. Header field names are case-insensitive, but upon -* insertion here they are converted to lowercase. Header field values are -* normalized upon insertion to contain no leading or trailing whitespace. -* -* Note also that per RFC 2616, section 4.2, two headers with the same name in -* a message may be treated as one header with the same field name and a field -* value consisting of the separate field values joined together with a "," in -* their original order. This hash stores multiple headers with the same name -* in this manner. -*/ - this._headers = {}; -} -nsHttpHeaders.prototype = -{ - /** -* Sets the header represented by name and value in this. -* -* @param name : string -* the header name -* @param value : string -* the header value -* @throws NS_ERROR_INVALID_ARG -* if name or value is not a valid header component -*/ - setHeader: function(fieldName, fieldValue, merge) - { - var name = headerUtils.normalizeFieldName(fieldName); - var value = headerUtils.normalizeFieldValue(fieldValue); - - // The following three headers are stored as arrays because their real-world - // syntax prevents joining individual headers into a single header using - // ",". See also - if (merge && name in this._headers) - { - if (name === "www-authenticate" || - name === "proxy-authenticate" || - name === "set-cookie") - { - this._headers[name].push(value); - } - else - { - this._headers[name][0] += "," + value; - NS_ASSERT(this._headers[name].length === 1, - "how'd a non-special header have multiple values?") - } - } - else - { - this._headers[name] = [value]; - } - }, - - /** -* Returns the value for the header specified by this. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns string -* the field value for the given header, possibly with non-semantic changes -* (i.e., leading/trailing whitespace stripped, whitespace runs replaced -* with spaces, etc.) at the option of the implementation; multiple -* instances of the header will be combined with a comma, except for -* the three headers noted in the description of getHeaderValues -*/ - getHeader: function(fieldName) - { - return this.getHeaderValues(fieldName).join("\n"); - }, - - /** -* Returns the value for the header specified by fieldName as an array. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns [string] -* an array of all the header values in this for the given -* header name. Header values will generally be collapsed -* into a single header by joining all header values together -* with commas, but certain headers (Proxy-Authenticate, -* WWW-Authenticate, and Set-Cookie) violate the HTTP spec -* and cannot be collapsed in this manner. For these headers -* only, the returned array may contain multiple elements if -* that header has been added more than once. -*/ - getHeaderValues: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - - if (name in this._headers) - return this._headers[name]; - else - throw Cr.NS_ERROR_NOT_AVAILABLE; - }, - - /** -* Returns true if a header with the given field name exists in this, false -* otherwise. -* -* @param fieldName : string -* the field name whose existence is to be determined in this -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @returns boolean -* true if the header's present, false otherwise -*/ - hasHeader: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - return (name in this._headers); - }, - - /** -* Returns a new enumerator over the field names of the headers in this, as -* nsISupportsStrings. The names returned will be in lowercase, regardless of -* how they were input using setHeader (header names are case-insensitive per -* RFC 2616). -*/ - get enumerator() - { - var headers = []; - for (var i in this._headers) - { - var supports = new SupportsString(); - supports.data = i; - headers.push(supports); - } - - return new nsSimpleEnumerator(headers); - } -}; - - -/** -* Constructs an nsISimpleEnumerator for the given array of items. -* -* @param items : Array -* the items, which must all implement nsISupports -*/ -function nsSimpleEnumerator(items) -{ - this._items = items; - this._nextIndex = 0; -} -nsSimpleEnumerator.prototype = -{ - hasMoreElements: function() - { - return this._nextIndex < this._items.length; - }, - getNext: function() - { - if (!this.hasMoreElements()) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - return this._items[this._nextIndex++]; - }, - QueryInterface: function(aIID) - { - if (Ci.nsISimpleEnumerator.equals(aIID) || - Ci.nsISupports.equals(aIID)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } -}; - - -/** -* A representation of the data in an HTTP request. -* -* @param port : uint -* the port on which the server receiving this request runs -*/ -function Request(port) -{ - /** Method of this request, e.g. GET or POST. */ - this._method = ""; - - /** Path of the requested resource; empty paths are converted to '/'. */ - this._path = ""; - - /** Query string, if any, associated with this request (not including '?'). */ - this._queryString = ""; - - /** Scheme of requested resource, usually http, always lowercase. */ - this._scheme = "http"; - - /** Hostname on which the requested resource resides. */ - this._host = undefined; - - /** Port number over which the request was received. */ - this._port = port; - - var bodyPipe = new Pipe(false, false, 0, PR_UINT32_MAX, null); - - /** Stream from which data in this request's body may be read. */ - this._bodyInputStream = bodyPipe.inputStream; - - /** Stream to which data in this request's body is written. */ - this._bodyOutputStream = bodyPipe.outputStream; - - /** -* The headers in this request. -*/ - this._headers = new nsHttpHeaders(); - - /** -* For the addition of ad-hoc properties and new functionality without having -* to change nsIHttpRequest every time; currently lazily created, as its only -* use is in directory listings. -*/ - this._bag = null; -} -Request.prototype = -{ - // SERVER METADATA - - // - // see nsIHttpRequest.scheme - // - get scheme() - { - return this._scheme; - }, - - // - // see nsIHttpRequest.host - // - get host() - { - return this._host; - }, - - // - // see nsIHttpRequest.port - // - get port() - { - return this._port; - }, - - // REQUEST LINE - - // - // see nsIHttpRequest.method - // - get method() - { - return this._method; - }, - - // - // see nsIHttpRequest.httpVersion - // - get httpVersion() - { - return this._httpVersion.toString(); - }, - - // - // see nsIHttpRequest.path - // - get path() - { - return this._path; - }, - - // - // see nsIHttpRequest.queryString - // - get queryString() - { - return this._queryString; - }, - - // HEADERS - - // - // see nsIHttpRequest.getHeader - // - getHeader: function(name) - { - return this._headers.getHeader(name); - }, - - // - // see nsIHttpRequest.hasHeader - // - hasHeader: function(name) - { - return this._headers.hasHeader(name); - }, - - // - // see nsIHttpRequest.headers - // - get headers() - { - return this._headers.enumerator; - }, - - // - // see nsIPropertyBag.enumerator - // - get enumerator() - { - this._ensurePropertyBag(); - return this._bag.enumerator; - }, - - // - // see nsIHttpRequest.headers - // - get bodyInputStream() - { - return this._bodyInputStream; - }, - - // - // see nsIPropertyBag.getProperty - // - getProperty: function(name) - { - this._ensurePropertyBag(); - return this._bag.getProperty(name); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpRequest) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** Ensures a property bag has been created for ad-hoc behaviors. */ - _ensurePropertyBag: function() - { - if (!this._bag) - this._bag = new WritablePropertyBag(); - } -}; - - -// XPCOM trappings -if ("XPCOMUtils" in this && // Firefox 3.6 doesn't load XPCOMUtils in this scope for some reason... - "generateNSGetFactory" in XPCOMUtils) { - var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsHttpServer]); -} - - - -/** -* Creates a new HTTP server listening for loopback traffic on the given port, -* starts it, and runs the server until the server processes a shutdown request, -* spinning an event loop so that events posted by the server's socket are -* processed. -* -* This method is primarily intended for use in running this script from within -* xpcshell and running a functional HTTP server without having to deal with -* non-essential details. -* -* Note that running multiple servers using variants of this method probably -* doesn't work, simply due to how the internal event loop is spun and stopped. -* -* @note -* This method only works with Mozilla 1.9 (i.e., Firefox 3 or trunk code); -* you should use this server as a component in Mozilla 1.8. -* @param port -* the port on which the server will run, or -1 if there exists no preference -* for a specific port; note that attempting to use some values for this -* parameter (particularly those below 1024) may cause this method to throw or -* may result in the server being prematurely shut down -* @param basePath -* a local directory from which requests will be served (i.e., if this is -* "/home/jwalden/" then a request to /index.html will load -* /home/jwalden/index.html); if this is omitted, only the default URLs in -* this server implementation will be functional -*/ -function server(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - // if you're running this, you probably want to see debugging info - DEBUG = true; - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", SJS_TYPE); - srv.start(port); - - var thread = gThreadManager.currentThread; - while (!srv.isStopped()) - thread.processNextEvent(true); - - // get rid of any pending requests - while (thread.hasPendingEvents()) - thread.processNextEvent(true); - - DEBUG = false; -} - -function startServerAsync(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", "sjs"); - srv.start(port); - return srv; -} - -exports.nsHttpServer = nsHttpServer; -exports.ScriptableInputStream = ScriptableInputStream; -exports.server = server; -exports.startServerAsync = startServerAsync; diff --git a/addon-sdk/source/test/addons/e10s-content/lib/main.js b/addon-sdk/source/test/addons/e10s-content/lib/main.js deleted file mode 100644 index 6ca7dc48c..000000000 --- a/addon-sdk/source/test/addons/e10s-content/lib/main.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 { merge } = require('sdk/util/object'); -const { version } = require('sdk/system'); - -const SKIPPING_TESTS = { - "test skip": (assert) => assert.pass("nothing to test here") -}; - -merge(module.exports, require('./test-content-script')); -merge(module.exports, require('./test-content-worker')); -merge(module.exports, require('./test-page-worker')); - -// run e10s tests only on builds from trunk, fx-team, Nightly.. -if (!version.endsWith('a1')) { - module.exports = SKIPPING_TESTS; -} - -require('sdk/test/runner').runTestsFromModule(module); diff --git a/addon-sdk/source/test/addons/e10s-content/lib/test-content-script.js b/addon-sdk/source/test/addons/e10s-content/lib/test-content-script.js deleted file mode 100644 index c24f841b2..000000000 --- a/addon-sdk/source/test/addons/e10s-content/lib/test-content-script.js +++ /dev/null @@ -1,845 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 hiddenFrames = require("sdk/frame/hidden-frame"); -const { create: makeFrame } = require("sdk/frame/utils"); -const { window } = require("sdk/addon/window"); -const { Loader } = require('sdk/test/loader'); -const { URL } = require("sdk/url"); -const testURI = require("./fixtures").url("test.html"); -const testHost = URL(testURI).scheme + '://' + URL(testURI).host; - -/* - * Utility function that allow to easily run a proxy test with a clean - * new HTML document. See first unit test for usage. - */ -function createProxyTest(html, callback) { - return function (assert, done) { - let url = 'data:text/html;charset=utf-8,' + encodeURIComponent(html); - let principalLoaded = false; - - let element = makeFrame(window.document, { - nodeName: "iframe", - type: "content", - allowJavascript: true, - allowPlugins: true, - allowAuth: true, - uri: testURI - }); - - element.addEventListener("DOMContentLoaded", onDOMReady, false); - - function onDOMReady() { - // Reload frame after getting principal from `testURI` - if (!principalLoaded) { - element.setAttribute("src", url); - principalLoaded = true; - return; - } - - assert.equal(element.getAttribute("src"), url, "correct URL loaded"); - element.removeEventListener("DOMContentLoaded", onDOMReady, - false); - let xrayWindow = element.contentWindow; - let rawWindow = xrayWindow.wrappedJSObject; - - let isDone = false; - let helper = { - xrayWindow: xrayWindow, - rawWindow: rawWindow, - createWorker: function (contentScript) { - return createWorker(assert, xrayWindow, contentScript, helper.done); - }, - done: function () { - if (isDone) - return; - isDone = true; - element.parentNode.removeChild(element); - done(); - } - }; - callback(helper, assert); - } - }; -} - -function createWorker(assert, xrayWindow, contentScript, done) { - let loader = Loader(module); - let Worker = loader.require("sdk/content/worker").Worker; - let worker = Worker({ - window: xrayWindow, - contentScript: [ - 'let assert, done; new ' + function () { - assert = function assert(v, msg) { - self.port.emit("assert", {assertion:v, msg:msg}); - } - done = function done() { - self.port.emit("done"); - } - }, - contentScript - ] - }); - - worker.port.on("done", done); - worker.port.on("assert", function (data) { - assert.ok(data.assertion, data.msg); - }); - - return worker; -} - -/* Examples for the `createProxyTest` uses */ - -var html = ""; - -exports["test Create Proxy Test"] = createProxyTest(html, function (helper, assert) { - // You can get access to regular `test` object in second argument of - // `createProxyTest` method: - assert.ok(helper.rawWindow.documentGlobal, - "You have access to a raw window reference via `helper.rawWindow`"); - assert.ok(!("documentGlobal" in helper.xrayWindow), - "You have access to an XrayWrapper reference via `helper.xrayWindow`"); - - // If you do not create a Worker, you have to call helper.done(), - // in order to say when your test is finished - helper.done(); -}); - -exports["test Create Proxy Test With Worker"] = createProxyTest("", function (helper) { - - helper.createWorker( - "new " + function WorkerScope() { - assert(true, "You can do assertions in your content script"); - // And if you create a worker, you either have to call `done` - // from content script or helper.done() - done(); - } - ); - -}); - -exports["test Create Proxy Test With Events"] = createProxyTest("", function (helper, assert) { - - let worker = helper.createWorker( - "new " + function WorkerScope() { - self.port.emit("foo"); - } - ); - - worker.port.on("foo", function () { - assert.pass("You can use events"); - // And terminate your test with helper.done: - helper.done(); - }); - -}); - -/* Disabled due to bug 1038432 -// Bug 714778: There was some issue around `toString` functions -// that ended up being shared between content scripts -exports["test Shared To String Proxies"] = createProxyTest("", function(helper) { - - let worker = helper.createWorker( - 'new ' + function ContentScriptScope() { - // We ensure that `toString` can't be modified so that nothing could - // leak to/from the document and between content scripts - // It only applies to JS proxies, there isn't any such issue with xrays. - //document.location.toString = function foo() {}; - document.location.toString.foo = "bar"; - assert("foo" in document.location.toString, "document.location.toString can be modified"); - assert(document.location.toString() == "data:text/html;charset=utf-8,", - "First document.location.toString()"); - self.postMessage("next"); - } - ); - worker.on("message", function () { - helper.createWorker( - 'new ' + function ContentScriptScope2() { - assert(!("foo" in document.location.toString), - "document.location.toString is different for each content script"); - assert(document.location.toString() == "data:text/html;charset=utf-8,", - "Second document.location.toString()"); - done(); - } - ); - }); -}); -*/ - -// Ensure that postMessage is working correctly across documents with an iframe -var html = ' - - diff --git a/addon-sdk/source/test/fixtures/test-iframe.js b/addon-sdk/source/test/fixtures/test-iframe.js deleted file mode 100644 index bbfadc4ff..000000000 --- a/addon-sdk/source/test/fixtures/test-iframe.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/. */ - -var count = 0; - -setTimeout(function() { - window.addEventListener("message", function(msg) { - if (++count > 1) { - self.postMessage(msg.data); - } - else msg.source.postMessage(msg.data, '*'); - }); - - document.getElementById('inner').src = iframePath; -}, 0); diff --git a/addon-sdk/source/test/fixtures/test-message-manager.js b/addon-sdk/source/test/fixtures/test-message-manager.js deleted file mode 100644 index d647bd8fd..000000000 --- a/addon-sdk/source/test/fixtures/test-message-manager.js +++ /dev/null @@ -1,6 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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_VALUE = 11; - diff --git a/addon-sdk/source/test/fixtures/test-net-url.txt b/addon-sdk/source/test/fixtures/test-net-url.txt deleted file mode 100644 index 9f8166e61..000000000 --- a/addon-sdk/source/test/fixtures/test-net-url.txt +++ /dev/null @@ -1 +0,0 @@ -Hello, ゼロ! \ No newline at end of file diff --git a/addon-sdk/source/test/fixtures/test-page-mod.html b/addon-sdk/source/test/fixtures/test-page-mod.html deleted file mode 100644 index 901abefc4..000000000 --- a/addon-sdk/source/test/fixtures/test-page-mod.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - Page Mod test - - -

Lorem ipsum dolor sit amet.

- - diff --git a/addon-sdk/source/test/fixtures/test-sidebar-addon-global.html b/addon-sdk/source/test/fixtures/test-sidebar-addon-global.html deleted file mode 100644 index 4552e3d78..000000000 --- a/addon-sdk/source/test/fixtures/test-sidebar-addon-global.html +++ /dev/null @@ -1,15 +0,0 @@ - - -SIDEBAR TEST diff --git a/addon-sdk/source/test/fixtures/test-trusted-document.html b/addon-sdk/source/test/fixtures/test-trusted-document.html deleted file mode 100644 index c31e055cb..000000000 --- a/addon-sdk/source/test/fixtures/test-trusted-document.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - Worker test - - -

Lorem ipsum dolor sit amet.

- - - diff --git a/addon-sdk/source/test/fixtures/test.html b/addon-sdk/source/test/fixtures/test.html deleted file mode 100644 index 70b5e31e5..000000000 --- a/addon-sdk/source/test/fixtures/test.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - foo - - -

bar

- - - diff --git a/addon-sdk/source/test/fixtures/testLocalXhr.json b/addon-sdk/source/test/fixtures/testLocalXhr.json deleted file mode 100644 index 0967ef424..000000000 --- a/addon-sdk/source/test/fixtures/testLocalXhr.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/addon-sdk/source/test/framescript-manager/frame-script.js b/addon-sdk/source/test/framescript-manager/frame-script.js deleted file mode 100644 index de9bb8385..000000000 --- a/addon-sdk/source/test/framescript-manager/frame-script.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/. */ -"use strict"; - -const {onPing} = require("./pong"); - -exports.onPing = onPing; - -exports.onInit = (context) => { - context.sendAsyncMessage("framescript-manager/ready", {state: "ready"}); - context.addMessageListener("framescript-manager/ping", exports.onPing); -}; diff --git a/addon-sdk/source/test/framescript-manager/pong.js b/addon-sdk/source/test/framescript-manager/pong.js deleted file mode 100644 index b7fb7e077..000000000 --- a/addon-sdk/source/test/framescript-manager/pong.js +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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"; - -exports.onPing = message => - message.target.sendAsyncMessage("framescript-manager/pong", message.data); diff --git a/addon-sdk/source/test/framescript-util/frame-script.js b/addon-sdk/source/test/framescript-util/frame-script.js deleted file mode 100644 index 2a4a2284c..000000000 --- a/addon-sdk/source/test/framescript-util/frame-script.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/. */ -"use strict"; - -const { windowToMessageManager, nodeToMessageManager } = require("framescript/util"); - - -const onInit = (context) => { - context.addMessageListener("framescript-util/window/request", _ => { - windowToMessageManager(context.content.window).sendAsyncMessage( - "framescript-util/window/response", {window: true}); - }); - - context.addMessageListener("framescript-util/node/request", message => { - const node = context.content.document.querySelector(message.data); - nodeToMessageManager(node).sendAsyncMessage( - "framescript-util/node/response", {node: true}); - }); -}; -exports.onInit = onInit; diff --git a/addon-sdk/source/test/jetpack-package.ini b/addon-sdk/source/test/jetpack-package.ini deleted file mode 100644 index fa93b9c2f..000000000 --- a/addon-sdk/source/test/jetpack-package.ini +++ /dev/null @@ -1,179 +0,0 @@ -[DEFAULT] -support-files = - buffers/** - commonjs-test-adapter/** - context-menu/** - event/** - fixtures.js - fixtures/** - fixtures/native-addon-test.xpi - fixtures/native-overrides-test.xpi - framescript-manager/** - framescript-util/** - lib/** - loader/** - modules/** - page-mod/** - path/** - private-browsing/** - querystring/** - sidebar/** - tabs/** - test-context-menu.html - traits/** - util.js - windows/** - zip/** -generated-files = - fixtures/native-addon-test.xpi - fixtures/native-overrides-test.xpi - -[test-addon-bootstrap.js] -[test-addon-extras.js] -[test-addon-installer.js] -[test-addon-window.js] -[test-api-utils.js] -[test-array.js] -[test-base64.js] -[test-bootstrap.js] -[test-browser-events.js] -[test-buffer.js] -[test-byte-streams.js] -[test-child_process.js] -[test-chrome.js] -[test-clipboard.js] -subsuite = clipboard -[test-collection.js] -[test-commonjs-test-adapter.js] -[test-content-events.js] -[test-content-script.js] -[test-content-sync-worker.js] -[test-content-worker.js] -[test-context-menu.js] -[test-context-menu@2.js] -[test-cuddlefish.js] -# Cuddlefish loader is unsupported -skip-if = true -[test-deprecate.js] -[test-dev-panel.js] -[test-diffpatcher.js] -[test-dispatcher.js] -[test-disposable.js] -[test-dom.js] -[test-environment.js] -[test-event-core.js] -[test-event-dom.js] -[test-event-target.js] -[test-event-utils.js] -[test-file.js] -[test-frame-utils.js] -[test-framescript-manager.js] -[test-framescript-util.js] -[test-fs.js] -[test-functional.js] -[test-globals.js] -[test-heritage.js] -[test-hidden-frame.js] -[test-host-events.js] -[test-hotkeys.js] -[test-httpd.js] -[test-indexed-db.js] -[test-jetpack-id.js] -[test-keyboard-observer.js] -[test-keyboard-utils.js] -[test-l10n-locale.js] -[test-l10n-plural-rules.js] -[test-lang-type.js] -[test-libxul.js] -[test-list.js] -[test-loader.js] -[test-match-pattern.js] -[test-method.js] -[test-module.js] -[test-modules.js] -[test-mozilla-toolkit-versioning.js] -[test-mpl2-license-header.js] -skip-if = true -[test-namespace.js] -[test-native-loader.js] -[test-native-options.js] -[test-net-url.js] -[test-node-os.js] -[test-notifications.js] -[test-object.js] -[test-observers.js] -[test-page-mod-debug.js] -[test-page-mod.js] -[test-page-worker.js] -[test-panel.js] -[test-passwords-utils.js] -[test-passwords.js] -[test-path.js] -[test-plain-text-console.js] -[test-preferences-service.js] -[test-preferences-target.js] -[test-private-browsing.js] -[test-promise.js] -[test-querystring.js] -[test-reference.js] -[test-request.js] -[test-require.js] -[test-rules.js] -[test-sandbox.js] -[test-selection.js] -[test-self.js] -[test-sequence.js] -[test-set-exports.js] -[test-shared-require.js] -[test-simple-prefs.js] -[test-simple-storage.js] -[test-system-events.js] -[test-system-input-output.js] -[test-system-runtime.js] -[test-system-startup.js] -[test-system.js] -[test-tab-events.js] -[test-tab-observer.js] -[test-tab-utils.js] -[test-tab.js] -[test-tabs-common.js] -[test-tabs.js] -[test-test-addon-file.js] -[test-test-assert.js] -[test-test-loader.js] -[test-test-memory.js] -[test-test-utils-async.js] -[test-test-utils-generator.js] -[test-test-utils-sync.js] -[test-test-utils.js] -[test-text-streams.js] -[test-timer.js] -[test-traceback.js] -[test-ui-action-button.js] -skip-if = debug || asan # Bug 1208727 -[test-ui-frame.js] -[test-ui-id.js] -[test-ui-sidebar-private-browsing.js] -[test-ui-sidebar.js] -[test-ui-toggle-button.js] -[test-ui-toolbar.js] -[test-unit-test-finder.js] -[test-unit-test.js] -[test-unload.js] -[test-unsupported-skip.js] -# Bug 1037235 -skip-if = true -[test-uri-resource.js] -[test-url.js] -[test-uuid.js] -[test-weak-set.js] -[test-window-events.js] -[test-window-observer.js] -[test-window-utils-private-browsing.js] -[test-window-utils.js] -[test-window-utils2.js] -[test-windows-common.js] -[test-windows.js] -[test-xhr.js] -[test-xpcom.js] -[test-xul-app.js] diff --git a/addon-sdk/source/test/leak/jetpack-package.ini b/addon-sdk/source/test/leak/jetpack-package.ini deleted file mode 100644 index 0632bdc87..000000000 --- a/addon-sdk/source/test/leak/jetpack-package.ini +++ /dev/null @@ -1,7 +0,0 @@ -[DEFAULT] -support-files = - leak-utils.js - -[test-leak-window-events.js] -[test-leak-event-dom-closed-window.js] -[test-leak-tab-events.js] diff --git a/addon-sdk/source/test/leak/leak-utils.js b/addon-sdk/source/test/leak/leak-utils.js deleted file mode 100644 index e01255ec8..000000000 --- a/addon-sdk/source/test/leak/leak-utils.js +++ /dev/null @@ -1,80 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cu, Ci } = require("chrome"); -const { Services } = Cu.import("resource://gre/modules/Services.jsm", {}); -const { SelfSupportBackend } = Cu.import("resource:///modules/SelfSupportBackend.jsm", {}); -const Startup = Cu.import("resource://gre/modules/sdk/system/Startup.js", {}).exports; - -// Adapted from the SpecialPowers.exactGC() code. We don't have a -// window to operate on so we cannot use the exact same logic. We -// use 6 GC iterations here as that is what is needed to clean up -// the windows we have tested with. -function gc() { - return new Promise(resolve => { - Cu.forceGC(); - Cu.forceCC(); - let count = 0; - function genGCCallback() { - Cu.forceCC(); - return function() { - if (++count < 5) { - Cu.schedulePreciseGC(genGCCallback()); - } else { - resolve(); - } - } - } - - Cu.schedulePreciseGC(genGCCallback()); - }); -} - -// Execute the given test function and verify that we did not leak windows -// in the process. The test function must return a promise or be a generator. -// If the promise is resolved, or generator completes, with an sdk loader -// object then it will be unloaded after the memory measurements. -exports.asyncWindowLeakTest = function*(assert, asyncTestFunc) { - - // SelfSupportBackend periodically tries to open windows. This can - // mess up our window leak detection below, so turn it off. - SelfSupportBackend.uninit(); - - // Wait for the browser to finish loading. - yield Startup.onceInitialized; - - // Track windows that are opened in an array of weak references. - let weakWindows = []; - function windowObserver(subject, topic) { - let supportsWeak = subject.QueryInterface(Ci.nsISupportsWeakReference); - if (supportsWeak) { - weakWindows.push(Cu.getWeakReference(supportsWeak)); - } - } - Services.obs.addObserver(windowObserver, "domwindowopened", false); - - // Execute the body of the test. - let testLoader = yield asyncTestFunc(assert); - - // Stop tracking new windows and attempt to GC any resources allocated - // by the test body. - Services.obs.removeObserver(windowObserver, "domwindowopened", false); - yield gc(); - - // Check to see if any of the windows we saw survived the GC. We consider - // these leaks. - assert.ok(weakWindows.length > 0, "should see at least one new window"); - for (let i = 0; i < weakWindows.length; ++i) { - assert.equal(weakWindows[i].get(), null, "window " + i + " should be GC'd"); - } - - // Finally, unload the test body's loader if it provided one. We do this - // after our leak detection to avoid free'ing things on unload. Users - // don't tend to unload their addons very often, so we want to find leaks - // that happen while addons are in use. - if (testLoader) { - testLoader.unload(); - } -} diff --git a/addon-sdk/source/test/leak/test-leak-event-dom-closed-window.js b/addon-sdk/source/test/leak/test-leak-event-dom-closed-window.js deleted file mode 100644 index c398462ab..000000000 --- a/addon-sdk/source/test/leak/test-leak-event-dom-closed-window.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 { asyncWindowLeakTest } = require("./leak-utils"); -const { Loader } = require('sdk/test/loader'); -const openWindow = require("sdk/window/utils").open; - -exports["test sdk/event/dom does not leak when attached to closed window"] = function*(assert) { - yield asyncWindowLeakTest(assert, _ => { - return new Promise(resolve => { - let loader = Loader(module); - let { open } = loader.require('sdk/event/dom'); - let w = openWindow(); - w.addEventListener("DOMWindowClose", function windowClosed(evt) { - w.removeEventListener("DOMWindowClose", windowClosed); - // The sdk/event/dom module tries to clean itself up when DOMWindowClose - // is fired. Verify that it doesn't leak if its attached to an - // already closed window either. (See bug 1268898.) - open(w.document, "TestEvent1"); - resolve(loader); - }); - w.close(); - }); - }); -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/leak/test-leak-tab-events.js b/addon-sdk/source/test/leak/test-leak-tab-events.js deleted file mode 100644 index 4266c04fc..000000000 --- a/addon-sdk/source/test/leak/test-leak-tab-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'; - -const { asyncWindowLeakTest } = require("./leak-utils"); -const { Loader } = require('sdk/test/loader'); -const openWindow = require("sdk/window/utils").open; - -exports["test sdk/tab/events does not leak new window"] = function*(assert) { - yield asyncWindowLeakTest(assert, _ => { - return new Promise(resolve => { - let loader = Loader(module); - let { events } = loader.require('sdk/tab/events'); - let w = openWindow(); - w.addEventListener("load", function windowLoaded(evt) { - w.removeEventListener("load", windowLoaded); - w.addEventListener("DOMWindowClose", function windowClosed(evt) { - w.removeEventListener("DOMWindowClose", windowClosed); - resolve(loader); - }); - w.close(); - }); - }); - }); -} - -exports["test sdk/tab/events does not leak when attached to existing window"] = function*(assert) { - yield asyncWindowLeakTest(assert, _ => { - return new Promise(resolve => { - let loader = Loader(module); - let w = openWindow(); - w.addEventListener("load", function windowLoaded(evt) { - w.removeEventListener("load", windowLoaded); - let { events } = loader.require('sdk/tab/events'); - w.addEventListener("DOMWindowClose", function windowClosed(evt) { - w.removeEventListener("DOMWindowClose", windowClosed); - resolve(loader); - }); - w.close(); - }); - }); - }); -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/leak/test-leak-window-events.js b/addon-sdk/source/test/leak/test-leak-window-events.js deleted file mode 100644 index ceb20f475..000000000 --- a/addon-sdk/source/test/leak/test-leak-window-events.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"; - -// Opening new windows in Fennec causes issues -module.metadata = { - engines: { - 'Firefox': '*' - } -}; - -const { asyncWindowLeakTest } = require("./leak-utils.js"); -const { Loader } = require("sdk/test/loader"); -const { open } = require("sdk/window/utils"); - -exports["test window/events for leaks"] = function*(assert) { - yield asyncWindowLeakTest(assert, _ => { - return new Promise((resolve, reject) => { - let loader = Loader(module); - let { events } = loader.require("sdk/window/events"); - let { on, off } = loader.require("sdk/event/core"); - - on(events, "data", function handler(e) { - try { - if (e.type === "load") { - e.target.close(); - } - else if (e.type === "close") { - off(events, "data", handler); - - // Let asyncWindowLeakTest call loader.unload() after the - // leak check. - resolve(loader); - } - } catch (e) { - reject(e); - } - }); - - // Open a window. This will trigger our data events. - open(); - }); - }); -}; - -exports["test window/events for leaks with existing window"] = function*(assert) { - yield asyncWindowLeakTest(assert, _ => { - return new Promise((resolve, reject) => { - let loader = Loader(module); - let w = open(); - w.addEventListener("load", function windowLoaded(evt) { - w.removeEventListener("load", windowLoaded); - let { events } = loader.require("sdk/window/events"); - w.addEventListener("DOMWindowClose", function windowClosed(evt) { - w.removeEventListener("DOMWindowClose", windowClosed); - resolve(loader); - }); - w.close(); - }); - }); - }); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/lib/httpd.js b/addon-sdk/source/test/lib/httpd.js deleted file mode 100644 index e46ca96a0..000000000 --- a/addon-sdk/source/test/lib/httpd.js +++ /dev/null @@ -1,5212 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* -* An implementation of an HTTP server both as a loadable script and as an XPCOM -* component. See the accompanying README file for user documentation on -* httpd.js. -*/ - -module.metadata = { - "stability": "experimental" -}; - -const { components, CC, Cc, Ci, Cr, Cu } = require("chrome"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - - -const PR_UINT32_MAX = Math.pow(2, 32) - 1; - -/** True if debugging output is enabled, false otherwise. */ -var DEBUG = false; // non-const *only* so tweakable in server tests - -/** True if debugging output should be timestamped. */ -var DEBUG_TIMESTAMP = false; // non-const so tweakable in server tests - -var gGlobalObject = Cc["@mozilla.org/systemprincipal;1"].createInstance(); - -/** -* Asserts that the given condition holds. If it doesn't, the given message is -* dumped, a stack trace is printed, and an exception is thrown to attempt to -* stop execution (which unfortunately must rely upon the exception not being -* accidentally swallowed by the code that uses it). -*/ -function NS_ASSERT(cond, msg) -{ - if (DEBUG && !cond) - { - dumpn("###!!!"); - dumpn("###!!! ASSERTION" + (msg ? ": " + msg : "!")); - dumpn("###!!! Stack follows:"); - - var stack = new Error().stack.split(/\n/); - dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n")); - - throw Cr.NS_ERROR_ABORT; - } -} - -/** Constructs an HTTP error object. */ -function HttpError(code, description) -{ - this.code = code; - this.description = description; -} -HttpError.prototype = -{ - toString: function() - { - return this.code + " " + this.description; - } -}; - -/** -* Errors thrown to trigger specific HTTP server responses. -*/ -const HTTP_400 = new HttpError(400, "Bad Request"); -const HTTP_401 = new HttpError(401, "Unauthorized"); -const HTTP_402 = new HttpError(402, "Payment Required"); -const HTTP_403 = new HttpError(403, "Forbidden"); -const HTTP_404 = new HttpError(404, "Not Found"); -const HTTP_405 = new HttpError(405, "Method Not Allowed"); -const HTTP_406 = new HttpError(406, "Not Acceptable"); -const HTTP_407 = new HttpError(407, "Proxy Authentication Required"); -const HTTP_408 = new HttpError(408, "Request Timeout"); -const HTTP_409 = new HttpError(409, "Conflict"); -const HTTP_410 = new HttpError(410, "Gone"); -const HTTP_411 = new HttpError(411, "Length Required"); -const HTTP_412 = new HttpError(412, "Precondition Failed"); -const HTTP_413 = new HttpError(413, "Request Entity Too Large"); -const HTTP_414 = new HttpError(414, "Request-URI Too Long"); -const HTTP_415 = new HttpError(415, "Unsupported Media Type"); -const HTTP_417 = new HttpError(417, "Expectation Failed"); - -const HTTP_500 = new HttpError(500, "Internal Server Error"); -const HTTP_501 = new HttpError(501, "Not Implemented"); -const HTTP_502 = new HttpError(502, "Bad Gateway"); -const HTTP_503 = new HttpError(503, "Service Unavailable"); -const HTTP_504 = new HttpError(504, "Gateway Timeout"); -const HTTP_505 = new HttpError(505, "HTTP Version Not Supported"); - -/** Creates a hash with fields corresponding to the values in arr. */ -function array2obj(arr) -{ - var obj = {}; - for (var i = 0; i < arr.length; i++) - obj[arr[i]] = arr[i]; - return obj; -} - -/** Returns an array of the integers x through y, inclusive. */ -function range(x, y) -{ - var arr = []; - for (var i = x; i <= y; i++) - arr.push(i); - return arr; -} - -/** An object (hash) whose fields are the numbers of all HTTP error codes. */ -const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505))); - - -/** -* The character used to distinguish hidden files from non-hidden files, a la -* the leading dot in Apache. Since that mechanism also hides files from -* easy display in LXR, ls output, etc. however, we choose instead to use a -* suffix character. If a requested file ends with it, we append another -* when getting the file on the server. If it doesn't, we just look up that -* file. Therefore, any file whose name ends with exactly one of the character -* is "hidden" and available for use by the server. -*/ -const HIDDEN_CHAR = "^"; - -/** -* The file name suffix indicating the file containing overridden headers for -* a requested file. -*/ -const HEADERS_SUFFIX = HIDDEN_CHAR + "headers" + HIDDEN_CHAR; - -/** Type used to denote SJS scripts for CGI-like functionality. */ -const SJS_TYPE = "sjs"; - -/** Base for relative timestamps produced by dumpn(). */ -var firstStamp = 0; - -/** dump(str) with a trailing "\n" -- only outputs if DEBUG. */ -function dumpn(str) -{ - if (DEBUG) - { - var prefix = "HTTPD-INFO | "; - if (DEBUG_TIMESTAMP) - { - if (firstStamp === 0) - firstStamp = Date.now(); - - var elapsed = Date.now() - firstStamp; // milliseconds - var min = Math.floor(elapsed / 60000); - var sec = (elapsed % 60000) / 1000; - - if (sec < 10) - prefix += min + ":0" + sec.toFixed(3) + " | "; - else - prefix += min + ":" + sec.toFixed(3) + " | "; - } - - dump(prefix + str + "\n"); - } -} - -/** Dumps the current JS stack if DEBUG. */ -function dumpStack() -{ - // peel off the frames for dumpStack() and Error() - var stack = new Error().stack.split(/\n/).slice(2); - stack.forEach(dumpn); -} - - -/** The XPCOM thread manager. */ -var gThreadManager = null; - -/** The XPCOM prefs service. */ -var gRootPrefBranch = null; -function getRootPrefBranch() -{ - if (!gRootPrefBranch) - { - gRootPrefBranch = Cc["@mozilla.org/preferences-service;1"] - .getService(Ci.nsIPrefBranch); - } - return gRootPrefBranch; -} - -/** -* JavaScript constructors for commonly-used classes; precreating these is a -* speedup over doing the same from base principles. See the docs at -* http://developer.mozilla.org/en/docs/components.Constructor for details. -*/ -const ServerSocket = CC("@mozilla.org/network/server-socket;1", - "nsIServerSocket", - "init"); -const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1", - "nsIScriptableInputStream", - "init"); -const Pipe = CC("@mozilla.org/pipe;1", - "nsIPipe", - "init"); -const FileInputStream = CC("@mozilla.org/network/file-input-stream;1", - "nsIFileInputStream", - "init"); -const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1", - "nsIConverterInputStream", - "init"); -const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1", - "nsIWritablePropertyBag2"); -const SupportsString = CC("@mozilla.org/supports-string;1", - "nsISupportsString"); - -/* These two are non-const only so a test can overwrite them. */ -var BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); -var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1", - "nsIBinaryOutputStream", - "setOutputStream"); - -/** -* Returns the RFC 822/1123 representation of a date. -* -* @param date : Number -* the date, in milliseconds from midnight (00:00:00), January 1, 1970 GMT -* @returns string -* the representation of the given date -*/ -function toDateString(date) -{ - // - // rfc1123-date = wkday "," SP date1 SP time SP "GMT" - // date1 = 2DIGIT SP month SP 4DIGIT - // ; day month year (e.g., 02 Jun 1982) - // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT - // ; 00:00:00 - 23:59:59 - // wkday = "Mon" | "Tue" | "Wed" - // | "Thu" | "Fri" | "Sat" | "Sun" - // month = "Jan" | "Feb" | "Mar" | "Apr" - // | "May" | "Jun" | "Jul" | "Aug" - // | "Sep" | "Oct" | "Nov" | "Dec" - // - - const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - - /** -* Processes a date and returns the encoded UTC time as a string according to -* the format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toTime(date) - { - var hrs = date.getUTCHours(); - var rv = (hrs < 10) ? "0" + hrs : hrs; - - var mins = date.getUTCMinutes(); - rv += ":"; - rv += (mins < 10) ? "0" + mins : mins; - - var secs = date.getUTCSeconds(); - rv += ":"; - rv += (secs < 10) ? "0" + secs : secs; - - return rv; - } - - /** -* Processes a date and returns the encoded UTC date as a string according to -* the date1 format specified in RFC 2616. -* -* @param date : Date -* the date to process -* @returns string -* a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59" -*/ - function toDate1(date) - { - var day = date.getUTCDate(); - var month = date.getUTCMonth(); - var year = date.getUTCFullYear(); - - var rv = (day < 10) ? "0" + day : day; - rv += " " + monthStrings[month]; - rv += " " + year; - - return rv; - } - - date = new Date(date); - - const fmtString = "%wkday%, %date1% %time% GMT"; - var rv = fmtString.replace("%wkday%", wkdayStrings[date.getUTCDay()]); - rv = rv.replace("%time%", toTime(date)); - return rv.replace("%date1%", toDate1(date)); -} - -/** -* Prints out a human-readable representation of the object o and its fields, -* omitting those whose names begin with "_" if showMembers != true (to ignore -* "private" properties exposed via getters/setters). -*/ -function printObj(o, showMembers) -{ - var s = "******************************\n"; - s += "o = {\n"; - for (var i in o) - { - if (typeof(i) != "string" || - (showMembers || (i.length > 0 && i[0] != "_"))) - s+= " " + i + ": " + o[i] + ",\n"; - } - s += " };\n"; - s += "******************************"; - dumpn(s); -} - -/** -* Instantiates a new HTTP server. -*/ -function nsHttpServer() -{ - if (!gThreadManager) - gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService(); - - /** The port on which this server listens. */ - this._port = undefined; - - /** The socket associated with this. */ - this._socket = null; - - /** The handler used to process requests to this server. */ - this._handler = new ServerHandler(this); - - /** Naming information for this server. */ - this._identity = new ServerIdentity(); - - /** -* Indicates when the server is to be shut down at the end of the request. -*/ - this._doQuit = false; - - /** -* True if the socket in this is closed (and closure notifications have been -* sent and processed if the socket was ever opened), false otherwise. -*/ - this._socketClosed = true; - - /** -* Used for tracking existing connections and ensuring that all connections -* are properly cleaned up before server shutdown; increases by 1 for every -* new incoming connection. -*/ - this._connectionGen = 0; - - /** -* Hash of all open connections, indexed by connection number at time of -* creation. -*/ - this._connections = {}; -} -nsHttpServer.prototype = -{ - classID: components.ID("{54ef6f81-30af-4b1d-ac55-8ba811293e41}"), - - // NSISERVERSOCKETLISTENER - - /** -* Processes an incoming request coming in on the given socket and contained -* in the given transport. -* -* @param socket : nsIServerSocket -* the socket through which the request was served -* @param trans : nsISocketTransport -* the transport for the request/response -* @see nsIServerSocketListener.onSocketAccepted -*/ - onSocketAccepted: function(socket, trans) - { - dumpn("*** onSocketAccepted(socket=" + socket + ", trans=" + trans + ")"); - - dumpn(">>> new connection on " + trans.host + ":" + trans.port); - - const SEGMENT_SIZE = 8192; - const SEGMENT_COUNT = 1024; - try - { - var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT) - .QueryInterface(Ci.nsIAsyncInputStream); - var output = trans.openOutputStream(0, 0, 0); - } - catch (e) - { - dumpn("*** error opening transport streams: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - var connectionNumber = ++this._connectionGen; - - try - { - var conn = new Connection(input, output, this, socket.port, trans.port, - connectionNumber); - var reader = new RequestReader(conn); - - // XXX add request timeout functionality here! - - // Note: must use main thread here, or we might get a GC that will cause - // threadsafety assertions. We really need to fix XPConnect so that - // you can actually do things in multi-threaded JS. :-( - input.asyncWait(reader, 0, 0, gThreadManager.mainThread); - } - catch (e) - { - // Assume this connection can't be salvaged and bail on it completely; - // don't attempt to close it so that we can assert that any connection - // being closed is in this._connections. - dumpn("*** error in initial request-processing stages: " + e); - trans.close(Cr.NS_BINDING_ABORTED); - return; - } - - this._connections[connectionNumber] = conn; - dumpn("*** starting connection " + connectionNumber); - }, - - /** -* Called when the socket associated with this is closed. -* -* @param socket : nsIServerSocket -* the socket being closed -* @param status : nsresult -* the reason the socket stopped listening (NS_BINDING_ABORTED if the server -* was stopped using nsIHttpServer.stop) -* @see nsIServerSocketListener.onStopListening -*/ - onStopListening: function(socket, status) - { - dumpn(">>> shutting down server on port " + socket.port); - this._socketClosed = true; - if (!this._hasOpenConnections()) - { - dumpn("*** no open connections, notifying async from onStopListening"); - - // Notify asynchronously so that any pending teardown in stop() has a - // chance to run first. - var self = this; - var stopEvent = - { - run: function() - { - dumpn("*** _notifyStopped async callback"); - self._notifyStopped(); - } - }; - gThreadManager.currentThread - .dispatch(stopEvent, Ci.nsIThread.DISPATCH_NORMAL); - } - }, - - // NSIHTTPSERVER - - // - // see nsIHttpServer.start - // - start: function(port) - { - this._start(port, "localhost") - }, - - _start: function(port, host) - { - if (this._socket) - throw Cr.NS_ERROR_ALREADY_INITIALIZED; - - this._port = port; - this._doQuit = this._socketClosed = false; - - this._host = host; - - // The listen queue needs to be long enough to handle - // network.http.max-persistent-connections-per-server concurrent connections, - // plus a safety margin in case some other process is talking to - // the server as well. - var prefs = getRootPrefBranch(); - var maxConnections; - try { - // Bug 776860: The original pref was removed in favor of this new one: - maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server") + 5; - } - catch(e) { - maxConnections = prefs.getIntPref("network.http.max-connections-per-server") + 5; - } - - try - { - var loopback = true; - if (this._host != "127.0.0.1" && this._host != "localhost") { - var loopback = false; - } - - var socket = new ServerSocket(this._port, - loopback, // true = localhost, false = everybody - maxConnections); - dumpn(">>> listening on port " + socket.port + ", " + maxConnections + - " pending connections"); - socket.asyncListen(this); - this._identity._initialize(socket.port, host, true); - this._socket = socket; - } - catch (e) - { - dumpn("!!! could not start server on port " + port + ": " + e); - throw Cr.NS_ERROR_NOT_AVAILABLE; - } - }, - - // - // see nsIHttpServer.stop - // - stop: function(callback) - { - if (!callback) - throw Cr.NS_ERROR_NULL_POINTER; - if (!this._socket) - throw Cr.NS_ERROR_UNEXPECTED; - - this._stopCallback = typeof callback === "function" - ? callback - : function() { callback.onStopped(); }; - - dumpn(">>> stopping listening on port " + this._socket.port); - this._socket.close(); - this._socket = null; - - // We can't have this identity any more, and the port on which we're running - // this server now could be meaningless the next time around. - this._identity._teardown(); - - this._doQuit = false; - - // socket-close notification and pending request completion happen async - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (file && (!file.exists() || file.isDirectory())) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handler.registerFile(path, file); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // XXX true path validation! - if (path.charAt(0) != "/" || - path.charAt(path.length - 1) != "/" || - (directory && - (!directory.exists() || !directory.isDirectory()))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX determine behavior of nonexistent /foo/bar when a /foo/bar/ mapping - // exists! - - this._handler.registerDirectory(path, directory); - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - this._handler.registerPathHandler(path, handler); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - this._handler.registerPrefixHandler(prefix, handler); - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(code, handler) - { - this._handler.registerErrorHandler(code, handler); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - this._handler.setIndexHandler(handler); - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - this._handler.registerContentType(ext, type); - }, - - // - // see nsIHttpServer.serverIdentity - // - get identity() - { - return this._identity; - }, - - // - // see nsIHttpServer.getState - // - getState: function(path, k) - { - return this._handler._getState(path, k); - }, - - // - // see nsIHttpServer.setState - // - setState: function(path, k, v) - { - return this._handler._setState(path, k, v); - }, - - // - // see nsIHttpServer.getSharedState - // - getSharedState: function(k) - { - return this._handler._getSharedState(k); - }, - - // - // see nsIHttpServer.setSharedState - // - setSharedState: function(k, v) - { - return this._handler._setSharedState(k, v); - }, - - // - // see nsIHttpServer.getObjectState - // - getObjectState: function(k) - { - return this._handler._getObjectState(k); - }, - - // - // see nsIHttpServer.setObjectState - // - setObjectState: function(k, v) - { - return this._handler._setObjectState(k, v); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIServerSocketListener) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NON-XPCOM PUBLIC API - - /** -* Returns true iff this server is not running (and is not in the process of -* serving any requests still to be processed when the server was last -* stopped after being run). -*/ - isStopped: function() - { - return this._socketClosed && !this._hasOpenConnections(); - }, - - // PRIVATE IMPLEMENTATION - - /** True if this server has any open connections to it, false otherwise. */ - _hasOpenConnections: function() - { - // - // If we have any open connections, they're tracked as numeric properties on - // |this._connections|. The non-standard __count__ property could be used - // to check whether there are any properties, but standard-wise, even - // looking forward to ES5, there's no less ugly yet still O(1) way to do - // this. - // - for (var n in this._connections) - return true; - return false; - }, - - /** Calls the server-stopped callback provided when stop() was called. */ - _notifyStopped: function() - { - NS_ASSERT(this._stopCallback !== null, "double-notifying?"); - NS_ASSERT(!this._hasOpenConnections(), "should be done serving by now"); - - // - // NB: We have to grab this now, null out the member, *then* call the - // callback here, or otherwise the callback could (indirectly) futz with - // this._stopCallback by starting and immediately stopping this, at - // which point we'd be nulling out a field we no longer have a right to - // modify. - // - var callback = this._stopCallback; - this._stopCallback = null; - try - { - callback(); - } - catch (e) - { - // not throwing because this is specified as being usually (but not - // always) asynchronous - dump("!!! error running onStopped callback: " + e + "\n"); - } - }, - - /** -* Notifies this server that the given connection has been closed. -* -* @param connection : Connection -* the connection that was closed -*/ - _connectionClosed: function(connection) - { - NS_ASSERT(connection.number in this._connections, - "closing a connection " + this + " that we never added to the " + - "set of open connections?"); - NS_ASSERT(this._connections[connection.number] === connection, - "connection number mismatch? " + - this._connections[connection.number]); - delete this._connections[connection.number]; - - // Fire a pending server-stopped notification if it's our responsibility. - if (!this._hasOpenConnections() && this._socketClosed) - this._notifyStopped(); - }, - - /** -* Requests that the server be shut down when possible. -*/ - _requestQuit: function() - { - dumpn(">>> requesting a quit"); - dumpStack(); - this._doQuit = true; - } -}; - - -// -// RFC 2396 section 3.2.2: -// -// host = hostname | IPv4address -// hostname = *( domainlabel "." ) toplabel [ "." ] -// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum -// toplabel = alpha | alpha *( alphanum | "-" ) alphanum -// IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit -// - -const HOST_REGEX = - new RegExp("^(?:" + - // *( domainlabel "." ) - "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" + - // toplabel - "[a-z](?:[a-z0-9-]*[a-z0-9])?" + - "|" + - // IPv4 address - "\\d+\\.\\d+\\.\\d+\\.\\d+" + - ")$", - "i"); - - -/** -* Represents the identity of a server. An identity consists of a set of -* (scheme, host, port) tuples denoted as locations (allowing a single server to -* serve multiple sites or to be used behind both HTTP and HTTPS proxies for any -* host/port). Any incoming request must be to one of these locations, or it -* will be rejected with an HTTP 400 error. One location, denoted as the -* primary location, is the location assigned in contexts where a location -* cannot otherwise be endogenously derived, such as for HTTP/1.0 requests. -* -* A single identity may contain at most one location per unique host/port pair; -* other than that, no restrictions are placed upon what locations may -* constitute an identity. -*/ -function ServerIdentity() -{ - /** The scheme of the primary location. */ - this._primaryScheme = "http"; - - /** The hostname of the primary location. */ - this._primaryHost = "127.0.0.1" - - /** The port number of the primary location. */ - this._primaryPort = -1; - - /** -* The current port number for the corresponding server, stored so that a new -* primary location can always be set if the current one is removed. -*/ - this._defaultPort = -1; - - /** -* Maps hosts to maps of ports to schemes, e.g. the following would represent -* https://example.com:789/ and http://example.org/: -* -* { -* "xexample.com": { 789: "https" }, -* "xexample.org": { 80: "http" } -* } -* -* Note the "x" prefix on hostnames, which prevents collisions with special -* JS names like "prototype". -*/ - this._locations = { "xlocalhost": {} }; -} -ServerIdentity.prototype = -{ - // NSIHTTPSERVERIDENTITY - - // - // see nsIHttpServerIdentity.primaryScheme - // - get primaryScheme() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryScheme; - }, - - // - // see nsIHttpServerIdentity.primaryHost - // - get primaryHost() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryHost; - }, - - // - // see nsIHttpServerIdentity.primaryPort - // - get primaryPort() - { - if (this._primaryPort === -1) - throw Cr.NS_ERROR_NOT_INITIALIZED; - return this._primaryPort; - }, - - // - // see nsIHttpServerIdentity.add - // - add: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - this._locations["x" + host] = entry = {}; - - entry[port] = scheme; - }, - - // - // see nsIHttpServerIdentity.remove - // - remove: function(scheme, host, port) - { - this._validate(scheme, host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return false; - - var present = port in entry; - delete entry[port]; - - if (this._primaryScheme == scheme && - this._primaryHost == host && - this._primaryPort == port && - this._defaultPort !== -1) - { - // Always keep at least one identity in existence at any time, unless - // we're in the process of shutting down (the last condition above). - this._primaryPort = -1; - this._initialize(this._defaultPort, host, false); - } - - return present; - }, - - // - // see nsIHttpServerIdentity.has - // - has: function(scheme, host, port) - { - this._validate(scheme, host, port); - - return "x" + host in this._locations && - scheme === this._locations["x" + host][port]; - }, - - // - // see nsIHttpServerIdentity.has - // - getScheme: function(host, port) - { - this._validate("http", host, port); - - var entry = this._locations["x" + host]; - if (!entry) - return ""; - - return entry[port] || ""; - }, - - // - // see nsIHttpServerIdentity.setPrimary - // - setPrimary: function(scheme, host, port) - { - this._validate(scheme, host, port); - - this.add(scheme, host, port); - - this._primaryScheme = scheme; - this._primaryHost = host; - this._primaryPort = port; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpServerIdentity) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Initializes the primary name for the corresponding server, based on the -* provided port number. -*/ - _initialize: function(port, host, addSecondaryDefault) - { - this._host = host; - if (this._primaryPort !== -1) - this.add("http", host, port); - else - this.setPrimary("http", "localhost", port); - this._defaultPort = port; - - // Only add this if we're being called at server startup - if (addSecondaryDefault && host != "127.0.0.1") - this.add("http", "127.0.0.1", port); - }, - - /** -* Called at server shutdown time, unsets the primary location only if it was -* the default-assigned location and removes the default location from the -* set of locations used. -*/ - _teardown: function() - { - if (this._host != "127.0.0.1") { - // Not the default primary location, nothing special to do here - this.remove("http", "127.0.0.1", this._defaultPort); - } - - // This is a *very* tricky bit of reasoning here; make absolutely sure the - // tests for this code pass before you commit changes to it. - if (this._primaryScheme == "http" && - this._primaryHost == this._host && - this._primaryPort == this._defaultPort) - { - // Make sure we don't trigger the readding logic in .remove(), then remove - // the default location. - var port = this._defaultPort; - this._defaultPort = -1; - this.remove("http", this._host, port); - - // Ensure a server start triggers the setPrimary() path in ._initialize() - this._primaryPort = -1; - } - else - { - // No reason not to remove directly as it's not our primary location - this.remove("http", this._host, this._defaultPort); - } - }, - - /** -* Ensures scheme, host, and port are all valid with respect to RFC 2396. -* -* @throws NS_ERROR_ILLEGAL_VALUE -* if any argument doesn't match the corresponding production -*/ - _validate: function(scheme, host, port) - { - if (scheme !== "http" && scheme !== "https") - { - dumpn("*** server only supports http/https schemes: '" + scheme + "'"); - dumpStack(); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (!HOST_REGEX.test(host)) - { - dumpn("*** unexpected host: '" + host + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - if (port < 0 || port > 65535) - { - dumpn("*** unexpected port: '" + port + "'"); - throw Cr.NS_ERROR_ILLEGAL_VALUE; - } - } -}; - - -/** -* Represents a connection to the server (and possibly in the future the thread -* on which the connection is processed). -* -* @param input : nsIInputStream -* stream from which incoming data on the connection is read -* @param output : nsIOutputStream -* stream to write data out the connection -* @param server : nsHttpServer -* the server handling the connection -* @param port : int -* the port on which the server is running -* @param outgoingPort : int -* the outgoing port used by this connection -* @param number : uint -* a serial number used to uniquely identify this connection -*/ -function Connection(input, output, server, port, outgoingPort, number) -{ - dumpn("*** opening new connection " + number + " on port " + outgoingPort); - - /** Stream of incoming data. */ - this.input = input; - - /** Stream for outgoing data. */ - this.output = output; - - /** The server associated with this request. */ - this.server = server; - - /** The port on which the server is running. */ - this.port = port; - - /** The outgoing poort used by this connection. */ - this._outgoingPort = outgoingPort; - - /** The serial number of this connection. */ - this.number = number; - - /** -* The request for which a response is being generated, null if the -* incoming request has not been fully received or if it had errors. -*/ - this.request = null; - - /** State variables for debugging. */ - this._closed = this._processed = false; -} -Connection.prototype = -{ - /** Closes this connection's input/output streams. */ - close: function() - { - dumpn("*** closing connection " + this.number + - " on port " + this._outgoingPort); - - this.input.close(); - this.output.close(); - this._closed = true; - - var server = this.server; - server._connectionClosed(this); - - // If an error triggered a server shutdown, act on it now - if (server._doQuit) - server.stop(function() { /* not like we can do anything better */ }); - }, - - /** -* Initiates processing of this connection, using the data in the given -* request. -* -* @param request : Request -* the request which should be processed -*/ - process: function(request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - - this.request = request; - this.server._handler.handleResponse(this); - }, - - /** -* Initiates processing of this connection, generating a response with the -* given HTTP error code. -* -* @param code : uint -* an HTTP code, so in the range [0, 1000) -* @param request : Request -* incomplete data about the incoming request (since there were errors -* during its processing -*/ - processError: function(code, request) - { - NS_ASSERT(!this._closed && !this._processed); - - this._processed = true; - this.request = request; - this.server._handler.handleError(code, this); - }, - - /** Converts this to a string for debugging purposes. */ - toString: function() - { - return ""; - } -}; - - - -/** Returns an array of count bytes from the given input stream. */ -function readBytes(inputStream, count) -{ - return new BinaryInputStream(inputStream).readByteArray(count); -} - - - -/** Request reader processing states; see RequestReader for details. */ -const READER_IN_REQUEST_LINE = 0; -const READER_IN_HEADERS = 1; -const READER_IN_BODY = 2; -const READER_FINISHED = 3; - - -/** -* Reads incoming request data asynchronously, does any necessary preprocessing, -* and forwards it to the request handler. Processing occurs in three states: -* -* READER_IN_REQUEST_LINE Reading the request's status line -* READER_IN_HEADERS Reading headers in the request -* READER_IN_BODY Reading the body of the request -* READER_FINISHED Entire request has been read and processed -* -* During the first two stages, initial metadata about the request is gathered -* into a Request object. Once the status line and headers have been processed, -* we start processing the body of the request into the Request. Finally, when -* the entire body has been read, we create a Response and hand it off to the -* ServerHandler to be given to the appropriate request handler. -* -* @param connection : Connection -* the connection for the request being read -*/ -function RequestReader(connection) -{ - /** Connection metadata for this request. */ - this._connection = connection; - - /** -* A container providing line-by-line access to the raw bytes that make up the -* data which has been read from the connection but has not yet been acted -* upon (by passing it to the request handler or by extracting request -* metadata from it). -*/ - this._data = new LineData(); - - /** -* The amount of data remaining to be read from the body of this request. -* After all headers in the request have been read this is the value in the -* Content-Length header, but as the body is read its value decreases to zero. -*/ - this._contentLength = 0; - - /** The current state of parsing the incoming request. */ - this._state = READER_IN_REQUEST_LINE; - - /** Metadata constructed from the incoming request for the request handler. */ - this._metadata = new Request(connection.port); - - /** -* Used to preserve state if we run out of line data midway through a -* multi-line header. _lastHeaderName stores the name of the header, while -* _lastHeaderValue stores the value we've seen so far for the header. -* -* These fields are always either both undefined or both strings. -*/ - this._lastHeaderName = this._lastHeaderValue = undefined; -} -RequestReader.prototype = -{ - // NSIINPUTSTREAMCALLBACK - - /** -* Called when more data from the incoming request is available. This method -* then reads the available data from input and deals with that data as -* necessary, depending upon the syntax of already-downloaded data. -* -* @param input : nsIAsyncInputStream -* the stream of incoming data from the connection -*/ - onInputStreamReady: function(input) - { - dumpn("*** onInputStreamReady(input=" + input + ") on thread " + - gThreadManager.currentThread + " (main is " + - gThreadManager.mainThread + ")"); - dumpn("*** this._state == " + this._state); - - // Handle cases where we get more data after a request error has been - // discovered but *before* we can close the connection. - var data = this._data; - if (!data) - return; - - try - { - data.appendBytes(readBytes(input, input.available())); - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** WARNING: unexpected error when reading from socket; will " + - "be treated as if the input stream had been closed"); - dumpn("*** WARNING: actual error was: " + e); - } - - // We've lost a race -- input has been closed, but we're still expecting - // to read more data. available() will throw in this case, and since - // we're dead in the water now, destroy the connection. - dumpn("*** onInputStreamReady called on a closed input, destroying " + - "connection"); - this._connection.close(); - return; - } - - switch (this._state) - { - default: - NS_ASSERT(false, "invalid state: " + this._state); - break; - - case READER_IN_REQUEST_LINE: - if (!this._processRequestLine()) - break; - /* fall through */ - - case READER_IN_HEADERS: - if (!this._processHeaders()) - break; - /* fall through */ - - case READER_IN_BODY: - this._processBody(); - } - - if (this._state != READER_FINISHED) - input.asyncWait(this, 0, 0, gThreadManager.currentThread); - }, - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIInputStreamCallback) || - aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE API - - /** -* Processes unprocessed, downloaded data as a request line. -* -* @returns boolean -* true iff the request line has been fully processed -*/ - _processRequestLine: function() - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - // Servers SHOULD ignore any empty line(s) received where a Request-Line - // is expected (section 4.1). - var data = this._data; - var line = {}; - var readSuccess; - while ((readSuccess = data.readLine(line)) && line.value == "") - dumpn("*** ignoring beginning blank line..."); - - // if we don't have a full line, wait until we do - if (!readSuccess) - return false; - - // we have the first non-blank line - try - { - this._parseRequestLine(line.value); - this._state = READER_IN_HEADERS; - return true; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing request headers. -* -* @returns boolean -* true iff header data in the request has been fully processed -*/ - _processHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - // XXX things to fix here: - // - // - need to support RFC 2047-encoded non-US-ASCII characters - - try - { - var done = this._parseHeaders(); - if (done) - { - var request = this._metadata; - - // XXX this is wrong for requests with transfer-encodings applied to - // them, particularly chunked (which by its nature can have no - // meaningful Content-Length header)! - this._contentLength = request.hasHeader("Content-Length") - ? parseInt(request.getHeader("Content-Length"), 10) - : 0; - dumpn("_processHeaders, Content-length=" + this._contentLength); - - this._state = READER_IN_BODY; - } - return done; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Processes stored data, assuming it is either at the beginning or in -* the middle of processing the request body. -* -* @returns boolean -* true iff the request body has been fully processed -*/ - _processBody: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - // XXX handle chunked transfer-coding request bodies! - - try - { - if (this._contentLength > 0) - { - var data = this._data.purge(); - var count = Math.min(data.length, this._contentLength); - dumpn("*** loading data=" + data + " len=" + data.length + - " excess=" + (data.length - count)); - - var bos = new BinaryOutputStream(this._metadata._bodyOutputStream); - bos.writeByteArray(data, count); - this._contentLength -= count; - } - - dumpn("*** remaining body data len=" + this._contentLength); - if (this._contentLength == 0) - { - this._validateRequest(); - this._state = READER_FINISHED; - this._handleResponse(); - return true; - } - - return false; - } - catch (e) - { - this._handleError(e); - return false; - } - }, - - /** -* Does various post-header checks on the data in this request. -* -* @throws : HttpError -* if the request was malformed in some way -*/ - _validateRequest: function() - { - NS_ASSERT(this._state == READER_IN_BODY); - - dumpn("*** _validateRequest"); - - var metadata = this._metadata; - var headers = metadata._headers; - - // 19.6.1.1 -- servers MUST report 400 to HTTP/1.1 requests w/o Host header - var identity = this._connection.server.identity; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - { - if (!headers.hasHeader("Host")) - { - dumpn("*** malformed HTTP/1.1 or greater request with no Host header!"); - throw HTTP_400; - } - - // If the Request-URI wasn't absolute, then we need to determine our host. - // We have to determine what scheme was used to access us based on the - // server identity data at this point, because the request just doesn't - // contain enough data on its own to do this, sadly. - if (!metadata._host) - { - var host, port; - var hostPort = headers.getHeader("Host"); - var colon = hostPort.indexOf(":"); - if (colon < 0) - { - host = hostPort; - port = ""; - } - else - { - host = hostPort.substring(0, colon); - port = hostPort.substring(colon + 1); - } - - // NB: We allow an empty port here because, oddly, a colon may be - // present even without a port number, e.g. "example.com:"; in this - // case the default port applies. - if (!HOST_REGEX.test(host) || !/^\d*$/.test(port)) - { - dumpn("*** malformed hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - // If we're not given a port, we're stuck, because we don't know what - // scheme to use to look up the correct port here, in general. Since - // the HTTPS case requires a tunnel/proxy and thus requires that the - // requested URI be absolute (and thus contain the necessary - // information), let's assume HTTP will prevail and use that. - port = +port || 80; - - var scheme = identity.getScheme(host, port); - if (!scheme) - { - dumpn("*** unrecognized hostname (" + hostPort + ") in Host " + - "header, 400 time"); - throw HTTP_400; - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - } - } - else - { - NS_ASSERT(metadata._host === undefined, - "HTTP/1.0 doesn't allow absolute paths in the request line!"); - - metadata._scheme = identity.primaryScheme; - metadata._host = identity.primaryHost; - metadata._port = identity.primaryPort; - } - - NS_ASSERT(identity.has(metadata._scheme, metadata._host, metadata._port), - "must have a location we recognize by now!"); - }, - - /** -* Handles responses in case of error, either in the server or in the request. -* -* @param e -* the specific error encountered, which is an HttpError in the case where -* the request is in some way invalid or cannot be fulfilled; if this isn't -* an HttpError we're going to be paranoid and shut down, because that -* shouldn't happen, ever -*/ - _handleError: function(e) - { - // Don't fall back into normal processing! - this._state = READER_FINISHED; - - var server = this._connection.server; - if (e instanceof HttpError) - { - var code = e.code; - } - else - { - dumpn("!!! UNEXPECTED ERROR: " + e + - (e.lineNumber ? ", line " + e.lineNumber : "")); - - // no idea what happened -- be paranoid and shut down - code = 500; - server._requestQuit(); - } - - // make attempted reuse of data an error - this._data = null; - - this._connection.processError(code, this._metadata); - }, - - /** -* Now that we've read the request line and headers, we can actually hand off -* the request to be handled. -* -* This method is called once per request, after the request line and all -* headers and the body, if any, have been received. -*/ - _handleResponse: function() - { - NS_ASSERT(this._state == READER_FINISHED); - - // We don't need the line-based data any more, so make attempted reuse an - // error. - this._data = null; - - this._connection.process(this._metadata); - }, - - - // PARSING - - /** -* Parses the request line for the HTTP request associated with this. -* -* @param line : string -* the request line -*/ - _parseRequestLine: function(line) - { - NS_ASSERT(this._state == READER_IN_REQUEST_LINE); - - dumpn("*** _parseRequestLine('" + line + "')"); - - var metadata = this._metadata; - - // clients and servers SHOULD accept any amount of SP or HT characters - // between fields, even though only a single SP is required (section 19.3) - var request = line.split(/[ \t]+/); - if (!request || request.length != 3) - throw HTTP_400; - - metadata._method = request[0]; - - // get the HTTP version - var ver = request[2]; - var match = ver.match(/^HTTP\/(\d+\.\d+)$/); - if (!match) - throw HTTP_400; - - // determine HTTP version - try - { - metadata._httpVersion = new nsHttpVersion(match[1]); - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_0)) - throw "unsupported HTTP version"; - } - catch (e) - { - // we support HTTP/1.0 and HTTP/1.1 only - throw HTTP_501; - } - - - var fullPath = request[1]; - var serverIdentity = this._connection.server.identity; - - var scheme, host, port; - - if (fullPath.charAt(0) != "/") - { - // No absolute paths in the request line in HTTP prior to 1.1 - if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1)) - throw HTTP_400; - - try - { - var uri = Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService) - .newURI(fullPath, null, null); - fullPath = uri.path; - scheme = uri.scheme; - host = metadata._host = uri.asciiHost; - port = uri.port; - if (port === -1) - { - if (scheme === "http") - port = 80; - else if (scheme === "https") - port = 443; - else - throw HTTP_400; - } - } - catch (e) - { - // If the host is not a valid host on the server, the response MUST be a - // 400 (Bad Request) error message (section 5.2). Alternately, the URI - // is malformed. - throw HTTP_400; - } - - if (!serverIdentity.has(scheme, host, port) || fullPath.charAt(0) != "/") - throw HTTP_400; - } - - var splitter = fullPath.indexOf("?"); - if (splitter < 0) - { - // _queryString already set in ctor - metadata._path = fullPath; - } - else - { - metadata._path = fullPath.substring(0, splitter); - metadata._queryString = fullPath.substring(splitter + 1); - } - - metadata._scheme = scheme; - metadata._host = host; - metadata._port = port; - }, - - /** -* Parses all available HTTP headers in this until the header-ending CRLFCRLF, -* adding them to the store of headers in the request. -* -* @throws -* HTTP_400 if the headers are malformed -* @returns boolean -* true if all headers have now been processed, false otherwise -*/ - _parseHeaders: function() - { - NS_ASSERT(this._state == READER_IN_HEADERS); - - dumpn("*** _parseHeaders"); - - var data = this._data; - - var headers = this._metadata._headers; - var lastName = this._lastHeaderName; - var lastVal = this._lastHeaderValue; - - var line = {}; - while (true) - { - NS_ASSERT(!((lastVal === undefined) ^ (lastName === undefined)), - lastName === undefined ? - "lastVal without lastName? lastVal: '" + lastVal + "'" : - "lastName without lastVal? lastName: '" + lastName + "'"); - - if (!data.readLine(line)) - { - // save any data we have from the header we might still be processing - this._lastHeaderName = lastName; - this._lastHeaderValue = lastVal; - return false; - } - - var lineText = line.value; - var firstChar = lineText.charAt(0); - - // blank line means end of headers - if (lineText == "") - { - // we're finished with the previous header - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - else - { - // no headers in request -- valid for HTTP/1.0 requests - } - - // either way, we're done processing headers - this._state = READER_IN_BODY; - return true; - } - else if (firstChar == " " || firstChar == "\t") - { - // multi-line header if we've already seen a header line - if (!lastName) - { - // we don't have a header to continue! - throw HTTP_400; - } - - // append this line's text to the value; starts with SP/HT, so no need - // for separating whitespace - lastVal += lineText; - } - else - { - // we have a new header, so set the old one (if one existed) - if (lastName) - { - try - { - headers.setHeader(lastName, lastVal, true); - } - catch (e) - { - dumpn("*** e == " + e); - throw HTTP_400; - } - } - - var colon = lineText.indexOf(":"); // first colon must be splitter - if (colon < 1) - { - // no colon or missing header field-name - throw HTTP_400; - } - - // set header name, value (to be set in the next loop, usually) - lastName = lineText.substring(0, colon); - lastVal = lineText.substring(colon + 1); - } // empty, continuation, start of header - } // while (true) - } -}; - - -/** The character codes for CR and LF. */ -const CR = 0x0D, LF = 0x0A; - -/** -* Calculates the number of characters before the first CRLF pair in array, or -* -1 if the array contains no CRLF pair. -* -* @param array : Array -* an array of numbers in the range [0, 256), each representing a single -* character; the first CRLF is the lowest index i where -* |array[i] == "\r".charCodeAt(0)| and |array[i+1] == "\n".charCodeAt(0)|, -* if such an |i| exists, and -1 otherwise -* @returns int -* the index of the first CRLF if any were present, -1 otherwise -*/ -function findCRLF(array) -{ - for (var i = array.indexOf(CR); i >= 0; i = array.indexOf(CR, i + 1)) - { - if (array[i + 1] == LF) - return i; - } - return -1; -} - - -/** -* A container which provides line-by-line access to the arrays of bytes with -* which it is seeded. -*/ -function LineData() -{ - /** An array of queued bytes from which to get line-based characters. */ - this._data = []; -} -LineData.prototype = -{ - /** -* Appends the bytes in the given array to the internal data cache maintained -* by this. -*/ - appendBytes: function(bytes) - { - Array.prototype.push.apply(this._data, bytes); - }, - - /** -* Removes and returns a line of data, delimited by CRLF, from this. -* -* @param out -* an object whose "value" property will be set to the first line of text -* present in this, sans CRLF, if this contains a full CRLF-delimited line -* of text; if this doesn't contain enough data, the value of the property -* is undefined -* @returns boolean -* true if a full line of data could be read from the data in this, false -* otherwise -*/ - readLine: function(out) - { - var data = this._data; - var length = findCRLF(data); - if (length < 0) - return false; - - // - // We have the index of the CR, so remove all the characters, including - // CRLF, from the array with splice, and convert the removed array into the - // corresponding string, from which we then strip the trailing CRLF. - // - // Getting the line in this matter acknowledges that substring is an O(1) - // operation in SpiderMonkey because strings are immutable, whereas two - // splices, both from the beginning of the data, are less likely to be as - // cheap as a single splice plus two extra character conversions. - // - var line = String.fromCharCode.apply(null, data.splice(0, length + 2)); - out.value = line.substring(0, length); - - return true; - }, - - /** -* Removes the bytes currently within this and returns them in an array. -* -* @returns Array -* the bytes within this when this method is called -*/ - purge: function() - { - var data = this._data; - this._data = []; - return data; - } -}; - - - -/** -* Creates a request-handling function for an nsIHttpRequestHandler object. -*/ -function createHandlerFunc(handler) -{ - return function(metadata, response) { handler.handle(metadata, response); }; -} - - -/** -* The default handler for directories; writes an HTML response containing a -* slightly-formatted directory listing. -*/ -function defaultIndexHandler(metadata, response) -{ - response.setHeader("Content-Type", "text/html", false); - - var path = htmlEscape(decodeURI(metadata.path)); - - // - // Just do a very basic bit of directory listings -- no need for too much - // fanciness, especially since we don't have a style sheet in which we can - // stick rules (don't want to pollute the default path-space). - // - - var body = '\ -\ -' + path + '\ -\ -\ -

' + path + '

\ -
    '; - - var directory = metadata.getProperty("directory").QueryInterface(Ci.nsILocalFile); - NS_ASSERT(directory && directory.isDirectory()); - - var fileList = []; - var files = directory.directoryEntries; - while (files.hasMoreElements()) - { - var f = files.getNext().QueryInterface(Ci.nsIFile); - var name = f.leafName; - if (!f.isHidden() && - (name.charAt(name.length - 1) != HIDDEN_CHAR || - name.charAt(name.length - 2) == HIDDEN_CHAR)) - fileList.push(f); - } - - fileList.sort(fileSort); - - for (var i = 0; i < fileList.length; i++) - { - var file = fileList[i]; - try - { - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - var sep = file.isDirectory() ? "/" : ""; - - // Note: using " to delimit the attribute here because encodeURIComponent - // passes through '. - var item = '
  1. ' + - htmlEscape(name) + sep + - '
  2. '; - - body += item; - } - catch (e) { /* some file system error, ignore the file */ } - } - - body += '
\ -\ -'; - - response.bodyOutputStream.write(body, body.length); -} - -/** -* Sorts a and b (nsIFile objects) into an aesthetically pleasing order. -*/ -function fileSort(a, b) -{ - var dira = a.isDirectory(), dirb = b.isDirectory(); - - if (dira && !dirb) - return -1; - if (dirb && !dira) - return 1; - - var namea = a.leafName.toLowerCase(), nameb = b.leafName.toLowerCase(); - return nameb > namea ? -1 : 1; -} - - -/** -* Converts an externally-provided path into an internal path for use in -* determining file mappings. -* -* @param path -* the path to convert -* @param encoded -* true if the given path should be passed through decodeURI prior to -* conversion -* @throws URIError -* if path is incorrectly encoded -*/ -function toInternalPath(path, encoded) -{ - if (encoded) - path = decodeURI(path); - - var comps = path.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - if (comp.charAt(comp.length - 1) == HIDDEN_CHAR) - comps[i] = comp + HIDDEN_CHAR; - } - return comps.join("/"); -} - - -/** -* Adds custom-specified headers for the given file to the given response, if -* any such headers are specified. -* -* @param file -* the file on the disk which is to be written -* @param metadata -* metadata about the incoming request -* @param response -* the Response to which any specified headers/data should be written -* @throws HTTP_500 -* if an error occurred while processing custom-specified headers -*/ -function maybeAddHeaders(file, metadata, response) -{ - var name = file.leafName; - if (name.charAt(name.length - 1) == HIDDEN_CHAR) - name = name.substring(0, name.length - 1); - - var headerFile = file.parent; - headerFile.append(name + HEADERS_SUFFIX); - - if (!headerFile.exists()) - return; - - const PR_RDONLY = 0x01; - var fis = new FileInputStream(headerFile, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0); - lis.QueryInterface(Ci.nsIUnicharLineInputStream); - - var line = {value: ""}; - var more = lis.readLine(line); - - if (!more && line.value == "") - return; - - - // request line - - var status = line.value; - if (status.indexOf("HTTP ") == 0) - { - status = status.substring(5); - var space = status.indexOf(" "); - var code, description; - if (space < 0) - { - code = status; - description = ""; - } - else - { - code = status.substring(0, space); - description = status.substring(space + 1, status.length); - } - - response.setStatusLine(metadata.httpVersion, parseInt(code, 10), description); - - line.value = ""; - more = lis.readLine(line); - } - - // headers - while (more || line.value != "") - { - var header = line.value; - var colon = header.indexOf(":"); - - response.setHeader(header.substring(0, colon), - header.substring(colon + 1, header.length), - false); // allow overriding server-set headers - - line.value = ""; - more = lis.readLine(line); - } - } - catch (e) - { - dumpn("WARNING: error in headers for " + metadata.path + ": " + e); - throw HTTP_500; - } - finally - { - fis.close(); - } -} - - -/** -* An object which handles requests for a server, executing default and -* overridden behaviors as instructed by the code which uses and manipulates it. -* Default behavior includes the paths / and /trace (diagnostics), with some -* support for HTTP error pages for various codes and fallback to HTTP 500 if -* those codes fail for any reason. -* -* @param server : nsHttpServer -* the server in which this handler is being used -*/ -function ServerHandler(server) -{ - // FIELDS - - /** -* The nsHttpServer instance associated with this handler. -*/ - this._server = server; - - /** -* A FileMap object containing the set of path->nsILocalFile mappings for -* all directory mappings set in the server (e.g., "/" for /var/www/html/, -* "/foo/bar/" for /local/path/, and "/foo/bar/baz/" for /local/path2). -* -* Note carefully: the leading and trailing "/" in each path (not file) are -* removed before insertion to simplify the code which uses this. You have -* been warned! -*/ - this._pathDirectoryMap = new FileMap(); - - /** -* Custom request handlers for the server in which this resides. Path-handler -* pairs are stored as property-value pairs in this property. -* -* @see ServerHandler.prototype._defaultPaths -*/ - this._overridePaths = {}; - - /** -* Custom request handlers for the server in which this resides. Prefix-handler -* pairs are stored as property-value pairs in this property. -*/ - this._overridePrefixes = {}; - - /** -* Custom request handlers for the error handlers in the server in which this -* resides. Path-handler pairs are stored as property-value pairs in this -* property. -* -* @see ServerHandler.prototype._defaultErrors -*/ - this._overrideErrors = {}; - - /** -* Maps file extensions to their MIME types in the server, overriding any -* mapping that might or might not exist in the MIME service. -*/ - this._mimeMappings = {}; - - /** -* The default handler for requests for directories, used to serve directories -* when no index file is present. -*/ - this._indexHandler = defaultIndexHandler; - - /** Per-path state storage for the server. */ - this._state = {}; - - /** Entire-server state storage. */ - this._sharedState = {}; - - /** Entire-server state storage for nsISupports values. */ - this._objectState = {}; -} -ServerHandler.prototype = -{ - // PUBLIC API - - /** -* Handles a request to this server, responding to the request appropriately -* and initiating server shutdown if necessary. -* -* This method never throws an exception. -* -* @param connection : Connection -* the connection for this request -*/ - handleResponse: function(connection) - { - var request = connection.request; - var response = new Response(connection); - - var path = request.path; - dumpn("*** path == " + path); - - try - { - try - { - if (path in this._overridePaths) - { - // explicit paths first, then files based on existing directory mappings, - // then (if the file doesn't exist) built-in server default paths - dumpn("calling override for " + path); - this._overridePaths[path](request, response); - } - else - { - let longestPrefix = ""; - for (let prefix in this._overridePrefixes) - { - if (prefix.length > longestPrefix.length && path.startsWith(prefix)) - { - longestPrefix = prefix; - } - } - if (longestPrefix.length > 0) - { - dumpn("calling prefix override for " + longestPrefix); - this._overridePrefixes[longestPrefix](request, response); - } - else - { - this._handleDefault(request, response); - } - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - if (!(e instanceof HttpError)) - { - dumpn("*** unexpected error: e == " + e); - throw HTTP_500; - } - if (e.code !== 404) - throw e; - - dumpn("*** default: " + (path in this._defaultPaths)); - - response = new Response(connection); - if (path in this._defaultPaths) - this._defaultPaths[path](request, response); - else - throw HTTP_404; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - var errorCode = "internal"; - - try - { - if (!(e instanceof HttpError)) - throw e; - - errorCode = e.code; - dumpn("*** errorCode == " + errorCode); - - response = new Response(connection); - if (e.customErrorHandling) - e.customErrorHandling(response); - this._handleError(errorCode, request, response); - return; - } - catch (e2) - { - dumpn("*** error handling " + errorCode + " error: " + - "e2 == " + e2 + ", shutting down server"); - - connection.server._requestQuit(); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // - // see nsIHttpServer.registerFile - // - registerFile: function(path, file) - { - if (!file) - { - dumpn("*** unregistering '" + path + "' mapping"); - delete this._overridePaths[path]; - return; - } - - dumpn("*** registering '" + path + "' as mapping to " + file.path); - file = file.clone(); - - var self = this; - this._overridePaths[path] = - function(request, response) - { - if (!file.exists()) - throw HTTP_404; - - response.setStatusLine(request.httpVersion, 200, "OK"); - self._writeFileResponse(request, file, response, 0, file.fileSize); - }; - }, - - // - // see nsIHttpServer.registerPathHandler - // - registerPathHandler: function(path, handler) - { - // XXX true path validation! - if (path.charAt(0) != "/") - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePaths, path); - }, - - // - // see nsIHttpServer.registerPrefixHandler - // - registerPrefixHandler: function(prefix, handler) - { - // XXX true prefix validation! - if (!(prefix.startsWith("/") && prefix.endsWith("/"))) - throw Cr.NS_ERROR_INVALID_ARG; - - this._handlerToField(handler, this._overridePrefixes, prefix); - }, - - // - // see nsIHttpServer.registerDirectory - // - registerDirectory: function(path, directory) - { - // strip off leading and trailing '/' so that we can use lastIndexOf when - // determining exactly how a path maps onto a mapped directory -- - // conditional is required here to deal with "/".substring(1, 0) being - // converted to "/".substring(0, 1) per the JS specification - var key = path.length == 1 ? "" : path.substring(1, path.length - 1); - - // the path-to-directory mapping code requires that the first character not - // be "/", or it will go into an infinite loop - if (key.charAt(0) == "/") - throw Cr.NS_ERROR_INVALID_ARG; - - key = toInternalPath(key, false); - - if (directory) - { - dumpn("*** mapping '" + path + "' to the location " + directory.path); - this._pathDirectoryMap.put(key, directory); - } - else - { - dumpn("*** removing mapping for '" + path + "'"); - this._pathDirectoryMap.put(key, null); - } - }, - - // - // see nsIHttpServer.registerErrorHandler - // - registerErrorHandler: function(err, handler) - { - if (!(err in HTTP_ERROR_CODES)) - dumpn("*** WARNING: registering non-HTTP/1.1 error code " + - "(" + err + ") handler -- was this intentional?"); - - this._handlerToField(handler, this._overrideErrors, err); - }, - - // - // see nsIHttpServer.setIndexHandler - // - setIndexHandler: function(handler) - { - if (!handler) - handler = defaultIndexHandler; - else if (typeof(handler) != "function") - handler = createHandlerFunc(handler); - - this._indexHandler = handler; - }, - - // - // see nsIHttpServer.registerContentType - // - registerContentType: function(ext, type) - { - if (!type) - delete this._mimeMappings[ext]; - else - this._mimeMappings[ext] = headerUtils.normalizeFieldValue(type); - }, - - // PRIVATE API - - /** -* Sets or remove (if handler is null) a handler in an object with a key. -* -* @param handler -* a handler, either function or an nsIHttpRequestHandler -* @param dict -* The object to attach the handler to. -* @param key -* The field name of the handler. -*/ - _handlerToField: function(handler, dict, key) - { - // for convenience, handler can be a function if this is run from xpcshell - if (typeof(handler) == "function") - dict[key] = handler; - else if (handler) - dict[key] = createHandlerFunc(handler); - else - delete dict[key]; - }, - - /** -* Handles a request which maps to a file in the local filesystem (if a base -* path has already been set; otherwise the 404 error is thrown). -* -* @param metadata : Request -* metadata for the incoming request -* @param response : Response -* an uninitialized Response to the given request, to be initialized by a -* request handler -* @throws HTTP_### -* if an HTTP error occurred (usually HTTP_404); note that in this case the -* calling code must handle post-processing of the response -*/ - _handleDefault: function(metadata, response) - { - dumpn("*** _handleDefault()"); - - response.setStatusLine(metadata.httpVersion, 200, "OK"); - - var path = metadata.path; - NS_ASSERT(path.charAt(0) == "/", "invalid path: <" + path + ">"); - - // determine the actual on-disk file; this requires finding the deepest - // path-to-directory mapping in the requested URL - var file = this._getFileForPath(path); - - // the "file" might be a directory, in which case we either serve the - // contained index.html or make the index handler write the response - if (file.exists() && file.isDirectory()) - { - file.append("index.html"); // make configurable? - if (!file.exists() || file.isDirectory()) - { - metadata._ensurePropertyBag(); - metadata._bag.setPropertyAsInterface("directory", file.parent); - this._indexHandler(metadata, response); - return; - } - } - - // alternately, the file might not exist - if (!file.exists()) - throw HTTP_404; - - var start, end; - if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1) && - metadata.hasHeader("Range") && - this._getTypeFromFile(file) !== SJS_TYPE) - { - var rangeMatch = metadata.getHeader("Range").match(/^bytes=(\d+)?-(\d+)?$/); - if (!rangeMatch) - throw HTTP_400; - - if (rangeMatch[1] !== undefined) - start = parseInt(rangeMatch[1], 10); - - if (rangeMatch[2] !== undefined) - end = parseInt(rangeMatch[2], 10); - - if (start === undefined && end === undefined) - throw HTTP_400; - - // No start given, so the end is really the count of bytes from the - // end of the file. - if (start === undefined) - { - start = Math.max(0, file.fileSize - end); - end = file.fileSize - 1; - } - - // start and end are inclusive - if (end === undefined || end >= file.fileSize) - end = file.fileSize - 1; - - if (start !== undefined && start >= file.fileSize) { - var HTTP_416 = new HttpError(416, "Requested Range Not Satisfiable"); - HTTP_416.customErrorHandling = function(errorResponse) - { - maybeAddHeaders(file, metadata, errorResponse); - }; - throw HTTP_416; - } - - if (end < start) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - start = 0; - end = file.fileSize - 1; - } - else - { - response.setStatusLine(metadata.httpVersion, 206, "Partial Content"); - var contentRange = "bytes " + start + "-" + end + "/" + file.fileSize; - response.setHeader("Content-Range", contentRange); - } - } - else - { - start = 0; - end = file.fileSize - 1; - } - - // finally... - dumpn("*** handling '" + path + "' as mapping to " + file.path + " from " + - start + " to " + end + " inclusive"); - this._writeFileResponse(metadata, file, response, start, end - start + 1); - }, - - /** -* Writes an HTTP response for the given file, including setting headers for -* file metadata. -* -* @param metadata : Request -* the Request for which a response is being generated -* @param file : nsILocalFile -* the file which is to be sent in the response -* @param response : Response -* the response to which the file should be written -* @param offset: uint -* the byte offset to skip to when writing -* @param count: uint -* the number of bytes to write -*/ - _writeFileResponse: function(metadata, file, response, offset, count) - { - const PR_RDONLY = 0x01; - - var type = this._getTypeFromFile(file); - if (type === SJS_TYPE) - { - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - try - { - var sis = new ScriptableInputStream(fis); - var s = Cu.Sandbox(gGlobalObject); - s.importFunction(dump, "dump"); - - // Define a basic key-value state-preservation API across requests, with - // keys initially corresponding to the empty string. - var self = this; - var path = metadata.path; - s.importFunction(function getState(k) - { - return self._getState(path, k); - }); - s.importFunction(function setState(k, v) - { - self._setState(path, k, v); - }); - s.importFunction(function getSharedState(k) - { - return self._getSharedState(k); - }); - s.importFunction(function setSharedState(k, v) - { - self._setSharedState(k, v); - }); - s.importFunction(function getObjectState(k, callback) - { - callback(self._getObjectState(k)); - }); - s.importFunction(function setObjectState(k, v) - { - self._setObjectState(k, v); - }); - s.importFunction(function registerPathHandler(p, h) - { - self.registerPathHandler(p, h); - }); - - // Make it possible for sjs files to access their location - this._setState(path, "__LOCATION__", file.path); - - try - { - // Alas, the line number in errors dumped to console when calling the - // request handler is simply an offset from where we load the SJS file. - // Work around this in a reasonably non-fragile way by dynamically - // getting the line number where we evaluate the SJS file. Don't - // separate these two lines! - var line = new Error().lineNumber; - Cu.evalInSandbox(sis.read(file.fileSize), s); - } - catch (e) - { - dumpn("*** syntax error in SJS at " + file.path + ": " + e); - throw HTTP_500; - } - - try - { - s.handleRequest(metadata, response); - } - catch (e) - { - dump("*** error running SJS at " + file.path + ": " + - e + " on line " + - (e instanceof Error - ? e.lineNumber + " in httpd.js" - : (e.lineNumber - line)) + "\n"); - throw HTTP_500; - } - } - finally - { - fis.close(); - } - } - else - { - try - { - response.setHeader("Last-Modified", - toDateString(file.lastModifiedTime), - false); - } - catch (e) { /* lastModifiedTime threw, ignore */ } - - response.setHeader("Content-Type", type, false); - maybeAddHeaders(file, metadata, response); - response.setHeader("Content-Length", "" + count, false); - - var fis = new FileInputStream(file, PR_RDONLY, 0o444, - Ci.nsIFileInputStream.CLOSE_ON_EOF); - - offset = offset || 0; - count = count || file.fileSize; - NS_ASSERT(offset === 0 || offset < file.fileSize, "bad offset"); - NS_ASSERT(count >= 0, "bad count"); - NS_ASSERT(offset + count <= file.fileSize, "bad total data size"); - - try - { - if (offset !== 0) - { - // Seek (or read, if seeking isn't supported) to the correct offset so - // the data sent to the client matches the requested range. - if (fis instanceof Ci.nsISeekableStream) - fis.seek(Ci.nsISeekableStream.NS_SEEK_SET, offset); - else - new ScriptableInputStream(fis).read(offset); - } - } - catch (e) - { - fis.close(); - throw e; - } - - let writeMore = function writeMore() - { - gThreadManager.currentThread - .dispatch(writeData, Ci.nsIThread.DISPATCH_NORMAL); - } - - var input = new BinaryInputStream(fis); - var output = new BinaryOutputStream(response.bodyOutputStream); - var writeData = - { - run: function() - { - var chunkSize = Math.min(65536, count); - count -= chunkSize; - NS_ASSERT(count >= 0, "underflow"); - - try - { - var data = input.readByteArray(chunkSize); - NS_ASSERT(data.length === chunkSize, - "incorrect data returned? got " + data.length + - ", expected " + chunkSize); - output.writeByteArray(data, data.length); - if (count === 0) - { - fis.close(); - response.finish(); - } - else - { - writeMore(); - } - } - catch (e) - { - try - { - fis.close(); - } - finally - { - response.finish(); - } - throw e; - } - } - }; - - writeMore(); - - // Now that we know copying will start, flag the response as async. - response.processAsync(); - } - }, - - /** -* Get the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getState: function(path, k) - { - var state = this._state; - if (path in state && k in state[path]) - return state[path][k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for the given path for SJS state -* preservation across requests. -* -* @param path : string -* the path from which the given state is to be retrieved -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setState: function(path, k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - var state = this._state; - if (!(path in state)) - state[path] = {}; - state[path][k] = v; - }, - - /** -* Get the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be returned -* @returns string -* the corresponding value, which is initially the empty string -*/ - _getSharedState: function(k) - { - var state = this._sharedState; - if (k in state) - return state[k]; - return ""; - }, - - /** -* Set the value corresponding to a given key for SJS state preservation -* across requests. -* -* @param k : string -* the key whose corresponding value is to be set -* @param v : string -* the value to be set -*/ - _setSharedState: function(k, v) - { - if (typeof v !== "string") - throw new Error("non-string value passed"); - this._sharedState[k] = v; - }, - - /** -* Returns the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be returned -* @returns nsISupports -* the corresponding object, or null if none was present -*/ - _getObjectState: function(k) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - return this._objectState[k] || null; - }, - - /** -* Sets the object associated with the given key in the server for SJS -* state preservation across requests. -* -* @param k : string -* the key whose corresponding object is to be set -* @param v : nsISupports -* the object to be associated with the given key; may be null -*/ - _setObjectState: function(k, v) - { - if (typeof k !== "string") - throw new Error("non-string key passed"); - if (typeof v !== "object") - throw new Error("non-object value passed"); - if (v && !("QueryInterface" in v)) - { - throw new Error("must pass an nsISupports; use wrappedJSObject to ease " + - "pain when using the server from JS"); - } - - this._objectState[k] = v; - }, - - /** -* Gets a content-type for the given file, first by checking for any custom -* MIME-types registered with this handler for the file's extension, second by -* asking the global MIME service for a content-type, and finally by failing -* over to application/octet-stream. -* -* @param file : nsIFile -* the nsIFile for which to get a file type -* @returns string -* the best content-type which can be determined for the file -*/ - _getTypeFromFile: function(file) - { - try - { - var name = file.leafName; - var dot = name.lastIndexOf("."); - if (dot > 0) - { - var ext = name.slice(dot + 1); - if (ext in this._mimeMappings) - return this._mimeMappings[ext]; - } - return Cc["@mozilla.org/uriloader/external-helper-app-service;1"] - .getService(Ci.nsIMIMEService) - .getTypeFromFile(file); - } - catch (e) - { - return "application/octet-stream"; - } - }, - - /** -* Returns the nsILocalFile which corresponds to the path, as determined using -* all registered path->directory mappings and any paths which are explicitly -* overridden. -* -* @param path : string -* the server path for which a file should be retrieved, e.g. "/foo/bar" -* @throws HttpError -* when the correct action is the corresponding HTTP error (i.e., because no -* mapping was found for a directory in path, the referenced file doesn't -* exist, etc.) -* @returns nsILocalFile -* the file to be sent as the response to a request for the path -*/ - _getFileForPath: function(path) - { - // decode and add underscores as necessary - try - { - path = toInternalPath(path, true); - } - catch (e) - { - throw HTTP_400; // malformed path - } - - // next, get the directory which contains this path - var pathMap = this._pathDirectoryMap; - - // An example progression of tmp for a path "/foo/bar/baz/" might be: - // "foo/bar/baz/", "foo/bar/baz", "foo/bar", "foo", "" - var tmp = path.substring(1); - while (true) - { - // do we have a match for current head of the path? - var file = pathMap.get(tmp); - if (file) - { - // XXX hack; basically disable showing mapping for /foo/bar/ when the - // requested path was /foo/bar, because relative links on the page - // will all be incorrect -- we really need the ability to easily - // redirect here instead - if (tmp == path.substring(1) && - tmp.length != 0 && - tmp.charAt(tmp.length - 1) != "/") - file = null; - else - break; - } - - // if we've finished trying all prefixes, exit - if (tmp == "") - break; - - tmp = tmp.substring(0, tmp.lastIndexOf("/")); - } - - // no mapping applies, so 404 - if (!file) - throw HTTP_404; - - - // last, get the file for the path within the determined directory - var parentFolder = file.parent; - var dirIsRoot = (parentFolder == null); - - // Strategy here is to append components individually, making sure we - // never move above the given directory; this allows paths such as - // "/foo/../bar" but prevents paths such as "/../base-sibling"; - // this component-wise approach also means the code works even on platforms - // which don't use "/" as the directory separator, such as Windows - var leafPath = path.substring(tmp.length + 1); - var comps = leafPath.split("/"); - for (var i = 0, sz = comps.length; i < sz; i++) - { - var comp = comps[i]; - - if (comp == "..") - file = file.parent; - else if (comp == "." || comp == "") - continue; - else - file.append(comp); - - if (!dirIsRoot && file.equals(parentFolder)) - throw HTTP_403; - } - - return file; - }, - - /** -* Writes the error page for the given HTTP error code over the given -* connection. -* -* @param errorCode : uint -* the HTTP error code to be used -* @param connection : Connection -* the connection on which the error occurred -*/ - handleError: function(errorCode, connection) - { - var response = new Response(connection); - - dumpn("*** error in request: " + errorCode); - - this._handleError(errorCode, new Request(connection.port), response); - }, - - /** -* Handles a request which generates the given error code, using the -* user-defined error handler if one has been set, gracefully falling back to -* the x00 status code if the code has no handler, and failing to status code -* 500 if all else fails. -* -* @param errorCode : uint -* the HTTP error which is to be returned -* @param metadata : Request -* metadata for the request, which will often be incomplete since this is an -* error -* @param response : Response -* an uninitialized Response should be initialized when this method -* completes with information which represents the desired error code in the -* ideal case or a fallback code in abnormal circumstances (i.e., 500 is a -* fallback for 505, per HTTP specs) -*/ - _handleError: function(errorCode, metadata, response) - { - if (!metadata) - throw Cr.NS_ERROR_NULL_POINTER; - - var errorX00 = errorCode - (errorCode % 100); - - try - { - if (!(errorCode in HTTP_ERROR_CODES)) - dumpn("*** WARNING: requested invalid error: " + errorCode); - - // RFC 2616 says that we should try to handle an error by its class if we - // can't otherwise handle it -- if that fails, we revert to handling it as - // a 500 internal server error, and if that fails we throw and shut down - // the server - - // actually handle the error - try - { - if (errorCode in this._overrideErrors) - this._overrideErrors[errorCode](metadata, response); - else - this._defaultErrors[errorCode](metadata, response); - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(e); - return; - } - - // don't retry the handler that threw - if (errorX00 == errorCode) - throw HTTP_500; - - dumpn("*** error in handling for error code " + errorCode + ", " + - "falling back to " + errorX00 + "..."); - response = new Response(response._connection); - if (errorX00 in this._overrideErrors) - this._overrideErrors[errorX00](metadata, response); - else if (errorX00 in this._defaultErrors) - this._defaultErrors[errorX00](metadata, response); - else - throw HTTP_500; - } - } - catch (e) - { - if (response.partiallySent()) - { - response.abort(); - return; - } - - // we've tried everything possible for a meaningful error -- now try 500 - dumpn("*** error in handling for error code " + errorX00 + ", falling " + - "back to 500..."); - - try - { - response = new Response(response._connection); - if (500 in this._overrideErrors) - this._overrideErrors[500](metadata, response); - else - this._defaultErrors[500](metadata, response); - } - catch (e2) - { - dumpn("*** multiple errors in default error handlers!"); - dumpn("*** e == " + e + ", e2 == " + e2); - response.abort(e2); - return; - } - } - - response.complete(); - }, - - // FIELDS - - /** -* This object contains the default handlers for the various HTTP error codes. -*/ - _defaultErrors: - { - 400: function(metadata, response) - { - // none of the data in metadata is reliable, so hard-code everything here - response.setStatusLine("1.1", 400, "Bad Request"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Bad request\n"; - response.bodyOutputStream.write(body, body.length); - }, - 403: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 403, "Forbidden"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -403 Forbidden\ -\ -

403 Forbidden

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 404: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 404, "Not Found"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -404 Not Found\ -\ -

404 Not Found

\ -

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

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 416: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 416, - "Requested Range Not Satisfiable"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -\ -416 Requested Range Not Satisfiable\ -\ -

416 Requested Range Not Satisfiable

\ -

The byte range was not valid for the\ -requested resource.\ -

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 500: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, - 500, - "Internal Server Error"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -500 Internal Server Error\ -\ -

500 Internal Server Error

\ -

Something's broken in this server and\ -needs to be fixed.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 501: function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 501, "Not Implemented"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -501 Not Implemented\ -\ -

501 Not Implemented

\ -

This server is not (yet) Apache.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - }, - 505: function(metadata, response) - { - response.setStatusLine("1.1", 505, "HTTP Version Not Supported"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -505 HTTP Version Not Supported\ -\ -

505 HTTP Version Not Supported

\ -

This server only supports HTTP/1.0 and HTTP/1.1\ -connections.

\ -\ -"; - response.bodyOutputStream.write(body, body.length); - } - }, - - /** -* Contains handlers for the default set of URIs contained in this server. -*/ - _defaultPaths: - { - "/": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - - var body = "\ -httpd.js\ -\ -

httpd.js

\ -

If you're seeing this page, httpd.js is up and\ -serving requests! Now set a base path and serve some\ -files!

\ -\ -"; - - response.bodyOutputStream.write(body, body.length); - }, - - "/trace": function(metadata, response) - { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/plain", false); - - var body = "Request-URI: " + - metadata.scheme + "://" + metadata.host + ":" + metadata.port + - metadata.path + "\n\n"; - body += "Request (semantically equivalent, slightly reformatted):\n\n"; - body += metadata.method + " " + metadata.path; - - if (metadata.queryString) - body += "?" + metadata.queryString; - - body += " HTTP/" + metadata.httpVersion + "\r\n"; - - var headEnum = metadata.headers; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - body += fieldName + ": " + metadata.getHeader(fieldName) + "\r\n"; - } - - response.bodyOutputStream.write(body, body.length); - } - } -}; - - -/** -* Maps absolute paths to files on the local file system (as nsILocalFiles). -*/ -function FileMap() -{ - /** Hash which will map paths to nsILocalFiles. */ - this._map = {}; -} -FileMap.prototype = -{ - // PUBLIC API - - /** -* Maps key to a clone of the nsILocalFile value if value is non-null; -* otherwise, removes any extant mapping for key. -* -* @param key : string -* string to which a clone of value is mapped -* @param value : nsILocalFile -* the file to map to key, or null to remove a mapping -*/ - put: function(key, value) - { - if (value) - this._map[key] = value.clone(); - else - delete this._map[key]; - }, - - /** -* Returns a clone of the nsILocalFile mapped to key, or null if no such -* mapping exists. -* -* @param key : string -* key to which the returned file maps -* @returns nsILocalFile -* a clone of the mapped file, or null if no mapping exists -*/ - get: function(key) - { - var val = this._map[key]; - return val ? val.clone() : null; - } -}; - - -// Response CONSTANTS - -// token = * -// CHAR = -// CTL = -// separators = "(" | ")" | "<" | ">" | "@" -// | "," | ";" | ":" | "\" | <"> -// | "/" | "[" | "]" | "?" | "=" -// | "{" | "}" | SP | HT -const IS_TOKEN_ARRAY = - [0, 0, 0, 0, 0, 0, 0, 0, // 0 - 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 0, 0, 0, 0, 0, 0, 0, 0, // 24 - - 0, 1, 0, 1, 1, 1, 1, 1, // 32 - 0, 0, 1, 1, 0, 1, 1, 0, // 40 - 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 1, 1, 0, 0, 0, 0, 0, 0, // 56 - - 0, 1, 1, 1, 1, 1, 1, 1, // 64 - 1, 1, 1, 1, 1, 1, 1, 1, // 72 - 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 1, 1, 1, 0, 0, 0, 1, 1, // 88 - - 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 1, 1, 1, 1, 1, 1, 1, 1, // 104 - 1, 1, 1, 1, 1, 1, 1, 1, // 112 - 1, 1, 1, 0, 1, 0, 1]; // 120 - - -/** -* Determines whether the given character code is a CTL. -* -* @param code : uint -* the character code -* @returns boolean -* true if code is a CTL, false otherwise -*/ -function isCTL(code) -{ - return (code >= 0 && code <= 31) || (code == 127); -} - -/** -* Represents a response to an HTTP request, encapsulating all details of that -* response. This includes all headers, the HTTP version, status code and -* explanation, and the entity itself. -* -* @param connection : Connection -* the connection over which this response is to be written -*/ -function Response(connection) -{ - /** The connection over which this response will be written. */ - this._connection = connection; - - /** -* The HTTP version of this response; defaults to 1.1 if not set by the -* handler. -*/ - this._httpVersion = nsHttpVersion.HTTP_1_1; - - /** -* The HTTP code of this response; defaults to 200. -*/ - this._httpCode = 200; - - /** -* The description of the HTTP code in this response; defaults to "OK". -*/ - this._httpDescription = "OK"; - - /** -* An nsIHttpHeaders object in which the headers in this response should be -* stored. This property is null after the status line and headers have been -* written to the network, and it may be modified up until it is cleared, -* except if this._finished is set first (in which case headers are written -* asynchronously in response to a finish() call not preceded by -* flushHeaders()). -*/ - this._headers = new nsHttpHeaders(); - - /** -* Set to true when this response is ended (completely constructed if possible -* and the connection closed); further actions on this will then fail. -*/ - this._ended = false; - - /** -* A stream used to hold data written to the body of this response. -*/ - this._bodyOutputStream = null; - - /** -* A stream containing all data that has been written to the body of this -* response so far. (Async handlers make the data contained in this -* unreliable as a way of determining content length in general, but auxiliary -* saved information can sometimes be used to guarantee reliability.) -*/ - this._bodyInputStream = null; - - /** -* A stream copier which copies data to the network. It is initially null -* until replaced with a copier for response headers; when headers have been -* fully sent it is replaced with a copier for the response body, remaining -* so for the duration of response processing. -*/ - this._asyncCopier = null; - - /** -* True if this response has been designated as being processed -* asynchronously rather than for the duration of a single call to -* nsIHttpRequestHandler.handle. -*/ - this._processAsync = false; - - /** -* True iff finish() has been called on this, signaling that no more changes -* to this may be made. -*/ - this._finished = false; - - /** -* True iff powerSeized() has been called on this, signaling that this -* response is to be handled manually by the response handler (which may then -* send arbitrary data in response, even non-HTTP responses). -*/ - this._powerSeized = false; -} -Response.prototype = -{ - // PUBLIC CONSTRUCTION API - - // - // see nsIHttpResponse.bodyOutputStream - // - get bodyOutputStream() - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - if (!this._bodyOutputStream) - { - var pipe = new Pipe(true, false, Response.SEGMENT_SIZE, PR_UINT32_MAX, - null); - this._bodyOutputStream = pipe.outputStream; - this._bodyInputStream = pipe.inputStream; - if (this._processAsync || this._powerSeized) - this._startAsyncProcessor(); - } - - return this._bodyOutputStream; - }, - - // - // see nsIHttpResponse.write - // - write: function(data) - { - if (this._finished) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - var dataAsString = String(data); - this.bodyOutputStream.write(dataAsString, dataAsString.length); - }, - - // - // see nsIHttpResponse.setStatusLine - // - setStatusLine: function(httpVersion, code, description) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - if (!(code >= 0 && code < 1000)) - throw Cr.NS_ERROR_INVALID_ARG; - - try - { - var httpVer; - // avoid version construction for the most common cases - if (!httpVersion || httpVersion == "1.1") - httpVer = nsHttpVersion.HTTP_1_1; - else if (httpVersion == "1.0") - httpVer = nsHttpVersion.HTTP_1_0; - else - httpVer = new nsHttpVersion(httpVersion); - } - catch (e) - { - throw Cr.NS_ERROR_INVALID_ARG; - } - - // Reason-Phrase = * - // TEXT = - // - // XXX this ends up disallowing octets which aren't Unicode, I think -- not - // much to do if description is IDL'd as string - if (!description) - description = ""; - for (var i = 0; i < description.length; i++) - if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t") - throw Cr.NS_ERROR_INVALID_ARG; - - // set the values only after validation to preserve atomicity - this._httpDescription = description; - this._httpCode = code; - this._httpVersion = httpVer; - }, - - // - // see nsIHttpResponse.setHeader - // - setHeader: function(name, value, merge) - { - if (!this._headers || this._finished || this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - this._ensureAlive(); - - this._headers.setHeader(name, value, merge); - }, - - // - // see nsIHttpResponse.processAsync - // - processAsync: function() - { - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._processAsync) - return; - this._ensureAlive(); - - dumpn("*** processing connection " + this._connection.number + " async"); - this._processAsync = true; - - /* -* Either the bodyOutputStream getter or this method is responsible for -* starting the asynchronous processor and catching writes of data to the -* response body of async responses as they happen, for the purpose of -* forwarding those writes to the actual connection's output stream. -* If bodyOutputStream is accessed first, calling this method will create -* the processor (when it first is clear that body data is to be written -* immediately, not buffered). If this method is called first, accessing -* bodyOutputStream will create the processor. If only this method is -* called, we'll write nothing, neither headers nor the nonexistent body, -* until finish() is called. Since that delay is easily avoided by simply -* getting bodyOutputStream or calling write(""), we don't worry about it. -*/ - if (this._bodyOutputStream && !this._asyncCopier) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.seizePower - // - seizePower: function() - { - if (this._processAsync) - throw Cr.NS_ERROR_NOT_AVAILABLE; - if (this._finished) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._powerSeized) - return; - this._ensureAlive(); - - dumpn("*** forcefully seizing power over connection " + - this._connection.number + "..."); - - // Purge any already-written data without sending it. We could as easily - // swap out the streams entirely, but that makes it possible to acquire and - // unknowingly use a stale reference, so we require there only be one of - // each stream ever for any response to avoid this complication. - if (this._asyncCopier) - this._asyncCopier.cancel(Cr.NS_BINDING_ABORTED); - this._asyncCopier = null; - if (this._bodyOutputStream) - { - var input = new BinaryInputStream(this._bodyInputStream); - var avail; - while ((avail = input.available()) > 0) - input.readByteArray(avail); - } - - this._powerSeized = true; - if (this._bodyOutputStream) - this._startAsyncProcessor(); - }, - - // - // see nsIHttpResponse.finish - // - finish: function() - { - if (!this._processAsync && !this._powerSeized) - throw Cr.NS_ERROR_UNEXPECTED; - if (this._finished) - return; - - dumpn("*** finishing connection " + this._connection.number); - this._startAsyncProcessor(); // in case bodyOutputStream was never accessed - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - this._finished = true; - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpResponse) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // POST-CONSTRUCTION API (not exposed externally) - - /** -* The HTTP version number of this, as a string (e.g. "1.1"). -*/ - get httpVersion() - { - this._ensureAlive(); - return this._httpVersion.toString(); - }, - - /** -* The HTTP status code of this response, as a string of three characters per -* RFC 2616. -*/ - get httpCode() - { - this._ensureAlive(); - - var codeString = (this._httpCode < 10 ? "0" : "") + - (this._httpCode < 100 ? "0" : "") + - this._httpCode; - return codeString; - }, - - /** -* The description of the HTTP status code of this response, or "" if none is -* set. -*/ - get httpDescription() - { - this._ensureAlive(); - - return this._httpDescription; - }, - - /** -* The headers in this response, as an nsHttpHeaders object. -*/ - get headers() - { - this._ensureAlive(); - - return this._headers; - }, - - // - // see nsHttpHeaders.getHeader - // - getHeader: function(name) - { - this._ensureAlive(); - - return this._headers.getHeader(name); - }, - - /** -* Determines whether this response may be abandoned in favor of a newly -* constructed response. A response may be abandoned only if it is not being -* sent asynchronously and if raw control over it has not been taken from the -* server. -* -* @returns boolean -* true iff no data has been written to the network -*/ - partiallySent: function() - { - dumpn("*** partiallySent()"); - return this._processAsync || this._powerSeized; - }, - - /** -* If necessary, kicks off the remaining request processing needed to be done -* after a request handler performs its initial work upon this response. -*/ - complete: function() - { - dumpn("*** complete()"); - if (this._processAsync || this._powerSeized) - { - NS_ASSERT(this._processAsync ^ this._powerSeized, - "can't both send async and relinquish power"); - return; - } - - NS_ASSERT(!this.partiallySent(), "completing a partially-sent response?"); - - this._startAsyncProcessor(); - - // Now make sure we finish processing this request! - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - }, - - /** -* Abruptly ends processing of this response, usually due to an error in an -* incoming request but potentially due to a bad error handler. Since we -* cannot handle the error in the usual way (giving an HTTP error page in -* response) because data may already have been sent (or because the response -* might be expected to have been generated asynchronously or completely from -* scratch by the handler), we stop processing this response and abruptly -* close the connection. -* -* @param e : Error -* the exception which precipitated this abort, or null if no such exception -* was generated -*/ - abort: function(e) - { - dumpn("*** abort(<" + e + ">)"); - - // This response will be ended by the processor if one was created. - var copier = this._asyncCopier; - if (copier) - { - // We dispatch asynchronously here so that any pending writes of data to - // the connection will be deterministically written. This makes it easier - // to specify exact behavior, and it makes observable behavior more - // predictable for clients. Note that the correctness of this depends on - // callbacks in response to _waitToReadData in WriteThroughCopier - // happening asynchronously with respect to the actual writing of data to - // bodyOutputStream, as they currently do; if they happened synchronously, - // an event which ran before this one could write more data to the - // response body before we get around to canceling the copier. We have - // tests for this in test_seizepower.js, however, and I can't think of a - // way to handle both cases without removing bodyOutputStream access and - // moving its effective write(data, length) method onto Response, which - // would be slower and require more code than this anyway. - gThreadManager.currentThread.dispatch({ - run: function() - { - dumpn("*** canceling copy asynchronously..."); - copier.cancel(Cr.NS_ERROR_UNEXPECTED); - } - }, Ci.nsIThread.DISPATCH_NORMAL); - } - else - { - this.end(); - } - }, - - /** -* Closes this response's network connection, marks the response as finished, -* and notifies the server handler that the request is done being processed. -*/ - end: function() - { - NS_ASSERT(!this._ended, "ending this response twice?!?!"); - - this._connection.close(); - if (this._bodyOutputStream) - this._bodyOutputStream.close(); - - this._finished = true; - this._ended = true; - }, - - // PRIVATE IMPLEMENTATION - - /** -* Sends the status line and headers of this response if they haven't been -* sent and initiates the process of copying data written to this response's -* body to the network. -*/ - _startAsyncProcessor: function() - { - dumpn("*** _startAsyncProcessor()"); - - // Handle cases where we're being called a second time. The former case - // happens when this is triggered both by complete() and by processAsync(), - // while the latter happens when processAsync() in conjunction with sent - // data causes abort() to be called. - if (this._asyncCopier || this._ended) - { - dumpn("*** ignoring second call to _startAsyncProcessor"); - return; - } - - // Send headers if they haven't been sent already and should be sent, then - // asynchronously continue to send the body. - if (this._headers && !this._powerSeized) - { - this._sendHeaders(); - return; - } - - this._headers = null; - this._sendBody(); - }, - - /** -* Signals that all modifications to the response status line and headers are -* complete and then sends that data over the network to the client. Once -* this method completes, a different response to the request that resulted -* in this response cannot be sent -- the only possible action in case of -* error is to abort the response and close the connection. -*/ - _sendHeaders: function() - { - dumpn("*** _sendHeaders()"); - - NS_ASSERT(this._headers); - NS_ASSERT(!this._powerSeized); - - // request-line - var statusLine = "HTTP/" + this.httpVersion + " " + - this.httpCode + " " + - this.httpDescription + "\r\n"; - - // header post-processing - - var headers = this._headers; - headers.setHeader("Connection", "close", false); - headers.setHeader("Server", "httpd.js", false); - if (!headers.hasHeader("Date")) - headers.setHeader("Date", toDateString(Date.now()), false); - - // Any response not being processed asynchronously must have an associated - // Content-Length header for reasons of backwards compatibility with the - // initial server, which fully buffered every response before sending it. - // Beyond that, however, it's good to do this anyway because otherwise it's - // impossible to test behaviors that depend on the presence or absence of a - // Content-Length header. - if (!this._processAsync) - { - dumpn("*** non-async response, set Content-Length"); - - var bodyStream = this._bodyInputStream; - var avail = bodyStream ? bodyStream.available() : 0; - - // XXX assumes stream will always report the full amount of data available - headers.setHeader("Content-Length", "" + avail, false); - } - - - // construct and send response - dumpn("*** header post-processing completed, sending response head..."); - - // request-line - var preambleData = [statusLine]; - - // headers - var headEnum = headers.enumerator; - while (headEnum.hasMoreElements()) - { - var fieldName = headEnum.getNext() - .QueryInterface(Ci.nsISupportsString) - .data; - var values = headers.getHeaderValues(fieldName); - for (var i = 0, sz = values.length; i < sz; i++) - preambleData.push(fieldName + ": " + values[i] + "\r\n"); - } - - // end request-line/headers - preambleData.push("\r\n"); - - var preamble = preambleData.join(""); - - var responseHeadPipe = new Pipe(true, false, 0, PR_UINT32_MAX, null); - responseHeadPipe.outputStream.write(preamble, preamble.length); - - var response = this; - var copyObserver = - { - onStartRequest: function(request, cx) - { - dumpn("*** preamble copying started"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** preamble copying complete " + - "[status=0x" + statusCode.toString(16) + "]"); - - if (!components.isSuccessCode(statusCode)) - { - dumpn("!!! header copying problems: non-success statusCode, " + - "ending response"); - - response.end(); - } - else - { - response._sendBody(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - var headerCopier = this._asyncCopier = - new WriteThroughCopier(responseHeadPipe.inputStream, - this._connection.output, - copyObserver, null); - - responseHeadPipe.outputStream.close(); - - // Forbid setting any more headers or modifying the request line. - this._headers = null; - }, - - /** -* Asynchronously writes the body of the response (or the entire response, if -* seizePower() has been called) to the network. -*/ - _sendBody: function() - { - dumpn("*** _sendBody"); - - NS_ASSERT(!this._headers, "still have headers around but sending body?"); - - // If no body data was written, we're done - if (!this._bodyInputStream) - { - dumpn("*** empty body, response finished"); - this.end(); - return; - } - - var response = this; - var copyObserver = - { - onStartRequest: function(request, context) - { - dumpn("*** onStartRequest"); - }, - - onStopRequest: function(request, cx, statusCode) - { - dumpn("*** onStopRequest [status=0x" + statusCode.toString(16) + "]"); - - if (statusCode === Cr.NS_BINDING_ABORTED) - { - dumpn("*** terminating copy observer without ending the response"); - } - else - { - if (!components.isSuccessCode(statusCode)) - dumpn("*** WARNING: non-success statusCode in onStopRequest"); - - response.end(); - } - }, - - QueryInterface: function(aIID) - { - if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } - }; - - dumpn("*** starting async copier of body data..."); - this._asyncCopier = - new WriteThroughCopier(this._bodyInputStream, this._connection.output, - copyObserver, null); - }, - - /** Ensures that this hasn't been ended. */ - _ensureAlive: function() - { - NS_ASSERT(!this._ended, "not handling response lifetime correctly"); - } -}; - -/** -* Size of the segments in the buffer used in storing response data and writing -* it to the socket. -*/ -Response.SEGMENT_SIZE = 8192; - -/** Serves double duty in WriteThroughCopier implementation. */ -function notImplemented() -{ - throw Cr.NS_ERROR_NOT_IMPLEMENTED; -} - -/** Returns true iff the given exception represents stream closure. */ -function streamClosed(e) -{ - return e === Cr.NS_BASE_STREAM_CLOSED || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_CLOSED); -} - -/** Returns true iff the given exception represents a blocked stream. */ -function wouldBlock(e) -{ - return e === Cr.NS_BASE_STREAM_WOULD_BLOCK || - (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_WOULD_BLOCK); -} - -/** -* Copies data from source to sink as it becomes available, when that data can -* be written to sink without blocking. -* -* @param source : nsIAsyncInputStream -* the stream from which data is to be read -* @param sink : nsIAsyncOutputStream -* the stream to which data is to be copied -* @param observer : nsIRequestObserver -* an observer which will be notified when the copy starts and finishes -* @param context : nsISupports -* context passed to observer when notified of start/stop -* @throws NS_ERROR_NULL_POINTER -* if source, sink, or observer are null -*/ -function WriteThroughCopier(source, sink, observer, context) -{ - if (!source || !sink || !observer) - throw Cr.NS_ERROR_NULL_POINTER; - - /** Stream from which data is being read. */ - this._source = source; - - /** Stream to which data is being written. */ - this._sink = sink; - - /** Observer watching this copy. */ - this._observer = observer; - - /** Context for the observer watching this. */ - this._context = context; - - /** -* True iff this is currently being canceled (cancel has been called, the -* callback may not yet have been made). -*/ - this._canceled = false; - - /** -* False until all data has been read from input and written to output, at -* which point this copy is completed and cancel() is asynchronously called. -*/ - this._completed = false; - - /** Required by nsIRequest, meaningless. */ - this.loadFlags = 0; - /** Required by nsIRequest, meaningless. */ - this.loadGroup = null; - /** Required by nsIRequest, meaningless. */ - this.name = "response-body-copy"; - - /** Status of this request. */ - this.status = Cr.NS_OK; - - /** Arrays of byte strings waiting to be written to output. */ - this._pendingData = []; - - // start copying - try - { - observer.onStartRequest(this, context); - this._waitToReadData(); - this._waitForSinkClosure(); - } - catch (e) - { - dumpn("!!! error starting copy: " + e + - ("lineNumber" in e ? ", line " + e.lineNumber : "")); - dumpn(e.stack); - this.cancel(Cr.NS_ERROR_UNEXPECTED); - } -} -WriteThroughCopier.prototype = -{ - /* nsISupports implementation */ - - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIInputStreamCallback) || - iid.equals(Ci.nsIOutputStreamCallback) || - iid.equals(Ci.nsIRequest) || - iid.equals(Ci.nsISupports)) - { - return this; - } - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // NSIINPUTSTREAMCALLBACK - - /** -* Receives a more-data-in-input notification and writes the corresponding -* data to the output. -* -* @param input : nsIAsyncInputStream -* the input stream on whose data we have been waiting -*/ - onInputStreamReady: function(input) - { - if (this._source === null) - return; - - dumpn("*** onInputStreamReady"); - - // - // Ordinarily we'll read a non-zero amount of data from input, queue it up - // to be written and then wait for further callbacks. The complications in - // this method are the cases where we deviate from that behavior when errors - // occur or when copying is drawing to a finish. - // - // The edge cases when reading data are: - // - // Zero data is read - // If zero data was read, we're at the end of available data, so we can - // should stop reading and move on to writing out what we have (or, if - // we've already done that, onto notifying of completion). - // A stream-closed exception is thrown - // This is effectively a less kind version of zero data being read; the - // only difference is that we notify of completion with that result - // rather than with NS_OK. - // Some other exception is thrown - // This is the least kind result. We don't know what happened, so we - // act as though the stream closed except that we notify of completion - // with the result NS_ERROR_UNEXPECTED. - // - - var bytesWanted = 0, bytesConsumed = -1; - try - { - input = new BinaryInputStream(input); - - bytesWanted = Math.min(input.available(), Response.SEGMENT_SIZE); - dumpn("*** input wanted: " + bytesWanted); - - if (bytesWanted > 0) - { - var data = input.readByteArray(bytesWanted); - bytesConsumed = data.length; - this._pendingData.push(String.fromCharCode.apply(String, data)); - } - - dumpn("*** " + bytesConsumed + " bytes read"); - - // Handle the zero-data edge case in the same place as all other edge - // cases are handled. - if (bytesWanted === 0) - throw Cr.NS_BASE_STREAM_CLOSED; - } - catch (e) - { - if (streamClosed(e)) - { - dumpn("*** input stream closed"); - e = bytesWanted === 0 ? Cr.NS_OK : Cr.NS_ERROR_UNEXPECTED; - } - else - { - dumpn("!!! unexpected error reading from input, canceling: " + e); - e = Cr.NS_ERROR_UNEXPECTED; - } - - this._doneReadingSource(e); - return; - } - - var pendingData = this._pendingData; - - NS_ASSERT(bytesConsumed > 0); - NS_ASSERT(pendingData.length > 0, "no pending data somehow?"); - NS_ASSERT(pendingData[pendingData.length - 1].length > 0, - "buffered zero bytes of data?"); - - NS_ASSERT(this._source !== null); - - // Reading has gone great, and we've gotten data to write now. What if we - // don't have a place to write that data, because output went away just - // before this read? Drop everything on the floor, including new data, and - // cancel at this point. - if (this._sink === null) - { - pendingData.length = 0; - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we've read the data, and we know we have a place to write it. We - // need to queue up the data to be written, but *only* if none is queued - // already -- if data's already queued, the code that actually writes the - // data will make sure to wait on unconsumed pending data. - try - { - if (pendingData.length === 1) - this._waitToWriteData(); - } - catch (e) - { - dumpn("!!! error waiting to write data just read, swallowing and " + - "writing only what we already have: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Whee! We successfully read some data, and it's successfully queued up to - // be written. All that remains now is to wait for more data to read. - try - { - this._waitToReadData(); - } - catch (e) - { - dumpn("!!! error waiting to read more data: " + e); - this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED); - } - }, - - - // NSIOUTPUTSTREAMCALLBACK - - /** -* Callback when data may be written to the output stream without blocking, or -* when the output stream has been closed. -* -* @param output : nsIAsyncOutputStream -* the output stream on whose writability we've been waiting, also known as -* this._sink -*/ - onOutputStreamReady: function(output) - { - if (this._sink === null) - return; - - dumpn("*** onOutputStreamReady"); - - var pendingData = this._pendingData; - if (pendingData.length === 0) - { - // There's no pending data to write. The only way this can happen is if - // we're waiting on the output stream's closure, so we can respond to a - // copying failure as quickly as possible (rather than waiting for data to - // be available to read and then fail to be copied). Therefore, we must - // be done now -- don't bother to attempt to write anything and wrap - // things up. - dumpn("!!! output stream closed prematurely, ending copy"); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - - NS_ASSERT(pendingData[0].length > 0, "queued up an empty quantum?"); - - // - // Write out the first pending quantum of data. The possible errors here - // are: - // - // The write might fail because we can't write that much data - // Okay, we've written what we can now, so re-queue what's left and - // finish writing it out later. - // The write failed because the stream was closed - // Discard pending data that we can no longer write, stop reading, and - // signal that copying finished. - // Some other error occurred. - // Same as if the stream were closed, but notify with the status - // NS_ERROR_UNEXPECTED so the observer knows something was wonky. - // - - try - { - var quantum = pendingData[0]; - - // XXX |quantum| isn't guaranteed to be ASCII, so we're relying on - // undefined behavior! We're only using this because writeByteArray - // is unusably broken for asynchronous output streams; see bug 532834 - // for details. - var bytesWritten = output.write(quantum, quantum.length); - if (bytesWritten === quantum.length) - pendingData.shift(); - else - pendingData[0] = quantum.substring(bytesWritten); - - dumpn("*** wrote " + bytesWritten + " bytes of data"); - } - catch (e) - { - if (wouldBlock(e)) - { - NS_ASSERT(pendingData.length > 0, - "stream-blocking exception with no data to write?"); - NS_ASSERT(pendingData[0].length > 0, - "stream-blocking exception with empty quantum?"); - this._waitToWriteData(); - return; - } - - if (streamClosed(e)) - dumpn("!!! output stream prematurely closed, signaling error..."); - else - dumpn("!!! unknown error: " + e + ", quantum=" + quantum); - - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // The day is ours! Quantum written, now let's see if we have more data - // still to write. - try - { - if (pendingData.length > 0) - { - this._waitToWriteData(); - return; - } - } - catch (e) - { - dumpn("!!! unexpected error waiting to write pending data: " + e); - this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED); - return; - } - - // Okay, we have no more pending data to write -- but might we get more in - // the future? - if (this._source !== null) - { - /* -* If we might, then wait for the output stream to be closed. (We wait -* only for closure because we have no data to write -- and if we waited -* for a specific amount of data, we would get repeatedly notified for no -* reason if over time the output stream permitted more and more data to -* be written to it without blocking.) -*/ - this._waitForSinkClosure(); - } - else - { - /* -* On the other hand, if we can't have more data because the input -* stream's gone away, then it's time to notify of copy completion. -* Victory! -*/ - this._sink = null; - this._cancelOrDispatchCancelCallback(Cr.NS_OK); - } - }, - - - // NSIREQUEST - - /** Returns true if the cancel observer hasn't been notified yet. */ - isPending: function() - { - return !this._completed; - }, - - /** Not implemented, don't use! */ - suspend: notImplemented, - /** Not implemented, don't use! */ - resume: notImplemented, - - /** -* Cancels data reading from input, asynchronously writes out any pending -* data, and causes the observer to be notified with the given error code when -* all writing has finished. -* -* @param status : nsresult -* the status to pass to the observer when data copying has been canceled -*/ - cancel: function(status) - { - dumpn("*** cancel(" + status.toString(16) + ")"); - - if (this._canceled) - { - dumpn("*** suppressing a late cancel"); - return; - } - - this._canceled = true; - this.status = status; - - // We could be in the middle of absolutely anything at this point. Both - // input and output might still be around, we might have pending data to - // write, and in general we know nothing about the state of the world. We - // therefore must assume everything's in progress and take everything to its - // final steady state (or so far as it can go before we need to finish - // writing out remaining data). - - this._doneReadingSource(status); - }, - - - // PRIVATE IMPLEMENTATION - - /** -* Stop reading input if we haven't already done so, passing e as the status -* when closing the stream, and kick off a copy-completion notice if no more -* data remains to be written. -* -* @param e : nsresult -* the status to be used when closing the input stream -*/ - _doneReadingSource: function(e) - { - dumpn("*** _doneReadingSource(0x" + e.toString(16) + ")"); - - this._finishSource(e); - if (this._pendingData.length === 0) - this._sink = null; - else - NS_ASSERT(this._sink !== null, "null output?"); - - // If we've written out all data read up to this point, then it's time to - // signal completion. - if (this._sink === null) - { - NS_ASSERT(this._pendingData.length === 0, "pending data still?"); - this._cancelOrDispatchCancelCallback(e); - } - }, - - /** -* Stop writing output if we haven't already done so, discard any data that -* remained to be sent, close off input if it wasn't already closed, and kick -* off a copy-completion notice. -* -* @param e : nsresult -* the status to be used when closing input if it wasn't already closed -*/ - _doneWritingToSink: function(e) - { - dumpn("*** _doneWritingToSink(0x" + e.toString(16) + ")"); - - this._pendingData.length = 0; - this._sink = null; - this._doneReadingSource(e); - }, - - /** -* Completes processing of this copy: either by canceling the copy if it -* hasn't already been canceled using the provided status, or by dispatching -* the cancel callback event (with the originally provided status, of course) -* if it already has been canceled. -* -* @param status : nsresult -* the status code to use to cancel this, if this hasn't already been -* canceled -*/ - _cancelOrDispatchCancelCallback: function(status) - { - dumpn("*** _cancelOrDispatchCancelCallback(" + status + ")"); - - NS_ASSERT(this._source === null, "should have finished input"); - NS_ASSERT(this._sink === null, "should have finished output"); - NS_ASSERT(this._pendingData.length === 0, "should have no pending data"); - - if (!this._canceled) - { - this.cancel(status); - return; - } - - var self = this; - var event = - { - run: function() - { - dumpn("*** onStopRequest async callback"); - - self._completed = true; - try - { - self._observer.onStopRequest(self, self._context, self.status); - } - catch (e) - { - NS_ASSERT(false, - "how are we throwing an exception here? we control " + - "all the callers! " + e); - } - } - }; - - gThreadManager.currentThread.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL); - }, - - /** -* Kicks off another wait for more data to be available from the input stream. -*/ - _waitToReadData: function() - { - dumpn("*** _waitToReadData"); - this._source.asyncWait(this, 0, Response.SEGMENT_SIZE, - gThreadManager.mainThread); - }, - - /** -* Kicks off another wait until data can be written to the output stream. -*/ - _waitToWriteData: function() - { - dumpn("*** _waitToWriteData"); - - var pendingData = this._pendingData; - NS_ASSERT(pendingData.length > 0, "no pending data to write?"); - NS_ASSERT(pendingData[0].length > 0, "buffered an empty write?"); - - this._sink.asyncWait(this, 0, pendingData[0].length, - gThreadManager.mainThread); - }, - - /** -* Kicks off a wait for the sink to which data is being copied to be closed. -* We wait for stream closure when we don't have any data to be copied, rather -* than waiting to write a specific amount of data. We can't wait to write -* data because the sink might be infinitely writable, and if no data appears -* in the source for a long time we might have to spin quite a bit waiting to -* write, waiting to write again, &c. Waiting on stream closure instead means -* we'll get just one notification if the sink dies. Note that when data -* starts arriving from the sink we'll resume waiting for data to be written, -* dropping this closure-only callback entirely. -*/ - _waitForSinkClosure: function() - { - dumpn("*** _waitForSinkClosure"); - - this._sink.asyncWait(this, Ci.nsIAsyncOutputStream.WAIT_CLOSURE_ONLY, 0, - gThreadManager.mainThread); - }, - - /** -* Closes input with the given status, if it hasn't already been closed; -* otherwise a no-op. -* -* @param status : nsresult -* status code use to close the source stream if necessary -*/ - _finishSource: function(status) - { - dumpn("*** _finishSource(" + status.toString(16) + ")"); - - if (this._source !== null) - { - this._source.closeWithStatus(status); - this._source = null; - } - } -}; - - -/** -* A container for utility functions used with HTTP headers. -*/ -const headerUtils = -{ - /** -* Normalizes fieldName (by converting it to lowercase) and ensures it is a -* valid header field name (although not necessarily one specified in RFC -* 2616). -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not match the field-name production in RFC 2616 -* @returns string -* fieldName converted to lowercase if it is a valid header, for characters -* where case conversion is possible -*/ - normalizeFieldName: function(fieldName) - { - if (fieldName == "") - throw Cr.NS_ERROR_INVALID_ARG; - - for (var i = 0, sz = fieldName.length; i < sz; i++) - { - if (!IS_TOKEN_ARRAY[fieldName.charCodeAt(i)]) - { - dumpn(fieldName + " is not a valid header field name!"); - throw Cr.NS_ERROR_INVALID_ARG; - } - } - - return fieldName.toLowerCase(); - }, - - /** -* Ensures that fieldValue is a valid header field value (although not -* necessarily as specified in RFC 2616 if the corresponding field name is -* part of the HTTP protocol), normalizes the value if it is, and -* returns the normalized value. -* -* @param fieldValue : string -* a value to be normalized as an HTTP header field value -* @throws NS_ERROR_INVALID_ARG -* if fieldValue does not match the field-value production in RFC 2616 -* @returns string -* fieldValue as a normalized HTTP header field value -*/ - normalizeFieldValue: function(fieldValue) - { - // field-value = *( field-content | LWS ) - // field-content = - // TEXT = - // LWS = [CRLF] 1*( SP | HT ) - // - // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - // qdtext = > - // quoted-pair = "\" CHAR - // CHAR = - - // Any LWS that occurs between field-content MAY be replaced with a single - // SP before interpreting the field value or forwarding the message - // downstream (section 4.2); we replace 1*LWS with a single SP - var val = fieldValue.replace(/(?:(?:\r\n)?[ \t]+)+/g, " "); - - // remove leading/trailing LWS (which has been converted to SP) - val = val.replace(/^ +/, "").replace(/ +$/, ""); - - // that should have taken care of all CTLs, so val should contain no CTLs - for (var i = 0, len = val.length; i < len; i++) - if (isCTL(val.charCodeAt(i))) - throw Cr.NS_ERROR_INVALID_ARG; - - // XXX disallows quoted-pair where CHAR is a CTL -- will not invalidly - // normalize, however, so this can be construed as a tightening of the - // spec and not entirely as a bug - return val; - } -}; - - - -/** -* Converts the given string into a string which is safe for use in an HTML -* context. -* -* @param str : string -* the string to make HTML-safe -* @returns string -* an HTML-safe version of str -*/ -function htmlEscape(str) -{ - // this is naive, but it'll work - var s = ""; - for (var i = 0; i < str.length; i++) - s += "&#" + str.charCodeAt(i) + ";"; - return s; -} - - -/** -* Constructs an object representing an HTTP version (see section 3.1). -* -* @param versionString -* a string of the form "#.#", where # is an non-negative decimal integer with -* or without leading zeros -* @throws -* if versionString does not specify a valid HTTP version number -*/ -function nsHttpVersion(versionString) -{ - var matches = /^(\d+)\.(\d+)$/.exec(versionString); - if (!matches) - throw "Not a valid HTTP version!"; - - /** The major version number of this, as a number. */ - this.major = parseInt(matches[1], 10); - - /** The minor version number of this, as a number. */ - this.minor = parseInt(matches[2], 10); - - if (isNaN(this.major) || isNaN(this.minor) || - this.major < 0 || this.minor < 0) - throw "Not a valid HTTP version!"; -} -nsHttpVersion.prototype = -{ - /** -* Returns the standard string representation of the HTTP version represented -* by this (e.g., "1.1"). -*/ - toString: function () - { - return this.major + "." + this.minor; - }, - - /** -* Returns true if this represents the same HTTP version as otherVersion, -* false otherwise. -* -* @param otherVersion : nsHttpVersion -* the version to compare against this -*/ - equals: function (otherVersion) - { - return this.major == otherVersion.major && - this.minor == otherVersion.minor; - }, - - /** True if this >= otherVersion, false otherwise. */ - atLeast: function(otherVersion) - { - return this.major > otherVersion.major || - (this.major == otherVersion.major && - this.minor >= otherVersion.minor); - } -}; - -nsHttpVersion.HTTP_1_0 = new nsHttpVersion("1.0"); -nsHttpVersion.HTTP_1_1 = new nsHttpVersion("1.1"); - - -/** -* An object which stores HTTP headers for a request or response. -* -* Note that since headers are case-insensitive, this object converts headers to -* lowercase before storing them. This allows the getHeader and hasHeader -* methods to work correctly for any case of a header, but it means that the -* values returned by .enumerator may not be equal case-sensitively to the -* values passed to setHeader when adding headers to this. -*/ -function nsHttpHeaders() -{ - /** -* A hash of headers, with header field names as the keys and header field -* values as the values. Header field names are case-insensitive, but upon -* insertion here they are converted to lowercase. Header field values are -* normalized upon insertion to contain no leading or trailing whitespace. -* -* Note also that per RFC 2616, section 4.2, two headers with the same name in -* a message may be treated as one header with the same field name and a field -* value consisting of the separate field values joined together with a "," in -* their original order. This hash stores multiple headers with the same name -* in this manner. -*/ - this._headers = {}; -} -nsHttpHeaders.prototype = -{ - /** -* Sets the header represented by name and value in this. -* -* @param name : string -* the header name -* @param value : string -* the header value -* @throws NS_ERROR_INVALID_ARG -* if name or value is not a valid header component -*/ - setHeader: function(fieldName, fieldValue, merge) - { - var name = headerUtils.normalizeFieldName(fieldName); - var value = headerUtils.normalizeFieldValue(fieldValue); - - // The following three headers are stored as arrays because their real-world - // syntax prevents joining individual headers into a single header using - // ",". See also - if (merge && name in this._headers) - { - if (name === "www-authenticate" || - name === "proxy-authenticate" || - name === "set-cookie") - { - this._headers[name].push(value); - } - else - { - this._headers[name][0] += "," + value; - NS_ASSERT(this._headers[name].length === 1, - "how'd a non-special header have multiple values?") - } - } - else - { - this._headers[name] = [value]; - } - }, - - /** -* Returns the value for the header specified by this. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns string -* the field value for the given header, possibly with non-semantic changes -* (i.e., leading/trailing whitespace stripped, whitespace runs replaced -* with spaces, etc.) at the option of the implementation; multiple -* instances of the header will be combined with a comma, except for -* the three headers noted in the description of getHeaderValues -*/ - getHeader: function(fieldName) - { - return this.getHeaderValues(fieldName).join("\n"); - }, - - /** -* Returns the value for the header specified by fieldName as an array. -* -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @throws NS_ERROR_NOT_AVAILABLE -* if the given header does not exist in this -* @returns [string] -* an array of all the header values in this for the given -* header name. Header values will generally be collapsed -* into a single header by joining all header values together -* with commas, but certain headers (Proxy-Authenticate, -* WWW-Authenticate, and Set-Cookie) violate the HTTP spec -* and cannot be collapsed in this manner. For these headers -* only, the returned array may contain multiple elements if -* that header has been added more than once. -*/ - getHeaderValues: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - - if (name in this._headers) - return this._headers[name]; - else - throw Cr.NS_ERROR_NOT_AVAILABLE; - }, - - /** -* Returns true if a header with the given field name exists in this, false -* otherwise. -* -* @param fieldName : string -* the field name whose existence is to be determined in this -* @throws NS_ERROR_INVALID_ARG -* if fieldName does not constitute a valid header field name -* @returns boolean -* true if the header's present, false otherwise -*/ - hasHeader: function(fieldName) - { - var name = headerUtils.normalizeFieldName(fieldName); - return (name in this._headers); - }, - - /** -* Returns a new enumerator over the field names of the headers in this, as -* nsISupportsStrings. The names returned will be in lowercase, regardless of -* how they were input using setHeader (header names are case-insensitive per -* RFC 2616). -*/ - get enumerator() - { - var headers = []; - for (var i in this._headers) - { - var supports = new SupportsString(); - supports.data = i; - headers.push(supports); - } - - return new nsSimpleEnumerator(headers); - } -}; - - -/** -* Constructs an nsISimpleEnumerator for the given array of items. -* -* @param items : Array -* the items, which must all implement nsISupports -*/ -function nsSimpleEnumerator(items) -{ - this._items = items; - this._nextIndex = 0; -} -nsSimpleEnumerator.prototype = -{ - hasMoreElements: function() - { - return this._nextIndex < this._items.length; - }, - getNext: function() - { - if (!this.hasMoreElements()) - throw Cr.NS_ERROR_NOT_AVAILABLE; - - return this._items[this._nextIndex++]; - }, - QueryInterface: function(aIID) - { - if (Ci.nsISimpleEnumerator.equals(aIID) || - Ci.nsISupports.equals(aIID)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - } -}; - - -/** -* A representation of the data in an HTTP request. -* -* @param port : uint -* the port on which the server receiving this request runs -*/ -function Request(port) -{ - /** Method of this request, e.g. GET or POST. */ - this._method = ""; - - /** Path of the requested resource; empty paths are converted to '/'. */ - this._path = ""; - - /** Query string, if any, associated with this request (not including '?'). */ - this._queryString = ""; - - /** Scheme of requested resource, usually http, always lowercase. */ - this._scheme = "http"; - - /** Hostname on which the requested resource resides. */ - this._host = undefined; - - /** Port number over which the request was received. */ - this._port = port; - - var bodyPipe = new Pipe(false, false, 0, PR_UINT32_MAX, null); - - /** Stream from which data in this request's body may be read. */ - this._bodyInputStream = bodyPipe.inputStream; - - /** Stream to which data in this request's body is written. */ - this._bodyOutputStream = bodyPipe.outputStream; - - /** -* The headers in this request. -*/ - this._headers = new nsHttpHeaders(); - - /** -* For the addition of ad-hoc properties and new functionality without having -* to change nsIHttpRequest every time; currently lazily created, as its only -* use is in directory listings. -*/ - this._bag = null; -} -Request.prototype = -{ - // SERVER METADATA - - // - // see nsIHttpRequest.scheme - // - get scheme() - { - return this._scheme; - }, - - // - // see nsIHttpRequest.host - // - get host() - { - return this._host; - }, - - // - // see nsIHttpRequest.port - // - get port() - { - return this._port; - }, - - // REQUEST LINE - - // - // see nsIHttpRequest.method - // - get method() - { - return this._method; - }, - - // - // see nsIHttpRequest.httpVersion - // - get httpVersion() - { - return this._httpVersion.toString(); - }, - - // - // see nsIHttpRequest.path - // - get path() - { - return this._path; - }, - - // - // see nsIHttpRequest.queryString - // - get queryString() - { - return this._queryString; - }, - - // HEADERS - - // - // see nsIHttpRequest.getHeader - // - getHeader: function(name) - { - return this._headers.getHeader(name); - }, - - // - // see nsIHttpRequest.hasHeader - // - hasHeader: function(name) - { - return this._headers.hasHeader(name); - }, - - // - // see nsIHttpRequest.headers - // - get headers() - { - return this._headers.enumerator; - }, - - // - // see nsIPropertyBag.enumerator - // - get enumerator() - { - this._ensurePropertyBag(); - return this._bag.enumerator; - }, - - // - // see nsIHttpRequest.headers - // - get bodyInputStream() - { - return this._bodyInputStream; - }, - - // - // see nsIPropertyBag.getProperty - // - getProperty: function(name) - { - this._ensurePropertyBag(); - return this._bag.getProperty(name); - }, - - - // NSISUPPORTS - - // - // see nsISupports.QueryInterface - // - QueryInterface: function(iid) - { - if (iid.equals(Ci.nsIHttpRequest) || iid.equals(Ci.nsISupports)) - return this; - - throw Cr.NS_ERROR_NO_INTERFACE; - }, - - - // PRIVATE IMPLEMENTATION - - /** Ensures a property bag has been created for ad-hoc behaviors. */ - _ensurePropertyBag: function() - { - if (!this._bag) - this._bag = new WritablePropertyBag(); - } -}; - - -// XPCOM trappings -if ("XPCOMUtils" in this && // Firefox 3.6 doesn't load XPCOMUtils in this scope for some reason... - "generateNSGetFactory" in XPCOMUtils) { - var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsHttpServer]); -} - - - -/** -* Creates a new HTTP server listening for loopback traffic on the given port, -* starts it, and runs the server until the server processes a shutdown request, -* spinning an event loop so that events posted by the server's socket are -* processed. -* -* This method is primarily intended for use in running this script from within -* xpcshell and running a functional HTTP server without having to deal with -* non-essential details. -* -* Note that running multiple servers using variants of this method probably -* doesn't work, simply due to how the internal event loop is spun and stopped. -* -* @note -* This method only works with Mozilla 1.9 (i.e., Firefox 3 or trunk code); -* you should use this server as a component in Mozilla 1.8. -* @param port -* the port on which the server will run, or -1 if there exists no preference -* for a specific port; note that attempting to use some values for this -* parameter (particularly those below 1024) may cause this method to throw or -* may result in the server being prematurely shut down -* @param basePath -* a local directory from which requests will be served (i.e., if this is -* "/home/jwalden/" then a request to /index.html will load -* /home/jwalden/index.html); if this is omitted, only the default URLs in -* this server implementation will be functional -*/ -function server(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - // if you're running this, you probably want to see debugging info - DEBUG = true; - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", SJS_TYPE); - srv.start(port); - - var thread = gThreadManager.currentThread; - while (!srv.isStopped()) - thread.processNextEvent(true); - - // get rid of any pending requests - while (thread.hasPendingEvents()) - thread.processNextEvent(true); - - DEBUG = false; -} - -function startServerAsync(port, basePath) -{ - if (basePath) - { - var lp = Cc["@mozilla.org/file/local;1"] - .createInstance(Ci.nsILocalFile); - lp.initWithPath(basePath); - } - - var srv = new nsHttpServer(); - if (lp) - srv.registerDirectory("/", lp); - srv.registerContentType("sjs", "sjs"); - srv.start(port); - return srv; -} - -exports.nsHttpServer = nsHttpServer; -exports.ScriptableInputStream = ScriptableInputStream; -exports.server = server; -exports.startServerAsync = startServerAsync; diff --git a/addon-sdk/source/test/loader/b2g.js b/addon-sdk/source/test/loader/b2g.js deleted file mode 100644 index 2982a0202..000000000 --- a/addon-sdk/source/test/loader/b2g.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"; - -const {Cc, Ci, Cu} = require("chrome"); -const {readURISync} = require("sdk/net/url"); - -const systemPrincipal = Cc["@mozilla.org/systemprincipal;1"]. - createInstance(Ci.nsIPrincipal); - - -const FakeCu = function() { - const sandbox = Cu.Sandbox(systemPrincipal, {wantXrays: false}); - sandbox.toString = function() { - return "[object BackstagePass]"; - } - this.sandbox = sandbox; -} -FakeCu.prototype = { - ["import"](url, scope) { - const {sandbox} = this; - sandbox.__URI__ = url; - const target = Cu.createObjectIn(sandbox); - target.toString = sandbox.toString; - Cu.evalInSandbox(`(function(){` + readURISync(url) + `\n})`, - sandbox, "1.8", url).call(target); - // Borrowed from mozJSComponentLoader.cpp to match errors closer. - // https://github.com/mozilla/gecko-dev/blob/f6ca65e8672433b2ce1a0e7c31f72717930b5e27/js/xpconnect/loader/mozJSComponentLoader.cpp#L1205-L1208 - if (!Array.isArray(target.EXPORTED_SYMBOLS)) { - throw Error("EXPORTED_SYMBOLS is not an array."); - } - - for (let key of target.EXPORTED_SYMBOLS) { - scope[key] = target[key]; - } - - return target; - } -}; -exports.FakeCu = FakeCu; diff --git a/addon-sdk/source/test/loader/fixture.js b/addon-sdk/source/test/loader/fixture.js deleted file mode 100644 index ebf91abba..000000000 --- a/addon-sdk/source/test/loader/fixture.js +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -exports.foo = foo; -exports.bar = 2; -print('testing'); diff --git a/addon-sdk/source/test/loader/user-global.js b/addon-sdk/source/test/loader/user-global.js deleted file mode 100644 index 34b233f42..000000000 --- a/addon-sdk/source/test/loader/user-global.js +++ /dev/null @@ -1,11 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 module to check presense of user defined globals. -// Related to bug 827792. - -exports.getCom = function() { - return com; -}; diff --git a/addon-sdk/source/test/modules/add.js b/addon-sdk/source/test/modules/add.js deleted file mode 100644 index 54729340d..000000000 --- a/addon-sdk/source/test/modules/add.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/. */ - -define('modules/add', function () { - return function (a, b) { - return a + b; - }; -}); diff --git a/addon-sdk/source/test/modules/async1.js b/addon-sdk/source/test/modules/async1.js deleted file mode 100644 index b7b60fdc2..000000000 --- a/addon-sdk/source/test/modules/async1.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/. */ - -define(['./traditional2', './async2'], function () { - var traditional2 = require('./traditional2'); - return { - name: 'async1', - traditional1Name: traditional2.traditional1Name, - traditional2Name: traditional2.name, - async2Name: require('./async2').name, - async2Traditional2Name: require('./async2').traditional2Name - }; -}); diff --git a/addon-sdk/source/test/modules/async2.js b/addon-sdk/source/test/modules/async2.js deleted file mode 100644 index 802fb2504..000000000 --- a/addon-sdk/source/test/modules/async2.js +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define(['./traditional2', 'exports'], function (traditional2, exports) { - exports.name = 'async2'; - exports.traditional2Name = traditional2.name; -}); diff --git a/addon-sdk/source/test/modules/badExportAndReturn.js b/addon-sdk/source/test/modules/badExportAndReturn.js deleted file mode 100644 index 35a5359f6..000000000 --- a/addon-sdk/source/test/modules/badExportAndReturn.js +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 is a bad module, it asks for exports but also returns a value from -// the define defintion function. -define(['exports'], function (exports) { - return 'badExportAndReturn'; -}); - diff --git a/addon-sdk/source/test/modules/badFirst.js b/addon-sdk/source/test/modules/badFirst.js deleted file mode 100644 index fdb03bd4d..000000000 --- a/addon-sdk/source/test/modules/badFirst.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/. */ - -define(['./badSecond'], function (badSecond) { - return { - name: 'badFirst' - }; -}); diff --git a/addon-sdk/source/test/modules/badSecond.js b/addon-sdk/source/test/modules/badSecond.js deleted file mode 100644 index 8321a8542..000000000 --- a/addon-sdk/source/test/modules/badSecond.js +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 first = require('./badFirst'); - -exports.name = 'badSecond'; -exports.badFirstName = first.name; diff --git a/addon-sdk/source/test/modules/blue.js b/addon-sdk/source/test/modules/blue.js deleted file mode 100644 index 14ab14933..000000000 --- a/addon-sdk/source/test/modules/blue.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/. */ - -define(function () { - return { - name: 'blue' - }; -}); diff --git a/addon-sdk/source/test/modules/castor.js b/addon-sdk/source/test/modules/castor.js deleted file mode 100644 index 9209623b5..000000000 --- a/addon-sdk/source/test/modules/castor.js +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define(['exports', './pollux'], function(exports, pollux) { - exports.name = 'castor'; - exports.getPolluxName = function () { - return pollux.name; - }; -}); diff --git a/addon-sdk/source/test/modules/cheetah.js b/addon-sdk/source/test/modules/cheetah.js deleted file mode 100644 index 37d12bfc1..000000000 --- a/addon-sdk/source/test/modules/cheetah.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/. */ - -define(function () { - return function () { - return 'cheetah'; - }; -}); diff --git a/addon-sdk/source/test/modules/color.js b/addon-sdk/source/test/modules/color.js deleted file mode 100644 index 0d946bd99..000000000 --- a/addon-sdk/source/test/modules/color.js +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define({ - type: 'color' -}); diff --git a/addon-sdk/source/test/modules/dupe.js b/addon-sdk/source/test/modules/dupe.js deleted file mode 100644 index f87fa555a..000000000 --- a/addon-sdk/source/test/modules/dupe.js +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define({ - name: 'dupe' -}); - -// This is wrong and should not be allowed. Only one call to -// define per file. -define([], function () { - return { - name: 'dupe2' - }; -}); diff --git a/addon-sdk/source/test/modules/dupeNested.js b/addon-sdk/source/test/modules/dupeNested.js deleted file mode 100644 index 703948ca7..000000000 --- a/addon-sdk/source/test/modules/dupeNested.js +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - - -define(function () { - // This is wrong and should not be allowed. - define('dupeNested2', { - name: 'dupeNested2' - }); - - return { - name: 'dupeNested' - }; -}); diff --git a/addon-sdk/source/test/modules/dupeSetExports.js b/addon-sdk/source/test/modules/dupeSetExports.js deleted file mode 100644 index 12a1be22b..000000000 --- a/addon-sdk/source/test/modules/dupeSetExports.js +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define({name: "dupeSetExports"}); - -// so this should cause a failure -module.setExports("no no no"); diff --git a/addon-sdk/source/test/modules/exportsEquals.js b/addon-sdk/source/test/modules/exportsEquals.js deleted file mode 100644 index e176316f4..000000000 --- a/addon-sdk/source/test/modules/exportsEquals.js +++ /dev/null @@ -1,5 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -module.exports = 4; diff --git a/addon-sdk/source/test/modules/green.js b/addon-sdk/source/test/modules/green.js deleted file mode 100644 index ce2d134b9..000000000 --- a/addon-sdk/source/test/modules/green.js +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define('modules/green', ['./color'], function (color) { - return { - name: 'green', - parentType: color.type - }; -}); diff --git a/addon-sdk/source/test/modules/lion.js b/addon-sdk/source/test/modules/lion.js deleted file mode 100644 index 9c3ac3bfe..000000000 --- a/addon-sdk/source/test/modules/lion.js +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define(function(require) { - return 'lion'; -}); diff --git a/addon-sdk/source/test/modules/orange.js b/addon-sdk/source/test/modules/orange.js deleted file mode 100644 index 900a32b08..000000000 --- a/addon-sdk/source/test/modules/orange.js +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define(['./color'], function (color) { - return { - name: 'orange', - parentType: color.type - }; -}); diff --git a/addon-sdk/source/test/modules/pollux.js b/addon-sdk/source/test/modules/pollux.js deleted file mode 100644 index 61cf66f9c..000000000 --- a/addon-sdk/source/test/modules/pollux.js +++ /dev/null @@ -1,10 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define(['exports', './castor'], function(exports, castor) { - exports.name = 'pollux'; - exports.getCastorName = function () { - return castor.name; - }; -}); diff --git a/addon-sdk/source/test/modules/red.js b/addon-sdk/source/test/modules/red.js deleted file mode 100644 index c47b8e924..000000000 --- a/addon-sdk/source/test/modules/red.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/. */ - -define(function (require) { - // comment fake-outs for require finding. - // require('bad1'); - return { - name: 'red', - parentType: require('./color').type - }; - - /* - require('bad2'); - */ -}); diff --git a/addon-sdk/source/test/modules/setExports.js b/addon-sdk/source/test/modules/setExports.js deleted file mode 100644 index 495c301cd..000000000 --- a/addon-sdk/source/test/modules/setExports.js +++ /dev/null @@ -1,5 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -module.setExports(5); diff --git a/addon-sdk/source/test/modules/subtract.js b/addon-sdk/source/test/modules/subtract.js deleted file mode 100644 index 06e1053ab..000000000 --- a/addon-sdk/source/test/modules/subtract.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/. */ - -define(function () { - return function (a, b) { - return a - b; - } -}); diff --git a/addon-sdk/source/test/modules/tiger.js b/addon-sdk/source/test/modules/tiger.js deleted file mode 100644 index 80479d019..000000000 --- a/addon-sdk/source/test/modules/tiger.js +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -define(function (require, exports) { - exports.name = 'tiger'; - exports.type = require('./types/cat').type; -}); diff --git a/addon-sdk/source/test/modules/traditional1.js b/addon-sdk/source/test/modules/traditional1.js deleted file mode 100644 index 28af8ef30..000000000 --- a/addon-sdk/source/test/modules/traditional1.js +++ /dev/null @@ -1,12 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -exports.name = 'traditional1' - -var async1 = require('./async1'); - -exports.traditional2Name = async1.traditional2Name; -exports.traditional1Name = async1.traditional1Name; -exports.async2Name = async1.async2Name; -exports.async2Traditional2Name = async1.async2Traditional2Name; diff --git a/addon-sdk/source/test/modules/traditional2.js b/addon-sdk/source/test/modules/traditional2.js deleted file mode 100644 index 67b64eecb..000000000 --- a/addon-sdk/source/test/modules/traditional2.js +++ /dev/null @@ -1,6 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -exports.name = 'traditional2'; -exports.traditional1Name = require('./traditional1').name; diff --git a/addon-sdk/source/test/modules/types/cat.js b/addon-sdk/source/test/modules/types/cat.js deleted file mode 100644 index 41513d682..000000000 --- a/addon-sdk/source/test/modules/types/cat.js +++ /dev/null @@ -1,5 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -exports.type = 'cat'; diff --git a/addon-sdk/source/test/page-mod/helpers.js b/addon-sdk/source/test/page-mod/helpers.js deleted file mode 100644 index 3aa3deb0d..000000000 --- a/addon-sdk/source/test/page-mod/helpers.js +++ /dev/null @@ -1,117 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cc, Ci } = require("chrome"); -const { setTimeout } = require("sdk/timers"); -const { Loader } = require("sdk/test/loader"); -const { openTab, getBrowserForTab, closeTab } = require("sdk/tabs/utils"); -const { getMostRecentBrowserWindow } = require("sdk/window/utils"); -const { merge } = require("sdk/util/object"); -const httpd = require("../lib/httpd"); -const { cleanUI } = require("sdk/test/utils"); - -const PORT = 8099; -const PATH = '/test-contentScriptWhen.html'; - -function createLoader () { - let options = merge({}, require('@loader/options'), - { id: "testloader", prefixURI: require('../fixtures').url() }); - return Loader(module, null, options); -} -exports.createLoader = createLoader; - -function openNewTab(url) { - return openTab(getMostRecentBrowserWindow(), url, { - inBackground: false - }); -} -exports.openNewTab = openNewTab; - -// an evil function enables the creation of tests -// that depend on delicate event timing. do not use. -function testPageMod(assert, done, testURL, pageModOptions, - testCallback, timeout) { - let loader = createLoader(); - let { PageMod } = loader.require("sdk/page-mod"); - let pageMods = pageModOptions.map(opts => new PageMod(opts)); - let newTab = openNewTab(testURL); - let b = getBrowserForTab(newTab); - - function onPageLoad() { - b.removeEventListener("load", onPageLoad, true); - // Delay callback execute as page-mod content scripts may be executed on - // load event. So page-mod actions may not be already done. - // If we delay even more contentScriptWhen:'end', we may want to modify - // this code again. - setTimeout(testCallback, timeout, - b.contentWindow.wrappedJSObject, // TODO: remove this CPOW - function () { - pageMods.forEach(mod => mod.destroy()); - // XXX leaks reported if we don't close the tab? - closeTab(newTab); - loader.unload(); - done(); - } - ); - } - b.addEventListener("load", onPageLoad, true); - - return pageMods; -} -exports.testPageMod = testPageMod; - -/** - * helper function that creates a PageMod and calls back the appropriate handler - * based on the value of document.readyState at the time contentScript is attached - */ -exports.handleReadyState = function(url, contentScriptWhen, callbacks) { - const loader = Loader(module); - const { PageMod } = loader.require('sdk/page-mod'); - - let pagemod = PageMod({ - include: url, - attachTo: ['existing', 'top'], - contentScriptWhen: contentScriptWhen, - contentScript: "self.postMessage(document.readyState)", - onAttach: worker => { - let { tab } = worker; - worker.on('message', readyState => { - // generate event name from `readyState`, e.g. `"loading"` becomes `onLoading`. - let type = 'on' + readyState[0].toUpperCase() + readyState.substr(1); - - if (type in callbacks) - callbacks[type](tab); - - pagemod.destroy(); - loader.unload(); - }) - } - }); -} - -// serves a slow page which takes 1.5 seconds to load, -// 0.5 seconds in each readyState: uninitialized, loading, interactive. -function contentScriptWhenServer() { - const URL = 'http://localhost:' + PORT + PATH; - - const HTML = `/* polyglot js - - delay both the "DOMContentLoaded" - - and "load" events */`; - - let srv = httpd.startServerAsync(PORT); - - srv.registerPathHandler(PATH, (_, response) => { - response.processAsync(); - response.setHeader('Content-Type', 'text/html', false); - setTimeout(_ => response.finish(), 500); - response.write(HTML); - }) - - srv.URL = URL; - return srv; -} -exports.contentScriptWhenServer = contentScriptWhenServer; diff --git a/addon-sdk/source/test/path/test-path.js b/addon-sdk/source/test/path/test-path.js deleted file mode 100644 index 38037af20..000000000 --- a/addon-sdk/source/test/path/test-path.js +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Adapted version of: -// https://github.com/joyent/node/blob/v0.9.1/test/simple/test-path.js - -exports['test path'] = function(assert) { - var system = require('sdk/system'); - var path = require('sdk/fs/path'); - - // Shim process global from node. - var process = Object.create(require('sdk/system')); - process.cwd = process.pathFor.bind(process, 'CurProcD'); - - var isWindows = require('sdk/system').platform.indexOf('win') === 0; - - assert.equal(path.basename(''), ''); - assert.equal(path.basename('/dir/basename.ext'), 'basename.ext'); - assert.equal(path.basename('/basename.ext'), 'basename.ext'); - assert.equal(path.basename('basename.ext'), 'basename.ext'); - assert.equal(path.basename('basename.ext/'), 'basename.ext'); - assert.equal(path.basename('basename.ext//'), 'basename.ext'); - - if (isWindows) { - // On Windows a backslash acts as a path separator. - assert.equal(path.basename('\\dir\\basename.ext'), 'basename.ext'); - assert.equal(path.basename('\\basename.ext'), 'basename.ext'); - assert.equal(path.basename('basename.ext'), 'basename.ext'); - assert.equal(path.basename('basename.ext\\'), 'basename.ext'); - assert.equal(path.basename('basename.ext\\\\'), 'basename.ext'); - - } else { - // On unix a backslash is just treated as any other character. - assert.equal(path.basename('\\dir\\basename.ext'), '\\dir\\basename.ext'); - assert.equal(path.basename('\\basename.ext'), '\\basename.ext'); - assert.equal(path.basename('basename.ext'), 'basename.ext'); - assert.equal(path.basename('basename.ext\\'), 'basename.ext\\'); - assert.equal(path.basename('basename.ext\\\\'), 'basename.ext\\\\'); - } - - // POSIX filenames may include control characters - // c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html - if (!isWindows) { - var controlCharFilename = 'Icon' + String.fromCharCode(13); - assert.equal(path.basename('/a/b/' + controlCharFilename), - controlCharFilename); - } - - assert.equal(path.dirname('/a/b/'), '/a'); - assert.equal(path.dirname('/a/b'), '/a'); - assert.equal(path.dirname('/a'), '/'); - assert.equal(path.dirname(''), '.'); - assert.equal(path.dirname('/'), '/'); - assert.equal(path.dirname('////'), '/'); - - if (isWindows) { - assert.equal(path.dirname('c:\\'), 'c:\\'); - assert.equal(path.dirname('c:\\foo'), 'c:\\'); - assert.equal(path.dirname('c:\\foo\\'), 'c:\\'); - assert.equal(path.dirname('c:\\foo\\bar'), 'c:\\foo'); - assert.equal(path.dirname('c:\\foo\\bar\\'), 'c:\\foo'); - assert.equal(path.dirname('c:\\foo\\bar\\baz'), 'c:\\foo\\bar'); - assert.equal(path.dirname('\\'), '\\'); - assert.equal(path.dirname('\\foo'), '\\'); - assert.equal(path.dirname('\\foo\\'), '\\'); - assert.equal(path.dirname('\\foo\\bar'), '\\foo'); - assert.equal(path.dirname('\\foo\\bar\\'), '\\foo'); - assert.equal(path.dirname('\\foo\\bar\\baz'), '\\foo\\bar'); - assert.equal(path.dirname('c:'), 'c:'); - assert.equal(path.dirname('c:foo'), 'c:'); - assert.equal(path.dirname('c:foo\\'), 'c:'); - assert.equal(path.dirname('c:foo\\bar'), 'c:foo'); - assert.equal(path.dirname('c:foo\\bar\\'), 'c:foo'); - assert.equal(path.dirname('c:foo\\bar\\baz'), 'c:foo\\bar'); - assert.equal(path.dirname('\\\\unc\\share'), '\\\\unc\\share'); - assert.equal(path.dirname('\\\\unc\\share\\foo'), '\\\\unc\\share\\'); - assert.equal(path.dirname('\\\\unc\\share\\foo\\'), '\\\\unc\\share\\'); - assert.equal(path.dirname('\\\\unc\\share\\foo\\bar'), - '\\\\unc\\share\\foo'); - assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\'), - '\\\\unc\\share\\foo'); - assert.equal(path.dirname('\\\\unc\\share\\foo\\bar\\baz'), - '\\\\unc\\share\\foo\\bar'); - } - - - assert.equal(path.extname(''), ''); - assert.equal(path.extname('/path/to/file'), ''); - assert.equal(path.extname('/path/to/file.ext'), '.ext'); - assert.equal(path.extname('/path.to/file.ext'), '.ext'); - assert.equal(path.extname('/path.to/file'), ''); - assert.equal(path.extname('/path.to/.file'), ''); - assert.equal(path.extname('/path.to/.file.ext'), '.ext'); - assert.equal(path.extname('/path/to/f.ext'), '.ext'); - assert.equal(path.extname('/path/to/..ext'), '.ext'); - assert.equal(path.extname('file'), ''); - assert.equal(path.extname('file.ext'), '.ext'); - assert.equal(path.extname('.file'), ''); - assert.equal(path.extname('.file.ext'), '.ext'); - assert.equal(path.extname('/file'), ''); - assert.equal(path.extname('/file.ext'), '.ext'); - assert.equal(path.extname('/.file'), ''); - assert.equal(path.extname('/.file.ext'), '.ext'); - assert.equal(path.extname('.path/file.ext'), '.ext'); - assert.equal(path.extname('file.ext.ext'), '.ext'); - assert.equal(path.extname('file.'), '.'); - assert.equal(path.extname('.'), ''); - assert.equal(path.extname('./'), ''); - assert.equal(path.extname('.file.ext'), '.ext'); - assert.equal(path.extname('.file'), ''); - assert.equal(path.extname('.file.'), '.'); - assert.equal(path.extname('.file..'), '.'); - assert.equal(path.extname('..'), ''); - assert.equal(path.extname('../'), ''); - assert.equal(path.extname('..file.ext'), '.ext'); - assert.equal(path.extname('..file'), '.file'); - assert.equal(path.extname('..file.'), '.'); - assert.equal(path.extname('..file..'), '.'); - assert.equal(path.extname('...'), '.'); - assert.equal(path.extname('...ext'), '.ext'); - assert.equal(path.extname('....'), '.'); - assert.equal(path.extname('file.ext/'), '.ext'); - assert.equal(path.extname('file.ext//'), '.ext'); - assert.equal(path.extname('file/'), ''); - assert.equal(path.extname('file//'), ''); - assert.equal(path.extname('file./'), '.'); - assert.equal(path.extname('file.//'), '.'); - - if (isWindows) { - // On windows, backspace is a path separator. - assert.equal(path.extname('.\\'), ''); - assert.equal(path.extname('..\\'), ''); - assert.equal(path.extname('file.ext\\'), '.ext'); - assert.equal(path.extname('file.ext\\\\'), '.ext'); - assert.equal(path.extname('file\\'), ''); - assert.equal(path.extname('file\\\\'), ''); - assert.equal(path.extname('file.\\'), '.'); - assert.equal(path.extname('file.\\\\'), '.'); - - } else { - // On unix, backspace is a valid name component like any other character. - assert.equal(path.extname('.\\'), ''); - assert.equal(path.extname('..\\'), '.\\'); - assert.equal(path.extname('file.ext\\'), '.ext\\'); - assert.equal(path.extname('file.ext\\\\'), '.ext\\\\'); - assert.equal(path.extname('file\\'), ''); - assert.equal(path.extname('file\\\\'), ''); - assert.equal(path.extname('file.\\'), '.\\'); - assert.equal(path.extname('file.\\\\'), '.\\\\'); - } - - // path.join tests - var failures = []; - var joinTests = - // arguments result - [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'], - [['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'], - [['/foo', '../../../bar'], '/bar'], - [['foo', '../../../bar'], '../../bar'], - [['foo/', '../../../bar'], '../../bar'], - [['foo/x', '../../../bar'], '../bar'], - [['foo/x', './bar'], 'foo/x/bar'], - [['foo/x/', './bar'], 'foo/x/bar'], - [['foo/x/', '.', 'bar'], 'foo/x/bar'], - [['./'], './'], - [['.', './'], './'], - [['.', '.', '.'], '.'], - [['.', './', '.'], '.'], - [['.', '/./', '.'], '.'], - [['.', '/////./', '.'], '.'], - [['.'], '.'], - [['', '.'], '.'], - [['', 'foo'], 'foo'], - [['foo', '/bar'], 'foo/bar'], - [['', '/foo'], '/foo'], - [['', '', '/foo'], '/foo'], - [['', '', 'foo'], 'foo'], - [['foo', ''], 'foo'], - [['foo/', ''], 'foo/'], - [['foo', '', '/bar'], 'foo/bar'], - [['./', '..', '/foo'], '../foo'], - [['./', '..', '..', '/foo'], '../../foo'], - [['.', '..', '..', '/foo'], '../../foo'], - [['', '..', '..', '/foo'], '../../foo'], - [['/'], '/'], - [['/', '.'], '/'], - [['/', '..'], '/'], - [['/', '..', '..'], '/'], - [[''], '.'], - [['', ''], '.'], - [[' /foo'], ' /foo'], - [[' ', 'foo'], ' /foo'], - [[' ', '.'], ' '], - [[' ', '/'], ' /'], - [[' ', ''], ' '], - [['/', 'foo'], '/foo'], - [['/', '/foo'], '/foo'], - [['/', '//foo'], '/foo'], - [['/', '', '/foo'], '/foo'], - [['', '/', 'foo'], '/foo'], - [['', '/', '/foo'], '/foo'] - ]; - - // Windows-specific join tests - if (isWindows) { - joinTests = joinTests.concat( - [// UNC path expected - [['//foo/bar'], '//foo/bar/'], - [['\\/foo/bar'], '//foo/bar/'], - [['\\\\foo/bar'], '//foo/bar/'], - // UNC path expected - server and share separate - [['//foo', 'bar'], '//foo/bar/'], - [['//foo/', 'bar'], '//foo/bar/'], - [['//foo', '/bar'], '//foo/bar/'], - // UNC path expected - questionable - [['//foo', '', 'bar'], '//foo/bar/'], - [['//foo/', '', 'bar'], '//foo/bar/'], - [['//foo/', '', '/bar'], '//foo/bar/'], - // UNC path expected - even more questionable - [['', '//foo', 'bar'], '//foo/bar/'], - [['', '//foo/', 'bar'], '//foo/bar/'], - [['', '//foo/', '/bar'], '//foo/bar/'], - // No UNC path expected (no double slash in first component) - [['\\', 'foo/bar'], '/foo/bar'], - [['\\', '/foo/bar'], '/foo/bar'], - [['', '/', '/foo/bar'], '/foo/bar'], - // No UNC path expected (no non-slashes in first component - questionable) - [['//', 'foo/bar'], '/foo/bar'], - [['//', '/foo/bar'], '/foo/bar'], - [['\\\\', '/', '/foo/bar'], '/foo/bar'], - [['//'], '/'], - // No UNC path expected (share name missing - questionable). - [['//foo'], '/foo'], - [['//foo/'], '/foo/'], - [['//foo', '/'], '/foo/'], - [['//foo', '', '/'], '/foo/'], - // No UNC path expected (too many leading slashes - questionable) - [['///foo/bar'], '/foo/bar'], - [['////foo', 'bar'], '/foo/bar'], - [['\\\\\\/foo/bar'], '/foo/bar'], - // Drive-relative vs drive-absolute paths. This merely describes the - // status quo, rather than being obviously right - [['c:'], 'c:.'], - [['c:.'], 'c:.'], - [['c:', ''], 'c:.'], - [['', 'c:'], 'c:.'], - [['c:.', '/'], 'c:./'], - [['c:.', 'file'], 'c:file'], - [['c:', '/'], 'c:/'], - [['c:', 'file'], 'c:/file'] - ]); - } - - // Run the join tests. - joinTests.forEach(function(test) { - var actual = path.join.apply(path, test[0]); - var expected = isWindows ? test[1].replace(/\//g, '\\') : test[1]; - var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' + - '\n expect=' + JSON.stringify(expected) + - '\n actual=' + JSON.stringify(actual); - if (actual !== expected) failures.push('\n' + message); - // assert.equal(actual, expected, message); - }); - assert.equal(failures.length, 0, failures.join('')); - var joinThrowTests = [true, false, 7, null, {}, undefined, [], NaN]; - joinThrowTests.forEach(function(test) { - assert.throws(function() { - path.join(test); - }, TypeError); - assert.throws(function() { - path.resolve(test); - }, TypeError); - }); - - - // path normalize tests - if (isWindows) { - assert.equal(path.normalize('./fixtures///b/../b/c.js'), - 'fixtures\\b\\c.js'); - assert.equal(path.normalize('/foo/../../../bar'), '\\bar'); - assert.equal(path.normalize('a//b//../b'), 'a\\b'); - assert.equal(path.normalize('a//b//./c'), 'a\\b\\c'); - assert.equal(path.normalize('a//b//.'), 'a\\b'); - assert.equal(path.normalize('//server/share/dir/file.ext'), - '\\\\server\\share\\dir\\file.ext'); - } else { - assert.equal(path.normalize('./fixtures///b/../b/c.js'), - 'fixtures/b/c.js'); - assert.equal(path.normalize('/foo/../../../bar'), '/bar'); - assert.equal(path.normalize('a//b//../b'), 'a/b'); - assert.equal(path.normalize('a//b//./c'), 'a/b/c'); - assert.equal(path.normalize('a//b//.'), 'a/b'); - } - - // path.resolve tests - if (isWindows) { - // windows - var resolveTests = - // arguments result - [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], - [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], - [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], - [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], - [['.'], process.cwd()], - [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'], - [['c:/', '//'], 'c:\\'], - [['c:/', '//dir'], 'c:\\dir'], - [['c:/', '//server/share'], '\\\\server\\share\\'], - [['c:/', '//server//share'], '\\\\server\\share\\'], - [['c:/', '///some//dir'], 'c:\\some\\dir'] - ]; - } else { - // Posix - var resolveTests = - // arguments result - [[['/var/lib', '../', 'file/'], '/var/file'], - [['/var/lib', '/../', 'file/'], '/file'], - // For some mysterious reasons OSX debug builds resolve incorrectly - // https://tbpl.mozilla.org/php/getParsedLog.php?id=25105489&tree=Mozilla-Inbound - // Disable this tests until Bug 891698 is fixed. - // [['a/b/c/', '../../..'], process.cwd()], - // [['.'], process.cwd()], - [['/some/dir', '.', '/absolute/'], '/absolute']]; - } - var failures = []; - resolveTests.forEach(function(test) { - var actual = path.resolve.apply(path, test[0]); - var expected = test[1]; - var message = 'path.resolve(' + test[0].map(JSON.stringify).join(',') + ')' + - '\n expect=' + JSON.stringify(expected) + - '\n actual=' + JSON.stringify(actual); - if (actual !== expected) failures.push('\n' + message); - // assert.equal(actual, expected, message); - }); - assert.equal(failures.length, 0, failures.join('')); - - // path.isAbsolute tests - if (isWindows) { - assert.equal(path.isAbsolute('//server/file'), true); - assert.equal(path.isAbsolute('\\\\server\\file'), true); - assert.equal(path.isAbsolute('C:/Users/'), true); - assert.equal(path.isAbsolute('C:\\Users\\'), true); - assert.equal(path.isAbsolute('C:cwd/another'), false); - assert.equal(path.isAbsolute('C:cwd\\another'), false); - assert.equal(path.isAbsolute('directory/directory'), false); - assert.equal(path.isAbsolute('directory\\directory'), false); - } else { - assert.equal(path.isAbsolute('/home/foo'), true); - assert.equal(path.isAbsolute('/home/foo/..'), true); - assert.equal(path.isAbsolute('bar/'), false); - assert.equal(path.isAbsolute('./baz'), false); - } - - // path.relative tests - if (isWindows) { - // windows - var relativeTests = - // arguments result - [['c:/blah\\blah', 'd:/games', 'd:\\games'], - ['c:/aaaa/bbbb', 'c:/aaaa', '..'], - ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], - ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], - ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], - ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], - ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], - ['c:/aaaa/bbbb', 'd:\\', 'd:\\']]; - } else { - // posix - var relativeTests = - // arguments result - [['/var/lib', '/var', '..'], - ['/var/lib', '/bin', '../../bin'], - ['/var/lib', '/var/lib', ''], - ['/var/lib', '/var/apache', '../apache'], - ['/var/', '/var/lib', 'lib'], - ['/', '/var/lib', 'var/lib']]; - } - var failures = []; - relativeTests.forEach(function(test) { - var actual = path.relative(test[0], test[1]); - var expected = test[2]; - var message = 'path.relative(' + - test.slice(0, 2).map(JSON.stringify).join(',') + - ')' + - '\n expect=' + JSON.stringify(expected) + - '\n actual=' + JSON.stringify(actual); - if (actual !== expected) failures.push('\n' + message); - }); - assert.equal(failures.length, 0, failures.join('')); - - // path.sep tests - if (isWindows) { - // windows - assert.equal(path.sep, '\\'); - } - else { - // posix - assert.equal(path.sep, '/'); - } - - // path.delimiter tests - if (isWindows) { - // windows - assert.equal(path.delimiter, ';'); - } - else { - // posix - assert.equal(path.delimiter, ':'); - } -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/preferences/common.json b/addon-sdk/source/test/preferences/common.json deleted file mode 100644 index c645e24d5..000000000 --- a/addon-sdk/source/test/preferences/common.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "browser.dom.window.dump.enabled": true, - "javascript.options.showInConsole": true, - "devtools.debugger.remote-enabled": true, - "extensions.sdk.console.logLevel": "info", - "extensions.checkCompatibility.nightly": false, - "extensions.update.enabled": false, - "lightweightThemes.update.enabled": false, - "extensions.update.notifyUser": false, - "extensions.enabledScopes": 5, - "extensions.getAddons.cache.enabled": false, - "extensions.installDistroAddons": false, - "extensions.autoDisableScopes": 10, - "app.releaseNotesURL": "http://localhost/app-dummy/", - "app.vendorURL": "http://localhost/app-dummy/" -} diff --git a/addon-sdk/source/test/preferences/e10s-off.json b/addon-sdk/source/test/preferences/e10s-off.json deleted file mode 100644 index 269d7a92a..000000000 --- a/addon-sdk/source/test/preferences/e10s-off.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "browser.tabs.remote.autostart": false, - "browser.tabs.remote.autostart.1": false, - "browser.tabs.remote.autostart.2": false -} diff --git a/addon-sdk/source/test/preferences/e10s-on.json b/addon-sdk/source/test/preferences/e10s-on.json deleted file mode 100644 index dd5a78dbf..000000000 --- a/addon-sdk/source/test/preferences/e10s-on.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "browser.tabs.remote.autostart": true -} diff --git a/addon-sdk/source/test/preferences/firefox.json b/addon-sdk/source/test/preferences/firefox.json deleted file mode 100644 index 5b8145cec..000000000 --- a/addon-sdk/source/test/preferences/firefox.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "browser.startup.homepage": "about:blank", - "startup.homepage_welcome_url": "about:blank", - "devtools.browsertoolbox.panel": "jsdebugger", - "devtools.chrome.enabled": true, - "urlclassifier.updateinterval": 172800, - "browser.safebrowsing.provider.google.gethashURL": "http://localhost/safebrowsing-dummy/gethash", - "browser.safebrowsing.provider.google.updateURL": "http://localhost/safebrowsing-dummy/update", - "browser.safebrowsing.provider.mozilla.gethashURL": "http://localhost/safebrowsing-dummy/gethash", - "browser.safebrowsing.provider.mozilla.updateURL": "http://localhost/safebrowsing-dummy/update" -} diff --git a/addon-sdk/source/test/preferences/no-connections.json b/addon-sdk/source/test/preferences/no-connections.json deleted file mode 100644 index 370b7909c..000000000 --- a/addon-sdk/source/test/preferences/no-connections.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "toolkit.telemetry.enabled": false, - "toolkit.telemetry.server": "https://localhost/telemetry-dummy/", - "app.update.auto": false, - "app.update.url": "http://localhost/app-dummy/update", - "app.update.enabled": false, - "app.update.staging.enabled": false, - "media.gmp-gmpopenh264.autoupdate": false, - "media.gmp-manager.cert.checkAttributes": false, - "media.gmp-manager.cert.requireBuiltIn": false, - "media.gmp-manager.url": "http://localhost/media-dummy/gmpmanager", - "media.gmp-manager.url.override": "http://localhost/dummy-gmp-manager.xml", - "media.gmp-manager.updateEnabled": false, - "browser.aboutHomeSnippets.updateUrl": "https://localhost/snippet-dummy", - "browser.newtab.url": "about:blank", - "browser.search.update": false, - "browser.search.suggest.enabled": false, - "browser.safebrowsing.phishing.enabled": false, - "browser.safebrowsing.provider.google.updateURL": "http://localhost/safebrowsing-dummy/update", - "browser.safebrowsing.provider.google.gethashURL": "http://localhost/safebrowsing-dummy/gethash", - "browser.safebrowsing.provider.google.reportURL": "http://localhost/safebrowsing-dummy/malwarereport", - "browser.selfsupport.url": "https://localhost/selfsupport-dummy", - "browser.safebrowsing.provider.mozilla.gethashURL": "http://localhost/safebrowsing-dummy/gethash", - "browser.safebrowsing.provider.mozilla.updateURL": "http://localhost/safebrowsing-dummy/update", - "browser.newtabpage.directory.source": "data:application/json,{'jetpack':1}", - "browser.newtabpage.directory.ping": "", - "extensions.update.url": "http://localhost/extensions-dummy/updateURL", - "extensions.update.background.url": "http://localhost/extensions-dummy/updateBackgroundURL", - "extensions.blocklist.url": "http://localhost/extensions-dummy/blocklistURL", - "extensions.webservice.discoverURL": "http://localhost/extensions-dummy/discoveryURL", - "extensions.getAddons.maxResults": 0, - "services.blocklist.base": "http://localhost/dummy-kinto/v1", - "geo.wifi.uri": "http://localhost/location-dummy/locationURL", - "browser.search.geoip.url": "http://localhost/location-dummy/locationURL", - "browser.search.isUS": true, - "browser.search.countryCode": "US", - "geo.wifi.uri": "http://localhost/extensions-dummy/geowifiURL", - "geo.wifi.scan": false, - "browser.webapps.checkForUpdates": 0, - "identity.fxaccounts.auth.uri": "http://localhost/fxa-dummy/" -} diff --git a/addon-sdk/source/test/preferences/test-e10s-preferences.js b/addon-sdk/source/test/preferences/test-e10s-preferences.js deleted file mode 100644 index ed09e5fa3..000000000 --- a/addon-sdk/source/test/preferences/test-e10s-preferences.js +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 extend = require("lodash").extend - -var e10sOn = require("./e10s-on.json"); -var commonPrefs = require("./common.json"); -var testPrefs = require("./test.json"); -var fxPrefs = require("./firefox.json"); -var disconnectionPrefs = require("./no-connections.json"); - -var prefs = extend({}, e10sOn, commonPrefs, testPrefs, disconnectionPrefs, fxPrefs); -module.exports = prefs; diff --git a/addon-sdk/source/test/preferences/test-preferences.js b/addon-sdk/source/test/preferences/test-preferences.js deleted file mode 100644 index 5cdb4a292..000000000 --- a/addon-sdk/source/test/preferences/test-preferences.js +++ /dev/null @@ -1,15 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 extend = require("lodash").extend - -var e10sOff = require("./e10s-off.json"); -var commonPrefs = require("./common.json"); -var testPrefs = require("./test.json"); -var fxPrefs = require("./firefox.json"); -var disconnectionPrefs = require("./no-connections.json"); - -var prefs = extend({}, e10sOff, commonPrefs, testPrefs, disconnectionPrefs, fxPrefs); -module.exports = prefs; diff --git a/addon-sdk/source/test/preferences/test.json b/addon-sdk/source/test/preferences/test.json deleted file mode 100644 index d34061fb8..000000000 --- a/addon-sdk/source/test/preferences/test.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "browser.console.showInPanel": true, - "browser.startup.page": 0, - "browser.firstrun.show.localepicker": false, - "browser.firstrun.show.uidiscovery": false, - "browser.ui.layout.tablet": 0, - "dom.disable_open_during_load": false, - "dom.experimental_forms": true, - "dom.forms.number": true, - "dom.forms.color": true, - "dom.max_script_run_time": 0, - "hangmonitor.timeout": 0, - "dom.max_chrome_script_run_time": 0, - "dom.popup_maximum": -1, - "dom.send_after_paint_to_content": true, - "dom.successive_dialog_time_limit": 0, - "browser.shell.checkDefaultBrowser": false, - "shell.checkDefaultClient": false, - "browser.warnOnQuit": false, - "accessibility.typeaheadfind.autostart": false, - "browser.EULA.override": true, - "gfx.color_management.force_srgb": true, - "network.manage-offline-status": false, - "network.http.speculative-parallel-limit": 0, - "test.mousescroll": true, - "security.default_personal_cert": "Select Automatically", - "network.http.prompt-temp-redirect": false, - "security.warn_viewing_mixed": false, - "extensions.defaultProviders.enabled": true, - "datareporting.policy.dataSubmissionPolicyBypassNotification": true, - "layout.css.report_errors": true, - "layout.css.grid.enabled": true, - "layout.spammy_warnings.enabled": false, - "dom.mozSettings.enabled": true, - "network.http.bypass-cachelock-threshold": 200000, - "geo.provider.testing": true, - "browser.pagethumbnails.capturing_disabled": true, - "browser.download.panel.shown": true, - "general.useragent.updates.enabled": false, - "media.eme.enabled": true, - "media.eme.apiVisible": true, - "dom.ipc.tabs.shutdownTimeoutSecs": 0, - "general.useragent.locale": "en-US", - "intl.locale.matchOS": "en-US", - "dom.indexedDB.experimental": true -} diff --git a/addon-sdk/source/test/private-browsing/helper.js b/addon-sdk/source/test/private-browsing/helper.js deleted file mode 100644 index 4a400b95b..000000000 --- a/addon-sdk/source/test/private-browsing/helper.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/. */ -'use strict'; - -const xulApp = require("sdk/system/xul-app"); -const { open: openWindow, getMostRecentBrowserWindow } = require('sdk/window/utils'); -const { openTab, getTabContentWindow, getActiveTab, setTabURL, closeTab } = require('sdk/tabs/utils'); -const promise = require("sdk/core/promise"); -const windowHelpers = require('sdk/window/helpers'); -const events = require("sdk/system/events"); - -exports.openWebpage = function openWebpage(url, enablePrivate) { - if (xulApp.is("Fennec")) { - let chromeWindow = getMostRecentBrowserWindow(); - let rawTab = openTab(chromeWindow, url, { - isPrivate: enablePrivate - }); - - return { - ready: promise.resolve(getTabContentWindow(rawTab)), - close: function () { - closeTab(rawTab); - // Returns a resolved promise as there is no need to wait - return promise.resolve(); - } - }; - } - else { - let win = openWindow(null, { - features: { - private: enablePrivate - } - }); - let deferred = promise.defer(); - - // Wait for delayed startup code to be executed, in order to ensure - // that the window is really ready - events.on("browser-delayed-startup-finished", function onReady({subject}) { - if (subject == win) { - events.off("browser-delayed-startup-finished", onReady); - deferred.resolve(win); - - let rawTab = getActiveTab(win); - setTabURL(rawTab, url); - deferred.resolve(getTabContentWindow(rawTab)); - } - }, true); - - return { - ready: deferred.promise, - close: function () { - return windowHelpers.close(win); - } - }; - } - return null; -} diff --git a/addon-sdk/source/test/private-browsing/tabs.js b/addon-sdk/source/test/private-browsing/tabs.js deleted file mode 100644 index 8564f0735..000000000 --- a/addon-sdk/source/test/private-browsing/tabs.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 { Ci } = require('chrome'); -const { openTab, closeTab } = require('sdk/tabs/utils'); -const { browserWindows } = require('sdk/windows'); -const { isPrivate } = require('sdk/private-browsing'); - -exports.testIsPrivateOnTab = function(assert) { - let window = browserWindows.activeWindow; - assert.ok(!isPrivate(chromeWindow), 'the top level window is not private'); - - let rawTab = openTab(chromeWindow, 'data:text/html,

Hi!

', { - isPrivate: true - }); - - // test that the tab is private - assert.ok(rawTab.browser.docShell.QueryInterface(Ci.nsILoadContext).usePrivateBrowsing); - assert.ok(isPrivate(rawTab.browser.contentWindow)); - assert.ok(isPrivate(rawTab.browser)); - - closeTab(rawTab); -}; diff --git a/addon-sdk/source/test/private-browsing/windows.js b/addon-sdk/source/test/private-browsing/windows.js deleted file mode 100644 index e6f9c53b5..000000000 --- a/addon-sdk/source/test/private-browsing/windows.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/. */ -'use strict'; - -const { onFocus, openDialog, open } = require('sdk/window/utils'); -const { open: openPromise, close, focus, promise } = require('sdk/window/helpers'); -const { isPrivate } = require('sdk/private-browsing'); -const { getMode } = require('sdk/private-browsing/utils'); -const { browserWindows: windows } = require('sdk/windows'); -const { defer } = require('sdk/core/promise'); -const tabs = require('sdk/tabs'); -const { getMostRecentBrowserWindow } = require('sdk/window/utils'); -const { cleanUI } = require("sdk/test/utils"); - -// test openDialog() from window/utils with private option -// test isActive state in pwpb case -// test isPrivate on ChromeWindow -exports.testPerWindowPrivateBrowsingGetter = function*(assert) { - let win = openDialog({ private: true }); - - yield promise(win, 'DOMContentLoaded'); - - assert.equal(getMode(win), true, 'Newly opened window is in PB mode'); - assert.ok(isPrivate(win), 'isPrivate(window) is true'); - - yield close(win); -} - -// test open() from window/utils with private feature -// test isActive state in pwpb case -// test isPrivate on ChromeWindow -exports.testPerWindowPrivateBrowsingGetter = function*(assert) { - let win = open('chrome://browser/content/browser.xul', { - features: { - private: true - } - }); - - yield promise(win, 'DOMContentLoaded'); - assert.equal(getMode(win), true, 'Newly opened window is in PB mode'); - assert.ok(isPrivate(win), 'isPrivate(window) is true'); - yield close(win) -} - -exports.testIsPrivateOnWindowOpen = function*(assert) { - let window = yield new Promise(resolve => { - windows.open({ - isPrivate: true, - onOpen: resolve - }); - }); - - assert.equal(isPrivate(window), false, 'isPrivate for a window is true when it should be'); - assert.equal(isPrivate(window.tabs[0]), false, 'isPrivate for a tab is false when it should be'); - - yield cleanUI(); -} - -exports.testIsPrivateOnWindowOpenFromPrivate = function(assert, done) { - // open a private window - openPromise(null, { - features: { - private: true, - chrome: true, - titlebar: true, - toolbar: true - } - }).then(focus).then(function(window) { - let { promise, resolve } = defer(); - - assert.equal(isPrivate(window), true, 'the only open window is private'); - - windows.open({ - url: 'about:blank', - onOpen: function(w) { - assert.equal(isPrivate(w), false, 'new test window is not private'); - w.close(() => resolve(window)); - } - }); - - return promise; - }).then(close). - then(done, assert.fail); -}; - -exports.testOpenTabWithPrivateWindow = function*(assert) { - let window = getMostRecentBrowserWindow().OpenBrowserWindow({ private: true }); - - assert.pass("loading new private window"); - - yield promise(window, 'load').then(focus); - - assert.equal(isPrivate(window), true, 'the focused window is private'); - - yield new Promise(resolve => tabs.open({ - url: 'about:blank', - onOpen: (tab) => { - assert.equal(isPrivate(tab), false, 'the opened tab is not private'); - tab.close(resolve); - } - })); - - yield close(window); -}; - -exports.testIsPrivateOnWindowOff = function(assert, done) { - windows.open({ - onOpen: function(window) { - assert.equal(isPrivate(window), false, 'isPrivate for a window is false when it should be'); - assert.equal(isPrivate(window.tabs[0]), false, 'isPrivate for a tab is false when it should be'); - window.close(done); - } - }) -} diff --git a/addon-sdk/source/test/querystring/test-querystring.js b/addon-sdk/source/test/querystring/test-querystring.js deleted file mode 100644 index 9a4fbe573..000000000 --- a/addon-sdk/source/test/querystring/test-querystring.js +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -"use strict"; - -// test using assert -var qs = require('sdk/querystring'); - -// folding block, commented to pass gjslint -// {{{ -// [ wonkyQS, canonicalQS, obj ] -var qsTestCases = [ - ['foo=918854443121279438895193', - 'foo=918854443121279438895193', - {'foo': '918854443121279438895193'}], - ['foo=bar', 'foo=bar', {'foo': 'bar'}], - //['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], - ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], - // ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', - // 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', - // {'my weird field': 'q1!2"\'w$5&7/z8)?' }], - ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], - ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], - /* - ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', - 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', - { 'str': 'foo', - 'arr': ['1', '2', '3'], - 'somenull': '', - 'undef': ''}], - */ - //[' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], - // disable test that fails ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], - ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }] -]; - -// [ wonkyQS, canonicalQS, obj ] -var qsColonTestCases = [ - ['foo:bar', 'foo:bar', {'foo': 'bar'}], - //['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], - ['foo:1&bar:2;baz:quux', - 'foo:1%26bar%3A2;baz:quux', - {'foo': '1&bar:2', 'baz': 'quux'}], - ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], - ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] -]; - -// [wonkyObj, qs, canonicalObj] -var extendedFunction = function() {}; -extendedFunction.prototype = {a: 'b'}; -var qsWeirdObjects = [ - //[{regexp: /./g}, 'regexp=', {'regexp': ''}], - //[{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], - //[{fn: function() {}}, 'fn=', {'fn': ''}], - //[{fn: new Function('')}, 'fn=', {'fn': ''}], - //[{math: Math}, 'math=', {'math': ''}], - //[{e: extendedFunction}, 'e=', {'e': ''}], - //[{d: new Date()}, 'd=', {'d': ''}], - //[{d: Date}, 'd=', {'d': ''}], - //[{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], - [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], - //[{n: null}, 'n=', {'n': ''}], - //[{nan: NaN}, 'nan=', {'nan': ''}], - //[{inf: Infinity}, 'inf=', {'inf': ''}] -]; -// }}} - -var qsNoMungeTestCases = [ - ['', {}], - //['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], - ['blah=burp', {'blah': 'burp'}], - //['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], - ['frappucino=muffin&goat%5B%5D=scone&pond=moose', - {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], - ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] -]; - -exports['test basic'] = function(assert) { - assert.strictEqual('918854443121279438895193', - qs.parse('id=918854443121279438895193').id, - 'prase id=918854443121279438895193'); -}; - -exports['test that the canonical qs is parsed properly'] = function(assert) { - qsTestCases.forEach(function(testCase) { - assert.deepEqual(testCase[2], qs.parse(testCase[0]), - 'parse ' + testCase[0]); - }); -}; - - -exports['test that the colon test cases can do the same'] = function(assert) { - qsColonTestCases.forEach(function(testCase) { - assert.deepEqual(testCase[2], qs.parse(testCase[0], ';', ':'), - 'parse ' + testCase[0] + ' -> ; :'); - }); -}; - -exports['test the weird objects, that they get parsed properly'] = function(assert) { - qsWeirdObjects.forEach(function(testCase) { - assert.deepEqual(testCase[2], qs.parse(testCase[1]), - 'parse ' + testCase[1]); - }); -}; - -exports['test non munge test cases'] = function(assert) { - qsNoMungeTestCases.forEach(function(testCase) { - assert.deepEqual(testCase[0], qs.stringify(testCase[1], '&', '=', false), - 'stringify ' + JSON.stringify(testCase[1]) + ' -> & ='); - }); -}; - -exports['test the nested qs-in-qs case'] = function(assert) { - var f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); - f.q = qs.parse(f.q); - assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }, - 'parse a=b&q=x%3Dy%26y%3Dz'); -}; - -exports['test nested in colon'] = function(assert) { - var f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); - f.q = qs.parse(f.q, ';', ':'); - assert.deepEqual(f, { a: 'b', q: { x: 'y', y: 'z' } }, - 'parse a:b;q:x%3Ay%3By%3Az -> ; :'); -}; - -exports['test stringifying'] = function(assert) { - qsTestCases.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[2]), - 'stringify ' + JSON.stringify(testCase[2])); - }); - - qsColonTestCases.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[2], ';', ':'), - 'stringify ' + JSON.stringify(testCase[2]) + ' -> ; :'); - }); - - qsWeirdObjects.forEach(function(testCase) { - assert.equal(testCase[1], qs.stringify(testCase[0]), - 'stringify ' + JSON.stringify(testCase[0])); - }); -}; - -exports['test stringifying nested'] = function(assert) { - var f = qs.stringify({ - a: 'b', - q: qs.stringify({ - x: 'y', - y: 'z' - }) - }); - assert.equal(f, 'a=b&q=x%3Dy%26y%3Dz', - JSON.stringify({ - a: 'b', - 'qs.stringify -> q': { - x: 'y', - y: 'z' - } - })); - - var threw = false; - try { qs.parse(undefined); } catch(error) { threw = true; } - assert.ok(!threw, "does not throws on undefined"); -}; - -exports['test nested in colon'] = function(assert) { - var f = qs.stringify({ - a: 'b', - q: qs.stringify({ - x: 'y', - y: 'z' - }, ';', ':') - }, ';', ':'); - assert.equal(f, 'a:b;q:x%3Ay%3By%3Az', - 'stringify ' + JSON.stringify({ - a: 'b', - 'qs.stringify -> q': { - x: 'y', - y: 'z' - } - }) + ' -> ; : '); - - - assert.deepEqual({}, qs.parse(), 'parse undefined'); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/sidebar/utils.js b/addon-sdk/source/test/sidebar/utils.js deleted file mode 100644 index 21002ba49..000000000 --- a/addon-sdk/source/test/sidebar/utils.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'; - -module.metadata = { - 'engines': { - 'Firefox': '*' - } -}; - -const { Cu } = require('chrome'); -const { getMostRecentBrowserWindow } = require('sdk/window/utils'); -const { fromIterator } = require('sdk/util/array'); - -const BUILTIN_SIDEBAR_MENUITEMS = exports.BUILTIN_SIDEBAR_MENUITEMS = [ - 'menu_socialSidebar', - 'menu_historySidebar', - 'menu_bookmarksSidebar', - 'menu_tabsSidebar', -]; - -function isSidebarShowing(window) { - window = window || getMostRecentBrowserWindow(); - let sidebar = window.document.getElementById('sidebar-box'); - return !sidebar.hidden; -} -exports.isSidebarShowing = isSidebarShowing; - -function getSidebarMenuitems(window) { - window = window || getMostRecentBrowserWindow(); - return fromIterator(window.document.querySelectorAll('#viewSidebarMenu menuitem')); -} -exports.getSidebarMenuitems = getSidebarMenuitems; - -function getExtraSidebarMenuitems() { - let menuitems = getSidebarMenuitems(); - return menuitems.filter(function(mi) { - return BUILTIN_SIDEBAR_MENUITEMS.indexOf(mi.getAttribute('id')) < 0; - }); -} -exports.getExtraSidebarMenuitems = getExtraSidebarMenuitems; - -function makeID(id) { - return 'jetpack-sidebar-' + id; -} -exports.makeID = makeID; - -function simulateCommand(ele) { - let window = ele.ownerDocument.defaultView; - let { document } = window; - var evt = document.createEvent('XULCommandEvent'); - evt.initCommandEvent('command', true, true, window, - 0, false, false, false, false, null); - ele.dispatchEvent(evt); -} -exports.simulateCommand = simulateCommand; - -function simulateClick(ele) { - let window = ele.ownerDocument.defaultView; - let { document } = window; - let evt = document.createEvent('MouseEvents'); - evt.initMouseEvent('click', true, true, window, - 0, 0, 0, 0, 0, false, false, false, false, 0, null); - ele.dispatchEvent(evt); -} -exports.simulateClick = simulateClick; - -// OSX and Windows exhibit different behaviors when 'checked' is false, -// so compare against the consistent 'true'. See bug 894809. -function isChecked(node) { - return node.getAttribute('checked') === 'true'; -}; -exports.isChecked = isChecked; diff --git a/addon-sdk/source/test/tabs/test-fennec-tabs.js b/addon-sdk/source/test/tabs/test-fennec-tabs.js deleted file mode 100644 index d7e362d41..000000000 --- a/addon-sdk/source/test/tabs/test-fennec-tabs.js +++ /dev/null @@ -1,595 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cc, Ci } = require('chrome'); -const { Loader, LoaderWithHookedConsole } = require('sdk/test/loader'); -const timer = require('sdk/timers'); -const tabs = require('sdk/tabs'); -const windows = require('sdk/windows'); -const { set: setPref } = require("sdk/preferences/service"); -const DEPRECATE_PREF = "devtools.errorconsole.deprecation_warnings"; - -const tabsLen = tabs.length; -const URL = 'data:text/html;charset=utf-8,#title#'; - -// Fennec error message dispatched on all currently unimplement tab features, -// that match LoaderWithHookedConsole messages object pattern -const ERR_FENNEC_MSG = { - type: "error", - msg: "This method is not yet supported by Fennec" -}; - -// TEST: tab unloader -exports.testAutomaticDestroy = function(assert, done) { - let called = false; - - let loader2 = Loader(module); - let loader3 = Loader(module); - let tabs2 = loader2.require('sdk/tabs'); - let tabs3 = loader3.require('sdk/tabs'); - let tabs2Len = tabs2.length; - - tabs2.on('open', function onOpen(tab) { - assert.fail("an onOpen listener was called that should not have been"); - called = true; - }); - tabs2.on('ready', function onReady(tab) { - assert.fail("an onReady listener was called that should not have been"); - called = true; - }); - tabs2.on('select', function onSelect(tab) { - assert.fail("an onSelect listener was called that should not have been"); - called = true; - }); - tabs2.on('close', function onClose(tab) { - assert.fail("an onClose listener was called that should not have been"); - called = true; - }); - loader2.unload(); - - tabs3.on('open', function onOpen(tab) { - assert.pass("an onOpen listener was called for tabs3"); - - tab.on('ready', function onReady(tab) { - assert.fail("an onReady listener was called that should not have been"); - called = true; - }); - tab.on('select', function onSelect(tab) { - assert.fail("an onSelect listener was called that should not have been"); - called = true; - }); - tab.on('close', function onClose(tab) { - assert.fail("an onClose listener was called that should not have been"); - called = true; - }); - }); - tabs3.open(URL.replace(/#title#/, 'tabs3')); - loader3.unload(); - - // Fire a tab event and ensure that the destroyed tab is inactive - tabs.once('open', function(tab) { - assert.pass('tabs.once("open") works!'); - - assert.equal(tabs2Len, tabs2.length, "tabs2 length was not changed"); - assert.equal(tabs.length, (tabs2.length+2), "tabs.length > tabs2.length"); - - tab.once('ready', function() { - assert.pass('tab.once("ready") works!'); - - tab.once('close', function() { - assert.pass('tab.once("close") works!'); - - timer.setTimeout(function () { - assert.ok(!called, "Unloaded tab module is destroyed and inactive"); - - // end test - done(); - }); - }); - - tab.close(); - }); - }); - - tabs.open('data:text/html;charset=utf-8,foo'); -}; - -// TEST: tab properties -exports.testTabProperties = function(assert, done) { - let url = "data:text/html;charset=utf-8,foofoo"; - let tabsLen = tabs.length; - tabs.open({ - url: url, - onReady: function(tab) { - assert.equal(tab.title, "foo", "title of the new tab matches"); - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tab.style, null, "style of the new tab matches"); - assert.equal(tab.index, tabsLen, "index of the new tab matches"); - assert.notEqual(tab.getThumbnail(), null, "thumbnail of the new tab matches"); - assert.notEqual(tab.id, null, "a tab object always has an id property"); - - tab.close(function() { - loader.unload(); - - // end test - done(); - }); - } - }); -}; - -// TEST: tabs iterator and length property -exports.testTabsIteratorAndLength = function(assert, done) { - let newTabs = []; - let startCount = 0; - for (let t of tabs) startCount++; - - assert.equal(startCount, tabs.length, "length property is correct"); - - let url = "data:text/html;charset=utf-8,testTabsIteratorAndLength"; - tabs.open({url: url, onOpen: tab => newTabs.push(tab)}); - tabs.open({url: url, onOpen: tab => newTabs.push(tab)}); - tabs.open({ - url: url, - onOpen: function(tab) { - let count = 0; - for (let t of tabs) count++; - assert.equal(count, startCount + 3, "iterated tab count matches"); - assert.equal(startCount + 3, tabs.length, "iterated tab count matches length property"); - - let newTabsLength = newTabs.length; - newTabs.forEach(t => t.close(function() { - if (--newTabsLength > 0) return; - - tab.close(done); - })); - } - }); -}; - -// TEST: tab.url setter -exports.testTabLocation = function(assert, done) { - let url1 = "data:text/html;charset=utf-8,foo"; - let url2 = "data:text/html;charset=utf-8,bar"; - - tabs.on('ready', function onReady(tab) { - if (tab.url != url2) - return; - - tabs.removeListener('ready', onReady); - assert.pass("tab loaded the correct url"); - - tab.close(done); - }); - - tabs.open({ - url: url1, - onOpen: function(tab) { - tab.url = url2; - } - }); -}; - -// TEST: tab.move() -exports.testTabMove = function(assert, done) { - let { loader, messages } = LoaderWithHookedConsole(); - let tabs = loader.require('sdk/tabs'); - - let url = "data:text/html;charset=utf-8,testTabMove"; - - tabs.open({ - url: url, - onOpen: function(tab1) { - assert.ok(tab1.index >= 0, "opening a tab returns a tab w/ valid index"); - - tabs.open({ - url: url, - onOpen: function(tab) { - let i = tab.index; - assert.ok(tab.index > tab1.index, "2nd tab has valid index"); - tab.index = 0; - assert.equal(tab.index, i, "tab index after move matches"); - assert.equal(JSON.stringify(messages), - JSON.stringify([ERR_FENNEC_MSG]), - "setting tab.index logs error"); - // end test - tab1.close(() => tab.close(function() { - loader.unload(); - done(); - })); - } - }); - } - }); -}; - -// TEST: open tab with default options -exports.testTabsOpen_alt = function(assert, done) { - let { loader, messages } = LoaderWithHookedConsole(); - let tabs = loader.require('sdk/tabs'); - let url = "data:text/html;charset=utf-8,default"; - - tabs.open({ - url: url, - onReady: function(tab) { - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tabs.activeTab, tab, "URL of active tab in the current window matches"); - assert.equal(tab.isPinned, false, "The new tab is not pinned"); - assert.equal(messages.length, 1, "isPinned logs error"); - - // end test - tab.close(function() { - loader.unload(); - done(); - }); - } - }); -}; - -// TEST: open pinned tab -exports.testOpenPinned_alt = function(assert, done) { - let { loader, messages } = LoaderWithHookedConsole(); - let tabs = loader.require('sdk/tabs'); - let url = "about:blank"; - - tabs.open({ - url: url, - isPinned: true, - onOpen: function(tab) { - assert.equal(tab.isPinned, false, "The new tab is pinned"); - // We get two error message: one for tabs.open's isPinned argument - // and another one for tab.isPinned - assert.equal(JSON.stringify(messages), - JSON.stringify([ERR_FENNEC_MSG, ERR_FENNEC_MSG]), - "isPinned logs error"); - - // end test - tab.close(function() { - loader.unload(); - done(); - }); - } - }); -}; - -// TEST: pin/unpin opened tab -exports.testPinUnpin_alt = function(assert, done) { - let { loader, messages } = LoaderWithHookedConsole(); - let tabs = loader.require('sdk/tabs'); - let url = "data:text/html;charset=utf-8,default"; - - tabs.open({ - url: url, - onOpen: function(tab) { - tab.pin(); - assert.equal(tab.isPinned, false, "The tab was pinned correctly"); - assert.equal(JSON.stringify(messages), - JSON.stringify([ERR_FENNEC_MSG, ERR_FENNEC_MSG]), - "tab.pin() logs error"); - - // Clear console messages for the following test - messages.length = 0; - - tab.unpin(); - assert.equal(tab.isPinned, false, "The tab was unpinned correctly"); - assert.equal(JSON.stringify(messages), - JSON.stringify([ERR_FENNEC_MSG, ERR_FENNEC_MSG]), - "tab.unpin() logs error"); - - // end test - tab.close(function() { - loader.unload(); - done(); - }); - } - }); -}; - -// TEST: open tab in background -exports.testInBackground = function(assert, done) { - let activeUrl = tabs.activeTab.url; - let url = "data:text/html;charset=utf-8,background"; - let window = windows.browserWindows.activeWindow; - tabs.once('ready', function onReady(tab) { - assert.equal(tabs.activeTab.url, activeUrl, "URL of active tab has not changed"); - assert.equal(tab.url, url, "URL of the new background tab matches"); - assert.equal(windows.browserWindows.activeWindow, window, "a new window was not opened"); - assert.notEqual(tabs.activeTab.url, url, "URL of active tab is not the new URL"); - - // end test - tab.close(done); - }); - - tabs.open({ - url: url, - inBackground: true - }); -}; - -// TEST: open tab in new window -exports.testOpenInNewWindow = function(assert, done) { - let url = "data:text/html;charset=utf-8,newwindow"; - let window = windows.browserWindows.activeWindow; - - tabs.open({ - url: url, - inNewWindow: true, - onReady: function(tab) { - assert.equal(windows.browserWindows.length, 1, "a new window was not opened"); - assert.equal(windows.browserWindows.activeWindow, window, "old window is active"); - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tabs.activeTab, tab, "tab is the activeTab"); - - tab.close(done); - } - }); -}; - -// TEST: onOpen event handler -exports.testTabsEvent_onOpen = function(assert, done) { - let url = URL.replace('#title#', 'testTabsEvent_onOpen'); - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - }; - tabs.on('open', listener1); - - // add listener via collection add - tabs.on('open', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener('open', listener1); - tabs.removeListener('open', listener2); - - // ends test - tab.close(done); - }); - - tabs.open(url); -}; - -// TEST: onClose event handler -exports.testTabsEvent_onClose = function(assert, done) { - let url = "data:text/html;charset=utf-8,onclose"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - } - tabs.on('close', listener1); - - // add listener via collection add - tabs.on('close', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener('close', listener1); - tabs.removeListener('close', listener2); - - // end test - done(); - }); - - tabs.on('ready', function onReady(tab) { - tabs.removeListener('ready', onReady); - tab.close(); - }); - - tabs.open(url); -}; - -// TEST: onClose event handler when a window is closed -exports.testTabsEvent_onCloseWindow = function(assert, done) { - let closeCount = 0, individualCloseCount = 0; - function listener() { - closeCount++; - } - tabs.on('close', listener); - - // One tab is already open with the window - let openTabs = 0; - function testCasePossiblyLoaded(tab) { - tab.close(function() { - if (++openTabs == 3) { - tabs.removeListener("close", listener); - - assert.equal(closeCount, 3, "Correct number of close events received"); - assert.equal(individualCloseCount, 3, - "Each tab with an attached onClose listener received a close " + - "event when the window was closed"); - - done(); - } - }); - } - - tabs.open({ - url: "data:text/html;charset=utf-8,tab2", - onOpen: testCasePossiblyLoaded, - onClose: () => individualCloseCount++ - }); - - tabs.open({ - url: "data:text/html;charset=utf-8,tab3", - onOpen: testCasePossiblyLoaded, - onClose: () => individualCloseCount++ - }); - - tabs.open({ - url: "data:text/html;charset=utf-8,tab4", - onOpen: testCasePossiblyLoaded, - onClose: () => individualCloseCount++ - }); -}; - -// TEST: onReady event handler -exports.testTabsEvent_onReady = function(assert, done) { - let url = "data:text/html;charset=utf-8,onready"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - }; - tabs.on('ready', listener1); - - // add listener via collection add - tabs.on('ready', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener('ready', listener1); - tabs.removeListener('ready', listener2); - - // end test - tab.close(done); - }); - - tabs.open(url); -}; - -// TEST: onActivate event handler -exports.testTabsEvent_onActivate = function(assert, done) { - let url = "data:text/html;charset=utf-8,onactivate"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - }; - tabs.on('activate', listener1); - - // add listener via collection add - tabs.on('activate', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - assert.equal(tab, tabs.activeTab, 'the active tab is correct'); - tabs.removeListener('activate', listener1); - tabs.removeListener('activate', listener2); - - // end test - tab.close(done); - }); - - tabs.open(url); -}; - -// TEST: onDeactivate event handler -exports.testTabsEvent_onDeactivate = function(assert, done) { - let url = "data:text/html;charset=utf-8,ondeactivate"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - }; - tabs.on('deactivate', listener1); - - // add listener via collection add - tabs.on('deactivate', function listener2(tab) { - assert.equal(++eventCount, 2, 'both listeners notified'); - assert.notEqual(tab, tabs.activeTab, 'the active tab is not the deactivated tab'); - tabs.removeListener('deactivate', listener1); - tabs.removeListener('deactivate', listener2); - - // end test - tab.close(done); - }); - - tabs.on('activate', function onActivate(tab) { - tabs.removeListener('activate', onActivate); - tabs.open("data:text/html;charset=utf-8,foo"); - tab.close(); - }); - - tabs.open(url); -}; - -// TEST: per-tab event handlers -exports.testPerTabEvents = function(assert, done) { - let eventCount = 0; - - tabs.open({ - url: "data:text/html;charset=utf-8,foo", - onOpen: function(tab) { - // add listener via property assignment - function listener1() { - eventCount++; - }; - tab.on('ready', listener1); - - // add listener via collection add - tab.on('ready', function listener2() { - assert.equal(eventCount, 1, "both listeners notified"); - tab.removeListener('ready', listener1); - tab.removeListener('ready', listener2); - - // end test - tab.close(done); - }); - } - }); -}; - -exports.testUniqueTabIds = function(assert, done) { - var tabs = require('sdk/tabs'); - var tabIds = {}; - var steps = [ - function (index) { - tabs.open({ - url: "data:text/html;charset=utf-8,foo", - onOpen: function(tab) { - tabIds['tab1'] = tab.id; - next(index); - } - }); - }, - function (index) { - tabs.open({ - url: "data:text/html;charset=utf-8,bar", - onOpen: function(tab) { - tabIds['tab2'] = tab.id; - next(index); - } - }); - }, - function (index) { - assert.notEqual(tabIds.tab1, tabIds.tab2, "Tab ids should be unique."); - done(); - } - ]; - - function next(index) { - if (index === steps.length) { - return; - } - let fn = steps[index]; - index++; - fn(index); - } - - next(0); -} - -exports.testOnLoadEventWithDOM = function(assert, done) { - let count = 0; - let title = 'testOnLoadEventWithDOM'; - - tabs.open({ - url: 'data:text/html;charset=utf-8,' + title + '', - inBackground: true, - onLoad: function(tab) { - assert.equal(tab.title, title, 'tab passed in as arg, load called'); - - if (++count > 1) { - assert.pass('onLoad event called on reload'); - tab.close(done); - } - else { - assert.pass('first onLoad event occured'); - tab.reload(); - } - } - }); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/tabs/test-firefox-tabs.js b/addon-sdk/source/test/tabs/test-firefox-tabs.js deleted file mode 100644 index 368ed02ba..000000000 --- a/addon-sdk/source/test/tabs/test-firefox-tabs.js +++ /dev/null @@ -1,1305 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cc, Ci } = require('chrome'); -const { Loader } = require('sdk/test/loader'); -const systemEvents = require("sdk/system/events"); -const { setTimeout, setImmediate } = require('sdk/timers'); -const { modelFor } = require('sdk/model/core'); -const { viewFor } = require('sdk/view/core'); -const { getOwnerWindow } = require('sdk/tabs/utils'); -const { windows, onFocus, getMostRecentBrowserWindow } = require('sdk/window/utils'); -const { open, focus, close } = require('sdk/window/helpers'); -const { observer: windowObserver } = require("sdk/windows/observer"); -const tabs = require('sdk/tabs'); -const { browserWindows } = require('sdk/windows'); -const { set: setPref, get: getPref, reset: resetPref } = require("sdk/preferences/service"); -const DEPRECATE_PREF = "devtools.errorconsole.deprecation_warnings"; -const OPEN_IN_NEW_WINDOW_PREF = 'browser.link.open_newwindow'; -const DISABLE_POPUP_PREF = 'dom.disable_open_during_load'; -const fixtures = require("../fixtures"); -const { base64jpeg } = fixtures; -const { cleanUI, before, after } = require("sdk/test/utils"); -const { wait } = require('../event/helpers'); - -// Bug 682681 - tab.title should never be empty -exports.testBug682681_aboutURI = function(assert, done) { - let url = 'chrome://browser/locale/tabbrowser.properties'; - let stringBundle = Cc["@mozilla.org/intl/stringbundle;1"]. - getService(Ci.nsIStringBundleService). - createBundle(url); - let emptyTabTitle = stringBundle.GetStringFromName('tabs.emptyTabTitle'); - - tabs.on('ready', function onReady(tab) { - tabs.removeListener('ready', onReady); - - assert.equal(tab.title, - emptyTabTitle, - "title of about: tab is not blank"); - - tab.close(done); - }); - - // open a about: url - tabs.open({ - url: "about:blank", - inBackground: true - }); -}; - -// related to Bug 682681 -exports.testTitleForDataURI = function(assert, done) { - tabs.open({ - url: "data:text/html;charset=utf-8,tab", - inBackground: true, - onReady: function(tab) { - assert.equal(tab.title, "tab", "data: title is not Connecting..."); - tab.close(done); - } - }); -}; - -// TEST: 'BrowserWindow' instance creation on tab 'activate' event -// See bug 648244: there was a infinite loop. -exports.testBrowserWindowCreationOnActivate = function(assert, done) { - let windows = require("sdk/windows").browserWindows; - let gotActivate = false; - - tabs.once('activate', function onActivate(eventTab) { - assert.ok(windows.activeWindow, "Is able to fetch activeWindow"); - gotActivate = true; - }); - - open().then(function(window) { - assert.ok(gotActivate, "Received activate event"); - return close(window); - }).then(done).then(null, assert.fail); -} - -// TEST: tab unloader -exports.testAutomaticDestroyEventOpen = function(assert, done) { - let called = false; - let loader = Loader(module); - let tabs2 = loader.require("sdk/tabs"); - tabs2.on('open', _ => called = true); - - // Fire a tab event and ensure that the destroyed tab is inactive - tabs.once('open', tab => { - setTimeout(_ => { - assert.ok(!called, "Unloaded tab module is destroyed and inactive"); - tab.close(done); - }); - }); - - loader.unload(); - tabs.open("data:text/html;charset=utf-8,testAutomaticDestroyEventOpen"); -}; - -exports.testAutomaticDestroyEventActivate = function(assert, done) { - let called = false; - let loader = Loader(module); - let tabs2 = loader.require("sdk/tabs"); - tabs2.on('activate', _ => called = true); - - // Fire a tab event and ensure that the destroyed tab is inactive - tabs.once('activate', tab => { - setTimeout(_ => { - assert.ok(!called, "Unloaded tab module is destroyed and inactive"); - tab.close(done); - }); - }); - - loader.unload(); - tabs.open("data:text/html;charset=utf-8,testAutomaticDestroyEventActivate"); -}; - -exports.testAutomaticDestroyEventDeactivate = function(assert, done) { - let called = false; - let currentTab = tabs.activeTab; - let loader = Loader(module); - let tabs2 = loader.require("sdk/tabs"); - - tabs.open({ - url: "data:text/html;charset=utf-8,testAutomaticDestroyEventDeactivate", - onActivate: _ => setTimeout(_ => { - tabs2.on('deactivate', _ => called = true); - - // Fire a tab event and ensure that the destroyed tab is inactive - tabs.once('deactivate', tab => { - setTimeout(_ => { - assert.ok(!called, "Unloaded tab module is destroyed and inactive"); - tab.close(done); - }); - }); - - loader.unload(); - currentTab.activate(); - }) - }); -}; - -exports.testAutomaticDestroyEventClose = function(assert, done) { - let called = false; - let loader = Loader(module); - let tabs2 = loader.require("sdk/tabs"); - - tabs.open({ - url: "data:text/html;charset=utf-8,testAutomaticDestroyEventClose", - onReady: tab => { - tabs2.on('close', _ => called = true); - - // Fire a tab event and ensure that the destroyed tab is inactive - tabs.once('close', tab => { - setTimeout(_ => { - assert.ok(!called, "Unloaded tab module is destroyed and inactive"); - done(); - }); - }); - - loader.unload(); - tab.close(); - } - }); -}; - -exports.testTabPropertiesInNewWindow = function(assert, done) { - const { LoaderWithFilteredConsole } = require("sdk/test/loader"); - let loader = LoaderWithFilteredConsole(module, function(type, message) { - return true; - }); - - let tabs = loader.require('sdk/tabs'); - let { viewFor } = loader.require('sdk/view/core'); - - let count = 0; - function onReadyOrLoad (tab) { - if (count++) { - close(getOwnerWindow(viewFor(tab))).then(done).then(null, assert.fail); - } - } - - let url = "data:text/html;charset=utf-8,foofoo"; - tabs.open({ - inNewWindow: true, - url: url, - onReady: function(tab) { - assert.equal(tab.title, "foo", "title of the new tab matches"); - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tab.favicon, undefined, "favicon of the new tab is undefined"); - assert.equal(tab.style, null, "style of the new tab matches"); - assert.equal(tab.index, 0, "index of the new tab matches"); - assert.notEqual(tab.getThumbnail(), null, "thumbnail of the new tab matches"); - assert.notEqual(tab.id, null, "a tab object always has an id property."); - - onReadyOrLoad(tab); - }, - onLoad: function(tab) { - assert.equal(tab.title, "foo", "title of the new tab matches"); - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tab.favicon, undefined, "favicon of the new tab is undefined"); - assert.equal(tab.style, null, "style of the new tab matches"); - assert.equal(tab.index, 0, "index of the new tab matches"); - assert.notEqual(tab.getThumbnail(), null, "thumbnail of the new tab matches"); - assert.notEqual(tab.id, null, "a tab object always has an id property."); - - onReadyOrLoad(tab); - } - }); -}; - -exports.testTabPropertiesInSameWindow = function(assert, done) { - const { LoaderWithFilteredConsole } = require("sdk/test/loader"); - let loader = LoaderWithFilteredConsole(module, function(type, message) { - return true; - }); - - let tabs = loader.require('sdk/tabs'); - - // Get current count of tabs so we know the index of the - // new tab, bug 893846 - let tabCount = tabs.length; - let count = 0; - function onReadyOrLoad (tab) { - if (count++) { - tab.close(done); - } - } - - let url = "data:text/html;charset=utf-8,foofoo"; - tabs.open({ - url: url, - onReady: function(tab) { - assert.equal(tab.title, "foo", "title of the new tab matches"); - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tab.favicon, undefined, "favicon of the new tab is undefined"); - assert.equal(tab.style, null, "style of the new tab matches"); - assert.equal(tab.index, tabCount, "index of the new tab matches"); - assert.notEqual(tab.getThumbnail(), null, "thumbnail of the new tab matches"); - assert.notEqual(tab.id, null, "a tab object always has an id property."); - - onReadyOrLoad(tab); - }, - onLoad: function(tab) { - assert.equal(tab.title, "foo", "title of the new tab matches"); - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tab.favicon, undefined, "favicon of the new tab is undefined"); - assert.equal(tab.style, null, "style of the new tab matches"); - assert.equal(tab.index, tabCount, "index of the new tab matches"); - assert.notEqual(tab.getThumbnail(), null, "thumbnail of the new tab matches"); - assert.notEqual(tab.id, null, "a tab object always has an id property."); - - onReadyOrLoad(tab); - } - }); -}; - -// TEST: tab properties -exports.testTabContentTypeAndReload = function(assert, done) { - open().then(focus).then(function(window) { - let url = "data:text/html;charset=utf-8,foofoo"; - let urlXML = "data:text/xml;charset=utf-8,bar"; - tabs.open({ - url: url, - onReady: function(tab) { - if (tab.url === url) { - assert.equal(tab.contentType, "text/html"); - tab.url = urlXML; - } - else { - assert.equal(tab.contentType, "text/xml"); - close(window).then(done).then(null, assert.fail); - } - } - }); - }); -}; - -// TEST: tabs iterator and length property -exports.testTabsIteratorAndLength = function(assert, done) { - open(null, { features: { chrome: true, toolbar: true } }).then(focus).then(function(window) { - let startCount = 0; - for (let t of tabs) startCount++; - assert.equal(startCount, tabs.length, "length property is correct"); - let url = "data:text/html;charset=utf-8,default"; - - tabs.open(url); - tabs.open(url); - tabs.open({ - url: url, - onOpen: function(tab) { - let count = 0; - for (let t of tabs) count++; - assert.equal(count, startCount + 3, "iterated tab count matches"); - assert.equal(startCount + 3, tabs.length, "iterated tab count matches length property"); - - close(window).then(done).then(null, assert.fail); - } - }); - }); -}; - -// TEST: tab.url setter -exports.testTabLocation = function(assert, done) { - open().then(focus).then(function(window) { - let url1 = "data:text/html;charset=utf-8,foo"; - let url2 = "data:text/html;charset=utf-8,bar"; - - tabs.on('ready', function onReady(tab) { - if (tab.url != url2) - return; - tabs.removeListener('ready', onReady); - assert.pass("tab.load() loaded the correct url"); - close(window).then(done).then(null, assert.fail); - }); - - tabs.open({ - url: url1, - onOpen: function(tab) { - tab.url = url2 - } - }); - }); -}; - -// TEST: tab.close() -exports.testTabClose = function(assert, done) { - let testName = "testTabClose"; - let url = "data:text/html;charset=utf-8," + testName; - - assert.notEqual(tabs.activeTab.url, url, "tab is not the active tab"); - tabs.once('ready', function onReady(tab) { - assert.equal(tabs.activeTab.url, tab.url, "tab is now the active tab"); - assert.equal(url, tab.url, "tab url is the test url"); - let secondOnCloseCalled = false; - - // Bug 699450: Multiple calls to tab.close should not throw - tab.close(() => secondOnCloseCalled = true); - try { - tab.close(function () { - assert.notEqual(tabs.activeTab.url, url, "tab is no longer the active tab"); - assert.ok(secondOnCloseCalled, - "The immediate second call to tab.close happened"); - assert.notEqual(tabs.activeTab.url, url, "tab is no longer the active tab"); - - done(); - }); - } - catch(e) { - assert.fail("second call to tab.close() thrown an exception: " + e); - } - }); - - tabs.open(url); -}; - -// TEST: tab.move() -exports.testTabMove = function(assert, done) { - open().then(focus).then(function(window) { - let url = "data:text/html;charset=utf-8,foo"; - - tabs.open({ - url: url, - onOpen: function(tab) { - assert.equal(tab.index, 1, "tab index before move matches"); - tab.index = 0; - assert.equal(tab.index, 0, "tab index after move matches"); - close(window).then(done).then(null, assert.fail); - } - }); - }).then(null, assert.fail); -}; - -exports.testIgnoreClosing = function*(assert) { - let url = "data:text/html;charset=utf-8,foobar"; - let originalWindow = getMostRecentBrowserWindow(); - - let window = yield open().then(focus); - - assert.equal(tabs.length, 2, "should be two windows open each with one tab"); - - yield new Promise(resolve => { - tabs.once("ready", (tab) => { - let win = tab.window; - assert.equal(win.tabs.length, 2, "should be two tabs in the new window"); - assert.equal(tabs.length, 3, "should be three tabs in total"); - - tab.close(() => { - assert.equal(win.tabs.length, 1, "should be one tab in the new window"); - assert.equal(tabs.length, 2, "should be two tabs in total"); - resolve(); - }); - }); - - tabs.open(url); - }); -}; - -// TEST: open tab with default options -exports.testOpen = function(assert, done) { - let url = "data:text/html;charset=utf-8,default"; - tabs.open({ - url: url, - onReady: function(tab) { - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(tab.isPinned, false, "The new tab is not pinned"); - - tab.close(done); - } - }); -}; - -// TEST: opening a pinned tab -exports.testOpenPinned = function(assert, done) { - let url = "data:text/html;charset=utf-8,default"; - tabs.open({ - url: url, - isPinned: true, - onOpen: function(tab) { - assert.equal(tab.isPinned, true, "The new tab is pinned"); - tab.close(done); - } - }); -}; - -// TEST: pin/unpin opened tab -exports.testPinUnpin = function(assert, done) { - let url = "data:text/html;charset=utf-8,default"; - tabs.open({ - url: url, - inBackground: true, - onOpen: function(tab) { - tab.pin(); - assert.equal(tab.isPinned, true, "The tab was pinned correctly"); - tab.unpin(); - assert.equal(tab.isPinned, false, "The tab was unpinned correctly"); - tab.close(done); - } - }); -} - -// TEST: open tab in background -exports.testInBackground = function(assert, done) { - assert.equal(tabs.length, 1, "Should be one tab"); - - let window = getMostRecentBrowserWindow(); - let activeUrl = tabs.activeTab.url; - let url = "data:text/html;charset=utf-8,background"; - assert.equal(getMostRecentBrowserWindow(), window, "getMostRecentBrowserWindow() matches this window"); - tabs.on('ready', function onReady(tab) { - tabs.removeListener('ready', onReady); - assert.equal(tabs.activeTab.url, activeUrl, "URL of active tab has not changed"); - assert.equal(tab.url, url, "URL of the new background tab matches"); - assert.equal(getMostRecentBrowserWindow(), window, "a new window was not opened"); - assert.notEqual(tabs.activeTab.url, url, "URL of active tab is not the new URL"); - tab.close(done); - }); - - tabs.open({ - url: url, - inBackground: true - }); -} - -// TEST: open tab in new window -exports.testOpenInNewWindow = function(assert, done) { - let startWindowCount = windows().length; - - let url = "data:text/html;charset=utf-8,testOpenInNewWindow"; - tabs.open({ - url: url, - inNewWindow: true, - onReady: function(tab) { - let newWindow = getOwnerWindow(viewFor(tab)); - assert.equal(windows().length, startWindowCount + 1, "a new window was opened"); - - onFocus(newWindow).then(function() { - assert.equal(getMostRecentBrowserWindow(), newWindow, "new window is active"); - assert.equal(tab.url, url, "URL of the new tab matches"); - assert.equal(newWindow.content.location, url, "URL of new tab in new window matches"); - assert.equal(tabs.activeTab.url, url, "URL of activeTab matches"); - - return close(newWindow).then(done); - }).then(null, assert.fail); - } - }); - -} - -// Test tab.open inNewWindow + onOpen combination -exports.testOpenInNewWindowOnOpen = function(assert, done) { - let startWindowCount = windows().length; - - let url = "data:text/html;charset=utf-8,newwindow"; - tabs.open({ - url: url, - inNewWindow: true, - onOpen: function(tab) { - let newWindow = getOwnerWindow(viewFor(tab)); - - onFocus(newWindow).then(function() { - assert.equal(windows().length, startWindowCount + 1, "a new window was opened"); - assert.equal(getMostRecentBrowserWindow(), newWindow, "new window is active"); - - close(newWindow).then(done).then(null, assert.fail); - }); - } - }); -}; - -// TEST: onOpen event handler -exports.testTabsEvent_onOpen = function(assert, done) { - open().then(focus).then(window => { - let url = "data:text/html;charset=utf-8,1"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - }; - tabs.on('open', listener1); - - // add listener via collection add - tabs.on('open', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener('open', listener1); - tabs.removeListener('open', listener2); - close(window).then(done).then(null, assert.fail); - }); - - tabs.open(url); - }).then(null, assert.fail); -}; - -// TEST: onClose event handler -exports.testTabsEvent_onClose = function*(assert) { - let window = yield open().then(focus); - let url = "data:text/html;charset=utf-8,onclose"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - } - tabs.on("close", listener1); - - yield new Promise(resolve => { - // add listener via collection add - tabs.on("close", function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener("close", listener2); - resolve(); - }); - - tabs.on('ready', function onReady(tab) { - tabs.removeListener('ready', onReady); - tab.close(); - }); - - tabs.open(url); - }); - - tabs.removeListener("close", listener1); - assert.pass("done test!"); - - yield close(window); - assert.pass("window was closed!"); -}; - -// TEST: onClose event handler when a window is closed -exports.testTabsEvent_onCloseWindow = function(assert, done) { - let closeCount = 0; - let individualCloseCount = 0; - - open().then(focus).then(window => { - assert.pass('opened a new window'); - - tabs.on("close", function listener() { - if (++closeCount == 4) { - tabs.removeListener("close", listener); - } - }); - - function endTest() { - if (++individualCloseCount < 3) { - assert.pass('tab closed ' + individualCloseCount); - return; - } - - assert.equal(closeCount, 4, "Correct number of close events received"); - assert.equal(individualCloseCount, 3, - "Each tab with an attached onClose listener received a close " + - "event when the window was closed"); - - done(); - } - - // One tab is already open with the window - let openTabs = 1; - function testCasePossiblyLoaded() { - if (++openTabs == 4) { - window.close(); - } - assert.pass('tab opened ' + openTabs); - } - - tabs.open({ - url: "data:text/html;charset=utf-8,tab2", - onOpen: testCasePossiblyLoaded, - onClose: endTest - }); - - tabs.open({ - url: "data:text/html;charset=utf-8,tab3", - onOpen: testCasePossiblyLoaded, - onClose: endTest - }); - - tabs.open({ - url: "data:text/html;charset=utf-8,tab4", - onOpen: testCasePossiblyLoaded, - onClose: endTest - }); - }).then(null, assert.fail); -} - -// TEST: onReady event handler -exports.testTabsEvent_onReady = function(assert, done) { - open().then(focus).then(window => { - let url = "data:text/html;charset=utf-8,onready"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - }; - tabs.on('ready', listener1); - - // add listener via collection add - tabs.on('ready', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener('ready', listener1); - tabs.removeListener('ready', listener2); - close(window).then(done); - }); - - tabs.open(url); - }).then(null, assert.fail); -}; - -// TEST: onActivate event handler -exports.testTabsEvent_onActivate = function(assert, done) { - open().then(focus).then(window => { - let url = "data:text/html;charset=utf-8,onactivate"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - }; - tabs.on('activate', listener1); - - // add listener via collection add - tabs.on('activate', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener('activate', listener1); - tabs.removeListener('activate', listener2); - close(window).then(done).then(null, assert.fail); - }); - - tabs.open(url); - }).then(null, assert.fail); -}; - -// onDeactivate event handler -exports.testTabsEvent_onDeactivate = function*(assert) { - let window = yield open().then(focus); - - let url = "data:text/html;charset=utf-8,ondeactivate"; - let eventCount = 0; - - // add listener via property assignment - function listener1(tab) { - eventCount++; - assert.pass("listener1 was called " + eventCount); - }; - tabs.on('deactivate', listener1); - - yield new Promise(resolve => { - // add listener via collection add - tabs.on('deactivate', function listener2(tab) { - assert.equal(++eventCount, 2, "both listeners notified"); - tabs.removeListener('deactivate', listener2); - resolve(); - }); - - tabs.on('open', function onOpen(tab) { - assert.pass("tab opened"); - tabs.removeListener('open', onOpen); - tabs.open("data:text/html;charset=utf-8,foo"); - }); - - tabs.open(url); - }); - - tabs.removeListener('deactivate', listener1); - assert.pass("listeners were removed"); -}; - -// pinning -exports.testTabsEvent_pinning = function(assert, done) { - open().then(focus).then(window => { - let url = "data:text/html;charset=utf-8,1"; - - tabs.on('open', function onOpen(tab) { - tabs.removeListener('open', onOpen); - tab.pin(); - }); - - tabs.on('pinned', function onPinned(tab) { - tabs.removeListener('pinned', onPinned); - assert.ok(tab.isPinned, "notified tab is pinned"); - tab.unpin(); - }); - - tabs.on('unpinned', function onUnpinned(tab) { - tabs.removeListener('unpinned', onUnpinned); - assert.ok(!tab.isPinned, "notified tab is not pinned"); - close(window).then(done).then(null, assert.fail); - }); - - tabs.open(url); - }).then(null, assert.fail); -}; - -// TEST: per-tab event handlers -exports.testPerTabEvents = function*(assert) { - let window = yield open().then(focus); - let eventCount = 0; - - let tab = yield new Promise(resolve => { - tabs.open({ - url: "data:text/html;charset=utf-8,foo", - onOpen: (tab) => { - assert.pass("the tab was opened"); - - // add listener via property assignment - function listener1() { - eventCount++; - }; - tab.on('ready', listener1); - - // add listener via collection add - tab.on('ready', function listener2() { - assert.equal(eventCount, 1, "listener1 called before listener2"); - tab.removeListener('ready', listener1); - tab.removeListener('ready', listener2); - assert.pass("removed listeners"); - eventCount++; - resolve(); - }); - } - }); - }); - - assert.equal(eventCount, 2, "both listeners were notified."); -}; - -exports.testAttachOnMultipleDocuments = function (assert, done) { - // Example of attach that process multiple tab documents - open().then(focus).then(window => { - let firstLocation = "data:text/html;charset=utf-8,foobar"; - let secondLocation = "data:text/html;charset=utf-8,bar"; - let thirdLocation = "data:text/html;charset=utf-8,fox"; - let onReadyCount = 0; - let worker1 = null; - let worker2 = null; - let detachEventCount = 0; - - tabs.open({ - url: firstLocation, - onReady: function (tab) { - onReadyCount++; - if (onReadyCount == 1) { - worker1 = tab.attach({ - contentScript: 'self.on("message", ' + - ' function () { return self.postMessage(document.location.href); }' + - ');', - onMessage: function (msg) { - assert.equal(msg, firstLocation, - "Worker url is equal to the 1st document"); - tab.url = secondLocation; - }, - onDetach: function () { - detachEventCount++; - assert.pass("Got worker1 detach event"); - assert.throws(function () { - worker1.postMessage("ex-1"); - }, - /Couldn't find the worker/, - "postMessage throw because worker1 is destroyed"); - checkEnd(); - } - }); - worker1.postMessage("new-doc-1"); - } - else if (onReadyCount == 2) { - - worker2 = tab.attach({ - contentScript: 'self.on("message", ' + - ' function () { return self.postMessage(document.location.href); }' + - ');', - onMessage: function (msg) { - assert.equal(msg, secondLocation, - "Worker url is equal to the 2nd document"); - tab.url = thirdLocation; - }, - onDetach: function () { - detachEventCount++; - assert.pass("Got worker2 detach event"); - assert.throws(function () { - worker2.postMessage("ex-2"); - }, - /Couldn't find the worker/, - "postMessage throw because worker2 is destroyed"); - checkEnd(); - } - }); - worker2.postMessage("new-doc-2"); - } - else if (onReadyCount == 3) { - tab.close(); - } - } - }); - - function checkEnd() { - if (detachEventCount != 2) - return; - - assert.pass("Got all detach events"); - - close(window).then(done).then(null, assert.fail); - } - }).then(null, assert.fail); -} - - -exports.testAttachWrappers = function (assert, done) { - // Check that content script has access to wrapped values by default - open().then(focus).then(window => { - let document = "data:text/html;charset=utf-8,"; - let count = 0; - - tabs.open({ - url: document, - onReady: function (tab) { - let worker = tab.attach({ - contentScript: 'try {' + - ' self.postMessage(!("globalJSVar" in window));' + - ' self.postMessage(typeof window.globalJSVar == "undefined");' + - '} catch(e) {' + - ' self.postMessage(e.message);' + - '}', - onMessage: function (msg) { - assert.equal(msg, true, "Worker has wrapped objects ("+count+")"); - if (count++ == 1) - close(window).then(done).then(null, assert.fail); - } - }); - } - }); - }).then(null, assert.fail); -} - -/* -// We do not offer unwrapped access to DOM since bug 601295 landed -// See 660780 to track progress of unwrap feature -exports.testAttachUnwrapped = function (assert, done) { - // Check that content script has access to unwrapped values through unsafeWindow - openBrowserWindow(function(window, browser) { - let document = "data:text/html;charset=utf-8,"; - let count = 0; - - tabs.open({ - url: document, - onReady: function (tab) { - let worker = tab.attach({ - contentScript: 'try {' + - ' self.postMessage(unsafeWindow.globalJSVar);' + - '} catch(e) {' + - ' self.postMessage(e.message);' + - '}', - onMessage: function (msg) { - assert.equal(msg, true, "Worker has access to javascript content globals ("+count+")"); - close(window).then(done); - } - }); - } - }); - - }); -} -*/ - -exports['test window focus changes active tab'] = function(assert, done) { - let url1 = "data:text/html;charset=utf-8," + encodeURIComponent("test window focus changes active tab

Window #1"); - - let win1 = openBrowserWindow(function() { - assert.pass("window 1 is open"); - - let win2 = openBrowserWindow(function() { - assert.pass("window 2 is open"); - - focus(win2).then(function() { - tabs.on("activate", function onActivate(tab) { - tabs.removeListener("activate", onActivate); - - if (tab.readyState === 'uninitialized') { - tab.once('ready', whenReady); - } - else { - whenReady(tab); - } - - function whenReady(tab) { - assert.pass("activate was called on windows focus change."); - assert.equal(tab.url, url1, 'the activated tab url is correct'); - - return close(win2).then(function() { - assert.pass('window 2 was closed'); - return close(win1); - }).then(done).then(null, assert.fail); - } - }); - - win1.focus(); - }); - }, "data:text/html;charset=utf-8,test window focus changes active tab

Window #2"); - }, url1); -}; - -exports['test ready event on new window tab'] = function(assert, done) { - let uri = encodeURI("data:text/html;charset=utf-8,Waiting for ready event!"); - - require("sdk/tabs").on("ready", function onReady(tab) { - if (tab.url === uri) { - require("sdk/tabs").removeListener("ready", onReady); - assert.pass("ready event was emitted"); - close(window).then(done).then(null, assert.fail); - } - }); - - let window = openBrowserWindow(function(){}, uri); -}; - -exports['test unique tab ids'] = function(assert, done) { - var windows = require('sdk/windows').browserWindows; - var { all, defer } = require('sdk/core/promise'); - - function openWindow() { - let deferred = defer(); - let win = windows.open({ - url: "data:text/html;charset=utf-8,foo", - }); - - win.on('open', function(window) { - assert.ok(window.tabs.length); - assert.ok(window.tabs.activeTab); - assert.ok(window.tabs.activeTab.id); - deferred.resolve({ - id: window.tabs.activeTab.id, - win: win - }); - }); - - return deferred.promise; - } - - var one = openWindow(), two = openWindow(); - all([one, two]).then(function(results) { - assert.notEqual(results[0].id, results[1].id, "tab Ids should not be equal."); - results[0].win.close(function() { - results[1].win.close(function () { - done(); - }); - }); - }); -} - -// related to Bug 671305 -exports.testOnLoadEventWithDOM = function(assert, done) { - let count = 0; - let title = 'testOnLoadEventWithDOM'; - - // open a about: url - tabs.open({ - url: 'data:text/html;charset=utf-8,' + title + '', - inBackground: true, - onLoad: function(tab) { - assert.equal(tab.title, title, 'tab passed in as arg, load called'); - - if (++count > 1) { - assert.pass('onLoad event called on reload'); - tab.close(done); - } - else { - assert.pass('first onLoad event occured'); - tab.reload(); - } - } - }); -}; - -// related to Bug 671305 -exports.testOnLoadEventWithImage = function(assert, done) { - let count = 0; - - tabs.open({ - url: base64jpeg, - inBackground: true, - onLoad: function(tab) { - if (++count > 1) { - assert.pass('onLoad event called on reload with image'); - tab.close(done); - } - else { - assert.pass('first onLoad event occured'); - tab.reload(); - } - } - }); -}; - -exports.testNoDeadObjects = function(assert, done) { - let loader = Loader(module); - let myTabs = loader.require("sdk/tabs"); - - // Load a tab, unload our modules, and navigate the tab to trigger an event - // on it. This would throw a dead object exception if our modules didn't - // clean up their event handlers on unload. - tabs.open({ - url: "data:text/html;charset=utf-8,one", - onLoad: function(tab) { - // 2. Arrange to nuke the sandboxes and then trigger the load event - // on the tab once the loader is kaput. - systemEvents.on("sdk:loader:destroy", function onUnload() { - systemEvents.off("sdk:loader:destroy", onUnload, true); - // Defer this carnage till the end of the event queue, to avoid nuking - // the sandboxes from under the modules as they're being cleaned up. - setTimeout(function() { - // 3. Arrange to close the tab once the second page loads. - tab.on("load", function() { - tab.close(function() { - let { viewFor } = loader.require("sdk/view/core"); - assert.equal(viewFor(tab), undefined, "didn't retain the closed tab"); - done(); - }); - }); - - // Trigger a load event on the tab, to give the now-unloaded - // myTabs a chance to choke on it. - tab.url = "data:text/html;charset=utf-8,two"; - }, 0); - }, true); - - // 1. Start unloading the modules. Defer till the end of the event - // queue, in case myTabs is attaching its own handlers here too. - // We want it to latch on before we pull the rug from under it. - setTimeout(function() { - loader.unload(); - }, 0); - } - }); -}; - -exports.testTabDestroy = function(assert, done) { - let loader = Loader(module); - let myTabs = loader.require("sdk/tabs"); - let { modelFor: myModelFor } = loader.require("sdk/model/core"); - let { viewFor: myViewFor } = loader.require("sdk/view/core"); - let myFirstTab = myTabs.activeTab; - - myTabs.open({ - url: "data:text/html;charset=utf-8,destroy", - onReady: (myTab) => setImmediate(() => { - let tab = modelFor(myViewFor(myTab)); - - function badListener(event, tab) { - // Ignore events for the other tabs - if (tab != myTab) - return; - assert.fail("Should not have seen the " + event + " listener called"); - } - - assert.ok(myTab, "Should have a tab in the test loader."); - assert.equal(myViewFor(myTab), viewFor(tab), "Should have the right view."); - assert.equal(myTabs.length, 2, "Should have the right number of global tabs."); - assert.equal(myTab.window.tabs.length, 2, "Should have the right number of window tabs."); - assert.equal(myTabs.activeTab, myTab, "Globally active tab is correct."); - assert.equal(myTab.window.tabs.activeTab, myTab, "Window active tab is correct."); - - assert.equal(myTabs[1], myTab, "Global tabs list contains tab."); - assert.equal(myTab.window.tabs[1], myTab, "Window tabs list contains tab."); - - myTab.once("ready", badListener.bind(null, "tab ready")); - myTab.once("deactivate", badListener.bind(null, "tab deactivate")); - myTab.once("activate", badListener.bind(null, "tab activate")); - myTab.once("close", badListener.bind(null, "tab close")); - - myTab.destroy(); - - myTab.once("ready", badListener.bind(null, "new tab ready")); - myTab.once("deactivate", badListener.bind(null, "new tab deactivate")); - myTab.once("activate", badListener.bind(null, "new tab activate")); - myTab.once("close", badListener.bind(null, "new tab close")); - - myTabs.once("ready", badListener.bind(null, "tabs ready")); - myTabs.once("deactivate", badListener.bind(null, "tabs deactivate")); - myTabs.once("activate", badListener.bind(null, "tabs activate")); - myTabs.once("close", badListener.bind(null, "tabs close")); - - assert.equal(myViewFor(myTab), viewFor(tab), "Should have the right view."); - assert.equal(myModelFor(viewFor(tab)), myTab, "Can still reach the tab object."); - assert.equal(myTabs.length, 2, "Should have the right number of global tabs."); - assert.equal(myTab.window.tabs.length, 2, "Should have the right number of window tabs."); - assert.equal(myTabs.activeTab, myTab, "Globally active tab is correct."); - assert.equal(myTab.window.tabs.activeTab, myTab, "Window active tab is correct."); - - assert.equal(myTabs[1], myTab, "Global tabs list still contains tab."); - assert.equal(myTab.window.tabs[1], myTab, "Window tabs list still contains tab."); - - assert.equal(myTab.url, undefined, "url property is not usable"); - assert.equal(myTab.contentType, undefined, "contentType property is not usable"); - assert.equal(myTab.title, undefined, "title property is not usable"); - assert.equal(myTab.id, undefined, "id property is not usable"); - assert.equal(myTab.index, undefined, "index property is not usable"); - - myTab.pin(); - assert.ok(!tab.isPinned, "pin method shouldn't work"); - - tabs.once("activate", () => setImmediate(() => { - assert.equal(myTabs.activeTab, myFirstTab, "Globally active tab is correct."); - assert.equal(myTab.window.tabs.activeTab, myFirstTab, "Window active tab is correct."); - - let sawActivate = false; - tabs.once("activate", () => setImmediate(() => { - sawActivate = true; - - assert.equal(myTabs.activeTab, myTab, "Globally active tab is correct."); - assert.equal(myTab.window.tabs.activeTab, myTab, "Window active tab is correct."); - - // This shouldn't have any effect - myTab.close(); - - tab.once("ready", () => setImmediate(() => { - tab.close(() => { - loader.unload(); - done(); - }); - })); - tab.url = "data:text/html;charset=utf-8,destroy2"; - })); - - myTab.activate(); - setImmediate(() => { - assert.ok(!sawActivate, "activate method shouldn't have done anything"); - - tab.activate(); - }); - })); - myFirstTab.activate(); - }) - }) -}; - -// related to bug 942511 -// https://bugzilla.mozilla.org/show_bug.cgi?id=942511 -exports['test active tab properties defined on popup closed'] = function (assert, done) { - setPref(OPEN_IN_NEW_WINDOW_PREF, 2); - setPref(DISABLE_POPUP_PREF, false); - - let tabID = ""; - let popupClosed = false; - - tabs.open({ - url: 'about:blank', - onReady: function (tab) { - tabID = tab.id; - tab.attach({ - contentScript: 'var popup = window.open("about:blank");' + - 'popup.close();' - }); - - windowObserver.once('close', () => { - popupClosed = true; - }); - - windowObserver.on('activate', () => { - // Only when the 'activate' event is fired after the popup was closed. - if (popupClosed) { - popupClosed = false; - let activeTabID = tabs.activeTab.id; - if (activeTabID) { - assert.equal(tabID, activeTabID, 'ActiveTab properties are correct'); - } - else { - assert.fail('ActiveTab properties undefined on popup closed'); - } - tab.close(done); - } - }); - } - }); -}; - -// related to bugs 922956 and 989288 -// https://bugzilla.mozilla.org/show_bug.cgi?id=922956 -// https://bugzilla.mozilla.org/show_bug.cgi?id=989288 -exports["test tabs ready and close after window.open"] = function*(assert, done) { - // ensure popups open in a new window and disable popup blocker - setPref(OPEN_IN_NEW_WINDOW_PREF, 2); - setPref(DISABLE_POPUP_PREF, false); - - // open windows to trigger observers - tabs.activeTab.attach({ - contentScript: "window.open('about:blank');" + - "window.open('about:blank', '', " + - "'width=800,height=600,resizable=no,status=no,location=no');" - }); - - let tab1 = yield wait(tabs, "ready"); - assert.pass("first tab ready has occured"); - - let tab2 = yield wait(tabs, "ready"); - assert.pass("second tab ready has occured"); - - tab1.close(); - yield wait(tabs, "close"); - assert.pass("first tab close has occured"); - - tab2.close(); - yield wait(tabs, "close"); - assert.pass("second tab close has occured"); -}; - -// related to bug #939496 -exports["test tab open event for new window"] = function(assert, done) { - // ensure popups open in a new window and disable popup blocker - setPref(OPEN_IN_NEW_WINDOW_PREF, 2); - setPref(DISABLE_POPUP_PREF, false); - - tabs.once('open', function onOpen(window) { - assert.pass("tab open has occured"); - window.close(done); - }); - - // open window to trigger observers - browserWindows.open("about:logo"); -}; - -after(exports, function*(name, assert) { - resetPopupPrefs(); - yield cleanUI(); -}); - -const resetPopupPrefs = () => { - resetPref(OPEN_IN_NEW_WINDOW_PREF); - resetPref(DISABLE_POPUP_PREF); -}; - -/******************* helpers *********************/ - -// Utility function to open a new browser window. -function openBrowserWindow(callback, url) { - let ww = Cc["@mozilla.org/embedcomp/window-watcher;1"]. - getService(Ci.nsIWindowWatcher); - let urlString = Cc["@mozilla.org/supports-string;1"]. - createInstance(Ci.nsISupportsString); - urlString.data = url; - let window = ww.openWindow(null, "chrome://browser/content/browser.xul", - "_blank", "chrome,all,dialog=no", urlString); - - if (callback) { - window.addEventListener("load", function onLoad(event) { - if (event.target && event.target.defaultView == window) { - window.removeEventListener("load", onLoad, true); - let browsers = window.document.getElementsByTagName("tabbrowser"); - try { - setTimeout(function () { - callback(window, browsers[0]); - }, 10); - } - catch (e) { - console.exception(e); - } - } - }, true); - } - - return window; -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/tabs/utils.js b/addon-sdk/source/test/tabs/utils.js deleted file mode 100644 index 4981a4d08..000000000 --- a/addon-sdk/source/test/tabs/utils.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 { openTab: makeTab, getTabContentWindow } = require("sdk/tabs/utils"); - -function openTab(rawWindow, url) { - return new Promise(resolve => { - let tab = makeTab(rawWindow, url); - let window = getTabContentWindow(tab); - if (window.document.readyState == "complete") { - return resolve(); - } - - window.addEventListener("load", function onLoad() { - window.removeEventListener("load", onLoad, true); - resolve(); - }, true); - - return null; - }) -} -exports.openTab = openTab; diff --git a/addon-sdk/source/test/test-addon-bootstrap.js b/addon-sdk/source/test/test-addon-bootstrap.js deleted file mode 100644 index 01e2d15fc..000000000 --- a/addon-sdk/source/test/test-addon-bootstrap.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"; - -const { Cu, Cc, Ci } = require("chrome"); -const { create, evaluate } = require("./fixtures/bootstrap/utils"); - -const ROOT = require.resolve("sdk/base64").replace("/sdk/base64.js", ""); - -// Note: much of this test code is from -// http://dxr.mozilla.org/mozilla-central/source/toolkit/mozapps/extensions/internal/XPIProvider.jsm -const BOOTSTRAP_REASONS = { - APP_STARTUP : 1, - APP_SHUTDOWN : 2, - ADDON_ENABLE : 3, - ADDON_DISABLE : 4, - ADDON_INSTALL : 5, - ADDON_UNINSTALL : 6, - ADDON_UPGRADE : 7, - ADDON_DOWNGRADE : 8 -}; - -exports["test install/startup/shutdown/uninstall all return a promise"] = function(assert) { - let uri = require.resolve("./fixtures/addon/bootstrap.js"); - let id = "test-min-boot@jetpack"; - let bootstrapScope = create({ - id: id, - uri: uri - }); - - // As we don't want our caller to control the JS version used for the - // bootstrap file, we run loadSubScript within the context of the - // sandbox with the latest JS version set explicitly. - bootstrapScope.ROOT = ROOT; - - evaluate({ - uri: uri, - scope: bootstrapScope - }); - - let addon = { - id: id, - version: "0.0.1", - resourceURI: { - spec: uri.replace("bootstrap.js", "") - } - }; - - let install = bootstrapScope.install(addon, BOOTSTRAP_REASONS.ADDON_INSTALL); - yield install.then(() => assert.pass("install returns a promise")); - - let startup = bootstrapScope.startup(addon, BOOTSTRAP_REASONS.ADDON_INSTALL); - yield startup.then(() => assert.pass("startup returns a promise")); - - let shutdown = bootstrapScope.shutdown(addon, BOOTSTRAP_REASONS.ADDON_DISABLE); - yield shutdown.then(() => assert.pass("shutdown returns a promise")); - - // calling shutdown multiple times is fine - shutdown = bootstrapScope.shutdown(addon, BOOTSTRAP_REASONS.ADDON_DISABLE); - yield shutdown.then(() => assert.pass("shutdown returns working promise on multiple calls")); - - let uninstall = bootstrapScope.uninstall(addon, BOOTSTRAP_REASONS.ADDON_UNINSTALL); - yield uninstall.then(() => assert.pass("uninstall returns a promise")); -} - -exports["test minimal bootstrap.js"] = function*(assert) { - let uri = require.resolve("./fixtures/addon/bootstrap.js"); - let bootstrapScope = create({ - id: "test-min-boot@jetpack", - uri: uri - }); - - // As we don't want our caller to control the JS version used for the - // bootstrap file, we run loadSubScript within the context of the - // sandbox with the latest JS version set explicitly. - bootstrapScope.ROOT = ROOT; - - assert.equal(typeof bootstrapScope.install, "undefined", "install DNE"); - assert.equal(typeof bootstrapScope.startup, "undefined", "startup DNE"); - assert.equal(typeof bootstrapScope.shutdown, "undefined", "shutdown DNE"); - assert.equal(typeof bootstrapScope.uninstall, "undefined", "uninstall DNE"); - - evaluate({ - uri: uri, - scope: bootstrapScope - }); - - assert.equal(typeof bootstrapScope.install, "function", "install exists"); - assert.equal(typeof bootstrapScope.startup, "function", "startup exists"); - assert.equal(typeof bootstrapScope.shutdown, "function", "shutdown exists"); - assert.equal(typeof bootstrapScope.uninstall, "function", "uninstall exists"); - - bootstrapScope.shutdown(null, BOOTSTRAP_REASONS.ADDON_DISABLE); -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-addon-extras.js b/addon-sdk/source/test/test-addon-extras.js deleted file mode 100644 index 1910db05e..000000000 --- a/addon-sdk/source/test/test-addon-extras.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 { Ci, Cu, Cc, components } = require("chrome"); -const self = require("sdk/self"); -const { before, after } = require("sdk/test/utils"); -const fixtures = require("./fixtures"); -const { Loader } = require("sdk/test/loader"); -const { merge } = require("sdk/util/object"); - -exports["test changing result from addon extras in panel"] = function(assert, done) { - let loader = Loader(module, null, null, { - modules: { - "sdk/self": merge({}, self, { - data: merge({}, self.data, {url: fixtures.url}) - }) - } - }); - - const { Panel } = loader.require("sdk/panel"); - const { events } = loader.require("sdk/content/sandbox/events"); - const { on } = loader.require("sdk/event/core"); - const { isAddonContent } = loader.require("sdk/content/utils"); - - var result = 1; - var extrasVal = { - test: function() { - return result; - } - }; - - on(events, "content-script-before-inserted", ({ window, worker }) => { - assert.pass("content-script-before-inserted"); - - if (isAddonContent({ contentURL: window.location.href })) { - let extraStuff = Cu.cloneInto(extrasVal, window, { - cloneFunctions: true - }); - getUnsafeWindow(window).extras = extraStuff; - - assert.pass("content-script-before-inserted done!"); - } - }); - - let panel = Panel({ - contentURL: "./test-addon-extras.html" - }); - - panel.port.once("result1", (result) => { - assert.equal(result, 1, "result is a number"); - result = true; - panel.port.emit("get-result"); - }); - - panel.port.once("result2", (result) => { - assert.equal(result, true, "result is a boolean"); - loader.unload(); - done(); - }); - - panel.port.emit("get-result"); -} - -function getUnsafeWindow (win) { - return win.wrappedJSObject || win; -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-addon-installer.js b/addon-sdk/source/test/test-addon-installer.js deleted file mode 100644 index bb39cca2d..000000000 --- a/addon-sdk/source/test/test-addon-installer.js +++ /dev/null @@ -1,230 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cc, Ci, Cu } = require("chrome"); -const { pathFor } = require("sdk/system"); -const AddonInstaller = require("sdk/addon/installer"); -const { on, off } = require("sdk/system/events"); -const { setTimeout } = require("sdk/timers"); -const fs = require("sdk/io/fs"); -const path = require("sdk/fs/path"); -const { OS } = require("resource://gre/modules/osfile.jsm"); -const { toFilename } = require("sdk/url"); - -// Retrieve the path to the OS temporary directory: -const tmpDir = pathFor("TmpD"); - -const profilePath = pathFor("ProfD"); -const corruptXPIPath = path.join(profilePath, "sdk-corrupt.xpi"); -const testFolderURL = module.uri.split('test-addon-installer.js')[0]; -const ADDON_URL = toFilename(testFolderURL + "fixtures/addon-install-unit-test@mozilla.com.xpi"); - -exports["test Install"] = function*(assert) { - var ADDON_PATH = OS.Path.join(OS.Constants.Path.tmpDir, "install-test.xpi"); - - assert.pass("Copying test add-on " + ADDON_URL + " to " + ADDON_PATH); - - yield OS.File.copy(ADDON_URL, ADDON_PATH); - - assert.pass("Copied test add-on to " + ADDON_PATH); - - // Save all events distpatched by bootstrap.js of the installed addon - let events = []; - function eventsObserver({ data }) { - events.push(data); - } - on("addon-install-unit-test", eventsObserver); - - // Install the test addon - yield AddonInstaller.install(ADDON_PATH).then((id) => { - assert.equal(id, "addon-install-unit-test@mozilla.com", "`id` is valid"); - - // Now uninstall it - return AddonInstaller.uninstall(id).then(function () { - // Ensure that bootstrap.js methods of the addon have been called - // successfully and in the right order - let expectedEvents = ["install", "startup", "shutdown", "uninstall"]; - assert.equal(JSON.stringify(events), - JSON.stringify(expectedEvents), - "addon's bootstrap.js functions have been called"); - - off("addon-install-unit-test", eventsObserver); - }); - }, (code) => { - assert.fail("Install failed: "+code); - off("addon-install-unit-test", eventsObserver); - }); - - assert.pass("Add-on was uninstalled."); - - yield OS.File.remove(ADDON_PATH); - - assert.pass("Removed the temp file"); -}; - -exports["test Failing Install With Invalid Path"] = function (assert, done) { - AddonInstaller.install("invalid-path").then( - function onInstalled(id) { - assert.fail("Unexpected success"); - done(); - }, - function onFailure(code) { - assert.equal(code, AddonInstaller.ERROR_FILE_ACCESS, - "Got expected error code"); - done(); - } - ); -}; - -exports["test Failing Install With Invalid File"] = function (assert, done) { - const content = "bad xpi"; - const path = corruptXPIPath; - - fs.writeFile(path, content, (error) => { - assert.equal(fs.readFileSync(path).toString(), - content, - "contet was written"); - - AddonInstaller.install(path).then( - () => { - assert.fail("Unexpected success"); - fs.unlink(path, done); - }, - (code) => { - assert.equal(code, AddonInstaller.ERROR_CORRUPT_FILE, - "Got expected error code"); - fs.unlink(path, done); - } - ); - }); -} - -exports["test Update"] = function*(assert) { - var ADDON_PATH = OS.Path.join(OS.Constants.Path.tmpDir, "update-test.xpi"); - - assert.pass("Copying test add-on " + ADDON_URL + " to " + ADDON_PATH); - - yield OS.File.copy(ADDON_URL, ADDON_PATH); - - assert.pass("Copied test add-on to " + ADDON_PATH); - - // Save all events distpatched by bootstrap.js of the installed addon - let events = []; - let iteration = 1; - let eventsObserver = ({data}) => events.push(data); - on("addon-install-unit-test", eventsObserver); - - yield new Promise(resolve => { - function onInstalled(id) { - let prefix = "[" + iteration + "] "; - assert.equal(id, "addon-install-unit-test@mozilla.com", - prefix + "`id` is valid"); - - // On 2nd and 3rd iteration, we receive uninstall events from the last - // previously installed addon - let expectedEvents = - iteration == 1 - ? ["install", "startup"] - : ["shutdown", "uninstall", "install", "startup"]; - assert.equal(JSON.stringify(events), - JSON.stringify(expectedEvents), - prefix + "addon's bootstrap.js functions have been called"); - - if (iteration++ < 3) { - next(); - } - else { - events = []; - AddonInstaller.uninstall(id).then(function() { - let expectedEvents = ["shutdown", "uninstall"]; - assert.equal(JSON.stringify(events), - JSON.stringify(expectedEvents), - prefix + "addon's bootstrap.js functions have been called"); - - off("addon-install-unit-test", eventsObserver); - resolve(); - }); - } - } - function onFailure(code) { - assert.fail("Install failed: "+code); - off("addon-install-unit-test", eventsObserver); - resolve(); - } - - function next() { - events = []; - AddonInstaller.install(ADDON_PATH).then(onInstalled, onFailure); - } - - next(); - }); - - assert.pass("Add-on was uninstalled."); - - yield OS.File.remove(ADDON_PATH); - - assert.pass("Removed the temp file"); -}; - -exports['test Uninstall failure'] = function (assert, done) { - AddonInstaller.uninstall('invalid-addon-path').then( - () => assert.fail('Addon uninstall should not resolve successfully'), - () => assert.pass('Addon correctly rejected invalid uninstall') - ).then(done, assert.fail); -}; - -exports['test Addon Disable and Enable'] = function*(assert) { - var ADDON_PATH = OS.Path.join(OS.Constants.Path.tmpDir, "disable-enable-test.xpi"); - - assert.pass("Copying test add-on " + ADDON_URL + " to " + ADDON_PATH); - - yield OS.File.copy(ADDON_URL, ADDON_PATH); - - assert.pass("Copied test add-on to " + ADDON_PATH); - - let ensureActive = (addonId) => AddonInstaller.isActive(addonId).then(state => { - assert.equal(state, true, 'Addon should be enabled by default'); - return addonId; - }); - let ensureInactive = (addonId) => AddonInstaller.isActive(addonId).then(state => { - assert.equal(state, false, 'Addon should be disabled after disabling'); - return addonId; - }); - - yield AddonInstaller.install(ADDON_PATH) - .then(ensureActive) - .then(AddonInstaller.enable) // should do nothing, yet not fail - .then(ensureActive) - .then(AddonInstaller.disable) - .then(ensureInactive) - .then(AddonInstaller.disable) // should do nothing, yet not fail - .then(ensureInactive) - .then(AddonInstaller.enable) - .then(ensureActive) - .then(AddonInstaller.uninstall); - - assert.pass("Add-on was uninstalled."); - - yield OS.File.remove(ADDON_PATH); - - assert.pass("Removed the temp file"); -}; - -exports['test Disable failure'] = function (assert, done) { - AddonInstaller.disable('not-an-id').then( - () => assert.fail('Addon disable should not resolve successfully'), - () => assert.pass('Addon correctly rejected invalid disable') - ).then(done, assert.fail); -}; - -exports['test Enable failure'] = function (assert, done) { - AddonInstaller.enable('not-an-id').then( - () => assert.fail('Addon enable should not resolve successfully'), - () => assert.pass('Addon correctly rejected invalid enable') - ).then(done, assert.fail); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-addon-window.js b/addon-sdk/source/test/test-addon-window.js deleted file mode 100644 index 8cb07bb07..000000000 --- a/addon-sdk/source/test/test-addon-window.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'; - -var { Loader } = require('sdk/test/loader'); - -exports.testReady = function(assert, done) { - let loader = Loader(module); - let { ready, window } = loader.require('sdk/addon/window'); - let windowIsReady = false; - - ready.then(function() { - assert.equal(windowIsReady, false, 'ready promise was resolved only once'); - windowIsReady = true; - - loader.unload(); - done(); - }).then(null, assert.fail); -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-api-utils.js b/addon-sdk/source/test/test-api-utils.js deleted file mode 100644 index 12f2bf44f..000000000 --- a/addon-sdk/source/test/test-api-utils.js +++ /dev/null @@ -1,316 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 apiUtils = require("sdk/deprecated/api-utils"); - -exports.testValidateOptionsEmpty = function (assert) { - let val = apiUtils.validateOptions(null, {}); - - assert.deepEqual(val, {}); - - val = apiUtils.validateOptions(null, { foo: {} }); - assert.deepEqual(val, {}); - - val = apiUtils.validateOptions({}, {}); - assert.deepEqual(val, {}); - - val = apiUtils.validateOptions({}, { foo: {} }); - assert.deepEqual(val, {}); -}; - -exports.testValidateOptionsNonempty = function (assert) { - let val = apiUtils.validateOptions({ foo: 123 }, {}); - assert.deepEqual(val, {}); - - val = apiUtils.validateOptions({ foo: 123, bar: 456 }, - { foo: {}, bar: {}, baz: {} }); - - assert.deepEqual(val, { foo: 123, bar: 456 }); -}; - -exports.testValidateOptionsMap = function (assert) { - let val = apiUtils.validateOptions({ foo: 3, bar: 2 }, { - foo: { map: v => v * v }, - bar: { map: v => undefined } - }); - assert.deepEqual(val, { foo: 9, bar: undefined }); -}; - -exports.testValidateOptionsMapException = function (assert) { - let val = apiUtils.validateOptions({ foo: 3 }, { - foo: { map: function () { throw new Error(); }} - }); - assert.deepEqual(val, { foo: 3 }); -}; - -exports.testValidateOptionsOk = function (assert) { - let val = apiUtils.validateOptions({ foo: 3, bar: 2, baz: 1 }, { - foo: { ok: v => v }, - bar: { ok: v => v } - }); - assert.deepEqual(val, { foo: 3, bar: 2 }); - - assert.throws( - () => apiUtils.validateOptions({ foo: 2, bar: 2 }, { - bar: { ok: v => v > 2 } - }), - /^The option "bar" is invalid/, - "ok should raise exception on invalid option" - ); - - assert.throws( - () => apiUtils.validateOptions(null, { foo: { ok: v => v }}), - /^The option "foo" is invalid/, - "ok should raise exception on invalid option" - ); -}; - -exports.testValidateOptionsIs = function (assert) { - let opts = { - array: [], - boolean: true, - func: function () {}, - nul: null, - number: 1337, - object: {}, - string: "foo", - undef1: undefined - }; - let requirements = { - array: { is: ["array"] }, - boolean: { is: ["boolean"] }, - func: { is: ["function"] }, - nul: { is: ["null"] }, - number: { is: ["number"] }, - object: { is: ["object"] }, - string: { is: ["string"] }, - undef1: { is: ["undefined"] }, - undef2: { is: ["undefined"] } - }; - let val = apiUtils.validateOptions(opts, requirements); - assert.deepEqual(val, opts); - - assert.throws( - () => apiUtils.validateOptions(null, { - foo: { is: ["object", "number"] } - }), - /^The option "foo" must be one of the following types: object, number/, - "Invalid type should raise exception" - ); -}; - -exports.testValidateOptionsIsWithExportedValue = function (assert) { - let { string, number, boolean, object } = apiUtils; - - let opts = { - boolean: true, - number: 1337, - object: {}, - string: "foo" - }; - let requirements = { - string: { is: string }, - number: { is: number }, - boolean: { is: boolean }, - object: { is: object } - }; - let val = apiUtils.validateOptions(opts, requirements); - assert.deepEqual(val, opts); - - // Test the types are optional by default - val = apiUtils.validateOptions({foo: 'bar'}, requirements); - assert.deepEqual(val, {}); -}; - -exports.testValidateOptionsIsWithEither = function (assert) { - let { string, number, boolean, either } = apiUtils; - let text = { is: either(string, number) }; - - let requirements = { - text: text, - boolOrText: { is: either(text, boolean) } - }; - - let val = apiUtils.validateOptions({text: 12}, requirements); - assert.deepEqual(val, {text: 12}); - - val = apiUtils.validateOptions({text: "12"}, requirements); - assert.deepEqual(val, {text: "12"}); - - val = apiUtils.validateOptions({boolOrText: true}, requirements); - assert.deepEqual(val, {boolOrText: true}); - - val = apiUtils.validateOptions({boolOrText: "true"}, requirements); - assert.deepEqual(val, {boolOrText: "true"}); - - val = apiUtils.validateOptions({boolOrText: 1}, requirements); - assert.deepEqual(val, {boolOrText: 1}); - - assert.throws( - () => apiUtils.validateOptions({text: true}, requirements), - /^The option "text" must be one of the following types/, - "Invalid type should raise exception" - ); - - assert.throws( - () => apiUtils.validateOptions({boolOrText: []}, requirements), - /^The option "boolOrText" must be one of the following types/, - "Invalid type should raise exception" - ); -}; - -exports.testValidateOptionsWithRequiredAndOptional = function (assert) { - let { string, number, required, optional } = apiUtils; - - let opts = { - number: 1337, - string: "foo" - }; - - let requirements = { - string: required(string), - number: number - }; - - let val = apiUtils.validateOptions(opts, requirements); - assert.deepEqual(val, opts); - - val = apiUtils.validateOptions({string: "foo"}, requirements); - assert.deepEqual(val, {string: "foo"}); - - assert.throws( - () => apiUtils.validateOptions({number: 10}, requirements), - /^The option "string" must be one of the following types/, - "Invalid type should raise exception" - ); - - // Makes string optional - requirements.string = optional(requirements.string); - - val = apiUtils.validateOptions({number: 10}, requirements), - assert.deepEqual(val, {number: 10}); - -}; - - - -exports.testValidateOptionsWithExportedValue = function (assert) { - let { string, number, boolean, object } = apiUtils; - - let opts = { - boolean: true, - number: 1337, - object: {}, - string: "foo" - }; - let requirements = { - string: string, - number: number, - boolean: boolean, - object: object - }; - let val = apiUtils.validateOptions(opts, requirements); - assert.deepEqual(val, opts); - - // Test the types are optional by default - val = apiUtils.validateOptions({foo: 'bar'}, requirements); - assert.deepEqual(val, {}); -}; - - -exports.testValidateOptionsMapIsOk = function (assert) { - let [map, is, ok] = [false, false, false]; - let val = apiUtils.validateOptions({ foo: 1337 }, { - foo: { - map: v => v.toString(), - is: ["string"], - ok: v => v.length > 0 - } - }); - assert.deepEqual(val, { foo: "1337" }); - - let requirements = { - foo: { - is: ["object"], - ok: () => assert.fail("is should have caused us to throw by now") - } - }; - assert.throws( - () => apiUtils.validateOptions(null, requirements), - /^The option "foo" must be one of the following types: object/, - "is should be used before ok is called" - ); -}; - -exports.testValidateOptionsErrorMsg = function (assert) { - assert.throws( - () => apiUtils.validateOptions(null, { - foo: { ok: v => v, msg: "foo!" } - }), - /^foo!/, - "ok should raise exception with customized message" - ); -}; - -exports.testValidateMapWithMissingKey = function (assert) { - let val = apiUtils.validateOptions({ }, { - foo: { - map: v => v || "bar" - } - }); - assert.deepEqual(val, { foo: "bar" }); - - val = apiUtils.validateOptions({ }, { - foo: { - map: v => { throw "bar" } - } - }); - assert.deepEqual(val, { }); -}; - -exports.testValidateMapWithMissingKeyAndThrown = function (assert) { - let val = apiUtils.validateOptions({}, { - bar: { - map: function(v) { throw "bar" } - }, - baz: { - map: v => "foo" - } - }); - assert.deepEqual(val, { baz: "foo" }); -}; - -exports.testAddIterator = function testAddIterator (assert) { - let obj = {}; - let keys = ["foo", "bar", "baz"]; - let vals = [1, 2, 3]; - let keysVals = [["foo", 1], ["bar", 2], ["baz", 3]]; - apiUtils.addIterator( - obj, - function keysValsGen() { - for (let keyVal of keysVals) - yield keyVal; - } - ); - - let keysItr = []; - for (let key in obj) - keysItr.push(key); - - assert.equal(keysItr.length, keys.length, - "the keys iterator returns the correct number of items"); - for (let i = 0; i < keys.length; i++) - assert.equal(keysItr[i], keys[i], "the key is correct"); - - let valsItr = []; - for each (let val in obj) - valsItr.push(val); - assert.equal(valsItr.length, vals.length, - "the vals iterator returns the correct number of items"); - for (let i = 0; i < vals.length; i++) - assert.equal(valsItr[i], vals[i], "the val is correct"); - -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-array.js b/addon-sdk/source/test/test-array.js deleted file mode 100644 index 161d8033d..000000000 --- a/addon-sdk/source/test/test-array.js +++ /dev/null @@ -1,103 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 array = require('sdk/util/array'); - -exports.testHas = function(assert) { - var testAry = [1, 2, 3]; - assert.equal(array.has([1, 2, 3], 1), true); - assert.equal(testAry.length, 3); - assert.equal(testAry[0], 1); - assert.equal(testAry[1], 2); - assert.equal(testAry[2], 3); - assert.equal(array.has(testAry, 2), true); - assert.equal(array.has(testAry, 3), true); - assert.equal(array.has(testAry, 4), false); - assert.equal(array.has(testAry, '1'), false); -}; -exports.testHasAny = function(assert) { - var testAry = [1, 2, 3]; - assert.equal(array.hasAny([1, 2, 3], [1]), true); - assert.equal(array.hasAny([1, 2, 3], [1, 5]), true); - assert.equal(array.hasAny([1, 2, 3], [5, 1]), true); - assert.equal(array.hasAny([1, 2, 3], [5, 2]), true); - assert.equal(array.hasAny([1, 2, 3], [5, 3]), true); - assert.equal(array.hasAny([1, 2, 3], [5, 4]), false); - assert.equal(testAry.length, 3); - assert.equal(testAry[0], 1); - assert.equal(testAry[1], 2); - assert.equal(testAry[2], 3); - assert.equal(array.hasAny(testAry, [2]), true); - assert.equal(array.hasAny(testAry, [3]), true); - assert.equal(array.hasAny(testAry, [4]), false); - assert.equal(array.hasAny(testAry), false); - assert.equal(array.hasAny(testAry, '1'), false); -}; - -exports.testAdd = function(assert) { - var testAry = [1]; - assert.equal(array.add(testAry, 1), false); - assert.equal(testAry.length, 1); - assert.equal(testAry[0], 1); - assert.equal(array.add(testAry, 2), true); - assert.equal(testAry.length, 2); - assert.equal(testAry[0], 1); - assert.equal(testAry[1], 2); -}; - -exports.testRemove = function(assert) { - var testAry = [1, 2]; - assert.equal(array.remove(testAry, 3), false); - assert.equal(testAry.length, 2); - assert.equal(testAry[0], 1); - assert.equal(testAry[1], 2); - assert.equal(array.remove(testAry, 2), true); - assert.equal(testAry.length, 1); - assert.equal(testAry[0], 1); -}; - -exports.testFlatten = function(assert) { - assert.equal(array.flatten([1, 2, 3]).length, 3); - assert.equal(array.flatten([1, [2, 3]]).length, 3); - assert.equal(array.flatten([1, [2, [3]]]).length, 3); - assert.equal(array.flatten([[1], [[2, [3]]]]).length, 3); -}; - -exports.testUnique = function(assert) { - var Class = function () {}; - var A = {}; - var B = new Class(); - var C = [ 1, 2, 3 ]; - var D = {}; - var E = new Class(); - - assert.deepEqual(array.unique([1,2,3,1,2]), [1,2,3]); - assert.deepEqual(array.unique([1,1,1,4,9,5,5]), [1,4,9,5]); - assert.deepEqual(array.unique([A, A, A, B, B, D]), [A,B,D]); - assert.deepEqual(array.unique([A, D, A, E, E, D, A, A, C]), [A, D, E, C]) -}; - -exports.testUnion = function(assert) { - var Class = function () {}; - var A = {}; - var B = new Class(); - var C = [ 1, 2, 3 ]; - var D = {}; - var E = new Class(); - - assert.deepEqual(array.union([1, 2, 3],[7, 1, 2]), [1, 2, 3, 7]); - assert.deepEqual(array.union([1, 1, 1, 4, 9, 5, 5], [10, 1, 5]), [1, 4, 9, 5, 10]); - assert.deepEqual(array.union([A, B], [A, D]), [A, B, D]); - assert.deepEqual(array.union([A, D], [A, E], [E, D, A], [A, C]), [A, D, E, C]); -}; - -exports.testFind = function(assert) { - let isOdd = (x) => x % 2; - assert.equal(array.find([2, 4, 5, 7, 8, 9], isOdd), 5); - assert.equal(array.find([2, 4, 6, 8], isOdd), undefined); - assert.equal(array.find([2, 4, 6, 8], isOdd, null), null); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-base64.js b/addon-sdk/source/test/test-base64.js deleted file mode 100644 index b969413f9..000000000 --- a/addon-sdk/source/test/test-base64.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/. */ - -"use strict"; - -const base64 = require("sdk/base64"); - -const text = "Awesome!"; -const b64text = "QXdlc29tZSE="; - -const utf8text = "\u2713 à la mode"; -const badutf8text = "\u0013 à la mode"; -const b64utf8text = "4pyTIMOgIGxhIG1vZGU="; - -// 1 MB string -const longtext = 'fff'.repeat(333333); -const b64longtext = 'ZmZm'.repeat(333333); - -exports["test base64.encode"] = function (assert) { - assert.equal(base64.encode(text), b64text, "encode correctly") -} - -exports["test base64.decode"] = function (assert) { - assert.equal(base64.decode(b64text), text, "decode correctly") -} - -exports["test base64.encode Unicode"] = function (assert) { - - assert.equal(base64.encode(utf8text, "utf-8"), b64utf8text, - "encode correctly Unicode strings.") -} - -exports["test base64.decode Unicode"] = function (assert) { - - assert.equal(base64.decode(b64utf8text, "utf-8"), utf8text, - "decode correctly Unicode strings.") -} - -exports["test base64.encode long string"] = function (assert) { - - assert.equal(base64.encode(longtext), b64longtext, "encode long strings") -} - -exports["test base64.decode long string"] = function (assert) { - - assert.equal(base64.decode(b64longtext), longtext, "decode long strings") -} - -exports["test base64.encode treats input as octet string"] = function (assert) { - - assert.equal(base64.encode("\u0066"), "Zg==", - "treat octet string as octet string") - assert.equal(base64.encode("\u0166"), "Zg==", - "treat non-octet string as octet string") - assert.equal(base64.encode("\uff66"), "Zg==", - "encode non-octet string as octet string") -} - -exports["test base64.encode with wrong charset"] = function (assert) { - - assert.throws(function() { - base64.encode(utf8text, "utf-16"); - }, "The charset argument can be only 'utf-8'"); - - assert.throws(function() { - base64.encode(utf8text, ""); - }, "The charset argument can be only 'utf-8'"); - - assert.throws(function() { - base64.encode(utf8text, 8); - }, "The charset argument can be only 'utf-8'"); - -} - -exports["test base64.decode with wrong charset"] = function (assert) { - - assert.throws(function() { - base64.decode(utf8text, "utf-16"); - }, "The charset argument can be only 'utf-8'"); - - assert.throws(function() { - base64.decode(utf8text, ""); - }, "The charset argument can be only 'utf-8'"); - - assert.throws(function() { - base64.decode(utf8text, 8); - }, "The charset argument can be only 'utf-8'"); - -} - -exports["test encode/decode Unicode without utf-8 as charset"] = function (assert) { - - assert.equal(base64.decode(base64.encode(utf8text)), badutf8text, - "Unicode strings needs 'utf-8' charset or will be mangled" - ); - -} - -require("test").run(exports); diff --git a/addon-sdk/source/test/test-bootstrap.js b/addon-sdk/source/test/test-bootstrap.js deleted file mode 100644 index 52a713e61..000000000 --- a/addon-sdk/source/test/test-bootstrap.js +++ /dev/null @@ -1,19 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Request } = require("sdk/request"); - -exports.testBootstrapExists = function (assert, done) { - Request({ - url: "resource://gre/modules/sdk/bootstrap.js", - onComplete: function (response) { - if (response.text) - assert.pass("the bootstrap file was found"); - done(); - } - }).get(); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-browser-events.js b/addon-sdk/source/test/test-browser-events.js deleted file mode 100644 index 9402f1ec5..000000000 --- a/addon-sdk/source/test/test-browser-events.js +++ /dev/null @@ -1,102 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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"; - -module.metadata = { - engines: { - "Firefox": "*" - } -}; - -const { Loader } = require("sdk/test/loader"); -const { open, getMostRecentBrowserWindow, getOuterId } = require("sdk/window/utils"); -const { setTimeout } = require("sdk/timers"); - -exports["test browser events"] = function(assert, done) { - let loader = Loader(module); - let { events } = loader.require("sdk/browser/events"); - let { on, off } = loader.require("sdk/event/core"); - let actual = []; - - on(events, "data", function handler(e) { - actual.push(e); - if (e.type === "load") window.close(); - if (e.type === "close") { - // Unload the module so that all listeners set by observer are removed. - - let [ ready, load, close ] = actual; - - assert.equal(ready.type, "DOMContentLoaded"); - assert.equal(ready.target, window, "window ready"); - - assert.equal(load.type, "load"); - assert.equal(load.target, window, "window load"); - - assert.equal(close.type, "close"); - assert.equal(close.target, window, "window load"); - - // Note: If window is closed right after this GC won't have time - // to claim loader and there for this listener, there for it's safer - // to remove listener. - off(events, "data", handler); - loader.unload(); - done(); - } - }); - - // Open window and close it to trigger observers. - let window = open(); -}; - -exports["test browser events ignore other wins"] = function(assert, done) { - let loader = Loader(module); - let { events: windowEvents } = loader.require("sdk/window/events"); - let { events: browserEvents } = loader.require("sdk/browser/events"); - let { on, off } = loader.require("sdk/event/core"); - let actualBrowser = []; - let actualWindow = []; - - function browserEventHandler(e) { - return actualBrowser.push(e); - } - on(browserEvents, "data", browserEventHandler); - on(windowEvents, "data", function handler(e) { - actualWindow.push(e); - // Delay close so that if "load" is also emitted on `browserEvents` - // `browserEventHandler` will be invoked. - if (e.type === "load") setTimeout(window.close); - if (e.type === "close") { - assert.deepEqual(actualBrowser, [], "browser events were not triggered"); - let [ open, ready, load, close ] = actualWindow; - - assert.equal(open.type, "open"); - assert.equal(open.target, window, "window is open"); - - - - assert.equal(ready.type, "DOMContentLoaded"); - assert.equal(ready.target, window, "window ready"); - - assert.equal(load.type, "load"); - assert.equal(load.target, window, "window load"); - - assert.equal(close.type, "close"); - assert.equal(close.target, window, "window load"); - - - // Note: If window is closed right after this GC won't have time - // to claim loader and there for this listener, there for it's safer - // to remove listener. - off(windowEvents, "data", handler); - off(browserEvents, "data", browserEventHandler); - loader.unload(); - done(); - } - }); - - // Open window and close it to trigger observers. - let window = open("data:text/html,not a browser"); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-buffer.js b/addon-sdk/source/test/test-buffer.js deleted file mode 100644 index e55bf2b2f..000000000 --- a/addon-sdk/source/test/test-buffer.js +++ /dev/null @@ -1,563 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - - -/* - * Many of these tests taken from Joyent's Node - * https://github.com/joyent/node/blob/master/test/simple/test-buffer.js - */ - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -const { Buffer, TextEncoder, TextDecoder } = require('sdk/io/buffer'); -const { safeMerge } = require('sdk/util/object'); - -const ENCODINGS = ['utf-8']; - -exports.testBufferMain = function (assert) { - let b = Buffer('abcdef'); - - // try to create 0-length buffers - new Buffer(''); - new Buffer(0); - // test encodings supported by node; - // this is different than what node supports, details - // in buffer.js - ENCODINGS.forEach(enc => { - new Buffer('', enc); - assert.pass('Creating a buffer with ' + enc + ' does not throw'); - }); - - ENCODINGS.forEach(function(encoding) { - // Does not work with utf8 - if (encoding === 'utf-8') return; - var b = new Buffer(10); - b.write('あいうえお', encoding); - assert.equal(b.toString(encoding), 'あいうえお', - 'encode and decodes buffer with ' + encoding); - }); - - // invalid encoding for Buffer.toString - assert.throws(() => { - b.toString('invalid'); - }, RangeError, 'invalid encoding for Buffer.toString'); - - // try to toString() a 0-length slice of a buffer, both within and without the - // valid buffer range - assert.equal(new Buffer('abc').toString('utf8', 0, 0), '', - 'toString 0-length buffer, valid range'); - assert.equal(new Buffer('abc').toString('utf8', -100, -100), '', - 'toString 0-length buffer, invalid range'); - assert.equal(new Buffer('abc').toString('utf8', 100, 100), '', - 'toString 0-length buffer, invalid range'); - - // try toString() with a object as a encoding - assert.equal(new Buffer('abc').toString({toString: function() { - return 'utf8'; - }}), 'abc', 'toString with object as an encoding'); - - // test for buffer overrun - var buf = new Buffer([0, 0, 0, 0, 0]); // length: 5 - var sub = buf.slice(0, 4); // length: 4 - var written = sub.write('12345', 'utf8'); - assert.equal(written, 4, 'correct bytes written in slice'); - assert.equal(buf[4], 0, 'correct origin buffer value'); - - // Check for fractional length args, junk length args, etc. - // https://github.com/joyent/node/issues/1758 - Buffer(3.3).toString(); // throws bad argument error in commit 43cb4ec - assert.equal(Buffer(-1).length, 0); - assert.equal(Buffer(NaN).length, 0); - assert.equal(Buffer(3.3).length, 3); - assert.equal(Buffer({length: 3.3}).length, 3); - assert.equal(Buffer({length: 'BAM'}).length, 0); - - // Make sure that strings are not coerced to numbers. - assert.equal(Buffer('99').length, 2); - assert.equal(Buffer('13.37').length, 5); -}; - -exports.testIsEncoding = function (assert) { - ENCODINGS.map(encoding => { - assert.ok(Buffer.isEncoding(encoding), - 'Buffer.isEncoding ' + encoding + ' truthy'); - }); - ['not-encoding', undefined, null, 100, {}].map(encoding => { - assert.ok(!Buffer.isEncoding(encoding), - 'Buffer.isEncoding ' + encoding + ' falsy'); - }); -}; - -exports.testBufferCopy = function (assert) { - // counter to ensure unique value is always copied - var cntr = 0; - var b = Buffer(1024); // safe constructor - - assert.strictEqual(1024, b.length); - b[0] = -1; - assert.strictEqual(b[0], 255); - - var shimArray = []; - for (var i = 0; i < 1024; i++) { - b[i] = i % 256; - shimArray[i] = i % 256; - } - - compareBuffers(assert, b, shimArray, 'array notation'); - - var c = new Buffer(512); - assert.strictEqual(512, c.length); - // copy 512 bytes, from 0 to 512. - b.fill(++cntr); - c.fill(++cntr); - var copied = b.copy(c, 0, 0, 512); - assert.strictEqual(512, copied, - 'copied ' + copied + ' bytes from b into c'); - - compareBuffers(assert, b, c, 'copied to other buffer'); - - // copy c into b, without specifying sourceEnd - b.fill(++cntr); - c.fill(++cntr); - var copied = c.copy(b, 0, 0); - assert.strictEqual(c.length, copied, - 'copied ' + copied + ' bytes from c into b w/o sourceEnd'); - compareBuffers(assert, b, c, - 'copied to other buffer without specifying sourceEnd'); - - // copy c into b, without specifying sourceStart - b.fill(++cntr); - c.fill(++cntr); - var copied = c.copy(b, 0); - assert.strictEqual(c.length, copied, - 'copied ' + copied + ' bytes from c into b w/o sourceStart'); - compareBuffers(assert, b, c, - 'copied to other buffer without specifying sourceStart'); - - // copy longer buffer b to shorter c without targetStart - b.fill(++cntr); - c.fill(++cntr); - - var copied = b.copy(c); - assert.strictEqual(c.length, copied, - 'copied ' + copied + ' bytes from b into c w/o targetStart'); - compareBuffers(assert, b, c, - 'copy long buffer to shorter buffer without targetStart'); - - // copy starting near end of b to c - b.fill(++cntr); - c.fill(++cntr); - var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2)); - assert.strictEqual(Math.floor(c.length / 2), copied, - 'copied ' + copied + ' bytes from end of b into beg. of c'); - - let successStatus = true; - for (var i = 0; i < Math.floor(c.length / 2); i++) { - if (b[b.length - Math.floor(c.length / 2) + i] !== c[i]) - successStatus = false; - } - - for (var i = Math.floor(c.length /2) + 1; i < c.length; i++) { - if (c[c.length-1] !== c[i]) - successStatus = false; - } - assert.ok(successStatus, - 'Copied bytes from end of large buffer into beginning of small buffer'); - - // try to copy 513 bytes, and check we don't overrun c - b.fill(++cntr); - c.fill(++cntr); - var copied = b.copy(c, 0, 0, 513); - assert.strictEqual(c.length, copied, - 'copied ' + copied + ' bytes from b trying to overrun c'); - compareBuffers(assert, b, c, - 'copying to buffer that would overflow'); - - // copy 768 bytes from b into b - b.fill(++cntr); - b.fill(++cntr, 256); - var copied = b.copy(b, 0, 256, 1024); - assert.strictEqual(768, copied, - 'copied ' + copied + ' bytes from b into b'); - - compareBuffers(assert, b, shimArray.map(()=>cntr), - 'copy partial buffer to itself'); - - // copy string longer than buffer length (failure will segfault) - var bb = new Buffer(10); - bb.fill('hello crazy world'); - - // copy throws at negative sourceStart - assert.throws(function() { - Buffer(5).copy(Buffer(5), 0, -1); - }, RangeError, 'buffer copy throws at negative sourceStart'); - - // check sourceEnd resets to targetEnd if former is greater than the latter - b.fill(++cntr); - c.fill(++cntr); - var copied = b.copy(c, 0, 0, 1025); - assert.strictEqual(copied, c.length, - 'copied ' + copied + ' bytes from b into c'); - compareBuffers(assert, b, c, 'copying should reset sourceEnd if targetEnd if sourceEnd > targetEnd'); - - // throw with negative sourceEnd - assert.throws(function() { - b.copy(c, 0, 0, -1); - }, RangeError, 'buffer copy throws at negative sourceEnd'); - - // when sourceStart is greater than sourceEnd, zero copied - assert.equal(b.copy(c, 0, 100, 10), 0); - - // when targetStart > targetLength, zero copied - assert.equal(b.copy(c, 512, 0, 10), 0); - - // try to copy 0 bytes worth of data into an empty buffer - b.copy(new Buffer(0), 0, 0, 0); - - // try to copy 0 bytes past the end of the target buffer - b.copy(new Buffer(0), 1, 1, 1); - b.copy(new Buffer(1), 1, 1, 1); - - // try to copy 0 bytes from past the end of the source buffer - b.copy(new Buffer(1), 0, 2048, 2048); -}; - -exports.testBufferWrite = function (assert) { - let b = Buffer(1024); - b.fill(0); - - // try to write a 0-length string beyond the end of b - assert.throws(function() { - b.write('', 2048); - }, RangeError, 'writing a 0-length string beyond buffer throws'); - // throw when writing to negative offset - assert.throws(function() { - b.write('a', -1); - }, RangeError, 'writing negative offset on buffer throws'); - - // throw when writing past bounds from the pool - assert.throws(function() { - b.write('a', 2048); - }, RangeError, 'writing past buffer bounds from pool throws'); - - // testing for smart defaults and ability to pass string values as offset - - // previous write API was the following: - // write(string, encoding, offset, length) - // this is planned on being removed in node v0.13, - // we will not support it - var writeTest = new Buffer('abcdes'); - writeTest.write('n', 'utf8'); -// writeTest.write('o', 'utf8', '1'); - writeTest.write('d', '2', 'utf8'); - writeTest.write('e', 3, 'utf8'); -// writeTest.write('j', 'utf8', 4); - assert.equal(writeTest.toString(), 'nbdees', - 'buffer write API alternative syntax works'); -}; - -exports.testBufferWriteEncoding = function (assert) { - - // Node #1210 Test UTF-8 string includes null character - var buf = new Buffer('\0'); - assert.equal(buf.length, 1); - buf = new Buffer('\0\0'); - assert.equal(buf.length, 2); - - buf = new Buffer(2); - var written = buf.write(''); // 0byte - assert.equal(written, 0); - written = buf.write('\0'); // 1byte (v8 adds null terminator) - assert.equal(written, 1); - written = buf.write('a\0'); // 1byte * 2 - assert.equal(written, 2); - // TODO, these tests write 0, possibly due to character encoding -/* - written = buf.write('あ'); // 3bytes - assert.equal(written, 0); - written = buf.write('\0あ'); // 1byte + 3bytes - assert.equal(written, 1); -*/ - written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes - buf = new Buffer(10); - written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator) - assert.equal(written, 9); - written = buf.write('あいう\0'); // 3bytes * 3 + 1byte - assert.equal(written, 10); -}; - -exports.testBufferWriteWithMaxLength = function (assert) { - // Node #243 Test write() with maxLength - var buf = new Buffer(4); - buf.fill(0xFF); - var written = buf.write('abcd', 1, 2, 'utf8'); - assert.equal(written, 2); - assert.equal(buf[0], 0xFF); - assert.equal(buf[1], 0x61); - assert.equal(buf[2], 0x62); - assert.equal(buf[3], 0xFF); - - buf.fill(0xFF); - written = buf.write('abcd', 1, 4); - assert.equal(written, 3); - assert.equal(buf[0], 0xFF); - assert.equal(buf[1], 0x61); - assert.equal(buf[2], 0x62); - assert.equal(buf[3], 0x63); - - buf.fill(0xFF); - // Ignore legacy API - /* - written = buf.write('abcd', 'utf8', 1, 2); // legacy style - console.log(buf); - assert.equal(written, 2); - assert.equal(buf[0], 0xFF); - assert.equal(buf[1], 0x61); - assert.equal(buf[2], 0x62); - assert.equal(buf[3], 0xFF); - */ -}; - -exports.testBufferSlice = function (assert) { - var asciiString = 'hello world'; - var offset = 100; - var b = Buffer(1024); - b.fill(0); - - for (var i = 0; i < asciiString.length; i++) { - b[i] = asciiString.charCodeAt(i); - } - var asciiSlice = b.toString('utf8', 0, asciiString.length); - assert.equal(asciiString, asciiSlice); - - var written = b.write(asciiString, offset, 'utf8'); - assert.equal(asciiString.length, written); - asciiSlice = b.toString('utf8', offset, offset + asciiString.length); - assert.equal(asciiString, asciiSlice); - - var sliceA = b.slice(offset, offset + asciiString.length); - var sliceB = b.slice(offset, offset + asciiString.length); - compareBuffers(assert, sliceA, sliceB, - 'slicing is idempotent'); - - let sliceTest = true; - for (var j = 0; j < 100; j++) { - var slice = b.slice(100, 150); - if (50 !== slice.length) - sliceTest = false; - for (var i = 0; i < 50; i++) { - if (b[100 + i] !== slice[i]) - sliceTest = false; - } - } - assert.ok(sliceTest, 'massive slice runs do not affect buffer'); - - // Single argument slice - let testBuf = new Buffer('abcde'); - assert.equal('bcde', testBuf.slice(1).toString(), 'single argument slice'); - - // slice(0,0).length === 0 - assert.equal(0, Buffer('hello').slice(0, 0).length, 'slice(0,0) === 0'); - - var buf = new Buffer('0123456789'); - assert.equal(buf.slice(-10, 10), '0123456789', 'buffer slice range correct'); - assert.equal(buf.slice(-20, 10), '0123456789', 'buffer slice range correct'); - assert.equal(buf.slice(-20, -10), '', 'buffer slice range correct'); - assert.equal(buf.slice(0, -1), '012345678', 'buffer slice range correct'); - assert.equal(buf.slice(2, -2), '234567', 'buffer slice range correct'); - assert.equal(buf.slice(0, 65536), '0123456789', 'buffer slice range correct'); - assert.equal(buf.slice(65536, 0), '', 'buffer slice range correct'); - - sliceTest = true; - for (var i = 0, s = buf.toString(); i < buf.length; ++i) { - if (buf.slice(-i) != s.slice(-i)) sliceTest = false; - if (buf.slice(0, -i) != s.slice(0, -i)) sliceTest = false; - } - assert.ok(sliceTest, 'buffer.slice should be consistent'); - - // Make sure modifying a sliced buffer, affects original and vice versa - b.fill(0); - let sliced = b.slice(0, 10); - let babyslice = sliced.slice(0, 5); - - for (let i = 0; i < sliced.length; i++) - sliced[i] = 'jetpack'.charAt(i); - - compareBuffers(assert, b, sliced, - 'modifying sliced buffer affects original'); - - compareBuffers(assert, b, babyslice, - 'modifying sliced buffer affects child-sliced buffer'); - - for (let i = 0; i < sliced.length; i++) - b[i] = 'odinmonkey'.charAt(i); - - compareBuffers(assert, b, sliced, - 'modifying original buffer affects sliced'); - - compareBuffers(assert, b, babyslice, - 'modifying original buffer affects grandchild sliced buffer'); -}; - -exports.testSlicingParents = function (assert) { - let root = Buffer(5); - let child = root.slice(0, 4); - let grandchild = child.slice(0, 3); - - assert.equal(root.parent, undefined, 'a new buffer should not have a parent'); - - // make sure a zero length slice doesn't set the .parent attribute - assert.equal(root.slice(0,0).parent, undefined, - '0-length slice should not have a parent'); - - assert.equal(child.parent, root, - 'a valid slice\'s parent should be the original buffer (child)'); - - assert.equal(grandchild.parent, root, - 'a valid slice\'s parent should be the original buffer (grandchild)'); -}; - -exports.testIsBuffer = function (assert) { - let buffer = new Buffer('content', 'utf8'); - assert.ok(Buffer.isBuffer(buffer), 'isBuffer truthy on buffers'); - assert.ok(!Buffer.isBuffer({}), 'isBuffer falsy on objects'); - assert.ok(!Buffer.isBuffer(new Uint8Array()), - 'isBuffer falsy on Uint8Array'); - assert.ok(Buffer.isBuffer(buffer.slice(0)), 'Buffer#slice should be a new buffer'); -}; - -exports.testBufferConcat = function (assert) { - let zero = []; - let one = [ new Buffer('asdf') ]; - let long = []; - for (let i = 0; i < 10; i++) long.push(new Buffer('asdf')); - - let flatZero = Buffer.concat(zero); - let flatOne = Buffer.concat(one); - let flatLong = Buffer.concat(long); - let flatLongLen = Buffer.concat(long, 40); - - assert.equal(flatZero.length, 0); - assert.equal(flatOne.toString(), 'asdf'); - assert.equal(flatOne, one[0]); - assert.equal(flatLong.toString(), (new Array(10+1).join('asdf'))); - assert.equal(flatLongLen.toString(), (new Array(10+1).join('asdf'))); -}; - -exports.testBufferByteLength = function (assert) { - let str = '\u00bd + \u00bc = \u00be'; - assert.equal(Buffer.byteLength(str), 12, - 'correct byteLength of string'); - - assert.equal(14, Buffer.byteLength('Il était tué')); - assert.equal(14, Buffer.byteLength('Il était tué', 'utf8')); - // We do not currently support these encodings - /* - ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) { - assert.equal(24, Buffer.byteLength('Il était tué', encoding)); - }); - assert.equal(12, Buffer.byteLength('Il était tué', 'ascii')); - assert.equal(12, Buffer.byteLength('Il était tué', 'binary')); - */ -}; - -exports.testTextEncoderDecoder = function (assert) { - assert.ok(TextEncoder, 'TextEncoder exists'); - assert.ok(TextDecoder, 'TextDecoder exists'); -}; - -exports.testOverflowedBuffers = function (assert) { - assert.throws(function() { - new Buffer(0xFFFFFFFF); - }, RangeError, 'correctly throws buffer overflow'); - - assert.throws(function() { - new Buffer(0xFFFFFFFFF); - }, RangeError, 'correctly throws buffer overflow'); - - assert.throws(function() { - var buf = new Buffer(8); - buf.readFloatLE(0xffffffff); - }, RangeError, 'correctly throws buffer overflow with readFloatLE'); - - assert.throws(function() { - var buf = new Buffer(8); - buf.writeFloatLE(0.0, 0xffffffff); - }, RangeError, 'correctly throws buffer overflow with writeFloatLE'); - - //ensure negative values can't get past offset - assert.throws(function() { - var buf = new Buffer(8); - buf.readFloatLE(-1); - }, RangeError, 'correctly throws with readFloatLE negative values'); - - assert.throws(function() { - var buf = new Buffer(8); - buf.writeFloatLE(0.0, -1); - }, RangeError, 'correctly throws with writeFloatLE with negative values'); - - assert.throws(function() { - var buf = new Buffer(8); - buf.readFloatLE(-1); - }, RangeError, 'correctly throws with readFloatLE with negative values'); -}; - -exports.testReadWriteDataTypeErrors = function (assert) { - var buf = new Buffer(0); - assert.throws(function() { buf.readUInt8(0); }, RangeError, - 'readUInt8(0) throws'); - assert.throws(function() { buf.readInt8(0); }, RangeError, - 'readInt8(0) throws'); - - [16, 32].forEach(function(bits) { - var buf = new Buffer(bits / 8 - 1); - assert.throws(function() { buf['readUInt' + bits + 'BE'](0); }, - RangeError, - 'readUInt' + bits + 'BE'); - - assert.throws(function() { buf['readUInt' + bits + 'LE'](0); }, - RangeError, - 'readUInt' + bits + 'LE'); - - assert.throws(function() { buf['readInt' + bits + 'BE'](0); }, - RangeError, - 'readInt' + bits + 'BE()'); - - assert.throws(function() { buf['readInt' + bits + 'LE'](0); }, - RangeError, - 'readInt' + bits + 'LE()'); - }); -}; - -safeMerge(exports, require('./buffers/test-write-types')); -safeMerge(exports, require('./buffers/test-read-types')); - -function compareBuffers (assert, buf1, buf2, message) { - let status = true; - for (let i = 0; i < Math.min(buf1.length, buf2.length); i++) { - if (buf1[i] !== buf2[i]) - status = false; - } - assert.ok(status, 'buffer successfully copied: ' + message); -} -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-byte-streams.js b/addon-sdk/source/test/test-byte-streams.js deleted file mode 100644 index 7d45130aa..000000000 --- a/addon-sdk/source/test/test-byte-streams.js +++ /dev/null @@ -1,169 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 byteStreams = require("sdk/io/byte-streams"); -const file = require("sdk/io/file"); -const { pathFor } = require("sdk/system"); -const { Loader } = require("sdk/test/loader"); - -const STREAM_CLOSED_ERROR = new RegExp("The stream is closed and cannot be used."); - -// This should match the constant of the same name in byte-streams.js. -const BUFFER_BYTE_LEN = 0x8000; - -exports.testWriteRead = function (assert) { - let fname = dataFileFilename(); - - // Write a small string less than the stream's buffer size... - let str = "exports.testWriteRead data!"; - let stream = open(assert, fname, true); - assert.ok(!stream.closed, "stream.closed after open should be false"); - stream.write(str); - stream.close(); - assert.ok(stream.closed, "Stream should be closed after stream.close"); - assert.throws(() => stream.write("This shouldn't be written!"), - STREAM_CLOSED_ERROR, - "stream.write after close should raise error"); - - // ... and read it. - stream = open(assert, fname); - assert.equal(stream.read(), str, - "stream.read should return string written"); - assert.equal(stream.read(), "", - "stream.read at EOS should return empty string"); - stream.close(); - assert.ok(stream.closed, "Stream should be closed after stream.close"); - assert.throws(() => stream.read(), - STREAM_CLOSED_ERROR, - "stream.read after close should raise error"); - - file.remove(fname); -}; - -// Write a big string many times the size of the stream's buffer and read it. -exports.testWriteReadBig = function (assert) { - let str = ""; - let bufLen = BUFFER_BYTE_LEN; - let fileSize = bufLen * 10; - for (let i = 0; i < fileSize; i++) - str += i % 10; - let fname = dataFileFilename(); - let stream = open(assert, fname, true); - stream.write(str); - stream.close(); - stream = open(assert, fname); - assert.equal(stream.read(), str, - "stream.read should return string written"); - stream.close(); - file.remove(fname); -}; - -// The same, but write and read in chunks. -exports.testWriteReadChunks = function (assert) { - let str = ""; - let bufLen = BUFFER_BYTE_LEN; - let fileSize = bufLen * 10; - for (let i = 0; i < fileSize; i++) - str += i % 10; - let fname = dataFileFilename(); - let stream = open(assert, fname, true); - let i = 0; - while (i < str.length) { - // Use a chunk length that spans buffers. - let chunk = str.substr(i, bufLen + 1); - stream.write(chunk); - i += bufLen + 1; - } - stream.close(); - stream = open(assert, fname); - let readStr = ""; - bufLen = BUFFER_BYTE_LEN; - let readLen = bufLen + 1; - do { - var frag = stream.read(readLen); - readStr += frag; - } while (frag); - stream.close(); - assert.equal(readStr, str, - "stream.write and read in chunks should work as expected"); - file.remove(fname); -}; - -exports.testReadLengths = function (assert) { - let fname = dataFileFilename(); - let str = "exports.testReadLengths data!"; - let stream = open(assert, fname, true); - stream.write(str); - stream.close(); - - stream = open(assert, fname); - assert.equal(stream.read(str.length * 1000), str, - "stream.read with big byte length should return string " + - "written"); - stream.close(); - - stream = open(assert, fname); - assert.equal(stream.read(0), "", - "string.read with zero byte length should return empty " + - "string"); - stream.close(); - - stream = open(assert, fname); - assert.equal(stream.read(-1), "", - "string.read with negative byte length should return " + - "empty string"); - stream.close(); - - file.remove(fname); -}; - -exports.testTruncate = function (assert) { - let fname = dataFileFilename(); - let str = "exports.testReadLengths data!"; - let stream = open(assert, fname, true); - stream.write(str); - stream.close(); - - stream = open(assert, fname); - assert.equal(stream.read(), str, - "stream.read should return string written"); - stream.close(); - - stream = open(assert, fname, true); - stream.close(); - - stream = open(assert, fname); - assert.equal(stream.read(), "", - "stream.read after truncate should be empty"); - stream.close(); - - file.remove(fname); -}; - -exports.testUnload = function (assert) { - let loader = Loader(module); - let file = loader.require("sdk/io/file"); - - let filename = dataFileFilename("temp-b"); - let stream = file.open(filename, "wb"); - - loader.unload(); - assert.ok(stream.closed, "Stream should be closed after module unload"); -}; - -// Returns the name of a file that should be used to test writing and reading. -function dataFileFilename() { - return file.join(pathFor("ProfD"), "test-byte-streams-data"); -} - -// Opens and returns the given file and ensures it's of the correct class. -function open(assert, filename, forWriting) { - let stream = file.open(filename, forWriting ? "wb" : "b"); - let klass = forWriting ? "ByteWriter" : "ByteReader"; - assert.ok(stream instanceof byteStreams[klass], - "Opened stream should be a " + klass); - return stream; -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-child_process.js b/addon-sdk/source/test/test-child_process.js deleted file mode 100644 index 4cfd9ec49..000000000 --- a/addon-sdk/source/test/test-child_process.js +++ /dev/null @@ -1,545 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { spawn, exec, execFile, fork } = require('sdk/system/child_process'); -const { env, platform, pathFor } = require('sdk/system'); -const { isNumber } = require('sdk/lang/type'); -const { after } = require('sdk/test/utils'); -const { emit } = require('sdk/event/core'); -const PROFILE_DIR= pathFor('ProfD'); -const isWindows = platform.toLowerCase().indexOf('win') === 0; -const { getScript, cleanUp } = require('./fixtures/child-process-scripts'); - -// We use direct paths to these utilities as we currently cannot -// call non-absolute paths to utilities in subprocess.jsm -const CAT_PATH = isWindows ? 'C:\\Windows\\System32\\more.com' : '/bin/cat'; - -exports.testExecCallbackSuccess = function (assert, done) { - exec(isWindows ? 'DIR /A-D' : 'ls -al', { - cwd: PROFILE_DIR - }, function (err, stdout, stderr) { - assert.ok(!err, 'no errors found'); - assert.equal(stderr, '', 'stderr is empty'); - assert.ok(/extensions\.ini/.test(stdout), 'stdout output of `ls -al` finds files'); - - if (isWindows) { - // `DIR /A-D` does not display directories on WIN - assert.ok(!//.test(stdout), - 'passing arguments in `exec` works'); - } - else { - // `ls -al` should list all the priviledge information on Unix - assert.ok(/d(r[-|w][-|x]){3}/.test(stdout), - 'passing arguments in `exec` works'); - } - done(); - }); -}; - -exports.testExecCallbackError = function (assert, done) { - exec('not-real-command', { cwd: PROFILE_DIR }, function (err, stdout, stderr) { - assert.ok(/not-real-command/.test(err.toString()), - 'error contains error message'); - assert.ok(err.lineNumber >= 0, 'error contains lineNumber'); - assert.ok(/resource:\/\//.test(err.fileName), 'error contains fileName'); - assert.ok(err.code && isNumber(err.code), 'non-zero error code property on error'); - assert.equal(err.signal, null, - 'null signal property when not manually terminated'); - assert.equal(stdout, '', 'stdout is empty'); - assert.ok(/not-real-command/.test(stderr), 'stderr contains error message'); - done(); - }); -}; - -exports.testExecOptionsEnvironment = function (assert, done) { - getScript('check-env').then(envScript => { - exec(envScript, { - cwd: PROFILE_DIR, - env: { CHILD_PROCESS_ENV_TEST: 'my-value-test' } - }, function (err, stdout, stderr) { - assert.equal(stderr, '', 'stderr is empty'); - assert.ok(!err, 'received `cwd` option'); - assert.ok(/my-value-test/.test(stdout), - 'receives environment option'); - done(); - }); - }).then(null, assert.fail); -}; - -exports.testExecOptionsTimeout = function (assert, done) { - let count = 0; - getScript('wait').then(script => { - let child = exec(script, { timeout: 100 }, (err, stdout, stderr) => { - assert.equal(err.killed, true, 'error has `killed` property as true'); - assert.equal(err.code, null, 'error has `code` as null'); - assert.equal(err.signal, 'SIGTERM', - 'error has `signal` as SIGTERM by default'); - assert.equal(stdout, '', 'stdout is empty'); - assert.equal(stderr, '', 'stderr is empty'); - if (++count === 3) complete(); - }); - - function exitHandler (code, signal) { - assert.equal(code, null, 'error has `code` as null'); - assert.equal(signal, 'SIGTERM', - 'error has `signal` as SIGTERM by default'); - if (++count === 3) complete(); - } - - function closeHandler (code, signal) { - assert.equal(code, null, 'error has `code` as null'); - assert.equal(signal, 'SIGTERM', - 'error has `signal` as SIGTERM by default'); - if (++count === 3) complete(); - } - - child.on('exit', exitHandler); - child.on('close', closeHandler); - - function complete () { - child.off('exit', exitHandler); - child.off('close', closeHandler); - done(); - } - }).then(null, assert.fail); -}; - -exports.testExecFileCallbackSuccess = function (assert, done) { - getScript('args').then(script => { - execFile(script, ['--myargs', '-j', '-s'], { cwd: PROFILE_DIR }, function (err, stdout, stderr) { - assert.ok(!err, 'no errors found'); - assert.equal(stderr, '', 'stderr is empty'); - // Trim output since different systems have different new line output - assert.equal(stdout.trim(), '--myargs -j -s'.trim(), 'passes in correct arguments'); - done(); - }); - }).then(null, assert.fail); -}; - -exports.testExecFileCallbackError = function (assert, done) { - execFile('not-real-command', { cwd: PROFILE_DIR }, function (err, stdout, stderr) { - assert.ok(/Executable not found/.test(err.message), - `error '${err.message}' contains error message`); - assert.ok(err.lineNumber >= 0, 'error contains lineNumber'); - assert.ok(/resource:\/\//.test(err.fileName), 'error contains fileName'); - assert.equal(stdout, '', 'stdout is empty'); - assert.equal(stderr, '', 'stdout is empty'); - done(); - }); -}; - -exports.testExecFileOptionsEnvironment = function (assert, done) { - getScript('check-env').then(script => { - execFile(script, { - cwd: PROFILE_DIR, - env: { CHILD_PROCESS_ENV_TEST: 'my-value-test' } - }, function (err, stdout, stderr) { - assert.equal(stderr, '', 'stderr is empty'); - assert.ok(!err, 'received `cwd` option'); - assert.ok(/my-value-test/.test(stdout), - 'receives environment option'); - done(); - }); - }).then(null, assert.fail); -}; - -exports.testExecFileOptionsTimeout = function (assert, done) { - let count = 0; - getScript('wait').then(script => { - let child = execFile(script, { timeout: 100 }, (err, stdout, stderr) => { - assert.equal(err.killed, true, 'error has `killed` property as true'); - assert.equal(err.code, null, 'error has `code` as null'); - assert.equal(err.signal, 'SIGTERM', - 'error has `signal` as SIGTERM by default'); - assert.equal(stdout, '', 'stdout is empty'); - assert.equal(stderr, '', 'stderr is empty'); - if (++count === 3) complete(); - }); - - function exitHandler (code, signal) { - assert.equal(code, null, 'error has `code` as null'); - assert.equal(signal, 'SIGTERM', - 'error has `signal` as SIGTERM by default'); - if (++count === 3) complete(); - } - - function closeHandler (code, signal) { - assert.equal(code, null, 'error has `code` as null'); - assert.equal(signal, 'SIGTERM', - 'error has `signal` as SIGTERM by default'); - if (++count === 3) complete(); - } - - child.on('exit', exitHandler); - child.on('close', closeHandler); - - function complete () { - child.off('exit', exitHandler); - child.off('close', closeHandler); - done(); - } - }).then(null, assert.fail); -}; - -/** - * Not necessary to test for both `exec` and `execFile`, but - * it is necessary to test both when the buffer is larger - * and smaller than buffer size used by the subprocess library (1024) - */ -exports.testExecFileOptionsMaxBufferLargeStdOut = function (assert, done) { - let count = 0; - let stdoutChild; - - // Creates a buffer of 2000 to stdout, greater than 1024 - getScript('large-out').then(script => { - stdoutChild = execFile(script, ['10000'], { maxBuffer: 50 }, (err, stdout, stderr) => { - assert.ok(/stdout maxBuffer exceeded/.test(err.toString()), - 'error contains stdout maxBuffer exceeded message'); - assert.ok(stdout.length >= 50, 'stdout has full buffer'); - assert.equal(stderr, '', 'stderr is empty'); - if (++count === 3) complete(); - }); - stdoutChild.on('exit', exitHandler); - stdoutChild.on('close', closeHandler); - }).then(null, assert.fail); - - function exitHandler (code, signal) { - assert.equal(code, null, 'Exit code is null in exit handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in exit handler'); - if (++count === 3) complete(); - } - - function closeHandler (code, signal) { - assert.equal(code, null, 'Exit code is null in close handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in close handler'); - if (++count === 3) complete(); - } - - function complete () { - stdoutChild.off('exit', exitHandler); - stdoutChild.off('close', closeHandler); - done(); - } -}; - -exports.testExecFileOptionsMaxBufferLargeStdOErr = function (assert, done) { - let count = 0; - let stderrChild; - // Creates a buffer of 2000 to stderr, greater than 1024 - getScript('large-err').then(script => { - stderrChild = execFile(script, ['10000'], { maxBuffer: 50 }, (err, stdout, stderr) => { - assert.ok(/stderr maxBuffer exceeded/.test(err.toString()), - 'error contains stderr maxBuffer exceeded message'); - assert.ok(stderr.length >= 50, 'stderr has full buffer'); - assert.equal(stdout, '', 'stdout is empty'); - if (++count === 3) complete(); - }); - stderrChild.on('exit', exitHandler); - stderrChild.on('close', closeHandler); - }).then(null, assert.fail); - - function exitHandler (code, signal) { - assert.equal(code, null, 'Exit code is null in exit handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in exit handler'); - if (++count === 3) complete(); - } - - function closeHandler (code, signal) { - assert.equal(code, null, 'Exit code is null in close handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in close handler'); - if (++count === 3) complete(); - } - - function complete () { - stderrChild.off('exit', exitHandler); - stderrChild.off('close', closeHandler); - done(); - } -}; - -/** - * When total buffer is < process buffer (1024), the process will exit - * and not get a chance to be killed for violating the maxBuffer, - * although the error will still be sent through (node behaviour) - */ -exports.testExecFileOptionsMaxBufferSmallStdOut = function (assert, done) { - let count = 0; - let stdoutChild; - - // Creates a buffer of 60 to stdout, less than 1024 - getScript('large-out').then(script => { - stdoutChild = execFile(script, ['60'], { maxBuffer: 50 }, (err, stdout, stderr) => { - assert.ok(/stdout maxBuffer exceeded/.test(err.toString()), - 'error contains stdout maxBuffer exceeded message'); - assert.ok(stdout.length >= 50, 'stdout has full buffer'); - assert.equal(stderr, '', 'stderr is empty'); - if (++count === 3) complete(); - }); - stdoutChild.on('exit', exitHandler); - stdoutChild.on('close', closeHandler); - }).then(null, assert.fail); - - function exitHandler (code, signal) { - // Sometimes the buffer limit is hit before the process closes successfully - // on both OSX/Windows - if (code === null) { - assert.equal(code, null, 'Exit code is null in exit handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in exit handler'); - } - else { - assert.equal(code, 0, 'Exit code is 0 in exit handler'); - assert.equal(signal, null, 'Signal is null in exit handler'); - } - if (++count === 3) complete(); - } - - function closeHandler (code, signal) { - // Sometimes the buffer limit is hit before the process closes successfully - // on both OSX/Windows - if (code === null) { - assert.equal(code, null, 'Exit code is null in close handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in close handler'); - } - else { - assert.equal(code, 0, 'Exit code is 0 in close handler'); - assert.equal(signal, null, 'Signal is null in close handler'); - } - if (++count === 3) complete(); - } - - function complete () { - stdoutChild.off('exit', exitHandler); - stdoutChild.off('close', closeHandler); - done(); - } -}; - -exports.testExecFileOptionsMaxBufferSmallStdErr = function (assert, done) { - let count = 0; - let stderrChild; - // Creates a buffer of 60 to stderr, less than 1024 - getScript('large-err').then(script => { - stderrChild = execFile(script, ['60'], { maxBuffer: 50 }, (err, stdout, stderr) => { - assert.ok(/stderr maxBuffer exceeded/.test(err.toString()), - 'error contains stderr maxBuffer exceeded message'); - assert.ok(stderr.length >= 50, 'stderr has full buffer'); - assert.equal(stdout, '', 'stdout is empty'); - if (++count === 3) complete(); - }); - stderrChild.on('exit', exitHandler); - stderrChild.on('close', closeHandler); - }).then(null, assert.fail); - - function exitHandler (code, signal) { - // Sometimes the buffer limit is hit before the process closes successfully - // on both OSX/Windows - if (code === null) { - assert.equal(code, null, 'Exit code is null in exit handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in exit handler'); - } - else { - assert.equal(code, 0, 'Exit code is 0 in exit handler'); - assert.equal(signal, null, 'Signal is null in exit handler'); - } - if (++count === 3) complete(); - } - - function closeHandler (code, signal) { - // Sometimes the buffer limit is hit before the process closes successfully - // on both OSX/Windows - if (code === null) { - assert.equal(code, null, 'Exit code is null in close handler'); - assert.equal(signal, 'SIGTERM', 'Signal is SIGTERM in close handler'); - } - else { - assert.equal(code, 0, 'Exit code is 0 in close handler'); - assert.equal(signal, null, 'Signal is null in close handler'); - } - if (++count === 3) complete(); - } - - function complete () { - stderrChild.off('exit', exitHandler); - stderrChild.off('close', closeHandler); - done(); - } -}; - -exports.testChildExecFileKillSignal = function (assert, done) { - getScript('wait').then(script => { - execFile(script, { - killSignal: 'beepbeep', - timeout: 10 - }, function (err, stdout, stderr) { - assert.equal(err.signal, 'beepbeep', 'correctly used custom killSignal'); - done(); - }); - }).then(null, assert.fail); -}; - -exports.testChildProperties = function (assert, done) { - getScript('check-env').then(script => { - let child = spawn(script, { - env: { CHILD_PROCESS_ENV_TEST: 'my-value-test' } - }); - - if (isWindows) - assert.ok(true, 'Windows environment does not have `pid`'); - else - assert.ok(child.pid > 0, 'Child has a pid'); - }).then(done, assert.fail); -}; - -exports.testChildStdinStreamLarge = function (assert, done) { - let REPEAT = 2000; - let allData = ''; - // Use direct paths to more/cat, as we do not currently support calling non-files - // from subprocess.jsm - let child = spawn(CAT_PATH); - - child.stdout.on('data', onData); - child.on('close', onClose); - - for (let i = 0; i < REPEAT; i++) - emit(child.stdin, 'data', '12345\n'); - - emit(child.stdin, 'end'); - - function onData (data) { - allData += data; - } - - function onClose (code, signal) { - child.stdout.off('data', onData); - child.off('close', onClose); - assert.equal(code, 0, 'exited succesfully'); - assert.equal(signal, null, 'no kill signal given'); - assert.equal(allData.replace(/\W/g, '').length, '12345'.length * REPEAT, - 'all data processed from stdin'); - done(); - } -}; - -exports.testChildStdinStreamSmall = function (assert, done) { - let allData = ''; - let child = spawn(CAT_PATH); - child.stdout.on('data', onData); - child.on('close', onClose); - - emit(child.stdin, 'data', '12345'); - emit(child.stdin, 'end'); - - function onData (data) { - allData += data; - } - - function onClose (code, signal) { - child.stdout.off('data', onData); - child.off('close', onClose); - assert.equal(code, 0, 'exited succesfully'); - assert.equal(signal, null, 'no kill signal given'); - assert.equal(allData.trim(), '12345', 'all data processed from stdin'); - done(); - } -}; -/* - * This tests failures when an error is thrown attempting to - * spawn the process, like an invalid command - */ -exports.testChildEventsSpawningError= function (assert, done) { - let handlersCalled = 0; - let child = execFile('i-do-not-exist', (err, stdout, stderr) => { - assert.ok(err, 'error was passed into callback'); - assert.equal(stdout, '', 'stdout is empty') - assert.equal(stderr, '', 'stderr is empty'); - if (++handlersCalled === 3) complete(); - }); - - child.on('error', handleError); - child.on('exit', handleExit); - child.on('close', handleClose); - - function handleError (e) { - assert.ok(e, 'error passed into error handler'); - if (++handlersCalled === 3) complete(); - } - - function handleClose (code, signal) { - assert.equal(code, -1, - 'process was never spawned, therefore exit code is -1'); - assert.equal(signal, null, 'signal should be null'); - if (++handlersCalled === 3) complete(); - } - - function handleExit (code, signal) { - assert.fail('Close event should not be called on init failure'); - } - - function complete () { - child.off('error', handleError); - child.off('exit', handleExit); - child.off('close', handleClose); - done(); - } -}; - -exports.testSpawnOptions = function (assert, done) { - let count = 0; - let envStdout = ''; - let cwdStdout = ''; - let checkEnv, checkPwd, envChild, cwdChild; - getScript('check-env').then(script => { - checkEnv = script; - return getScript('check-pwd'); - }).then(script => { - checkPwd = script; - - envChild = spawn(checkEnv, { - env: { CHILD_PROCESS_ENV_TEST: 'my-value-test' } - }); - cwdChild = spawn(checkPwd, { cwd: PROFILE_DIR }); - - // Do these need to be unbound? - envChild.stdout.on('data', data => envStdout += data); - cwdChild.stdout.on('data', data => cwdStdout += data); - - envChild.on('close', envClose); - cwdChild.on('close', cwdClose); - }).then(null, assert.fail); - - function envClose () { - assert.equal(envStdout.trim(), 'my-value-test', 'spawn correctly passed in ENV'); - if (++count === 2) complete(); - } - - function cwdClose () { - // Check for PROFILE_DIR in the output because - // some systems resolve symbolic links, and on OSX - // /var -> /private/var - let isCorrectPath = ~cwdStdout.trim().indexOf(PROFILE_DIR); - assert.ok(isCorrectPath, 'spawn correctly passed in cwd'); - if (++count === 2) complete(); - } - - function complete () { - envChild.off('close', envClose); - cwdChild.off('close', cwdClose); - done(); - } -}; - -exports.testFork = function (assert) { - assert.throws(function () { - fork(); - }, /not currently supported/, 'fork() correctly throws an unsupported error'); -}; - -after(exports, cleanUp); - -require("sdk/test").run(exports); - -// Test disabled because of bug 979675 -module.exports = {}; diff --git a/addon-sdk/source/test/test-chrome.js b/addon-sdk/source/test/test-chrome.js deleted file mode 100644 index 3d1f29dd0..000000000 --- a/addon-sdk/source/test/test-chrome.js +++ /dev/null @@ -1,84 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 chrome = require('chrome'); - -const FIXTURES_URL = module.uri.substr(0, module.uri.lastIndexOf('/') + 1) + - 'fixtures/chrome-worker/' - -exports['test addEventListener'] = function(assert, done) { - let uri = FIXTURES_URL + 'addEventListener.js'; - - let worker = new chrome.ChromeWorker(uri); - worker.addEventListener('message', function(event) { - assert.equal(event.data, 'Hello', 'message received'); - worker.terminate(); - done(); - }); -}; - -exports['test onmessage'] = function(assert, done) { - let uri = FIXTURES_URL + 'onmessage.js'; - - let worker = new chrome.ChromeWorker(uri); - worker.onmessage = function(event) { - assert.equal(event.data, 'ok', 'message received'); - worker.terminate(); - done(); - }; - worker.postMessage('ok'); -}; - -exports['test setTimeout'] = function(assert, done) { - let uri = FIXTURES_URL + 'setTimeout.js'; - - let worker = new chrome.ChromeWorker(uri); - worker.onmessage = function(event) { - assert.equal(event.data, 'ok', 'setTimeout fired'); - worker.terminate(); - done(); - }; -}; - -exports['test jsctypes'] = function(assert, done) { - let uri = FIXTURES_URL + 'jsctypes.js'; - - let worker = new chrome.ChromeWorker(uri); - worker.onmessage = function(event) { - assert.equal(event.data, 'function', 'ctypes.open is a function'); - worker.terminate(); - done(); - }; -}; - -exports['test XMLHttpRequest'] = function(assert, done) { - let uri = FIXTURES_URL + 'xhr.js'; - - let worker = new chrome.ChromeWorker(uri); - worker.onmessage = function(event) { - assert.equal(event.data, 'ok', 'XMLHttpRequest works'); - worker.terminate(); - done(); - }; -}; - -exports['test onerror'] = function(assert, done) { - let uri = FIXTURES_URL + 'onerror.js'; - - let worker = new chrome.ChromeWorker(uri); - worker.onerror = function(event) { - assert.equal(event.filename, uri, 'event reports the correct uri'); - assert.equal(event.lineno, 6, 'event reports the correct line number'); - assert.equal(event.target, worker, 'event reports the correct worker'); - assert.ok(event.message.match(/ok/), - 'event contains the exception message'); - // Call preventDefault in order to avoid being displayed in JS console. - event.preventDefault(); - worker.terminate(); - done(); - }; -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-clipboard.js b/addon-sdk/source/test/test-clipboard.js deleted file mode 100644 index f7ffd05be..000000000 --- a/addon-sdk/source/test/test-clipboard.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/. */ -"use strict"; - -require("sdk/clipboard"); - -const { Cc, Ci } = require("chrome"); - -const imageTools = Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools); -const io = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); -const appShellService = Cc['@mozilla.org/appshell/appShellService;1'].getService(Ci.nsIAppShellService); - -const XHTML_NS = "http://www.w3.org/1999/xhtml"; -const base64png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYA" + - "AABzenr0AAAASUlEQVRYhe3O0QkAIAwD0eyqe3Q993AQ3cBSUKpygfsNTy" + - "N5ugbQpK0BAADgP0BRDWXWlwEAAAAAgPsA3rzDaAAAAHgPcGrpgAnzQ2FG" + - "bWRR9AAAAABJRU5ErkJggg%3D%3D"; - -const { base64jpeg } = require("./fixtures"); - -const { platform } = require("sdk/system"); -// For Windows, Mac and Linux, platform returns the following: winnt, darwin and linux. -var isWindows = platform.toLowerCase().indexOf("win") == 0; - -// Test the typical use case, setting & getting with no flavors specified -exports["test With No Flavor"] = function(assert) { - var contents = "hello there"; - var flavor = "text"; - var fullFlavor = "text/unicode"; - var clip = require("sdk/clipboard"); - - // Confirm we set the clipboard - assert.ok(clip.set(contents)); - - // Confirm flavor is set - assert.equal(clip.currentFlavors[0], flavor); - - // Confirm we set the clipboard - assert.equal(clip.get(), contents); - - // Confirm we can get the clipboard using the flavor - assert.equal(clip.get(flavor), contents); - - // Confirm we can still get the clipboard using the full flavor - assert.equal(clip.get(fullFlavor), contents); -}; - -// Test the slightly less common case where we specify the flavor -exports["test With Flavor"] = function(assert) { - var contents = "hello there"; - var contentsText = "hello there"; - - // On windows, HTML clipboard includes extra data. - // The values are from widget/windows/nsDataObj.cpp. - var contentsWindowsHtml = "\n" + - contents + - "\n\n"; - - var flavor = "html"; - var fullFlavor = "text/html"; - var unicodeFlavor = "text"; - var unicodeFullFlavor = "text/unicode"; - var clip = require("sdk/clipboard"); - - assert.ok(clip.set(contents, flavor)); - - assert.equal(clip.currentFlavors[0], unicodeFlavor); - assert.equal(clip.currentFlavors[1], flavor); - assert.equal(clip.get(), contentsText); - assert.equal(clip.get(flavor), isWindows ? contentsWindowsHtml : contents); - assert.equal(clip.get(fullFlavor), isWindows ? contentsWindowsHtml : contents); - assert.equal(clip.get(unicodeFlavor), contentsText); - assert.equal(clip.get(unicodeFullFlavor), contentsText); -}; - -// Test that the typical case still works when we specify the flavor to set -exports["test With Redundant Flavor"] = function(assert) { - var contents = "hello there"; - var flavor = "text"; - var fullFlavor = "text/unicode"; - var clip = require("sdk/clipboard"); - - assert.ok(clip.set(contents, flavor)); - assert.equal(clip.currentFlavors[0], flavor); - assert.equal(clip.get(), contents); - assert.equal(clip.get(flavor), contents); - assert.equal(clip.get(fullFlavor), contents); -}; - -exports["test Not In Flavor"] = function(assert) { - var contents = "hello there"; - var flavor = "html"; - var clip = require("sdk/clipboard"); - - assert.ok(clip.set(contents)); - // If there's nothing on the clipboard with this flavor, should return null - assert.equal(clip.get(flavor), null); -}; - -exports["test Set Image"] = function(assert) { - var clip = require("sdk/clipboard"); - var flavor = "image"; - var fullFlavor = "image/png"; - - assert.ok(clip.set(base64png, flavor), "clipboard set"); - assert.equal(clip.currentFlavors[0], flavor, "flavor is set"); -}; - -exports["test Get Image"] = function* (assert) { - var clip = require("sdk/clipboard"); - - clip.set(base64png, "image"); - - var contents = clip.get(); - const hiddenWindow = appShellService.hiddenDOMWindow; - const Image = hiddenWindow.Image; - const canvas = hiddenWindow.document.createElementNS(XHTML_NS, "canvas"); - let context = canvas.getContext("2d"); - - const imageURLToPixels = (imageURL) => { - return new Promise((resolve) => { - let img = new Image(); - - img.onload = function() { - context.drawImage(this, 0, 0); - - let pixels = Array.join(context.getImageData(0, 0, 32, 32).data); - resolve(pixels); - }; - - img.src = imageURL; - }); - }; - - let [base64pngPixels, clipboardPixels] = yield Promise.all([ - imageURLToPixels(base64png), imageURLToPixels(contents), - ]); - - assert.ok(base64pngPixels === clipboardPixels, - "Image gets from clipboard equals to image sets to the clipboard"); -}; - -exports["test Set Image Type Not Supported"] = function(assert) { - var clip = require("sdk/clipboard"); - var flavor = "image"; - - assert.throws(function () { - clip.set(base64jpeg, flavor); - }, "Invalid flavor for image/jpeg"); - -}; - -// Notice that `imageTools.decodeImageData`, used by `clipboard.set` method for -// images, write directly to the javascript console the error in case the image -// is corrupt, even if the error is catched. -// -// See: http://mxr.mozilla.org/mozilla-central/source/image/src/Decoder.cpp#136 -exports["test Set Image Type Wrong Data"] = function(assert) { - var clip = require("sdk/clipboard"); - var flavor = "image"; - - var wrongPNG = "data:image/png" + base64jpeg.substr(15); - - assert.throws(function () { - clip.set(wrongPNG, flavor); - }, "Unable to decode data given in a valid image."); -}; - -require("sdk/test").run(exports) diff --git a/addon-sdk/source/test/test-collection.js b/addon-sdk/source/test/test-collection.js deleted file mode 100644 index d723c14ce..000000000 --- a/addon-sdk/source/test/test-collection.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"; - -const collection = require("sdk/util/collection"); - -exports.testAddRemove = function (assert) { - let coll = new collection.Collection(); - compare(assert, coll, []); - addRemove(assert, coll, [], false); -}; - -exports.testAddRemoveBackingArray = function (assert) { - let items = ["foo"]; - let coll = new collection.Collection(items); - compare(assert, coll, items); - addRemove(assert, coll, items, true); - - items = ["foo", "bar"]; - coll = new collection.Collection(items); - compare(assert, coll, items); - addRemove(assert, coll, items, true); -}; - -exports.testProperty = function (assert) { - let obj = makeObjWithCollProp(); - compare(assert, obj.coll, []); - addRemove(assert, obj.coll, [], false); - - // Test single-value set. - let items = ["foo"]; - obj.coll = items[0]; - compare(assert, obj.coll, items); - addRemove(assert, obj.coll, items, false); - - // Test array set. - items = ["foo", "bar"]; - obj.coll = items; - compare(assert, obj.coll, items); - addRemove(assert, obj.coll, items, false); -}; - -exports.testPropertyBackingArray = function (assert) { - let items = ["foo"]; - let obj = makeObjWithCollProp(items); - compare(assert, obj.coll, items); - addRemove(assert, obj.coll, items, true); - - items = ["foo", "bar"]; - obj = makeObjWithCollProp(items); - compare(assert, obj.coll, items); - addRemove(assert, obj.coll, items, true); -}; - -// Adds some values to coll and then removes them. initialItems is an array -// containing coll's initial items. isBacking is true if initialItems is coll's -// backing array; the point is that updates to coll should affect initialItems -// if that's the case. -function addRemove(assert, coll, initialItems, isBacking) { - let items = isBacking ? initialItems : initialItems.slice(0); - let numInitialItems = items.length; - - // Test add(val). - let numInsertions = 5; - for (let i = 0; i < numInsertions; i++) { - compare(assert, coll, items); - coll.add(i); - if (!isBacking) - items.push(i); - } - compare(assert, coll, items); - - // Add the items we just added to make sure duplicates aren't added. - for (let i = 0; i < numInsertions; i++) - coll.add(i); - compare(assert, coll, items); - - // Test remove(val). Do a kind of shuffled remove. Remove item 1, then - // item 0, 3, 2, 5, 4, ... - for (let i = 0; i < numInsertions; i++) { - let val = i % 2 ? i - 1 : - i === numInsertions - 1 ? i : i + 1; - coll.remove(val); - if (!isBacking) - items.splice(items.indexOf(val), 1); - compare(assert, coll, items); - } - assert.equal(coll.length, numInitialItems, - "All inserted items should be removed"); - - // Remove the items we just removed. coll should be unchanged. - for (let i = 0; i < numInsertions; i++) - coll.remove(i); - compare(assert, coll, items); - - // Test add and remove([val1, val2]). - let newItems = [0, 1]; - coll.add(newItems); - compare(assert, coll, isBacking ? items : items.concat(newItems)); - coll.remove(newItems); - compare(assert, coll, items); - assert.equal(coll.length, numInitialItems, - "All inserted items should be removed"); -} - -// Asserts that the items in coll are the items of array. -function compare(assert, coll, array) { - assert.equal(coll.length, array.length, - "Collection length should be correct"); - let numItems = 0; - for (let item in coll) { - assert.equal(item, array[numItems], "Items should be equal"); - numItems++; - } - assert.equal(numItems, array.length, - "Number of items in iteration should be correct"); -} - -// Returns a new object with a collection property named "coll". backingArray, -// if defined, will create the collection with that backing array. -function makeObjWithCollProp(backingArray) { - let obj = {}; - collection.addCollectionProperty(obj, "coll", backingArray); - return obj; -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-commonjs-test-adapter.js b/addon-sdk/source/test/test-commonjs-test-adapter.js deleted file mode 100644 index 936bea918..000000000 --- a/addon-sdk/source/test/test-commonjs-test-adapter.js +++ /dev/null @@ -1,11 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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"; - -exports["test custom `Assert`'s"] = require("./commonjs-test-adapter/asserts"); - -// Disabling this check since it is not yet supported by jetpack. -// if (module == require.main) - require("test").run(exports); diff --git a/addon-sdk/source/test/test-content-events.js b/addon-sdk/source/test/test-content-events.js deleted file mode 100644 index 059c356c4..000000000 --- a/addon-sdk/source/test/test-content-events.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 { Loader } = require("sdk/test/loader"); -const { getMostRecentBrowserWindow, getInnerId } = require("sdk/window/utils"); -const { openTab, closeTab, getBrowserForTab } = require("sdk/tabs/utils"); -const { defer } = require("sdk/core/promise"); -const { curry, identity, partial } = require("sdk/lang/functional"); - -const { nuke } = require("sdk/loader/sandbox"); - -const { open: openWindow, close: closeWindow } = require('sdk/window/helpers'); - -const openBrowserWindow = partial(openWindow, null, {features: {toolbar: true}}); - -var when = curry(function(options, tab) { - let type = options.type || options; - let capture = options.capture || false; - let target = getBrowserForTab(tab); - let { promise, resolve } = defer(); - - target.addEventListener(type, function handler(event) { - if (!event.target.defaultView.frameElement) { - target.removeEventListener(type, handler, capture); - resolve(tab); - } - }, capture); - - return promise; -}); - -var use = use = value => () => value; - - -var open = curry((url, window) => openTab(window, url)); -var close = function(tab) { - let promise = when("pagehide", tab); - closeTab(tab); - return promise; -} - -exports["test dead object errors"] = function(assert, done) { - let system = require("sdk/system/events"); - let loader = Loader(module); - let { events } = loader.require("sdk/content/events"); - - // The dead object error is properly reported on console but - // doesn't raise any test's exception - function onMessage({ subject }) { - let message = subject.wrappedJSObject; - let { level } = message; - let text = String(message.arguments[0]); - - if (level === "error" && text.includes("can't access dead object")) - fail(text); - } - - let cleanup = () => system.off("console-api-log-event", onMessage); - let fail = (reason) => { - cleanup(); - assert.fail(reason); - } - - loader.unload(); - - nuke(loader.sharedGlobalSandbox); - - system.on("console-api-log-event", onMessage, true); - - openBrowserWindow(). - then(closeWindow). - then(() => assert.pass("checking dead object errors")). - then(cleanup). - then(done, fail); -}; - -// ignore *-document-global-created events that are not very consistent. -// only allow data uris that we create to ignore unwanted events, e.g., -// about:blank, http:// requests from Fennec's `about:`home page that displays -// add-ons a user could install, local `searchplugins`, other chrome uris -// Calls callback if passes filter -function eventFilter (type, target, callback) { - if (target.URL.startsWith("data:text/html,") && - type !== "chrome-document-global-created" && - type !== "content-document-global-created") - - callback(); -} -require("test").run(exports); diff --git a/addon-sdk/source/test/test-content-script.js b/addon-sdk/source/test/test-content-script.js deleted file mode 100644 index d3c7e1bbc..000000000 --- a/addon-sdk/source/test/test-content-script.js +++ /dev/null @@ -1,845 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 hiddenFrames = require("sdk/frame/hidden-frame"); -const { create: makeFrame } = require("sdk/frame/utils"); -const { window } = require("sdk/addon/window"); -const { Loader } = require('sdk/test/loader'); -const { URL } = require("sdk/url"); -const testURI = require("./fixtures").url("test.html"); -const testHost = URL(testURI).scheme + '://' + URL(testURI).host; - -/* - * Utility function that allow to easily run a proxy test with a clean - * new HTML document. See first unit test for usage. - */ -function createProxyTest(html, callback) { - return function (assert, done) { - let url = 'data:text/html;charset=utf-8,' + encodeURIComponent(html); - let principalLoaded = false; - - let element = makeFrame(window.document, { - nodeName: "iframe", - type: "content", - allowJavascript: true, - allowPlugins: true, - allowAuth: true, - uri: testURI - }); - - element.addEventListener("DOMContentLoaded", onDOMReady, false); - - function onDOMReady() { - // Reload frame after getting principal from `testURI` - if (!principalLoaded) { - element.setAttribute("src", url); - principalLoaded = true; - return; - } - - assert.equal(element.getAttribute("src"), url, "correct URL loaded"); - element.removeEventListener("DOMContentLoaded", onDOMReady, - false); - let xrayWindow = element.contentWindow; - let rawWindow = xrayWindow.wrappedJSObject; - - let isDone = false; - let helper = { - xrayWindow: xrayWindow, - rawWindow: rawWindow, - createWorker: function (contentScript) { - return createWorker(assert, xrayWindow, contentScript, helper.done); - }, - done: function () { - if (isDone) - return; - isDone = true; - element.parentNode.removeChild(element); - done(); - } - }; - callback(helper, assert); - } - }; -} - -function createWorker(assert, xrayWindow, contentScript, done) { - let loader = Loader(module); - let Worker = loader.require("sdk/content/worker").Worker; - let worker = Worker({ - window: xrayWindow, - contentScript: [ - 'new ' + function () { - assert = function assert(v, msg) { - self.port.emit("assert", {assertion:v, msg:msg}); - } - done = function done() { - self.port.emit("done"); - } - }, - contentScript - ] - }); - - worker.port.on("done", done); - worker.port.on("assert", function (data) { - assert.ok(data.assertion, data.msg); - }); - - return worker; -} - -/* Examples for the `createProxyTest` uses */ - -var html = ""; - -exports["test Create Proxy Test"] = createProxyTest(html, function (helper, assert) { - // You can get access to regular `test` object in second argument of - // `createProxyTest` method: - assert.ok(helper.rawWindow.documentGlobal, - "You have access to a raw window reference via `helper.rawWindow`"); - assert.ok(!("documentGlobal" in helper.xrayWindow), - "You have access to an XrayWrapper reference via `helper.xrayWindow`"); - - // If you do not create a Worker, you have to call helper.done(), - // in order to say when your test is finished - helper.done(); -}); - -exports["test Create Proxy Test With Worker"] = createProxyTest("", function (helper) { - - helper.createWorker( - "new " + function WorkerScope() { - assert(true, "You can do assertions in your content script"); - // And if you create a worker, you either have to call `done` - // from content script or helper.done() - done(); - } - ); - -}); - -exports["test Create Proxy Test With Events"] = createProxyTest("", function (helper, assert) { - - let worker = helper.createWorker( - "new " + function WorkerScope() { - self.port.emit("foo"); - } - ); - - worker.port.on("foo", function () { - assert.pass("You can use events"); - // And terminate your test with helper.done: - helper.done(); - }); - -}); - -/* Disabled due to bug 1038432 -// Bug 714778: There was some issue around `toString` functions -// that ended up being shared between content scripts -exports["test Shared To String Proxies"] = createProxyTest("", function(helper) { - - let worker = helper.createWorker( - 'new ' + function ContentScriptScope() { - // We ensure that `toString` can't be modified so that nothing could - // leak to/from the document and between content scripts - // It only applies to JS proxies, there isn't any such issue with xrays. - //document.location.toString = function foo() {}; - document.location.toString.foo = "bar"; - assert("foo" in document.location.toString, "document.location.toString can be modified"); - assert(document.location.toString() == "data:text/html;charset=utf-8,", - "First document.location.toString()"); - self.postMessage("next"); - } - ); - worker.on("message", function () { - helper.createWorker( - 'new ' + function ContentScriptScope2() { - assert(!("foo" in document.location.toString), - "document.location.toString is different for each content script"); - assert(document.location.toString() == "data:text/html;charset=utf-8,", - "Second document.location.toString()"); - done(); - } - ); - }); -}); -*/ - -// Ensure that postMessage is working correctly across documents with an iframe -var html = ' -

- -

- - A targetted link. - -

- -

- -

- -

- - A link with no ID and an anchor, used by PredicateContext tests. - -

- -

- - - -

-

- - - - - A complex nested structure. - - - - -

- -

- -

- -

- -

- -

- -

- -

-

This content is editable.

-

- - diff --git a/addon-sdk/source/test/test-context-menu.js b/addon-sdk/source/test/test-context-menu.js deleted file mode 100644 index f1a955545..000000000 --- a/addon-sdk/source/test/test-context-menu.js +++ /dev/null @@ -1,3763 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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'; - -require("sdk/context-menu"); - -const { defer } = require("sdk/core/promise"); -const { isTravisCI } = require("sdk/test/utils"); -const packaging = require('@loader/options'); - -// These should match the same constants in the module. -const OVERFLOW_THRESH_DEFAULT = 10; -const OVERFLOW_THRESH_PREF = - "extensions.addon-sdk.context-menu.overflowThreshold"; - -const TEST_DOC_URL = module.uri.replace(/\.js$/, ".html"); -const data = require("./fixtures"); - -const { TestHelper } = require("./context-menu/test-helper.js") - -// Tests that when present the separator is placed before the separator from -// the old context-menu module -exports.testSeparatorPosition = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - // Create the old separator - let oldSeparator = test.contextMenuPopup.ownerDocument.createElement("menuseparator"); - oldSeparator.id = "jetpack-context-menu-separator"; - test.contextMenuPopup.appendChild(oldSeparator); - - // Create an item. - let item = new loader.cm.Item({ label: "item" }); - - test.showMenu(null, function (popup) { - assert.equal(test.contextMenuSeparator.nextSibling.nextSibling, oldSeparator, - "New separator should appear before the old one"); - test.contextMenuPopup.removeChild(oldSeparator); - test.done(); - }); -}; - -// Destroying items that were previously created should cause them to be absent -// from the menu. -exports.testConstructDestroy = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - // Create an item. - let item = new loader.cm.Item({ label: "item" }); - assert.equal(item.parentMenu, loader.cm.contentContextMenu, - "item's parent menu should be correct"); - - test.showMenu(null, function (popup) { - - // It should be present when the menu is shown. - test.checkMenu([item], [], []); - popup.hidePopup(); - - // Destroy the item. Multiple destroys should be harmless. - item.destroy(); - item.destroy(); - test.showMenu(null, function (popup) { - - // It should be removed from the menu. - test.checkMenu([item], [], [item]); - test.done(); - }); - }); -}; - - -// Destroying an item twice should not cause an error. -exports.testDestroyTwice = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ label: "item" }); - item.destroy(); - item.destroy(); - - test.pass("Destroying an item twice should not cause an error."); - test.done(); -}; - - -// CSS selector contexts should cause their items to be present in the menu -// when the menu is invoked on nodes that match the selectors. -exports.testSelectorContextMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - data: "item", - context: loader.cm.SelectorContext("img") - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); -}; - - -// CSS selector contexts should cause their items to be present in the menu -// when the menu is invoked on nodes that have ancestors that match the -// selectors. -exports.testSelectorAncestorContextMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - data: "item", - context: loader.cm.SelectorContext("a[href]") - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#span-link", function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); -}; - - -// CSS selector contexts should cause their items to be absent from the menu -// when the menu is not invoked on nodes that match or have ancestors that -// match the selectors. -exports.testSelectorContextNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - data: "item", - context: loader.cm.SelectorContext("img") - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); -}; - - -// Page contexts should cause their items to be present in the menu when the -// menu is not invoked on an active element. -exports.testPageContextMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - new loader.cm.Item({ - label: "item 0" - }), - new loader.cm.Item({ - label: "item 1", - context: undefined - }), - new loader.cm.Item({ - label: "item 2", - context: loader.cm.PageContext() - }), - new loader.cm.Item({ - label: "item 3", - context: [loader.cm.PageContext()] - }) - ]; - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); -}; - - -// Page contexts should cause their items to be absent from the menu when the -// menu is invoked on an active element. -exports.testPageContextNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - new loader.cm.Item({ - label: "item 0" - }), - new loader.cm.Item({ - label: "item 1", - context: undefined - }), - new loader.cm.Item({ - label: "item 2", - context: loader.cm.PageContext() - }), - new loader.cm.Item({ - label: "item 3", - context: [loader.cm.PageContext()] - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, items, []); - test.done(); - }); - }); -}; - - -// Selection contexts should cause items to appear when a selection exists. -exports.testSelectionContextMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "item", - context: loader.cm.SelectionContext() - }); - - test.withTestDoc(function (window, doc) { - window.getSelection().selectAllChildren(doc.body); - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); -}; - - -// Selection contexts should cause items to appear when a selection exists in -// a text field. -exports.testSelectionContextMatchInTextField = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "item", - context: loader.cm.SelectionContext() - }); - - test.withTestDoc(function (window, doc) { - test.selectRange("#textfield", 0, null); - test.showMenu("#textfield", function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); -}; - - -// Selection contexts should not cause items to appear when a selection does -// not exist in a text field. -exports.testSelectionContextNoMatchInTextField = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "item", - context: loader.cm.SelectionContext() - }); - - test.withTestDoc(function (window, doc) { - test.selectRange("#textfield", 0, 0); - test.showMenu("#textfield", function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); - }); -}; - - -// Selection contexts should not cause items to appear when a selection does -// not exist. -exports.testSelectionContextNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "item", - context: loader.cm.SelectionContext() - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); -}; - - -// Selection contexts should cause items to appear when a selection exists even -// for newly opened pages -exports.testSelectionContextInNewTab = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "item", - context: loader.cm.SelectionContext() - }); - - test.withTestDoc(function (window, doc) { - let link = doc.getElementById("targetlink"); - link.click(); - - let tablistener = event => { - this.tabBrowser.tabContainer.removeEventListener("TabOpen", tablistener, false); - let tab = event.target; - let browser = tab.linkedBrowser; - this.loadFrameScript(browser); - this.delayedEventListener(browser, "load", () => { - let window = browser.contentWindow; - let doc = browser.contentDocument; - window.getSelection().selectAllChildren(doc.body); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - popup.hidePopup(); - - test.tabBrowser.removeTab(test.tabBrowser.selectedTab); - test.tabBrowser.selectedTab = test.tab; - - test.showMenu(null, function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); - }); - }, true); - }; - this.tabBrowser.tabContainer.addEventListener("TabOpen", tablistener, false); - }); -}; - - -// Selection contexts should work when right clicking a form button -exports.testSelectionContextButtonMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "item", - context: loader.cm.SelectionContext() - }); - - test.withTestDoc(function (window, doc) { - window.getSelection().selectAllChildren(doc.body); - test.showMenu("#button", function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); -}; - - -//Selection contexts should work when right clicking a form button -exports.testSelectionContextButtonNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "item", - context: loader.cm.SelectionContext() - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#button", function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); - }); -}; - - -// URL contexts should cause items to appear on pages that match. -exports.testURLContextMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - loader.cm.Item({ - label: "item 0", - context: loader.cm.URLContext(TEST_DOC_URL) - }), - loader.cm.Item({ - label: "item 1", - context: loader.cm.URLContext([TEST_DOC_URL, "*.bogus.com"]) - }), - loader.cm.Item({ - label: "item 2", - context: loader.cm.URLContext([new RegExp(".*\\.html")]) - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// URL contexts should not cause items to appear on pages that do not match. -exports.testURLContextNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - loader.cm.Item({ - label: "item 0", - context: loader.cm.URLContext("*.bogus.com") - }), - loader.cm.Item({ - label: "item 1", - context: loader.cm.URLContext(["*.bogus.com", "*.gnarly.com"]) - }), - loader.cm.Item({ - label: "item 2", - context: loader.cm.URLContext([new RegExp(".*\\.js")]) - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, items, []); - test.done(); - }); - }); -}; - - -// Loading a new page in the same tab should correctly start a new worker for -// any content scripts -exports.testPageReload = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ - label: "Item", - contentScript: "var doc = document; self.on('context', node => doc.body.getAttribute('showItem') == 'true');" - }); - - test.withTestDoc(function (window, doc) { - // Set a flag on the document that the item uses - doc.body.setAttribute("showItem", "true"); - - test.showMenu(null, function (popup) { - // With the attribute true the item should be visible in the menu - test.checkMenu([item], [], []); - test.hideMenu(function() { - let browser = this.tabBrowser.getBrowserForTab(this.tab) - test.delayedEventListener(browser, "load", function() { - test.delayedEventListener(browser, "load", function() { - window = browser.contentWindow; - doc = window.document; - - // Set a flag on the document that the item uses - doc.body.setAttribute("showItem", "false"); - - test.showMenu(null, function (popup) { - // In the new document with the attribute false the item should be - // hidden, but if the contentScript hasn't been reloaded it will - // still see the old value - test.checkMenu([item], [item], []); - - test.done(); - }); - }, true); - browser.loadURI(TEST_DOC_URL, null, null); - }, true); - // Required to make sure we load a new page in history rather than - // just reloading the current page which would unload it - browser.loadURI("about:blank", null, null); - }); - }); - }); -}; - -// Closing a page after it's been used with a worker should cause the worker -// to be destroyed -/*exports.testWorkerDestroy = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let loadExpected = false; - - let item = loader.cm.Item({ - label: "item", - contentScript: 'self.postMessage("loaded"); self.on("detach", function () { console.log("saw detach"); self.postMessage("detach") });', - onMessage: function (msg) { - switch (msg) { - case "loaded": - assert.ok(loadExpected, "Should have seen the load event at the right time"); - loadExpected = false; - break; - case "detach": - test.done(); - break; - } - } - }); - - test.withTestDoc(function (window, doc) { - loadExpected = true; - test.showMenu(null, function (popup) { - assert.ok(!loadExpected, "Should have seen a message"); - - test.checkMenu([item], [], []); - - test.closeTab(); - }); - }); -};*/ - - -// Content contexts that return true should cause their items to be present -// in the menu. -exports.testContentContextMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => true);' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); -}; - - -// Content contexts that return false should cause their items to be absent -// from the menu. -exports.testContentContextNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => false);' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); -}; - - -// Content contexts that return undefined should cause their items to be absent -// from the menu. -exports.testContentContextUndefined = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", function () {});' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); -}; - - -// Content contexts that return an empty string should cause their items to be -// absent from the menu and shouldn't wipe the label -exports.testContentContextEmptyString = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => "");' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [item], []); - assert.equal(item.label, "item", "Label should still be correct"); - test.done(); - }); -}; - - -// If any content contexts returns true then their items should be present in -// the menu. -exports.testMultipleContentContextMatch1 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => true); ' + - 'self.on("context", () => false);', - onMessage: function() { - test.fail("Should not have called the second context listener"); - } - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); -}; - - -// If any content contexts returns true then their items should be present in -// the menu. -exports.testMultipleContentContextMatch2 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => false); ' + - 'self.on("context", () => true);' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); -}; - - -// If any content contexts returns a string then their items should be present -// in the menu. -exports.testMultipleContentContextString1 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => "new label"); ' + - 'self.on("context", () => false);' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - assert.equal(item.label, "new label", "Label should have changed"); - test.done(); - }); -}; - - -// If any content contexts returns a string then their items should be present -// in the menu. -exports.testMultipleContentContextString2 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => false); ' + - 'self.on("context", () => "new label");' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - assert.equal(item.label, "new label", "Label should have changed"); - test.done(); - }); -}; - - -// If many content contexts returns a string then the first should take effect -exports.testMultipleContentContextString3 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", () => "new label 1"); ' + - 'self.on("context", () => "new label 2");' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - assert.equal(item.label, "new label 1", "Label should have changed"); - test.done(); - }); -}; - - -// Content contexts that return true should cause their items to be present -// in the menu when context clicking an active element. -exports.testContentContextMatchActiveElement = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - new loader.cm.Item({ - label: "item 1", - contentScript: 'self.on("context", () => true);' - }), - new loader.cm.Item({ - label: "item 2", - context: undefined, - contentScript: 'self.on("context", () => true);' - }), - // These items will always be hidden by the declarative usage of PageContext - new loader.cm.Item({ - label: "item 3", - context: loader.cm.PageContext(), - contentScript: 'self.on("context", () => true);' - }), - new loader.cm.Item({ - label: "item 4", - context: [loader.cm.PageContext()], - contentScript: 'self.on("context", () => true);' - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, [items[2], items[3]], []); - test.done(); - }); - }); -}; - - -// Content contexts that return false should cause their items to be absent -// from the menu when context clicking an active element. -exports.testContentContextNoMatchActiveElement = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - new loader.cm.Item({ - label: "item 1", - contentScript: 'self.on("context", () => false);' - }), - new loader.cm.Item({ - label: "item 2", - context: undefined, - contentScript: 'self.on("context", () => false);' - }), - // These items will always be hidden by the declarative usage of PageContext - new loader.cm.Item({ - label: "item 3", - context: loader.cm.PageContext(), - contentScript: 'self.on("context", () => false);' - }), - new loader.cm.Item({ - label: "item 4", - context: [loader.cm.PageContext()], - contentScript: 'self.on("context", () => false);' - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, items, []); - test.done(); - }); - }); -}; - - -// Content contexts that return undefined should cause their items to be absent -// from the menu when context clicking an active element. -exports.testContentContextNoMatchActiveElement = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - new loader.cm.Item({ - label: "item 1", - contentScript: 'self.on("context", () => {});' - }), - new loader.cm.Item({ - label: "item 2", - context: undefined, - contentScript: 'self.on("context", () => {});' - }), - // These items will always be hidden by the declarative usage of PageContext - new loader.cm.Item({ - label: "item 3", - context: loader.cm.PageContext(), - contentScript: 'self.on("context", () => {});' - }), - new loader.cm.Item({ - label: "item 4", - context: [loader.cm.PageContext()], - contentScript: 'self.on("context", () => {});' - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, items, []); - test.done(); - }); - }); -}; - - -// Content contexts that return a string should cause their items to be present -// in the menu and the items' labels to be updated. -exports.testContentContextMatchString = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "first label", - contentScript: 'self.on("context", () => "second label");' - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - assert.equal(item.label, "second label", - "item's label should be updated"); - test.done(); - }); -}; - - -// Ensure that contentScriptFile is working correctly -exports.testContentScriptFile = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - let { defer, all } = require("sdk/core/promise"); - let itemScript = [defer(), defer()]; - let menuShown = defer(); - let menuPromises = itemScript.concat(menuShown).map(({promise}) => promise); - - // Reject remote files - assert.throws(function() { - new loader.cm.Item({ - label: "item", - contentScriptFile: "http://mozilla.com/context-menu.js" - }); - }, - /The `contentScriptFile` option must be a local URL or an array of URLs/, - "Item throws when contentScriptFile is a remote URL"); - - // But accept files from data folder - let item = new loader.cm.Item({ - label: "item", - contentScriptFile: data.url("test-contentScriptFile.js"), - onMessage: (message) => { - assert.equal(message, "msg from contentScriptFile", - "contentScriptFile loaded with absolute url"); - itemScript[0].resolve(); - } - }); - - let item2 = new loader.cm.Item({ - label: "item2", - contentScriptFile: "./test-contentScriptFile.js", - onMessage: (message) => { - assert.equal(message, "msg from contentScriptFile", - "contentScriptFile loaded with relative url"); - itemScript[1].resolve(); - } - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item, item2], [], []); - menuShown.resolve(); - }); - - all(menuPromises).then(() => test.done()); -}; - - -// The args passed to context listeners should be correct. -exports.testContentContextArgs = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - let callbacks = 0; - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'self.on("context", function (node) {' + - ' self.postMessage(node.tagName);' + - ' return false;' + - '});', - onMessage: function (tagName) { - assert.equal(tagName, "HTML", "node should be an HTML element"); - if (++callbacks == 2) test.done(); - } - }); - - test.showMenu(null, function () { - if (++callbacks == 2) test.done(); - }); -}; - -// Multiple contexts imply intersection, not union. -exports.testMultipleContexts = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - context: [loader.cm.SelectorContext("a[href]"), loader.cm.PageContext()], - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#span-link", function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); - }); -}; - -// Once a context is removed, it should no longer cause its item to appear. -exports.testRemoveContext = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let ctxt = loader.cm.SelectorContext("img"); - let item = new loader.cm.Item({ - label: "item", - context: ctxt - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - - // The item should be present at first. - test.checkMenu([item], [], []); - popup.hidePopup(); - - // Remove the img context and check again. - item.context.remove(ctxt); - test.showMenu("#image", function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); - }); - }); -}; - -// Once a context is removed, it should no longer cause its item to appear. -exports.testSetContextRemove = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let ctxt = loader.cm.SelectorContext("img"); - let item = new loader.cm.Item({ - label: "item", - context: ctxt - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - - // The item should be present at first. - test.checkMenu([item], [], []); - popup.hidePopup(); - - // Remove the img context and check again. - item.context = []; - test.showMenu("#image", function (popup) { - test.checkMenu([item], [item], []); - test.done(); - }); - }); - }); -}; - -// Once a context is added, it should affect whether the item appears. -exports.testAddContext = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let ctxt = loader.cm.SelectorContext("img"); - let item = new loader.cm.Item({ - label: "item" - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - - // The item should not be present at first. - test.checkMenu([item], [item], []); - popup.hidePopup(); - - // Add the img context and check again. - item.context.add(ctxt); - test.showMenu("#image", function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); - }); -}; - -// Once a context is added, it should affect whether the item appears. -exports.testSetContextAdd = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let ctxt = loader.cm.SelectorContext("img"); - let item = new loader.cm.Item({ - label: "item" - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - - // The item should not be present at first. - test.checkMenu([item], [item], []); - popup.hidePopup(); - - // Add the img context and check again. - item.context = [ctxt]; - test.showMenu("#image", function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); - }); -}; - -// Lots of items should overflow into the overflow submenu. -exports.testOverflow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = []; - for (let i = 0; i < OVERFLOW_THRESH_DEFAULT + 1; i++) { - let item = new loader.cm.Item({ label: "item " + i }); - items.push(item); - } - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); -}; - - -// Module unload should cause all items to be removed. -exports.testUnload = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ label: "item" }); - - test.showMenu(null, function (popup) { - - // The menu should contain the item. - test.checkMenu([item], [], []); - popup.hidePopup(); - - // Unload the module. - loader.unload(); - test.showMenu(null, function (popup) { - - // The item should be removed from the menu. - test.checkMenu([item], [], [item]); - test.done(); - }); - }); -}; - - -// Using multiple module instances to add items without causing overflow should -// work OK. Assumes OVERFLOW_THRESH_DEFAULT >= 2. -exports.testMultipleModulesAdd = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - // Use each module to add an item, then unload each module in turn. - let item0 = new loader0.cm.Item({ label: "item 0" }); - let item1 = new loader1.cm.Item({ label: "item 1" }); - - test.showMenu(null, function (popup) { - - // The menu should contain both items. - test.checkMenu([item0, item1], [], []); - popup.hidePopup(); - - // Unload the first module. - loader0.unload(); - test.showMenu(null, function (popup) { - - // The first item should be removed from the menu. - test.checkMenu([item0, item1], [], [item0]); - popup.hidePopup(); - - // Unload the second module. - loader1.unload(); - test.showMenu(null, function (popup) { - - // Both items should be removed from the menu. - test.checkMenu([item0, item1], [], [item0, item1]); - test.done(); - }); - }); - }); -}; - - -// Using multiple module instances to add items causing overflow should work OK. -exports.testMultipleModulesAddOverflow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - // Use module 0 to add OVERFLOW_THRESH_DEFAULT items. - let items0 = []; - for (let i = 0; i < OVERFLOW_THRESH_DEFAULT; i++) { - let item = new loader0.cm.Item({ label: "item 0 " + i }); - items0.push(item); - } - - // Use module 1 to add one item. - let item1 = new loader1.cm.Item({ label: "item 1" }); - - let allItems = items0.concat(item1); - - test.showMenu(null, function (popup) { - - // The menu should contain all items in overflow. - test.checkMenu(allItems, [], []); - popup.hidePopup(); - - // Unload the first module. - loader0.unload(); - test.showMenu(null, function (popup) { - - // The first items should be removed from the menu, which should not - // overflow. - test.checkMenu(allItems, [], items0); - popup.hidePopup(); - - // Unload the second module. - loader1.unload(); - test.showMenu(null, function (popup) { - - // All items should be removed from the menu. - test.checkMenu(allItems, [], allItems); - test.done(); - }); - }); - }); -}; - - -// Using multiple module instances to modify the menu without causing overflow -// should work OK. This test creates two loaders and: -// loader0 create item -> loader1 create item -> loader0.unload -> -// loader1.unload -exports.testMultipleModulesDiffContexts1 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let item0 = new loader0.cm.Item({ - label: "item 0", - context: loader0.cm.SelectorContext("img") - }); - - let item1 = new loader1.cm.Item({ label: "item 1" }); - - test.showMenu(null, function (popup) { - - // The menu should contain item1. - test.checkMenu([item0, item1], [item0], []); - popup.hidePopup(); - - // Unload module 0. - loader0.unload(); - test.showMenu(null, function (popup) { - - // item0 should be removed from the menu. - test.checkMenu([item0, item1], [], [item0]); - popup.hidePopup(); - - // Unload module 1. - loader1.unload(); - test.showMenu(null, function (popup) { - - // Both items should be removed from the menu. - test.checkMenu([item0, item1], [], [item0, item1]); - test.done(); - }); - }); - }); -}; - - -// Using multiple module instances to modify the menu without causing overflow -// should work OK. This test creates two loaders and: -// loader1 create item -> loader0 create item -> loader0.unload -> -// loader1.unload -exports.testMultipleModulesDiffContexts2 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let item1 = new loader1.cm.Item({ label: "item 1" }); - - let item0 = new loader0.cm.Item({ - label: "item 0", - context: loader0.cm.SelectorContext("img") - }); - - test.showMenu(null, function (popup) { - - // The menu should contain item1. - test.checkMenu([item0, item1], [item0], []); - popup.hidePopup(); - - // Unload module 0. - loader0.unload(); - test.showMenu(null, function (popup) { - - // item0 should be removed from the menu. - test.checkMenu([item0, item1], [], [item0]); - popup.hidePopup(); - - // Unload module 1. - loader1.unload(); - test.showMenu(null, function (popup) { - - // Both items should be removed from the menu. - test.checkMenu([item0, item1], [], [item0, item1]); - test.done(); - }); - }); - }); -}; - - -// Using multiple module instances to modify the menu without causing overflow -// should work OK. This test creates two loaders and: -// loader0 create item -> loader1 create item -> loader1.unload -> -// loader0.unload -exports.testMultipleModulesDiffContexts3 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let item0 = new loader0.cm.Item({ - label: "item 0", - context: loader0.cm.SelectorContext("img") - }); - - let item1 = new loader1.cm.Item({ label: "item 1" }); - - test.showMenu(null, function (popup) { - - // The menu should contain item1. - test.checkMenu([item0, item1], [item0], []); - popup.hidePopup(); - - // Unload module 1. - loader1.unload(); - test.showMenu(null, function (popup) { - - // item1 should be removed from the menu. - test.checkMenu([item0, item1], [item0], [item1]); - popup.hidePopup(); - - // Unload module 0. - loader0.unload(); - test.showMenu(null, function (popup) { - - // Both items should be removed from the menu. - test.checkMenu([item0, item1], [], [item0, item1]); - test.done(); - }); - }); - }); -}; - - -// Using multiple module instances to modify the menu without causing overflow -// should work OK. This test creates two loaders and: -// loader1 create item -> loader0 create item -> loader1.unload -> -// loader0.unload -exports.testMultipleModulesDiffContexts4 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let item1 = new loader1.cm.Item({ label: "item 1" }); - - let item0 = new loader0.cm.Item({ - label: "item 0", - context: loader0.cm.SelectorContext("img") - }); - - test.showMenu(null, function (popup) { - - // The menu should contain item1. - test.checkMenu([item0, item1], [item0], []); - popup.hidePopup(); - - // Unload module 1. - loader1.unload(); - test.showMenu(null, function (popup) { - - // item1 should be removed from the menu. - test.checkMenu([item0, item1], [item0], [item1]); - popup.hidePopup(); - - // Unload module 0. - loader0.unload(); - test.showMenu(null, function (popup) { - - // Both items should be removed from the menu. - test.checkMenu([item0, item1], [], [item0, item1]); - test.done(); - }); - }); - }); -}; - - -// Test interactions between a loaded module, unloading another module, and the -// menu separator and overflow submenu. -exports.testMultipleModulesAddRemove = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let item = new loader0.cm.Item({ label: "item" }); - - test.showMenu(null, function (popup) { - - // The menu should contain the item. - test.checkMenu([item], [], []); - popup.hidePopup(); - - // Remove the item. - item.destroy(); - test.showMenu(null, function (popup) { - - // The item should be removed from the menu. - test.checkMenu([item], [], [item]); - popup.hidePopup(); - - // Unload module 1. - loader1.unload(); - test.showMenu(null, function (popup) { - - // There shouldn't be any errors involving the menu separator or - // overflow submenu. - test.checkMenu([item], [], [item]); - test.done(); - }); - }); - }); -}; - - -// Checks that the order of menu items is correct when adding/removing across -// multiple modules. All items from a single module should remain in a group -exports.testMultipleModulesOrder = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - // Use each module to add an item, then unload each module in turn. - let item0 = new loader0.cm.Item({ label: "item 0" }); - let item1 = new loader1.cm.Item({ label: "item 1" }); - - test.showMenu(null, function (popup) { - - // The menu should contain both items. - test.checkMenu([item0, item1], [], []); - popup.hidePopup(); - - let item2 = new loader0.cm.Item({ label: "item 2" }); - - test.showMenu(null, function (popup) { - - // The new item should be grouped with the same items from loader0. - test.checkMenu([item0, item2, item1], [], []); - popup.hidePopup(); - - let item3 = new loader1.cm.Item({ label: "item 3" }); - - test.showMenu(null, function (popup) { - - // Same again - test.checkMenu([item0, item2, item1, item3], [], []); - test.done(); - }); - }); - }); -}; - - -// Checks that the order of menu items is correct when adding/removing across -// multiple modules when overflowing. All items from a single module should -// remain in a group -exports.testMultipleModulesOrderOverflow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let prefs = loader0.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 0); - - // Use each module to add an item, then unload each module in turn. - let item0 = new loader0.cm.Item({ label: "item 0" }); - let item1 = new loader1.cm.Item({ label: "item 1" }); - - test.showMenu(null, function (popup) { - - // The menu should contain both items. - test.checkMenu([item0, item1], [], []); - popup.hidePopup(); - - let item2 = new loader0.cm.Item({ label: "item 2" }); - - test.showMenu(null, function (popup) { - - // The new item should be grouped with the same items from loader0. - test.checkMenu([item0, item2, item1], [], []); - popup.hidePopup(); - - let item3 = new loader1.cm.Item({ label: "item 3" }); - - test.showMenu(null, function (popup) { - - // Same again - test.checkMenu([item0, item2, item1, item3], [], []); - test.done(); - }); - }); - }); -}; - - -// Checks that if a module's items are all hidden then the overflow menu doesn't -// get hidden -exports.testMultipleModulesOverflowHidden = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let prefs = loader0.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 0); - - // Use each module to add an item, then unload each module in turn. - let item0 = new loader0.cm.Item({ label: "item 0" }); - let item1 = new loader1.cm.Item({ - label: "item 1", - context: loader1.cm.SelectorContext("a") - }); - - test.showMenu(null, function (popup) { - // One should be hidden - test.checkMenu([item0, item1], [item1], []); - test.done(); - }); -}; - - -// Checks that if a module's items are all hidden then the overflow menu doesn't -// get hidden (reverse order to above) -exports.testMultipleModulesOverflowHidden2 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let prefs = loader0.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 0); - - // Use each module to add an item, then unload each module in turn. - let item0 = new loader0.cm.Item({ - label: "item 0", - context: loader0.cm.SelectorContext("a") - }); - let item1 = new loader1.cm.Item({ label: "item 1" }); - - test.showMenu(null, function (popup) { - // One should be hidden - test.checkMenu([item0, item1], [item0], []); - test.done(); - }); -}; - - -// Checks that we don't overflow if there are more items than the overflow -// threshold but not all of them are visible -exports.testOverflowIgnoresHidden = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let prefs = loader.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 2); - - let allItems = [ - new loader.cm.Item({ - label: "item 0" - }), - new loader.cm.Item({ - label: "item 1" - }), - new loader.cm.Item({ - label: "item 2", - context: loader.cm.SelectorContext("a") - }) - ]; - - test.showMenu(null, function (popup) { - // One should be hidden - test.checkMenu(allItems, [allItems[2]], []); - test.done(); - }); -}; - - -// Checks that we don't overflow if there are more items than the overflow -// threshold but not all of them are visible -exports.testOverflowIgnoresHiddenMultipleModules1 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let prefs = loader0.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 2); - - let allItems = [ - new loader0.cm.Item({ - label: "item 0" - }), - new loader0.cm.Item({ - label: "item 1" - }), - new loader1.cm.Item({ - label: "item 2", - context: loader1.cm.SelectorContext("a") - }), - new loader1.cm.Item({ - label: "item 3", - context: loader1.cm.SelectorContext("a") - }) - ]; - - test.showMenu(null, function (popup) { - // One should be hidden - test.checkMenu(allItems, [allItems[2], allItems[3]], []); - test.done(); - }); -}; - - -// Checks that we don't overflow if there are more items than the overflow -// threshold but not all of them are visible -exports.testOverflowIgnoresHiddenMultipleModules2 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let prefs = loader0.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 2); - - let allItems = [ - new loader0.cm.Item({ - label: "item 0" - }), - new loader0.cm.Item({ - label: "item 1", - context: loader0.cm.SelectorContext("a") - }), - new loader1.cm.Item({ - label: "item 2" - }), - new loader1.cm.Item({ - label: "item 3", - context: loader1.cm.SelectorContext("a") - }) - ]; - - test.showMenu(null, function (popup) { - // One should be hidden - test.checkMenu(allItems, [allItems[1], allItems[3]], []); - test.done(); - }); -}; - - -// Checks that we don't overflow if there are more items than the overflow -// threshold but not all of them are visible -exports.testOverflowIgnoresHiddenMultipleModules3 = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let prefs = loader0.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 2); - - let allItems = [ - new loader0.cm.Item({ - label: "item 0", - context: loader0.cm.SelectorContext("a") - }), - new loader0.cm.Item({ - label: "item 1", - context: loader0.cm.SelectorContext("a") - }), - new loader1.cm.Item({ - label: "item 2" - }), - new loader1.cm.Item({ - label: "item 3" - }) - ]; - - test.showMenu(null, function (popup) { - // One should be hidden - test.checkMenu(allItems, [allItems[0], allItems[1]], []); - test.done(); - }); -}; - - -// Tests that we transition between overflowing to non-overflowing to no items -// and back again -exports.testOverflowTransition = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let prefs = loader.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 2); - - let pItems = [ - new loader.cm.Item({ - label: "item 0", - context: loader.cm.SelectorContext("p") - }), - new loader.cm.Item({ - label: "item 1", - context: loader.cm.SelectorContext("p") - }) - ]; - - let aItems = [ - new loader.cm.Item({ - label: "item 2", - context: loader.cm.SelectorContext("a") - }), - new loader.cm.Item({ - label: "item 3", - context: loader.cm.SelectorContext("a") - }) - ]; - - let allItems = pItems.concat(aItems); - - test.withTestDoc(function (window, doc) { - test.showMenu("#link", function (popup) { - // The menu should contain all items and will overflow - test.checkMenu(allItems, [], []); - popup.hidePopup(); - - test.showMenu("#text", function (popup) { - // Only contains hald the items and will not overflow - test.checkMenu(allItems, aItems, []); - popup.hidePopup(); - - test.showMenu(null, function (popup) { - // None of the items will be visible - test.checkMenu(allItems, allItems, []); - popup.hidePopup(); - - test.showMenu("#text", function (popup) { - // Only contains hald the items and will not overflow - test.checkMenu(allItems, aItems, []); - popup.hidePopup(); - - test.showMenu("#link", function (popup) { - // The menu should contain all items and will overflow - test.checkMenu(allItems, [], []); - popup.hidePopup(); - - test.showMenu(null, function (popup) { - // None of the items will be visible - test.checkMenu(allItems, allItems, []); - popup.hidePopup(); - - test.showMenu("#link", function (popup) { - // The menu should contain all items and will overflow - test.checkMenu(allItems, [], []); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -}; - - -// An item's command listener should work. -exports.testItemCommand = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - data: "item data", - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function (data) { - assert.equal(this, item, "`this` inside onMessage should be item"); - assert.equal(data.tagName, "HTML", "node should be an HTML element"); - assert.equal(data.data, item.data, "data should be item data"); - test.done(); - } - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - let elt = test.getItemElt(popup, item); - - // create a command event - let evt = elt.ownerDocument.createEvent('Event'); - evt.initEvent('command', true, true); - elt.dispatchEvent(evt); - }); -}; - - -// A menu's click listener should work and receive bubbling 'command' events from -// sub-items appropriately. This also tests menus and ensures that when a CSS -// selector context matches the clicked node's ancestor, the matching ancestor -// is passed to listeners as the clicked node. -exports.testMenuCommand = function (assert, done) { - // Create a top-level menu, submenu, and item, like this: - // topMenu -> submenu -> item - // Click the item and make sure the click bubbles. - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "submenu item", - data: "submenu item data", - context: loader.cm.SelectorContext("a"), - }); - - let submenu = new loader.cm.Menu({ - label: "submenu", - context: loader.cm.SelectorContext("a"), - items: [item] - }); - - let topMenu = new loader.cm.Menu({ - label: "top menu", - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function (data) { - assert.equal(this, topMenu, "`this` inside top menu should be menu"); - assert.equal(data.tagName, "A", "Clicked node should be anchor"); - assert.equal(data.data, item.data, - "Clicked item data should be correct"); - test.done(); - }, - items: [submenu], - context: loader.cm.SelectorContext("a") - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#span-link", function (popup) { - test.checkMenu([topMenu], [], []); - let topMenuElt = test.getItemElt(popup, topMenu); - let topMenuPopup = topMenuElt.firstChild; - let submenuElt = test.getItemElt(topMenuPopup, submenu); - let submenuPopup = submenuElt.firstChild; - let itemElt = test.getItemElt(submenuPopup, item); - - // create a command event - let evt = itemElt.ownerDocument.createEvent('Event'); - evt.initEvent('command', true, true); - itemElt.dispatchEvent(evt); - }); - }); -}; - - -// Click listeners should work when multiple modules are loaded. -exports.testItemCommandMultipleModules = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let item0 = loader0.cm.Item({ - label: "loader 0 item", - contentScript: 'self.on("click", self.postMessage);', - onMessage: function () { - test.fail("loader 0 item should not emit click event"); - } - }); - let item1 = loader1.cm.Item({ - label: "loader 1 item", - contentScript: 'self.on("click", self.postMessage);', - onMessage: function () { - test.pass("loader 1 item clicked as expected"); - test.done(); - } - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item0, item1], [], []); - let item1Elt = test.getItemElt(popup, item1); - - // create a command event - let evt = item1Elt.ownerDocument.createEvent('Event'); - evt.initEvent('command', true, true); - item1Elt.dispatchEvent(evt); - }); -}; - - - - -// An item's click listener should work. -exports.testItemClick = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - data: "item data", - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function (data) { - assert.equal(this, item, "`this` inside onMessage should be item"); - assert.equal(data.tagName, "HTML", "node should be an HTML element"); - assert.equal(data.data, item.data, "data should be item data"); - test.done(); - } - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - let elt = test.getItemElt(popup, item); - elt.click(); - }); -}; - - -// A menu's click listener should work and receive bubbling clicks from -// sub-items appropriately. This also tests menus and ensures that when a CSS -// selector context matches the clicked node's ancestor, the matching ancestor -// is passed to listeners as the clicked node. -exports.testMenuClick = function (assert, done) { - // Create a top-level menu, submenu, and item, like this: - // topMenu -> submenu -> item - // Click the item and make sure the click bubbles. - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "submenu item", - data: "submenu item data", - context: loader.cm.SelectorContext("a"), - }); - - let submenu = new loader.cm.Menu({ - label: "submenu", - context: loader.cm.SelectorContext("a"), - items: [item] - }); - - let topMenu = new loader.cm.Menu({ - label: "top menu", - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function (data) { - assert.equal(this, topMenu, "`this` inside top menu should be menu"); - assert.equal(data.tagName, "A", "Clicked node should be anchor"); - assert.equal(data.data, item.data, - "Clicked item data should be correct"); - test.done(); - }, - items: [submenu], - context: loader.cm.SelectorContext("a") - }); - - test.withTestDoc(function (window, doc) { - test.showMenu("#span-link", function (popup) { - test.checkMenu([topMenu], [], []); - let topMenuElt = test.getItemElt(popup, topMenu); - let topMenuPopup = topMenuElt.firstChild; - let submenuElt = test.getItemElt(topMenuPopup, submenu); - let submenuPopup = submenuElt.firstChild; - let itemElt = test.getItemElt(submenuPopup, item); - itemElt.click(); - }); - }); -}; - -// Click listeners should work when multiple modules are loaded. -exports.testItemClickMultipleModules = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let item0 = loader0.cm.Item({ - label: "loader 0 item", - contentScript: 'self.on("click", self.postMessage);', - onMessage: function () { - test.fail("loader 0 item should not emit click event"); - } - }); - let item1 = loader1.cm.Item({ - label: "loader 1 item", - contentScript: 'self.on("click", self.postMessage);', - onMessage: function () { - test.pass("loader 1 item clicked as expected"); - test.done(); - } - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item0, item1], [], []); - let item1Elt = test.getItemElt(popup, item1); - item1Elt.click(); - }); -}; - - -// Adding a separator to a submenu should work OK. -exports.testSeparator = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let menu = new loader.cm.Menu({ - label: "submenu", - items: [new loader.cm.Separator()] - }); - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], []); - test.done(); - }); -}; - - -// The parentMenu option should work -exports.testParentMenu = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let menu = new loader.cm.Menu({ - label: "submenu", - items: [loader.cm.Item({ label: "item 1" })], - parentMenu: loader.cm.contentContextMenu - }); - - let item = loader.cm.Item({ - label: "item 2", - parentMenu: menu, - }); - - assert.equal(menu.items[1], item, "Item should be in the sub menu"); - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], []); - test.done(); - }); -}; - - -// Existing context menu modifications should apply to new windows. -exports.testNewWindow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ label: "item" }); - - test.withNewWindow(function () { - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); -}; - - -// When a new window is opened, items added by an unloaded module should not -// be present in the menu. -exports.testNewWindowMultipleModules = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - let item = new loader.cm.Item({ label: "item" }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - popup.hidePopup(); - loader.unload(); - test.withNewWindow(function () { - test.showMenu(null, function (popup) { - test.checkMenu([item], [], [item]); - test.done(); - }); - }); - }); -}; - - -// Existing context menu modifications should not apply to new private windows. -exports.testNewPrivateWindow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ label: "item" }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - popup.hidePopup(); - - test.withNewPrivateWindow(function () { - test.showMenu(null, function (popup) { - test.checkMenu([], [], []); - test.done(); - }); - }); - }); -}; - - -// Existing context menu modifications should apply to new private windows when -// private browsing support is enabled. -exports.testNewPrivateEnabledWindow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newPrivateLoader(); - - let item = new loader.cm.Item({ label: "item" }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - popup.hidePopup(); - - test.withNewPrivateWindow(function () { - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); - }); -}; - - -// Existing context menu modifications should apply to new private windows when -// private browsing support is enabled unless unloaded. -exports.testNewPrivateEnabledWindowUnloaded = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newPrivateLoader(); - - let item = new loader.cm.Item({ label: "item" }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - popup.hidePopup(); - - loader.unload(); - - test.withNewPrivateWindow(function () { - test.showMenu(null, function (popup) { - test.checkMenu([], [], []); - test.done(); - }); - }); - }); -}; - - -// Items in the context menu should be sorted according to locale. -exports.testSorting = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - // Make an unsorted items list. It'll look like this: - // item 1, item 0, item 3, item 2, item 5, item 4, ... - let items = []; - for (let i = 0; i < OVERFLOW_THRESH_DEFAULT; i += 2) { - items.push(new loader.cm.Item({ label: "item " + (i + 1) })); - items.push(new loader.cm.Item({ label: "item " + i })); - } - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); -}; - - -// Items in the overflow menu should be sorted according to locale. -exports.testSortingOverflow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - // Make an unsorted items list. It'll look like this: - // item 1, item 0, item 3, item 2, item 5, item 4, ... - let items = []; - for (let i = 0; i < OVERFLOW_THRESH_DEFAULT * 2; i += 2) { - items.push(new loader.cm.Item({ label: "item " + (i + 1) })); - items.push(new loader.cm.Item({ label: "item " + i })); - } - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); -}; - - -// Multiple modules shouldn't interfere with sorting. -exports.testSortingMultipleModules = function (assert, done) { - let test = new TestHelper(assert, done); - let loader0 = test.newLoader(); - let loader1 = test.newLoader(); - - let items0 = []; - let items1 = []; - for (let i = 0; i < OVERFLOW_THRESH_DEFAULT; i++) { - if (i % 2) { - let item = new loader0.cm.Item({ label: "item " + i }); - items0.push(item); - } - else { - let item = new loader1.cm.Item({ label: "item " + i }); - items1.push(item); - } - } - let allItems = items0.concat(items1); - - test.showMenu(null, function (popup) { - - // All items should be present and sorted. - test.checkMenu(allItems, [], []); - popup.hidePopup(); - loader0.unload(); - loader1.unload(); - test.showMenu(null, function (popup) { - - // All items should be removed. - test.checkMenu(allItems, [], allItems); - test.done(); - }); - }); -}; - - -// Content click handlers and context handlers should be able to communicate, -// i.e., they're eval'ed in the same worker and sandbox. -exports.testContentCommunication = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ - label: "item", - contentScript: 'var potato;' + - 'self.on("context", function () {' + - ' potato = "potato";' + - ' return true;' + - '});' + - 'self.on("click", function () {' + - ' self.postMessage(potato);' + - '});', - }); - - item.on("message", function (data) { - assert.equal(data, "potato", "That's a lot of potatoes!"); - test.done(); - }); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - let elt = test.getItemElt(popup, item); - elt.click(); - }); -}; - - -// When the context menu is invoked on a tab that was already open when the -// module was loaded, it should contain the expected items and content workers -// should function as expected. -exports.testLoadWithOpenTab = function (assert, done) { - let test = new TestHelper(assert, done); - test.withTestDoc(function (window, doc) { - let loader = test.newLoader(); - let item = new loader.cm.Item({ - label: "item", - contentScript: - 'self.on("click", () => self.postMessage("click"));', - onMessage: function (msg) { - if (msg === "click") - test.done(); - } - }); - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.getItemElt(popup, item).click(); - }); - }); -}; - -// Bug 732716: Ensure that the node given in `click` event works fine -// (i.e. is correctly wrapped) -exports.testDrawImageOnClickNode = function (assert, done) { - let test = new TestHelper(assert, done); - test.withTestDoc(function (window, doc) { - let loader = test.newLoader(); - let item = new loader.cm.Item({ - label: "item", - context: loader.cm.SelectorContext("img"), - contentScript: "new " + function() { - self.on("click", function (img, data) { - let ctx = document.createElement("canvas").getContext("2d"); - ctx.drawImage(img, 1, 1, 1, 1); - self.postMessage("done"); - }); - }, - onMessage: function (msg) { - if (msg === "done") - test.done(); - } - }); - test.showMenu("#image", function (popup) { - test.checkMenu([item], [], []); - test.getItemElt(popup, item).click(); - }); - }); -}; - - -// Setting an item's label before the menu is ever shown should correctly change -// its label. -exports.testSetLabelBeforeShow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - new loader.cm.Item({ label: "a" }), - new loader.cm.Item({ label: "b" }) - ] - items[0].label = "z"; - assert.equal(items[0].label, "z"); - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); -}; - - -// Setting an item's label after the menu is shown should correctly change its -// label. -exports.testSetLabelAfterShow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - new loader.cm.Item({ label: "a" }), - new loader.cm.Item({ label: "b" }) - ]; - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - popup.hidePopup(); - - items[0].label = "z"; - assert.equal(items[0].label, "z"); - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Setting an item's label before the menu is ever shown should correctly change -// its label. -exports.testSetLabelBeforeShowOverflow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let prefs = loader.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 0); - - let items = [ - new loader.cm.Item({ label: "a" }), - new loader.cm.Item({ label: "b" }) - ] - items[0].label = "z"; - assert.equal(items[0].label, "z"); - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); -}; - - -// Setting an item's label after the menu is shown should correctly change its -// label. -exports.testSetLabelAfterShowOverflow = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let prefs = loader.loader.require("sdk/preferences/service"); - prefs.set(OVERFLOW_THRESH_PREF, 0); - - let items = [ - new loader.cm.Item({ label: "a" }), - new loader.cm.Item({ label: "b" }) - ]; - - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - popup.hidePopup(); - - items[0].label = "z"; - assert.equal(items[0].label, "z"); - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Setting the label of an item in a Menu should work. -exports.testSetLabelMenuItem = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let menu = loader.cm.Menu({ - label: "menu", - items: [loader.cm.Item({ label: "a" })] - }); - menu.items[0].label = "z"; - - assert.equal(menu.items[0].label, "z"); - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], []); - test.done(); - }); -}; - - -// Menu.addItem() should work. -exports.testMenuAddItem = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let menu = loader.cm.Menu({ - label: "menu", - items: [ - loader.cm.Item({ label: "item 0" }) - ] - }); - menu.addItem(loader.cm.Item({ label: "item 1" })); - menu.addItem(loader.cm.Item({ label: "item 2" })); - - assert.equal(menu.items.length, 3, - "menu should have correct number of items"); - for (let i = 0; i < 3; i++) { - assert.equal(menu.items[i].label, "item " + i, - "item label should be correct"); - assert.equal(menu.items[i].parentMenu, menu, - "item's parent menu should be correct"); - } - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], []); - test.done(); - }); -}; - - -// Adding the same item twice to a menu should work as expected. -exports.testMenuAddItemTwice = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let menu = loader.cm.Menu({ - label: "menu", - items: [] - }); - let subitem = loader.cm.Item({ label: "item 1" }) - menu.addItem(subitem); - menu.addItem(loader.cm.Item({ label: "item 0" })); - menu.addItem(subitem); - - assert.equal(menu.items.length, 2, - "menu should have correct number of items"); - for (let i = 0; i < 2; i++) { - assert.equal(menu.items[i].label, "item " + i, - "item label should be correct"); - } - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], []); - test.done(); - }); -}; - - -// Menu.removeItem() should work. -exports.testMenuRemoveItem = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let subitem = loader.cm.Item({ label: "item 1" }); - let menu = loader.cm.Menu({ - label: "menu", - items: [ - loader.cm.Item({ label: "item 0" }), - subitem, - loader.cm.Item({ label: "item 2" }) - ] - }); - - // Removing twice should be harmless. - menu.removeItem(subitem); - menu.removeItem(subitem); - - assert.equal(subitem.parentMenu, null, - "item's parent menu should be correct"); - - assert.equal(menu.items.length, 2, - "menu should have correct number of items"); - assert.equal(menu.items[0].label, "item 0", - "item label should be correct"); - assert.equal(menu.items[1].label, "item 2", - "item label should be correct"); - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], []); - test.done(); - }); -}; - - -// Adding an item currently contained in one menu to another menu should work. -exports.testMenuItemSwap = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let subitem = loader.cm.Item({ label: "item" }); - let menu0 = loader.cm.Menu({ - label: "menu 0", - items: [subitem] - }); - let menu1 = loader.cm.Menu({ - label: "menu 1", - items: [] - }); - menu1.addItem(subitem); - - assert.equal(menu0.items.length, 0, - "menu should have correct number of items"); - - assert.equal(menu1.items.length, 1, - "menu should have correct number of items"); - assert.equal(menu1.items[0].label, "item", - "item label should be correct"); - - assert.equal(subitem.parentMenu, menu1, - "item's parent menu should be correct"); - - test.showMenu(null, function (popup) { - test.checkMenu([menu0, menu1], [menu0], []); - test.done(); - }); -}; - - -// Destroying an item should remove it from its parent menu. -exports.testMenuItemDestroy = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let subitem = loader.cm.Item({ label: "item" }); - let menu = loader.cm.Menu({ - label: "menu", - items: [subitem] - }); - subitem.destroy(); - - assert.equal(menu.items.length, 0, - "menu should have correct number of items"); - assert.equal(subitem.parentMenu, null, - "item's parent menu should be correct"); - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [menu], []); - test.done(); - }); -}; - - -// Setting Menu.items should work. -exports.testMenuItemsSetter = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let menu = loader.cm.Menu({ - label: "menu", - items: [ - loader.cm.Item({ label: "old item 0" }), - loader.cm.Item({ label: "old item 1" }) - ] - }); - menu.items = [ - loader.cm.Item({ label: "new item 0" }), - loader.cm.Item({ label: "new item 1" }), - loader.cm.Item({ label: "new item 2" }) - ]; - - assert.equal(menu.items.length, 3, - "menu should have correct number of items"); - for (let i = 0; i < 3; i++) { - assert.equal(menu.items[i].label, "new item " + i, - "item label should be correct"); - assert.equal(menu.items[i].parentMenu, menu, - "item's parent menu should be correct"); - } - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], []); - test.done(); - }); -}; - - -// Setting Item.data should work. -exports.testItemDataSetter = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = loader.cm.Item({ label: "old item 0", data: "old" }); - item.data = "new"; - - assert.equal(item.data, "new", "item should have correct data"); - - test.showMenu(null, function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); -}; - - -// Open the test doc, load the module, make sure items appear when context- -// clicking the iframe. -exports.testAlreadyOpenIframe = function (assert, done) { - let test = new TestHelper(assert, done); - test.withTestDoc(function (window, doc) { - let loader = test.newLoader(); - let item = new loader.cm.Item({ - label: "item" - }); - test.showMenu("#iframe", function (popup) { - test.checkMenu([item], [], []); - test.done(); - }); - }); -}; - - -// Tests that a missing label throws an exception -exports.testItemNoLabel = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - try { - new loader.cm.Item({}); - assert.ok(false, "Should have seen exception"); - } - catch (e) { - assert.ok(true, "Should have seen exception"); - } - - try { - new loader.cm.Item({ label: null }); - assert.ok(false, "Should have seen exception"); - } - catch (e) { - assert.ok(true, "Should have seen exception"); - } - - try { - new loader.cm.Item({ label: undefined }); - assert.ok(false, "Should have seen exception"); - } - catch (e) { - assert.ok(true, "Should have seen exception"); - } - - try { - new loader.cm.Item({ label: "" }); - assert.ok(false, "Should have seen exception"); - } - catch (e) { - assert.ok(true, "Should have seen exception"); - } - - test.done(); -} - -/* bug 1302854 - disabled this subtest as it is intermittent -// Tests that items can have an empty data property -exports.testItemNoData = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - function checkData(data) { - assert.equal(data, undefined, "Data should be undefined"); - } - - let item1 = new loader.cm.Item({ - label: "item 1", - contentScript: 'self.on("click", (node, data) => self.postMessage(data))', - onMessage: checkData - }); - let item2 = new loader.cm.Item({ - label: "item 2", - data: null, - contentScript: 'self.on("click", (node, data) => self.postMessage(data))', - onMessage: checkData - }); - let item3 = new loader.cm.Item({ - label: "item 3", - data: undefined, - contentScript: 'self.on("click", (node, data) => self.postMessage(data))', - onMessage: checkData - }); - - assert.equal(item1.data, undefined, "Should be no defined data"); - assert.equal(item2.data, null, "Should be no defined data"); - assert.equal(item3.data, undefined, "Should be no defined data"); - - test.showMenu(null, function (popup) { - test.checkMenu([item1, item2, item3], [], []); - - let itemElt = test.getItemElt(popup, item1); - itemElt.click(); - - test.hideMenu(function() { - test.showMenu(null, function (popup) { - let itemElt = test.getItemElt(popup, item2); - itemElt.click(); - - test.hideMenu(function() { - test.showMenu(null, function (popup) { - let itemElt = test.getItemElt(popup, item3); - itemElt.click(); - - test.done(); - }); - }); - }); - }); - }); -} -*/ - - -exports.testItemNoAccessKey = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item1 = new loader.cm.Item({ label: "item 1" }); - let item2 = new loader.cm.Item({ label: "item 2", accesskey: null }); - let item3 = new loader.cm.Item({ label: "item 3", accesskey: undefined }); - - assert.equal(item1.accesskey, undefined, "Should be no defined image"); - assert.equal(item2.accesskey, null, "Should be no defined image"); - assert.equal(item3.accesskey, undefined, "Should be no defined image"); - - test.showMenu(). - then((popup) => test.checkMenu([item1, item2, item3], [], [])). - then(test.done). - catch(assert.fail); -} - - -// Test accesskey support. -exports.testItemAccessKey = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item = new loader.cm.Item({ label: "item", accesskey: "i" }); - assert.equal(item.accesskey, "i", "Should have set the image to i"); - - let menu = new loader.cm.Menu({ label: "menu", accesskey: "m", items: [ - loader.cm.Item({ label: "subitem" }) - ]}); - assert.equal(menu.accesskey, "m", "Should have set the accesskey to m"); - - test.showMenu().then((popup) => { - test.checkMenu([item, menu], [], []); - - let accesskey = "e"; - menu.accesskey = item.accesskey = accesskey; - assert.equal(item.accesskey, accesskey, "Should have set the accesskey to " + accesskey); - assert.equal(menu.accesskey, accesskey, "Should have set the accesskey to " + accesskey); - test.checkMenu([item, menu], [], []); - - item.accesskey = null; - menu.accesskey = null; - assert.equal(item.accesskey, null, "Should have set the accesskey to " + accesskey); - assert.equal(menu.accesskey, null, "Should have set the accesskey to " + accesskey); - test.checkMenu([item, menu], [], []); - }). - then(test.done). - catch(assert.fail); -}; - - -// Tests that items without an image don't attempt to show one -exports.testItemNoImage = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let item1 = new loader.cm.Item({ label: "item 1" }); - let item2 = new loader.cm.Item({ label: "item 2", image: null }); - let item3 = new loader.cm.Item({ label: "item 3", image: undefined }); - - assert.equal(item1.image, undefined, "Should be no defined image"); - assert.equal(item2.image, null, "Should be no defined image"); - assert.equal(item3.image, undefined, "Should be no defined image"); - - test.showMenu(null, function (popup) { - test.checkMenu([item1, item2, item3], [], []); - - test.done(); - }); -} - - -// Test image support. -exports.testItemImage = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let imageURL = data.url("moz_favicon.ico"); - let item = new loader.cm.Item({ label: "item", image: imageURL }); - let menu = new loader.cm.Menu({ label: "menu", image: imageURL, items: [ - loader.cm.Item({ label: "subitem" }) - ]}); - assert.equal(item.image, imageURL, "Should have set the image correctly"); - assert.equal(menu.image, imageURL, "Should have set the image correctly"); - - test.showMenu(null, function (popup) { - test.checkMenu([item, menu], [], []); - - let imageURL2 = data.url("dummy.ico"); - item.image = imageURL2; - menu.image = imageURL2; - assert.equal(item.image, imageURL2, "Should have set the image correctly"); - assert.equal(menu.image, imageURL2, "Should have set the image correctly"); - test.checkMenu([item, menu], [], []); - - item.image = null; - menu.image = null; - assert.equal(item.image, null, "Should have set the image correctly"); - assert.equal(menu.image, null, "Should have set the image correctly"); - test.checkMenu([item, menu], [], []); - - test.done(); - }); -}; - -// Test image URL validation. -exports.testItemImageValidURL = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - assert.throws(function(){ - new loader.cm.Item({ - label: "item 1", - image: "foo" - }) - }, /Image URL validation failed/ - ); - - assert.throws(function(){ - new loader.cm.Item({ - label: "item 2", - image: false - }) - }, /Image URL validation failed/ - ); - - assert.throws(function(){ - new loader.cm.Item({ - label: "item 3", - image: 0 - }) - }, /Image URL validation failed/ - ); - - let imageURL = data.url("moz_favicon.ico"); - let item4 = new loader.cm.Item({ label: "item 4", image: imageURL }); - let item5 = new loader.cm.Item({ label: "item 5", image: null }); - let item6 = new loader.cm.Item({ label: "item 6", image: undefined }); - - assert.equal(item4.image, imageURL, "Should be proper image URL"); - assert.equal(item5.image, null, "Should be null image"); - assert.equal(item6.image, undefined, "Should be undefined image"); - - test.done(); -}; - - -// Menu.destroy should destroy the item tree rooted at that menu. -exports.testMenuDestroy = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let menu = loader.cm.Menu({ - label: "menu", - items: [ - loader.cm.Item({ label: "item 0" }), - loader.cm.Menu({ - label: "item 1", - items: [ - loader.cm.Item({ label: "subitem 0" }), - loader.cm.Item({ label: "subitem 1" }), - loader.cm.Item({ label: "subitem 2" }) - ] - }), - loader.cm.Item({ label: "item 2" }) - ] - }); - menu.destroy(); - - /*let numRegistryEntries = 0; - loader.globalScope.browserManager.browserWins.forEach(function (bwin) { - for (let itemID in bwin.items) - numRegistryEntries++; - }); - assert.equal(numRegistryEntries, 0, "All items should be unregistered.");*/ - - test.showMenu(null, function (popup) { - test.checkMenu([menu], [], [menu]); - test.done(); - }); -}; - -// Checks that if a menu contains sub items that are hidden then the menu is -// hidden too. Also checks that content scripts and contexts work for sub items. -exports.testSubItemContextNoMatchHideMenu = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - loader.cm.Menu({ - label: "menu 1", - items: [ - loader.cm.Item({ - label: "subitem 1", - context: loader.cm.SelectorContext(".foo") - }) - ] - }), - loader.cm.Menu({ - label: "menu 2", - items: [ - loader.cm.Item({ - label: "subitem 2", - contentScript: 'self.on("context", () => false);' - }) - ] - }), - loader.cm.Menu({ - label: "menu 3", - items: [ - loader.cm.Item({ - label: "subitem 3", - context: loader.cm.SelectorContext(".foo") - }), - loader.cm.Item({ - label: "subitem 4", - contentScript: 'self.on("context", () => false);' - }) - ] - }) - ]; - - test.showMenu(null, function (popup) { - test.checkMenu(items, items, []); - test.done(); - }); -}; - - -// Checks that if a menu contains a combination of hidden and visible sub items -// then the menu is still visible too. -exports.testSubItemContextMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let hiddenItems = [ - loader.cm.Item({ - label: "subitem 3", - context: loader.cm.SelectorContext(".foo") - }), - loader.cm.Item({ - label: "subitem 6", - contentScript: 'self.on("context", () => false);' - }) - ]; - - let items = [ - loader.cm.Menu({ - label: "menu 1", - items: [ - loader.cm.Item({ - label: "subitem 1", - context: loader.cm.URLContext(TEST_DOC_URL) - }) - ] - }), - loader.cm.Menu({ - label: "menu 2", - items: [ - loader.cm.Item({ - label: "subitem 2", - contentScript: 'self.on("context", () => true);' - }) - ] - }), - loader.cm.Menu({ - label: "menu 3", - items: [ - hiddenItems[0], - loader.cm.Item({ - label: "subitem 4", - contentScript: 'self.on("context", () => true);' - }) - ] - }), - loader.cm.Menu({ - label: "menu 4", - items: [ - loader.cm.Item({ - label: "subitem 5", - context: loader.cm.URLContext(TEST_DOC_URL) - }), - hiddenItems[1] - ] - }), - loader.cm.Menu({ - label: "menu 5", - items: [ - loader.cm.Item({ - label: "subitem 7", - context: loader.cm.URLContext(TEST_DOC_URL) - }), - loader.cm.Item({ - label: "subitem 8", - contentScript: 'self.on("context", () => true);' - }) - ] - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, hiddenItems, []); - test.done(); - }); - }); -}; - - -// Child items should default to visible, not to PageContext -exports.testSubItemDefaultVisible = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [ - loader.cm.Menu({ - label: "menu 1", - context: loader.cm.SelectorContext("img"), - items: [ - loader.cm.Item({ - label: "subitem 1" - }), - loader.cm.Item({ - label: "subitem 2", - context: loader.cm.SelectorContext("img") - }), - loader.cm.Item({ - label: "subitem 3", - context: loader.cm.SelectorContext("a") - }) - ] - }) - ]; - - // subitem 3 will be hidden - let hiddenItems = [items[0].items[2]]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, hiddenItems, []); - test.done(); - }); - }); -}; - -// Tests that the click event on sub menuitem -// tiggers the click event for the sub menuitem and the parent menu -exports.testSubItemClick = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let state = 0; - - let items = [ - loader.cm.Menu({ - label: "menu 1", - items: [ - loader.cm.Item({ - label: "subitem 1", - data: "foobar", - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function(msg) { - assert.equal(msg.tagName, "HTML", "should have seen the right node"); - assert.equal(msg.data, "foobar", "should have seen the right data"); - assert.equal(state, 0, "should have seen the event at the right time"); - state++; - } - }) - ], - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function(msg) { - assert.equal(msg.tagName, "HTML", "should have seen the right node"); - assert.equal(msg.data, "foobar", "should have seen the right data"); - assert.equal(state, 1, "should have seen the event at the right time"); - - test.done(); - } - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - - let topMenuElt = test.getItemElt(popup, items[0]); - let topMenuPopup = topMenuElt.firstChild; - let itemElt = test.getItemElt(topMenuPopup, items[0].items[0]); - itemElt.click(); - }); - }); -}; - -// Tests that the command event on sub menuitem -// tiggers the click event for the sub menuitem and the parent menu -exports.testSubItemCommand = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let state = 0; - - let items = [ - loader.cm.Menu({ - label: "menu 1", - items: [ - loader.cm.Item({ - label: "subitem 1", - data: "foobar", - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function(msg) { - assert.equal(msg.tagName, "HTML", "should have seen the right node"); - assert.equal(msg.data, "foobar", "should have seen the right data"); - assert.equal(state, 0, "should have seen the event at the right time"); - state++; - } - }) - ], - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage({' + - ' tagName: node.tagName,' + - ' data: data' + - ' });' + - '});', - onMessage: function(msg) { - assert.equal(msg.tagName, "HTML", "should have seen the right node"); - assert.equal(msg.data, "foobar", "should have seen the right data"); - assert.equal(state, 1, "should have seen the event at the right time"); - state++ - - test.done(); - } - }) - ]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - - let topMenuElt = test.getItemElt(popup, items[0]); - let topMenuPopup = topMenuElt.firstChild; - let itemElt = test.getItemElt(topMenuPopup, items[0].items[0]); - - // create a command event - let evt = itemElt.ownerDocument.createEvent('Event'); - evt.initEvent('command', true, true); - itemElt.dispatchEvent(evt); - }); - }); -}; - -// Tests that opening a context menu for an outer frame when an inner frame -// has a selection doesn't activate the SelectionContext -exports.testSelectionInInnerFrameNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let state = 0; - - let items = [ - loader.cm.Item({ - label: "test item", - context: loader.cm.SelectionContext() - }) - ]; - - test.withTestDoc(function (window, doc) { - let frame = doc.getElementById("iframe"); - frame.contentWindow.getSelection().selectAllChildren(frame.contentDocument.body); - - test.showMenu(null, function (popup) { - test.checkMenu(items, items, []); - test.done(); - }); - }); -}; - -// Tests that opening a context menu for an inner frame when the inner frame -// has a selection does activate the SelectionContext -exports.testSelectionInInnerFrameMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let state = 0; - - let items = [ - loader.cm.Item({ - label: "test item", - context: loader.cm.SelectionContext() - }) - ]; - - test.withTestDoc(function (window, doc) { - let frame = doc.getElementById("iframe"); - frame.contentWindow.getSelection().selectAllChildren(frame.contentDocument.body); - - test.showMenu(["#iframe", "#text"], function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Tests that opening a context menu for an inner frame when the outer frame -// has a selection doesn't activate the SelectionContext -exports.testSelectionInOuterFrameNoMatch = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let state = 0; - - let items = [ - loader.cm.Item({ - label: "test item", - context: loader.cm.SelectionContext() - }) - ]; - - test.withTestDoc(function (window, doc) { - let frame = doc.getElementById("iframe"); - window.getSelection().selectAllChildren(doc.body); - - test.showMenu(["#iframe", "#text"], function (popup) { - test.checkMenu(items, items, []); - test.done(); - }); - }); -}; - - -// Test that the return value of the predicate function determines if -// item is shown -exports.testPredicateContextControl = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let itemTrue = loader.cm.Item({ - label: "visible", - context: loader.cm.PredicateContext(function () { return true; }) - }); - - let itemFalse = loader.cm.Item({ - label: "hidden", - context: loader.cm.PredicateContext(function () { return false; }) - }); - - test.showMenu(null, function (popup) { - test.checkMenu([itemTrue, itemFalse], [itemFalse], []); - test.done(); - }); -}; - -// Test that the data object has the correct document type -exports.testPredicateContextDocumentType = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.equal(data.documentType, 'text/html'); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has the correct document URL -exports.testPredicateContextDocumentURL = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.equal(data.documentURL, TEST_DOC_URL); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Test that the data object has the correct element name -exports.testPredicateContextTargetName = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.targetName, "input"); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#button", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Test that the data object has the correct ID -exports.testPredicateContextTargetIDSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.targetID, "button"); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#button", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has the correct ID -exports.testPredicateContextTargetIDNotSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.targetID, null); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu(".predicate-test-a", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object is showing editable correctly for regular text inputs -exports.testPredicateContextTextBoxIsEditable = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.isEditable, true); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#textbox", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object is showing editable correctly for readonly text inputs -exports.testPredicateContextReadonlyTextBoxIsNotEditable = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.isEditable, false); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#readonly-textbox", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object is showing editable correctly for disabled text inputs -exports.testPredicateContextDisabledTextBoxIsNotEditable = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.isEditable, false); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#disabled-textbox", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object is showing editable correctly for text areas -exports.testPredicateContextTextAreaIsEditable = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.isEditable, true); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#textfield", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that non-text inputs are not considered editable -exports.testPredicateContextButtonIsNotEditable = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.isEditable, false); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#button", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Test that the data object is showing editable correctly -exports.testPredicateContextNonInputIsNotEditable = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.isEditable, false); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Test that the data object is showing editable correctly for HTML contenteditable elements -exports.testPredicateContextEditableElement = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.isEditable, true); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#editable", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Test that the data object does not have a selection when there is none -exports.testPredicateContextNoSelectionInPage = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.selectionText, null); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object includes the selected page text -exports.testPredicateContextSelectionInPage = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - // since we might get whitespace - assert.ok(data.selectionText && data.selectionText.search(/^\s*Some text.\s*$/) != -1, - 'Expected "Some text.", got "' + data.selectionText + '"'); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - window.getSelection().selectAllChildren(doc.getElementById("text")); - test.showMenu(null, function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object includes the selected input text -exports.testPredicateContextSelectionInTextBox = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - // since we might get whitespace - assert.strictEqual(data.selectionText, "t v"); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - let textbox = doc.getElementById("textbox"); - test.selectRange("#textbox", 3, 6); - test.showMenu("#textbox", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has the correct src for an image -exports.testPredicateContextTargetSrcSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - let image; - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.srcURL, image.src); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - image = doc.getElementById("image"); - test.showMenu("#image", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has no src for a link -exports.testPredicateContextTargetSrcNotSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.srcURL, null); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#link", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - - -// Test that the data object has the correct link set -exports.testPredicateContextTargetLinkSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - let image; - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.linkURL, TEST_DOC_URL + "#test"); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu(".predicate-test-a", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has no link for an image -exports.testPredicateContextTargetLinkNotSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.linkURL, null); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has the correct link for a nested image -exports.testPredicateContextTargetLinkSetNestedImage = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.linkURL, TEST_DOC_URL + "#nested-image"); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#predicate-test-nested-image", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has the correct link for a complex nested structure -exports.testPredicateContextTargetLinkSetNestedStructure = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.linkURL, TEST_DOC_URL + "#nested-structure"); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#predicate-test-nested-structure", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has the value for an input textbox -exports.testPredicateContextTargetValueSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - let image; - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.value, "test value"); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#textbox", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -// Test that the data object has no value for an image -exports.testPredicateContextTargetValueNotSet = function (assert, done) { - let test = new TestHelper(assert, done); - let loader = test.newLoader(); - - let items = [loader.cm.Item({ - label: "item", - context: loader.cm.PredicateContext(function (data) { - assert.strictEqual(data.value, null); - return true; - }) - })]; - - test.withTestDoc(function (window, doc) { - test.showMenu("#image", function (popup) { - test.checkMenu(items, [], []); - test.done(); - }); - }); -}; - -if (isTravisCI) { - module.exports = { - "test skip on jpm": (assert) => assert.pass("skipping this file with jpm") - }; -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-context-menu@2.js b/addon-sdk/source/test/test-context-menu@2.js deleted file mode 100644 index 78c496220..000000000 --- a/addon-sdk/source/test/test-context-menu@2.js +++ /dev/null @@ -1,1350 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cc, Ci } = require("chrome"); -const {openWindow, closeWindow, openTab, closeTab, - openContextMenu, closeContextMenu, select, - readNode, captureContextMenu, withTab, withItems } = require("./context-menu/util"); -const {when} = require("sdk/dom/events"); -const {Item, Menu, Separator, Contexts, Readers } = require("sdk/context-menu@2"); -const prefs = require("sdk/preferences/service"); -const { before, after } = require('sdk/test/utils'); - -const testPageURI = require.resolve("./test-context-menu").replace(".js", ".html"); - -const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; - -const data = input => - `data:text/html;charset=utf-8,${encodeURIComponent(input)}` - -const menugroup = (...children) => Object.assign({ - tagName: "menugroup", - namespaceURI: XUL_NS, - style: "-moz-box-orient: vertical;", - className: "sdk-context-menu-extension" -}, children.length ? {children} : {}); - -const menuseparator = () => ({ - tagName: "menuseparator", - namespaceURI: XUL_NS, - className: "sdk-context-menu-separator" -}) - -const menuitem = properties => Object.assign({ - tagName: "menuitem", - namespaceURI: XUL_NS, - className: "sdk-context-menu-item menuitem-iconic" -}, properties); - -const menu = (properties, ...children) => Object.assign({ - tagName: "menu", - namespaceURI: XUL_NS, - className: "sdk-context-menu menu-iconic" -}, properties, { - children: [Object.assign({tagName: "menupopup", namespaceURI: XUL_NS}, - children.length ? {children} : {})] -}); - -// Destroying items that were previously created should cause them to be absent -// from the menu. -exports["test create / destroy menu item"] = withTab(function*(assert) { - const item = new Item({ - label: "test-1" - }); - - const before = yield captureContextMenu("h1"); - - assert.deepEqual(before, - menugroup(menuseparator(), - menuitem({label: "test-1"})), - "context menu contains separator & added item"); - - item.destroy(); - - const after = yield captureContextMenu("h1"); - assert.deepEqual(after, menugroup(), - "all items were removed children are present"); -}, data`

hello

`); - - -/* Bug 1115419 - Disable occasionally failing test until we - figure out why it fails. -// Items created should be present on all browser windows. -exports["test menu item in new window"] = function*(assert) { - const isMenuPopulated = function*(tab) { - const state = yield captureContextMenu("h1", tab); - assert.deepEqual(state, - menugroup(menuseparator(), - menuitem({label: "multi-window"})), - "created menu item is present") - }; - - const isMenuEmpty = function*(tab) { - const state = yield captureContextMenu("h1", tab); - assert.deepEqual(state, menugroup(), "no sdk items present"); - }; - - const item = new Item({ label: "multi-window" }); - - const tab1 = yield openTab(`data:text/html,

hello

`); - yield* isMenuPopulated(tab1); - - const window2 = yield openWindow(); - assert.pass("window is ready"); - - const tab2 = yield openTab(`data:text/html,

hello window-2

`, window2); - assert.pass("tab is ready"); - - yield* isMenuPopulated(tab2); - - item.destroy(); - - yield* isMenuEmpty(tab2); - yield closeWindow(window2); - - yield* isMenuEmpty(tab1); - - yield closeTab(tab1); -}; -*/ - - -// Multilpe items can be created and destroyed at different points -// in time & they should not affect each other. -exports["test multiple items"] = withTab(function*(assert) { - const item1 = new Item({ label: "one" }); - - const step1 = yield captureContextMenu("h1"); - assert.deepEqual(step1, - menugroup(menuseparator(), - menuitem({label: "one"})), - "item1 is present"); - - const item2 = new Item({ label: "two" }); - const step2 = yield captureContextMenu("h1"); - - assert.deepEqual(step2, - menugroup(menuseparator(), - menuitem({label: "one"}), - menuitem({label: "two"})), - "both items where present"); - - item1.destroy(); - - const step3 = yield captureContextMenu("h1"); - assert.deepEqual(step3, - menugroup(menuseparator(), - menuitem({label: "two"})), - "one items left"); - - item2.destroy(); - - const step4 = yield captureContextMenu("h1"); - assert.deepEqual(step4, menugroup(), "no items left"); -}, data`

Multiple Items

`); - -// Destroying an item twice should not cause an error. -exports["test destroy twice"] = withTab(function*(assert) { - const item = new Item({ label: "destroy" }); - const withItem = yield captureContextMenu("h2"); - assert.deepEqual(withItem, - menugroup(menuseparator(), - menuitem({label:"destroy"})), - "Item is added"); - - item.destroy(); - - const withoutItem = yield captureContextMenu("h2"); - assert.deepEqual(withoutItem, menugroup(), "Item was removed"); - - item.destroy(); - assert.pass("Destroying an item twice should not cause an error."); -}, "data:text/html,

item destroy

"); - -// CSS selector contexts should cause their items to be absent from the menu -// when the menu is not invoked on nodes that match selectors. -exports["test selector context"] = withTab(function*(assert) { - const item = new Item({ - context: [new Contexts.Selector("body b")], - label: "bold" - }); - - const match = yield captureContextMenu("b"); - assert.deepEqual(match, - menugroup(menuseparator(), - menuitem({label: "bold"})), - "item mathched context"); - - const noMatch = yield captureContextMenu("i"); - assert.deepEqual(noMatch, menugroup(), "item did not match context"); - - item.destroy(); - - const cleared = yield captureContextMenu("b"); - assert.deepEqual(cleared, menugroup(), "item was removed"); -}, data`onetwo`); - -// CSS selector contexts should cause their items to be absent in the menu -// when the menu is invoked even on nodes that have ancestors that match the -// selectors. -exports["test parent selector don't match children"] = withTab(function*(assert) { - const item = new Item({ - label: "parent match", - context: [new Contexts.Selector("a[href]")] - }); - - const match = yield captureContextMenu("a"); - assert.deepEqual(match, - menugroup(menuseparator(), - menuitem({label: "parent match"})), - "item mathched context"); - - const noMatch = yield captureContextMenu("strong"); - assert.deepEqual(noMatch, menugroup(), "item did not mathch context"); - - item.destroy(); - - const destroyed = yield captureContextMenu("a"); - assert.deepEqual(destroyed, menugroup(), "no items left"); -}, data`This text must be long & bold!`); - -// Page contexts should cause their items to be present in the menu when the -// menu is not invoked on an active element. -exports["test page context match"] = withTab(function*(assert) { - const isPageMatch = (tree, description="page context matched") => - assert.deepEqual(tree, - menugroup(menuseparator(), - menuitem({label: "page match"}), - menuitem({label: "any match"})), - description); - - const isntPageMatch = (tree, description="page context did not match") => - assert.deepEqual(tree, - menugroup(menuseparator(), - menuitem({label: "any match"})), - description); - - yield* withItems({ - pageMatch: new Item({ - label: "page match", - context: [new Contexts.Page()], - }), - anyMatch: new Item({ - label: "any match" - }) - }, function*({pageMatch, anyMatch}) { - for (let tagName of [null, "p", "h3"]) { - isPageMatch((yield captureContextMenu(tagName)), - `Page context matches ${tagName} passive element`); - } - - for (let tagName of ["button", "canvas", "img", "input", "textarea", - "select", "menu", "embed" ,"object", "video", "audio", - "applet"]) - { - isntPageMatch((yield captureContextMenu(tagName)), - `Page context does not match <${tagName}/> active element`); - } - - for (let selector of ["span"]) - { - isntPageMatch((yield captureContextMenu(selector)), - `Page context does not match decedents of active element`); - } - }); -}, -data` - - - -

paragraph

- -

hi

-
-
-
-
-
-
-
-
-
-
-
-
-`); - -// Page context does not match if if there is a selection. -exports["test page context doesn't match on selection"] = withTab(function*(assert) { - const isPageMatch = (tree, description="page context matched") => - assert.deepEqual(tree, - menugroup(menuseparator(), - menuitem({label: "page match"}), - menuitem({label: "any match"})), - description); - - const isntPageMatch = (tree, description="page context did not match") => - assert.deepEqual(tree, - menugroup(menuseparator(), - menuitem({label: "any match"})), - description); - - yield* withItems({ - pageMatch: new Item({ - label: "page match", - context: [new Contexts.Page()], - }), - anyMatch: new Item({ - label: "any match" - }) - }, function*({pageMatch, anyMatch}) { - yield select("b"); - isntPageMatch((yield captureContextMenu("i")), - "page context does not match if there is a selection"); - - yield select(null); - isPageMatch((yield captureContextMenu("i")), - "page context match if there is no selection"); - }); -}, data`onetwo`); - -exports["test selection context"] = withTab(function*(assert) { - yield* withItems({ - item: new Item({ - label: "selection", - context: [new Contexts.Selection()] - }) - }, function*({item}) { - assert.deepEqual((yield captureContextMenu()), - menugroup(), - "item does not match if there is no selection"); - - yield select("b"); - - assert.deepEqual((yield captureContextMenu()), - menugroup(menuseparator(), - menuitem({label: "selection"})), - "item matches if there is a selection"); - }); -}, data`onetwo`); - -exports["test selection context in textarea"] = withTab(function*(assert) { - yield* withItems({ - item: new Item({ - label: "selection", - context: [new Contexts.Selection()] - }) - }, function*({item}) { - assert.deepEqual((yield captureContextMenu()), - menugroup(), - "does not match if there's no selection"); - - yield select({target:"textarea", start:0, end:5}); - - assert.deepEqual((yield captureContextMenu("b")), - menugroup(), - "does not match if target isn't input with selection"); - - assert.deepEqual((yield captureContextMenu("textarea")), - menugroup(menuseparator(), - menuitem({label: "selection"})), - "matches if target is input with selected text"); - - yield select({target: "textarea", start: 0, end: 0}); - - assert.deepEqual((yield captureContextMenu("textarea")), - menugroup(), - "does not match when selection is cleared"); - }); -}, data`!!`); - -exports["test url contexts"] = withTab(function*(assert) { - yield* withItems({ - a: new Item({ - label: "a", - context: [new Contexts.URL(testPageURI)] - }), - b: new Item({ - label: "b", - context: [new Contexts.URL("*.bogus.com")] - }), - c: new Item({ - label: "c", - context: [new Contexts.URL("*.bogus.com"), - new Contexts.URL(testPageURI)] - }), - d: new Item({ - label: "d", - context: [new Contexts.URL(/.*\.html/)] - }), - e: new Item({ - label: "e", - context: [new Contexts.URL("http://*"), - new Contexts.URL(testPageURI)] - }), - f: new Item({ - label: "f", - context: [new Contexts.URL("http://*").required, - new Contexts.URL(testPageURI)] - }), - }, function*(_) { - assert.deepEqual((yield captureContextMenu()), - menugroup(menuseparator(), - menuitem({label: "a"}), - menuitem({label: "c"}), - menuitem({label: "d"}), - menuitem({label: "e"})), - "shows only matching items"); - }); -}, testPageURI); - -exports["test iframe context"] = withTab(function*(assert) { - yield* withItems({ - page: new Item({ - label: "page", - context: [new Contexts.Page()] - }), - iframe: new Item({ - label: "iframe", - context: [new Contexts.Frame()] - }), - h2: new Item({ - label: "element", - context: [new Contexts.Selector("*")] - }) - }, function(_) { - assert.deepEqual((yield captureContextMenu("iframe")), - menugroup(menuseparator(), - menuitem({label: "page"}), - menuitem({label: "iframe"}), - menuitem({label: "element"})), - "matching items are present"); - - assert.deepEqual((yield captureContextMenu("h1")), - menugroup(menuseparator(), - menuitem({label: "page"}), - menuitem({label: "element"})), - "only matching items are present"); - - }); - -}, -data`

hello

-

-

-

-

-

-

-

-

- -`; -exports["test predicate context"] = withTab(function*(assert) { - const test = function*(selector, expect) { - var isMatch = false; - test.return = (target) => { - return isMatch = expect(target); - } - assert.deepEqual((yield captureContextMenu(selector)), - isMatch ? menugroup(menuseparator(), - menuitem({label:"predicate"})) : - menugroup(), - isMatch ? `predicate item matches ${selector}` : - `predicate item doesn't match ${selector}`); - }; - test.predicate = target => test.return(target); - - yield* withItems({ - item: new Item({ - label: "predicate", - read: { - mediaType: new Readers.MediaType(), - link: new Readers.LinkURL(), - isPage: new Readers.isPage(), - isFrame: new Readers.isFrame(), - isEditable: new Readers.isEditable(), - tagName: new Readers.Query("tagName"), - appCodeName: new Readers.Query("ownerDocument.defaultView.navigator.appCodeName"), - width: new Readers.Attribute("width"), - src: new Readers.SrcURL(), - url: new Readers.PageURL(), - selection: new Readers.Selection() - }, - context: [Contexts.Predicate(test.predicate)] - }) - }, function*(items) { - yield* test("strong p", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: true, - isFrame: false, - isEditable: false, - tagName: "P", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "pagraph read test"); - return true; - }); - - yield* test("a span", target => { - assert.deepEqual(target, { - mediaType: null, - link: "./link", - isPage: false, - isFrame: false, - isEditable: false, - tagName: "SPAN", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "video tag test"); - return false; - }); - - yield* test("h3", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: true, - isFrame: false, - isEditable: false, - tagName: "H3", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "video tag test"); - return false; - }); - - yield select("h3"); - - yield* test("a span", target => { - assert.deepEqual(target, { - mediaType: null, - link: "./link", - isPage: false, - isFrame: false, - isEditable: false, - tagName: "SPAN", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: "hi", - }, "test selection with link"); - return true; - }); - - yield select(null); - - - yield* test("button", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "BUTTON", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test button"); - return true; - }); - - yield* test("canvas", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "CANVAS", - appCodeName: "Mozilla", - width: "50", - src: null, - url: predicateTestURL, - selection: null, - }, "test button"); - return true; - }); - - yield* test("img", target => { - assert.deepEqual(target, { - mediaType: "image", - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "IMG", - appCodeName: "Mozilla", - width: "50", - src: "./no.png", - url: predicateTestURL, - selection: null, - }, "test image"); - return true; - }); - - yield* test("code", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: true, - tagName: "CODE", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test content editable"); - return false; - }); - - yield* test("input[readonly=true]", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "INPUT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test readonly input"); - return false; - }); - - yield* test("input[disabled=true]", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "INPUT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test disabled input"); - return false; - }); - - yield select({target: "input#text", start: 0, end: 5 }); - - yield* test("input#text", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: true, - tagName: "INPUT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: "test ", - }, "test editable input"); - return false; - }); - - yield select({target: "input#text", start:0, end: 0}); - - yield* test("input[type=submit]", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "INPUT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test submit input"); - return false; - }); - - yield* test("input[type=radio]", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "INPUT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test radio input"); - return false; - }); - - yield* test("input[type=checkbox]", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "INPUT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test checkbox input"); - return false; - }); - - yield* test("input[type=foo]", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: true, - tagName: "INPUT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test unrecognized input"); - return false; - }); - - yield* test("textarea", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: true, - tagName: "TEXTAREA", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test textarea"); - return false; - }); - - - yield* test("iframe", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: true, - isFrame: true, - isEditable: false, - tagName: "BODY", - appCodeName: "Mozilla", - width: null, - src: null, - url: `data:text/html,Bye`, - selection: null, - }, "test iframe"); - return true; - }); - - yield* test("select", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "SELECT", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test select"); - return true; - }); - - yield* test("menu", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "MENU", - appCodeName: "Mozilla", - width: null, - src: null, - url: predicateTestURL, - selection: null, - }, "test menu"); - return false; - }); - - yield* test("video", target => { - assert.deepEqual(target, { - mediaType: "video", - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "VIDEO", - appCodeName: "Mozilla", - width: "50", - src: null, - url: predicateTestURL, - selection: null, - }, "test video"); - return true; - }); - - yield* test("audio", target => { - assert.deepEqual(target, { - mediaType: "audio", - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "AUDIO", - appCodeName: "Mozilla", - width: "10", - src: null, - url: predicateTestURL, - selection: null, - }, "test audio"); - return true; - }); - - yield* test("object", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "OBJECT", - appCodeName: "Mozilla", - width: "10", - src: null, - url: predicateTestURL, - selection: null, - }, "test object"); - return true; - }); - - yield* test("embed", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "EMBED", - appCodeName: "Mozilla", - width: "10", - src: null, - url: predicateTestURL, - selection: null, - }, "test embed"); - return true; - }); - - yield* test("applet", target => { - assert.deepEqual(target, { - mediaType: null, - link: null, - isPage: false, - isFrame: false, - isEditable: false, - tagName: "APPLET", - appCodeName: "Mozilla", - width: "30", - src: null, - url: predicateTestURL, - selection: null, - }, "test applet"); - return false; - }); - - }); -}, predicateTestURL); - -exports["test extractor reader"] = withTab(function*(assert) { - const test = function*(selector, expect) { - var isMatch = false; - test.return = (target) => { - return isMatch = expect(target); - } - assert.deepEqual((yield captureContextMenu(selector)), - isMatch ? menugroup(menuseparator(), - menuitem({label:"extractor"})) : - menugroup(), - isMatch ? `predicate item matches ${selector}` : - `predicate item doesn't match ${selector}`); - }; - test.predicate = target => test.return(target); - - - yield* withItems({ - item: new Item({ - label: "extractor", - context: [Contexts.Predicate(test.predicate)], - read: { - tagName: Readers.Query("tagName"), - selector: Readers.Extractor(target => { - let node = target; - let path = []; - while (node) { - if (node.id) { - path.unshift(`#${node.id}`); - node = null; - } - else { - path.unshift(node.localName); - node = node.parentElement; - } - } - return path.join(" > "); - }) - } - }) - }, function*(_) { - yield* test("footer", target => { - assert.deepEqual(target, { - tagName: "FOOTER", - selector: "html > body > nav > footer" - }, "test footer"); - return false; - }); - - - }); -}, data` - - -
-
First title
-
-

First paragraph

-

Second paragraph

-
-
-
-
Second title
-
-

First paragraph

-

Second paragraph

-
-
- -`); - -exports["test items overflow"] = withTab(function*(assert) { - yield* withItems({ - i1: new Item({label: "item-1"}), - i2: new Item({label: "item-2"}), - i3: new Item({label: "item-3"}), - i4: new Item({label: "item-4"}), - i5: new Item({label: "item-5"}), - i6: new Item({label: "item-6"}), - i7: new Item({label: "item-7"}), - i8: new Item({label: "item-8"}), - i9: new Item({label: "item-9"}), - i10: new Item({label: "item-10"}), - }, function*(_) { - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menu({ - className: "sdk-context-menu-overflow-menu", - label: "Add-ons", - accesskey: "A", - }, menuitem({label: "item-1"}), - menuitem({label: "item-2"}), - menuitem({label: "item-3"}), - menuitem({label: "item-4"}), - menuitem({label: "item-5"}), - menuitem({label: "item-6"}), - menuitem({label: "item-7"}), - menuitem({label: "item-8"}), - menuitem({label: "item-9"}), - menuitem({label: "item-10"}))), - "context menu has an overflow"); - }); - - prefs.set("extensions.addon-sdk.context-menu.overflowThreshold", 3); - - yield* withItems({ - i1: new Item({label: "item-1"}), - i2: new Item({label: "item-2"}), - }, function*(_) { - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menuseparator(), - menuitem({label: "item-1"}), - menuitem({label: "item-2"})), - "two items do not overflow"); - }); - - yield* withItems({ - one: new Item({label: "one"}), - two: new Item({label: "two"}), - three: new Item({label: "three"}) - }, function*(_) { - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menu({className: "sdk-context-menu-overflow-menu", - label: "Add-ons", - accesskey: "A"}, - menuitem({label: "one"}), - menuitem({label: "two"}), - menuitem({label: "three"}))), - "three items overflow"); - }); - - prefs.reset("extensions.addon-sdk.context-menu.overflowThreshold"); - - yield* withItems({ - one: new Item({label: "one"}), - two: new Item({label: "two"}), - three: new Item({label: "three"}) - }, function*(_) { - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menuseparator(), - menuitem({label: "one"}), - menuitem({label: "two"}), - menuitem({label: "three"})), - "three items no longer overflow"); - }); -}, data`

Hello

`); - - -exports["test context menus"] = withTab(function*(assert) { - const one = new Item({ - label: "one", - context: [Contexts.Selector("p")], - read: {tagName: Readers.Query("tagName")} - }); - - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menuseparator(), - menuitem({label: "one"})), - "item is present"); - - const two = new Item({ - label: "two", - read: {tagName: Readers.Query("tagName")} - }); - - - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menuseparator(), - menuitem({label: "one"}), - menuitem({label: "two"})), - "both items are present"); - - const groupLevel1 = new Menu({label: "Level 1"}, - [one]); - - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menuseparator(), - menuitem({label: "two"}), - menu({label: "Level 1"}, - menuitem({label: "one"}))), - "first item moved to group"); - - assert.deepEqual((yield captureContextMenu("h1")), - menugroup(menuseparator(), - menuitem({label: "two"})), - "menu is hidden since only item does not match"); - - - const groupLevel2 = new Menu({label: "Level 2" }, [groupLevel1]); - - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menuseparator(), - menuitem({label: "two"}), - menu({label: "Level 2"}, - menu({label: "Level 1"}, - menuitem({label: "one"})))), - "top level menu moved to submenu"); - - assert.deepEqual((yield captureContextMenu("h1")), - menugroup(menuseparator(), - menuitem({label: "two"})), - "menu is hidden since only item does not match"); - - - const contextGroup = new Menu({ - label: "H1 Group", - context: [Contexts.Selector("h1")] - }, [ - two, - new Separator(), - new Item({ label: "three" }) - ]); - - - assert.deepEqual((yield captureContextMenu("p")), - menugroup(menuseparator(), - menu({label: "Level 2"}, - menu({label: "Level 1"}, - menuitem({label: "one"})))), - "nested menu is rendered"); - - assert.deepEqual((yield captureContextMenu("h1")), - menugroup(menuseparator(), - menu({label: "H1 Group"}, - menuitem({label: "two"}), - menuseparator(), - menuitem({label: "three"}))), - "new contextual menu rendered"); - - yield* withItems({one, two, - groupLevel1, groupLevel2, contextGroup}, function*() { - - }); - - assert.deepEqual((yield captureContextMenu("p")), - menugroup(), - "everyhing matching p was desposed"); - - assert.deepEqual((yield captureContextMenu("h1")), - menugroup(), - "everyhing matching h1 was desposed"); - -}, data`

Title

Content

`); - -exports["test unloading"] = withTab(function*(assert) { - const { Loader } = require("sdk/test/loader"); - const loader = Loader(module); - - const {Item, Menu, Separator, Contexts, Readers } = loader.require("sdk/context-menu@2"); - - const item = new Item({label: "item"}); - const group = new Menu({label: "menu"}, - [new Separator(), - new Item({label: "sub-item"})]); - assert.deepEqual((yield captureContextMenu()), - menugroup(menuseparator(), - menuitem({label: "item"}), - menu({label: "menu"}, - menuseparator(), - menuitem({label: "sub-item"}))), - "all items rendered"); - - - loader.unload(); - - assert.deepEqual((yield captureContextMenu()), - menugroup(), - "all items disposed"); -}, data``); - -if (require("@loader/options").isNative) { - module.exports = { - "test skip on jpm": (assert) => assert.pass("skipping this file with jpm") - }; -} - -before(exports, (name, assert) => { - // Make sure Java doesn't activate - prefs.set("plugin.state.java", 0); -}); - -after(exports, (name, assert) => { - prefs.reset("plugin.state.java"); -}); - -require("sdk/test").run(module.exports); diff --git a/addon-sdk/source/test/test-cuddlefish.js b/addon-sdk/source/test/test-cuddlefish.js deleted file mode 100644 index c92eaa624..000000000 --- a/addon-sdk/source/test/test-cuddlefish.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 { Cc, Ci, Cu, CC, Cr, Cm, ChromeWorker, components } = require("chrome"); - -const packaging = require("@loader/options"); -const app = require('sdk/system/xul-app'); -const { resolve } = require; - -const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1']. - getService(Ci.mozIJSSubScriptLoader); -const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')(); - -function loadSandbox(uri) { - let proto = { - sandboxPrototype: { - loadSandbox: loadSandbox, - ChromeWorker: ChromeWorker - } - }; - let sandbox = Cu.Sandbox(systemPrincipal, proto); - // Create a fake commonjs environnement just to enable loading loader.js - // correctly - sandbox.exports = {}; - sandbox.module = { uri: uri, exports: sandbox.exports }; - sandbox.require = function (id) { - if (id !== "chrome") - throw new Error("Bootstrap sandbox `require` method isn't implemented."); - - return Object.freeze({ Cc: Cc, Ci: Ci, Cu: Cu, Cr: Cr, Cm: Cm, - CC: CC, components: components, - ChromeWorker: ChromeWorker }); - }; - scriptLoader.loadSubScript(uri, sandbox, 'UTF-8'); - return sandbox; -} - -exports['test loader'] = function(assert) { - let { Loader, Require, unload, override } = loadSandbox(resolve('sdk/loader/cuddlefish.js')).exports; - var prints = []; - function print(message) { - prints.push(message); - } - - let loader = Loader(override(packaging, { - globals: { - print: print, - foo: 1 - } - })); - let require = Require(loader, module); - - var fixture = require('./loader/fixture'); - - assert.equal(fixture.foo, 1, 'custom globals must work.'); - assert.equal(fixture.bar, 2, 'exports are set'); - - assert.equal(prints[0], 'testing', 'global print must be injected.'); - - var unloadsCalled = ''; - - require("sdk/system/unload").when(function(reason) { - assert.equal(reason, 'test', 'unload reason is passed'); - unloadsCalled += 'a'; - }); - require('sdk/system/unload.js').when(function() { - unloadsCalled += 'b'; - }); - - unload(loader, 'test'); - - assert.equal(unloadsCalled, 'ba', - 'loader.unload() must call listeners in LIFO order.'); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-deprecate.js b/addon-sdk/source/test/test-deprecate.js deleted file mode 100644 index c1bd443c6..000000000 --- a/addon-sdk/source/test/test-deprecate.js +++ /dev/null @@ -1,160 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 deprecate = require("sdk/util/deprecate"); -const { LoaderWithHookedConsole } = require("sdk/test/loader"); -const { get, set } = require("sdk/preferences/service"); -const PREFERENCE = "devtools.errorconsole.deprecation_warnings"; - -exports["test Deprecate Usage"] = function testDeprecateUsage(assert) { - set(PREFERENCE, true); - let { loader, messages } = LoaderWithHookedConsole(module); - let deprecate = loader.require("sdk/util/deprecate"); - - function functionIsDeprecated() { - deprecate.deprecateUsage("foo"); - } - - functionIsDeprecated(); - - assert.equal(messages.length, 1, "only one error is dispatched"); - assert.equal(messages[0].type, "error", "the console message is an error"); - - let msg = messages[0].msg; - - assert.ok(msg.indexOf("foo") !== -1, - "message contains the given message"); - assert.ok(msg.indexOf("functionIsDeprecated") !== -1, - "message contains name of the caller function"); - assert.ok(msg.indexOf(module.uri) !== -1, - "message contains URI of the caller module"); - - loader.unload(); -} - -exports["test Deprecate Function"] = function testDeprecateFunction(assert) { - set(PREFERENCE, true); - let { loader, messages } = LoaderWithHookedConsole(module); - let deprecate = loader.require("sdk/util/deprecate"); - - let self = {}; - let arg1 = "foo"; - let arg2 = {}; - - function originalFunction(a1, a2) { - assert.equal(this, self); - assert.equal(a1, arg1); - assert.equal(a2, arg2); - }; - - let deprecateFunction = deprecate.deprecateFunction(originalFunction, - "bar"); - - deprecateFunction.call(self, arg1, arg2); - - assert.equal(messages.length, 1, "only one error is dispatched"); - assert.equal(messages[0].type, "error", "the console message is an error"); - - let msg = messages[0].msg; - assert.ok(msg.indexOf("bar") !== -1, "message contains the given message"); - assert.ok(msg.indexOf("testDeprecateFunction") !== -1, - "message contains name of the caller function"); - assert.ok(msg.indexOf(module.uri) !== -1, - "message contains URI of the caller module"); - - loader.unload(); -} - -exports.testDeprecateEvent = function(assert, done) { - set(PREFERENCE, true); - let { loader, messages } = LoaderWithHookedConsole(module); - let deprecate = loader.require("sdk/util/deprecate"); - - let { on, emit } = loader.require('sdk/event/core'); - let testObj = {}; - testObj.on = deprecate.deprecateEvent(on.bind(null, testObj), 'BAD', ['fire']); - - testObj.on('fire', function() { - testObj.on('water', function() { - assert.equal(messages.length, 1, "only one error is dispatched"); - loader.unload(); - done(); - }) - assert.equal(messages.length, 1, "only one error is dispatched"); - emit(testObj, 'water'); - }); - - assert.equal(messages.length, 1, "only one error is dispatched"); - assert.equal(messages[0].type, "error", "the console message is an error"); - let msg = messages[0].msg; - assert.ok(msg.indexOf("BAD") !== -1, "message contains the given message"); - assert.ok(msg.indexOf("deprecateEvent") !== -1, - "message contains name of the caller function"); - assert.ok(msg.indexOf(module.uri) !== -1, - "message contains URI of the caller module"); - - emit(testObj, 'fire'); -} - -exports.testDeprecateSettingToggle = function (assert) { - let { loader, messages } = LoaderWithHookedConsole(module); - let deprecate = loader.require("sdk/util/deprecate"); - - function fn () { deprecate.deprecateUsage("foo"); } - - set(PREFERENCE, false); - fn(); - assert.equal(messages.length, 0, 'no deprecation warnings'); - - set(PREFERENCE, true); - fn(); - assert.equal(messages.length, 1, 'deprecation warnings when toggled'); - - set(PREFERENCE, false); - fn(); - assert.equal(messages.length, 1, 'no new deprecation warnings'); -}; - -exports.testDeprecateSetting = function (assert, done) { - // Set devtools.errorconsole.deprecation_warnings to false - set(PREFERENCE, false); - - let { loader, messages } = LoaderWithHookedConsole(module); - let deprecate = loader.require("sdk/util/deprecate"); - - // deprecateUsage test - function functionIsDeprecated() { - deprecate.deprecateUsage("foo"); - } - functionIsDeprecated(); - - assert.equal(messages.length, 0, - "no errors dispatched on deprecateUsage"); - - // deprecateFunction test - function originalFunction() {}; - - let deprecateFunction = deprecate.deprecateFunction(originalFunction, - "bar"); - deprecateFunction(); - - assert.equal(messages.length, 0, - "no errors dispatched on deprecateFunction"); - - // deprecateEvent - let { on, emit } = loader.require('sdk/event/core'); - let testObj = {}; - testObj.on = deprecate.deprecateEvent(on.bind(null, testObj), 'BAD', ['fire']); - - testObj.on('fire', () => { - assert.equal(messages.length, 0, - "no errors dispatched on deprecateEvent"); - done(); - }); - - emit(testObj, 'fire'); -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-dev-panel.js b/addon-sdk/source/test/test-dev-panel.js deleted file mode 100644 index fb786b043..000000000 --- a/addon-sdk/source/test/test-dev-panel.js +++ /dev/null @@ -1,426 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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"; - -module.metadata = { - "engines": { - "Firefox": "*" - } -}; - -const { Tool } = require("dev/toolbox"); -const { Panel } = require("dev/panel"); -const { Class } = require("sdk/core/heritage"); -const { openToolbox, closeToolbox, getCurrentPanel } = require("dev/utils"); -const { MessageChannel } = require("sdk/messaging"); -const { when } = require("sdk/dom/events-shimmed"); -const { viewFor } = require("sdk/view/core"); -const { createView } = require("dev/panel/view"); - -const iconURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAKQWlDQ1BJQ0MgUHJvZmlsZQAASA2dlndUU9kWh8+9N73QEiIgJfQaegkg0jtIFQRRiUmAUAKGhCZ2RAVGFBEpVmRUwAFHhyJjRRQLg4Ji1wnyEFDGwVFEReXdjGsJ7601896a/cdZ39nnt9fZZ+9917oAUPyCBMJ0WAGANKFYFO7rwVwSE8vE9wIYEAEOWAHA4WZmBEf4RALU/L09mZmoSMaz9u4ugGS72yy/UCZz1v9/kSI3QyQGAApF1TY8fiYX5QKUU7PFGTL/BMr0lSkyhjEyFqEJoqwi48SvbPan5iu7yZiXJuShGlnOGbw0noy7UN6aJeGjjAShXJgl4GejfAdlvVRJmgDl9yjT0/icTAAwFJlfzOcmoWyJMkUUGe6J8gIACJTEObxyDov5OWieAHimZ+SKBIlJYqYR15hp5ejIZvrxs1P5YjErlMNN4Yh4TM/0tAyOMBeAr2+WRQElWW2ZaJHtrRzt7VnW5mj5v9nfHn5T/T3IevtV8Sbsz55BjJ5Z32zsrC+9FgD2JFqbHbO+lVUAtG0GQOXhrE/vIADyBQC03pzzHoZsXpLE4gwnC4vs7GxzAZ9rLivoN/ufgm/Kv4Y595nL7vtWO6YXP4EjSRUzZUXlpqemS0TMzAwOl89k/fcQ/+PAOWnNycMsnJ/AF/GF6FVR6JQJhIlou4U8gViQLmQKhH/V4X8YNicHGX6daxRodV8AfYU5ULhJB8hvPQBDIwMkbj96An3rWxAxCsi+vGitka9zjzJ6/uf6Hwtcim7hTEEiU+b2DI9kciWiLBmj34RswQISkAd0oAo0gS4wAixgDRyAM3AD3iAAhIBIEAOWAy5IAmlABLJBPtgACkEx2AF2g2pwANSBetAEToI2cAZcBFfADXALDIBHQAqGwUswAd6BaQiC8BAVokGqkBakD5lC1hAbWgh5Q0FQOBQDxUOJkBCSQPnQJqgYKoOqoUNQPfQjdBq6CF2D+qAH0CA0Bv0BfYQRmALTYQ3YALaA2bA7HAhHwsvgRHgVnAcXwNvhSrgWPg63whfhG/AALIVfwpMIQMgIA9FGWAgb8URCkFgkAREha5EipAKpRZqQDqQbuY1IkXHkAwaHoWGYGBbGGeOHWYzhYlZh1mJKMNWYY5hWTBfmNmYQM4H5gqVi1bGmWCesP3YJNhGbjS3EVmCPYFuwl7ED2GHsOxwOx8AZ4hxwfrgYXDJuNa4Etw/XjLuA68MN4SbxeLwq3hTvgg/Bc/BifCG+Cn8cfx7fjx/GvyeQCVoEa4IPIZYgJGwkVBAaCOcI/YQRwjRRgahPdCKGEHnEXGIpsY7YQbxJHCZOkxRJhiQXUiQpmbSBVElqIl0mPSa9IZPJOmRHchhZQF5PriSfIF8lD5I/UJQoJhRPShxFQtlOOUq5QHlAeUOlUg2obtRYqpi6nVpPvUR9Sn0vR5Mzl/OX48mtk6uRa5Xrl3slT5TXl3eXXy6fJ18hf0r+pvy4AlHBQMFTgaOwVqFG4bTCPYVJRZqilWKIYppiiWKD4jXFUSW8koGStxJPqUDpsNIlpSEaQtOledK4tE20Otpl2jAdRzek+9OT6cX0H+i99AllJWVb5SjlHOUa5bPKUgbCMGD4M1IZpYyTjLuMj/M05rnP48/bNq9pXv+8KZX5Km4qfJUilWaVAZWPqkxVb9UU1Z2qbapP1DBqJmphatlq+9Uuq43Pp893ns+dXzT/5PyH6rC6iXq4+mr1w+o96pMamhq+GhkaVRqXNMY1GZpumsma5ZrnNMe0aFoLtQRa5VrntV4wlZnuzFRmJbOLOaGtru2nLdE+pN2rPa1jqLNYZ6NOs84TXZIuWzdBt1y3U3dCT0svWC9fr1HvoT5Rn62fpL9Hv1t/ysDQINpgi0GbwaihiqG/YZ5ho+FjI6qRq9Eqo1qjO8Y4Y7ZxivE+41smsImdSZJJjclNU9jU3lRgus+0zwxr5mgmNKs1u8eisNxZWaxG1qA5wzzIfKN5m/krCz2LWIudFt0WXyztLFMt6ywfWSlZBVhttOqw+sPaxJprXWN9x4Zq42Ozzqbd5rWtqS3fdr/tfTuaXbDdFrtOu8/2DvYi+yb7MQc9h3iHvQ732HR2KLuEfdUR6+jhuM7xjOMHJ3snsdNJp9+dWc4pzg3OowsMF/AX1C0YctFx4bgccpEuZC6MX3hwodRV25XjWuv6zE3Xjed2xG3E3dg92f24+ysPSw+RR4vHlKeT5xrPC16Il69XkVevt5L3Yu9q76c+Oj6JPo0+E752vqt9L/hh/QL9dvrd89fw5/rX+08EOASsCegKpARGBFYHPgsyCRIFdQTDwQHBu4IfL9JfJFzUFgJC/EN2hTwJNQxdFfpzGC4sNKwm7Hm4VXh+eHcELWJFREPEu0iPyNLIR4uNFksWd0bJR8VF1UdNRXtFl0VLl1gsWbPkRoxajCCmPRYfGxV7JHZyqffS3UuH4+ziCuPuLjNclrPs2nK15anLz66QX8FZcSoeGx8d3xD/iRPCqeVMrvRfuXflBNeTu4f7kufGK+eN8V34ZfyRBJeEsoTRRJfEXYljSa5JFUnjAk9BteB1sl/ygeSplJCUoykzqdGpzWmEtPi000IlYYqwK10zPSe9L8M0ozBDuspp1e5VE6JA0ZFMKHNZZruYjv5M9UiMJJslg1kLs2qy3mdHZZ/KUcwR5vTkmuRuyx3J88n7fjVmNXd1Z752/ob8wTXuaw6thdauXNu5Tnddwbrh9b7rj20gbUjZ8MtGy41lG99uit7UUaBRsL5gaLPv5sZCuUJR4b0tzlsObMVsFWzt3WazrWrblyJe0fViy+KK4k8l3JLr31l9V/ndzPaE7b2l9qX7d+B2CHfc3em681iZYlle2dCu4F2t5czyovK3u1fsvlZhW3FgD2mPZI+0MqiyvUqvakfVp+qk6oEaj5rmvep7t+2d2sfb17/fbX/TAY0DxQc+HhQcvH/I91BrrUFtxWHc4azDz+ui6rq/Z39ff0TtSPGRz0eFR6XHwo911TvU1zeoN5Q2wo2SxrHjccdv/eD1Q3sTq+lQM6O5+AQ4ITnx4sf4H++eDDzZeYp9qukn/Z/2ttBailqh1tzWibakNml7THvf6YDTnR3OHS0/m/989Iz2mZqzymdLz5HOFZybOZ93fvJCxoXxi4kXhzpXdD66tOTSna6wrt7LgZevXvG5cqnbvfv8VZerZ645XTt9nX297Yb9jdYeu56WX+x+aem172296XCz/ZbjrY6+BX3n+l37L972un3ljv+dGwOLBvruLr57/17cPel93v3RB6kPXj/Mejj9aP1j7OOiJwpPKp6qP6391fjXZqm99Oyg12DPs4hnj4a4Qy//lfmvT8MFz6nPK0a0RupHrUfPjPmM3Xqx9MXwy4yX0+OFvyn+tveV0auffnf7vWdiycTwa9HrmT9K3qi+OfrW9m3nZOjk03dp76anit6rvj/2gf2h+2P0x5Hp7E/4T5WfjT93fAn88ngmbWbm3/eE8/syOll+AAAACXBIWXMAAAsTAAALEwEAmpwYAAADqmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIKICAgICAgICAgICAgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiCiAgICAgICAgICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyI+CiAgICAgICAgIDx4bXBNTTpEb2N1bWVudElEPnhtcC5kaWQ6M0ExNEY4NjZBNkU1MTFFMTlGMkFGQ0QyNTUyN0VDRjY8L3htcE1NOkRvY3VtZW50SUQ+CiAgICAgICAgIDx4bXBNTTpEZXJpdmVkRnJvbSByZGY6cGFyc2VUeXBlPSJSZXNvdXJjZSI+CiAgICAgICAgICAgIDxzdFJlZjppbnN0YW5jZUlEPnhtcC5paWQ6M0ExNEY4NjNBNkU1MTFFMTlGMkFGQ0QyNTUyN0VDRjY8L3N0UmVmOmluc3RhbmNlSUQ+CiAgICAgICAgICAgIDxzdFJlZjpkb2N1bWVudElEPnhtcC5kaWQ6M0ExNEY4NjRBNkU1MTFFMTlGMkFGQ0QyNTUyN0VDRjY8L3N0UmVmOmRvY3VtZW50SUQ+CiAgICAgICAgIDwveG1wTU06RGVyaXZlZEZyb20+CiAgICAgICAgIDx4bXBNTTpJbnN0YW5jZUlEPnhtcC5paWQ6M0ExNEY4NjVBNkU1MTFFMTlGMkFGQ0QyNTUyN0VDRjY8L3htcE1NOkluc3RhbmNlSUQ+CiAgICAgICAgIDx4bXA6Q3JlYXRvclRvb2w+QWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2g8L3htcDpDcmVhdG9yVG9vbD4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+ChetDDYAAACaSURBVEgNY2AYboAR3UNnzpx5DxQTQBP/YGJiIogmBuYSq54Ji2Z0S0BKsInBtGKTwxDDZhHMAKrSdLOIqq7GZxjj+fPnBf7+/bseqMgBn0IK5A4wMzMHMtHYEpD7HEB2gOLIAcSjMXCgW2IYtYjsqBwNutGgg4fAaGKABwWpDLoG3QFSXUeG+gNMoEoJqJGWloErPjIcR54WALqPHeiJgl15AAAAAElFTkSuQmCC"; -const makeHTML = fn => - "data:text/html;charset=utf-8,"; - - -const test = function(unit) { - return function*(assert) { - assert.isRendered = (panel, toolbox) => { - const doc = toolbox.doc; - assert.ok(doc.querySelector("[value='" + panel.label + "']"), - "panel.label is found in the developer toolbox DOM"); - assert.ok(doc.querySelector("[tooltiptext='" + panel.tooltip + "']"), - "panel.tooltip is found in the developer toolbox DOM"); - - assert.ok(doc.querySelector("#toolbox-panel-" + panel.id), - "toolbar panel with a matching id is present"); - }; - - - yield* unit(assert); - }; -}; - -exports["test Panel API"] = test(function*(assert) { - const MyPanel = Class({ - extends: Panel, - label: "test panel", - tooltip: "my test panel", - icon: iconURI, - url: makeHTML(() => { - document.documentElement.innerHTML = "hello world"; - }), - setup: function({debuggee}) { - this.debuggee = debuggee; - assert.equal(this.readyState, "uninitialized", - "at construction time panel document is not inited"); - }, - dispose: function() { - delete this.debuggee; - } - }); - assert.ok(MyPanel, "panel is defined"); - - const myTool = new Tool({ - panels: { - myPanel: MyPanel - } - }); - assert.ok(myTool, "tool is defined"); - - - var toolbox = yield openToolbox(MyPanel); - var panel = yield getCurrentPanel(toolbox); - assert.ok(panel instanceof MyPanel, "is instance of MyPanel"); - - assert.isRendered(panel, toolbox); - - if (panel.readyState === "uninitialized") { - yield panel.ready(); - assert.equal(panel.readyState, "interactive", "panel is ready"); - } - - yield panel.loaded(); - assert.equal(panel.readyState, "complete", "panel is loaded"); - - yield closeToolbox(); - - assert.equal(panel.readyState, "destroyed", "panel is destroyed"); - - myTool.destroy(); -}); - -exports["test forbid remote https docs"] = test(function*(assert) { - const MyPanel = Class({ - extends: Panel, - label: "test https panel", - tooltip: "my test panel", - icon: iconURI, - url: "https://mozilla.org", - }); - - assert.throws(() => { - new Tool({ panels: { myPanel: MyPanel } }); - }, - /The `options.url` must be a valid local URI/, - "can't use panel with remote URI"); -}); - -exports["test forbid remote http docs"] = test(function*(assert) { - const MyPanel = Class({ - extends: Panel, - label: "test http panel", - tooltip: "my test panel", - icon: iconURI, - url: "http://arewefastyet.com/", - }); - - assert.throws(() => { - new Tool({ panels: { myPanel: MyPanel } }); - }, - /The `options.url` must be a valid local URI/, - "can't use panel with remote URI"); -}); - -exports["test forbid remote ftp docs"] = test(function*(assert) { - const MyPanel = Class({ - extends: Panel, - label: "test ftp panel", - tooltip: "my test panel", - icon: iconURI, - url: "ftp://ftp.mozilla.org/", - }); - - assert.throws(() => { - new Tool({ panels: { myPanel: MyPanel } }); - }, - /The `options.url` must be a valid local URI/, - "can't use panel with remote URI"); -}); - - -exports["test Panel communication"] = test(function*(assert) { - const MyPanel = Class({ - extends: Panel, - label: "communication", - tooltip: "test palen communication", - icon: iconURI, - url: makeHTML(() => { - window.addEventListener("message", event => { - if (event.source === window) { - var port = event.ports[0]; - port.start(); - port.postMessage("ping"); - port.onmessage = (event) => { - if (event.data === "pong") { - port.postMessage("bye"); - port.close(); - } - }; - } - }); - }), - dispose: function() { - delete this.port; - } - }); - - - const myTool = new Tool({ - panels: { - myPanel: MyPanel - } - }); - - - const toolbox = yield openToolbox(MyPanel); - const panel = yield getCurrentPanel(toolbox); - assert.ok(panel instanceof MyPanel, "is instance of MyPanel"); - - assert.isRendered(panel, toolbox); - - yield panel.ready(); - const { port1, port2 } = new MessageChannel(); - panel.port = port1; - panel.postMessage("connect", [port2]); - panel.port.start(); - - const ping = yield when(panel.port, "message"); - - assert.equal(ping.data, "ping", "received ping from panel doc"); - - panel.port.postMessage("pong"); - - const bye = yield when(panel.port, "message"); - - assert.equal(bye.data, "bye", "received bye from panel doc"); - - panel.port.close(); - - yield closeToolbox(); - - assert.equal(panel.readyState, "destroyed", "panel is destroyed"); - myTool.destroy(); -}); - -exports["test communication with debuggee"] = test(function*(assert) { - const MyPanel = Class({ - extends: Panel, - label: "debuggee", - tooltip: "test debuggee", - icon: iconURI, - url: makeHTML(() => { - window.addEventListener("message", event => { - if (event.source === window) { - var debuggee = event.ports[0]; - var port = event.ports[1]; - debuggee.start(); - port.start(); - - - debuggee.onmessage = (event) => { - port.postMessage(event.data); - }; - port.onmessage = (event) => { - debuggee.postMessage(event.data); - }; - } - }); - }), - setup: function({debuggee}) { - this.debuggee = debuggee; - }, - onReady: function() { - const { port1, port2 } = new MessageChannel(); - this.port = port1; - this.port.start(); - this.debuggee.start(); - - this.postMessage("connect", [this.debuggee, port2]); - }, - dispose: function() { - this.port.close(); - this.debuggee.close(); - - delete this.port; - delete this.debuggee; - } - }); - - - const myTool = new Tool({ - panels: { - myPanel: MyPanel - } - }); - - - const toolbox = yield openToolbox(MyPanel); - const panel = yield getCurrentPanel(toolbox); - assert.ok(panel instanceof MyPanel, "is instance of MyPanel"); - - assert.isRendered(panel, toolbox); - - yield panel.ready(); - const intro = yield when(panel.port, "message"); - - assert.equal(intro.data.from, "root", "intro message from root"); - - panel.port.postMessage({ - to: "root", - type: "echo", - text: "ping" - }); - - const pong = yield when(panel.port, "message"); - - assert.deepEqual(pong.data, { - to: "root", - from: "root", - type: "echo", - text: "ping" - }, "received message back from root"); - - yield closeToolbox(); - - assert.equal(panel.readyState, "destroyed", "panel is destroyed"); - - myTool.destroy(); -}); - - -exports["test viewFor panel"] = test(function*(assert) { - const url = "data:text/html;charset=utf-8,viewFor"; - const MyPanel = Class({ - extends: Panel, - label: "view for panel", - tooltip: "my panel view", - icon: iconURI, - url: url - }); - - const myTool = new Tool({ - panels: { - myPanel: MyPanel - } - }); - - - const toolbox = yield openToolbox(MyPanel); - const panel = yield getCurrentPanel(toolbox); - assert.ok(panel instanceof MyPanel, "is instance of MyPanel"); - - const frame = viewFor(panel); - - assert.equal(frame.nodeName.toLowerCase(), "iframe", - "viewFor(panel) returns associated iframe"); - - yield panel.loaded(); - - assert.equal(frame.contentDocument.URL, url, "is expected iframe"); - - yield closeToolbox(); - - myTool.destroy(); -}); - - -exports["test createView panel"] = test(function*(assert) { - var frame = null; - var panel = null; - - const url = "data:text/html;charset=utf-8,createView"; - const id = Math.random().toString(16).substr(2); - const MyPanel = Class({ - extends: Panel, - label: "create view", - tooltip: "panel creator", - icon: iconURI, - url: url - }); - - createView.define(MyPanel, (instance, document) => { - var view = document.createElement("iframe"); - view.setAttribute("type", "content"); - - // save instances for later asserts - frame = view; - panel = instance; - - return view; - }); - - const myTool = new Tool({ - panels: { - myPanel: MyPanel - } - }); - - const toolbox = yield openToolbox(MyPanel); - const myPanel = yield getCurrentPanel(toolbox); - - assert.equal(myPanel, panel, - "panel passed to createView is one instantiated"); - assert.equal(viewFor(panel), frame, - "createView has created an iframe"); - - yield panel.loaded(); - - assert.equal(frame.contentDocument.URL, url, "is expected iframe"); - - yield closeToolbox(); - - myTool.destroy(); -}); - - -exports["test ports is an optional"] = test(function*(assert) { - const MyPanel = Class({ - extends: Panel, - label: "no-port", - icon: iconURI, - url: makeHTML(() => { - window.addEventListener("message", event => { - if (event.ports.length) { - event.ports[0].postMessage(window.firstPacket); - } else { - window.firstPacket = event.data; - } - }); - }) - }); - - - const myTool = new Tool({ - panels: { - myPanel: MyPanel - } - }); - - - const toolbox = yield openToolbox(MyPanel); - const panel = yield getCurrentPanel(toolbox); - assert.ok(panel instanceof MyPanel, "is instance of MyPanel"); - - assert.isRendered(panel, toolbox); - - yield panel.ready(); - - const { port1, port2 } = new MessageChannel(); - port1.start(); - - panel.postMessage("hi"); - panel.postMessage("bye", [port2]); - - const packet = yield when(port1, "message"); - - assert.equal(packet.data, "hi", "got first packet back"); - - yield closeToolbox(); - - assert.equal(panel.readyState, "destroyed", "panel is destroyed"); - - myTool.destroy(); -}); - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-diffpatcher.js b/addon-sdk/source/test/test-diffpatcher.js deleted file mode 100644 index 47126c930..000000000 --- a/addon-sdk/source/test/test-diffpatcher.js +++ /dev/null @@ -1,8 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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"; - -exports["test diffpatcher"] = require("diffpatcher/test/index"); -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-dispatcher.js b/addon-sdk/source/test/test-dispatcher.js deleted file mode 100644 index 437d75176..000000000 --- a/addon-sdk/source/test/test-dispatcher.js +++ /dev/null @@ -1,76 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { dispatcher } = require("sdk/util/dispatcher"); - -exports["test dispatcher API"] = assert => { - const dispatch = dispatcher(); - - assert.equal(typeof(dispatch), "function", - "dispatch is a function"); - - assert.equal(typeof(dispatch.define), "function", - "dispatch.define is a function"); - - assert.equal(typeof(dispatch.implement), "function", - "dispatch.implement is a function"); - - assert.equal(typeof(dispatch.when), "function", - "dispatch.when is a function"); -}; - -exports["test dispatcher"] = assert => { - const isDuck = dispatcher(); - - const quacks = x => x && typeof(x.quack) === "function"; - - const Duck = function() {}; - const Goose = function() {}; - - const True = _ => true; - const False = _ => false; - - - - isDuck.define(Goose, False); - isDuck.define(Duck, True); - isDuck.when(quacks, True); - - assert.equal(isDuck(new Goose()), false, - "Goose ain't duck"); - - assert.equal(isDuck(new Duck()), true, - "Ducks are ducks"); - - assert.equal(isDuck({ quack: () => "Quaaaaaack!" }), true, - "It's a duck if it quacks"); - - - assert.throws(() => isDuck({}), /Type does not implements method/, "not implemneted"); - - isDuck.define(Object, False); - - assert.equal(isDuck({}), false, - "Ain't duck if it does not quacks!"); -}; - -exports["test redefining fails"] = assert => { - const isPM = dispatcher(); - const isAfternoon = time => time.getHours() > 12; - - isPM.when(isAfternoon, _ => true); - - assert.equal(isPM(new Date(Date.parse("Jan 23, 1985, 13:20:00"))), true, - "yeap afternoon"); - assert.equal(isPM({ getHours: _ => 17 }), true, - "seems like afternoon"); - - assert.throws(() => isPM.when(isAfternoon, x => x > 12 && x < 24), - /Already implemented for the given predicate/, - "can't redefine on same predicate"); - -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-disposable.js b/addon-sdk/source/test/test-disposable.js deleted file mode 100644 index 3204c2479..000000000 --- a/addon-sdk/source/test/test-disposable.js +++ /dev/null @@ -1,393 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Loader } = require("sdk/test/loader"); -const { Class } = require("sdk/core/heritage"); -const { Disposable } = require("sdk/core/disposable"); -const { Cc, Ci, Cu } = require("chrome"); -const { setTimeout } = require("sdk/timers"); - -exports["test disposeDisposable"] = assert => { - let loader = Loader(module); - - const { Disposable, disposeDisposable } = loader.require("sdk/core/disposable"); - const { isWeak, WeakReference } = loader.require("sdk/core/reference"); - - let disposals = 0; - - const Foo = Class({ - extends: Disposable, - implements: [WeakReference], - dispose(...params) { - disposeDisposable(this); - disposals = disposals + 1; - } - }); - - const f1 = new Foo(); - assert.equal(isWeak(f1), true, "f1 has WeakReference support"); - - f1.dispose(); - assert.equal(disposals, 1, "disposed on dispose"); - - loader.unload("uninstall"); - assert.equal(disposals, 1, "after disposeDisposable, dispose is not called anymore"); -}; - -exports["test destroy reasons"] = assert => { - let disposals = 0; - - const Foo = Class({ - extends: Disposable, - dispose: function() { - disposals = disposals + 1; - } - }); - - const f1 = new Foo(); - - f1.destroy(); - assert.equal(disposals, 1, "disposed on destroy"); - f1.destroy(); - assert.equal(disposals, 1, "second destroy is ignored"); - - disposals = 0; - const f2 = new Foo(); - - f2.destroy("uninstall"); - assert.equal(disposals, 1, "uninstall invokes disposal"); - f2.destroy("uninstall") - f2.destroy(); - assert.equal(disposals, 1, "disposal happens just once"); - - disposals = 0; - const f3 = new Foo(); - - f3.destroy("shutdown"); - assert.equal(disposals, 0, "shutdown invoke disposal"); - f3.destroy("shutdown"); - f3.destroy(); - assert.equal(disposals, 0, "shutdown disposal happens just once"); - - disposals = 0; - const f4 = new Foo(); - - f4.destroy("disable"); - assert.equal(disposals, 1, "disable invokes disposal"); - f4.destroy("disable") - f4.destroy(); - assert.equal(disposals, 1, "destroy happens just once"); - - disposals = 0; - const f5 = new Foo(); - - f5.destroy("disable"); - assert.equal(disposals, 1, "disable invokes disposal"); - f5.destroy("disable") - f5.destroy(); - assert.equal(disposals, 1, "destroy happens just once"); - - disposals = 0; - const f6 = new Foo(); - - f6.destroy("upgrade"); - assert.equal(disposals, 1, "upgrade invokes disposal"); - f6.destroy("upgrade") - f6.destroy(); - assert.equal(disposals, 1, "destroy happens just once"); - - disposals = 0; - const f7 = new Foo(); - - f7.destroy("downgrade"); - assert.equal(disposals, 1, "downgrade invokes disposal"); - f7.destroy("downgrade") - f7.destroy(); - assert.equal(disposals, 1, "destroy happens just once"); - - - disposals = 0; - const f8 = new Foo(); - - f8.destroy("whatever"); - assert.equal(disposals, 1, "unrecognized reason invokes disposal"); - f8.destroy("meh") - f8.destroy(); - assert.equal(disposals, 1, "destroy happens just once"); -}; - -exports["test different unload hooks"] = assert => { - const { uninstall, shutdown, disable, upgrade, - downgrade, dispose } = require("sdk/core/disposable"); - const UberUnload = Class({ - extends: Disposable, - setup: function() { - this.log = []; - } - }); - - uninstall.define(UberUnload, x => x.log.push("uninstall")); - shutdown.define(UberUnload, x => x.log.push("shutdown")); - disable.define(UberUnload, x => x.log.push("disable")); - upgrade.define(UberUnload, x => x.log.push("upgrade")); - downgrade.define(UberUnload, x => x.log.push("downgrade")); - dispose.define(UberUnload, x => x.log.push("dispose")); - - const u1 = new UberUnload(); - u1.destroy("uninstall"); - u1.destroy(); - u1.destroy("shutdown"); - assert.deepEqual(u1.log, ["uninstall"], "uninstall hook invoked"); - - const u2 = new UberUnload(); - u2.destroy("shutdown"); - u2.destroy(); - u2.destroy("uninstall"); - assert.deepEqual(u2.log, ["shutdown"], "shutdown hook invoked"); - - const u3 = new UberUnload(); - u3.destroy("disable"); - u3.destroy(); - u3.destroy("uninstall"); - assert.deepEqual(u3.log, ["disable"], "disable hook invoked"); - - const u4 = new UberUnload(); - u4.destroy("upgrade"); - u4.destroy(); - u4.destroy("uninstall"); - assert.deepEqual(u4.log, ["upgrade"], "upgrade hook invoked"); - - const u5 = new UberUnload(); - u5.destroy("downgrade"); - u5.destroy(); - u5.destroy("uninstall"); - assert.deepEqual(u5.log, ["downgrade"], "downgrade hook invoked"); - - const u6 = new UberUnload(); - u6.destroy(); - u6.destroy(); - u6.destroy("uninstall"); - assert.deepEqual(u6.log, ["dispose"], "dispose hook invoked"); - - const u7 = new UberUnload(); - u7.destroy("whatever"); - u7.destroy(); - u7.destroy("uninstall"); - assert.deepEqual(u7.log, ["dispose"], "dispose hook invoked"); -}; - -exports["test disposables are disposed on unload"] = function(assert) { - let loader = Loader(module); - let { Disposable } = loader.require("sdk/core/disposable"); - - let arg1 = {} - let arg2 = 2 - let disposals = 0 - - let Foo = Class({ - extends: Disposable, - setup: function setup(a, b) { - assert.equal(a, arg1, - "arguments passed to constructur is passed to setup"); - assert.equal(b, arg2, - "second argument is also passed to a setup"); - assert.ok(this instanceof Foo, - "this is an instance in the scope of the setup method"); - - this.fooed = true - }, - dispose: function dispose() { - assert.equal(this.fooed, true, "attribute was set") - this.fooed = false - disposals = disposals + 1 - } - }) - - let foo1 = Foo(arg1, arg2) - let foo2 = Foo(arg1, arg2) - - loader.unload(); - - assert.equal(disposals, 2, "both instances were disposed") -} - -exports["test destroyed windows dispose before unload"] = function(assert) { - let loader = Loader(module); - let { Disposable } = loader.require("sdk/core/disposable"); - - let arg1 = {} - let arg2 = 2 - let disposals = 0 - - let Foo = Class({ - extends: Disposable, - setup: function setup(a, b) { - assert.equal(a, arg1, - "arguments passed to constructur is passed to setup"); - assert.equal(b, arg2, - "second argument is also passed to a setup"); - assert.ok(this instanceof Foo, - "this is an instance in the scope of the setup method"); - - this.fooed = true - }, - dispose: function dispose() { - assert.equal(this.fooed, true, "attribute was set") - this.fooed = false - disposals = disposals + 1 - } - }) - - let foo1 = Foo(arg1, arg2) - let foo2 = Foo(arg1, arg2) - - foo1.destroy(); - assert.equal(disposals, 1, "destroy disposes instance") - - loader.unload(); - - assert.equal(disposals, 2, "unload disposes alive instances") -} - -exports["test disposables are GC-able"] = function(assert, done) { - let loader = Loader(module); - let { Disposable } = loader.require("sdk/core/disposable"); - let { WeakReference } = loader.require("sdk/core/reference"); - - let arg1 = {} - let arg2 = 2 - let disposals = 0 - - let Foo = Class({ - extends: Disposable, - implements: [WeakReference], - setup: function setup(a, b) { - assert.equal(a, arg1, - "arguments passed to constructur is passed to setup"); - assert.equal(b, arg2, - "second argument is also passed to a setup"); - assert.ok(this instanceof Foo, - "this is an instance in the scope of the setup method"); - - this.fooed = true - }, - dispose: function dispose() { - assert.equal(this.fooed, true, "attribute was set") - this.fooed = false - disposals = disposals + 1 - } - }); - - let foo1 = Foo(arg1, arg2) - let foo2 = Foo(arg1, arg2) - - foo1 = foo2 = null; - - Cu.schedulePreciseGC(function() { - loader.unload(); - assert.equal(disposals, 0, "GC removed dispose listeners"); - done(); - }); -} - - -exports["test loader unloads do not affect other loaders"] = function(assert) { - let loader1 = Loader(module); - let loader2 = Loader(module); - let { Disposable: Disposable1 } = loader1.require("sdk/core/disposable"); - let { Disposable: Disposable2 } = loader2.require("sdk/core/disposable"); - - let arg1 = {} - let arg2 = 2 - let disposals = 0 - - let Foo1 = Class({ - extends: Disposable1, - dispose: function dispose() { - disposals = disposals + 1; - } - }); - - let Foo2 = Class({ - extends: Disposable2, - dispose: function dispose() { - disposals = disposals + 1; - } - }); - - let foo1 = Foo1(arg1, arg2); - let foo2 = Foo2(arg1, arg2); - - assert.equal(disposals, 0, "no destroy calls"); - - loader1.unload(); - - assert.equal(disposals, 1, "1 destroy calls"); - - loader2.unload(); - - assert.equal(disposals, 2, "2 destroy calls"); -} - -exports["test disposables that throw"] = function(assert) { - let loader = Loader(module); - let { Disposable } = loader.require("sdk/core/disposable"); - - let disposals = 0 - - let Foo = Class({ - extends: Disposable, - setup: function setup(a, b) { - throw Error("Boom!") - }, - dispose: function dispose() { - disposals = disposals + 1 - } - }) - - assert.throws(function() { - let foo1 = Foo() - }, /Boom/, "disposable constructors may throw"); - - loader.unload(); - - assert.equal(disposals, 0, "no disposal if constructor threw"); -} - -exports["test multiple destroy"] = function(assert) { - let loader = Loader(module); - let { Disposable } = loader.require("sdk/core/disposable"); - - let disposals = 0 - - let Foo = Class({ - extends: Disposable, - dispose: function dispose() { - disposals = disposals + 1 - } - }) - - let foo1 = Foo(); - let foo2 = Foo(); - let foo3 = Foo(); - - assert.equal(disposals, 0, "no disposals yet"); - - foo1.destroy(); - assert.equal(disposals, 1, "disposed properly"); - foo1.destroy(); - assert.equal(disposals, 1, "didn't attempt to dispose twice"); - - foo2.destroy(); - assert.equal(disposals, 2, "other instances still dispose fine"); - foo2.destroy(); - assert.equal(disposals, 2, "but not twice"); - - loader.unload(); - - assert.equal(disposals, 3, "unload only disposed the remaining instance"); -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-dom.js b/addon-sdk/source/test/test-dom.js deleted file mode 100644 index 0b50a7639..000000000 --- a/addon-sdk/source/test/test-dom.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/. */ - -"use strict"; - -const events = require("sdk/dom/events"); -const { activeBrowserWindow: { document } } = require("sdk/deprecated/window-utils"); -const window = document.window; -/* -exports["test on / emit"] = function (assert, done) { - let element = document.createElement("div"); - events.on(element, "click", function listener(event) { - assert.equal(event.target, element, "event has correct target"); - events.removeListener(element, "click", listener); - done(); - }); - - events.emit(element, "click", { - category: "MouseEvents", - settings: [ - true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null - ] - }); -}; - -exports["test remove"] = function (assert, done) { - let element = document.createElement("span"); - let l1 = 0; - let l2 = 0; - let options = { - category: "MouseEvents", - settings: [ - true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null - ] - }; - - events.on(element, "click", function listener1(event) { - l1 ++; - assert.equal(event.target, element, "event has correct target"); - events.removeListener(element, "click", listener1); - }); - - events.on(element, "click", function listener2(event) { - l2 ++; - if (l1 < l2) { - assert.equal(l1, 1, "firs listener was called and then romeved"); - events.removeListener(element, "click", listener2); - done(); - } - events.emit(element, "click", options); - }); - - events.emit(element, "click", options); -}; - -exports["test once"] = function (assert, done) { - let element = document.createElement("h1"); - let l1 = 0; - let l2 = 0; - let options = { - category: "MouseEvents", - settings: [ - true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null - ] - }; - - - events.once(element, "click", function listener(event) { - assert.equal(event.target, element, "event target is a correct element"); - l1 ++; - }); - - events.on(element, "click", function listener(event) { - l2 ++; - if (l2 > 3) { - events.removeListener(element, "click", listener); - assert.equal(event.target, element, "event has correct target"); - assert.equal(l1, 1, "once was called only once"); - done(); - } - events.emit(element, "click", options); - }); - - events.emit(element, "click", options); -} -*/ -require("test").run(exports); diff --git a/addon-sdk/source/test/test-environment.js b/addon-sdk/source/test/test-environment.js deleted file mode 100644 index 9fec6f83d..000000000 --- a/addon-sdk/source/test/test-environment.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/. */ -'use strict'; - -const { env } = require('sdk/system/environment'); -const { Cc, Ci } = require('chrome'); -const { get, set, exists } = Cc['@mozilla.org/process/environment;1']. - getService(Ci.nsIEnvironment); - -exports['test exists'] = function(assert) { - assert.equal('PATH' in env, exists('PATH'), - 'PATH environment variable is defined'); - assert.equal('FOO1' in env, exists('FOO1'), - 'FOO1 environment variable is not defined'); - set('FOO1', 'foo'); - assert.equal('FOO1' in env, true, - 'FOO1 environment variable was set'); - set('FOO1', null); - assert.equal('FOO1' in env, false, - 'FOO1 environment variable was unset'); -}; - -exports['test get'] = function(assert) { - assert.equal(env.PATH, get('PATH'), 'PATH env variable matches'); - assert.equal(env.BAR2, undefined, 'BAR2 env variable is not defined'); - set('BAR2', 'bar'); - assert.equal(env.BAR2, 'bar', 'BAR2 env variable was set'); - set('BAR2', null); - assert.equal(env.BAR2, undefined, 'BAR2 env variable was unset'); -}; - -exports['test set'] = function(assert) { - assert.equal(get('BAZ3'), '', 'BAZ3 env variable is not set'); - assert.equal(env.BAZ3, undefined, 'BAZ3 is not set'); - env.BAZ3 = 'baz'; - assert.equal(env.BAZ3, get('BAZ3'), 'BAZ3 env variable is set'); - assert.equal(get('BAZ3'), 'baz', 'BAZ3 env variable was set to "baz"'); -}; - -exports['test unset'] = function(assert) { - env.BLA4 = 'bla'; - assert.equal(env.BLA4, 'bla', 'BLA4 env variable is set'); - assert.equal(delete env.BLA4, true, 'BLA4 env variable is removed'); - assert.equal(env.BLA4, undefined, 'BLA4 env variable is unset'); - assert.equal('BLA4' in env, false, 'BLA4 env variable no longer exists' ); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-event-core.js b/addon-sdk/source/test/test-event-core.js deleted file mode 100644 index ca937b259..000000000 --- a/addon-sdk/source/test/test-event-core.js +++ /dev/null @@ -1,347 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { on, once, off, emit, count } = require('sdk/event/core'); -const { LoaderWithHookedConsole } = require("sdk/test/loader"); -const { defer } = require("sdk/core/promise"); -const { gc } = require("sdk/test/memory"); - -exports['test add a listener'] = function(assert) { - let events = [ { name: 'event#1' }, 'event#2' ]; - let target = { name: 'target' }; - - on(target, 'message', function(message) { - assert.equal(this, target, 'this is a target object'); - assert.equal(message, events.shift(), 'message is emitted event'); - }); - emit(target, 'message', events[0]); - emit(target, 'message', events[0]); -}; - -exports['test that listener is unique per type'] = function(assert) { - let actual = [] - let target = {} - function listener() { actual.push(1) } - on(target, 'message', listener); - on(target, 'message', listener); - on(target, 'message', listener); - on(target, 'foo', listener); - on(target, 'foo', listener); - - emit(target, 'message'); - assert.deepEqual([ 1 ], actual, 'only one message listener added'); - emit(target, 'foo'); - assert.deepEqual([ 1, 1 ], actual, 'same listener added for other event'); -}; - -exports['test event type matters'] = function(assert) { - let target = { name: 'target' } - on(target, 'message', function() { - assert.fail('no event is expected'); - }); - on(target, 'done', function() { - assert.pass('event is emitted'); - }); - emit(target, 'foo') - emit(target, 'done'); -}; - -exports['test all arguments are pasesd'] = function(assert) { - let foo = { name: 'foo' }, bar = 'bar'; - let target = { name: 'target' }; - on(target, 'message', function(a, b) { - assert.equal(a, foo, 'first argument passed'); - assert.equal(b, bar, 'second argument passed'); - }); - emit(target, 'message', foo, bar); -}; - -exports['test no side-effects in emit'] = function(assert) { - let target = { name: 'target' }; - on(target, 'message', function() { - assert.pass('first listener is called'); - on(target, 'message', function() { - assert.fail('second listener is called'); - }); - }); - emit(target, 'message'); -}; - -exports['test can remove next listener'] = function(assert) { - let target = { name: 'target' }; - function fail() { - return assert.fail('Listener should be removed'); - }; - - on(target, 'data', function() { - assert.pass('first litener called'); - off(target, 'data', fail); - }); - on(target, 'data', fail); - - emit(target, 'data', 'hello'); -}; - -exports['test order of propagation'] = function(assert) { - let actual = []; - let target = { name: 'target' }; - on(target, 'message', function() { actual.push(1); }); - on(target, 'message', function() { actual.push(2); }); - on(target, 'message', function() { actual.push(3); }); - emit(target, 'message'); - assert.deepEqual([ 1, 2, 3 ], actual, 'called in order they were added'); -}; - -exports['test remove a listener'] = function(assert) { - let target = { name: 'target' }; - let actual = []; - on(target, 'message', function listener() { - actual.push(1); - on(target, 'message', function() { - off(target, 'message', listener); - actual.push(2); - }) - }); - - emit(target, 'message'); - assert.deepEqual([ 1 ], actual, 'first listener called'); - emit(target, 'message'); - assert.deepEqual([ 1, 1, 2 ], actual, 'second listener called'); - - emit(target, 'message'); - assert.deepEqual([ 1, 1, 2, 2, 2 ], actual, 'first listener removed'); -}; - -exports['test remove all listeners for type'] = function(assert) { - let actual = []; - let target = { name: 'target' } - on(target, 'message', function() { actual.push(1); }); - on(target, 'message', function() { actual.push(2); }); - on(target, 'message', function() { actual.push(3); }); - on(target, 'bar', function() { actual.push('b') }); - off(target, 'message'); - - emit(target, 'message'); - emit(target, 'bar'); - - assert.deepEqual([ 'b' ], actual, 'all message listeners were removed'); -}; - -exports['test remove all listeners'] = function(assert) { - let actual = []; - let target = { name: 'target' } - on(target, 'message', function() { actual.push(1); }); - on(target, 'message', function() { actual.push(2); }); - on(target, 'message', function() { actual.push(3); }); - on(target, 'bar', function() { actual.push('b') }); - off(target); - - emit(target, 'message'); - emit(target, 'bar'); - - assert.deepEqual([], actual, 'all listeners events were removed'); -}; - -exports['test falsy arguments are fine'] = function(assert) { - let type, listener, actual = []; - let target = { name: 'target' } - on(target, 'bar', function() { actual.push(0) }); - - off(target, 'bar', listener); - emit(target, 'bar'); - assert.deepEqual([ 0 ], actual, '3rd bad ard will keep listeners'); - - off(target, type); - emit(target, 'bar'); - assert.deepEqual([ 0, 0 ], actual, '2nd bad arg will keep listener'); - - off(target, type, listener); - emit(target, 'bar'); - assert.deepEqual([ 0, 0, 0 ], actual, '2nd&3rd bad args will keep listener'); -}; - -exports['test error handling'] = function(assert) { - let target = Object.create(null); - let error = Error('boom!'); - - on(target, 'message', function() { throw error; }) - on(target, 'error', function(boom) { - assert.equal(boom, error, 'thrown exception causes error event'); - }); - emit(target, 'message'); -}; - -exports['test unhandled exceptions'] = function(assert) { - let exceptions = []; - let { loader, messages } = LoaderWithHookedConsole(module); - - let { emit, on } = loader.require('sdk/event/core'); - let target = {}; - let boom = Error('Boom!'); - let drax = Error('Draax!!'); - - on(target, 'message', function() { throw boom; }); - - emit(target, 'message'); - assert.equal(messages.length, 1, 'Got the first exception'); - assert.equal(messages[0].type, 'exception', 'The console message is exception'); - assert.ok(~String(messages[0].msg).indexOf('Boom!'), - 'unhandled exception is logged'); - - on(target, 'error', function() { throw drax; }); - emit(target, 'message'); - assert.equal(messages.length, 2, 'Got the second exception'); - assert.equal(messages[1].type, 'exception', 'The console message is exception'); - assert.ok(~String(messages[1].msg).indexOf('Draax!'), - 'error in error handler is logged'); -}; - -exports['test unhandled errors'] = function(assert) { - let exceptions = []; - let { loader, messages } = LoaderWithHookedConsole(module); - - let { emit } = loader.require('sdk/event/core'); - let target = {}; - let boom = Error('Boom!'); - - emit(target, 'error', boom); - assert.equal(messages.length, 1, 'Error was logged'); - assert.equal(messages[0].type, 'exception', 'The console message is exception'); - assert.ok(~String(messages[0].msg).indexOf('Boom!'), - 'unhandled exception is logged'); -}; - -exports['test piped errors'] = function(assert) { - let exceptions = []; - let { loader, messages } = LoaderWithHookedConsole(module); - - let { emit } = loader.require('sdk/event/core'); - let { pipe } = loader.require('sdk/event/utils'); - let target = {}; - let second = {}; - - pipe(target, second); - emit(target, 'error', 'piped!'); - - assert.equal(messages.length, 1, 'error logged only once, ' + - 'considered "handled" on `target` by the catch-all pipe'); - assert.equal(messages[0].type, 'exception', 'The console message is exception'); - assert.ok(~String(messages[0].msg).indexOf('piped!'), - 'unhandled (piped) exception is logged on `second` target'); -}; - -exports['test count'] = function(assert) { - let target = {}; - - assert.equal(count(target, 'foo'), 0, 'no listeners for "foo" events'); - on(target, 'foo', function() {}); - assert.equal(count(target, 'foo'), 1, 'listener registered'); - on(target, 'foo', function() {}, 2, 'another listener registered'); - off(target) - assert.equal(count(target, 'foo'), 0, 'listeners unregistered'); -}; - -exports['test listen to all events'] = function(assert) { - let actual = []; - let target = {}; - - on(target, 'foo', message => actual.push(message)); - on(target, '*', (type, ...message) => { - actual.push([type].concat(message)); - }); - - emit(target, 'foo', 'hello'); - assert.equal(actual[0], 'hello', - 'non-wildcard listeners still work'); - assert.deepEqual(actual[1], ['foo', 'hello'], - 'wildcard listener called'); - - emit(target, 'bar', 'goodbye'); - assert.deepEqual(actual[2], ['bar', 'goodbye'], - 'wildcard listener called for unbound event name'); -}; - -exports['test once'] = function(assert, done) { - let target = {}; - let called = false; - let { resolve, promise } = defer(); - - once(target, 'foo', function(value) { - assert.ok(!called, "listener called only once"); - assert.equal(value, "bar", "correct argument was passed"); - }); - once(target, 'done', resolve); - - emit(target, 'foo', 'bar'); - emit(target, 'foo', 'baz'); - emit(target, 'done', ""); - - yield promise; -}; - -exports['test once with gc'] = function*(assert) { - let target = {}; - let called = false; - let { resolve, promise } = defer(); - - once(target, 'foo', function(value) { - assert.ok(!called, "listener called only once"); - assert.equal(value, "bar", "correct argument was passed"); - }); - once(target, 'done', resolve); - - yield gc(); - - emit(target, 'foo', 'bar'); - emit(target, 'foo', 'baz'); - emit(target, 'done', ""); - - yield promise; -}; - -exports["test removing once"] = function(assert, done) { - let target = {}; - - function test() { - assert.fail("listener was called"); - } - - once(target, "foo", test); - once(target, "done", done); - - off(target, "foo", test); - - assert.pass("emit foo"); - emit(target, "foo", "bar"); - - assert.pass("emit done"); - emit(target, "done", ""); -}; - -exports["test removing once with gc"] = function*(assert) { - let target = {}; - let { resolve, promise } = defer(); - - function test() { - assert.fail("listener was called"); - } - - once(target, "foo", test); - once(target, "done", resolve); - - yield gc(); - - off(target, "foo", test); - - assert.pass("emit foo"); - emit(target, "foo", "bar"); - - assert.pass("emit done"); - emit(target, "done", ""); - - yield promise; -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-event-dom.js b/addon-sdk/source/test/test-event-dom.js deleted file mode 100644 index fbbc6825b..000000000 --- a/addon-sdk/source/test/test-event-dom.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 { openWindow, closeWindow } = require('./util'); -const { Loader } = require('sdk/test/loader'); -const { getMostRecentBrowserWindow } = require('sdk/window/utils'); -const { Cc, Ci } = require('chrome'); -const els = Cc["@mozilla.org/eventlistenerservice;1"]. - getService(Ci.nsIEventListenerService); - -function countListeners(target, type) { - let listeners = els.getListenerInfoFor(target, {}); - return listeners.filter(listener => listener.type == type).length; -} - -exports['test window close clears listeners'] = function(assert) { - let window = yield openWindow(); - let loader = Loader(module); - - // Any element will do here - let gBrowser = window.gBrowser; - - // Other parts of the app may be listening for this - let windowListeners = countListeners(window, "DOMWindowClose"); - - // We can assume we're the only ones using the test events - assert.equal(countListeners(gBrowser, "TestEvent1"), 0, "Should be no listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 0, "Should be no listener for test event 2"); - - let { open } = loader.require('sdk/event/dom'); - - open(gBrowser, "TestEvent1"); - assert.equal(countListeners(window, "DOMWindowClose"), windowListeners + 1, - "Should have added a DOMWindowClose listener"); - assert.equal(countListeners(gBrowser, "TestEvent1"), 1, "Should be a listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 0, "Should be no listener for test event 2"); - - open(gBrowser, "TestEvent2"); - assert.equal(countListeners(window, "DOMWindowClose"), windowListeners + 1, - "Should not have added another DOMWindowClose listener"); - assert.equal(countListeners(gBrowser, "TestEvent1"), 1, "Should be a listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 1, "Should be a listener for test event 2"); - - window = yield closeWindow(window); - - assert.equal(countListeners(window, "DOMWindowClose"), windowListeners, - "Should have removed a DOMWindowClose listener"); - assert.equal(countListeners(gBrowser, "TestEvent1"), 0, "Should be no listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 0, "Should be no listener for test event 2"); - - loader.unload(); -}; - -exports['test unload clears listeners'] = function(assert) { - let window = getMostRecentBrowserWindow(); - let loader = Loader(module); - - // Any element will do here - let gBrowser = window.gBrowser; - - // Other parts of the app may be listening for this - let windowListeners = countListeners(window, "DOMWindowClose"); - - // We can assume we're the only ones using the test events - assert.equal(countListeners(gBrowser, "TestEvent1"), 0, "Should be no listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 0, "Should be no listener for test event 2"); - - let { open } = loader.require('sdk/event/dom'); - - open(gBrowser, "TestEvent1"); - assert.equal(countListeners(window, "DOMWindowClose"), windowListeners + 1, - "Should have added a DOMWindowClose listener"); - assert.equal(countListeners(gBrowser, "TestEvent1"), 1, "Should be a listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 0, "Should be no listener for test event 2"); - - open(gBrowser, "TestEvent2"); - assert.equal(countListeners(window, "DOMWindowClose"), windowListeners + 1, - "Should not have added another DOMWindowClose listener"); - assert.equal(countListeners(gBrowser, "TestEvent1"), 1, "Should be a listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 1, "Should be a listener for test event 2"); - - loader.unload(); - - assert.equal(countListeners(window, "DOMWindowClose"), windowListeners, - "Should have removed a DOMWindowClose listener"); - assert.equal(countListeners(gBrowser, "TestEvent1"), 0, "Should be no listener for test event 1"); - assert.equal(countListeners(gBrowser, "TestEvent2"), 0, "Should be no listener for test event 2"); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-event-target.js b/addon-sdk/source/test/test-event-target.js deleted file mode 100644 index d51314aa5..000000000 --- a/addon-sdk/source/test/test-event-target.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'; - -const { emit } = require('sdk/event/core'); -const { EventTarget } = require('sdk/event/target'); -const { Loader } = require('sdk/test/loader'); - -exports['test add a listener'] = function(assert) { - let events = [ { name: 'event#1' }, 'event#2' ]; - let target = EventTarget(); - - target.on('message', function(message) { - assert.equal(this, target, 'this is a target object'); - assert.equal(message, events.shift(), 'message is emitted event'); - }); - - emit(target, 'message', events[0]); - emit(target, 'message', events[0]); -}; - -exports['test pass in listeners'] = function(assert) { - let actual = [ ]; - let target = EventTarget({ - onMessage: function onMessage(message) { - assert.equal(this, target, 'this is an event target'); - actual.push(1); - }, - onFoo: null, - onbla: function() { - assert.fail('`onbla` is not supposed to be called'); - } - }); - target.on('message', function(message) { - assert.equal(this, target, 'this is an event target'); - actual.push(2); - }); - - emit(target, 'message'); - emit(target, 'missing'); - - assert.deepEqual([ 1, 2 ], actual, 'all listeners trigerred in right order'); -}; - -exports['test that listener is unique per type'] = function(assert) { - let actual = [] - let target = EventTarget(); - function listener() { actual.push(1) } - target.on('message', listener); - target.on('message', listener); - target.on('message', listener); - target.on('foo', listener); - target.on('foo', listener); - - emit(target, 'message'); - assert.deepEqual([ 1 ], actual, 'only one message listener added'); - emit(target, 'foo'); - assert.deepEqual([ 1, 1 ], actual, 'same listener added for other event'); -}; - -exports['test event type matters'] = function(assert) { - let target = EventTarget(); - target.on('message', function() { - assert.fail('no event is expected'); - }); - target.on('done', function() { - assert.pass('event is emitted'); - }); - - emit(target, 'foo'); - emit(target, 'done'); -}; - -exports['test all arguments are pasesd'] = function(assert) { - let foo = { name: 'foo' }, bar = 'bar'; - let target = EventTarget(); - target.on('message', function(a, b) { - assert.equal(a, foo, 'first argument passed'); - assert.equal(b, bar, 'second argument passed'); - }); - emit(target, 'message', foo, bar); -}; - -exports['test no side-effects in emit'] = function(assert) { - let target = EventTarget(); - target.on('message', function() { - assert.pass('first listener is called'); - target.on('message', function() { - assert.fail('second listener is called'); - }); - }); - emit(target, 'message'); -}; - -exports['test order of propagation'] = function(assert) { - let actual = []; - let target = EventTarget(); - target.on('message', function() { actual.push(1); }); - target.on('message', function() { actual.push(2); }); - target.on('message', function() { actual.push(3); }); - emit(target, 'message'); - assert.deepEqual([ 1, 2, 3 ], actual, 'called in order they were added'); -}; - -exports['test remove a listener'] = function(assert) { - let target = EventTarget(); - let actual = []; - target.on('message', function listener() { - actual.push(1); - target.on('message', function() { - target.removeListener('message', listener); - actual.push(2); - }) - }); - - emit(target, 'message'); - assert.deepEqual([ 1 ], actual, 'first listener called'); - emit(target, 'message'); - assert.deepEqual([ 1, 1, 2 ], actual, 'second listener called'); - emit(target, 'message'); - assert.deepEqual([ 1, 1, 2, 2, 2 ], actual, 'first listener removed'); -}; - -exports['test .off() removes all listeners'] = function(assert) { - let target = EventTarget(); - let actual = []; - target.on('message', function listener() { - actual.push(1); - target.on('message', function() { - target.removeListener('message', listener); - actual.push(2); - }) - }); - - emit(target, 'message'); - assert.deepEqual([ 1 ], actual, 'first listener called'); - emit(target, 'message'); - assert.deepEqual([ 1, 1, 2 ], actual, 'second listener called'); - target.off(); - emit(target, 'message'); - assert.deepEqual([ 1, 1, 2 ], actual, 'target.off() removed all listeners'); -}; - -exports['test error handling'] = function(assert) { - let target = EventTarget(); - let error = Error('boom!'); - - target.on('message', function() { throw error; }) - target.on('error', function(boom) { - assert.equal(boom, error, 'thrown exception causes error event'); - }); - emit(target, 'message'); -}; - -exports['test unhandled errors'] = function(assert) { - let exceptions = []; - let loader = Loader(module); - let { emit } = loader.require('sdk/event/core'); - let { EventTarget } = loader.require('sdk/event/target'); - Object.defineProperties(loader.sandbox('sdk/event/core'), { - console: { value: { - exception: function(e) { - exceptions.push(e); - } - }} - }); - let target = EventTarget(); - let boom = Error('Boom!'); - let drax = Error('Draax!!'); - - target.on('message', function() { throw boom; }); - - emit(target, 'message'); - assert.ok(~String(exceptions[0]).indexOf('Boom!'), - 'unhandled exception is logged'); - - target.on('error', function() { throw drax; }); - emit(target, 'message'); - assert.ok(~String(exceptions[1]).indexOf('Draax!'), - 'error in error handler is logged'); -}; - -exports['test target is chainable'] = function (assert, done) { - let loader = Loader(module); - let exceptions = []; - let { EventTarget } = loader.require('sdk/event/target'); - let { emit } = loader.require('sdk/event/core'); - Object.defineProperties(loader.sandbox('sdk/event/core'), { - console: { value: { - exception: function(e) { - exceptions.push(e); - } - }} - }); - - let emitter = EventTarget(); - let boom = Error('Boom'); - let onceCalled = 0; - - emitter.once('oneTime', function () { - assert.equal(++onceCalled, 1, 'once event called only once'); - }).on('data', function (message) { - assert.equal(message, 'message', 'handles event'); - emit(emitter, 'oneTime'); - emit(emitter, 'data2', 'message2'); - }).on('phony', function () { - assert.fail('removeListener does not remove chained event'); - }).removeListener('phony') - .on('data2', function (message) { - assert.equal(message, 'message2', 'handle chained event'); - emit(emitter, 'oneTime'); - throw boom; - }).on('error', function (error) { - assert.equal(error, boom, 'error handled in chained event'); - done(); - }); - - emit(emitter, 'data', 'message'); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-event-utils.js b/addon-sdk/source/test/test-event-utils.js deleted file mode 100644 index ea69e7677..000000000 --- a/addon-sdk/source/test/test-event-utils.js +++ /dev/null @@ -1,285 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { on, emit } = require("sdk/event/core"); -const { filter, map, merge, expand, pipe, stripListeners } = require("sdk/event/utils"); -const $ = require("./event/helpers"); - -function isEven(x) { - return !(x % 2); -} -function inc(x) { - return x + 1; -} - -exports["test filter events"] = function(assert) { - let input = {}; - let evens = filter(input, isEven); - let actual = []; - on(evens, "data", e => actual.push(e)); - - [1, 2, 3, 4, 5, 6, 7].forEach(x => emit(input, "data", x)); - - assert.deepEqual(actual, [2, 4, 6], "only even numbers passed through"); -}; - -exports["test filter emits"] = $.emits(function(input, assert) { - let output = filter(input, isEven); - assert(output, [1, 2, 3, 4, 5], [2, 4], "this is `output` & evens passed"); -});; - -exports["test filter reg once"] = $.registerOnce(function(input, assert) { - assert(filter(input, isEven), [1, 2, 3, 4, 5, 6], [2, 4, 6], - "listener can be registered only once"); -}); - -exports["test filter ignores new"] = $.ignoreNew(function(input, assert) { - assert(filter(input, isEven), [1, 2, 3], [2], - "new listener is ignored") -}); - -exports["test filter is FIFO"] = $.FIFO(function(input, assert) { - assert(filter(input, isEven), [1, 2, 3, 4], [2, 4], - "listeners are invoked in fifo order") -}); - -exports["test map events"] = function(assert) { - let input = {}; - let incs = map(input, inc); - let actual = []; - on(incs, "data", e => actual.push(e)); - - [1, 2, 3, 4].forEach(x => emit(input, "data", x)); - - assert.deepEqual(actual, [2, 3, 4, 5], "all numbers were incremented"); -}; - -exports["test map emits"] = $.emits(function(input, assert) { - let output = map(input, inc); - assert(output, [1, 2, 3], [2, 3, 4], "this is `output` & evens passed"); -}); - -exports["test map reg once"] = $.registerOnce(function(input, assert) { - assert(map(input, inc), [1, 2, 3], [2, 3, 4], - "listener can be registered only once"); -}); - -exports["test map ignores new"] = $.ignoreNew(function(input, assert) { - assert(map(input, inc), [1], [2], - "new listener is ignored") -}); - -exports["test map is FIFO"] = $.FIFO(function(input, assert) { - assert(map(input, inc), [1, 2, 3, 4], [2, 3, 4, 5], - "listeners are invoked in fifo order") -}); - -exports["test merge stream[stream]"] = function(assert) { - let a = {}, b = {}, c = {}; - let inputs = {}; - let actual = []; - - on(merge(inputs), "data", $ => actual.push($)) - - emit(inputs, "data", a); - emit(a, "data", "a1"); - emit(inputs, "data", b); - emit(b, "data", "b1"); - emit(a, "data", "a2"); - emit(inputs, "data", c); - emit(c, "data", "c1"); - emit(c, "data", "c2"); - emit(b, "data", "b2"); - emit(a, "data", "a3"); - - assert.deepEqual(actual, ["a1", "b1", "a2", "c1", "c2", "b2", "a3"], - "all inputs data merged into one"); -}; - -exports["test merge array[stream]"] = function(assert) { - let a = {}, b = {}, c = {}; - let inputs = {}; - let actual = []; - - on(merge([a, b, c]), "data", $ => actual.push($)) - - emit(a, "data", "a1"); - emit(b, "data", "b1"); - emit(a, "data", "a2"); - emit(c, "data", "c1"); - emit(c, "data", "c2"); - emit(b, "data", "b2"); - emit(a, "data", "a3"); - - assert.deepEqual(actual, ["a1", "b1", "a2", "c1", "c2", "b2", "a3"], - "all inputs data merged into one"); -}; - -exports["test merge emits"] = $.emits(function(input, assert) { - let evens = filter(input, isEven) - let output = merge([evens, input]); - assert(output, [1, 2, 3], [1, 2, 2, 3], "this is `output` & evens passed"); -}); - - -exports["test merge reg once"] = $.registerOnce(function(input, assert) { - let evens = filter(input, isEven) - let output = merge([input, evens]); - assert(output, [1, 2, 3, 4], [1, 2, 2, 3, 4, 4], - "listener can be registered only once"); -}); - -exports["test merge ignores new"] = $.ignoreNew(function(input, assert) { - let evens = filter(input, isEven) - let output = merge([input, evens]) - assert(output, [1], [1], - "new listener is ignored") -}); - -exports["test marge is FIFO"] = $.FIFO(function(input, assert) { - let evens = filter(input, isEven) - let output = merge([input, evens]) - - assert(output, [1, 2, 3, 4], [1, 2, 2, 3, 4, 4], - "listeners are invoked in fifo order") -}); - -exports["test expand"] = function(assert) { - let a = {}, b = {}, c = {}; - let inputs = {}; - let actual = []; - - on(expand(inputs, $ => $()), "data", $ => actual.push($)) - - emit(inputs, "data", () => a); - emit(a, "data", "a1"); - emit(inputs, "data", () => b); - emit(b, "data", "b1"); - emit(a, "data", "a2"); - emit(inputs, "data", () => c); - emit(c, "data", "c1"); - emit(c, "data", "c2"); - emit(b, "data", "b2"); - emit(a, "data", "a3"); - - assert.deepEqual(actual, ["a1", "b1", "a2", "c1", "c2", "b2", "a3"], - "all inputs data merged into one"); -}; - -exports["test pipe"] = function (assert, done) { - let src = {}; - let dest = {}; - - let aneventCount = 0, multiargsCount = 0; - let wildcardCount = {}; - - on(dest, 'an-event', arg => { - assert.equal(arg, 'my-arg', 'piped argument to event'); - ++aneventCount; - check(); - }); - on(dest, 'multiargs', (...data) => { - assert.equal(data[0], 'a', 'multiple arguments passed via pipe'); - assert.equal(data[1], 'b', 'multiple arguments passed via pipe'); - assert.equal(data[2], 'c', 'multiple arguments passed via pipe'); - ++multiargsCount; - check(); - }); - - on(dest, '*', (name, ...data) => { - wildcardCount[name] = (wildcardCount[name] || 0) + 1; - if (name === 'multiargs') { - assert.equal(data[0], 'a', 'multiple arguments passed via pipe, wildcard'); - assert.equal(data[1], 'b', 'multiple arguments passed via pipe, wildcard'); - assert.equal(data[2], 'c', 'multiple arguments passed via pipe, wildcard'); - } - if (name === 'an-event') - assert.equal(data[0], 'my-arg', 'argument passed via pipe, wildcard'); - check(); - }); - - pipe(src, dest); - - for (let i = 0; i < 3; i++) - emit(src, 'an-event', 'my-arg'); - - emit(src, 'multiargs', 'a', 'b', 'c'); - - function check () { - if (aneventCount === 3 && multiargsCount === 1 && - wildcardCount['an-event'] === 3 && - wildcardCount['multiargs'] === 1) - done(); - } -}; - -exports["test pipe multiple targets"] = function (assert) { - let src1 = {}; - let src2 = {}; - let middle = {}; - let dest = {}; - - pipe(src1, middle); - pipe(src2, middle); - pipe(middle, dest); - - let middleFired = 0; - let destFired = 0; - let src1Fired = 0; - let src2Fired = 0; - - on(src1, '*', () => src1Fired++); - on(src2, '*', () => src2Fired++); - on(middle, '*', () => middleFired++); - on(dest, '*', () => destFired++); - - emit(src1, 'ev'); - assert.equal(src1Fired, 1, 'event triggers in source in pipe chain'); - assert.equal(middleFired, 1, 'event passes through the middle of pipe chain'); - assert.equal(destFired, 1, 'event propagates to end of pipe chain'); - assert.equal(src2Fired, 0, 'event does not fire on alternative chain routes'); - - emit(src2, 'ev'); - assert.equal(src2Fired, 1, 'event triggers in source in pipe chain'); - assert.equal(middleFired, 2, - 'event passes through the middle of pipe chain from different src'); - assert.equal(destFired, 2, - 'event propagates to end of pipe chain from different src'); - assert.equal(src1Fired, 1, 'event does not fire on alternative chain routes'); - - emit(middle, 'ev'); - assert.equal(middleFired, 3, - 'event triggers in source of pipe chain'); - assert.equal(destFired, 3, - 'event propagates to end of pipe chain from middle src'); - assert.equal(src1Fired, 1, 'event does not fire on alternative chain routes'); - assert.equal(src2Fired, 1, 'event does not fire on alternative chain routes'); -}; - -exports['test stripListeners'] = function (assert) { - var options = { - onAnEvent: noop1, - onMessage: noop2, - verb: noop1, - value: 100 - }; - - var stripped = stripListeners(options); - assert.ok(stripped !== options, 'stripListeners should return a new object'); - assert.equal(options.onAnEvent, noop1, 'stripListeners does not affect original'); - assert.equal(options.onMessage, noop2, 'stripListeners does not affect original'); - assert.equal(options.verb, noop1, 'stripListeners does not affect original'); - assert.equal(options.value, 100, 'stripListeners does not affect original'); - - assert.ok(!stripped.onAnEvent, 'stripListeners removes `on*` values'); - assert.ok(!stripped.onMessage, 'stripListeners removes `on*` values'); - assert.equal(stripped.verb, noop1, 'stripListeners leaves not `on*` values'); - assert.equal(stripped.value, 100, 'stripListeners leaves not `on*` values'); - - function noop1 () {} - function noop2 () {} -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-file.js b/addon-sdk/source/test/test-file.js deleted file mode 100644 index 268c7f791..000000000 --- a/addon-sdk/source/test/test-file.js +++ /dev/null @@ -1,271 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { pathFor } = require('sdk/system'); -const file = require("sdk/io/file"); -const url = require("sdk/url"); - -const byteStreams = require("sdk/io/byte-streams"); -const textStreams = require("sdk/io/text-streams"); - -const ERRORS = { - FILE_NOT_FOUND: /^path does not exist: .+$/, - NOT_A_DIRECTORY: /^path is not a directory: .+$/, - NOT_A_FILE: /^path is not a file: .+$/, -}; - -// Use profile directory to list / read / write files. -const profilePath = pathFor('ProfD'); -const fileNameInProfile = 'compatibility.ini'; -const dirNameInProfile = 'extensions'; -const filePathInProfile = file.join(profilePath, fileNameInProfile); -const dirPathInProfile = file.join(profilePath, dirNameInProfile); - -exports.testDirName = function(assert) { - assert.equal(file.dirname(dirPathInProfile), profilePath, - "file.dirname() of dir should return parent dir"); - - assert.equal(file.dirname(filePathInProfile), profilePath, - "file.dirname() of file should return its dir"); - - let dir = profilePath; - while (dir) - dir = file.dirname(dir); - - assert.equal(dir, "", - "dirname should return empty string when dir has no parent"); -}; - -exports.testBasename = function(assert) { - // Get the top-most path -- the path with no basename. E.g., on Unix-like - // systems this will be /. We'll use it below to build up some test paths. - // We have to go to this trouble because file.join() needs a legal path as a - // base case; join("foo", "bar") doesn't work unfortunately. - let topPath = profilePath; - let parentPath = file.dirname(topPath); - while (parentPath) { - topPath = parentPath; - parentPath = file.dirname(topPath); - } - - let path = topPath; - assert.equal(file.basename(path), "", - "basename should work on paths with no components"); - - path = file.join(path, "foo"); - assert.equal(file.basename(path), "foo", - "basename should work on paths with a single component"); - - path = file.join(path, "bar"); - assert.equal(file.basename(path), "bar", - "basename should work on paths with multiple components"); -}; - -exports.testList = function(assert) { - let list = file.list(profilePath); - let found = list.filter(name => name === fileNameInProfile); - - assert.equal(found.length, 1, "file.list() should work"); - - assert.throws(function() { - file.list(filePathInProfile); - }, ERRORS.NOT_A_DIRECTORY, "file.list() on non-dir should raise error"); - - assert.throws(function() { - file.list(file.join(dirPathInProfile, "does-not-exist")); - }, ERRORS.FILE_NOT_FOUND, "file.list() on nonexistent should raise error"); -}; - -exports.testRead = function(assert) { - let contents = file.read(filePathInProfile); - assert.ok(/Compatibility/.test(contents), - "file.read() should work"); - - assert.throws(function() { - file.read(file.join(dirPathInProfile, "does-not-exists")); - }, ERRORS.FILE_NOT_FOUND, "file.read() on nonexistent file should throw"); - - assert.throws(function() { - file.read(dirPathInProfile); - }, ERRORS.NOT_A_FILE, "file.read() on dir should throw"); -}; - -exports.testJoin = function(assert) { - let baseDir = file.dirname(filePathInProfile); - - assert.equal(file.join(baseDir, fileNameInProfile), - filePathInProfile, "file.join() should work"); -}; - -exports.testOpenNonexistentForRead = function (assert) { - var filename = file.join(profilePath, 'does-not-exists'); - assert.throws(function() { - file.open(filename); - }, ERRORS.FILE_NOT_FOUND, "file.open() on nonexistent file should throw"); - - assert.throws(function() { - file.open(filename, "r"); - }, ERRORS.FILE_NOT_FOUND, "file.open('r') on nonexistent file should throw"); - - assert.throws(function() { - file.open(filename, "zz"); - }, ERRORS.FILE_NOT_FOUND, "file.open('zz') on nonexistent file should throw"); -}; - -exports.testOpenNonexistentForWrite = function (assert) { - let filename = file.join(profilePath, 'open.txt'); - - let stream = file.open(filename, "w"); - stream.close(); - - assert.ok(file.exists(filename), - "file.exists() should return true after file.open('w')"); - file.remove(filename); - assert.ok(!file.exists(filename), - "file.exists() should return false after file.remove()"); - - stream = file.open(filename, "rw"); - stream.close(); - - assert.ok(file.exists(filename), - "file.exists() should return true after file.open('rw')"); - file.remove(filename); - assert.ok(!file.exists(filename), - "file.exists() should return false after file.remove()"); -}; - -exports.testOpenDirectory = function (assert) { - let dir = dirPathInProfile; - assert.throws(function() { - file.open(dir); - }, ERRORS.NOT_A_FILE, "file.open() on directory should throw"); - - assert.throws(function() { - file.open(dir, "w"); - }, ERRORS.NOT_A_FILE, "file.open('w') on directory should throw"); -}; - -exports.testOpenTypes = function (assert) { - let filename = file.join(profilePath, 'open-types.txt'); - - - // Do the opens first to create the data file. - var stream = file.open(filename, "w"); - assert.ok(stream instanceof textStreams.TextWriter, - "open(w) should return a TextWriter"); - stream.close(); - - stream = file.open(filename, "wb"); - assert.ok(stream instanceof byteStreams.ByteWriter, - "open(wb) should return a ByteWriter"); - stream.close(); - - stream = file.open(filename); - assert.ok(stream instanceof textStreams.TextReader, - "open() should return a TextReader"); - stream.close(); - - stream = file.open(filename, "r"); - assert.ok(stream instanceof textStreams.TextReader, - "open(r) should return a TextReader"); - stream.close(); - - stream = file.open(filename, "b"); - assert.ok(stream instanceof byteStreams.ByteReader, - "open(b) should return a ByteReader"); - stream.close(); - - stream = file.open(filename, "rb"); - assert.ok(stream instanceof byteStreams.ByteReader, - "open(rb) should return a ByteReader"); - stream.close(); - - file.remove(filename); -}; - -exports.testMkpathRmdir = function (assert) { - let basePath = profilePath; - let dirs = []; - for (let i = 0; i < 3; i++) - dirs.push("test-file-dir"); - - let paths = []; - for (let i = 0; i < dirs.length; i++) { - let args = [basePath].concat(dirs.slice(0, i + 1)); - paths.unshift(file.join.apply(null, args)); - } - - for (let i = 0; i < paths.length; i++) { - assert.ok(!file.exists(paths[i]), - "Sanity check: path should not exist: " + paths[i]); - } - - file.mkpath(paths[0]); - assert.ok(file.exists(paths[0]), "mkpath should create path: " + paths[0]); - - for (let i = 0; i < paths.length; i++) { - file.rmdir(paths[i]); - assert.ok(!file.exists(paths[i]), - "rmdir should remove path: " + paths[i]); - } -}; - -exports.testMkpathTwice = function (assert) { - let dir = profilePath; - let path = file.join(dir, "test-file-dir"); - assert.ok(!file.exists(path), - "Sanity check: path should not exist: " + path); - file.mkpath(path); - assert.ok(file.exists(path), "mkpath should create path: " + path); - file.mkpath(path); - assert.ok(file.exists(path), - "After second mkpath, path should still exist: " + path); - file.rmdir(path); - assert.ok(!file.exists(path), "rmdir should remove path: " + path); -}; - -exports.testMkpathExistingNondirectory = function (assert) { - var fname = file.join(profilePath, 'conflict.txt'); - file.open(fname, "w").close(); - assert.ok(file.exists(fname), "File should exist"); - assert.throws(() => file.mkpath(fname), - /^The path already exists and is not a directory: .+$/, - "mkpath on file should raise error"); - file.remove(fname); -}; - -exports.testRmdirNondirectory = function (assert) { - var fname = file.join(profilePath, 'not-a-dir') - file.open(fname, "w").close(); - assert.ok(file.exists(fname), "File should exist"); - assert.throws(function() { - file.rmdir(fname); - }, ERRORS.NOT_A_DIRECTORY, "rmdir on file should raise error"); - file.remove(fname); - assert.ok(!file.exists(fname), "File should not exist"); - assert.throws(() => file.rmdir(fname), - ERRORS.FILE_NOT_FOUND, - "rmdir on non-existing file should raise error"); -}; - -exports.testRmdirNonempty = function (assert) { - let dir = profilePath; - let path = file.join(dir, "test-file-dir"); - assert.ok(!file.exists(path), - "Sanity check: path should not exist: " + path); - file.mkpath(path); - let filePath = file.join(path, "file"); - file.open(filePath, "w").close(); - assert.ok(file.exists(filePath), - "Sanity check: path should exist: " + filePath); - assert.throws(() => file.rmdir(path), - /^The directory is not empty: .+$/, - "rmdir on non-empty directory should raise error"); - file.remove(filePath); - file.rmdir(path); - assert.ok(!file.exists(path), "Path should not exist"); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-frame-utils.js b/addon-sdk/source/test/test-frame-utils.js deleted file mode 100644 index 501f93c87..000000000 --- a/addon-sdk/source/test/test-frame-utils.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'; - -const { create } = require('sdk/frame/utils'); -const { open, close } = require('sdk/window/helpers'); - -exports['test frame creation'] = function(assert, done) { - open('data:text/html;charset=utf-8,Window').then(function (window) { - let frame = create(window.document); - - assert.equal(frame.getAttribute('type'), 'content', - 'frame type is content'); - assert.ok(frame.contentWindow, 'frame has contentWindow'); - assert.equal(frame.contentWindow.location.href, 'about:blank', - 'by default "about:blank" is loaded'); - assert.equal(frame.docShell.allowAuth, false, 'auth disabled by default'); - assert.equal(frame.docShell.allowJavascript, false, 'js disabled by default'); - assert.equal(frame.docShell.allowPlugins, false, - 'plugins disabled by default'); - close(window).then(done); - }); -}; - -exports['test fram has js disabled by default'] = function(assert, done) { - open('data:text/html;charset=utf-8,window').then(function (window) { - let frame = create(window.document, { - uri: 'data:text/html;charset=utf-8,', - }); - frame.contentWindow.addEventListener('DOMContentLoaded', function ready() { - frame.contentWindow.removeEventListener('DOMContentLoaded', ready, false); - assert.ok(!~frame.contentDocument.documentElement.innerHTML.indexOf('JS'), - 'JS was executed'); - - close(window).then(done); - }, false); - }); -}; - -exports['test frame with js enabled'] = function(assert, done) { - open('data:text/html;charset=utf-8,window').then(function (window) { - let frame = create(window.document, { - uri: 'data:text/html;charset=utf-8,', - allowJavascript: true - }); - frame.contentWindow.addEventListener('DOMContentLoaded', function ready() { - frame.contentWindow.removeEventListener('DOMContentLoaded', ready, false); - assert.ok(~frame.contentDocument.documentElement.innerHTML.indexOf('JS'), - 'JS was executed'); - - close(window).then(done); - }, false); - }); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-framescript-manager.js b/addon-sdk/source/test/test-framescript-manager.js deleted file mode 100644 index 442f71eda..000000000 --- a/addon-sdk/source/test/test-framescript-manager.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/. */ -"use strict"; - -const {loadModule} = require("framescript/manager"); -const {withTab, receiveMessage} = require("./util"); -const {getBrowserForTab} = require("sdk/tabs/utils"); - -exports.testLoadModule = withTab(function*(assert, tab) { - const {messageManager} = getBrowserForTab(tab); - - loadModule(messageManager, - require.resolve("./framescript-manager/frame-script"), - true, - "onInit"); - - const message = yield receiveMessage(messageManager, "framescript-manager/ready"); - - assert.deepEqual(message.data, {state: "ready"}, - "received ready message from the loaded module"); - - messageManager.sendAsyncMessage("framescript-manager/ping", {x: 1}); - - const pong = yield receiveMessage(messageManager, "framescript-manager/pong"); - - assert.deepEqual(pong.data, {x: 1}, - "received pong back"); -}, "data:text/html,

Message Manager

"); - - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-framescript-util.js b/addon-sdk/source/test/test-framescript-util.js deleted file mode 100644 index 0a55bcbf6..000000000 --- a/addon-sdk/source/test/test-framescript-util.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 {loadModule} = require("framescript/manager"); -const {withTab, receiveMessage} = require("./util"); -const {getBrowserForTab} = require("sdk/tabs/utils"); - -exports["test windowToMessageManager"] = withTab(function*(assert, tab) { - const {messageManager} = getBrowserForTab(tab); - - loadModule(messageManager, - require.resolve("./framescript-util/frame-script"), - true, - "onInit"); - - messageManager.sendAsyncMessage("framescript-util/window/request"); - - const response = yield receiveMessage(messageManager, - "framescript-util/window/response"); - - assert.deepEqual(response.data, {window: true}, - "got response"); -}, "data:text/html,

Window to Message Manager

"); - - -exports["test nodeToMessageManager"] = withTab(function*(assert, tab) { - const {messageManager} = getBrowserForTab(tab); - - loadModule(messageManager, - require.resolve("./framescript-util/frame-script"), - true, - "onInit"); - - messageManager.sendAsyncMessage("framescript-util/node/request", "h1"); - - const response = yield receiveMessage(messageManager, - "framescript-util/node/response"); - - assert.deepEqual(response.data, {node: true}, - "got response"); -}, "data:text/html,

Node to Message Manager

"); - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-fs.js b/addon-sdk/source/test/test-fs.js deleted file mode 100644 index ed26ca3e3..000000000 --- a/addon-sdk/source/test/test-fs.js +++ /dev/null @@ -1,621 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { pathFor, platform } = require("sdk/system"); -const fs = require("sdk/io/fs"); -const url = require("sdk/url"); -const path = require("sdk/fs/path"); -const { defer } = require("sdk/core/promise"); -const { Buffer } = require("sdk/io/buffer"); -const { is } = require("sdk/system/xul-app"); - -// Use profile directory to list / read / write files. -const profilePath = pathFor("ProfD"); -const fileNameInProfile = "compatibility.ini"; -const dirNameInProfile = "extensions"; -const filePathInProfile = path.join(profilePath, fileNameInProfile); -const dirPathInProfile = path.join(profilePath, dirNameInProfile); -const mkdirPath = path.join(profilePath, "sdk-fixture-mkdir"); -const writePath = path.join(profilePath, "sdk-fixture-writeFile"); -const unlinkPath = path.join(profilePath, "sdk-fixture-unlink"); -const truncatePath = path.join(profilePath, "sdk-fixture-truncate"); -const renameFromPath = path.join(profilePath, "sdk-fixture-rename-from"); -const renameToPath = path.join(profilePath, "sdk-fixture-rename-to"); -const chmodPath = path.join(profilePath, "sdk-fixture-chmod"); - -const profileEntries = [ - "compatibility.ini", - "extensions", - "prefs.js" - // There are likely to be a lot more files but we can"t really - // on consistent list so we limit to this. -]; - -const isWindows = platform.indexOf('win') === 0; - -exports["test readdir"] = function(assert, end) { - var async = false; - fs.readdir(profilePath, function(error, entries) { - assert.ok(async, "readdir is async"); - assert.ok(!error, "there is no error when reading directory"); - assert.ok(profileEntries.length <= entries.length, - "got at least number of entries we expect"); - assert.ok(profileEntries.every(function(entry) { - return entries.indexOf(entry) >= 0; - }), "all profiles are present"); - end(); - }); - - async = true; -}; - -exports["test readdir error"] = function(assert, end) { - var async = false; - var path = profilePath + "-does-not-exists"; - fs.readdir(path, function(error, entries) { - assert.ok(async, "readdir is async"); - assert.equal(error.message, "ENOENT, readdir " + path); - assert.equal(error.code, "ENOENT", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 34, "error has a errno"); - end(); - }); - - async = true; -}; - -exports["test readdirSync"] = function(assert) { - var async = false; - var entries = fs.readdirSync(profilePath); - assert.ok(profileEntries.length <= entries.length, - "got at least number of entries we expect"); - assert.ok(profileEntries.every(function(entry) { - return entries.indexOf(entry) >= 0; - }), "all profiles are present"); -}; - -exports["test readdirSync error"] = function(assert) { - var async = false; - var path = profilePath + "-does-not-exists"; - try { - fs.readdirSync(path); - assert.fail(Error("No error was thrown")); - } catch (error) { - assert.equal(error.message, "ENOENT, readdir " + path); - assert.equal(error.code, "ENOENT", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 34, "error has a errno"); - } -}; - -exports["test readFile"] = function(assert, end) { - let async = false; - fs.readFile(filePathInProfile, function(error, content) { - assert.ok(async, "readFile is async"); - assert.ok(!error, "error is falsy"); - - assert.ok(Buffer.isBuffer(content), "readFile returns buffer"); - assert.ok(typeof(content.length) === "number", "buffer has length"); - assert.ok(content.toString().indexOf("[Compatibility]") >= 0, - "content contains expected data"); - end(); - }); - async = true; -}; - -exports["test readFile error"] = function(assert, end) { - let async = false; - let path = filePathInProfile + "-does-not-exists"; - fs.readFile(path, function(error, content) { - assert.ok(async, "readFile is async"); - assert.equal(error.message, "ENOENT, open " + path); - assert.equal(error.code, "ENOENT", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 34, "error has a errno"); - - end(); - }); - async = true; -}; - -exports["test readFileSync not implemented"] = function(assert) { - let buffer = fs.readFileSync(filePathInProfile); - assert.ok(buffer.toString().indexOf("[Compatibility]") >= 0, - "read content"); -}; - -exports["test fs.stat file"] = function(assert, end) { - let async = false; - let path = filePathInProfile; - fs.stat(path, function(error, stat) { - assert.ok(async, "fs.stat is async"); - assert.ok(!error, "error is falsy"); - assert.ok(!stat.isDirectory(), "not a dir"); - assert.ok(stat.isFile(), "is a file"); - assert.ok(!stat.isSymbolicLink(), "isn't a symlink"); - assert.ok(typeof(stat.size) === "number", "size is a number"); - assert.ok(stat.exists === true, "file exists"); - assert.ok(typeof(stat.isBlockDevice()) === "boolean"); - assert.ok(typeof(stat.isCharacterDevice()) === "boolean"); - assert.ok(typeof(stat.isFIFO()) === "boolean"); - assert.ok(typeof(stat.isSocket()) === "boolean"); - assert.ok(typeof(stat.hidden) === "boolean"); - assert.ok(typeof(stat.writable) === "boolean") - assert.ok(stat.readable === true); - - end(); - }); - async = true; -}; - -exports["test fs.stat dir"] = function(assert, end) { - let async = false; - let path = dirPathInProfile; - fs.stat(path, function(error, stat) { - assert.ok(async, "fs.stat is async"); - assert.ok(!error, "error is falsy"); - assert.ok(stat.isDirectory(), "is a dir"); - assert.ok(!stat.isFile(), "not a file"); - assert.ok(!stat.isSymbolicLink(), "isn't a symlink"); - assert.ok(typeof(stat.size) === "number", "size is a number"); - assert.ok(stat.exists === true, "file exists"); - assert.ok(typeof(stat.isBlockDevice()) === "boolean"); - assert.ok(typeof(stat.isCharacterDevice()) === "boolean"); - assert.ok(typeof(stat.isFIFO()) === "boolean"); - assert.ok(typeof(stat.isSocket()) === "boolean"); - assert.ok(typeof(stat.hidden) === "boolean"); - assert.ok(typeof(stat.writable) === "boolean") - assert.ok(typeof(stat.readable) === "boolean"); - - end(); - }); - async = true; -}; - -exports["test fs.stat error"] = function(assert, end) { - let async = false; - let path = filePathInProfile + "-does-not-exists"; - fs.stat(path, function(error, stat) { - assert.ok(async, "fs.stat is async"); - assert.equal(error.message, "ENOENT, stat " + path); - assert.equal(error.code, "ENOENT", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 34, "error has a errno"); - - end(); - }); - async = true; -}; - -exports["test fs.exists NO"] = function(assert, end) { - let async = false - let path = filePathInProfile + "-does-not-exists"; - fs.exists(path, function(error, value) { - assert.ok(async, "fs.exists is async"); - assert.ok(!error, "error is falsy"); - assert.ok(!value, "file does not exists"); - end(); - }); - async = true; -}; - -exports["test fs.exists YES"] = function(assert, end) { - let async = false - let path = filePathInProfile - fs.exists(path, function(error, value) { - assert.ok(async, "fs.exists is async"); - assert.ok(!error, "error is falsy"); - assert.ok(value, "file exists"); - end(); - }); - async = true; -}; - -exports["test fs.exists NO"] = function(assert, end) { - let async = false - let path = filePathInProfile + "-does-not-exists"; - fs.exists(path, function(error, value) { - assert.ok(async, "fs.exists is async"); - assert.ok(!error, "error is falsy"); - assert.ok(!value, "file does not exists"); - end(); - }); - async = true; -}; - -exports["test fs.existsSync"] = function(assert) { - let path = filePathInProfile - assert.equal(fs.existsSync(path), true, "exists"); - assert.equal(fs.existsSync(path + "-does-not-exists"), false, "exists"); -}; - -exports["test fs.mkdirSync fs.rmdirSync"] = function(assert) { - let path = mkdirPath; - - assert.equal(fs.existsSync(path), false, "does not exists"); - fs.mkdirSync(path); - assert.equal(fs.existsSync(path), true, "dir was created"); - try { - fs.mkdirSync(path); - assert.fail(Error("mkdir on existing should throw")); - } catch (error) { - assert.equal(error.message, "EEXIST, mkdir " + path); - assert.equal(error.code, "EEXIST", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 47, "error has a errno"); - } - fs.rmdirSync(path); - assert.equal(fs.existsSync(path), false, "dir was removed"); -}; - -exports["test fs.mkdir"] = function(assert, end) { - let path = mkdirPath; - - if (!fs.existsSync(path)) { - let async = false; - fs.mkdir(path, function(error) { - assert.ok(async, "mkdir is async"); - assert.ok(!error, "no error"); - assert.equal(fs.existsSync(path), true, "dir was created"); - fs.rmdirSync(path); - assert.equal(fs.existsSync(path), false, "dir was removed"); - end(); - }); - async = true; - } -}; - -exports["test fs.mkdir error"] = function(assert, end) { - let path = mkdirPath; - - if (!fs.existsSync(path)) { - fs.mkdirSync(path); - let async = false; - fs.mkdir(path, function(error) { - assert.ok(async, "mkdir is async"); - assert.equal(error.message, "EEXIST, mkdir " + path); - assert.equal(error.code, "EEXIST", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 47, "error has a errno"); - fs.rmdirSync(path); - assert.equal(fs.existsSync(path), false, "dir was removed"); - end(); - }); - async = true; - } -}; - -exports["test fs.rmdir"] = function(assert, end) { - let path = mkdirPath; - - if (!fs.existsSync(path)) { - fs.mkdirSync(path); - assert.equal(fs.existsSync(path), true, "dir exists"); - let async = false; - fs.rmdir(path, function(error) { - assert.ok(async, "mkdir is async"); - assert.ok(!error, "no error"); - assert.equal(fs.existsSync(path), false, "dir was removed"); - end(); - }); - async = true; - } -}; - - -exports["test fs.rmdir error"] = function(assert, end) { - let path = mkdirPath; - - if (!fs.existsSync(path)) { - assert.equal(fs.existsSync(path), false, "dir doesn't exists"); - let async = false; - fs.rmdir(path, function(error) { - assert.ok(async, "mkdir is async"); - assert.equal(error.message, "ENOENT, remove " + path); - assert.equal(error.code, "ENOENT", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 34, "error has a errno"); - assert.equal(fs.existsSync(path), false, "dir is removed"); - end(); - }); - async = true; - } -}; - -exports["test fs.truncateSync fs.unlinkSync"] = function(assert) { - let path = truncatePath; - - assert.equal(fs.existsSync(path), false, "does not exists"); - fs.truncateSync(path); - assert.equal(fs.existsSync(path), true, "file was created"); - fs.truncateSync(path); - fs.unlinkSync(path); - assert.equal(fs.existsSync(path), false, "file was removed"); -}; - - -exports["test fs.truncate"] = function(assert, end) { - let path = truncatePath; - if (!fs.existsSync(path)) { - let async = false; - fs.truncate(path, 0, function(error) { - assert.ok(async, "truncate is async"); - assert.ok(!error, "no error"); - assert.equal(fs.existsSync(path), true, "file was created"); - fs.unlinkSync(path); - assert.equal(fs.existsSync(path), false, "file was removed"); - end(); - }) - async = true; - } -}; - -exports["test fs.unlink"] = function(assert, end) { - let path = unlinkPath; - let async = false; - assert.ok(!fs.existsSync(path), "file doesn't exists yet"); - fs.truncateSync(path, 0); - assert.ok(fs.existsSync(path), "file was created"); - fs.unlink(path, function(error) { - assert.ok(async, "fs.unlink is async"); - assert.ok(!error, "error is falsy"); - assert.ok(!fs.existsSync(path), "file was removed"); - end(); - }); - async = true; -}; - -exports["test fs.unlink error"] = function(assert, end) { - let path = unlinkPath; - let async = false; - assert.ok(!fs.existsSync(path), "file doesn't exists yet"); - fs.unlink(path, function(error) { - assert.ok(async, "fs.unlink is async"); - assert.equal(error.message, "ENOENT, remove " + path); - assert.equal(error.code, "ENOENT", "error has a code"); - assert.equal(error.path, path, "error has a path"); - assert.equal(error.errno, 34, "error has a errno"); - end(); - }); - async = true; -}; - -exports["test fs.rename"] = function(assert, end) { - let fromPath = renameFromPath; - let toPath = renameToPath; - - fs.truncateSync(fromPath); - assert.ok(fs.existsSync(fromPath), "source file exists"); - assert.ok(!fs.existsSync(toPath), "destination doesn't exists"); - var async = false; - fs.rename(fromPath, toPath, function(error) { - assert.ok(async, "fs.rename is async"); - assert.ok(!error, "error is falsy"); - assert.ok(!fs.existsSync(fromPath), "source path no longer exists"); - assert.ok(fs.existsSync(toPath), "destination file exists"); - fs.unlinkSync(toPath); - assert.ok(!fs.existsSync(toPath), "cleaned up properly"); - end(); - }); - async = true; -}; - -exports["test fs.rename (missing source file)"] = function(assert, end) { - let fromPath = renameFromPath; - let toPath = renameToPath; - - assert.ok(!fs.existsSync(fromPath), "source file doesn't exists"); - assert.ok(!fs.existsSync(toPath), "destination doesn't exists"); - var async = false; - fs.rename(fromPath, toPath, function(error) { - assert.ok(async, "fs.rename is async"); - assert.equal(error.message, "ENOENT, rename " + fromPath); - assert.equal(error.code, "ENOENT", "error has a code"); - assert.equal(error.path, fromPath, "error has a path"); - assert.equal(error.errno, 34, "error has a errno"); - end(); - }); - async = true; -}; - -exports["test fs.rename (existing target file)"] = function(assert, end) { - let fromPath = renameFromPath; - let toPath = renameToPath; - - fs.truncateSync(fromPath); - fs.truncateSync(toPath); - assert.ok(fs.existsSync(fromPath), "source file exists"); - assert.ok(fs.existsSync(toPath), "destination file exists"); - var async = false; - fs.rename(fromPath, toPath, function(error) { - assert.ok(async, "fs.rename is async"); - assert.ok(!error, "error is falsy"); - assert.ok(!fs.existsSync(fromPath), "source path no longer exists"); - assert.ok(fs.existsSync(toPath), "destination file exists"); - fs.unlinkSync(toPath); - assert.ok(!fs.existsSync(toPath), "cleaned up properly"); - end(); - }); - async = true; -}; - -exports["test fs.writeFile"] = function(assert, end) { - let path = writePath; - let content = ["hello world", - "this is some text"].join("\n"); - - var async = false; - fs.writeFile(path, content, function(error) { - assert.ok(async, "fs write is async"); - assert.ok(!error, "error is falsy"); - assert.ok(fs.existsSync(path), "file was created"); - assert.equal(fs.readFileSync(path).toString(), - content, - "contet was written"); - fs.unlinkSync(path); - assert.ok(!fs.exists(path), "file was removed"); - - end(); - }); - async = true; -}; - -exports["test fs.writeFile (with large files)"] = function(assert, end) { - let path = writePath; - let content = ""; - - for (var i = 0; i < 100000; i++) { - content += "buffer\n"; - } - - var async = false; - fs.writeFile(path, content, function(error) { - assert.ok(async, "fs write is async"); - assert.ok(!error, "error is falsy"); - assert.ok(fs.existsSync(path), "file was created"); - assert.equal(fs.readFileSync(path).toString(), - content, - "contet was written"); - fs.unlinkSync(path); - assert.ok(!fs.exists(path), "file was removed"); - - end(); - }); - async = true; -}; - -exports["test fs.writeFile error"] = function (assert, done) { - try { - fs.writeFile({}, 'content', function (err) { - assert.fail('Error thrown from TypeError should not be caught'); - }); - } catch (e) { - assert.ok(e, - 'writeFile with a non-string error should not be caught'); - assert.equal(e.name, 'TypeError', 'error should be TypeError'); - } - fs.writeFile('not/a/valid/path', 'content', function (err) { - assert.ok(err, 'error caught and handled in callback'); - done(); - }); -}; - -exports["test fs.chmod"] = function (assert, done) { - let content = ["hej från sverige"]; - - fs.writeFile(chmodPath, content, function (err) { - testPerm("0755")() - .then(testPerm("0777")) - .then(testPerm("0666")) - .then(testPerm(0o511)) - .then(testPerm(0o200)) - .then(testPerm("0040")) - .then(testPerm("0000")) - .then(testPermSync(0o777)) - .then(testPermSync(0o666)) - .then(testPermSync("0511")) - .then(testPermSync("0200")) - .then(testPermSync("0040")) - .then(testPermSync("0000")) - .then(() => { - assert.pass("Successful chmod passes"); - }, assert.fail) - // Test invalid paths - .then(() => chmod("not-a-valid-file", 0o755)) - .then(assert.fail, (err) => { - checkPermError(err, "not-a-valid-file"); - }) - .then(() => chmod("not-a-valid-file", 0o755, "sync")) - .then(assert.fail, (err) => { - checkPermError(err, "not-a-valid-file"); - }) - // Test invalid files - .then(() => chmod("resource://not-a-real-file", 0o755)) - .then(assert.fail, (err) => { - checkPermError(err, "resource://not-a-real-file"); - }) - .then(() => chmod("resource://not-a-real-file", 0o755, 'sync')) - .then(assert.fail, (err) => { - checkPermError(err, "resource://not-a-real-file"); - }) - .then(done, assert.fail); - }); - - function checkPermError (err, path) { - assert.equal(err.message, "ENOENT, chmod " + path); - assert.equal(err.code, "ENOENT", "error has a code"); - assert.equal(err.path, path, "error has a path"); - assert.equal(err.errno, 34, "error has a errno"); - } - - function chmod (path, mode, sync) { - let { promise, resolve, reject } = defer(); - if (!sync) { - fs.chmod(path, mode, (err) => { - if (err) reject(err); - else resolve(); - }); - } else { - fs.chmodSync(path, mode); - resolve(); - } - return promise; - } - - function testPerm (mode, sync) { - return function () { - return chmod(chmodPath, mode, sync) - .then(() => getPerm(chmodPath)) - .then(perm => { - let nMode = normalizeMode(mode); - if (isWindows) - assert.equal(perm, nMode, - "mode correctly set to " + mode + " (" + nMode + " on windows)"); - else - assert.equal(perm, nMode, "mode correctly set to " + nMode); - }); - }; - } - - function testPermSync (mode) { - return testPerm(mode, true); - } - - function getPerm (path) { - let { promise, resolve, reject } = defer(); - fs.stat(path, function (err, stat) { - if (err) reject(err); - else resolve(stat.mode); - }); - return promise; - } - - /* - * Converts a unix mode `0755` into a Windows version of unix permissions - */ - function normalizeMode (mode) { - if (typeof mode === "string") - mode = parseInt(mode, 8); - - if (!isWindows) - return mode; - - var ANY_READ = 0o444; - var ANY_WRITE = 0o222; - var winMode = 0; - - // On Windows, if WRITE is true, then READ is also true - if (mode & ANY_WRITE) - winMode |= ANY_WRITE | ANY_READ; - // Minimum permissions are READ for Windows - else - winMode |= ANY_READ; - - return winMode; - } -}; - -require("test").run(exports); diff --git a/addon-sdk/source/test/test-functional.js b/addon-sdk/source/test/test-functional.js deleted file mode 100644 index 02ae15fc6..000000000 --- a/addon-sdk/source/test/test-functional.js +++ /dev/null @@ -1,463 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { setTimeout } = require('sdk/timers'); -const utils = require('sdk/lang/functional'); -const { invoke, defer, partial, compose, memoize, once, is, isnt, - delay, wrap, curry, chainable, field, query, isInstance, debounce, throttle -} = utils; -const { LoaderWithHookedConsole } = require('sdk/test/loader'); - -exports['test forwardApply'] = function(assert) { - function sum(b, c) { return this.a + b + c; } - assert.equal(invoke(sum, [2, 3], { a: 1 }), 6, - 'passed arguments and pseoude-variable are used'); - - assert.equal(invoke(sum.bind({ a: 2 }), [2, 3], { a: 1 }), 7, - 'bounded `this` pseoudo variable is used'); -}; - -exports['test deferred function'] = function(assert, done) { - let nextTurn = false; - function sum(b, c) { - assert.ok(nextTurn, 'enqueued is called in next turn of event loop'); - assert.equal(this.a + b + c, 6, - 'passed arguments an pseoude-variable are used'); - done(); - } - - let fixture = { a: 1, method: defer(sum) }; - fixture.method(2, 3); - nextTurn = true; -}; - -exports['test partial function'] = function(assert) { - function sum(b, c) { return this.a + b + c; } - - let foo = { a : 5 }; - - foo.sum7 = partial(sum, 7); - foo.sum8and4 = partial(sum, 8, 4); - - assert.equal(foo.sum7(2), 14, 'partial one arguments works'); - - assert.equal(foo.sum8and4(), 17, 'partial both arguments works'); -}; - -exports["test curry defined numeber of arguments"] = function(assert) { - var sum = curry(function(a, b, c) { - return a + b + c; - }); - - assert.equal(sum(2, 2, 1), 5, "sum(2, 2, 1) => 5"); - assert.equal(sum(2, 4)(1), 7, "sum(2, 4)(1) => 7"); - assert.equal(sum(2)(4, 2), 8, "sum(2)(4, 2) => 8"); - assert.equal(sum(2)(4)(3), 9, "sum(2)(4)(3) => 9"); -}; - -exports['test compose'] = function(assert) { - let greet = function(name) { return 'hi: ' + name; }; - let exclaim = function(sentence) { return sentence + '!'; }; - - assert.equal(compose(exclaim, greet)('moe'), 'hi: moe!', - 'can compose a function that takes another'); - - assert.equal(compose(greet, exclaim)('moe'), 'hi: moe!', - 'in this case, the functions are also commutative'); - - let target = { - name: 'Joe', - greet: compose(function exclaim(sentence) { - return sentence + '!'; - }, function(title) { - return 'hi : ' + title + ' ' + this.name; - }) - }; - - assert.equal(target.greet('Mr'), 'hi : Mr Joe!', - 'this can be passed in'); - assert.equal(target.greet.call({ name: 'Alex' }, 'Dr'), 'hi : Dr Alex!', - 'this can be applied'); - - let single = compose(function(value) { - return value + ':suffix'; - }); - - assert.equal(single('text'), 'text:suffix', 'works with single function'); - - let identity = compose(); - assert.equal(identity('bla'), 'bla', 'works with zero functions'); -}; - -exports['test wrap'] = function(assert) { - let greet = function(name) { return 'hi: ' + name; }; - let backwards = wrap(greet, function(f, name) { - return f(name) + ' ' + name.split('').reverse().join(''); - }); - - assert.equal(backwards('moe'), 'hi: moe eom', - 'wrapped the saluation function'); - - let inner = function () { return 'Hello '; }; - let target = { - name: 'Matteo', - hi: wrap(inner, function(f) { return f() + this.name; }) - }; - - assert.equal(target.hi(), 'Hello Matteo', 'works with this'); - - function noop() { } - let wrapped = wrap(noop, function(f) { - return Array.slice(arguments); - }); - - let actual = wrapped([ 'whats', 'your' ], 'vector', 'victor'); - assert.deepEqual(actual, [ noop, ['whats', 'your'], 'vector', 'victor' ], - 'works with fancy stuff'); -}; - -exports['test memoize'] = function(assert) { - const fib = n => n < 2 ? n : fib(n - 1) + fib(n - 2); - let fibnitro = memoize(fib); - - assert.equal(fib(10), 55, - 'a memoized version of fibonacci produces identical results'); - assert.equal(fibnitro(10), 55, - 'a memoized version of fibonacci produces identical results'); - - function o(key, value) { return value; } - let oo = memoize(o), v1 = {}, v2 = {}; - - - assert.equal(oo(1, v1), v1, 'returns value back'); - assert.equal(oo(1, v2), v1, 'memoized by a first argument'); - assert.equal(oo(2, v2), v2, 'returns back value if not memoized'); - assert.equal(oo(2), v2, 'memoized new value'); - assert.notEqual(oo(1), oo(2), 'values do not override'); - assert.equal(o(3, v2), oo(2, 3), 'returns same value as un-memoized'); - - let get = memoize(function(attribute) { return this[attribute]; }); - let target = { name: 'Bob', get: get }; - - assert.equal(target.get('name'), 'Bob', 'has correct `this`'); - assert.equal(target.get.call({ name: 'Jack' }, 'name'), 'Bob', - 'name is memoized'); - assert.equal(get('name'), 'Bob', 'once memoized can be called without this'); -}; - -exports['test delay'] = function(assert, done) { - let delayed = false; - delay(function() { - assert.ok(delayed, 'delayed the function'); - done(); - }, 1); - delayed = true; -}; - -exports['test delay with this'] = function(assert, done) { - let context = {}; - delay.call(context, function(name) { - assert.equal(this, context, 'this was passed in'); - assert.equal(name, 'Tom', 'argument was passed in'); - done(); - }, 10, 'Tom'); -}; - -exports['test once'] = function(assert) { - let n = 0; - let increment = once(function() { n ++; }); - - increment(); - increment(); - - assert.equal(n, 1, 'only incremented once'); - - let target = { - state: 0, - update: once(function() { - return this.state ++; - }) - }; - - target.update(); - target.update(); - - assert.equal(target.state, 1, 'this was passed in and called only once'); -}; - -exports['test once with argument'] = function(assert) { - let n = 0; - let increment = once(a => n++); - - increment(); - increment('foo'); - - assert.equal(n, 1, 'only incremented once'); - - increment(); - increment('foo'); - - assert.equal(n, 1, 'only incremented once'); -}; - -exports['test complement'] = assert => { - let { complement } = require("sdk/lang/functional"); - - let isOdd = x => Boolean(x % 2); - - assert.equal(isOdd(1), true); - assert.equal(isOdd(2), false); - - let isEven = complement(isOdd); - - assert.equal(isEven(1), false); - assert.equal(isEven(2), true); - - let foo = {}; - let isFoo = function() { return this === foo; }; - let insntFoo = complement(isFoo); - - assert.equal(insntFoo.call(foo), false); - assert.equal(insntFoo.call({}), true); -}; - -exports['test constant'] = assert => { - let { constant } = require("sdk/lang/functional"); - - let one = constant(1); - - assert.equal(one(1), 1); - assert.equal(one(2), 1); -}; - -exports['test apply'] = assert => { - let { apply } = require("sdk/lang/functional"); - - let dashify = (...args) => args.join("-"); - - assert.equal(apply(dashify, 1, [2, 3]), "1-2-3"); - assert.equal(apply(dashify, "a"), "a"); - assert.equal(apply(dashify, ["a", "b"]), "a-b"); - assert.equal(apply(dashify, ["a", "b"], "c"), "a,b-c"); - assert.equal(apply(dashify, [1, 2], [3, 4]), "1,2-3-4"); -}; - -exports['test flip'] = assert => { - let { flip } = require("sdk/lang/functional"); - - let append = (left, right) => left + " " + right; - let prepend = flip(append); - - assert.equal(append("hello", "world"), "hello world"); - assert.equal(prepend("hello", "world"), "world hello"); - - let wrap = function(left, right) { - return left + " " + this + " " + right; - }; - let invertWrap = flip(wrap); - - assert.equal(wrap.call("@", "hello", "world"), "hello @ world"); - assert.equal(invertWrap.call("@", "hello", "world"), "world @ hello"); - - let reverse = flip((...args) => args); - - assert.deepEqual(reverse(1, 2, 3, 4), [4, 3, 2, 1]); - assert.deepEqual(reverse(1), [1]); - assert.deepEqual(reverse(), []); - - // currying still works - let prependr = curry(prepend); - - assert.equal(prependr("hello", "world"), "world hello"); - assert.equal(prependr("hello")("world"), "world hello"); -}; - -exports["test when"] = assert => { - let { when } = require("sdk/lang/functional"); - - let areNums = (...xs) => xs.every(x => typeof(x) === "number"); - - let sum = when(areNums, (...xs) => xs.reduce((y, x) => x + y, 0)); - - assert.equal(sum(1, 2, 3), 6); - assert.equal(sum(1, 2, "3"), undefined); - - let multiply = when(areNums, - (...xs) => xs.reduce((y, x) => x * y, 1), - (...xs) => xs); - - assert.equal(multiply(2), 2); - assert.equal(multiply(2, 3), 6); - assert.deepEqual(multiply(2, "4"), [2, "4"]); - - function Point(x, y) { - this.x = x; - this.y = y; - } - - let isPoint = x => x instanceof Point; - - let inc = when(isPoint, ({x, y}) => new Point(x + 1, y + 1)); - - assert.equal(inc({}), undefined); - assert.deepEqual(inc(new Point(0, 0)), { x: 1, y: 1 }); - - let axis = when(isPoint, - ({ x, y }) => [x, y], - _ => [0, 0]); - - assert.deepEqual(axis(new Point(1, 4)), [1, 4]); - assert.deepEqual(axis({ foo: "bar" }), [0, 0]); -}; - -exports["test chainable"] = function(assert) { - let Player = function () { this.volume = 5; }; - Player.prototype = { - setBand: chainable(function (band) { return (this.band = band); }), - incVolume: chainable(function () { return this.volume++; }) - }; - let player = new Player(); - player - .setBand('Animals As Leaders') - .incVolume().incVolume().incVolume().incVolume().incVolume().incVolume(); - - assert.equal(player.band, 'Animals As Leaders', 'passes arguments into chained'); - assert.equal(player.volume, 11, 'accepts no arguments in chain'); -}; - -exports["test field"] = assert => { - let Num = field("constructor", 0); - assert.equal(Num.name, Number.name); - assert.ok(typeof(Num), "function"); - - let x = field("x"); - - [ - [field("foo", { foo: 1 }), 1], - [field("foo")({ foo: 1 }), 1], - [field("bar", {}), undefined], - [field("bar")({}), undefined], - [field("hey", undefined), undefined], - [field("hey")(undefined), undefined], - [field("how", null), null], - [field("how")(null), null], - [x(1), undefined], - [x(undefined), undefined], - [x(null), null], - [x({ x: 1 }), 1], - [x({ x: 2 }), 2], - ].forEach(([actual, expected]) => assert.equal(actual, expected)); -}; - -exports["test query"] = assert => { - let Num = query("constructor", 0); - assert.equal(Num.name, Number.name); - assert.ok(typeof(Num), "function"); - - let x = query("x"); - let xy = query("x.y"); - - [ - [query("foo", { foo: 1 }), 1], - [query("foo")({ foo: 1 }), 1], - [query("foo.bar", { foo: { bar: 2 } }), 2], - [query("foo.bar")({ foo: { bar: 2 } }), 2], - [query("foo.bar", { foo: 1 }), undefined], - [query("foo.bar")({ foo: 1 }), undefined], - [x(1), undefined], - [x(undefined), undefined], - [x(null), null], - [x({ x: 1 }), 1], - [x({ x: 2 }), 2], - [xy(1), undefined], - [xy(undefined), undefined], - [xy(null), null], - [xy({ x: 1 }), undefined], - [xy({ x: 2 }), undefined], - [xy({ x: { y: 1 } }), 1], - [xy({ x: { y: 2 } }), 2] - ].forEach(([actual, expected]) => assert.equal(actual, expected)); -}; - -exports["test isInstance"] = assert => { - function X() {} - function Y() {} - let isX = isInstance(X); - - [ - isInstance(X, new X()), - isInstance(X)(new X()), - !isInstance(X, new Y()), - !isInstance(X)(new Y()), - isX(new X()), - !isX(new Y()) - ].forEach(x => assert.ok(x)); -}; - -exports["test is"] = assert => { - - assert.deepEqual([ 1, 0, 1, 0, 1 ].map(is(1)), - [ true, false, true, false, true ], - "is can be partially applied"); - - assert.ok(is(1, 1)); - assert.ok(!is({}, {})); - assert.ok(is()(1)()(1), "is is curried"); - assert.ok(!is()(1)()(2)); -}; - -exports["test isnt"] = assert => { - - assert.deepEqual([ 1, 0, 1, 0, 1 ].map(isnt(0)), - [ true, false, true, false, true ], - "is can be partially applied"); - - assert.ok(!isnt(1, 1)); - assert.ok(isnt({}, {})); - assert.ok(!isnt()(1)()(1)); - assert.ok(isnt()(1)()(2)); -}; - -exports["test debounce"] = (assert, done) => { - let counter = 0; - let fn = debounce(() => counter++, 100); - - new Array(10).join(0).split("").forEach(fn); - - assert.equal(counter, 0, "debounce does not fire immediately"); - setTimeout(() => { - assert.equal(counter, 1, "function called after wait time"); - fn(); - setTimeout(() => { - assert.equal(counter, 2, "function able to be called again after wait"); - done(); - }, 150); - }, 200); -}; - -exports["test throttle"] = (assert, done) => { - let called = 0; - let attempt = 0; - let atleast100ms = false; - let throttledFn = throttle(() => { - called++; - if (called === 2) { - assert.equal(attempt, 10, "called twice, but attempted 10 times"); - fn(); - } - if (called === 3) { - assert.ok(atleast100ms, "atleast 100ms have passed"); - assert.equal(attempt, 11, "called third, waits for delay to happen"); - done(); - } - }, 200); - let fn = () => ++attempt && throttledFn(); - - setTimeout(() => atleast100ms = true, 100); - - new Array(11).join(0).split("").forEach(fn); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-globals.js b/addon-sdk/source/test/test-globals.js deleted file mode 100644 index bc3364367..000000000 --- a/addon-sdk/source/test/test-globals.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'; - -Object.defineProperty(this, 'global', { value: this }); - -exports.testGlobals = function(assert) { - // the only globals in module scope should be: - // module, exports, require, dump, console - assert.equal(typeof module, 'object', 'have "module", good'); - assert.equal(typeof exports, 'object', 'have "exports", good'); - assert.equal(typeof require, 'function', 'have "require", good'); - assert.equal(typeof dump, 'function', 'have "dump", good'); - assert.equal(typeof console, 'object', 'have "console", good'); - - // in particular, these old globals should no longer be present - assert.ok(!('packaging' in global), "no 'packaging', good"); - assert.ok(!('memory' in global), "no 'memory', good"); - assert.ok(/test-globals\.js$/.test(module.uri), - 'should contain filename'); -}; - -exports.testComponent = function (assert) { - assert.throws(() => { - Components; - }, /`Components` is not available/, 'using `Components` throws'); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-heritage.js b/addon-sdk/source/test/test-heritage.js deleted file mode 100644 index e087f3e4d..000000000 --- a/addon-sdk/source/test/test-heritage.js +++ /dev/null @@ -1,301 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Class, extend, mix, obscure } = require('sdk/core/heritage'); - -exports['test extend'] = function(assert) { - let ancestor = { a: 1 }; - let descendant = extend(ancestor, { - b: 2, - get c() { return 3 }, - d: function() { return 4 } - }); - - assert.ok(ancestor.isPrototypeOf(descendant), - 'descendant inherits from ancestor'); - assert.ok(descendant.b, 2, 'proprety was implemented'); - assert.ok(descendant.c, 3, 'getter was implemented'); - assert.ok(descendant.d(), 4, 'method was implemented'); - - /* Will be fixed once Bug 674195 is shipped. - assert.ok(Object.isFrozen(descendant), - 'extend returns frozen objects'); - */ -}; - -exports['test mix'] = function(assert) { - let ancestor = { a: 1 } - let mixed = mix(extend(ancestor, { b: 1, c: 1 }), { c: 2 }, { d: 3 }); - - assert.deepEqual(JSON.parse(JSON.stringify(mixed)), { b: 1, c: 2, d: 3 }, - 'properties mixed as expected'); - assert.ok(ancestor.isPrototypeOf(mixed), - 'first arguments ancestor is ancestor of result'); -}; - -exports['test obscure'] = function(assert) { - let fixture = mix({ a: 1 }, obscure({ b: 2 })); - - assert.equal(fixture.a, 1, 'a property is included'); - assert.equal(fixture.b, 2, 'b proprety is included'); - assert.ok(!Object.getOwnPropertyDescriptor(fixture, 'b').enumerable, - 'obscured properties are non-enumerable'); -}; - -exports['test inheritance'] = function(assert) { - let Ancestor = Class({ - name: 'ancestor', - method: function () { - return 'hello ' + this.name; - } - }); - - assert.ok(Ancestor() instanceof Ancestor, - 'can be instantiated without new'); - assert.ok(new Ancestor() instanceof Ancestor, - 'can also be instantiated with new'); - assert.ok(Ancestor() instanceof Class, - 'if ancestor not specified than defaults to Class'); - assert.ok(Ancestor.prototype.extends, Class.prototype, - 'extends of prototype points to ancestors prototype'); - - - assert.equal(Ancestor().method(), 'hello ancestor', - 'instance inherits defined properties'); - - let Descendant = Class({ - extends: Ancestor, - name: 'descendant' - }); - - assert.ok(Descendant() instanceof Descendant, - 'instantiates correctly'); - assert.ok(Descendant() instanceof Ancestor, - 'Inherits for passed `extends`'); - assert.equal(Descendant().method(), 'hello descendant', - 'propreties inherited'); -}; - -exports['test immunity against __proto__'] = function(assert) { - let Foo = Class({ name: 'foo', hacked: false }); - - let Bar = Class({ extends: Foo, name: 'bar' }); - - assert.throws(function() { - Foo.prototype.__proto__ = { hacked: true }; - if (Foo() instanceof Base && !Foo().hacked) - throw Error('can not change prototype chain'); - }, 'prototype chain is immune to __proto__ hacks'); - - assert.throws(function() { - Foo.prototype.__proto__ = { hacked: true }; - if (Bar() instanceof Foo && !Bar().hacked) - throw Error('can not change prototype chain'); - }, 'prototype chain of decedants immune to __proto__ hacks'); -}; - -exports['test super'] = function(assert) { - var Foo = Class({ - initialize: function initialize(options) { - this.name = options.name; - } - }); - - var Bar = Class({ - extends: Foo, - initialize: function Bar(options) { - Foo.prototype.initialize.call(this, options); - this.type = 'bar'; - } - }); - - var bar = Bar({ name: 'test' }); - - assert.equal(bar.type, 'bar', 'bar initializer was called'); - assert.equal(bar.name, 'test', 'bar initializer called Foo initializer'); -}; - -exports['test initialize'] = function(assert) { - var Dog = Class({ - initialize: function initialize(name) { - this.name = name; - }, - type: 'dog', - bark: function bark() { - return 'Ruff! Ruff!' - } - }); - - var fluffy = Dog('Fluffy'); // instatiation - assert.ok(fluffy instanceof Dog, - 'instanceof works as expected'); - assert.ok(fluffy instanceof Class, - 'inherits form Class if not specified otherwise'); - assert.ok(fluffy.name, 'fluffy', - 'initialize unless specified otherwise'); -}; - -exports['test complements regular inheritace'] = function(assert) { - let Base = Class({ name: 'base' }); - - function Type() { - // ... - } - Type.prototype = Object.create(Base.prototype); - Type.prototype.run = function() { - // ... - }; - - let value = new Type(); - - assert.ok(value instanceof Type, 'creates instance of Type'); - assert.ok(value instanceof Base, 'inherits from Base'); - assert.equal(value.name, 'base', 'inherits properties from Base'); - - - let SubType = Class({ - extends: Type, - sub: 'type' - }); - - let fixture = SubType(); - - assert.ok(fixture instanceof Base, 'is instance of Base'); - assert.ok(fixture instanceof Type, 'is instance of Type'); - assert.ok(fixture instanceof SubType, 'is instance of SubType'); - - assert.equal(fixture.sub, 'type', 'proprety is defined'); - assert.equal(fixture.run, Type.prototype.run, 'proprety is inherited'); - assert.equal(fixture.name, 'base', 'inherits base properties'); -}; - -exports['test extends object'] = function(assert) { - let prototype = { constructor: function() { return this; }, name: 'me' }; - let Foo = Class({ - extends: prototype, - value: 2 - }); - let foo = new Foo(); - - assert.ok(foo instanceof Foo, 'instance of Foo'); - assert.ok(!(foo instanceof Class), 'is not instance of Class'); - assert.ok(prototype.isPrototypeOf(foo), 'inherits from given prototype'); - assert.equal(Object.getPrototypeOf(Foo.prototype), prototype, - 'contsructor prototype inherits from extends option'); - assert.equal(foo.value, 2, 'property is defined'); - assert.equal(foo.name, 'me', 'prototype proprety is inherited'); -}; - - -var HEX = Class({ - hex: function hex() { - return '#' + this.color; - } -}); - -var RGB = Class({ - red: function red() { - return parseInt(this.color.substr(0, 2), 16); - }, - green: function green() { - return parseInt(this.color.substr(2, 2), 16); - }, - blue: function blue() { - return parseInt(this.color.substr(4, 2), 16); - } -}); - -var CMYK = Class({ - black: function black() { - var color = Math.max(Math.max(this.red(), this.green()), this.blue()); - return (1 - color / 255).toFixed(4); - }, - magenta: function magenta() { - var K = this.black(); - return (((1 - this.green() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); - }, - yellow: function yellow() { - var K = this.black(); - return (((1 - this.blue() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); - }, - cyan: function cyan() { - var K = this.black(); - return (((1 - this.red() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); - } -}); - -var Color = Class({ - implements: [ HEX, RGB, CMYK ], - initialize: function initialize(color) { - this.color = color; - } -}); - -exports['test composition'] = function(assert) { - var pink = Color('FFC0CB'); - - assert.equal(pink.red(), 255, 'red() works'); - assert.equal(pink.green(), 192, 'green() works'); - assert.equal(pink.blue(), 203, 'blue() works'); - - assert.equal(pink.magenta(), 0.2471, 'magenta() works'); - assert.equal(pink.yellow(), 0.2039, 'yellow() works'); - assert.equal(pink.cyan(), 0.0000, 'cyan() works'); - - assert.ok(pink instanceof Color, 'is instance of Color'); - assert.ok(pink instanceof Class, 'is instance of Class'); -}; - -var Point = Class({ - initialize: function initialize(x, y) { - this.x = x; - this.y = y; - }, - toString: function toString() { - return this.x + ':' + this.y; - } -}) - -var Pixel = Class({ - extends: Point, - implements: [ Color ], - initialize: function initialize(x, y, color) { - Color.prototype.initialize.call(this, color); - Point.prototype.initialize.call(this, x, y); - }, - toString: function toString() { - return this.hex() + '@' + Point.prototype.toString.call(this) - } -}); - -exports['test compostion with inheritance'] = function(assert) { - var pixel = Pixel(11, 23, 'CC3399'); - - assert.equal(pixel.toString(), '#CC3399@11:23', 'stringifies correctly'); - assert.ok(pixel instanceof Pixel, 'instance of Pixel'); - assert.ok(pixel instanceof Point, 'instance of Point'); -}; - -exports['test composition with objects'] = function(assert) { - var A = { a: 1, b: 1 }; - var B = Class({ b: 2, c: 2 }); - var C = { c: 3 }; - var D = { d: 4 }; - - var ABCD = Class({ - implements: [ A, B, C, D ], - e: 5 - }); - - var f = ABCD(); - - assert.equal(f.a, 1, 'inherits A.a'); - assert.equal(f.b, 2, 'inherits B.b overrides A.b'); - assert.equal(f.c, 3, 'inherits C.c overrides B.c'); - assert.equal(f.d, 4, 'inherits D.d'); - assert.equal(f.e, 5, 'implements e'); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-hidden-frame.js b/addon-sdk/source/test/test-hidden-frame.js deleted file mode 100644 index 945c2413f..000000000 --- a/addon-sdk/source/test/test-hidden-frame.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 { Loader } = require("sdk/test/loader"); -const hiddenFrames = require("sdk/frame/hidden-frame"); -const { HiddenFrame } = hiddenFrames; - -exports["test Frame"] = function(assert, done) { - let url = "data:text/html;charset=utf-8,"; - - let hiddenFrame = hiddenFrames.add(HiddenFrame({ - onReady: function () { - assert.equal(this.element.contentWindow.location, "about:blank", - "HiddenFrame loads about:blank by default."); - - function onDOMReady() { - hiddenFrame.element.removeEventListener("DOMContentLoaded", onDOMReady, - false); - assert.equal(hiddenFrame.element.contentWindow.location, url, - "HiddenFrame loads the specified content."); - done(); - } - - this.element.addEventListener("DOMContentLoaded", onDOMReady, false); - this.element.setAttribute("src", url); - } - })); -}; - -exports["test frame removed properly"] = function(assert, done) { - let url = "data:text/html;charset=utf-8,"; - - let hiddenFrame = hiddenFrames.add(HiddenFrame({ - onReady: function () { - let frame = this.element; - assert.ok(frame.parentNode, "frame has a parent node"); - hiddenFrames.remove(hiddenFrame); - assert.ok(!frame.parentNode, "frame no longer has a parent node"); - done(); - } - })); -}; - -exports["test unload detaches panels"] = function(assert, done) { - let loader = Loader(module); - let { add, remove, HiddenFrame } = loader.require("sdk/frame/hidden-frame"); - let frames = [] - - function ready() { - frames.push(this.element); - if (frames.length === 2) complete(); - } - - add(HiddenFrame({ onReady: ready })); - add(HiddenFrame({ onReady: ready })); - - function complete() { - frames.forEach(function(frame) { - assert.ok(frame.parentNode, "frame is in the document"); - }) - loader.unload(); - frames.forEach(function(frame) { - assert.ok(!frame.parentNode, "frame isn't in the document'"); - }); - done(); - } -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-host-events.js b/addon-sdk/source/test/test-host-events.js deleted file mode 100644 index 1c6664534..000000000 --- a/addon-sdk/source/test/test-host-events.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/. */ -'use strict'; - -const { Cc, Ci } = require('chrome'); -const { defer, all } = require('sdk/core/promise'); -const { setTimeout } = require('sdk/timers'); -const { request, response } = require('sdk/addon/host'); -const { send } = require('sdk/addon/events'); -const { filter } = require('sdk/event/utils'); -const { on, emit, off } = require('sdk/event/core'); - -var stream = filter(request, (data) => /sdk-x-test/.test(data.event)); - -exports.testSend = function (assert, done) { - on(stream, 'data', handle); - send('sdk-x-test-simple', { title: 'my test data' }).then((data) => { - assert.equal(data.title, 'my response', 'response is handled'); - off(stream, 'data', handle); - done(); - }, (reason) => { - assert.fail('should not call reject'); - }); - function handle (e) { - assert.equal(e.event, 'sdk-x-test-simple', 'correct event name'); - assert.ok(e.id != null, 'message has an ID'); - assert.equal(e.data.title, 'my test data', 'serialized data passes'); - e.data.title = 'my response'; - emit(response, 'data', e); - } -}; - -exports.testSendError = function (assert, done) { - on(stream, 'data', handle); - send('sdk-x-test-error', { title: 'my test data' }).then((data) => { - assert.fail('should not call success'); - }, (reason) => { - assert.equal(reason, 'ErrorInfo', 'should reject with error/reason'); - off(stream, 'data', handle); - done(); - }); - function handle (e) { - e.error = 'ErrorInfo'; - emit(response, 'data', e); - } -}; - -exports.testMultipleSends = function (assert, done) { - let count = 0; - let ids = []; - on(stream, 'data', handle); - ['firefox', 'thunderbird', 'rust'].map(data => - send('sdk-x-test-multi', { data: data }).then(val => { - assert.ok(val === 'firefox' || val === 'rust', 'successful calls resolve correctly'); - if (++count === 3) { - off(stream, 'data', handle); - done(); - } - }, reason => { - assert.equal(reason.error, 'too blue', 'rejected calls are rejected'); - if (++count === 3) { - off(stream, 'data', handle); - done(); - } - })); - - function handle (e) { - if (e.data !== 'firefox' || e.data !== 'rust') - e.error = { data: e.data, error: 'too blue' }; - assert.ok(!~ids.indexOf(e.id), 'ID should be unique'); - assert.equal(e.event, 'sdk-x-test-multi', 'has event name'); - ids.push(e.id); - emit(response, 'data', e); - } -}; - -exports.testSerialization = function (assert, done) { - on(stream, 'data', handle); - let object = { title: 'my test data' }; - let resObject; - send('sdk-x-test-serialize', object).then(data => { - data.title = 'another title'; - assert.equal(object.title, 'my test data', 'original object not modified'); - assert.equal(resObject.title, 'new title', 'object passed by value from host'); - off(stream, 'data', handle); - done(); - }, (reason) => { - assert.fail('should not call reject'); - }); - function handle (e) { - e.data.title = 'new title'; - assert.equal(object.title, 'my test data', 'object passed by value to host'); - resObject = e.data; - emit(response, 'data', e); - } -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-hotkeys.js b/addon-sdk/source/test/test-hotkeys.js deleted file mode 100644 index ba460ee45..000000000 --- a/addon-sdk/source/test/test-hotkeys.js +++ /dev/null @@ -1,183 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Hotkey } = require("sdk/hotkeys"); -const { keyDown } = require("sdk/dom/events/keys"); -const { Loader } = require('sdk/test/loader'); -const { getMostRecentBrowserWindow } = require("sdk/window/utils"); - -const element = getMostRecentBrowserWindow().document.documentElement; - -exports["test hotkey: function key"] = function(assert, done) { - var showHotKey = Hotkey({ - combo: "f1", - onPress: function() { - assert.pass("first callback is called"); - assert.equal(this, showHotKey, - 'Context `this` in `onPress` should be the hotkey object'); - keyDown(element, "f2"); - showHotKey.destroy(); - } - }); - - var hideHotKey = Hotkey({ - combo: "f2", - onPress: function() { - assert.pass("second callback is called"); - hideHotKey.destroy(); - done(); - } - }); - - keyDown(element, "f1"); -}; - -exports["test hotkey: accel alt shift"] = function(assert, done) { - var showHotKey = Hotkey({ - combo: "accel-shift-6", - onPress: function() { - assert.pass("first callback is called"); - keyDown(element, "accel-alt-shift-6"); - showHotKey.destroy(); - } - }); - - var hideHotKey = Hotkey({ - combo: "accel-alt-shift-6", - onPress: function() { - assert.pass("second callback is called"); - hideHotKey.destroy(); - done(); - } - }); - - keyDown(element, "accel-shift-6"); -}; - -exports["test hotkey meta & control"] = function(assert, done) { - var showHotKey = Hotkey({ - combo: "meta-3", - onPress: function() { - assert.pass("first callback is called"); - keyDown(element, "alt-control-shift-b"); - showHotKey.destroy(); - } - }); - - var hideHotKey = Hotkey({ - combo: "Ctrl-Alt-Shift-B", - onPress: function() { - assert.pass("second callback is called"); - hideHotKey.destroy(); - done(); - } - }); - - keyDown(element, "meta-3"); -}; - -exports["test hotkey: control-1 / meta--"] = function(assert, done) { - var showHotKey = Hotkey({ - combo: "control-1", - onPress: function() { - assert.pass("first callback is called"); - keyDown(element, "meta--"); - showHotKey.destroy(); - } - }); - - var hideHotKey = Hotkey({ - combo: "meta--", - onPress: function() { - assert.pass("second callback is called"); - hideHotKey.destroy(); - done(); - } - }); - - keyDown(element, "control-1"); -}; - -exports["test invalid combos"] = function(assert) { - assert.throws(function() { - Hotkey({ - combo: "d", - onPress: function() {} - }); - }, "throws if no modifier is present"); - assert.throws(function() { - Hotkey({ - combo: "alt", - onPress: function() {} - }); - }, "throws if no key is present"); - assert.throws(function() { - Hotkey({ - combo: "alt p b", - onPress: function() {} - }); - }, "throws if more then one key is present"); -}; - -exports["test no exception on unmodified keypress"] = function(assert) { - var someHotkey = Hotkey({ - combo: "control-alt-1", - onPress: () => {} - }); - keyDown(element, "a"); - assert.pass("No exception throw, unmodified keypress passed"); - someHotkey.destroy(); -}; - -exports["test hotkey: automatic destroy"] = function*(assert) { - // Hacky way to be able to create unloadable modules via makeSandboxedLoader. - let loader = Loader(module); - - var called = false; - var hotkey = loader.require("sdk/hotkeys").Hotkey({ - combo: "accel-shift-x", - onPress: () => called = true - }); - - // Unload the module so that previous hotkey is automatically destroyed - loader.unload(); - - // Ensure that the hotkey is really destroyed - keyDown(element, "accel-shift-x"); - - assert.ok(!called, "Hotkey is destroyed and not called."); - - // create a new hotkey for a different set - yield new Promise(resolve => { - let key = Hotkey({ - combo: "accel-shift-y", - onPress: () => { - key.destroy(); - assert.pass("accel-shift-y was pressed."); - resolve(); - } - }); - keyDown(element, "accel-shift-y"); - }); - - assert.ok(!called, "Hotkey is still not called, in time it would take."); - - // create a new hotkey for the same set - yield new Promise(resolve => { - let key = Hotkey({ - combo: "accel-shift-x", - onPress: () => { - key.destroy(); - assert.pass("accel-shift-x was pressed."); - resolve(); - } - }); - keyDown(element, "accel-shift-x"); - }); - - assert.ok(!called, "Hotkey is still not called, and reusing is ok."); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-httpd.js b/addon-sdk/source/test/test-httpd.js deleted file mode 100644 index 78740f1bf..000000000 --- a/addon-sdk/source/test/test-httpd.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/. */ - -const port = 8099; -const file = require("sdk/io/file"); -const { pathFor } = require("sdk/system"); -const { Loader } = require("sdk/test/loader"); -const options = require("sdk/test/options"); - -const loader = Loader(module); -const httpd = loader.require("./lib/httpd"); -if (options.parseable || options.verbose) - loader.sandbox("./lib/httpd").DEBUG = true; - -exports.testBasicHTTPServer = function(assert, done) { - // Use the profile directory for the temporary file as that will be deleted - // when tests are complete - let basePath = pathFor("ProfD"); - let filePath = file.join(basePath, 'test-httpd.txt'); - let content = "This is the HTTPD test file.\n"; - let fileStream = file.open(filePath, 'w'); - fileStream.write(content); - fileStream.close(); - - let srv = httpd.startServerAsync(port, basePath); - - // Request this very file. - let Request = require('sdk/request').Request; - Request({ - url: "http://localhost:" + port + "/test-httpd.txt", - onComplete: function (response) { - assert.equal(response.text, content); - srv.stop(done); - } - }).get(); -}; - -exports.testDynamicServer = function (assert, done) { - let content = "This is the HTTPD test file.\n"; - - let srv = httpd.startServerAsync(port); - - // See documentation here: - //http://doxygen.db48x.net/mozilla/html/interfacensIHttpServer.html#a81fc7e7e29d82aac5ce7d56d0bedfb3a - //http://doxygen.db48x.net/mozilla/html/interfacensIHttpRequestHandler.html - srv.registerPathHandler("/test-httpd.txt", function handle(request, response) { - // Add text content type, only to avoid error in `Request` API - response.setHeader("Content-Type", "text/plain", false); - response.write(content); - }); - - // Request this very file. - let Request = require('sdk/request').Request; - Request({ - url: "http://localhost:" + port + "/test-httpd.txt", - onComplete: function (response) { - assert.equal(response.text, content); - srv.stop(done); - } - }).get(); -}; - -exports.testAutomaticPortSelection = function (assert, done) { - const srv = httpd.startServerAsync(-1); - - const port = srv.identity.primaryPort; - assert.ok(0 <= port && port <= 65535); - - srv.stop(done); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-indexed-db.js b/addon-sdk/source/test/test-indexed-db.js deleted file mode 100644 index ea53a3e72..000000000 --- a/addon-sdk/source/test/test-indexed-db.js +++ /dev/null @@ -1,182 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { indexedDB, IDBKeyRange, DOMException - } = require("sdk/indexed-db"); - -exports["test indexedDB is frozen"] = function(assert){ - let original = indexedDB.open; - let f = function(){}; - assert.throws(function(){indexedDB.open = f}); - assert.equal(indexedDB.open,original); - assert.notEqual(indexedDB.open,f); - -}; - -exports["test db variables"] = function(assert) { - [ indexedDB, IDBKeyRange, DOMException - ].forEach(function(value) { - assert.notEqual(typeof(value), "undefined", "variable is defined"); - }); -} - -exports["test open"] = function(assert, done) { - testOpen(0, assert, done); -} - -function testOpen(step, assert, done) { - const dbName = "MyTestDatabase"; - const openParams = [ - { dbName: "MyTestDatabase", dbVersion: 10 }, - { dbName: "MyTestDatabase" }, - { dbName: "MyTestDatabase", dbOptions: { storage: "temporary" } }, - { dbName: "MyTestDatabase", dbOptions: { version: 20, storage: "default" } } - ]; - - let params = openParams[step]; - - let request; - let expectedStorage; - let expectedVersion; - let upgradeNeededCalled = false; - if ("dbVersion" in params) { - request = indexedDB.open(params.dbName, params.dbVersion); - expectedVersion = params.dbVersion; - expectedStorage = "persistent"; - } else if ("dbOptions" in params) { - request = indexedDB.open(params.dbName, params.dbOptions); - if ("version" in params.dbOptions) { - expectedVersion = params.dbOptions.version; - } else { - expectedVersion = 1; - } - if ("storage" in params.dbOptions) { - expectedStorage = params.dbOptions.storage; - } else { - expectedStorage = "persistent"; - } - } else { - request = indexedDB.open(params.dbName); - expectedVersion = 1; - expectedStorage = "persistent"; - } - request.onerror = function(event) { - assert.fail("Failed to open indexedDB") - done(); - } - request.onupgradeneeded = function(event) { - upgradeNeededCalled = true; - assert.equal(event.oldVersion, 0, "Correct old version"); - } - request.onsuccess = function(event) { - assert.pass("IndexedDB was open"); - assert.equal(upgradeNeededCalled, true, "Upgrade needed called"); - let db = request.result; - assert.equal(db.storage, expectedStorage, "Storage is correct"); - db.onversionchange = function(event) { - assert.equal(event.oldVersion, expectedVersion, "Old version is correct"); - db.close(); - } - if ("dbOptions" in params) { - request = indexedDB.deleteDatabase(params.dbName, params.dbOptions); - } else { - request = indexedDB.deleteDatabase(params.dbName); - } - request.onerror = function(event) { - assert.fail("Failed to delete indexedDB") - done(); - } - request.onsuccess = function(event) { - assert.pass("IndexedDB was deleted"); - - if (++step == openParams.length) { - done(); - } else { - testOpen(step, assert, done); - } - } - } -} - -exports["test dbname is unprefixed"] = function(assert, done) { - // verify fixes in https://bugzilla.mozilla.org/show_bug.cgi?id=786688 - let dbName = "dbname-unprefixed"; - let request = indexedDB.open(dbName); - request.onerror = function(event) { - assert.fail("Failed to open db"); - done(); - }; - request.onsuccess = function(event) { - assert.equal(request.result.name, dbName); - done(); - }; -}; - -exports["test structuring the database"] = function(assert, done) { - // This is what our customer data looks like. - let customerData = [ - { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" }, - { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" } - ]; - let dbName = "the_name"; - let request = indexedDB.open(dbName, 2); - request.onerror = function(event) { - assert.fail("Failed to open db"); - done(); - }; - request.onsuccess = function(event) { - assert.pass("transaction is complete"); - testRead(assert, done); - } - request.onupgradeneeded = function(event) { - assert.pass("data base upgrade") - - var db = event.target.result; - - // Create an objectStore to hold information about our customers. We"re - // going to use "ssn" as our key path because it"s guaranteed to be - // unique. - var objectStore = db.createObjectStore("customers", { keyPath: "ssn" }); - - // Create an index to search customers by name. We may have duplicates - // so we can"t use a unique index. - objectStore.createIndex("name", "name", { unique: false }); - - // Create an index to search customers by email. We want to ensure that - // no two customers have the same email, so use a unique index. - objectStore.createIndex("email", "email", { unique: true }); - - // Store values in the newly created objectStore. - customerData.forEach(function(data) { - objectStore.add(data); - }); - assert.pass("data added to object store"); - }; -}; - -function testRead(assert, done) { - let dbName = "the_name"; - let request = indexedDB.open(dbName, 2); - request.onsuccess = function(event) { - assert.pass("data opened") - var db = event.target.result; - let transaction = db.transaction(["customers"]); - var objectStore = transaction.objectStore("customers"); - var request = objectStore.get("444-44-4444"); - request.onerror = function(event) { - assert.fail("Failed to retrive data") - }; - request.onsuccess = function(event) { - // Do something with the request.result! - assert.equal(request.result.name, "Bill", "Name is correct"); - done(); - }; - }; - request.onerror = function() { - assert.fail("failed to open db"); - }; -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-jetpack-id.js b/addon-sdk/source/test/test-jetpack-id.js deleted file mode 100644 index 99479e32d..000000000 --- a/addon-sdk/source/test/test-jetpack-id.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/. */ -"use strict"; - -var getID = require("jetpack-id/index"); - -exports["test Returns GUID when `id` GUID"] = assert => { - var guid = "{8490ae4f-93bc-13af-80b3-39adf9e7b243}"; - assert.equal(getID({ id: guid }), guid); -}; - -exports["test Returns domain id when `id` domain id"] = assert => { - var id = "my-addon@jetpack"; - assert.equal(getID({ id: id }), id); -}; - -exports["test allows underscores in name"] = assert => { - var name = "my_addon"; - assert.equal(getID({ name: name }), `@${name}`); -}; - -exports["test allows underscores in id"] = assert => { - var id = "my_addon@jetpack"; - assert.equal(getID({ id: id }), id); -}; - -exports["test Returns valid name when `name` exists"] = assert => { - var id = "my-addon"; - assert.equal(getID({ name: id }), `@${id}`); -}; - - -exports["test Returns null when `id` and `name` do not exist"] = assert => { - assert.equal(getID({}), null) -} - -exports["test Returns null when no object passed in"] = assert => { - assert.equal(getID(), null) -} - -exports["test Returns null when `id` exists but not GUID/domain"] = assert => { - var id = "my-addon"; - assert.equal(getID({ id: id }), null); -} - -exports["test Returns null when `id` contains multiple @"] = assert => { - assert.equal(getID({ id: "my@addon@yeah" }), null); -}; - -exports["test Returns null when `id` or `name` specified in domain format but has invalid characters"] = assert => { - [" ", "!", "/", "$", " ", "~", "("].forEach(sym => { - assert.equal(getID({ id: "my" + sym + "addon@domain" }), null); - assert.equal(getID({ name: "my" + sym + "addon" }), null); - }); -}; - -exports["test Returns null, does not crash, when providing non-string properties for `name` and `id`"] = assert => { - assert.equal(getID({ id: 5 }), null); - assert.equal(getID({ name: 5 }), null); - assert.equal(getID({ name: {} }), null); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-keyboard-observer.js b/addon-sdk/source/test/test-keyboard-observer.js deleted file mode 100644 index 18f32eab3..000000000 --- a/addon-sdk/source/test/test-keyboard-observer.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 { keyPress } = require("sdk/dom/events/keys"); -const { Loader } = require("sdk/test/loader"); -const timer = require("sdk/timers"); - -exports["test unload keyboard observer"] = function(assert, done) { - let loader = Loader(module); - let element = loader.require("sdk/deprecated/window-utils"). - activeBrowserWindow.document.documentElement; - let observer = loader.require("sdk/keyboard/observer"). - observer; - let called = 0; - - observer.on("keypress", function () { called++; }); - - // dispatching "keypress" event to trigger observer listeners. - keyPress(element, "accel-%"); - - // Unload the module. - loader.unload(); - - // dispatching "keypress" even once again. - keyPress(element, "accel-%"); - - // Enqueuing asserts to make sure that assertion is not performed early. - timer.setTimeout(function () { - assert.equal(called, 1, "observer was called before unload only."); - done(); - }, 0); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-keyboard-utils.js b/addon-sdk/source/test/test-keyboard-utils.js deleted file mode 100644 index 00fc841ee..000000000 --- a/addon-sdk/source/test/test-keyboard-utils.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 utils = require("sdk/keyboard/utils"); -const runtime = require("sdk/system/runtime"); - -const isMac = runtime.OS === "Darwin"; - -exports["test toString"] = function(assert) { - assert.equal(utils.toString({ - key: "B", - modifiers: [ "Shift", "Ctrl" ] - }), "Shift-Ctrl-B", "toString does not normalizes JSON"); - - assert.equal(utils.toString({ - key: "C", - modifiers: [], - }), "C", "Works with objects with empty array of modifiers"); - - assert.equal(utils.toString(Object.create((function Type() {}).prototype, { - key: { value: "d" }, - modifiers: { value: [ "alt" ] }, - method: { value: function() {} } - })), "alt-d", "Works with non-json objects"); - - assert.equal(utils.toString({ - modifiers: [ "shift", "alt" ] - }), "shift-alt-", "works with only modifiers"); -}; - -exports["test toJSON"] = function(assert) { - assert.deepEqual(utils.toJSON("Shift-Ctrl-B"), { - key: "b", - modifiers: [ "control", "shift" ] - }, "toJSON normalizes input"); - - assert.deepEqual(utils.toJSON("Meta-Alt-option-C"), { - key: "c", - modifiers: [ "alt", "meta" ] - }, "removes dublicates"); - - assert.deepEqual(utils.toJSON("AccEl+sHiFt+Z", "+"), { - key: "z", - modifiers: isMac ? [ "meta", "shift" ] : [ "control", "shift" ] - }, "normalizes OS specific keys and adjustes seperator"); -}; - -exports["test normalize"] = function assert(assert) { - assert.equal(utils.normalize("Shift Ctrl A control ctrl", " "), - "control shift a", "removes reapeted modifiers"); - assert.equal(utils.normalize("shift-ctrl-left"), "control-shift-left", - "normilizes non printed characters"); - - assert.throws(function() { - utils.normalize("shift-alt-b-z"); - }, "throws if contains more then on non-modifier key"); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-l10n-locale.js b/addon-sdk/source/test/test-l10n-locale.js deleted file mode 100644 index 564abbf1b..000000000 --- a/addon-sdk/source/test/test-l10n-locale.js +++ /dev/null @@ -1,169 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { getPreferedLocales, findClosestLocale } = require("sdk/l10n/locale"); -const prefs = require("sdk/preferences/service"); -const { Cc, Ci, Cu } = require("chrome"); -const { Services } = Cu.import("resource://gre/modules/Services.jsm"); -const BundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService); - -const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS"; -const PREF_SELECTED_LOCALE = "general.useragent.locale"; -const PREF_ACCEPT_LANGUAGES = "intl.accept_languages"; - -function assertPrefered(assert, expected, msg) { - assert.equal(JSON.stringify(getPreferedLocales()), JSON.stringify(expected), - msg); -} - -exports.testGetPreferedLocales = function(assert) { - prefs.set(PREF_MATCH_OS_LOCALE, false); - prefs.set(PREF_SELECTED_LOCALE, ""); - prefs.set(PREF_ACCEPT_LANGUAGES, ""); - assertPrefered(assert, ["en-us"], - "When all preferences are empty, we only have en-us"); - - prefs.set(PREF_SELECTED_LOCALE, "fr"); - prefs.set(PREF_ACCEPT_LANGUAGES, "jp"); - assertPrefered(assert, ["fr", "jp", "en-us"], - "We first have useragent locale, then web one and finally en-US"); - - prefs.set(PREF_SELECTED_LOCALE, "en-US"); - prefs.set(PREF_ACCEPT_LANGUAGES, "en-US"); - assertPrefered(assert, ["en-us"], - "We do not have duplicates"); - - prefs.set(PREF_SELECTED_LOCALE, "en-US"); - prefs.set(PREF_ACCEPT_LANGUAGES, "fr"); - assertPrefered(assert, ["en-us", "fr"], - "en-US can be first if specified by higher priority preference"); - - // Reset what we changed - prefs.reset(PREF_MATCH_OS_LOCALE); - prefs.reset(PREF_SELECTED_LOCALE); - prefs.reset(PREF_ACCEPT_LANGUAGES); -} - -// In some cases, mainly on Fennec and on Linux version, -// `general.useragent.locale` is a special 'localized' value, like: -// "chrome://global/locale/intl.properties" -exports.testPreferedLocalizedLocale = function(assert) { - prefs.set(PREF_MATCH_OS_LOCALE, false); - let bundleURL = "chrome://global/locale/intl.properties"; - prefs.setLocalized(PREF_SELECTED_LOCALE, bundleURL); - let contentLocale = "ja"; - prefs.set(PREF_ACCEPT_LANGUAGES, contentLocale); - - // Read manually the expected locale value from the property file - let expectedLocale = BundleService.createBundle(bundleURL). - GetStringFromName(PREF_SELECTED_LOCALE). - toLowerCase(); - - // First add the useragent locale - let expectedLocaleList = [expectedLocale]; - - // Then the content locale - if (expectedLocaleList.indexOf(contentLocale) == -1) - expectedLocaleList.push(contentLocale); - - // Add default "en-us" fallback if the main language is not already en-us - if (expectedLocaleList.indexOf("en-us") == -1) - expectedLocaleList.push("en-us"); - - assertPrefered(assert, expectedLocaleList, "test localized pref value"); - - // Reset what we have changed - prefs.reset(PREF_MATCH_OS_LOCALE); - prefs.reset(PREF_SELECTED_LOCALE); - prefs.reset(PREF_ACCEPT_LANGUAGES); -} - -// On Linux the PREF_ACCEPT_LANGUAGES pref can be a localized pref. -exports.testPreferedContentLocale = function(assert) { - prefs.set(PREF_MATCH_OS_LOCALE, false); - let noLocale = "", - bundleURL = "chrome://global/locale/intl.properties"; - prefs.set(PREF_SELECTED_LOCALE, noLocale); - prefs.setLocalized(PREF_ACCEPT_LANGUAGES, bundleURL); - - // Read the expected locale values from the property file - let expectedLocaleList = BundleService.createBundle(bundleURL). - GetStringFromName(PREF_ACCEPT_LANGUAGES). - split(","). - map(locale => locale.trim().toLowerCase()); - - // Add default "en-us" fallback if the main language is not already en-us - if (expectedLocaleList.indexOf("en-us") == -1) - expectedLocaleList.push("en-us"); - - assertPrefered(assert, expectedLocaleList, "test localized content locale pref value"); - - // Reset what we have changed - prefs.reset(PREF_MATCH_OS_LOCALE); - prefs.reset(PREF_SELECTED_LOCALE); - prefs.reset(PREF_ACCEPT_LANGUAGES); -} - -exports.testPreferedOsLocale = function(assert) { - prefs.set(PREF_MATCH_OS_LOCALE, true); - prefs.set(PREF_SELECTED_LOCALE, ""); - prefs.set(PREF_ACCEPT_LANGUAGES, ""); - - let expectedLocale = Services.locale.getLocaleComponentForUserAgent(). - toLowerCase(); - let expectedLocaleList = [expectedLocale]; - - // Add default "en-us" fallback if the main language is not already en-us - if (expectedLocale != "en-us") - expectedLocaleList.push("en-us"); - - assertPrefered(assert, expectedLocaleList, "Ensure that we select OS locale when related preference is set"); - - // Reset what we have changed - prefs.reset(PREF_MATCH_OS_LOCALE); - prefs.reset(PREF_SELECTED_LOCALE); - prefs.reset(PREF_ACCEPT_LANGUAGES); -} - -exports.testFindClosestLocale = function(assert) { - // Second param of findClosestLocale (aMatchLocales) have to be in lowercase - assert.equal(findClosestLocale([], []), null, - "When everything is empty we get null"); - - assert.equal(findClosestLocale(["en", "en-US"], ["en"]), - "en", "We always accept exact match first 1/5"); - assert.equal(findClosestLocale(["en-US", "en"], ["en"]), - "en", "We always accept exact match first 2/5"); - assert.equal(findClosestLocale(["en", "en-US"], ["en-us"]), - "en-US", "We always accept exact match first 3/5"); - assert.equal(findClosestLocale(["ja-JP-mac", "ja", "ja-JP"], ["ja-jp"]), - "ja-JP", "We always accept exact match first 4/5"); - assert.equal(findClosestLocale(["ja-JP-mac", "ja", "ja-JP"], ["ja-jp-mac"]), - "ja-JP-mac", "We always accept exact match first 5/5"); - - assert.equal(findClosestLocale(["en", "en-GB"], ["en-us"]), - "en", "We accept more generic locale, when there is no exact match 1/2"); - assert.equal(findClosestLocale(["en-ZA", "en"], ["en-gb"]), - "en", "We accept more generic locale, when there is no exact match 2/2"); - - assert.equal(findClosestLocale(["ja-JP"], ["ja"]), - "ja-JP", "We accept more specialized locale, when there is no exact match 1/2"); - // Better to select "ja" in this case but behave same as current AddonManager - assert.equal(findClosestLocale(["ja-JP-mac", "ja"], ["ja-jp"]), - "ja-JP-mac", "We accept more specialized locale, when there is no exact match 2/2"); - - assert.equal(findClosestLocale(["en-US"], ["en-us"]), - "en-US", "We keep the original one as result 1/2"); - assert.equal(findClosestLocale(["en-us"], ["en-us"]), - "en-us", "We keep the original one as result 2/2"); - - assert.equal(findClosestLocale(["ja-JP-mac"], ["ja-jp-mac"]), - "ja-JP-mac", "We accept locale with 3 parts"); - assert.equal(findClosestLocale(["ja-JP"], ["ja-jp-mac"]), - "ja-JP", "We accept locale with 2 parts from locale with 3 parts"); - assert.equal(findClosestLocale(["ja"], ["ja-jp-mac"]), - "ja", "We accept locale with 1 part from locale with 3 parts"); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-l10n-plural-rules.js b/addon-sdk/source/test/test-l10n-plural-rules.js deleted file mode 100644 index 953d977a4..000000000 --- a/addon-sdk/source/test/test-l10n-plural-rules.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/. */ - "use strict"; - -const { getRulesForLocale } = require("sdk/l10n/plural-rules"); - -// For more information, please visit unicode website: -// http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html - -function map(assert, f, n, form) { - assert.equal(f(n), form, n + " maps to '" + form + "'"); -} - -exports.testFrench = function(assert) { - let f = getRulesForLocale("fr"); - map(assert, f, -1, "other"); - map(assert, f, 0, "one"); - map(assert, f, 1, "one"); - map(assert, f, 1.5, "one"); - map(assert, f, 2, "other"); - map(assert, f, 100, "other"); -} - -exports.testEnglish = function(assert) { - let f = getRulesForLocale("en"); - map(assert, f, -1, "other"); - map(assert, f, 0, "other"); - map(assert, f, 1, "one"); - map(assert, f, 1.5, "other"); - map(assert, f, 2, "other"); - map(assert, f, 100, "other"); -} - -exports.testArabic = function(assert) { - let f = getRulesForLocale("ar"); - map(assert, f, -1, "other"); - map(assert, f, 0, "zero"); - map(assert, f, 0.5, "other"); - - map(assert, f, 1, "one"); - map(assert, f, 1.5, "other"); - - map(assert, f, 2, "two"); - map(assert, f, 2.5, "other"); - - map(assert, f, 3, "few"); - map(assert, f, 3.5, "few"); // I'd expect it to be 'other', but the unicode.org - // algorithm computes 'few'. - map(assert, f, 5, "few"); - map(assert, f, 10, "few"); - map(assert, f, 103, "few"); - map(assert, f, 105, "few"); - map(assert, f, 110, "few"); - map(assert, f, 203, "few"); - map(assert, f, 205, "few"); - map(assert, f, 210, "few"); - - map(assert, f, 11, "many"); - map(assert, f, 50, "many"); - map(assert, f, 99, "many"); - map(assert, f, 111, "many"); - map(assert, f, 150, "many"); - map(assert, f, 199, "many"); - - map(assert, f, 100, "other"); - map(assert, f, 101, "other"); - map(assert, f, 102, "other"); - map(assert, f, 200, "other"); - map(assert, f, 201, "other"); - map(assert, f, 202, "other"); -} - -exports.testJapanese = function(assert) { - // Japanese doesn't have plural forms. - let f = getRulesForLocale("ja"); - map(assert, f, -1, "other"); - map(assert, f, 0, "other"); - map(assert, f, 1, "other"); - map(assert, f, 1.5, "other"); - map(assert, f, 2, "other"); - map(assert, f, 100, "other"); -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-lang-type.js b/addon-sdk/source/test/test-lang-type.js deleted file mode 100644 index c0e510076..000000000 --- a/addon-sdk/source/test/test-lang-type.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/. */ -"use strict" - -var utils = require("sdk/lang/type"); - -exports["test function"] = function (assert) { - assert.equal(utils.isFunction(function(){}), true, "value is a function"); - assert.equal(utils.isFunction(Object), true, "Object is a function"); - assert.equal(utils.isFunction(new Function("")), true, "Genertaed value is a function"); - assert.equal(utils.isFunction({}), false, "object is not a function"); - assert.equal(utils.isFunction(4), false, "number is not a function"); -}; - -exports["test atoms"] = function (assert) { - assert.equal(utils.isPrimitive(2), true, "number is a primitive"); - assert.equal(utils.isPrimitive(NaN), true, "`NaN` is a primitve"); - assert.equal(utils.isPrimitive(undefined), true, "`undefined` is a primitive"); - assert.equal(utils.isPrimitive(null), true, "`null` is a primitive"); - assert.equal(utils.isPrimitive(Infinity), true, "`Infinity` is a primitive"); - assert.equal(utils.isPrimitive("foo"), true, "strings are a primitive"); - assert.ok(utils.isPrimitive(true) && utils.isPrimitive(false), - "booleans are primitive"); -}; - -exports["test object"] = function (assert) { - assert.equal(utils.isObject({}), true, "`{}` is an object"); - assert.ok(!utils.isObject(null), "`null` is not an object"); - assert.ok(!utils.isObject(Object), "functions is not an object"); -}; - -exports["test generator"] = function (assert) { - assert.equal(utils.isGenerator(function*(){}), true, "`function*(){}` is a generator"); - assert.equal(utils.isGenerator(function(){}), false, "`function(){}` is not a generator"); - assert.equal(utils.isGenerator(() => {}), false, "`() => {}` is not a generator"); - assert.equal(utils.isGenerator({}), false, "`{}` is not a generator"); - assert.equal(utils.isGenerator(1), false, "`1` is not a generator"); - assert.equal(utils.isGenerator([]), false, "`[]` is not a generator"); - assert.equal(utils.isGenerator(null), false, "`null` is not a generator"); - assert.equal(utils.isGenerator(undefined), false, "`undefined` is not a generator"); -}; - -exports["test array"] = function (assert) { - assert.equal(utils.isArray([]), true, "[] is an array"); - assert.equal(utils.isArray([1]), true, "[1] is an array"); - assert.equal(utils.isArray(new Array()), true, "new Array() is an array"); - assert.equal(utils.isArray(new Array(10)), true, "new Array(10) is an array"); - assert.equal(utils.isArray(Array.prototype), true, "Array.prototype is an array"); - - assert.equal(utils.isArray(), false, "implicit undefined is not an array"); - assert.equal(utils.isArray(null), false, "null is not an array"); - assert.equal(utils.isArray(undefined), false, "undefined is not an array"); - assert.equal(utils.isArray(1), false, "1 is not an array"); - assert.equal(utils.isArray(true), false, "true is not an array"); - assert.equal(utils.isArray('foo'), false, "'foo' is not an array"); - assert.equal(utils.isArray({}), false, "{} is not an array"); - assert.equal(utils.isArray(Symbol.iterator), false, "Symbol.iterator is not an array"); -}; - -exports["test arguments"] = function (assert) { - assert.equal(utils.isArguments(arguments), true, "arguments is an arguments"); - (function() { - assert.equal(utils.isArguments(arguments), true, "arguments in nested function is an arguments"); - })(); - (function*() { - assert.equal(utils.isArguments(arguments), true, "arguments in nested generator is an arguments"); - })(); - (() => { - assert.equal(utils.isArguments(arguments), true, "arguments in arrow function is an arguments"); - })(); - - assert.equal(utils.isArguments(), false, "implicit undefined is not an arguments"); - assert.equal(utils.isArguments(null), false, "null is not an arguments"); - assert.equal(utils.isArguments(undefined), false, "undefined is not an arguments"); - assert.equal(utils.isArguments(1), false, "1 is not an arguments"); - assert.equal(utils.isArguments(true), false, "true is not an arguments"); - assert.equal(utils.isArguments('foo'), false, "'foo' is not an arguments"); - assert.equal(utils.isArguments([]), false, "[] is not an arguments"); - assert.equal(utils.isArguments({}), false, "{} is not an arguments"); - assert.equal(utils.isArguments(Symbol.iterator), false, "Symbol.iterator is not an arguments"); - (function(...args) { - assert.equal(utils.isArguments(args), false, "rest arguments is not an arguments"); - })(); -}; - -exports["test flat objects"] = function (assert) { - assert.ok(utils.isFlat({}), "`{}` is a flat object"); - assert.ok(!utils.isFlat([]), "`[]` is not a flat object"); - assert.ok(!utils.isFlat(new function() {}), "derived objects are not flat"); - assert.ok(utils.isFlat(Object.prototype), "Object.prototype is flat"); -}; - -exports["test json atoms"] = function (assert) { - assert.ok(utils.isJSON(null), "`null` is JSON"); - assert.ok(utils.isJSON(undefined), "`undefined` is JSON"); - assert.ok(utils.isJSON(NaN), "`NaN` is JSON"); - assert.ok(utils.isJSON(Infinity), "`Infinity` is JSON"); - assert.ok(utils.isJSON(true) && utils.isJSON(false), "booleans are JSON"); - assert.ok(utils.isJSON(4), utils.isJSON(0), "numbers are JSON"); - assert.ok(utils.isJSON("foo bar"), "strings are JSON"); -}; - -exports["test jsonable values"] = function (assert) { - assert.ok(utils.isJSONable(null), "`null` is JSONable"); - assert.ok(!utils.isJSONable(undefined), "`undefined` is not JSONable"); - assert.ok(utils.isJSONable(NaN), "`NaN` is JSONable"); - assert.ok(utils.isJSONable(Infinity), "`Infinity` is JSONable"); - assert.ok(utils.isJSONable(true) && utils.isJSONable(false), "booleans are JSONable"); - assert.ok(utils.isJSONable(0), "numbers are JSONable"); - assert.ok(utils.isJSONable("foo bar"), "strings are JSONable"); - assert.ok(!utils.isJSONable(function(){}), "functions are not JSONable"); - - const functionWithToJSON = function(){}; - functionWithToJSON.toJSON = function() { return "foo bar"; }; - assert.ok(utils.isJSONable(functionWithToJSON), "functions with toJSON() are JSONable"); - - assert.ok(utils.isJSONable({}), "`{}` is JSONable"); - - const foo = {}; - foo.bar = foo; - assert.ok(!utils.isJSONable(foo), "recursive objects are not JSONable"); -}; - -exports["test instanceOf"] = function (assert) { - assert.ok(utils.instanceOf(assert, Object), - "assert is object from other sandbox"); - assert.ok(utils.instanceOf(new Date(), Date), "instance of date"); - assert.ok(!utils.instanceOf(null, Object), "null is not an instance"); -}; - -exports["test json"] = function (assert) { - assert.ok(!utils.isJSON(function(){}), "functions are not json"); - assert.ok(utils.isJSON({}), "`{}` is JSON"); - assert.ok(utils.isJSON({ - a: "foo", - b: 3, - c: undefined, - d: null, - e: { - f: { - g: "bar", - p: [{}, "oueou", 56] - }, - q: { nan: NaN, infinity: Infinity }, - "non standard name": "still works" - } - }), "JSON can contain nested objects"); - - var foo = {}; - var bar = { foo: foo }; - foo.bar = bar; - assert.ok(!utils.isJSON(foo), "recursive objects are not json"); - - - assert.ok(!utils.isJSON({ get foo() { return 5 } }), - "json can not have getter"); - - assert.ok(!utils.isJSON({ foo: "bar", baz: function () {} }), - "json can not contain functions"); - - assert.ok(!utils.isJSON(Object.create({})), - "json must be direct descendant of `Object.prototype`"); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-libxul.js b/addon-sdk/source/test/test-libxul.js deleted file mode 100644 index 7a11a69cb..000000000 --- a/addon-sdk/source/test/test-libxul.js +++ /dev/null @@ -1,18 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 we can link with libxul using js-ctypes - -const {Cu} = require("chrome"); -const {ctypes} = Cu.import("resource://gre/modules/ctypes.jsm", {}); -const {OS} = Cu.import("resource://gre/modules/osfile.jsm", {}); - -exports.test = function(assert) { - let path = OS.Constants.Path.libxul; - assert.pass("libxul is at " + path); - let lib = ctypes.open(path); - assert.ok(lib != null, "linked to libxul successfully"); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-list.js b/addon-sdk/source/test/test-list.js deleted file mode 100644 index 9b03a9513..000000000 --- a/addon-sdk/source/test/test-list.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/. */ -'use strict'; - -const { List, addListItem, removeListItem } = require('sdk/util/list'); -const { Class } = require('sdk/core/heritage'); - -exports.testList = function(assert) { - let list = List(); - addListItem(list, 1); - - for (let key in list) { - assert.equal(key, 0, 'key is correct'); - assert.equal(list[key], 1, 'value is correct'); - } - - let count = 0; - for (let ele of list) { - assert.equal(ele, 1, 'ele is correct'); - assert.equal(++count, 1, 'count is correct'); - } - - count = 0; - for (let ele of list) { - assert.equal(ele, 1, 'ele is correct'); - assert.equal(++count, 1, 'count is correct'); - } - - removeListItem(list, 1); - assert.equal(list.length, 0, 'remove worked'); -}; - -exports.testImplementsList = function(assert) { - let List2 = Class({ - implements: [List], - initialize: function() { - List.prototype.initialize.apply(this, [0, 1, 2]); - } - }); - let list2 = List2(); - let count = 0; - - for (let ele of list2) { - assert.equal(ele, count++, 'ele is correct'); - } - - count = 0; - for (let ele of list2) { - assert.equal(ele, count++, 'ele is correct'); - } - - addListItem(list2, 3); - assert.equal(list2.length, 4, '3 was added'); - assert.equal(list2[list2.length-1], 3, '3 was added'); -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-loader.js b/addon-sdk/source/test/test-loader.js deleted file mode 100644 index 3ee3e34f0..000000000 --- a/addon-sdk/source/test/test-loader.js +++ /dev/null @@ -1,657 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { - Loader, main, unload, parseStack, resolve, join, - Require, Module -} = require('toolkit/loader'); -var { readURI } = require('sdk/net/url'); - -var root = module.uri.substr(0, module.uri.lastIndexOf('/')); - -const app = require('sdk/system/xul-app'); - -// The following adds Debugger constructor to the global namespace. -const { Cu } = require('chrome'); -const { addDebuggerToGlobal } = Cu.import('resource://gre/modules/jsdebugger.jsm', {}); -addDebuggerToGlobal(this); - -exports['test resolve'] = function (assert) { - let cuddlefish_id = 'sdk/loader/cuddlefish'; - assert.equal(resolve('../index.js', './dir/c.js'), './index.js'); - assert.equal(resolve('./index.js', './dir/c.js'), './dir/index.js'); - assert.equal(resolve('./dir/c.js', './index.js'), './dir/c.js'); - assert.equal(resolve('../utils/file.js', './dir/b.js'), './utils/file.js'); - - assert.equal(resolve('../utils/./file.js', './dir/b.js'), './utils/file.js'); - assert.equal(resolve('../utils/file.js', './'), './../utils/file.js'); - assert.equal(resolve('./utils/file.js', './'), './utils/file.js'); - assert.equal(resolve('./utils/file.js', './index.js'), './utils/file.js'); - - assert.equal(resolve('../utils/./file.js', cuddlefish_id), 'sdk/utils/file.js'); - assert.equal(resolve('../utils/file.js', cuddlefish_id), 'sdk/utils/file.js'); - assert.equal(resolve('./utils/file.js', cuddlefish_id), 'sdk/loader/utils/file.js'); - - assert.equal(resolve('..//index.js', './dir/c.js'), './index.js'); - assert.equal(resolve('../modules/XPCOMUtils.jsm', 'resource://gre/utils/file.js'), 'resource://gre/modules/XPCOMUtils.jsm'); - assert.equal(resolve('../modules/XPCOMUtils.jsm', 'chrome://gre/utils/file.js'), 'chrome://gre/modules/XPCOMUtils.jsm'); - assert.equal(resolve('../../a/b/c.json', 'file:///thing/utils/file.js'), 'file:///a/b/c.json'); - - // Does not change absolute paths - assert.equal(resolve('resource://gre/modules/file.js', './dir/b.js'), - 'resource://gre/modules/file.js'); - assert.equal(resolve('file:///gre/modules/file.js', './dir/b.js'), - 'file:///gre/modules/file.js'); - assert.equal(resolve('/root.js', './dir/b.js'), - '/root.js'); -}; - -exports['test join'] = function (assert) { - assert.equal(join('a/path', '../../../module'), '../module'); - assert.equal(join('a/path/to', '../module'), 'a/path/module'); - assert.equal(join('a/path/to', './module'), 'a/path/to/module'); - assert.equal(join('a/path/to', '././../module'), 'a/path/module'); - assert.equal(join('resource://my/path/yeah/yuh', '../whoa'), - 'resource://my/path/yeah/whoa'); - assert.equal(join('resource://my/path/yeah/yuh', './whoa'), - 'resource://my/path/yeah/yuh/whoa'); - assert.equal(join('resource:///my/path/yeah/yuh', '../whoa'), - 'resource:///my/path/yeah/whoa'); - assert.equal(join('resource:///my/path/yeah/yuh', './whoa'), - 'resource:///my/path/yeah/yuh/whoa'); - assert.equal(join('file:///my/path/yeah/yuh', '../whoa'), - 'file:///my/path/yeah/whoa'); - assert.equal(join('file:///my/path/yeah/yuh', './whoa'), - 'file:///my/path/yeah/yuh/whoa'); - assert.equal(join('a/path/to', '..//module'), 'a/path/module'); -}; - -exports['test dependency cycles'] = function(assert) { - let uri = root + '/fixtures/loader/cycles/'; - let loader = Loader({ paths: { '': uri } }); - - let program = main(loader, 'main'); - - assert.equal(program.a.b, program.b, 'module `a` gets correct `b`'); - assert.equal(program.b.a, program.a, 'module `b` gets correct `a`'); - assert.equal(program.c.main, program, 'module `c` gets correct `main`'); - - unload(loader); -} - -exports['test syntax errors'] = function(assert) { - let uri = root + '/fixtures/loader/syntax-error/'; - let loader = Loader({ paths: { '': uri } }); - - try { - let program = main(loader, 'main'); - } catch (error) { - assert.equal(error.name, "SyntaxError", "throws syntax error"); - assert.equal(error.fileName.split("/").pop(), "error.js", - "Error contains filename"); - assert.equal(error.lineNumber, 11, "error is on line 11"); - let stack = parseStack(error.stack); - - assert.equal(stack.pop().fileName, uri + "error.js", - "last frame file containing syntax error"); - assert.equal(stack.pop().fileName, uri + "main.js", - "previous frame is a requirer module"); - assert.equal(stack.pop().fileName, module.uri, - "previous to it is a test module"); - - } finally { - unload(loader); - } -} - -exports['test sandboxes are not added if error'] = function (assert) { - let uri = root + '/fixtures/loader/missing-twice/'; - let loader = Loader({ paths: { '': uri } }); - let program = main(loader, 'main'); - assert.ok(!(uri + 'not-found.js' in loader.sandboxes), 'not-found.js not in loader.sandboxes'); -} - -exports['test missing module'] = function(assert) { - let uri = root + '/fixtures/loader/missing/' - let loader = Loader({ paths: { '': uri } }); - - try { - let program = main(loader, 'main') - } catch (error) { - assert.equal(error.message, "Module `not-found` is not found at " + - uri + "not-found.js", "throws if error not found"); - - assert.equal(error.fileName.split("/").pop(), "main.js", - "Error fileName is requirer module"); - - assert.equal(error.lineNumber, 7, "error is on line 7"); - - let stack = parseStack(error.stack); - - assert.equal(stack.pop().fileName, uri + "main.js", - "loader stack is omitted"); - - assert.equal(stack.pop().fileName, module.uri, - "previous in the stack is test module"); - } finally { - unload(loader); - } -} - -exports["test invalid module not cached and throws everytime"] = function(assert) { - let uri = root + "/fixtures/loader/missing-twice/"; - let loader = Loader({ paths: { "": uri } }); - - let { firstError, secondError, invalidJSON1, invalidJSON2 } = main(loader, "main"); - assert.equal(firstError.message, "Module `not-found` is not found at " + - uri + "not-found.js", "throws on first invalid require"); - assert.equal(firstError.lineNumber, 8, "first error is on line 7"); - assert.equal(secondError.message, "Module `not-found` is not found at " + - uri + "not-found.js", "throws on second invalid require"); - assert.equal(secondError.lineNumber, 14, "second error is on line 14"); - - assert.equal(invalidJSON1.message, - "JSON.parse: unexpected character at line 1 column 1 of the JSON data", - "throws on invalid JSON"); - assert.equal(invalidJSON2.message, - "JSON.parse: unexpected character at line 1 column 1 of the JSON data", - "throws on invalid JSON second time"); -}; - -exports['test exceptions in modules'] = function(assert) { - let uri = root + '/fixtures/loader/exceptions/' - - let loader = Loader({ paths: { '': uri } }); - - try { - let program = main(loader, 'main') - } catch (error) { - assert.equal(error.message, "Boom!", "thrown errors propagate"); - - assert.equal(error.fileName.split("/").pop(), "boomer.js", - "Error comes from the module that threw it"); - - assert.equal(error.lineNumber, 8, "error is on line 8"); - - let stack = parseStack(error.stack); - - let frame = stack.pop() - assert.equal(frame.fileName, uri + "boomer.js", - "module that threw is first in the stack"); - assert.equal(frame.name, "exports.boom", - "name is in the stack"); - - frame = stack.pop() - assert.equal(frame.fileName, uri + "main.js", - "module that called it is next in the stack"); - assert.equal(frame.lineNumber, 9, "caller line is in the stack"); - - - assert.equal(stack.pop().fileName, module.uri, - "this test module is next in the stack"); - } finally { - unload(loader); - } -} - -exports['test early errors in module'] = function(assert) { - let uri = root + '/fixtures/loader/errors/'; - let loader = Loader({ paths: { '': uri } }); - - try { - let program = main(loader, 'main') - } catch (error) { - assert.equal(String(error), - "Error: opening input stream (invalid filename?)", - "thrown errors propagate"); - - assert.equal(error.fileName.split("/").pop(), "boomer.js", - "Error comes from the module that threw it"); - - assert.equal(error.lineNumber, 7, "error is on line 7"); - - let stack = parseStack(error.stack); - - let frame = stack.pop() - assert.equal(frame.fileName, uri + "boomer.js", - "module that threw is first in the stack"); - - frame = stack.pop() - assert.equal(frame.fileName, uri + "main.js", - "module that called it is next in the stack"); - assert.equal(frame.lineNumber, 7, "caller line is in the stack"); - - - assert.equal(stack.pop().fileName, module.uri, - "this test module is next in the stack"); - } finally { - unload(loader); - } -}; - -exports['test require json'] = function (assert) { - let data = require('./fixtures/loader/json/manifest.json'); - assert.equal(data.name, 'Jetpack Loader Test', 'loads json with strings'); - assert.equal(data.version, '1.0.1', 'loads json with strings'); - assert.equal(data.dependencies.async, '*', 'loads json with objects'); - assert.equal(data.dependencies.underscore, '*', 'loads json with objects'); - assert.equal(data.contributors.length, 4, 'loads json with arrays'); - assert.ok(Array.isArray(data.contributors), 'loads json with arrays'); - data.version = '2.0.0'; - let newdata = require('./fixtures/loader/json/manifest.json'); - assert.equal(newdata.version, '2.0.0', - 'JSON objects returned should be cached and the same instance'); - - try { - require('./fixtures/loader/json/invalid.json'); - assert.fail('Error not thrown when loading invalid json'); - } catch (err) { - assert.ok(err, 'error thrown when loading invalid json'); - assert.ok(/JSON\.parse/.test(err.message), - 'should thrown an error from JSON.parse, not attempt to load .json.js'); - } - - // Try again to ensure an empty module isn't loaded from cache - try { - require('./fixtures/loader/json/invalid.json'); - assert.fail('Error not thrown when loading invalid json a second time'); - } catch (err) { - assert.ok(err, - 'error thrown when loading invalid json a second time'); - assert.ok(/JSON\.parse/.test(err.message), - 'should thrown an error from JSON.parse a second time, not attempt to load .json.js'); - } -}; - -exports['test setting metadata for newly created sandboxes'] = function(assert) { - let addonID = 'random-addon-id'; - let uri = root + '/fixtures/loader/cycles/'; - let loader = Loader({ paths: { '': uri }, id: addonID }); - - let dbg = new Debugger(); - dbg.onNewGlobalObject = function(global) { - dbg.onNewGlobalObject = undefined; - - let metadata = Cu.getSandboxMetadata(global.unsafeDereference()); - assert.ok(metadata, 'this global has attached metadata'); - assert.equal(metadata.URI, uri + 'main.js', 'URI is set properly'); - assert.equal(metadata.addonID, addonID, 'addon ID is set'); - } - - let program = main(loader, 'main'); -}; - -exports['test require .json, .json.js'] = function (assert) { - let testjson = require('./fixtures/loader/json/test.json'); - assert.equal(testjson.filename, 'test.json', - 'require("./x.json") should load x.json, not x.json.js'); - - let nodotjson = require('./fixtures/loader/json/nodotjson.json'); - assert.equal(nodotjson.filename, 'nodotjson.json.js', - 'require("./x.json") should load x.json.js when x.json does not exist'); - nodotjson.data.prop = 'hydralisk'; - - // require('nodotjson.json') and require('nodotjson.json.js') - // should resolve to the same file - let nodotjsonjs = require('./fixtures/loader/json/nodotjson.json.js'); - assert.equal(nodotjsonjs.data.prop, 'hydralisk', - 'js modules are cached whether access via .json.js or .json'); -}; - -exports['test invisibleToDebugger: false'] = function (assert) { - let uri = root + '/fixtures/loader/cycles/'; - let loader = Loader({ paths: { '': uri } }); - main(loader, 'main'); - - let dbg = new Debugger(); - let sandbox = loader.sandboxes[uri + 'main.js']; - - try { - dbg.addDebuggee(sandbox); - assert.ok(true, 'debugger added visible value'); - } catch(e) { - assert.fail('debugger could not add visible value'); - } -}; - -exports['test invisibleToDebugger: true'] = function (assert) { - let uri = root + '/fixtures/loader/cycles/'; - let loader = Loader({ paths: { '': uri }, invisibleToDebugger: true }); - main(loader, 'main'); - - let dbg = new Debugger(); - let sandbox = loader.sandboxes[uri + 'main.js']; - - try { - dbg.addDebuggee(sandbox); - assert.fail('debugger added invisible value'); - } catch(e) { - assert.ok(true, 'debugger did not add invisible value'); - } -}; - -exports['test console global by default'] = function (assert) { - let uri = root + '/fixtures/loader/globals/'; - let loader = Loader({ paths: { '': uri }}); - let program = main(loader, 'main'); - - assert.ok(typeof program.console === 'object', 'global `console` exists'); - assert.ok(typeof program.console.log === 'function', 'global `console.log` exists'); - - let loader2 = Loader({ paths: { '': uri }, globals: { console: fakeConsole }}); - let program2 = main(loader2, 'main'); - - assert.equal(program2.console, fakeConsole, - 'global console can be overridden with Loader options'); - function fakeConsole () {}; -}; - -exports['test shared globals'] = function(assert) { - let uri = root + '/fixtures/loader/cycles/'; - let loader = Loader({ paths: { '': uri }, sharedGlobal: true, - sharedGlobalBlocklist: ['b'] }); - - let program = main(loader, 'main'); - - // As it is hard to verify what is the global of an object - // (due to wrappers) we check that we see the `foo` symbol - // being manually injected into the shared global object - loader.sharedGlobalSandbox.foo = true; - - let m = loader.sandboxes[uri + 'main.js']; - let a = loader.sandboxes[uri + 'a.js']; - let b = loader.sandboxes[uri + 'b.js']; - - assert.ok(Cu.getGlobalForObject(m).foo, "main is shared"); - assert.ok(Cu.getGlobalForObject(a).foo, "a is shared"); - assert.ok(!Cu.getGlobalForObject(b).foo, "b isn't shared"); - - unload(loader); -} - -exports['test deprecated shared globals exception name'] = function(assert) { - let uri = root + '/fixtures/loader/cycles/'; - let loader = Loader({ paths: { '': uri }, sharedGlobal: true, - sharedGlobalBlacklist: ['b'] }); - - let program = main(loader, 'main'); - - assert.ok(loader.sharedGlobalBlocklist.includes("b"), "b should be in the blocklist"); - assert.equal(loader.sharedGlobalBlocklist.length, loader.sharedGlobalBlacklist.length, - "both blocklists should have the same number of items."); - assert.equal(loader.sharedGlobalBlocklist.join(","), loader.sharedGlobalBlacklist.join(","), - "both blocklists should have the same items."); - - // As it is hard to verify what is the global of an object - // (due to wrappers) we check that we see the `foo` symbol - // being manually injected into the shared global object - loader.sharedGlobalSandbox.foo = true; - - let m = loader.sandboxes[uri + 'main.js']; - let a = loader.sandboxes[uri + 'a.js']; - let b = loader.sandboxes[uri + 'b.js']; - - assert.ok(Cu.getGlobalForObject(m).foo, "main is shared"); - assert.ok(Cu.getGlobalForObject(a).foo, "a is shared"); - assert.ok(!Cu.getGlobalForObject(b).foo, "b isn't shared"); - - unload(loader); -} - -exports['test prototype of global'] = function (assert) { - let uri = root + '/fixtures/loader/globals/'; - let loader = Loader({ paths: { '': uri }, sharedGlobal: true, - sandboxPrototype: { globalFoo: 5 }}); - - let program = main(loader, 'main'); - - assert.ok(program.globalFoo === 5, '`globalFoo` exists'); -}; - -exports["test require#resolve"] = function(assert) { - let foundRoot = require.resolve("sdk/tabs").replace(/sdk\/tabs.js$/, ""); - assert.ok(root, foundRoot, "correct resolution root"); - - assert.equal(foundRoot + "sdk/tabs.js", require.resolve("sdk/tabs"), "correct resolution of sdk module"); - assert.equal(foundRoot + "toolkit/loader.js", require.resolve("toolkit/loader"), "correct resolution of sdk module"); - - const localLoader = Loader({ - paths: { "foo/bar": "bizzle", - "foo/bar2/": "bizzle2", - // Just to make sure this doesn't match the first entry, - // let use resolve this module - "foo/bar-bar": "foo/bar-bar" } - }); - const localRequire = Require(localLoader, module); - assert.equal(localRequire.resolve("foo/bar"), "bizzle.js"); - assert.equal(localRequire.resolve("foo/bar/baz"), "bizzle/baz.js"); - assert.equal(localRequire.resolve("foo/bar-bar"), "foo/bar-bar.js"); - assert.equal(localRequire.resolve("foo/bar2/"), "bizzle2.js"); -}; - -const modulesURI = require.resolve("toolkit/loader").replace("toolkit/loader.js", ""); -exports["test loading a loader"] = function(assert) { - const loader = Loader({ paths: { "": modulesURI } }); - - const require = Require(loader, module); - - const requiredLoader = require("toolkit/loader"); - - assert.equal(requiredLoader.Loader, Loader, - "got the same Loader instance"); - - const jsmLoader = Cu.import(require.resolve("toolkit/loader"), {}).Loader; - - assert.equal(jsmLoader.Loader, requiredLoader.Loader, - "loading loader via jsm returns same loader"); - - unload(loader); -}; - -exports['test loader on unsupported modules with checkCompatibility true'] = function(assert) { - let loader = Loader({ - paths: { '': root + "/" }, - checkCompatibility: true - }); - let require = Require(loader, module); - - assert.throws(() => { - if (!app.is('Firefox')) { - require('fixtures/loader/unsupported/firefox'); - } - else { - require('fixtures/loader/unsupported/fennec'); - } - }, /^Unsupported Application/, "throws Unsupported Application"); - - unload(loader); -}; - -exports['test loader on unsupported modules with checkCompatibility false'] = function(assert) { - let loader = Loader({ - paths: { '': root + "/" }, - checkCompatibility: false - }); - let require = Require(loader, module); - - try { - if (!app.is('Firefox')) { - require('fixtures/loader/unsupported/firefox'); - } - else { - require('fixtures/loader/unsupported/fennec'); - } - assert.pass("loaded unsupported module without an error"); - } - catch(e) { - assert.fail(e); - } - - unload(loader); -}; - -exports['test loader on unsupported modules with checkCompatibility default'] = function(assert) { - let loader = Loader({ paths: { '': root + "/" } }); - let require = Require(loader, module); - - try { - if (!app.is('Firefox')) { - require('fixtures/loader/unsupported/firefox'); - } - else { - require('fixtures/loader/unsupported/fennec'); - } - assert.pass("loaded unsupported module without an error"); - } - catch(e) { - assert.fail(e); - } - - unload(loader); -}; - -exports["test Cu.import of toolkit/loader"] = (assert) => { - const toolkitLoaderURI = require.resolve("toolkit/loader"); - const loaderModule = Cu.import(toolkitLoaderURI).Loader; - const { Loader, Require, Main } = loaderModule; - const version = "0.1.0"; - const id = `fxos_${version.replace(".", "_")}_simulator@mozilla.org`; - const uri = `resource://${encodeURIComponent(id.replace("@", "at"))}/`; - - const loader = Loader({ - paths: { - "./": uri + "lib/", - // Can't just put `resource://gre/modules/commonjs/` as it - // won't take module overriding into account. - "": toolkitLoaderURI.replace("toolkit/loader.js", "") - }, - globals: { - console: console - }, - modules: { - "toolkit/loader": loaderModule, - addon: { - id: "simulator", - version: "0.1", - uri: uri - } - } - }); - - let require_ = Require(loader, { id: "./addon" }); - assert.equal(typeof(loaderModule), - typeof(require_("toolkit/loader")), - "module returned is whatever was mapped to it"); -}; - -exports["test Cu.import in b2g style"] = (assert) => { - const {FakeCu} = require("./loader/b2g"); - const toolkitLoaderURI = require.resolve("toolkit/loader"); - const b2g = new FakeCu(); - - const exported = {}; - const loader = b2g.import(toolkitLoaderURI, exported); - - assert.equal(typeof(exported.Loader), - "function", - "loader is a function"); - assert.equal(typeof(exported.Loader.Loader), - "function", - "Loader.Loader is a funciton"); -}; - -exports['test lazy globals'] = function (assert) { - let uri = root + '/fixtures/loader/lazy/'; - let gotFoo = false; - let foo = {}; - let modules = { - get foo() { - gotFoo = true; - return foo; - } - }; - let loader = Loader({ paths: { '': uri }, modules: modules}); - assert.ok(!gotFoo, "foo hasn't been accessed during loader instanciation"); - let program = main(loader, 'main'); - assert.ok(!gotFoo, "foo hasn't been accessed during module loading"); - assert.equal(program.useFoo(), foo, "foo mock works"); - assert.ok(gotFoo, "foo has been accessed only when we first try to use it"); -}; - -exports['test user global'] = function(assert) { - // Test case for bug 827792 - let com = {}; - let loader = require('toolkit/loader'); - let loadOptions = require('@loader/options'); - let options = loader.override(loadOptions, - {globals: loader.override(loadOptions.globals, - {com: com, - console: console, - dump: dump})}); - let subloader = loader.Loader(options); - let userRequire = loader.Require(subloader, module); - let userModule = userRequire("./loader/user-global"); - - assert.equal(userModule.getCom(), com, - "user module returns expected `com` global"); -}; - -exports['test custom require caching'] = function(assert) { - const loader = Loader({ - paths: { '': root + "/" }, - requireHook: (id, require) => { - // Just load it normally - return require(id); - } - }); - const require = Require(loader, module); - - let data = require('fixtures/loader/json/mutation.json'); - assert.equal(data.value, 1, 'has initial value'); - data.value = 2; - let newdata = require('fixtures/loader/json/mutation.json'); - assert.equal( - newdata.value, - 2, - 'JSON objects returned should be cached and the same instance' - ); -}; - -exports['test caching when proxying a loader'] = function(assert) { - const parentRequire = require; - const loader = Loader({ - paths: { '': root + "/" }, - requireHook: (id, childRequire) => { - if(id === 'gimmejson') { - return childRequire('fixtures/loader/json/mutation.json') - } - // Load it with the original (global) require - return parentRequire(id); - } - }); - const childRequire = Require(loader, module); - - let data = childRequire('./fixtures/loader/json/mutation.json'); - assert.equal(data.value, 1, 'data has initial value'); - data.value = 2; - - let newdata = childRequire('./fixtures/loader/json/mutation.json'); - assert.equal(newdata.value, 2, 'data has changed'); - - let childData = childRequire('gimmejson'); - assert.equal(childData.value, 1, 'data from child loader has initial value'); - childData.value = 3; - let newChildData = childRequire('gimmejson'); - assert.equal(newChildData.value, 3, 'data from child loader has changed'); - - data = childRequire('./fixtures/loader/json/mutation.json'); - assert.equal(data.value, 2, 'data from parent loader has not changed'); - - // Set it back to the original value just in case (this instance - // will be shared across tests) - data.value = 1; -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-match-pattern.js b/addon-sdk/source/test/test-match-pattern.js deleted file mode 100644 index 651ad3148..000000000 --- a/addon-sdk/source/test/test-match-pattern.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/. */ -"use strict"; - -const { MatchPattern } = require("sdk/util/match-pattern"); - -exports.testMatchPatternTestTrue = function(assert) { - function ok(pattern, url) { - let mp = new MatchPattern(pattern); - assert.ok(mp.test(url), pattern + " should match " + url); - } - - ok("*", "http://example.com"); - ok("*", "https://example.com"); - ok("*", "ftp://example.com"); - - ok("*.example.com", "http://example.com"); - ok("*.example.com", "http://hamburger.example.com"); - ok("*.example.com", "http://hotdog.hamburger.example.com"); - - ok("http://example.com*", "http://example.com"); - ok("http://example.com*", "http://example.com/"); - ok("http://example.com/*", "http://example.com/"); - ok("http://example.com/*", "http://example.com/potato-salad"); - ok("http://example.com/pickles/*", "http://example.com/pickles/"); - ok("http://example.com/pickles/*", "http://example.com/pickles/lemonade"); - - ok("http://example.com", "http://example.com"); - ok("http://example.com/ice-cream", "http://example.com/ice-cream"); - - ok(/.*zilla.*/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); - ok(/.*A.*/i, "http://A.com"); - ok(/.*A.*/i, "http://a.com"); - ok(/https:.*zilla.*/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); - ok('*.sample.com', 'http://ex.sample.com/foo.html'); - ok('*.amp.le.com', 'http://ex.amp.le.com'); - - ok('data:*', 'data:text/html;charset=utf-8,'); -}; - -exports.testMatchPatternTestFalse = function(assert) { - function ok(pattern, url) { - let mp = new MatchPattern(pattern); - assert.ok(!mp.test(url), pattern + " should not match " + url); - } - - ok("*", null); - ok("*", ""); - ok("*", "bogus"); - ok("*", "chrome://browser/content/browser.xul"); - ok("*", "nttp://example.com"); - - ok("*.example.com", null); - ok("*.example.com", ""); - ok("*.example.com", "bogus"); - ok("*.example.com", "http://example.net"); - ok("*.example.com", "http://foo.com"); - ok("*.example.com", "http://example.com.foo"); - ok("*.example2.com", "http://example.com"); - - ok("http://example.com/*", null); - ok("http://example.com/*", ""); - ok("http://example.com/*", "bogus"); - ok("http://example.com/*", "http://example.com"); - ok("http://example.com/*", "http://foo.com/"); - - ok("http://example.com", null); - ok("http://example.com", ""); - ok("http://example.com", "bogus"); - ok("http://example.com", "http://example.com/"); - - ok(/zilla.*/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); - ok(/.*zilla/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); - ok(/.*Zilla.*/, "https://bugzilla.redhat.com/show_bug.cgi?id=655464"); // bug 655464 - ok(/https:.*zilla/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); - - // bug 856913 - ok('*.ign.com', 'http://www.design.com'); - ok('*.ign.com', 'http://design.com'); - ok('*.zilla.com', 'http://bugzilla.mozilla.com'); - ok('*.zilla.com', 'http://mo-zilla.com'); - ok('*.amp.le.com', 'http://amp-le.com'); - ok('*.amp.le.com', 'http://examp.le.com'); -}; - -exports.testMatchPatternErrors = function(assert) { - assert.throws( - () => new MatchPattern("*.google.com/*"), - /There can be at most one/, - "MatchPattern throws when supplied multiple '*'" - ); - - assert.throws( - () => new MatchPattern("google.com"), - /expected to be either an exact URL/, - "MatchPattern throws when the wildcard doesn't use '*' and doesn't " + - "look like a URL" - ); - - assert.throws( - () => new MatchPattern("http://google*.com"), - /expected to be the first or the last/, - "MatchPattern throws when a '*' is in the middle of the wildcard" - ); - - assert.throws( - () => new MatchPattern(/ /g), - /^A RegExp match pattern cannot be set to `global` \(i\.e\. \/\/g\)\.$/, - "MatchPattern throws on a RegExp set to `global` (i.e. //g)." - ); - - assert.throws( - () => new MatchPattern( / /m ), - /^A RegExp match pattern cannot be set to `multiline` \(i\.e\. \/\/m\)\.$/, - "MatchPattern throws on a RegExp set to `multiline` (i.e. //m)." - ); -}; - -exports.testMatchPatternInternals = function(assert) { - assert.equal( - new MatchPattern("http://google.com/test").exactURL, - "http://google.com/test" - ); - - assert.equal( - new MatchPattern("http://google.com/test/*").urlPrefix, - "http://google.com/test/" - ); - - assert.equal( - new MatchPattern("*.example.com").domain, - "example.com" - ); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-method.js b/addon-sdk/source/test/test-method.js deleted file mode 100644 index 0478593c1..000000000 --- a/addon-sdk/source/test/test-method.js +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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"; - -module.exports = require("method/test/common"); diff --git a/addon-sdk/source/test/test-module.js b/addon-sdk/source/test/test-module.js deleted file mode 100644 index 1f9979e4b..000000000 --- a/addon-sdk/source/test/test-module.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"; - -/** Disabled because of Bug 672199 -exports["test module exports are frozen"] = function(assert) { - assert.ok(Object.isFrozen(require("sdk/hotkeys")), - "module exports are frozen"); -}; - -exports["test redefine exported property"] = function(assert) { - let hotkeys = require("sdk/hotkeys"); - let { Hotkey } = hotkeys; - try { Object.defineProperty(hotkeys, 'Hotkey', { value: {} }); } catch(e) {} - assert.equal(hotkeys.Hotkey, Hotkey, "exports can't be redefined"); -}; -*/ - -exports["test can't delete exported property"] = function(assert) { - let hotkeys = require("sdk/hotkeys"); - let { Hotkey } = hotkeys; - - try { delete hotkeys.Hotkey; } catch(e) {} - assert.equal(hotkeys.Hotkey, Hotkey, "exports can't be deleted"); -}; - -exports["test can't override exported property"] = function(assert) { - let hotkeys = require("sdk/hotkeys"); - let { Hotkey } = hotkeys; - - try { hotkeys.Hotkey = Object } catch(e) {} - assert.equal(hotkeys.Hotkey, Hotkey, "exports can't be overriden"); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-modules.js b/addon-sdk/source/test/test-modules.js deleted file mode 100644 index ee9d3d9b5..000000000 --- a/addon-sdk/source/test/test-modules.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/. */ - -exports.testDefine = function(assert) { - let tiger = require('./modules/tiger'); - assert.equal(tiger.name, 'tiger', 'name proprety was exported properly'); - assert.equal(tiger.type, 'cat', 'property form other module exported'); -}; - -exports.testDefineInoresNonFactory = function(assert) { - let mod = require('./modules/async2'); - assert.equal(mod.name, 'async2', 'name proprety was exported properly'); - assert.ok(mod.traditional2Name !== 'traditional2', '1st is ignored'); -}; -/* Disable test that require AMD specific functionality: - -// define() that exports a function as the module value, -// specifying a module name. -exports.testDefExport = function(assert) { - var add = require('modules/add'); - assert.equal(add(1, 1), 2, 'Named define() exporting a function'); -}; - -// define() that exports function as a value, but is anonymous -exports.testAnonDefExport = function (assert) { - var subtract = require('modules/subtract'); - assert.equal(subtract(4, 2), 2, - 'Anonymous define() exporting a function'); -} - -// using require([], function () {}) to load modules. -exports.testSimpleRequire = function (assert) { - require(['modules/blue', 'modules/orange'], function (blue, orange) { - assert.equal(blue.name, 'blue', 'Simple require for blue'); - assert.equal(orange.name, 'orange', 'Simple require for orange'); - assert.equal(orange.parentType, 'color', - 'Simple require dependency check for orange'); - }); -} - -// using nested require([]) calls. -exports.testSimpleRequireNested = function (assert) { - require(['modules/blue', 'modules/orange', 'modules/green'], - function (blue, orange, green) { - - require(['modules/orange', 'modules/red'], function (orange, red) { - assert.equal(red.name, 'red', 'Simple require for red'); - assert.equal(red.parentType, 'color', - 'Simple require dependency check for red'); - assert.equal(blue.name, 'blue', 'Simple require for blue'); - assert.equal(orange.name, 'orange', 'Simple require for orange'); - assert.equal(orange.parentType, 'color', - 'Simple require dependency check for orange'); - assert.equal(green.name, 'green', 'Simple require for green'); - assert.equal(green.parentType, 'color', - 'Simple require dependency check for green'); - }); - - }); -} - -// requiring a traditional module, that uses async, that use traditional and -// async, with a circular reference -exports.testMixedCircular = function (assert) { - var t = require('modules/traditional1'); - assert.equal(t.name, 'traditional1', 'Testing name'); - assert.equal(t.traditional2Name, 'traditional2', - 'Testing dependent name'); - assert.equal(t.traditional1Name, 'traditional1', 'Testing circular name'); - assert.equal(t.async2Name, 'async2', 'Testing async2 name'); - assert.equal(t.async2Traditional2Name, 'traditional2', - 'Testing nested traditional2 name'); -} - -// Testing define()(function(require) {}) with some that use exports, -// some that use return. -exports.testAnonExportsReturn = function (assert) { - var lion = require('modules/lion'); - require(['modules/tiger', 'modules/cheetah'], function (tiger, cheetah) { - assert.equal('lion', lion, 'Check lion name'); - assert.equal('tiger', tiger.name, 'Check tiger name'); - assert.equal('cat', tiger.type, 'Check tiger type'); - assert.equal('cheetah', cheetah(), 'Check cheetah name'); - }); -} - -// circular dependency -exports.testCircular = function (assert) { - var pollux = require('modules/pollux'), - castor = require('modules/castor'); - - assert.equal(pollux.name, 'pollux', 'Pollux\'s name'); - assert.equal(pollux.getCastorName(), - 'castor', 'Castor\'s name from Pollux.'); - assert.equal(castor.name, 'castor', 'Castor\'s name'); - assert.equal(castor.getPolluxName(), 'pollux', - 'Pollux\'s name from Castor.'); -} - -// test a bad module that asks for exports but also does a define() return -exports.testBadExportAndReturn = function (assert) { - var passed = false; - try { - var bad = require('modules/badExportAndReturn'); - } catch(e) { - passed = /cannot use exports and also return/.test(e.toString()); - } - assert.equal(passed, true, 'Make sure exports and return fail'); -} - -// test a bad circular dependency, where an exported value is needed, but -// the return value happens too late, a module already asked for the exported -// value. -exports.testBadExportAndReturnCircular = function (assert) { - var passed = false; - try { - var bad = require('modules/badFirst'); - } catch(e) { - passed = /after another module has referenced its exported value/ - .test(e.toString()); - } - assert.equal(passed, true, 'Make sure return after an exported ' + - 'value is grabbed by another module fails.'); -} - -// only allow one define call per file. -exports.testOneDefine = function (assert) { - var passed = false; - try { - var dupe = require('modules/dupe'); - } catch(e) { - passed = /Only one call to define/.test(e.toString()); - } - assert.equal(passed, true, 'Only allow one define call per module'); -} - -// only allow one define call per file, testing a bad nested define call. -exports.testOneDefineNested = function (assert) { - var passed = false; - try { - var dupe = require('modules/dupeNested'); - } catch(e) { - passed = /Only one call to define/.test(e.toString()); - } - assert.equal(passed, true, 'Only allow one define call per module'); -} -*/ - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-mozilla-toolkit-versioning.js b/addon-sdk/source/test/test-mozilla-toolkit-versioning.js deleted file mode 100644 index 148919595..000000000 --- a/addon-sdk/source/test/test-mozilla-toolkit-versioning.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"; - -const {parse, increment} = require("mozilla-toolkit-versioning/index") - -const TestParse = assert => (version, min, max) => { - const actual = parse(version); - assert.equal(actual.min, min); - assert.equal(actual.max, max); -} - -const TestInc = assert => (version, expected) => { - assert.equal(increment(version), expected, - `increment: ${version} should be equal ${expected}`) -} - - - -exports['test parse(version) single value'] = assert => { - const testParse = TestParse(assert) - testParse('1.2.3', '1.2.3', '1.2.3'); - testParse('>=1.2.3', '1.2.3', undefined); - testParse('<=1.2.3', undefined, '1.2.3'); - testParse('>1.2.3', '1.2.3.1', undefined); - testParse('<1.2.3', undefined, '1.2.3.-1'); - testParse('*', undefined, undefined); -}; - -exports['test parse(version) range'] = assert => { - const testParse = TestParse(assert); - testParse('>=1.2.3 <=2.3.4', '1.2.3', '2.3.4'); - testParse('>1.2.3 <=2.3.4', '1.2.3.1', '2.3.4'); - testParse('>=1.2.3 <2.3.4', '1.2.3', '2.3.4.-1'); - testParse('>1.2.3 <2.3.4', '1.2.3.1', '2.3.4.-1'); - - testParse('<=2.3.4 >=1.2.3', '1.2.3', '2.3.4'); - testParse('<=2.3.4 >1.2.3', '1.2.3.1', '2.3.4'); - testParse('<2.3.4 >=1.2.3', '1.2.3', '2.3.4.-1'); - testParse('<2.3.4 >1.2.3', '1.2.3.1', '2.3.4.-1'); - - testParse('1.2.3pre1 - 2.3.4', '1.2.3pre1', '2.3.4'); -}; - -exports['test increment(version)'] = assert => { - const testInc = TestInc(assert); - - testInc('1.2.3', '1.2.3.1'); - testInc('1.2.3a', '1.2.3a1'); - testInc('1.2.3pre', '1.2.3pre1'); - testInc('1.2.3pre1', '1.2.3pre2'); - testInc('1.2', '1.2.1'); - testInc('1.2pre1a', '1.2pre1b'); - testInc('1.2pre1pre', '1.2pre1prf'); -}; - - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-mpl2-license-header.js b/addon-sdk/source/test/test-mpl2-license-header.js deleted file mode 100644 index 22a2cf0ea..000000000 --- a/addon-sdk/source/test/test-mpl2-license-header.js +++ /dev/null @@ -1,105 +0,0 @@ -// Note: This line is here intentionally, to break MPL2_LICENSE_TEST -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cc, Ci, Cu } = require("chrome"); -const options = require('@loader/options'); -const { id } = require("sdk/self"); -const { getAddonByID } = require("sdk/addon/manager"); -const { mapcat, map, filter, fromEnumerator } = require("sdk/util/sequence"); -const { readURISync } = require('sdk/net/url'); -const { Request } = require('sdk/request'); -const { defer } = require("sdk/core/promise"); - -const ios = Cc['@mozilla.org/network/io-service;1']. - getService(Ci.nsIIOService); - -const MIT_LICENSE_HEADER = []; - -const MPL2_LICENSE_TEST = new RegExp([ - "^\\/\\* This Source Code Form is subject to the terms of the Mozilla Public", - " \\* License, v\\. 2\\.0\\. If a copy of the MPL was not distributed with this", - " \\* file, You can obtain one at http:\\/\\/mozilla\\.org\\/MPL\\/2\\.0\\/\\. \\*\\/" -].join("\n")); - -// Note: Using regular expressions because the paths a different for cfx vs jpm -const IGNORES = [ - /lib[\/\\](diffpatcher|method)[\/\\].+$/, // MIT - /lib[\/\\]sdk[\/\\]fs[\/\\]path\.js$/, // MIT - /lib[\/\\]sdk[\/\\]system[\/\\]child_process[\/\\].*/, - /tests?[\/\\]buffers[\/\\].+$/, // MIT - /tests?[\/\\]path[\/\\]test-path\.js$/, - /tests?[\/\\]querystring[\/\\]test-querystring\.js$/, -]; - -const ignoreFile = file => !!IGNORES.find(regex => regex.test(file)); - -const baseURI = "resource://test-sdk-addon/"; - -const uri = (path="") => baseURI + path; - -const toFile = x => x.QueryInterface(Ci.nsIFile); -const isTestFile = ({ path, leafName }) => { - return !ignoreFile(path) && /\.jsm?$/.test(leafName) -}; -const getFileURI = x => ios.newFileURI(x).spec; - -const getDirectoryEntries = file => map(toFile, fromEnumerator(_ => file.directoryEntries)); - -const isDirectory = x => x.isDirectory(); -const getEntries = directory => mapcat(entry => { - if (isDirectory(entry)) { - return getEntries(entry); - } - else if (isTestFile(entry)) { - return [ entry ]; - } - return []; -}, filter(() => true, getDirectoryEntries(directory))); - -function readURL(url) { - let { promise, resolve } = defer(); - - Request({ - url: url, - overrideMimeType: "text/plain", - onComplete: (response) => resolve(response.text) - }).get(); - - return promise; -} - -exports["test MPL2 license header"] = function*(assert) { - let addon = yield getAddonByID(id); - let xpiURI = addon.getResourceURI(); - let rootURL = xpiURI.spec; - assert.ok(rootURL, rootURL); - let files = [...getEntries(xpiURI.QueryInterface(Ci.nsIFileURL).file)]; - - assert.ok(files.length > 1, files.length + " files found."); - let failures = []; - let success = 0; - - for (let i = 0, len = files.length; i < len; i++) { - let file = files[i]; - assert.ok(file.path, "Trying " + file.path); - - const URI = ios.newFileURI(file); - - let leafName = URI.spec.replace(rootURL, ""); - - let contents = yield readURL(URI.spec); - if (!MPL2_LICENSE_TEST.test(contents)) { - failures.push(leafName); - } - } - - assert.equal(1, failures.length, "we expect one failure"); - assert.ok(/test-mpl2-license-header\.js$/.test(failures[0]), "the only failure is this file"); - failures.shift(); - assert.equal("", failures.join(",\n"), failures.length + " files found missing the required mpl 2 header"); -} - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-namespace.js b/addon-sdk/source/test/test-namespace.js deleted file mode 100644 index 636682e9e..000000000 --- a/addon-sdk/source/test/test-namespace.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/. */ -"use strict"; - -const { ns } = require("sdk/core/namespace"); -const { Cc, Ci, Cu } = require("chrome"); -const { setTimeout } = require("sdk/timers") - -exports["test post GC references"] = function (assert, done) { - var target = {}, local = ns() - local(target).there = true - - assert.equal(local(target).there, true, "namespaced preserved"); - - Cu.schedulePreciseGC(function() { - assert.equal(local(target).there, true, "namespace is preserved post GC"); - done(); - }); -}; - -exports["test namsepace basics"] = function(assert) { - var privates = ns(); - var object = { foo: function foo() { return "hello foo"; } }; - - assert.notEqual(privates(object), object, - "namespaced object is not the same"); - assert.ok(!('foo' in privates(object)), - "public properties are not in the namespace"); - - assert.equal(privates(object), privates(object), - "same namespaced object is returned on each call"); -}; - -exports["test namespace overlays"] = function(assert) { - var _ = ns(); - var object = { foo: 'foo' }; - - _(object).foo = 'bar'; - - assert.equal(_(object).foo, "bar", - "namespaced property `foo` changed value"); - - assert.equal(object.foo, "foo", - "public property `foo` has original value"); - - object.foo = "baz"; - assert.equal(_(object).foo, "bar", - "property changes do not affect namespaced properties"); - - object.bar = "foo"; - assert.ok(!("bar" in _(object)), - "new public properties are not reflected in namespace"); -}; - -exports["test shared namespaces"] = function(assert) { - var _ = ns(); - - var f1 = { hello: 1 }; - var f2 = { foo: 'foo', hello: 2 }; - _(f1).foo = _(f2).foo = 'bar'; - - assert.equal(_(f1).hello, _(f2).hello, "namespace can be shared"); - assert.notEqual(f1.hello, _(f1).hello, "shared namespace can overlay"); - assert.notEqual(f2.hello, _(f2).hello, "target is not affected"); - - _(f1).hello = 3; - - assert.notEqual(_(f1).hello, _(f2).hello, - "namespaced property can be overided"); - assert.equal(_(f2).hello, _({}).hello, "namespace does not change"); -}; - -exports["test multi namespace"] = function(assert) { - var n1 = ns(); - var n2 = ns(); - var object = { baz: 1 }; - n1(object).foo = 1; - n2(object).foo = 2; - n1(object).bar = n2(object).bar = 3; - - assert.notEqual(n1(object).foo, n2(object).foo, - "object can have multiple namespaces"); - assert.equal(n1(object).bar, n2(object).bar, - "object can have matching props in diff namespaces"); -}; - -exports["test ns alias"] = function(assert) { - assert.strictEqual(ns, require('sdk/core/namespace').Namespace, - "ns is an alias of Namespace"); -}; - -exports["test ns inheritance"] = function(assert) { - let _ = ns(); - - let prototype = { level: 1 }; - let object = Object.create(prototype); - let delegee = Object.create(object); - - _(prototype).foo = {}; - - assert.ok(!Object.prototype.hasOwnProperty.call(_(delegee), "foo"), - "namespaced property is not copied to descendants"); - assert.equal(_(delegee).foo, _(prototype).foo, - "namespaced properties are inherited by descendants"); - - _(object).foo = {}; - assert.notEqual(_(object).foo, _(prototype).foo, - "namespaced properties may be shadowed"); - assert.equal(_(object).foo, _(delegee).foo, - "shadwed properties are inherited by descendants"); - - _(object).bar = {}; - assert.ok(!("bar" in _(prototype)), - "descendants properties are not copied to ancestors"); - assert.ok(_(object).bar, _(delegee).bar, - "descendants properties are inherited"); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-native-loader.js b/addon-sdk/source/test/test-native-loader.js deleted file mode 100644 index cc7185522..000000000 --- a/addon-sdk/source/test/test-native-loader.js +++ /dev/null @@ -1,423 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { - Loader, main, unload, parseStack, resolve, nodeResolve -} = require('toolkit/loader'); -var { readURI } = require('sdk/net/url'); -var { all } = require('sdk/core/promise'); -var { before, after } = require('sdk/test/utils'); -var testOptions = require('@test/options'); - -var root = module.uri.substr(0, module.uri.lastIndexOf('/')) -// The following adds Debugger constructor to the global namespace. -const { Cc, Ci, Cu } = require('chrome'); -const { addDebuggerToGlobal } = Cu.import('resource://gre/modules/jsdebugger.jsm', {}); -addDebuggerToGlobal(this); - -const { NetUtil } = Cu.import('resource://gre/modules/NetUtil.jsm', {}); - -const resProto = Cc["@mozilla.org/network/protocol;1?name=resource"] - .getService(Ci.nsIResProtocolHandler); - -const fileRoot = resProto.resolveURI(NetUtil.newURI(root)); - -let variants = [ - { - description: "unpacked resource:", - getRootURI(fixture) { - return `${root}/fixtures/${fixture}/`; - }, - }, - { - description: "unpacked file:", - getRootURI(fixture) { - return `${fileRoot}/fixtures/${fixture}/`; - }, - }, - { - description: "packed resource:", - getRootURI(fixture) { - return `resource://${fixture}/`; - }, - }, - { - description: "packed jar:", - getRootURI(fixture) { - return `jar:${fileRoot}/fixtures/${fixture}.xpi!/`; - }, - }, -]; - -let fixtures = [ - 'native-addon-test', - 'native-overrides-test', -]; - -for (let variant of variants) { - exports[`test nodeResolve (${variant.description})`] = function (assert) { - let rootURI = variant.getRootURI('native-addon-test'); - let manifest = {}; - manifest.dependencies = {}; - - // Handles extensions - resolveTest('../package.json', './dir/c.js', './package.json'); - resolveTest('../dir/b.js', './dir/c.js', './dir/b.js'); - - resolveTest('./dir/b', './index.js', './dir/b.js'); - resolveTest('../index', './dir/b.js', './index.js'); - resolveTest('../', './dir/b.js', './index.js'); - resolveTest('./dir/a', './index.js', './dir/a.js', 'Precedence dir/a.js over dir/a/'); - resolveTest('../utils', './dir/a.js', './utils/index.js', 'Requiring a directory defaults to dir/index.js'); - resolveTest('../newmodule', './dir/c.js', './newmodule/lib/file.js', 'Uses package.json main in dir to load appropriate "main"'); - resolveTest('test-math', './utils/index.js', './node_modules/test-math/index.js', - 'Dependencies default to their index.js'); - resolveTest('test-custom-main', './utils/index.js', './node_modules/test-custom-main/lib/custom-entry.js', - 'Dependencies use "main" entry'); - resolveTest('test-math/lib/sqrt', './utils/index.js', './node_modules/test-math/lib/sqrt.js', - 'Dependencies\' files can be consumed via "/"'); - - resolveTest('sdk/tabs/utils', './index.js', undefined, - 'correctly ignores SDK references in paths'); - resolveTest('fs', './index.js', undefined, - 'correctly ignores built in node modules in paths'); - - resolveTest('test-add', './node_modules/test-math/index.js', - './node_modules/test-math/node_modules/test-add/index.js', - 'Dependencies\' dependencies can be found'); - - resolveTest('resource://gre/modules/commonjs/sdk/tabs.js', './index.js', undefined, - 'correctly ignores absolute URIs.'); - - resolveTest('../tabs', 'resource://gre/modules/commonjs/sdk/addon/bootstrap.js', undefined, - 'correctly ignores attempts to resolve from a module at an absolute URI.'); - - resolveTest('sdk/tabs', 'resource://gre/modules/commonjs/sdk/addon/bootstrap.js', undefined, - 'correctly ignores attempts to resolve from a module at an absolute URI.'); - - function resolveTest (id, requirer, expected, msg) { - let result = nodeResolve(id, requirer, { manifest: manifest, rootURI: rootURI }); - assert.equal(result, expected, 'nodeResolve ' + id + ' from ' + requirer + ' ' +msg); - } - } - - /* - // TODO not working in current env - exports[`test bundle (${variant.description`] = function (assert, done) { - loadAddon('/native-addons/native-addon-test/') - }; - */ - - exports[`test native Loader with mappings (${variant.description})`] = function (assert, done) { - all([ - getJSON('/fixtures/native-addon-test/expectedmap.json'), - getJSON('/fixtures/native-addon-test/package.json') - ]).then(([expectedMap, manifest]) => { - - // Override dummy module and point it to `test-math` to see if the - // require is pulling from the mapping - expectedMap['./index.js']['./dir/dummy'] = './dir/a.js'; - - let rootURI = variant.getRootURI('native-addon-test'); - let loader = Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - requireMap: expectedMap, - isNative: true - }); - - let program = main(loader); - assert.equal(program.dummyModule, 'dir/a', - 'The lookup uses the information given in the mapping'); - - testLoader(program, assert); - unload(loader); - done(); - }).then(null, (reason) => console.error(reason)); - }; - - exports[`test native Loader overrides (${variant.description})`] = function*(assert) { - const expectedKeys = Object.keys(require("sdk/io/fs")).join(", "); - const manifest = yield getJSON('/fixtures/native-overrides-test/package.json'); - const rootURI = variant.getRootURI('native-overrides-test'); - - let loader = Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - metadata: manifest, - isNative: true - }); - - let program = main(loader); - let fooKeys = Object.keys(program.foo).join(", "); - let barKeys = Object.keys(program.foo).join(", "); - let fsKeys = Object.keys(program.fs).join(", "); - let overloadKeys = Object.keys(program.overload.fs).join(", "); - let overloadLibKeys = Object.keys(program.overloadLib.fs).join(", "); - - assert.equal(fooKeys, expectedKeys, "foo exports sdk/io/fs"); - assert.equal(barKeys, expectedKeys, "bar exports sdk/io/fs"); - assert.equal(fsKeys, expectedKeys, "sdk/io/fs exports sdk/io/fs"); - assert.equal(overloadKeys, expectedKeys, "overload exports foo which exports sdk/io/fs"); - assert.equal(overloadLibKeys, expectedKeys, "overload/lib/foo exports foo/lib/foo"); - assert.equal(program.internal, "test", "internal exports ./lib/internal"); - assert.equal(program.extra, true, "fs-extra was exported properly"); - - assert.equal(program.Tabs, "no tabs exist", "sdk/tabs exports ./lib/tabs from the add-on"); - assert.equal(program.CoolTabs, "no tabs exist", "sdk/tabs exports ./lib/tabs from the node_modules"); - assert.equal(program.CoolTabsLib, "a cool tabs implementation", "./lib/tabs true relative path from the node_modules"); - - assert.equal(program.ignore, "do not ignore this export", "../ignore override was ignored."); - - unload(loader); - }; - - exports[`test invalid native Loader overrides cause no errors (${variant.description})`] = function*(assert) { - const manifest = yield getJSON('/fixtures/native-overrides-test/package.json'); - const rootURI = variant.getRootURI('native-overrides-test'); - const EXPECTED = JSON.stringify({}); - - let makeLoader = (rootURI, manifest) => Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - metadata: manifest, - isNative: true - }); - - manifest.jetpack.overrides = "string"; - let loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to a string caused no errors making the loader"); - unload(loader); - - manifest.jetpack.overrides = true; - loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to a boolean caused no errors making the loader"); - unload(loader); - - manifest.jetpack.overrides = 5; - loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to a number caused no errors making the loader"); - unload(loader); - - manifest.jetpack.overrides = null; - loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to null caused no errors making the loader"); - unload(loader); - }; - - exports[`test invalid native Loader jetpack key cause no errors (${variant.description})`] = function*(assert) { - const manifest = yield getJSON('/fixtures/native-overrides-test/package.json'); - const rootURI = variant.getRootURI('native-overrides-test'); - const EXPECTED = JSON.stringify({}); - - let makeLoader = (rootURI, manifest) => Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - metadata: manifest, - isNative: true - }); - - manifest.jetpack = "string"; - let loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to a string caused no errors making the loader"); - unload(loader); - - manifest.jetpack = true; - loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to a boolean caused no errors making the loader"); - unload(loader); - - manifest.jetpack = 5; - loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to a number caused no errors making the loader"); - unload(loader); - - manifest.jetpack = null; - loader = makeLoader(rootURI, manifest); - assert.equal(JSON.stringify(loader.manifest.jetpack.overrides), EXPECTED, - "setting jetpack.overrides to null caused no errors making the loader"); - unload(loader); - }; - - exports[`test native Loader without mappings (${variant.description})`] = function (assert, done) { - getJSON('/fixtures/native-addon-test/package.json').then(manifest => { - let rootURI = variant.getRootURI('native-addon-test'); - let loader = Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - isNative: true - }); - - let program = main(loader); - testLoader(program, assert); - unload(loader); - done(); - }).then(null, (reason) => console.error(reason)); - }; - - exports[`test require#resolve with relative, dependencies (${variant.description})`] = function(assert, done) { - getJSON('/fixtures/native-addon-test/package.json').then(manifest => { - let rootURI = variant.getRootURI('native-addon-test'); - let loader = Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - isNative: true - }); - - let program = main(loader); - let fixtureRoot = program.require.resolve("./").replace(/index\.js$/, ""); - - assert.equal(variant.getRootURI("native-addon-test"), fixtureRoot, "correct resolution root"); - assert.equal(program.require.resolve("test-math"), fixtureRoot + "node_modules/test-math/index.js", "works with node_modules"); - assert.equal(program.require.resolve("./newmodule"), fixtureRoot + "newmodule/lib/file.js", "works with directory mains"); - assert.equal(program.require.resolve("./dir/a"), fixtureRoot + "dir/a.js", "works with normal relative module lookups"); - assert.equal(program.require.resolve("modules/Promise.jsm"), "resource://gre/modules/Promise.jsm", "works with path lookups"); - - // TODO bug 1050422, handle loading non JS/JSM file paths - // assert.equal(program.require.resolve("test-assets/styles.css"), fixtureRoot + "node_modules/test-assets/styles.css", - // "works with different file extension lookups in dependencies"); - - unload(loader); - done(); - }).then(null, (reason) => console.error(reason)); - }; -} - -before(exports, () => { - for (let fixture of fixtures) { - let url = `jar:${root}/fixtures/${fixture}.xpi!/`; - - resProto.setSubstitution(fixture, NetUtil.newURI(url)); - } -}); - -after(exports, () => { - for (let fixture of fixtures) - resProto.setSubstitution(fixture, null); -}); - -exports['test JSM loading'] = function (assert, done) { - getJSON('/fixtures/jsm-package/package.json').then(manifest => { - let rootURI = root + '/fixtures/jsm-package/'; - let loader = Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - isNative: true - }); - - let program = main(loader); - assert.ok(program.localJSMCached, 'local relative JSMs are cached'); - assert.ok(program.isCachedJSAbsolute , 'absolute resource:// js are cached'); - assert.ok(program.isCachedPath, 'JSMs resolved in paths are cached'); - assert.ok(program.isCachedAbsolute, 'absolute resource:// JSMs are cached'); - - assert.ok(program.localJSM, 'able to load local relative JSMs'); - all([ - program.isLoadedPath(10), - program.isLoadedAbsolute(20), - program.isLoadedJSAbsolute(30) - ]).then(([path, absolute, jsabsolute]) => { - assert.equal(path, 10, 'JSM files resolved from path work'); - assert.equal(absolute, 20, 'JSM files resolved from full resource:// work'); - assert.equal(jsabsolute, 30, 'JS files resolved from full resource:// work'); - }).then(done, console.error); - - }).then(null, console.error); -}; - -function testLoader (program, assert) { - // Test 'main' entries - // no relative custom main `lib/index.js` - assert.equal(program.customMainModule, 'custom entry file', - 'a node_module dependency correctly uses its `main` entry in manifest'); - // relative custom main `./lib/index.js` - assert.equal(program.customMainModuleRelative, 'custom entry file relative', - 'a node_module dependency correctly uses its `main` entry in manifest with relative ./'); - // implicit './index.js' - assert.equal(program.defaultMain, 'default main', - 'a node_module dependency correctly defautls to index.js for main'); - - // Test directory exports - assert.equal(program.directoryDefaults, 'utils', - '`require`ing a directory defaults to dir/index.js'); - assert.equal(program.directoryMain, 'main from new module', - '`require`ing a directory correctly loads the `main` entry and not index.js'); - assert.equal(program.resolvesJSoverDir, 'dir/a', - '`require`ing "a" resolves "a.js" over "a/index.js"'); - - // Test dependency's dependencies - assert.ok(program.math.add, - 'correctly defaults to index.js of a module'); - assert.equal(program.math.add(10, 5), 15, - 'node dependencies correctly include their own dependencies'); - assert.equal(program.math.subtract(10, 5), 5, - 'node dependencies correctly include their own dependencies'); - assert.equal(program.mathInRelative.subtract(10, 5), 5, - 'relative modules can also include node dependencies'); - - // Test SDK natives - assert.ok(program.promise.defer, 'main entry can include SDK modules with no deps'); - assert.ok(program.promise.resolve, 'main entry can include SDK modules with no deps'); - assert.ok(program.eventCore.on, 'main entry can include SDK modules that have dependencies'); - assert.ok(program.eventCore.off, 'main entry can include SDK modules that have dependencies'); - - // Test JSMs - assert.ok(program.promisejsm.defer, 'can require JSM files in path'); - assert.equal(program.localJSM.test, 'this is a jsm', - 'can require relative JSM files'); - - // Other tests - assert.equal(program.areModulesCached, true, - 'modules are correctly cached'); - assert.equal(program.testJSON.dependencies['test-math'], '*', - 'correctly requires JSON files'); -} - -function getJSON (uri) { - return readURI(root + uri).then(manifest => JSON.parse(manifest)); -} - -function makePaths (uri) { - // Uses development SDK modules if overloaded in loader - let sdkPaths = testOptions.paths ? testOptions.paths[''] : 'resource://gre/modules/commonjs/'; - return { - './': uri, - 'sdk/': sdkPaths + 'sdk/', - 'toolkit/': sdkPaths + 'toolkit/', - 'modules/': 'resource://gre/modules/' - }; -} - -function loadAddon (uri, map) { - let rootURI = root + uri; - getJSON(uri + '/package.json').then(manifest => { - let loader = Loader({ - paths: makePaths(rootURI), - rootURI: rootURI, - manifest: manifest, - isNative: true, - modules: { - '@test/options': testOptions - } - }); - let program = main(loader); - }).then(null, console.error); -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-native-options.js b/addon-sdk/source/test/test-native-options.js deleted file mode 100644 index 84212757a..000000000 --- a/addon-sdk/source/test/test-native-options.js +++ /dev/null @@ -1,183 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { setDefaults, injectOptions: inject, validate } = require('sdk/preferences/native-options'); -const { activeBrowserWindow: { document } } = require("sdk/deprecated/window-utils"); -const { preferencesBranch, id } = require('sdk/self'); -const { get } = require('sdk/preferences/service'); -const { setTimeout } = require('sdk/timers'); -const simple = require('sdk/simple-prefs'); -const fixtures = require('./fixtures'); -const { Cc, Ci } = require('chrome'); - -const prefsrv = Cc['@mozilla.org/preferences-service;1']. - getService(Ci.nsIPrefService); - -function injectOptions(preferences, preferencesBranch, document, parent) { - inject({ - id: id, - preferences: preferences, - preferencesBranch: preferencesBranch, - document: document, - parent: parent - }); -} - -exports.testValidate = function(assert) { - let { preferences } = packageJSON('simple-prefs'); - - let block = () => validate(preferences); - - delete preferences[3].options[0].value; - assert.throws(block, /option requires both a value/, "option missing value error"); - - delete preferences[2].options; - assert.throws(block, /'test3' pref requires options/, "menulist missing options error"); - - preferences[1].type = 'control'; - assert.throws(block, /'test2' control requires a label/, "control missing label error"); - - preferences[1].type = 'nonvalid'; - assert.throws(block, /'test2' pref must be of valid type/, "invalid pref type error"); - - delete preferences[0].title; - assert.throws(block, /'test' pref requires a title/, "pref missing title error"); -} - -exports.testNoPrefs = function(assert, done) { - let { preferences } = packageJSON('no-prefs'); - - let parent = document.createDocumentFragment(); - injectOptions(preferences || [], preferencesBranch, document, parent); - assert.equal(parent.children.length, 0, "No setting elements injected"); - - // must test with events because we can't reset default prefs - function onPrefChange(name) { - assert.fail("No preferences should be defined"); - } - - simple.on('', onPrefChange); - setDefaults(preferences || [], preferencesBranch); - setTimeout(function() { - assert.pass("No preferences were defined"); - simple.off('', onPrefChange); - done(); - }, 100); -} - -exports.testCurlyID = function(assert) { - let { preferences, id } = packageJSON('curly-id'); - let branch = prefsrv.getDefaultBranch('extensions.' + id); - - let parent = document.createDocumentFragment(); - injectOptions(preferences, id, document, parent); - assert.equal(parent.children.length, 1, "One setting elements injected"); - assert.equal(parent.firstElementChild.attributes.pref.value, - "extensions.{34a1eae1-c20a-464f-9b0e-000000000000}.test13", - "Setting pref attribute is set properly"); - - setDefaults(preferences, id); - assert.equal(get('extensions.{34a1eae1-c20a-464f-9b0e-000000000000}.test13'), - 26, "test13 is 26"); - - branch.deleteBranch(''); - assert.equal(get('extensions.{34a1eae1-c20a-464f-9b0e-000000000000}.test13'), - undefined, "test13 is undefined"); -} - -exports.testPreferencesBranch = function(assert) { - let { preferences, 'preferences-branch': prefsBranch } = packageJSON('preferences-branch'); - let branch = prefsrv.getDefaultBranch('extensions.' + prefsBranch); - - let parent = document.createDocumentFragment(); - injectOptions(preferences, prefsBranch, document, parent); - assert.equal(parent.children.length, 1, "One setting elements injected"); - assert.equal(parent.firstElementChild.attributes.pref.value, - "extensions.human-readable.test42", - "Setting pref attribute is set properly"); - - setDefaults(preferences, prefsBranch); - assert.equal(get('extensions.human-readable.test42'), true, "test42 is true"); - - branch.deleteBranch(''); - assert.equal(get('extensions.human-readable.test42'), undefined, "test42 is undefined"); -} - -exports.testSimplePrefs = function(assert) { - let { preferences } = packageJSON('simple-prefs'); - let branch = prefsrv.getDefaultBranch('extensions.' + preferencesBranch); - - function assertPref(setting, name, type, title, description = null) { - assert.equal(setting.getAttribute('data-jetpack-id'), id, - "setting 'data-jetpack-id' attribute correct"); - assert.equal(setting.getAttribute('pref'), 'extensions.' + id + '.' + name, - "setting 'pref' attribute correct"); - assert.equal(setting.getAttribute('pref-name'), name, - "setting 'pref-name' attribute correct"); - assert.equal(setting.getAttribute('type'), type, - "setting 'type' attribute correct"); - assert.equal(setting.getAttribute('title'), title, - "setting 'title' attribute correct"); - if (description) { - assert.equal(setting.getAttribute('desc'), description, - "setting 'desc' attribute correct"); - } - else { - assert.ok(!setting.hasAttribute('desc'), - "setting 'desc' attribute is not present"); - } - } - - function assertOption(option, value, label) { - assert.equal(option.getAttribute('value'), value, "value attribute correct"); - assert.equal(option.getAttribute('label'), label, "label attribute correct"); - } - - let parent = document.createDocumentFragment(); - injectOptions(preferences, preferencesBranch, document, parent); - assert.equal(parent.children.length, 8, "Eight setting elements injected"); - - assertPref(parent.children[0], 'test', 'bool', 't\u00EBst', 'descr\u00EFpti\u00F6n'); - assertPref(parent.children[1], 'test2', 'string', 't\u00EBst'); - assertPref(parent.children[2], 'test3', 'menulist', '">menuitem'); - let radios = parent.children[3].querySelectorAll('radiogroup>radio'); - - assertOption(menuItems[0], '0', 'label1'); - assertOption(menuItems[1], '1', 'label2'); - assertOption(radios[0], 'red', 'rouge'); - assertOption(radios[1], 'blue', 'bleu'); - - setDefaults(preferences, preferencesBranch); - assert.strictEqual(simple.prefs.test, false, "test is false"); - assert.strictEqual(simple.prefs.test2, "\u00FCnic\u00F8d\u00E9", "test2 is unicode"); - assert.strictEqual(simple.prefs.test3, "1", "test3 is '1'"); - assert.strictEqual(simple.prefs.test4, "red", "test4 is 'red'"); - - // Only delete the test preferences to avoid unsetting any test harness - // preferences. - for (let setting of parent.children) { - let name = setting.getAttribute('pref-name'); - branch.deleteBranch("." + name); - } - - assert.strictEqual(simple.prefs.test, undefined, "test is undefined"); - assert.strictEqual(simple.prefs.test2, undefined, "test2 is undefined"); - assert.strictEqual(simple.prefs.test3, undefined, "test3 is undefined"); - assert.strictEqual(simple.prefs.test4, undefined, "test4 is undefined"); -} - -function packageJSON(dir) { - return require(fixtures.url('preferences/' + dir + '/package.json')); -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-net-url.js b/addon-sdk/source/test/test-net-url.js deleted file mode 100644 index 9e463b798..000000000 --- a/addon-sdk/source/test/test-net-url.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/. */ -"use strict"; - -const { readURI, readURISync } = require("sdk/net/url"); -const data = require("./fixtures"); - -const utf8text = "Hello, ゼロ!"; -const latin1text = "Hello, ゼロ!"; - -const dataURIutf8 = "data:text/plain;charset=utf-8," + encodeURIComponent(utf8text); -const dataURIlatin1 = "data:text/plain;charset=ISO-8859-1," + escape(latin1text); -const chromeURI = "chrome://global-platform/locale/accessible.properties"; - -exports["test async readURI"] = function(assert, done) { - let content = ""; - - readURI(data.url("test-net-url.txt")).then(function(data) { - content = data; - assert.equal(content, utf8text, "The URL content is loaded properly"); - done(); - }, function() { - assert.fail("should not reject"); - done(); - }) - - assert.equal(content, "", "The URL content is not load yet"); -} - -exports["test readURISync"] = function(assert) { - let content = readURISync(data.url("test-net-url.txt")); - - assert.equal(content, utf8text, "The URL content is loaded properly"); -} - -exports["test async readURI with ISO-8859-1 charset"] = function(assert, done) { - let content = ""; - - readURI(data.url("test-net-url.txt"), { charset : "ISO-8859-1"}).then(function(data) { - content = data; - assert.equal(content, latin1text, "The URL content is loaded properly"); - done(); - }, function() { - assert.fail("should not reject"); - done(); - }) - - assert.equal(content, "", "The URL content is not load yet"); -} - -exports["test readURISync with ISO-8859-1 charset"] = function(assert) { - let content = readURISync(data.url("test-net-url.txt"), "ISO-8859-1"); - - assert.equal(content, latin1text, "The URL content is loaded properly"); -} - -exports["test async readURI with not existing file"] = function(assert, done) { - readURI(data.url("test-net-url-fake.txt")).then(function(data) { - assert.fail("should not resolve"); - done(); - }, function(reason) { - assert.ok(reason.indexOf("Failed to read:") === 0); - done(); - }) -} - -exports["test readURISync with not existing file"] = function(assert) { - assert.throws(function() { - readURISync(data.url("test-net-url-fake.txt")); - }, /NS_ERROR_FILE_NOT_FOUND/); -} - -exports["test async readURI with data URI"] = function(assert, done) { - let content = ""; - - readURI(dataURIutf8).then(function(data) { - content = data; - assert.equal(content, utf8text, "The URL content is loaded properly"); - done(); - }, function() { - assert.fail("should not reject"); - done(); - }) - - assert.equal(content, "", "The URL content is not load yet"); -} - -exports["test readURISync with data URI"] = function(assert) { - let content = readURISync(dataURIutf8); - - assert.equal(content, utf8text, "The URL content is loaded properly"); -} - -exports["test async readURI with data URI and ISO-8859-1 charset"] = function(assert, done) { - let content = ""; - - readURI(dataURIlatin1, { charset : "ISO-8859-1"}).then(function(data) { - content = unescape(data); - assert.equal(content, latin1text, "The URL content is loaded properly"); - done(); - }, function() { - assert.fail("should not reject"); - done(); - }) - - assert.equal(content, "", "The URL content is not load yet"); -} - -exports["test readURISync with data URI and ISO-8859-1 charset"] = function(assert) { - let content = unescape(readURISync(dataURIlatin1, "ISO-8859-1")); - - assert.equal(content, latin1text, "The URL content is loaded properly"); -} - -exports["test readURISync with chrome URI"] = function(assert) { - let content = readURISync(chromeURI); - - assert.ok(content, "The URL content is loaded properly"); -} - -exports["test async readURI with chrome URI"] = function(assert, done) { - let content = ""; - - readURI(chromeURI).then(function(data) { - content = data; - assert.equal(content, readURISync(chromeURI), "The URL content is loaded properly"); - done(); - }, function() { - assert.fail("should not reject"); - done(); - }) - - assert.equal(content, "", "The URL content is not load yet"); -} - -require("sdk/test").run(exports) diff --git a/addon-sdk/source/test/test-node-os.js b/addon-sdk/source/test/test-node-os.js deleted file mode 100644 index e8316d7d9..000000000 --- a/addon-sdk/source/test/test-node-os.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 os = require("node/os"); -var system = require("sdk/system"); - -exports["test os"] = function (assert) { - assert.equal(os.tmpdir(), system.pathFor("TmpD"), "os.tmpdir() matches temp dir"); - assert.ok(os.endianness() === "BE" || os.endianness() === "LE", "os.endianness is BE or LE"); - - assert.ok(os.arch().length > 0, "os.arch() returns a value"); - assert.equal(typeof os.arch(), "string", "os.arch() returns a string"); - assert.ok(os.type().length > 0, "os.type() returns a value"); - assert.equal(typeof os.type(), "string", "os.type() returns a string"); - assert.ok(os.platform().length > 0, "os.platform() returns a value"); - assert.equal(typeof os.platform(), "string", "os.platform() returns a string"); - - assert.ok(os.release().length > 0, "os.release() returns a value"); - assert.equal(typeof os.release(), "string", "os.release() returns a string"); - assert.ok(os.hostname().length > 0, "os.hostname() returns a value"); - assert.equal(typeof os.hostname(), "string", "os.hostname() returns a string"); - assert.ok(os.EOL === "\n" || os.EOL === "\r\n", "os.EOL returns a correct EOL char"); - - assert.deepEqual(os.loadavg(), [0, 0, 0], "os.loadavg() returns an array of 0s"); - - ["uptime", "totalmem", "freemem", "cpus"].forEach(method => { - assert.throws(() => os[method](), "os." + method + " throws"); - }); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-notifications.js b/addon-sdk/source/test/test-notifications.js deleted file mode 100644 index 9a4d6cea0..000000000 --- a/addon-sdk/source/test/test-notifications.js +++ /dev/null @@ -1,94 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Loader } = require('sdk/test/loader'); - -exports["test onClick"] = function(assert) { - let [loader, mockAlertServ] = makeLoader(module); - let notifs = loader.require("sdk/notifications"); - let data = "test data"; - let opts = { - onClick: function (clickedData) { - assert.equal(this, notifs, "|this| should be notifications module"); - assert.equal(clickedData, data, - "data passed to onClick should be correct"); - }, - data: data, - title: "test title", - text: "test text", - iconURL: "test icon URL" - }; - notifs.notify(opts); - mockAlertServ.click(); - loader.unload(); -}; - -exports['test numbers and URLs in options'] = function(assert) { - let [loader] = makeLoader(module); - let notifs = loader.require('sdk/notifications'); - let opts = { - title: 123, - text: 45678, - // must use in-loader `sdk/url` module for the validation type check to work - iconURL: loader.require('sdk/url').URL('data:image/png,blah') - }; - try { - notifs.notify(opts); - assert.pass('using numbers and URLs in options works'); - } catch (e) { - assert.fail('using numbers and URLs in options must not throw'); - } - loader.unload(); -} - -exports['test new tag, dir and lang options'] = function(assert) { - let [loader] = makeLoader(module); - let notifs = loader.require('sdk/notifications'); - let opts = { - title: 'best', - tag: 'tagging', - lang: 'en' - }; - - try { - opts.dir = 'ttb'; - notifs.notify(opts); - assert.fail('`dir` option must not accept TopToBottom direction.'); - } catch (e) { - assert.equal(e.message, - '`dir` option must be one of: "auto", "ltr" or "rtl".'); - } - - try { - opts.dir = 'rtl'; - notifs.notify(opts); - assert.pass('`dir` option accepts "rtl" direction.'); - } catch (e) { - assert.fail('`dir` option must accept "rtl" direction.'); - } - - loader.unload(); -} - -// Returns [loader, mockAlertService]. -function makeLoader(module) { - let loader = Loader(module); - let mockAlertServ = { - showAlertNotification: function (imageUrl, title, text, textClickable, - cookie, alertListener, name) { - this._cookie = cookie; - this._alertListener = alertListener; - }, - click: function () { - this._alertListener.observe(null, "alertclickcallback", this._cookie); - } - }; - loader.require("sdk/notifications"); - let scope = loader.sandbox("sdk/notifications"); - scope.notify = mockAlertServ.showAlertNotification.bind(mockAlertServ); - return [loader, mockAlertServ]; -} - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-object.js b/addon-sdk/source/test/test-object.js deleted file mode 100644 index a380fac8a..000000000 --- a/addon-sdk/source/test/test-object.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 { merge, extend, has, each } = require('sdk/util/object'); - -var o = { - 'paper': 0, - 'rock': 1, - 'scissors': 2 -}; - -//exports.testMerge = function(assert) {} -//exports.testExtend = function(assert) {} - -exports.testHas = function(assert) { - assert.equal(has(o, 'paper'), true, 'has correctly finds key'); - assert.equal(has(o, 'rock'), true, 'has correctly finds key'); - assert.equal(has(o, 'scissors'), true, 'has correctly finds key'); - assert.equal(has(o, 'nope'), false, 'has correctly does not find key'); - assert.equal(has(o, '__proto__'), false, 'has correctly does not find key'); - assert.equal(has(o, 'isPrototypeOf'), false, 'has correctly does not find key'); -}; - -exports.testEach = function(assert) { - var keys = new Set(); - each(o, function (value, key, object) { - keys.add(key); - assert.equal(o[key], value, 'Key and value pairs passed in'); - assert.equal(o, object, 'Object passed in'); - }); - assert.equal(keys.size, 3, 'All keys have been iterated upon'); -}; - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-observers.js b/addon-sdk/source/test/test-observers.js deleted file mode 100644 index 4f15a87f1..000000000 --- a/addon-sdk/source/test/test-observers.js +++ /dev/null @@ -1,183 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Loader } = require("sdk/test/loader"); -const { isWeak, WeakReference } = require("sdk/core/reference"); -const { subscribe, unsubscribe, - observe, Observer } = require("sdk/core/observer"); -const { Class } = require("sdk/core/heritage"); - -const { Cc, Ci, Cu } = require("chrome"); -const { notifyObservers } = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); -const { defer } = require("sdk/core/promise"); - -const message = x => ({wrappedJSObject: x}); - -exports["test subscribe unsubscribe"] = assert => { - const topic = Date.now().toString(32); - const Subscriber = Class({ - extends: Observer, - initialize: function(observe) { - this.observe = observe; - } - }); - observe.define(Subscriber, (x, subject, _, data) => - x.observe(subject.wrappedJSObject.x)); - - let xs = []; - const x = Subscriber((...rest) => xs.push(...rest)); - - let ys = []; - const y = Subscriber((...rest) => ys.push(...rest)); - - const publish = (topic, data) => - notifyObservers(message(data), topic, null); - - publish({x:0}); - - subscribe(x, topic); - - publish(topic, {x:1}); - - subscribe(y, topic); - - publish(topic, {x:2}); - publish(topic + "!", {x: 2.5}); - - unsubscribe(x, topic); - - publish(topic, {x:3}); - - subscribe(y, topic); - - publish(topic, {x:4}); - - subscribe(x, topic); - - publish(topic, {x:5}); - - unsubscribe(x, topic); - unsubscribe(y, topic); - - publish(topic, {x:6}); - - assert.deepEqual(xs, [1, 2, 5]); - assert.deepEqual(ys, [2, 3, 4, 5]); -} - -exports["test weak observers are GC-ed on unload"] = (assert, end) => { - const topic = Date.now().toString(32); - const loader = Loader(module); - const { Observer, observe, - subscribe, unsubscribe } = loader.require("sdk/core/observer"); - const { isWeak, WeakReference } = loader.require("sdk/core/reference"); - - const MyObserver = Class({ - extends: Observer, - initialize: function(observe) { - this.observe = observe; - } - }); - observe.define(MyObserver, (x, ...rest) => x.observe(...rest)); - - const MyWeakObserver = Class({ - extends: MyObserver, - implements: [WeakReference] - }); - - let xs = []; - let ys = []; - let x = new MyObserver((subject, topic, data) => { - xs.push(subject.wrappedJSObject, topic, data); - }); - let y = new MyWeakObserver((subject, topic, data) => { - ys.push(subject.wrappedJSObject, topic, data); - }); - - subscribe(x, topic); - subscribe(y, topic); - - - notifyObservers(message({ foo: 1 }), topic, null); - x = null; - y = null; - loader.unload(); - - Cu.schedulePreciseGC(() => { - - notifyObservers(message({ bar: 2 }), topic, ":)"); - - assert.deepEqual(xs, [{ foo: 1 }, topic, null, - { bar: 2 }, topic, ":)"], - "non week observer is kept"); - - assert.deepEqual(ys, [{ foo: 1 }, topic, null], - "week observer was GC-ed"); - - end(); - }); -}; - -exports["test weak observer unsubscribe"] = function*(assert) { - const loader = Loader(module); - const { Observer, observe, subscribe, unsubscribe } = loader.require("sdk/core/observer"); - const { WeakReference } = loader.require("sdk/core/reference"); - - let sawNotification = false; - let firstWait = defer(); - let secondWait = defer(); - - const WeakObserver = Class({ - extends: Observer, - implements: [WeakReference], - observe: function() { - sawNotification = true; - firstWait.resolve(); - } - }); - - const StrongObserver = Class({ - extends: Observer, - observe: function() { - secondWait.resolve(); - } - }); - - observe.define(Observer, (x, ...rest) => x.observe(...rest)); - - let weakObserver = new WeakObserver; - let strongObserver = new StrongObserver(); - subscribe(weakObserver, "test-topic"); - subscribe(strongObserver, "test-wait"); - - notifyObservers(null, "test-topic", null); - yield firstWait.promise; - - assert.ok(sawNotification, "Should have seen notification before GC"); - sawNotification = false; - - yield loader.require("sdk/test/memory").gc(); - - notifyObservers(null, "test-topic", null); - notifyObservers(null, "test-wait", null); - yield secondWait.promise; - - assert.ok(sawNotification, "Should have seen notification after GC"); - sawNotification = false; - - try { - unsubscribe(weakObserver, "test-topic"); - unsubscribe(strongObserver, "test-wait"); - assert.pass("Should not have seen an exception"); - } - catch (e) { - assert.fail("Should not have seen an exception"); - } - - loader.unload(); -}; - -require("sdk/test").run(exports); diff --git a/addon-sdk/source/test/test-page-mod-debug.js b/addon-sdk/source/test/test-page-mod-debug.js deleted file mode 100644 index 86f491149..000000000 --- a/addon-sdk/source/test/test-page-mod-debug.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/. */ -"use strict"; - -const { Cc, Ci, Cu } = require("chrome"); -const { PageMod } = require("sdk/page-mod"); -const { testPageMod, handleReadyState, openNewTab, - contentScriptWhenServer, createLoader } = require("./page-mod/helpers"); -const { cleanUI, after } = require("sdk/test/utils"); -const { open, getFrames, getMostRecentBrowserWindow, getInnerId } = require("sdk/window/utils"); - -const { devtools } = Cu.import("resource://devtools/shared/Loader.jsm", {}); -const { require: devtoolsRequire } = devtools; -const contentGlobals = devtoolsRequire("devtools/server/content-globals"); - -// The following adds Debugger constructor to the global namespace. -const { addDebuggerToGlobal } = require('resource://gre/modules/jsdebugger.jsm'); -addDebuggerToGlobal(this); - -exports.testDebugMetadata = function(assert, done) { - let dbg = new Debugger; - let globalDebuggees = []; - dbg.onNewGlobalObject = function(global) { - globalDebuggees.push(global); - } - - let mods = testPageMod(assert, done, "about:", [{ - include: "about:", - contentScriptWhen: "start", - contentScript: "null;", - }], function(win, done) { - assert.ok(globalDebuggees.some(function(global) { - try { - let metadata = Cu.getSandboxMetadata(global.unsafeDereference()); - return metadata && metadata.addonID && metadata.SDKContentScript && - metadata['inner-window-id'] == getInnerId(win); - } catch(e) { - // Some of the globals might not be Sandbox instances and thus - // will cause getSandboxMetadata to fail. - return false; - } - }), "one of the globals is a content script"); - done(); - } - ); -}; - -exports.testDevToolsExtensionsGetContentGlobals = function(assert, done) { - let mods = testPageMod(assert, done, "about:", [{ - include: "about:", - contentScriptWhen: "start", - contentScript: "null;", - }], function(win, done) { - assert.equal(contentGlobals.getContentGlobals({ 'inner-window-id': getInnerId(win) }).length, 1); - done(); - } - ); -}; - -after(exports, function*(name, assert) { - assert.pass("cleaning ui."); - yield cleanUI(); -}); - -require('sdk/test').run(exports); diff --git a/addon-sdk/source/test/test-page-mod.js b/addon-sdk/source/test/test-page-mod.js deleted file mode 100644 index d03463d2d..000000000 --- a/addon-sdk/source/test/test-page-mod.js +++ /dev/null @@ -1,2214 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.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 { Cc, Ci, Cu } = require("chrome"); -const { PageMod } = require("sdk/page-mod"); -const { testPageMod, handleReadyState, openNewTab, - contentScriptWhenServer, createLoader } = require("./page-mod/helpers"); -const { Loader } = require("sdk/test/loader"); -const tabs = require("sdk/tabs"); -const { setTimeout } = require("sdk/timers"); -const system = require("sdk/system/events"); -const { open, getFrames, getMostRecentBrowserWindow, getInnerId } = require("sdk/window/utils"); -const { getTabContentWindow, getActiveTab, setTabURL, openTab, closeTab, - getBrowserForTab } = require("sdk/tabs/utils"); -const xulApp = require("sdk/system/xul-app"); -const { isPrivateBrowsingSupported } = require("sdk/self"); -const { isPrivate } = require("sdk/private-browsing"); -const { openWebpage } = require("./private-browsing/helper"); -const { isTabPBSupported, isWindowPBSupported } = require("sdk/private-browsing/utils"); -const promise = require("sdk/core/promise"); -const { pb } = require("./private-browsing/helper"); -const { URL } = require("sdk/url"); -const { defer, all, resolve } = require("sdk/core/promise"); -const { waitUntil } = require("sdk/test/utils"); -const data = require("./fixtures"); -const { cleanUI, after } = require("sdk/test/utils"); - -const testPageURI = data.url("test.html"); - -function Isolate(worker) { - return "(" + worker + ")()"; -} - -/* Tests for the PageMod APIs */ - -exports.testPageMod1 = function*(assert) { - let modAttached = defer(); - let mod = PageMod({ - include: /about:/, - contentScriptWhen: "end", - contentScript: "new " + function WorkerScope() { - window.document.body.setAttribute("JEP-107", "worked"); - - self.port.once("done", () => { - self.port.emit("results", window.document.body.getAttribute("JEP-107")) - }); - }, - onAttach: function(worker) { - assert.equal(this, mod, "The 'this' object is the page mod."); - mod.port.once("results", modAttached.resolve) - mod.port.emit("done"); - } - }); - - let tab = yield new Promise(resolve => { - tabs.open({ - url: "about:", - inBackground: true, - onReady: resolve - }) - }); - assert.pass("test tab was opened."); - - let worked = yield modAttached.promise; - assert.pass("test mod was attached."); - - mod.destroy(); - assert.pass("test mod was destroyed."); - - assert.equal(worked, "worked", "PageMod.onReady test"); -}; - -exports.testPageMod2 = function*(assert) { - let modAttached = defer(); - let mod = PageMod({ - include: testPageURI, - contentScriptWhen: "end", - contentScript: [ - 'new ' + function contentScript() { - window.AUQLUE = function() { return 42; } - try { - window.AUQLUE() - } - catch(e) { - throw new Error("PageMod scripts executed in order"); - } - document.documentElement.setAttribute("first", "true"); - }, - 'new ' + function contentScript() { - document.documentElement.setAttribute("second", "true"); - - self.port.once("done", () => { - self.port.emit("results", { - "first": window.document.documentElement.getAttribute("first"), - "second": window.document.documentElement.getAttribute("second"), - "AUQLUE": unsafeWindow.getAUQLUE() - }); - }); - } - ], - onAttach: modAttached.resolve - }); - - let tab = yield new Promise(resolve => { - tabs.open({ - url: testPageURI, - inBackground: true, - onReady: resolve - }) - }); - assert.pass("test tab was opened."); - - let worker = yield modAttached.promise; - assert.pass("test mod was attached."); - - let results = yield new Promise(resolve => { - worker.port.once("results", resolve) - worker.port.emit("done"); - }); - - mod.destroy(); - assert.pass("test mod was destroyed."); - - assert.equal(results["first"], - "true", - "PageMod test #2: first script has run"); - assert.equal(results["second"], - "true", - "PageMod test #2: second script has run"); - assert.equal(results["AUQLUE"], false, - "PageMod test #2: scripts get a wrapped window"); -}; - -exports.testPageModIncludes = function*(assert) { - var modsAttached = []; - var modNumber = 0; - var modAttached = defer(); - let includes = [ - "*", - "*.google.com", - "resource:*", - "resource:", - testPageURI - ]; - let expected = [ - false, - false, - true, - false, - true - ] - - let mod = PageMod({ - include: testPageURI, - contentScript: 'new ' + function() { - self.port.on("get-local-storage", () => { - let result = {}; - self.options.forEach(include => { - result[include] = !!window.localStorage[include] - }); - - self.port.emit("got-local-storage", result); - - window.localStorage.clear(); - }); - }, - contentScriptOptions: includes, - onAttach: modAttached.resolve - }); - - function createPageModTest(include, expectedMatch) { - var modIndex = modNumber++; - - let attached = defer(); - modsAttached.push(expectedMatch ? attached.promise : resolve()); - - // ...and corresponding PageMod options - return PageMod({ - include: include, - contentScript: 'new ' + function() { - self.on("message", function(msg) { - window.localStorage[msg] = true - self.port.emit('done'); - }); - }, - // The testPageMod callback with test assertions is called on 'end', - // and we want this page mod to be attached before it gets called, - // so we attach it on 'start'. - contentScriptWhen: 'start', - onAttach: function(worker) { - assert.pass("mod " + modIndex + " was attached"); - - worker.port.once("done", () => { - assert.pass("mod " + modIndex + " is done"); - attached.resolve(worker); - }); - worker.postMessage(this.include[0]); - } - }); - } - - let mods = [ - createPageModTest("*", false), - createPageModTest("*.google.com", false), - createPageModTest("resource:*", true), - createPageModTest("resource:", false), - createPageModTest(testPageURI, true) - ]; - - let tab = yield new Promise(resolve => { - tabs.open({ - url: testPageURI, - inBackground: true, - onReady: resolve - }); - }); - assert.pass("tab was opened"); - - yield all(modsAttached); - assert.pass("all mods were attached."); - - mods.forEach(mod => mod.destroy()); - assert.pass("all mods were destroyed."); - - yield modAttached.promise; - assert.pass("final test mod was attached."); - - yield new Promise(resolve => { - mod.port.on("got-local-storage", (storage) => { - includes.forEach((include, i) => { - assert.equal(storage[include], expected[i], "localStorage is correct for " + include); - }); - resolve(); - }); - mod.port.emit("get-local-storage"); - }); - assert.pass("final test of localStorage is complete."); - - mod.destroy(); - assert.pass("final test mod was destroyed."); -}; - -exports.testPageModExcludes = function(assert, done) { - var asserts = []; - function createPageModTest(include, exclude, expectedMatch) { - // Create an 'onload' test function... - asserts.push(function(test, win) { - var matches = JSON.stringify([include, exclude]) in win.localStorage; - assert.ok(expectedMatch ? matches : !matches, - "[include, exclude] = [" + include + ", " + exclude + - "] match test, expected: " + expectedMatch); - }); - // ...and corresponding PageMod options - return { - include: include, - exclude: exclude, - contentScript: 'new ' + function() { - self.on("message", function(msg) { - // The key in localStorage is "[, ]". - window.localStorage[JSON.stringify(msg)] = true; - }); - }, - // The testPageMod callback with test assertions is called on 'end', - // and we want this page mod to be attached before it gets called, - // so we attach it on 'start'. - contentScriptWhen: 'start', - onAttach: function(worker) { - worker.postMessage([this.include[0], this.exclude[0]]); - } - }; - } - - testPageMod(assert, done, testPageURI, [ - createPageModTest("*", testPageURI, false), - createPageModTest(testPageURI, testPageURI, false), - createPageModTest(testPageURI, "resource://*", false), - createPageModTest(testPageURI, "*.google.com", true) - ], - function (win, done) { - waitUntil(() => win.localStorage[JSON.stringify([testPageURI, "*.google.com"])], - testPageURI + " page-mod to be executed") - .then(() => { - asserts.forEach(fn => fn(assert, win)); - win.localStorage.clear(); - done(); - }); - }); -}; - -exports.testPageModValidationAttachTo = function(assert) { - [{ val: 'top', type: 'string "top"' }, - { val: 'frame', type: 'string "frame"' }, - { val: ['top', 'existing'], type: 'array with "top" and "existing"' }, - { val: ['frame', 'existing'], type: 'array with "frame" and "existing"' }, - { val: ['top'], type: 'array with "top"' }, - { val: ['frame'], type: 'array with "frame"' }, - { val: undefined, type: 'undefined' }].forEach((attachTo) => { - new PageMod({ attachTo: attachTo.val, include: '*.validation111' }); - assert.pass("PageMod() does not throw when attachTo is " + attachTo.type); - }); - - [{ val: 'existing', type: 'string "existing"' }, - { val: ['existing'], type: 'array with "existing"' }, - { val: 'not-legit', type: 'string with "not-legit"' }, - { val: ['not-legit'], type: 'array with "not-legit"' }, - { val: {}, type: 'object' }].forEach((attachTo) => { - assert.throws(() => - new PageMod({ attachTo: attachTo.val, include: '*.validation111' }), - /The `attachTo` option/, - "PageMod() throws when 'attachTo' option is " + attachTo.type + "."); - }); -}; - -exports.testPageModValidationInclude = function(assert) { - [{ val: undefined, type: 'undefined' }, - { val: {}, type: 'object' }, - { val: [], type: 'empty array'}, - { val: [/regexp/, 1], type: 'array with non string/regexp' }, - { val: 1, type: 'number' }].forEach((include) => { - assert.throws(() => new PageMod({ include: include.val }), - /The `include` option must always contain atleast one rule/, - "PageMod() throws when 'include' option is " + include.type + "."); - }); - - [{ val: '*.validation111', type: 'string' }, - { val: /validation111/, type: 'regexp' }, - { val: ['*.validation111'], type: 'array with length > 0'}].forEach((include) => { - new PageMod({ include: include.val }); - assert.pass("PageMod() does not throw when include option is " + include.type); - }); -}; - -exports.testPageModValidationExclude = function(assert) { - let includeVal = '*.validation111'; - - [{ val: {}, type: 'object' }, - { val: [], type: 'empty array'}, - { val: [/regexp/, 1], type: 'array with non string/regexp' }, - { val: 1, type: 'number' }].forEach((exclude) => { - assert.throws(() => new PageMod({ include: includeVal, exclude: exclude.val }), - /If set, the `exclude` option must always contain at least one rule as a string, regular expression, or an array of strings and regular expressions./, - "PageMod() throws when 'exclude' option is " + exclude.type + "."); - }); - - [{ val: undefined, type: 'undefined' }, - { val: '*.validation111', type: 'string' }, - { val: /validation111/, type: 'regexp' }, - { val: ['*.validation111'], type: 'array with length > 0'}].forEach((exclude) => { - new PageMod({ include: includeVal, exclude: exclude.val }); - assert.pass("PageMod() does not throw when exclude option is " + exclude.type); - }); -}; - -/* Tests for internal functions. */ -exports.testCommunication1 = function*(assert) { - let workerDone = defer(); - - let mod = PageMod({ - include: "about:*", - contentScriptWhen: "end", - contentScript: 'new ' + function WorkerScope() { - self.on('message', function(msg) { - document.body.setAttribute('JEP-107', 'worked'); - self.postMessage(document.body.getAttribute('JEP-107')); - }); - self.port.on('get-jep-107', () => { - self.port.emit('got-jep-107', document.body.getAttribute('JEP-107')); - }); - }, - onAttach: function(worker) { - worker.on('error', function(e) { - assert.fail('Errors where reported'); - }); - worker.on('message', function(value) { - assert.equal( - "worked", - value, - "test comunication" - ); - workerDone.resolve(); - }); - worker.postMessage("do it!") - } - }); - - let tab = yield new Promise(resolve => { - tabs.open({ - url: "about:", - onReady: resolve - }); - }); - assert.pass("opened tab"); - - yield workerDone.promise; - assert.pass("the worker has made a change"); - - let value = yield new Promise(resolve => { - mod.port.once("got-jep-107", resolve); - mod.port.emit("get-jep-107"); - }); - - assert.equal("worked", value, "attribute should be modified"); - - mod.destroy(); - assert.pass("the worker was destroyed"); -}; - -exports.testCommunication2 = function*(assert) { - let workerDone = defer(); - let url = data.url("test.html"); - - let mod = PageMod({ - include: url, - contentScriptWhen: 'start', - contentScript: 'new ' + function WorkerScope() { - document.documentElement.setAttribute('AUQLUE', 42); - - window.addEventListener('load', function listener() { - self.postMessage({ - msg: 'onload', - AUQLUE: document.documentElement.getAttribute('AUQLUE') - }); - }, false); - - self.on("message", function(msg) { - if (msg == "get window.test") { - unsafeWindow.changesInWindow(); - } - - self.postMessage({ - msg: document.documentElement.getAttribute("test") - }); - }); - }, - onAttach: function(worker) { - worker.on('error', function(e) { - assert.fail('Errors where reported'); - }); - worker.on('message', function({ msg, AUQLUE }) { - if ('onload' == msg) { - assert.equal('42', AUQLUE, 'PageMod scripts executed in order'); - worker.postMessage('get window.test'); - } - else { - assert.equal('changes in window', msg, 'PageMod test #2: second script has run'); - workerDone.resolve(); - } - }); - } - }); - - let tab = yield new Promise(resolve => { - tabs.open({ - url: url, - inBackground: true, - onReady: resolve - }); - }); - assert.pass("opened tab"); - - yield workerDone.promise; - - mod.destroy(); - assert.pass("the worker was destroyed"); -}; - -exports.testEventEmitter = function(assert, done) { - let workerDone = false, - callbackDone = null; - - testPageMod(assert, done, "about:", [{ - include: "about:*", - contentScript: 'new ' + function WorkerScope() { - self.port.on('addon-to-content', function(data) { - self.port.emit('content-to-addon', data); - }); - }, - onAttach: function(worker) { - worker.on('error', function(e) { - assert.fail('Errors were reported : '+e); - }); - worker.port.on('content-to-addon', function(value) { - assert.equal( - "worked", - value, - "EventEmitter API works!" - ); - if (callbackDone) - callbackDone(); - else - workerDone = true; - }); - worker.port.emit('addon-to-content', 'worked'); - } - }], - function(win, done) { - if (workerDone) - done(); - else - callbackDone = done; - } - ); -}; - -// Execute two concurrent page mods on same document to ensure that their -// JS contexts are different -exports.testMixedContext = function(assert, done) { - let doneCallback = null; - let messages = 0; - let modObject = { - include: "data:text/html;charset=utf-8,", - contentScript: 'new ' + function WorkerScope() { - // Both scripts will execute this, - // context is shared if one script see the other one modification. - let isContextShared = "sharedAttribute" in document; - self.postMessage(isContextShared); - document.sharedAttribute = true; - }, - onAttach: function(w) { - w.on("message", function (isContextShared) { - if (isContextShared) { - assert.fail("Page mod contexts are mixed."); - doneCallback(); - } - else if (++messages == 2) { - assert.pass("Page mod contexts are different."); - doneCallback(); - } - }); - } - }; - testPageMod(assert, done, "data:text/html;charset=utf-8,", [modObject, modObject], - function(win, done) { - doneCallback = done; - } - ); -}; - -exports.testHistory = function(assert, done) { - // We need a valid url in order to have a working History API. - // (i.e do not work on data: or about: pages) - // Test bug 679054. - let url = data.url("test-page-mod.html"); - let callbackDone = null; - testPageMod(assert, done, url, [{ - include: url, - contentScriptWhen: 'end', - contentScript: 'new ' + function WorkerScope() { - history.pushState({}, "", "#"); - history.replaceState({foo: "bar"}, "", "#"); - self.postMessage(history.state); - }, - onAttach: function(worker) { - worker.on('message', function (data) { - assert.equal(JSON.stringify(data), JSON.stringify({foo: "bar"}), - "History API works!"); - callbackDone(); - }); - } - }], - function(win, done) { - callbackDone = done; - } - ); -}; - -exports.testRelatedTab = function(assert, done) { - let tab; - let pageMod = new PageMod({ - include: "about:*", - onAttach: function(worker) { - assert.ok(!!worker.tab, "Worker.tab exists"); - assert.equal(tab, worker.tab, "Worker.tab is valid"); - pageMod.destroy(); - tab.close(done); - } - }); - - tabs.open({ - url: "about:", - onOpen: function onOpen(t) { - tab = t; - } - }); -}; - -// related to bug #989288 -// https://bugzilla.mozilla.org/show_bug.cgi?id=989288 -exports.testRelatedTabNewWindow = function(assert, done) { - let url = "about:logo" - let pageMod = new PageMod({ - include: url, - onAttach: function(worker) { - assert.equal(worker.tab.url, url, "Worker.tab.url is valid"); - worker.tab.close(done); - } - }); - - tabs.activeTab.attach({ - contentScript: "window.open('about:logo', '', " + - "'width=800,height=600,resizable=no,status=no,location=no');" - }); - -}; - -exports.testRelatedTabNoRequireTab = function(assert, done) { - let loader = Loader(module); - let tab; - let url = "data:text/html;charset=utf-8," + encodeURI("Test related worker tab 2"); - let { PageMod } = loader.require("sdk/page-mod"); - let pageMod = new PageMod({ - include: url, - onAttach: function(worker) { - assert.equal(worker.tab.url, url, "Worker.tab.url is valid"); - worker.tab.close(function() { - pageMod.destroy(); - loader.unload(); - done(); - }); - } - }); - - tabs.open(url); -}; - -exports.testRelatedTabNoOtherReqs = function(assert, done) { - let loader = Loader(module); - let { PageMod } = loader.require("sdk/page-mod"); - let pageMod = new PageMod({ - include: "about:blank?testRelatedTabNoOtherReqs", - onAttach: function(worker) { - assert.ok(!!worker.tab, "Worker.tab exists"); - pageMod.destroy(); - worker.tab.close(function() { - worker.destroy(); - loader.unload(); - done(); - }); - } - }); - - tabs.open({ - url: "about:blank?testRelatedTabNoOtherReqs" - }); -}; - -exports.testWorksWithExistingTabs = function(assert, done) { - let url = "data:text/html;charset=utf-8," + encodeURI("Test unique document"); - let { PageMod } = require("sdk/page-mod"); - tabs.open({ - url: url, - onReady: function onReady(tab) { - let pageModOnExisting = new PageMod({ - include: url, - attachTo: ["existing", "top", "frame"], - onAttach: function(worker) { - assert.ok(!!worker.tab, "Worker.tab exists"); - assert.equal(tab, worker.tab, "A worker has been created on this existing tab"); - - worker.on('pageshow', () => { - assert.fail("Should not have seen pageshow for an already loaded page"); - }); - - setTimeout(function() { - pageModOnExisting.destroy(); - pageModOffExisting.destroy(); - tab.close(done); - }, 0); - } - }); - - let pageModOffExisting = new PageMod({ - include: url, - onAttach: function(worker) { - assert.fail("pageModOffExisting page-mod should not have attached to anything"); - } - }); - } - }); -}; - -exports.testExistingFrameDoesntMatchInclude = function(assert, done) { - let iframeURL = 'data:text/html;charset=utf-8,UNIQUE-TEST-STRING-42'; - let iframe = '