summaryrefslogtreecommitdiffstats
path: root/toolkit/components
diff options
context:
space:
mode:
authorMatt A. Tobin <email@mattatobin.com>2020-02-25 15:07:00 -0500
committerwolfbeast <mcwerewolf@wolfbeast.com>2020-04-14 12:55:19 +0200
commiteb70e6e3d0bff11c25f14b1196025791bf2308fb (patch)
tree5ef4ce17db83c74d7b05ec12c8f59e095a6dd5bd /toolkit/components
parent32ead795290b3399d56b4708fc75b77d296f6a1a (diff)
downloadUXP-eb70e6e3d0bff11c25f14b1196025791bf2308fb.tar
UXP-eb70e6e3d0bff11c25f14b1196025791bf2308fb.tar.gz
UXP-eb70e6e3d0bff11c25f14b1196025791bf2308fb.tar.lz
UXP-eb70e6e3d0bff11c25f14b1196025791bf2308fb.tar.xz
UXP-eb70e6e3d0bff11c25f14b1196025791bf2308fb.zip
Issue #439 - Remove tests from toolkit/
Diffstat (limited to 'toolkit/components')
-rw-r--r--toolkit/components/aboutcheckerboard/moz.build5
-rw-r--r--toolkit/components/aboutmemory/moz.build5
-rw-r--r--toolkit/components/aboutmemory/tests/.eslintrc.js7
-rw-r--r--toolkit/components/aboutmemory/tests/chrome.ini28
-rw-r--r--toolkit/components/aboutmemory/tests/crash-dump-diff1.json11
-rw-r--r--toolkit/components/aboutmemory/tests/crash-dump-diff2.json11
-rw-r--r--toolkit/components/aboutmemory/tests/crash-dump-good.json14
-rw-r--r--toolkit/components/aboutmemory/tests/memory-reports-bad.json3
-rw-r--r--toolkit/components/aboutmemory/tests/memory-reports-diff1.json45
-rw-r--r--toolkit/components/aboutmemory/tests/memory-reports-diff2.json44
-rw-r--r--toolkit/components/aboutmemory/tests/memory-reports-good.json29
-rw-r--r--toolkit/components/aboutmemory/tests/remote.xul12
-rw-r--r--toolkit/components/aboutmemory/tests/test_aboutmemory.xul602
-rw-r--r--toolkit/components/aboutmemory/tests/test_aboutmemory2.xul423
-rw-r--r--toolkit/components/aboutmemory/tests/test_aboutmemory3.xul515
-rw-r--r--toolkit/components/aboutmemory/tests/test_aboutmemory4.xul179
-rw-r--r--toolkit/components/aboutmemory/tests/test_aboutmemory5.xul167
-rw-r--r--toolkit/components/aboutmemory/tests/test_aboutmemory6.xul88
-rw-r--r--toolkit/components/aboutmemory/tests/test_dumpGCAndCCLogsToFile.xul98
-rw-r--r--toolkit/components/aboutmemory/tests/test_memoryReporters.xul424
-rw-r--r--toolkit/components/aboutmemory/tests/test_memoryReporters2.xul108
-rw-r--r--toolkit/components/aboutmemory/tests/test_sqliteMultiReporter.xul54
-rw-r--r--toolkit/components/aboutperformance/moz.build2
-rw-r--r--toolkit/components/aboutperformance/tests/browser/.eslintrc.js7
-rw-r--r--toolkit/components/aboutperformance/tests/browser/browser.ini8
-rw-r--r--toolkit/components/aboutperformance/tests/browser/browser_aboutperformance.js300
-rw-r--r--toolkit/components/aboutperformance/tests/browser/browser_compartments.html20
-rw-r--r--toolkit/components/aboutperformance/tests/browser/browser_compartments_frame.html12
-rw-r--r--toolkit/components/aboutperformance/tests/browser/browser_compartments_script.js29
-rw-r--r--toolkit/components/aboutperformance/tests/browser/head.js52
-rw-r--r--toolkit/components/addoncompat/moz.build2
-rw-r--r--toolkit/components/addoncompat/tests/addon/bootstrap.js653
-rw-r--r--toolkit/components/addoncompat/tests/addon/chrome.manifest1
-rw-r--r--toolkit/components/addoncompat/tests/addon/content/page.html2
-rw-r--r--toolkit/components/addoncompat/tests/addon/install.rdf37
-rw-r--r--toolkit/components/addoncompat/tests/browser/.eslintrc.js7
-rw-r--r--toolkit/components/addoncompat/tests/browser/addon.xpibin10761 -> 0 bytes
-rw-r--r--toolkit/components/addoncompat/tests/browser/browser.ini9
-rw-r--r--toolkit/components/addoncompat/tests/browser/browser_addonShims.js67
-rw-r--r--toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage.html17
-rw-r--r--toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage2.html16
-rw-r--r--toolkit/components/addoncompat/tests/browser/compat-addon.xpibin5692 -> 0 bytes
-rw-r--r--toolkit/components/addoncompat/tests/compat-addon/bootstrap.js99
-rw-r--r--toolkit/components/addoncompat/tests/compat-addon/install.rdf37
-rw-r--r--toolkit/components/addoncompat/tests/moz.build7
-rw-r--r--toolkit/components/alerts/moz.build9
-rw-r--r--toolkit/components/alerts/test/.eslintrc.js7
-rw-r--r--toolkit/components/alerts/test/image.gifbin60901 -> 0 bytes
-rw-r--r--toolkit/components/alerts/test/image.pngbin2531 -> 0 bytes
-rw-r--r--toolkit/components/alerts/test/image_server.sjs82
-rw-r--r--toolkit/components/alerts/test/mochitest.ini16
-rw-r--r--toolkit/components/alerts/test/test_alerts.html89
-rw-r--r--toolkit/components/alerts/test/test_alerts_noobserve.html96
-rw-r--r--toolkit/components/alerts/test/test_alerts_requireinteraction.html168
-rw-r--r--toolkit/components/alerts/test/test_image.html118
-rw-r--r--toolkit/components/alerts/test/test_multiple_alerts.html103
-rw-r--r--toolkit/components/alerts/test/test_principal.html122
-rw-r--r--toolkit/components/asyncshutdown/moz.build14
-rw-r--r--toolkit/components/asyncshutdown/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/asyncshutdown/tests/xpcshell/head.js174
-rw-r--r--toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown.js194
-rw-r--r--toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js96
-rw-r--r--toolkit/components/asyncshutdown/tests/xpcshell/test_converters.js88
-rw-r--r--toolkit/components/asyncshutdown/tests/xpcshell/xpcshell.ini8
-rw-r--r--toolkit/components/autocomplete/moz.build5
-rw-r--r--toolkit/components/autocomplete/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/autocomplete/tests/unit/head_autocomplete.js211
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_330578.js45
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_378079.js285
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_393191.js272
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_440866.js285
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_463023.js12
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_660156.js101
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js276
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js45
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js78
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js96
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js63
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js48
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js119
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js107
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js104
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js66
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_hiddenResult.js76
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_immediate_search.js157
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js14
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_popupSelectionVsDefaultCompleteValue.js71
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_previousResult.js280
-rw-r--r--toolkit/components/autocomplete/tests/unit/test_stopSearch.js187
-rw-r--r--toolkit/components/autocomplete/tests/unit/xpcshell.ini26
-rw-r--r--toolkit/components/captivedetect/moz.build7
-rw-r--r--toolkit/components/captivedetect/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/captivedetect/test/unit/head_setprefs.js49
-rw-r--r--toolkit/components/captivedetect/test/unit/test_abort.js53
-rw-r--r--toolkit/components/captivedetect/test/unit/test_abort_during_user_login.js66
-rw-r--r--toolkit/components/captivedetect/test/unit/test_abort_ongoing_request.js72
-rw-r--r--toolkit/components/captivedetect/test/unit/test_abort_pending_request.js71
-rw-r--r--toolkit/components/captivedetect/test/unit/test_captive_portal_found.js67
-rw-r--r--toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js74
-rw-r--r--toolkit/components/captivedetect/test/unit/test_captive_portal_not_found.js52
-rw-r--r--toolkit/components/captivedetect/test/unit/test_captive_portal_not_found_404.js49
-rw-r--r--toolkit/components/captivedetect/test/unit/test_multiple_requests.js83
-rw-r--r--toolkit/components/captivedetect/test/unit/test_user_cancel.js54
-rw-r--r--toolkit/components/captivedetect/test/unit/xpcshell.ini15
-rw-r--r--toolkit/components/commandlines/moz.build14
-rw-r--r--toolkit/components/commandlines/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/commandlines/test/unit/data/test_bug410156.desktop7
-rw-r--r--toolkit/components/commandlines/test/unit/data/test_bug410156.url9
-rw-r--r--toolkit/components/commandlines/test/unit/test_bug666224.js6
-rw-r--r--toolkit/components/commandlines/test/unit/test_classinfo.js9
-rw-r--r--toolkit/components/commandlines/test/unit/xpcshell.ini10
-rw-r--r--toolkit/components/commandlines/test/unit_unix/.eslintrc.js7
-rw-r--r--toolkit/components/commandlines/test/unit_unix/test_bug410156.js11
-rw-r--r--toolkit/components/commandlines/test/unit_unix/xpcshell.ini9
-rw-r--r--toolkit/components/commandlines/test/unit_win/.eslintrc.js7
-rw-r--r--toolkit/components/commandlines/test/unit_win/test_bug410156.js11
-rw-r--r--toolkit/components/commandlines/test/unit_win/xpcshell.ini8
-rw-r--r--toolkit/components/console/moz.build2
-rw-r--r--toolkit/components/console/tests/chrome.ini3
-rw-r--r--toolkit/components/console/tests/test_hugeURIs.xul64
-rw-r--r--toolkit/components/contentprefs/moz.build12
-rw-r--r--toolkit/components/contentprefs/tests/mochitest/.eslintrc.js7
-rw-r--r--toolkit/components/contentprefs/tests/mochitest/mochitest.ini4
-rw-r--r--toolkit/components/contentprefs/tests/mochitest/test_remoteContentPrefs.html311
-rw-r--r--toolkit/components/contentprefs/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/contentprefs/tests/unit/head_contentPrefs.js162
-rw-r--r--toolkit/components/contentprefs/tests/unit/tail_contentPrefs.js6
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_bug248970.js42
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_bug503971.js35
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_bug679784.js103
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_contentPrefs.js463
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_contentPrefsCache.js244
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js34
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_stringGroups.js128
-rw-r--r--toolkit/components/contentprefs/tests/unit/test_unusedGroupsAndSettings.js52
-rw-r--r--toolkit/components/contentprefs/tests/unit/xpcshell.ini12
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/.eslintrc.js7
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/AsyncRunner.jsm69
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/head.js401
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_extractDomain.js20
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_getCached.js95
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_getCachedSubdomains.js186
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_getSubdomains.js68
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_migrationToSchema4.js82
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_observers.js178
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_remove.js222
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomains.js87
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomainsSince.js111
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_removeByDomain.js199
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_removeByName.js96
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_service.js12
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js206
-rw-r--r--toolkit/components/contentprefs/tests/unit_cps2/xpcshell.ini19
-rw-r--r--toolkit/components/contextualidentity/moz.build6
-rw-r--r--toolkit/components/contextualidentity/tests/unit/test_basic.js67
-rw-r--r--toolkit/components/contextualidentity/tests/unit/xpcshell.ini3
-rw-r--r--toolkit/components/crashes/moz.build5
-rw-r--r--toolkit/components/crashes/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/crashes/tests/xpcshell/test_crash_manager.js494
-rw-r--r--toolkit/components/crashes/tests/xpcshell/test_crash_service.js31
-rw-r--r--toolkit/components/crashes/tests/xpcshell/test_crash_store.js587
-rw-r--r--toolkit/components/crashes/tests/xpcshell/xpcshell.ini8
-rw-r--r--toolkit/components/crashmonitor/moz.build2
-rw-r--r--toolkit/components/crashmonitor/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/crashmonitor/test/unit/head.js22
-rw-r--r--toolkit/components/crashmonitor/test/unit/test_init.js17
-rw-r--r--toolkit/components/crashmonitor/test/unit/test_invalid_file.js22
-rw-r--r--toolkit/components/crashmonitor/test/unit/test_invalid_json.js18
-rw-r--r--toolkit/components/crashmonitor/test/unit/test_missing_file.js13
-rw-r--r--toolkit/components/crashmonitor/test/unit/test_register.js24
-rw-r--r--toolkit/components/crashmonitor/test/unit/test_valid_file.js20
-rw-r--r--toolkit/components/crashmonitor/test/unit/xpcshell.ini11
-rw-r--r--toolkit/components/ctypes/moz.build17
-rw-r--r--toolkit/components/ctypes/tests/chrome/.eslintrc.js7
-rw-r--r--toolkit/components/ctypes/tests/chrome/chrome.ini8
-rw-r--r--toolkit/components/ctypes/tests/chrome/ctypes_worker.js14
-rw-r--r--toolkit/components/ctypes/tests/chrome/test_ctypes.xul106
-rw-r--r--toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js100
-rw-r--r--toolkit/components/ctypes/tests/jsctypes-test-errno.cpp41
-rw-r--r--toolkit/components/ctypes/tests/jsctypes-test-errno.h21
-rw-r--r--toolkit/components/ctypes/tests/jsctypes-test-finalizer.cpp323
-rw-r--r--toolkit/components/ctypes/tests/jsctypes-test-finalizer.h57
-rw-r--r--toolkit/components/ctypes/tests/jsctypes-test.cpp394
-rw-r--r--toolkit/components/ctypes/tests/jsctypes-test.h197
-rw-r--r--toolkit/components/ctypes/tests/moz.build30
-rw-r--r--toolkit/components/ctypes/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/ctypes/tests/unit/head.js128
-rw-r--r--toolkit/components/ctypes/tests/unit/test_errno.js69
-rw-r--r--toolkit/components/ctypes/tests/unit/test_finalizer.js452
-rw-r--r--toolkit/components/ctypes/tests/unit/test_finalizer_shouldaccept.js174
-rw-r--r--toolkit/components/ctypes/tests/unit/test_finalizer_shouldfail.js176
-rw-r--r--toolkit/components/ctypes/tests/unit/test_jsctypes.js2808
-rw-r--r--toolkit/components/ctypes/tests/unit/xpcshell.ini13
-rw-r--r--toolkit/components/downloads/moz.build29
-rw-r--r--toolkit/components/downloads/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/downloads/test/unit/data/block_digest.chunk2
-rw-r--r--toolkit/components/downloads/test/unit/data/digest.chunk3
-rw-r--r--toolkit/components/downloads/test/unit/data/signed_win.exebin61064 -> 0 bytes
-rw-r--r--toolkit/components/downloads/test/unit/head_download_manager.js26
-rw-r--r--toolkit/components/downloads/test/unit/tail_download_manager.js23
-rw-r--r--toolkit/components/downloads/test/unit/test_app_rep.js342
-rw-r--r--toolkit/components/downloads/test/unit/test_app_rep_maclinux.js303
-rw-r--r--toolkit/components/downloads/test/unit/test_app_rep_windows.js434
-rw-r--r--toolkit/components/downloads/test/unit/xpcshell.ini14
-rw-r--r--toolkit/components/exthelper/moz.build4
-rw-r--r--toolkit/components/feeds/moz.build6
-rw-r--r--toolkit/components/feeds/test/.eslintrc.js8
-rw-r--r--toolkit/components/feeds/test/chrome.ini3
-rw-r--r--toolkit/components/feeds/test/head.js80
-rw-r--r--toolkit/components/feeds/test/test_bug675492.xul31
-rw-r--r--toolkit/components/feeds/test/test_xml.js97
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/author_namespaces.xml16
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_author.xml30
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_content.xml35
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_content_encoded.xml43
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_content_html.xml35
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml.xml39
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml_with_markup.xml39
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_contributor.xml30
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_html_cdata.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_id.xml35
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore2.xml33
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_IANA.xml29
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_alt_extension.xml25
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure_populate_enclosures.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_otherURI_alt.xml25
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_payment_alt.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_link_random.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_published.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_rights_normalized.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_summary.xml40
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_title.xml35
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_title_normalized.xml35
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_updated.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_w_content_encoded.xml43
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_xhtml_baseURI_with_amp.xml37
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase_on_link.xml22
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_atom_rights_xhtml.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_author.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_author2.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_author_email.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_author_email_2.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_author_name.xml13
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_author_surrounded.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_author_uri.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_comment_rss_extra_att.xml29
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_contributor.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_entry_count.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_generator.xml33
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri.xml33
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri_xmlbase.xml33
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_generator_version.xml33
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_icon.xml11
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_id.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_id_extra_att.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_logo.xml11
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_random_attributes_on_feed_and_entry.xml30
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_rights_normalized.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml_nested_divs.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_subtitle.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_tantek_title.xml46
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_title.xml10
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_title_full_feed.xml936
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml_entities.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_updated.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_updated_invalid.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_updated_normalized.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_version.xml9
-rw-r--r--toolkit/components/feeds/test/xml/rfc4287/feed_xmlBase.xml23
-rw-r--r--toolkit/components/feeds/test/xml/rss09x/rss090.xml50
-rw-r--r--toolkit/components/feeds/test/xml/rss09x/rss091.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rss09x/rss091_withNS.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rss09x/rss092.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rss09x/rss093.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rss09x/rss094.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rss09x/rssUnknown.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_bogus_title.xml45
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_description.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_description_normalized.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_description_with_dc.xml19
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_description_with_dc_only.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_generator.xml34
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_id.xml25
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_image.xml39
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_items_length_zero.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_link.xml16
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_link_normalized.xml16
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_textInput.xml40
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_title.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_title_extra_att.xml16
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_title_normalized.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_updated.xml26
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_updated_dctermsmodified.xml27
-rw-r--r--toolkit/components/feeds/test/xml/rss1/feed_version.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss1/full_feed.xml41
-rw-r--r--toolkit/components/feeds/test/xml/rss1/full_feed_not_bozo.xml354
-rw-r--r--toolkit/components/feeds/test/xml/rss1/full_feed_unknown_extension.xml55
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_2_dc_description.xml34
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher.xml35
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher_extra_att_invalid_rdf.xml36
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_count.xml32
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_dc_creator.xml34
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_dc_description.xml35
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_dc_description_normalized.xml37
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_description.xml31
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_id.xml32
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_link.xml32
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_link_normalized.xml32
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_title.xml31
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_title_normalized.xml32
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_updated_dcterms.xml28
-rw-r--r--toolkit/components/feeds/test/xml/rss1/item_wiki_importance_extra_att.xml34
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_category.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_category_count.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_cloud.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_copyright.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_copyright_linebreak.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_data_outside_channel.xml13
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_dc_contributor.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_dc_creator.xml13
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_description.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_description_html.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_description_html_cdata.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_docs.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_generator.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_image_desc.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_image_desc_width_height.xml19
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_image_required.xml16
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_language.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_lastBuildDate.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_linebreak_link.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_link.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_link_cdata.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_managingEditor.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_managingEditor_extra_att.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_multiple_categories.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_pubDate.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_pubDate_invalid.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_1.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_2.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_pubDate_timezoneZ.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_pubDate_utc.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_rating.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_single_quote_stylesheet_pi.xml26
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_skipDays.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_skipHours.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_subtitle.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_subtitle_html.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_subtitle_markup_stripped.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_textinput.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_title.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_title_cdata_mixed.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_title_nesting.xml13
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_ttl.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_updated.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_updated_dcdate.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate_priority.xml13
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_webMaster.xml12
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_wfw_commentapi.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_wfw_commentrss.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_wiki.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rss2/feed_wiki_unusual_prefix.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_author.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_category.xml16
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_comments.xml19
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_content_encoded.xml15
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_count.xml26
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_count2.xml30
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_description.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_description_2.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_description_cdata.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_description_decode_entities.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_description_normalized.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_description_normalized_nohtml.xml18
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_enclosure.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates.xml24
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates2.xml24
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed.xml33
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed2.xml33
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_bogus_url.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_default.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false_uppercase.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_true_uppercase.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_unknown_value.xml20
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_normalized.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_guid_with_link.xml22
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_link.xml19
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_link_normalized.xml19
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_plain_desc.xml19
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_populated_enclosures.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_pubDate.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_published.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_title.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_title_normalized.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/item_updated_dcdate.xml14
-rw-r--r--toolkit/components/feeds/test/xml/rss2/items_2_titles.xml17
-rw-r--r--toolkit/components/feeds/test/xml/rss2/mrss_content.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/mrss_content2.xml22
-rw-r--r--toolkit/components/feeds/test/xml/rss2/mrss_content_429049.xml32
-rw-r--r--toolkit/components/feeds/test/xml/rss2/mrss_content_multiple.xml23
-rw-r--r--toolkit/components/feeds/test/xml/rss2/mrss_content_populate_enclosure.xml21
-rw-r--r--toolkit/components/feeds/test/xml/rss2/mrss_group_content.xml26
-rw-r--r--toolkit/components/feeds/test/xml/rss2/mrss_group_content_populate_enclosure.xml26
-rw-r--r--toolkit/components/feeds/test/xpcshell.ini209
-rw-r--r--toolkit/components/filepicker/moz.build24
-rw-r--r--toolkit/components/filepicker/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/filepicker/test/unit/test_filecomplete.js45
-rw-r--r--toolkit/components/filepicker/test/unit/xpcshell.ini7
-rw-r--r--toolkit/components/filewatcher/moz.build14
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/head.js29
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_arguments.js79
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js69
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_remove_non_watched.js39
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_shared_callback.js62
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_creation_single.js49
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_deletion_single.js46
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_file_creation_single.js51
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js54
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_file_modification_single.js54
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_many_changes.js73
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_multi_paths.js114
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_recursively.js55
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/test_watch_resource.js32
-rw-r--r--toolkit/components/filewatcher/tests/xpcshell/xpcshell.ini18
-rw-r--r--toolkit/components/formautofill/moz.build28
-rw-r--r--toolkit/components/formautofill/test/browser/.eslintrc.js7
-rw-r--r--toolkit/components/formautofill/test/browser/browser.ini10
-rw-r--r--toolkit/components/formautofill/test/browser/browser_infrastructure.js48
-rw-r--r--toolkit/components/formautofill/test/browser/browser_ui_requestAutocomplete.js48
-rw-r--r--toolkit/components/formautofill/test/browser/head.js18
-rw-r--r--toolkit/components/formautofill/test/browser/loader.js38
-rw-r--r--toolkit/components/formautofill/test/chrome/.eslintrc.js7
-rw-r--r--toolkit/components/formautofill/test/chrome/chrome.ini17
-rw-r--r--toolkit/components/formautofill/test/chrome/head.js15
-rw-r--r--toolkit/components/formautofill/test/chrome/loader.js116
-rw-r--r--toolkit/components/formautofill/test/chrome/loader_parent.js77
-rw-r--r--toolkit/components/formautofill/test/chrome/test_infrastructure.html8
-rw-r--r--toolkit/components/formautofill/test/chrome/test_infrastructure.js61
-rw-r--r--toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.html9
-rw-r--r--toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.js26
-rw-r--r--toolkit/components/formautofill/test/head_common.js245
-rw-r--r--toolkit/components/formautofill/test/loader_common.js120
-rw-r--r--toolkit/components/formautofill/test/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/formautofill/test/xpcshell/head.js23
-rw-r--r--toolkit/components/formautofill/test/xpcshell/loader.js46
-rw-r--r--toolkit/components/formautofill/test/xpcshell/test_infrastructure.js48
-rw-r--r--toolkit/components/formautofill/test/xpcshell/test_integration.js72
-rw-r--r--toolkit/components/formautofill/test/xpcshell/xpcshell.ini12
-rw-r--r--toolkit/components/jsdownloads/moz.build11
-rw-r--r--toolkit/components/jsdownloads/test/browser/.eslintrc.js7
-rw-r--r--toolkit/components/jsdownloads/test/browser/browser.ini7
-rw-r--r--toolkit/components/jsdownloads/test/browser/browser_DownloadPDFSaver.js97
-rw-r--r--toolkit/components/jsdownloads/test/browser/head.js87
-rw-r--r--toolkit/components/jsdownloads/test/browser/testFile.html9
-rw-r--r--toolkit/components/jsdownloads/test/data/.eslintrc.js7
-rw-r--r--toolkit/components/jsdownloads/test/data/empty.txt0
-rw-r--r--toolkit/components/jsdownloads/test/data/source.txt1
-rw-r--r--toolkit/components/jsdownloads/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/jsdownloads/test/unit/common_test_Download.js2432
-rw-r--r--toolkit/components/jsdownloads/test/unit/head.js843
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_DownloadCore.js87
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_DownloadImport.js701
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_DownloadIntegration.js432
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_DownloadLegacy.js17
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_DownloadList.js564
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_DownloadStore.js315
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_Downloads.js194
-rw-r--r--toolkit/components/jsdownloads/test/unit/test_PrivateTemp.js24
-rw-r--r--toolkit/components/jsdownloads/test/unit/xpcshell.ini19
-rw-r--r--toolkit/components/lz4/moz.build6
-rw-r--r--toolkit/components/lz4/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/lz4/tests/xpcshell/data/chrome.manifest1
-rw-r--r--toolkit/components/lz4/tests/xpcshell/data/compression.lzbin23 -> 0 bytes
-rw-r--r--toolkit/components/lz4/tests/xpcshell/data/worker_lz4.js146
-rw-r--r--toolkit/components/lz4/tests/xpcshell/test_lz4.js43
-rw-r--r--toolkit/components/lz4/tests/xpcshell/test_lz4_sync.js41
-rw-r--r--toolkit/components/lz4/tests/xpcshell/xpcshell.ini11
-rw-r--r--toolkit/components/mediasniffer/moz.build9
-rw-r--r--toolkit/components/mediasniffer/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/bug1079747.mp4bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/detodos.mp3bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/ff-inst.exebin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/file.mkvbin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/file.webmbin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/fl10.mp2bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/he_free.mp3bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/id3tags.mp3bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/notags-bad.mp3bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/notags-scan.mp3bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/data/notags.mp3bin512 -> 0 bytes
-rw-r--r--toolkit/components/mediasniffer/test/unit/test_mediasniffer.js105
-rw-r--r--toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js122
-rw-r--r--toolkit/components/mediasniffer/test/unit/xpcshell.ini19
-rw-r--r--toolkit/components/microformats/manifest.ini7
-rw-r--r--toolkit/components/microformats/moz.build7
-rw-r--r--toolkit/components/microformats/test/interface-tests/count-test.js107
-rw-r--r--toolkit/components/microformats/test/interface-tests/experimental-test.js37
-rw-r--r--toolkit/components/microformats/test/interface-tests/get-test.js605
-rw-r--r--toolkit/components/microformats/test/interface-tests/getParent-test.js220
-rw-r--r--toolkit/components/microformats/test/interface-tests/hasMicroformats-test.js185
-rw-r--r--toolkit/components/microformats/test/interface-tests/index.html69
-rw-r--r--toolkit/components/microformats/test/interface-tests/isMicroformat-test.js146
-rw-r--r--toolkit/components/microformats/test/lib/dates.js268
-rw-r--r--toolkit/components/microformats/test/lib/domparser.js103
-rw-r--r--toolkit/components/microformats/test/lib/domutils.js611
-rw-r--r--toolkit/components/microformats/test/lib/html.js107
-rw-r--r--toolkit/components/microformats/test/lib/isodate.js481
-rw-r--r--toolkit/components/microformats/test/lib/living-standard.js1
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-adr.js29
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-card.js85
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-entry.js52
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-event.js64
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-feed.js36
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-geo.js22
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-item.js30
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-listing.js41
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-news.js42
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-org.js24
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-product.js49
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-recipe.js47
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-resume.js34
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-review-aggregate.js40
-rw-r--r--toolkit/components/microformats/test/lib/maps/h-review.js46
-rw-r--r--toolkit/components/microformats/test/lib/maps/rel.js47
-rw-r--r--toolkit/components/microformats/test/lib/parser-implied.js439
-rw-r--r--toolkit/components/microformats/test/lib/parser-includes.js150
-rw-r--r--toolkit/components/microformats/test/lib/parser-rels.js200
-rw-r--r--toolkit/components/microformats/test/lib/parser.js1453
-rw-r--r--toolkit/components/microformats/test/lib/text.js151
-rw-r--r--toolkit/components/microformats/test/lib/url.js73
-rw-r--r--toolkit/components/microformats/test/lib/utilities.js206
-rw-r--r--toolkit/components/microformats/test/lib/version.js1
-rw-r--r--toolkit/components/microformats/test/marionette/microformats_tester.py170
-rw-r--r--toolkit/components/microformats/test/marionette/test_interface.py17
-rw-r--r--toolkit/components/microformats/test/marionette/test_modules.py17
-rw-r--r--toolkit/components/microformats/test/marionette/test_standards.py17
-rw-r--r--toolkit/components/microformats/test/module-tests/dates-test.js113
-rw-r--r--toolkit/components/microformats/test/module-tests/domutils-test.js206
-rw-r--r--toolkit/components/microformats/test/module-tests/html-test.js50
-rw-r--r--toolkit/components/microformats/test/module-tests/index.html76
-rw-r--r--toolkit/components/microformats/test/module-tests/isodate-test.js145
-rw-r--r--toolkit/components/microformats/test/module-tests/text-test.js56
-rw-r--r--toolkit/components/microformats/test/module-tests/url-test.js25
-rw-r--r--toolkit/components/microformats/test/module-tests/utilities-test.js93
-rw-r--r--toolkit/components/microformats/test/standards-tests/index.html179
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-mixedpropertries.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-tworoots.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-mixed-h-entry-mixedroots.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-mixed-h-resume-mixedroots.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-adr-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-geo-abbrpattern.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-geo-hidden.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-geo-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-geo-valuetitleclass.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-ampm.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-attendees.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-combining.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-concatenate.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-time.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-email.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-format.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-hyperlinkedphoto.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justahyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-multiple.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-name.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hcard-single.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hentry-summarycontent.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hfeed-simple.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hnews-all.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hnews-minimum.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-aggregate.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hresume-affiliation.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hresume-contact.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hresume-education.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hresume-skill.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hresume-work.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-hcard.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-justahyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-vevent.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hreview-item.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-hreview-vcard.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-includes-hcarditemref.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-includes-heventitemref.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-includes-hyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-includes-object.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v1-includes-table.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geo.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geourl.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-as-note-note.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-baseurl.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-childimplied.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-extendeddescription.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hcard.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-horghcard.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hyperlinkedphoto.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedphoto.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedurl.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justahyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-nested.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-p-property.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-card-relativeurls.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-impliedvalue-nested.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justahyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-summarycontent.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-u-property.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-urlincontent.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-ampm.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-attendees.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-combining.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-concatenate.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dates.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dt-property.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justahyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-event-time.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-implied-title.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-simple.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-abbrpattern.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-altitude.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-hidden.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-valuetitleclass.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-news-all.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-news-minimum.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-org-hyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simple.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-product-aggregate.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justahyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-product-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-all.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-minimum.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-affiliation.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-contact.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-education.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-skill.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-work.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-hevent.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-justahyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-simpleproperties.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-hyperlink.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-implieditem.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-item.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-justaname.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-photo.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-h-review-vcard.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-rel-duplicate-rels.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-rel-license.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-rel-nofollow.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-rel-rel-urls.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-rel-varying-text-duplicate-rels.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-all.js27
-rw-r--r--toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-elsewhere.js27
-rw-r--r--toolkit/components/microformats/test/static/count.html84
-rw-r--r--toolkit/components/microformats/test/static/css/mocha-custom.css9
-rw-r--r--toolkit/components/microformats/test/static/css/mocha.css270
-rw-r--r--toolkit/components/microformats/test/static/css/prettify.css65
-rw-r--r--toolkit/components/microformats/test/static/css/testrunner.css367
-rw-r--r--toolkit/components/microformats/test/static/images/logo.gifbin2943 -> 0 bytes
-rw-r--r--toolkit/components/microformats/test/static/images/photo.gifbin2943 -> 0 bytes
-rw-r--r--toolkit/components/microformats/test/static/javascript/DOMParser.js99
-rw-r--r--toolkit/components/microformats/test/static/javascript/beautify.js518
-rw-r--r--toolkit/components/microformats/test/static/javascript/chai.js5351
-rw-r--r--toolkit/components/microformats/test/static/javascript/count.js62
-rw-r--r--toolkit/components/microformats/test/static/javascript/data.js1
-rw-r--r--toolkit/components/microformats/test/static/javascript/deep-diff-0.3.1.min.js5
-rw-r--r--toolkit/components/microformats/test/static/javascript/mocha.js6573
-rw-r--r--toolkit/components/microformats/test/static/javascript/parse.js133
-rw-r--r--toolkit/components/microformats/test/static/javascript/prettify.js1479
-rw-r--r--toolkit/components/microformats/test/static/javascript/testrunner.js179
-rw-r--r--toolkit/components/microformats/test/static/parse-umd.html85
-rw-r--r--toolkit/components/microformats/test/static/parse.html127
-rw-r--r--toolkit/components/microformats/test/static/testrunner.html69
-rw-r--r--toolkit/components/mozintl/moz.build10
-rw-r--r--toolkit/components/mozintl/test/test_mozintl.js46
-rw-r--r--toolkit/components/mozintl/test/xpcshell.ini5
-rw-r--r--toolkit/components/mozprotocol/moz.build4
-rw-r--r--toolkit/components/mozprotocol/tests/browser.ini5
-rw-r--r--toolkit/components/mozprotocol/tests/browser_mozprotocol.js14
-rw-r--r--toolkit/components/mozprotocol/tests/mozprotocol.html7
-rw-r--r--toolkit/components/narrate/moz.build2
-rw-r--r--toolkit/components/narrate/test/.eslintrc.js23
-rw-r--r--toolkit/components/narrate/test/NarrateTestUtils.jsm148
-rw-r--r--toolkit/components/narrate/test/browser.ini12
-rw-r--r--toolkit/components/narrate/test/browser_narrate.js137
-rw-r--r--toolkit/components/narrate/test/browser_narrate_disable.js37
-rw-r--r--toolkit/components/narrate/test/browser_narrate_language.js73
-rw-r--r--toolkit/components/narrate/test/browser_voiceselect.js112
-rw-r--r--toolkit/components/narrate/test/browser_word_highlight.js69
-rw-r--r--toolkit/components/narrate/test/head.js87
-rw-r--r--toolkit/components/narrate/test/inferno.html238
-rw-r--r--toolkit/components/narrate/test/moby_dick.html218
-rw-r--r--toolkit/components/osfile/moz.build28
-rw-r--r--toolkit/components/osfile/tests/mochi/.eslintrc.js7
-rw-r--r--toolkit/components/osfile/tests/mochi/chrome.ini15
-rw-r--r--toolkit/components/osfile/tests/mochi/main_test_osfile_async.js443
-rw-r--r--toolkit/components/osfile/tests/mochi/test_osfile_async.xul23
-rw-r--r--toolkit/components/osfile/tests/mochi/test_osfile_back.xul46
-rw-r--r--toolkit/components/osfile/tests/mochi/test_osfile_comms.xul84
-rw-r--r--toolkit/components/osfile/tests/mochi/test_osfile_front.xul44
-rw-r--r--toolkit/components/osfile/tests/mochi/worker_handler.js34
-rw-r--r--toolkit/components/osfile/tests/mochi/worker_test_osfile_comms.js145
-rw-r--r--toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js566
-rw-r--r--toolkit/components/osfile/tests/mochi/worker_test_osfile_shared.js32
-rw-r--r--toolkit/components/osfile/tests/mochi/worker_test_osfile_unix.js201
-rw-r--r--toolkit/components/osfile/tests/mochi/worker_test_osfile_win.js211
-rw-r--r--toolkit/components/osfile/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/osfile/tests/xpcshell/head.js99
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_available_free_space.js38
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_compression.js98
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_constants.js26
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_creationDate.js31
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_duration.js91
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_exception.js89
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_file_URL_conversion.js114
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_loader.js37
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_loader/module_test_loader.js9
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_logging.js74
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_makeDir.js142
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_open.js70
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async.js16
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_append.js122
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_bytes.js39
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_copy.js113
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_flush.js30
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_largefiles.js153
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js211
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_setPermissions.js103
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_closed.js48
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_error.js63
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_kill.js100
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_win_async_setPermissions.js114
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_backupTo_option.js143
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_zerobytes.js27
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_path.js159
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_path_constants.js83
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_queue.js38
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_read_write.js103
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_remove.js56
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_removeDir.js177
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_removeEmptyDir.js55
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_reset.js95
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_shutdown.js98
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_telemetry.js63
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_unique.js88
-rw-r--r--toolkit/components/osfile/tests/xpcshell/xpcshell.ini51
-rw-r--r--toolkit/components/passwordmgr/moz.build14
-rw-r--r--toolkit/components/passwordmgr/test/.eslintrc.js13
-rw-r--r--toolkit/components/passwordmgr/test/LoginTestUtils.jsm295
-rw-r--r--toolkit/components/passwordmgr/test/authenticate.sjs228
-rw-r--r--toolkit/components/passwordmgr/test/blank.html8
-rw-r--r--toolkit/components/passwordmgr/test/browser/.eslintrc.js7
-rw-r--r--toolkit/components/passwordmgr/test/browser/authenticate.sjs110
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser.ini72
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_DOMFormHasPassword.js94
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_DOMInputPasswordAdded.js99
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_autocomplete_insecure_warning.js41
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger.js600
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_httpsUpgrade.js123
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_window_open.js144
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_context_menu.js432
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_context_menu_autocomplete_interaction.js99
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_context_menu_iframe.js144
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_exceptions_dialog.js56
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_formless_submit_chrome.js126
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms.js93
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms_streamConverter.js102
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_http_autofill.js78
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_insecurePasswordConsoleWarning.js94
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_master_password_autocomplete.js59
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_notifications.js81
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_notifications_2.js125
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_notifications_password.js145
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_notifications_username.js119
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_passwordmgr_contextmenu.js100
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js126
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js65
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js129
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js208
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js42
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js192
-rw-r--r--toolkit/components/passwordmgr/test/browser/browser_username_select_dialog.js144
-rw-r--r--toolkit/components/passwordmgr/test/browser/form_autofocus_js.html10
-rw-r--r--toolkit/components/passwordmgr/test/browser/form_basic.html12
-rw-r--r--toolkit/components/passwordmgr/test/browser/form_basic_iframe.html13
-rw-r--r--toolkit/components/passwordmgr/test/browser/form_cross_origin_insecure_action.html12
-rw-r--r--toolkit/components/passwordmgr/test/browser/form_cross_origin_secure_action.html12
-rw-r--r--toolkit/components/passwordmgr/test/browser/form_same_origin_action.html12
-rw-r--r--toolkit/components/passwordmgr/test/browser/formless_basic.html18
-rw-r--r--toolkit/components/passwordmgr/test/browser/head.js137
-rw-r--r--toolkit/components/passwordmgr/test/browser/insecure_test.html9
-rw-r--r--toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html13
-rw-r--r--toolkit/components/passwordmgr/test/browser/multiple_forms.html129
-rw-r--r--toolkit/components/passwordmgr/test/browser/streamConverter_content.sjs6
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_1.html29
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_10.html27
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_11.html25
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_11_popup.html32
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_2.html30
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_0un.html27
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_1un_1text.html31
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_3.html30
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_4.html30
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_5.html26
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_6.html27
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_8.html29
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_9.html29
-rw-r--r--toolkit/components/passwordmgr/test/browser/subtst_notifications_change_p.html32
-rw-r--r--toolkit/components/passwordmgr/test/chrome/chrome.ini13
-rw-r--r--toolkit/components/passwordmgr/test/chrome/notification_common.js111
-rw-r--r--toolkit/components/passwordmgr/test/chrome/privbrowsing_perwindowpb_iframe.html9
-rw-r--r--toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_1.html33
-rw-r--r--toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_2.html33
-rw-r--r--toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_3.html29
-rw-r--r--toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_4.html40
-rw-r--r--toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html322
-rw-r--r--toolkit/components/passwordmgr/test/chrome_timeout.js11
-rw-r--r--toolkit/components/passwordmgr/test/formsubmit.sjs37
-rw-r--r--toolkit/components/passwordmgr/test/mochitest.ini20
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/auth2/authenticate.sjs220
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/mochitest.ini69
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_autocomplete_https_upgrade.html218
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_autofill_https_upgrade.html117
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_autofill_password-only.html143
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_autofocus_js.html115
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form.html44
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_0pw.html72
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw.html167
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw_2.html109
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_1.html187
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_2.html105
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_3pw_1.html177
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_autocomplete.html859
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_html5.html164
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwevent.html55
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwonly.html213
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_bug_627616.html145
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_bug_776171.html56
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_case_differences.html147
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_form_action_1.html137
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_form_action_2.html170
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_form_action_javascript.html52
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_formless_autofill.html147
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_formless_submit.html183
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation.html191
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation_negative.html121
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_input_events.html96
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_input_events_for_identical_values.html51
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_autocomplete.html861
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_no_saved_login.html103
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_maxlength.html137
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_password_field_autocomplete.html291
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_passwords_in_type_password.html122
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_prompt.html705
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_prompt_http.html362
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_prompt_noWindow.html81
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth.html406
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html264
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_recipe_login_fields.html145
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_username_focus.html263
-rw-r--r--toolkit/components/passwordmgr/test/mochitest/test_xhr_2.html55
-rw-r--r--toolkit/components/passwordmgr/test/prompt_common.js79
-rw-r--r--toolkit/components/passwordmgr/test/pwmgr_common.js509
-rw-r--r--toolkit/components/passwordmgr/test/subtst_master_pass.html12
-rw-r--r--toolkit/components/passwordmgr/test/subtst_prompt_async.html12
-rw-r--r--toolkit/components/passwordmgr/test/test_master_password.html308
-rw-r--r--toolkit/components/passwordmgr/test/test_prompt_async.html540
-rw-r--r--toolkit/components/passwordmgr/test/test_xhr.html201
-rw-r--r--toolkit/components/passwordmgr/test/test_xml_load.html191
-rw-r--r--toolkit/components/passwordmgr/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/corruptDB.sqlitebin32772 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/key3.dbbin16384 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v1.sqlitebin8192 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v1v2.sqlitebin10240 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v2.sqlitebin11264 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v2v3.sqlitebin12288 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v3.sqlitebin11264 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v3v4.sqlitebin11264 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v4.sqlitebin294912 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v4v5.sqlitebin327680 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v5v6.sqlitebin327680 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v999-2.sqlitebin8192 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/data/signons-v999.sqlitebin11264 -> 0 bytes
-rw-r--r--toolkit/components/passwordmgr/test/unit/head.js135
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_OSCrypto_win.js75
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_context_menu.js165
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_dedupeLogins.js284
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_disabled_hosts.js196
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_getFormFields.js147
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_getPasswordFields.js156
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_getPasswordOrigin.js28
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_isOriginMatching.js40
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_legacy_empty_formSubmitURL.js107
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_legacy_validation.js76
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_logins_change.js384
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_logins_decrypt_failure.js77
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_logins_metainfo.js284
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_logins_search.js220
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_maybeImportLogin.js169
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_module_LoginImport.js243
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_module_LoginStore.js206
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_notifications.js172
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_recipes_add.js177
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_recipes_content.js39
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_removeLegacySignonFiles.js69
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_search_schemeUpgrades.js184
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_storage.js102
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_storage_mozStorage.js507
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_telemetry.js187
-rw-r--r--toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js488
-rw-r--r--toolkit/components/passwordmgr/test/unit/xpcshell.ini46
-rw-r--r--toolkit/components/perf/chrome.ini3
-rw-r--r--toolkit/components/perf/moz.build2
-rw-r--r--toolkit/components/perf/test_pm.xul48
-rw-r--r--toolkit/components/perfmonitoring/moz.build26
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/.eslintrc.js7
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser.ini15
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_AddonWatcher.js151
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample.xpibin7848 -> 0 bytes
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/bootstrap.js105
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/build.sh4
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/chrome.manifest1
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/content/framescript.js23
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/install.rdf30
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts.js91
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts_2.js25
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_compartments.html20
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_compartments.js312
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_compartments_frame.html12
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_compartments_script.js29
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/browser_webpagePerformanceAlerts.js111
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/head.js287
-rw-r--r--toolkit/components/perfmonitoring/tests/browser/install.rdf30
-rw-r--r--toolkit/components/places/moz.build6
-rw-r--r--toolkit/components/places/tests/.eslintrc.js9
-rw-r--r--toolkit/components/places/tests/PlacesTestUtils.jsm163
-rw-r--r--toolkit/components/places/tests/bookmarks/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/bookmarks/head_bookmarks.js20
-rw-r--r--toolkit/components/places/tests/bookmarks/test_1016953-renaming-uncompressed.js103
-rw-r--r--toolkit/components/places/tests/bookmarks/test_1017502-bookmarks_foreign_count.js112
-rw-r--r--toolkit/components/places/tests/bookmarks/test_1129529.js76
-rw-r--r--toolkit/components/places/tests/bookmarks/test_384228.js98
-rw-r--r--toolkit/components/places/tests/bookmarks/test_385829.js182
-rw-r--r--toolkit/components/places/tests/bookmarks/test_388695.js52
-rw-r--r--toolkit/components/places/tests/bookmarks/test_393498.js102
-rw-r--r--toolkit/components/places/tests/bookmarks/test_395101.js87
-rw-r--r--toolkit/components/places/tests/bookmarks/test_395593.js69
-rw-r--r--toolkit/components/places/tests/bookmarks/test_405938_restore_queries.js221
-rw-r--r--toolkit/components/places/tests/bookmarks/test_417228-exclude-from-backup.js141
-rw-r--r--toolkit/components/places/tests/bookmarks/test_417228-other-roots.js158
-rw-r--r--toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js91
-rw-r--r--toolkit/components/places/tests/bookmarks/test_448584.js113
-rw-r--r--toolkit/components/places/tests/bookmarks/test_458683.js131
-rw-r--r--toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js124
-rw-r--r--toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js56
-rw-r--r--toolkit/components/places/tests/bookmarks/test_675416.js56
-rw-r--r--toolkit/components/places/tests/bookmarks/test_711914.js56
-rw-r--r--toolkit/components/places/tests/bookmarks/test_818584-discard-duplicate-backups.js59
-rw-r--r--toolkit/components/places/tests/bookmarks/test_818587_compress-bookmarks-backups.js57
-rw-r--r--toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js57
-rw-r--r--toolkit/components/places/tests/bookmarks/test_992901-backup-unsorted-hierarchy.js48
-rw-r--r--toolkit/components/places/tests/bookmarks/test_997030-bookmarks-html-encode.js37
-rw-r--r--toolkit/components/places/tests/bookmarks/test_async_observers.js177
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bmindex.js124
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks.js718
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_eraseEverything.js116
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_fetch.js310
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_getRecent.js44
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_insert.js264
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_notifications.js527
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_remove.js204
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_reorder.js177
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_search.js223
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarks_update.js414
-rw-r--r--toolkit/components/places/tests/bookmarks/test_bookmarkstree_cache.js18
-rw-r--r--toolkit/components/places/tests/bookmarks/test_changeBookmarkURI.js68
-rw-r--r--toolkit/components/places/tests/bookmarks/test_getBookmarkedURIFor.js84
-rw-r--r--toolkit/components/places/tests/bookmarks/test_keywords.js310
-rw-r--r--toolkit/components/places/tests/bookmarks/test_nsINavBookmarkObserver.js640
-rw-r--r--toolkit/components/places/tests/bookmarks/test_protectRoots.js37
-rw-r--r--toolkit/components/places/tests/bookmarks/test_removeFolderTransaction_reinsert.js70
-rw-r--r--toolkit/components/places/tests/bookmarks/test_removeItem.js30
-rw-r--r--toolkit/components/places/tests/bookmarks/test_savedsearches.js209
-rw-r--r--toolkit/components/places/tests/bookmarks/xpcshell.ini50
-rw-r--r--toolkit/components/places/tests/browser/.eslintrc.js8
-rw-r--r--toolkit/components/places/tests/browser/399606-history.go-0.html11
-rw-r--r--toolkit/components/places/tests/browser/399606-httprefresh.html8
-rw-r--r--toolkit/components/places/tests/browser/399606-location.reload.html11
-rw-r--r--toolkit/components/places/tests/browser/399606-location.replace.html11
-rw-r--r--toolkit/components/places/tests/browser/399606-window.location.href.html11
-rw-r--r--toolkit/components/places/tests/browser/399606-window.location.html11
-rw-r--r--toolkit/components/places/tests/browser/461710_iframe.html8
-rw-r--r--toolkit/components/places/tests/browser/461710_link_page-2.html13
-rw-r--r--toolkit/components/places/tests/browser/461710_link_page-3.html13
-rw-r--r--toolkit/components/places/tests/browser/461710_link_page.html13
-rw-r--r--toolkit/components/places/tests/browser/461710_visited_page.html9
-rw-r--r--toolkit/components/places/tests/browser/begin.html10
-rw-r--r--toolkit/components/places/tests/browser/browser.ini26
-rw-r--r--toolkit/components/places/tests/browser/browser_bug248970.js152
-rw-r--r--toolkit/components/places/tests/browser/browser_bug399606.js77
-rw-r--r--toolkit/components/places/tests/browser/browser_bug461710.js82
-rw-r--r--toolkit/components/places/tests/browser/browser_bug646422.js51
-rw-r--r--toolkit/components/places/tests/browser/browser_bug680727.js109
-rw-r--r--toolkit/components/places/tests/browser/browser_colorAnalyzer.js259
-rw-r--r--toolkit/components/places/tests/browser/browser_double_redirect.js63
-rw-r--r--toolkit/components/places/tests/browser/browser_favicon_privatebrowsing_perwindowpb.js43
-rw-r--r--toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js152
-rw-r--r--toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js261
-rw-r--r--toolkit/components/places/tests/browser/browser_history_post.js23
-rw-r--r--toolkit/components/places/tests/browser/browser_notfound.js46
-rw-r--r--toolkit/components/places/tests/browser/browser_redirect.js61
-rw-r--r--toolkit/components/places/tests/browser/browser_settitle.js76
-rw-r--r--toolkit/components/places/tests/browser/browser_visited_notfound.js51
-rw-r--r--toolkit/components/places/tests/browser/browser_visituri.js84
-rw-r--r--toolkit/components/places/tests/browser/browser_visituri_nohistory.js42
-rw-r--r--toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js73
-rw-r--r--toolkit/components/places/tests/browser/colorAnalyzer/category-discover.pngbin1324 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/browser/colorAnalyzer/dictionaryGeneric-16.pngbin742 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/browser/colorAnalyzer/extensionGeneric-16.pngbin554 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/browser/colorAnalyzer/localeGeneric.pngbin2410 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/browser/favicon-normal16.pngbin286 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/browser/favicon-normal32.pngbin344 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/browser/favicon.html13
-rw-r--r--toolkit/components/places/tests/browser/final.html10
-rw-r--r--toolkit/components/places/tests/browser/head.js319
-rw-r--r--toolkit/components/places/tests/browser/history_post.html12
-rw-r--r--toolkit/components/places/tests/browser/history_post.sjs6
-rw-r--r--toolkit/components/places/tests/browser/redirect-target.html1
-rw-r--r--toolkit/components/places/tests/browser/redirect.sjs14
-rw-r--r--toolkit/components/places/tests/browser/redirect_once.sjs9
-rw-r--r--toolkit/components/places/tests/browser/redirect_twice.sjs9
-rw-r--r--toolkit/components/places/tests/browser/title1.html12
-rw-r--r--toolkit/components/places/tests/browser/title2.html14
-rw-r--r--toolkit/components/places/tests/chrome/.eslintrc.js8
-rw-r--r--toolkit/components/places/tests/chrome/bad_links.atom74
-rw-r--r--toolkit/components/places/tests/chrome/browser_disableglobalhistory.xul44
-rw-r--r--toolkit/components/places/tests/chrome/chrome.ini12
-rw-r--r--toolkit/components/places/tests/chrome/link-less-items-no-site-uri.rss18
-rw-r--r--toolkit/components/places/tests/chrome/link-less-items.rss19
-rw-r--r--toolkit/components/places/tests/chrome/rss_as_html.rss27
-rw-r--r--toolkit/components/places/tests/chrome/rss_as_html.rss^headers^2
-rw-r--r--toolkit/components/places/tests/chrome/sample_feed.atom23
-rw-r--r--toolkit/components/places/tests/chrome/test_303567.xul122
-rw-r--r--toolkit/components/places/tests/chrome/test_341972a.xul87
-rw-r--r--toolkit/components/places/tests/chrome/test_341972b.xul84
-rw-r--r--toolkit/components/places/tests/chrome/test_342484.xul88
-rw-r--r--toolkit/components/places/tests/chrome/test_371798.xul101
-rw-r--r--toolkit/components/places/tests/chrome/test_381357.xul85
-rw-r--r--toolkit/components/places/tests/chrome/test_browser_disableglobalhistory.xul26
-rw-r--r--toolkit/components/places/tests/chrome/test_favicon_annotations.xul168
-rw-r--r--toolkit/components/places/tests/chrome/test_reloadLivemarks.xul155
-rw-r--r--toolkit/components/places/tests/cpp/mock_Link.h229
-rw-r--r--toolkit/components/places/tests/cpp/moz.build14
-rw-r--r--toolkit/components/places/tests/cpp/places_test_harness.h413
-rw-r--r--toolkit/components/places/tests/cpp/places_test_harness_tail.h120
-rw-r--r--toolkit/components/places/tests/cpp/test_IHistory.cpp639
-rw-r--r--toolkit/components/places/tests/expiration/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/expiration/head_expiration.js124
-rw-r--r--toolkit/components/places/tests/expiration/test_analyze_runs.js118
-rw-r--r--toolkit/components/places/tests/expiration/test_annos_expire_history.js93
-rw-r--r--toolkit/components/places/tests/expiration/test_annos_expire_never.js95
-rw-r--r--toolkit/components/places/tests/expiration/test_annos_expire_policy.js189
-rw-r--r--toolkit/components/places/tests/expiration/test_annos_expire_session.js83
-rw-r--r--toolkit/components/places/tests/expiration/test_clearHistory.js157
-rw-r--r--toolkit/components/places/tests/expiration/test_debug_expiration.js225
-rw-r--r--toolkit/components/places/tests/expiration/test_idle_daily.js21
-rw-r--r--toolkit/components/places/tests/expiration/test_notifications.js38
-rw-r--r--toolkit/components/places/tests/expiration/test_notifications_onDeleteURI.js114
-rw-r--r--toolkit/components/places/tests/expiration/test_notifications_onDeleteVisits.js142
-rw-r--r--toolkit/components/places/tests/expiration/test_outdated_analyze.js72
-rw-r--r--toolkit/components/places/tests/expiration/test_pref_interval.js61
-rw-r--r--toolkit/components/places/tests/expiration/test_pref_maxpages.js124
-rw-r--r--toolkit/components/places/tests/expiration/xpcshell.ini22
-rw-r--r--toolkit/components/places/tests/favicons/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/favicons/expected-favicon-big32.jpg.pngbin3105 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/expected-favicon-big4.jpg.pngbin563 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/expected-favicon-big48.ico.pngbin1425 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/expected-favicon-big64.png.pngbin3157 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/expected-favicon-scale160x3.jpg.pngbin175 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/expected-favicon-scale3x160.jpg.pngbin169 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-big16.icobin1406 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-big32.jpgbin3494 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-big4.jpgbin4751 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-big48.icobin56646 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-big64.pngbin10698 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-normal16.pngbin286 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-normal32.pngbin344 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-scale160x3.jpgbin5095 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/favicon-scale3x160.jpgbin5059 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/favicons/head_favicons.js105
-rw-r--r--toolkit/components/places/tests/favicons/test_expireAllFavicons.js39
-rw-r--r--toolkit/components/places/tests/favicons/test_favicons_conversions.js131
-rw-r--r--toolkit/components/places/tests/favicons/test_getFaviconDataForPage.js57
-rw-r--r--toolkit/components/places/tests/favicons/test_getFaviconURLForPage.js51
-rw-r--r--toolkit/components/places/tests/favicons/test_moz-anno_favicon_mime_type.js90
-rw-r--r--toolkit/components/places/tests/favicons/test_page-icon_protocol.js66
-rw-r--r--toolkit/components/places/tests/favicons/test_query_result_favicon_changed_on_child.js74
-rw-r--r--toolkit/components/places/tests/favicons/test_replaceFaviconData.js264
-rw-r--r--toolkit/components/places/tests/favicons/test_replaceFaviconDataFromDataURL.js352
-rw-r--r--toolkit/components/places/tests/favicons/xpcshell.ini32
-rw-r--r--toolkit/components/places/tests/head_common.js869
-rw-r--r--toolkit/components/places/tests/history/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/history/head_history.js19
-rw-r--r--toolkit/components/places/tests/history/test_insert.js257
-rw-r--r--toolkit/components/places/tests/history/test_remove.js360
-rw-r--r--toolkit/components/places/tests/history/test_removeVisits.js316
-rw-r--r--toolkit/components/places/tests/history/test_removeVisitsByFilter.js345
-rw-r--r--toolkit/components/places/tests/history/test_updatePlaces_sameUri_titleChanged.js52
-rw-r--r--toolkit/components/places/tests/history/xpcshell.ini9
-rw-r--r--toolkit/components/places/tests/migration/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/migration/head_migration.js46
-rw-r--r--toolkit/components/places/tests/migration/places_v10.sqlitebin172032 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v11.sqlitebin1081344 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v17.sqlitebin1212416 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v19.sqlitebin1179648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v21.sqlitebin1179648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v22.sqlitebin1179648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v23.sqlitebin1179648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v24.sqlitebin1179648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v25.sqlitebin1179648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v26.sqlitebin1179648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v27.sqlitebin1212416 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v28.sqlitebin1212416 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v29.sqlitebin1245184 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v30.sqlitebin1212416 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v31.sqlitebin1146880 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v32.sqlitebin1146880 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v33.sqlitebin1146880 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v34.sqlitebin1146880 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v35.sqlitebin1146880 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/places_v6.sqlitebin155648 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_downgraded.js19
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v11.js48
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v19.js42
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v24.js36
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v25.js30
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v26.js98
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v27.js77
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v31.js46
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v34.js141
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v34_no_roots.js21
-rw-r--r--toolkit/components/places/tests/migration/test_current_from_v6.js38
-rw-r--r--toolkit/components/places/tests/migration/xpcshell.ini36
-rw-r--r--toolkit/components/places/tests/moz.build67
-rw-r--r--toolkit/components/places/tests/queries/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/queries/head_queries.js370
-rw-r--r--toolkit/components/places/tests/queries/readme.txt16
-rw-r--r--toolkit/components/places/tests/queries/test_415716.js108
-rw-r--r--toolkit/components/places/tests/queries/test_abstime-annotation-domain.js210
-rw-r--r--toolkit/components/places/tests/queries/test_abstime-annotation-uri.js162
-rw-r--r--toolkit/components/places/tests/queries/test_async.js371
-rw-r--r--toolkit/components/places/tests/queries/test_containersQueries_sorting.js411
-rw-r--r--toolkit/components/places/tests/queries/test_history_queries_tags_liveUpdate.js200
-rw-r--r--toolkit/components/places/tests/queries/test_history_queries_titles_liveUpdate.js210
-rw-r--r--toolkit/components/places/tests/queries/test_onlyBookmarked.js128
-rw-r--r--toolkit/components/places/tests/queries/test_queryMultipleFolder.js65
-rw-r--r--toolkit/components/places/tests/queries/test_querySerialization.js797
-rw-r--r--toolkit/components/places/tests/queries/test_redirects.js311
-rw-r--r--toolkit/components/places/tests/queries/test_results-as-tag-contents-query.js127
-rw-r--r--toolkit/components/places/tests/queries/test_results-as-visit.js119
-rw-r--r--toolkit/components/places/tests/queries/test_searchTerms_includeHidden.js84
-rw-r--r--toolkit/components/places/tests/queries/test_searchterms-bookmarklets.js70
-rw-r--r--toolkit/components/places/tests/queries/test_searchterms-domain.js125
-rw-r--r--toolkit/components/places/tests/queries/test_searchterms-uri.js87
-rw-r--r--toolkit/components/places/tests/queries/test_sort-date-site-grouping.js225
-rw-r--r--toolkit/components/places/tests/queries/test_sorting.js1265
-rw-r--r--toolkit/components/places/tests/queries/test_tags.js743
-rw-r--r--toolkit/components/places/tests/queries/test_transitions.js178
-rw-r--r--toolkit/components/places/tests/queries/xpcshell.ini34
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/data/engine-rel-searchform.xml5
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/data/engine-suggestions.xml14
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/head_autocomplete.js505
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_416211.js22
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_416214.js39
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_417798.js51
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_418257.js67
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_422277.js19
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_autocomplete_functional.js171
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_autocomplete_on_value_removed_479089.js39
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_autofill_default_behavior.js310
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_avoid_middle_complete.js179
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_avoid_stripping_to_empty_tokens.js41
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_casing.js157
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_do_not_trim.js91
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_download_embed_bookmarks.js71
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_dupe_urls.js23
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_empty_search.js98
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_enabled.js68
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_escape_self.js31
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_extension_matches.js384
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_ignore_protocol.js24
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_keyword_search.js73
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_keyword_search_actions.js149
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_keywords.js78
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_match_beginning.js54
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_multi_word_search.js68
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_query_url.js68
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_remote_tab_matches.js203
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_search_engine_alias.js51
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_search_engine_current.js45
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_search_engine_host.js49
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_search_engine_restyle.js43
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_search_suggestions.js651
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_special_search.js447
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_swap_protocol.js153
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_tab_matches.js125
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_trimming.js313
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_typed.js84
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_visit_url.js186
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_word_boundary_search.js175
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/test_zero_frecency.js35
-rw-r--r--toolkit/components/places/tests/unifiedcomplete/xpcshell.ini49
-rw-r--r--toolkit/components/places/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/places/tests/unit/bookmarks.corrupt.html36
-rw-r--r--toolkit/components/places/tests/unit/bookmarks.json1
-rw-r--r--toolkit/components/places/tests/unit/bookmarks.preplaces.html35
-rw-r--r--toolkit/components/places/tests/unit/bookmarks_html_singleframe.html10
-rw-r--r--toolkit/components/places/tests/unit/bug476292.sqlitebin139264 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/unit/corruptDB.sqlitebin32772 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/unit/default.sqlitebin1081344 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/unit/head_bookmarks.js20
-rw-r--r--toolkit/components/places/tests/unit/livemark.xml17
-rw-r--r--toolkit/components/places/tests/unit/mobile_bookmarks_folder_import.json1
-rw-r--r--toolkit/components/places/tests/unit/mobile_bookmarks_folder_merge.json1
-rw-r--r--toolkit/components/places/tests/unit/mobile_bookmarks_multiple_folders.json1
-rw-r--r--toolkit/components/places/tests/unit/mobile_bookmarks_root_import.json1
-rw-r--r--toolkit/components/places/tests/unit/mobile_bookmarks_root_merge.json1
-rw-r--r--toolkit/components/places/tests/unit/nsDummyObserver.js48
-rw-r--r--toolkit/components/places/tests/unit/nsDummyObserver.manifest4
-rw-r--r--toolkit/components/places/tests/unit/places.sparse.sqlitebin221184 -> 0 bytes
-rw-r--r--toolkit/components/places/tests/unit/test_000_frecency.js267
-rw-r--r--toolkit/components/places/tests/unit/test_1085291.js42
-rw-r--r--toolkit/components/places/tests/unit/test_1105208.js24
-rw-r--r--toolkit/components/places/tests/unit/test_1105866.js63
-rw-r--r--toolkit/components/places/tests/unit/test_317472.js65
-rw-r--r--toolkit/components/places/tests/unit/test_331487.js95
-rw-r--r--toolkit/components/places/tests/unit/test_384370.js173
-rw-r--r--toolkit/components/places/tests/unit/test_385397.js142
-rw-r--r--toolkit/components/places/tests/unit/test_399264_query_to_string.js51
-rw-r--r--toolkit/components/places/tests/unit/test_399264_string_to_query.js75
-rw-r--r--toolkit/components/places/tests/unit/test_399266.js78
-rw-r--r--toolkit/components/places/tests/unit/test_402799.js62
-rw-r--r--toolkit/components/places/tests/unit/test_405497.js57
-rw-r--r--toolkit/components/places/tests/unit/test_408221.js165
-rw-r--r--toolkit/components/places/tests/unit/test_412132.js136
-rw-r--r--toolkit/components/places/tests/unit/test_413784.js118
-rw-r--r--toolkit/components/places/tests/unit/test_415460.js43
-rw-r--r--toolkit/components/places/tests/unit/test_415757.js102
-rw-r--r--toolkit/components/places/tests/unit/test_418643_removeFolderChildren.js143
-rw-r--r--toolkit/components/places/tests/unit/test_419731.js96
-rw-r--r--toolkit/components/places/tests/unit/test_419792_node_tags_property.js49
-rw-r--r--toolkit/components/places/tests/unit/test_425563.js74
-rw-r--r--toolkit/components/places/tests/unit/test_429505_remove_shortcuts.js35
-rw-r--r--toolkit/components/places/tests/unit/test_433317_query_title_update.js38
-rw-r--r--toolkit/components/places/tests/unit/test_433525_hasChildren_crash.js56
-rw-r--r--toolkit/components/places/tests/unit/test_452777.js36
-rw-r--r--toolkit/components/places/tests/unit/test_454977.js124
-rw-r--r--toolkit/components/places/tests/unit/test_463863.js60
-rw-r--r--toolkit/components/places/tests/unit/test_485442_crash_bug_nsNavHistoryQuery_GetUri.js21
-rw-r--r--toolkit/components/places/tests/unit/test_486978_sort_by_date_queries.js129
-rw-r--r--toolkit/components/places/tests/unit/test_536081.js56
-rw-r--r--toolkit/components/places/tests/unit/test_PlacesSearchAutocompleteProvider.js133
-rw-r--r--toolkit/components/places/tests/unit/test_PlacesUtils_asyncGetBookmarkIds.js77
-rw-r--r--toolkit/components/places/tests/unit/test_PlacesUtils_invalidateCachedGuidFor.js25
-rw-r--r--toolkit/components/places/tests/unit/test_PlacesUtils_lazyobservers.js47
-rw-r--r--toolkit/components/places/tests/unit/test_adaptive.js406
-rw-r--r--toolkit/components/places/tests/unit/test_adaptive_bug527311.js141
-rw-r--r--toolkit/components/places/tests/unit/test_analyze.js28
-rw-r--r--toolkit/components/places/tests/unit/test_annotations.js363
-rw-r--r--toolkit/components/places/tests/unit/test_asyncExecuteLegacyQueries.js95
-rw-r--r--toolkit/components/places/tests/unit/test_async_history_api.js1118
-rw-r--r--toolkit/components/places/tests/unit/test_async_in_batchmode.js55
-rw-r--r--toolkit/components/places/tests/unit/test_async_transactions.js1739
-rw-r--r--toolkit/components/places/tests/unit/test_autocomplete_stopSearch_no_throw.js39
-rw-r--r--toolkit/components/places/tests/unit/test_bookmark_catobs.js57
-rw-r--r--toolkit/components/places/tests/unit/test_bookmarks_html.js385
-rw-r--r--toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js143
-rw-r--r--toolkit/components/places/tests/unit/test_bookmarks_html_import_tags.js57
-rw-r--r--toolkit/components/places/tests/unit/test_bookmarks_html_singleframe.js32
-rw-r--r--toolkit/components/places/tests/unit/test_bookmarks_json.js241
-rw-r--r--toolkit/components/places/tests/unit/test_bookmarks_restore_notification.js325
-rw-r--r--toolkit/components/places/tests/unit/test_bookmarks_setNullTitle.js44
-rw-r--r--toolkit/components/places/tests/unit/test_broken_folderShortcut_result.js79
-rw-r--r--toolkit/components/places/tests/unit/test_browserhistory.js129
-rw-r--r--toolkit/components/places/tests/unit/test_bug636917_isLivemark.js35
-rw-r--r--toolkit/components/places/tests/unit/test_childlessTags.js117
-rw-r--r--toolkit/components/places/tests/unit/test_corrupt_telemetry.js31
-rw-r--r--toolkit/components/places/tests/unit/test_crash_476292.js28
-rw-r--r--toolkit/components/places/tests/unit/test_database_replaceOnStartup.js46
-rw-r--r--toolkit/components/places/tests/unit/test_download_history.js283
-rw-r--r--toolkit/components/places/tests/unit/test_frecency.js294
-rw-r--r--toolkit/components/places/tests/unit/test_frecency_observers.js84
-rw-r--r--toolkit/components/places/tests/unit/test_frecency_zero_updated.js30
-rw-r--r--toolkit/components/places/tests/unit/test_getChildIndex.js69
-rw-r--r--toolkit/components/places/tests/unit/test_getPlacesInfo.js112
-rw-r--r--toolkit/components/places/tests/unit/test_history.js184
-rw-r--r--toolkit/components/places/tests/unit/test_history_autocomplete_tags.js185
-rw-r--r--toolkit/components/places/tests/unit/test_history_catobs.js55
-rw-r--r--toolkit/components/places/tests/unit/test_history_clear.js169
-rw-r--r--toolkit/components/places/tests/unit/test_history_notifications.js38
-rw-r--r--toolkit/components/places/tests/unit/test_history_observer.js215
-rw-r--r--toolkit/components/places/tests/unit/test_history_sidebar.js447
-rw-r--r--toolkit/components/places/tests/unit/test_hosts_triggers.js226
-rw-r--r--toolkit/components/places/tests/unit/test_import_mobile_bookmarks.js292
-rw-r--r--toolkit/components/places/tests/unit/test_isPageInDB.js10
-rw-r--r--toolkit/components/places/tests/unit/test_isURIVisited.js84
-rw-r--r--toolkit/components/places/tests/unit/test_isvisited.js75
-rw-r--r--toolkit/components/places/tests/unit/test_keywords.js548
-rw-r--r--toolkit/components/places/tests/unit/test_lastModified.js34
-rw-r--r--toolkit/components/places/tests/unit/test_markpageas.js61
-rw-r--r--toolkit/components/places/tests/unit/test_mozIAsyncLivemarks.js514
-rw-r--r--toolkit/components/places/tests/unit/test_multi_queries.js53
-rw-r--r--toolkit/components/places/tests/unit/test_multi_word_tags.js150
-rw-r--r--toolkit/components/places/tests/unit/test_nsINavHistoryViewer.js256
-rw-r--r--toolkit/components/places/tests/unit/test_null_interfaces.js98
-rw-r--r--toolkit/components/places/tests/unit/test_onItemChanged_tags.js52
-rw-r--r--toolkit/components/places/tests/unit/test_pageGuid_bookmarkGuid.js179
-rw-r--r--toolkit/components/places/tests/unit/test_placeURIs.js42
-rw-r--r--toolkit/components/places/tests/unit/test_placesTxn.js937
-rw-r--r--toolkit/components/places/tests/unit/test_preventive_maintenance.js1356
-rw-r--r--toolkit/components/places/tests/unit/test_preventive_maintenance_checkAndFixDatabase.js50
-rw-r--r--toolkit/components/places/tests/unit/test_preventive_maintenance_runTasks.js46
-rw-r--r--toolkit/components/places/tests/unit/test_promiseBookmarksTree.js256
-rw-r--r--toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js49
-rw-r--r--toolkit/components/places/tests/unit/test_result_sort.js139
-rw-r--r--toolkit/components/places/tests/unit/test_resultsAsVisit_details.js85
-rw-r--r--toolkit/components/places/tests/unit/test_sql_guid_functions.js106
-rw-r--r--toolkit/components/places/tests/unit/test_svg_favicon.js31
-rw-r--r--toolkit/components/places/tests/unit/test_sync_utils.js1150
-rw-r--r--toolkit/components/places/tests/unit/test_tag_autocomplete_search.js137
-rw-r--r--toolkit/components/places/tests/unit/test_tagging.js189
-rw-r--r--toolkit/components/places/tests/unit/test_telemetry.js166
-rw-r--r--toolkit/components/places/tests/unit/test_update_frecency_after_delete.js151
-rw-r--r--toolkit/components/places/tests/unit/test_utils_backups_create.js90
-rw-r--r--toolkit/components/places/tests/unit/test_utils_getURLsForContainerNode.js181
-rw-r--r--toolkit/components/places/tests/unit/test_utils_setAnnotationsFor.js79
-rw-r--r--toolkit/components/places/tests/unit/test_visitsInDB.js12
-rw-r--r--toolkit/components/places/tests/unit/xpcshell.ini163
-rw-r--r--toolkit/components/printing/moz.build7
-rw-r--r--toolkit/components/printing/tests/browser.ini5
-rw-r--r--toolkit/components/printing/tests/browser_page_change_print_original.js60
-rw-r--r--toolkit/components/printing/tests/file_page_change_print_original_1.html8
-rw-r--r--toolkit/components/printing/tests/file_page_change_print_original_2.html1
-rw-r--r--toolkit/components/promiseworker/moz.build13
-rw-r--r--toolkit/components/promiseworker/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/promiseworker/tests/xpcshell/data/chrome.manifest1
-rw-r--r--toolkit/components/promiseworker/tests/xpcshell/data/worker.js34
-rw-r--r--toolkit/components/promiseworker/tests/xpcshell/test_Promise.js117
-rw-r--r--toolkit/components/promiseworker/tests/xpcshell/xpcshell.ini9
-rw-r--r--toolkit/components/prompts/moz.build2
-rw-r--r--toolkit/components/prompts/test/.eslintrc.js7
-rw-r--r--toolkit/components/prompts/test/bug619644_inner.html7
-rw-r--r--toolkit/components/prompts/test/bug625187_iframe.html16
-rw-r--r--toolkit/components/prompts/test/chromeScript.js241
-rw-r--r--toolkit/components/prompts/test/mochitest.ini19
-rw-r--r--toolkit/components/prompts/test/prompt_common.js158
-rw-r--r--toolkit/components/prompts/test/test_bug619644.html76
-rw-r--r--toolkit/components/prompts/test/test_bug620145.html105
-rw-r--r--toolkit/components/prompts/test/test_dom_prompts.html208
-rw-r--r--toolkit/components/prompts/test/test_modal_prompts.html1184
-rw-r--r--toolkit/components/prompts/test/test_modal_select.html146
-rw-r--r--toolkit/components/prompts/test/test_subresources_prompts.html202
-rw-r--r--toolkit/components/reader/moz.build11
-rw-r--r--toolkit/components/reader/test/browser.ini15
-rw-r--r--toolkit/components/reader/test/browser_bug1124271_readerModePinnedTab.js47
-rw-r--r--toolkit/components/reader/test/browser_readerMode.js220
-rw-r--r--toolkit/components/reader/test/browser_readerMode_hidden_nodes.js53
-rw-r--r--toolkit/components/reader/test/browser_readerMode_with_anchor.js21
-rw-r--r--toolkit/components/reader/test/head.js126
-rw-r--r--toolkit/components/reader/test/readerModeArticle.html25
-rw-r--r--toolkit/components/reader/test/readerModeArticleHiddenNodes.html22
-rw-r--r--toolkit/components/remotebrowserutils/moz.build2
-rw-r--r--toolkit/components/remotebrowserutils/tests/browser/.eslintrc.js7
-rw-r--r--toolkit/components/remotebrowserutils/tests/browser/browser.ini6
-rw-r--r--toolkit/components/remotebrowserutils/tests/browser/browser_RemoteWebNavigation.js156
-rw-r--r--toolkit/components/remotebrowserutils/tests/browser/dummy_page.html7
-rw-r--r--toolkit/components/satchel/moz.build12
-rw-r--r--toolkit/components/satchel/test/.eslintrc.js7
-rw-r--r--toolkit/components/satchel/test/browser/.eslintrc.js7
-rw-r--r--toolkit/components/satchel/test/browser/browser.ini5
-rw-r--r--toolkit/components/satchel/test/browser/browser_privbrowsing_perwindowpb.js63
-rw-r--r--toolkit/components/satchel/test/mochitest.ini19
-rw-r--r--toolkit/components/satchel/test/parent_utils.js149
-rw-r--r--toolkit/components/satchel/test/satchel_common.js274
-rw-r--r--toolkit/components/satchel/test/subtst_form_submission_1.html38
-rw-r--r--toolkit/components/satchel/test/subtst_privbrowsing.html22
-rw-r--r--toolkit/components/satchel/test/test_bug_511615.html194
-rw-r--r--toolkit/components/satchel/test/test_bug_787624.html88
-rw-r--r--toolkit/components/satchel/test/test_datalist_with_caching.html139
-rw-r--r--toolkit/components/satchel/test/test_form_autocomplete.html1074
-rw-r--r--toolkit/components/satchel/test/test_form_autocomplete_with_list.html506
-rw-r--r--toolkit/components/satchel/test/test_form_submission.html537
-rw-r--r--toolkit/components/satchel/test/test_form_submission_cap.html85
-rw-r--r--toolkit/components/satchel/test/test_form_submission_cap2.html190
-rw-r--r--toolkit/components/satchel/test/test_password_autocomplete.html107
-rw-r--r--toolkit/components/satchel/test/test_popup_direction.html61
-rw-r--r--toolkit/components/satchel/test/test_popup_enter_event.html86
-rw-r--r--toolkit/components/satchel/test/unit/.eslintrc.js7
-rw-r--r--toolkit/components/satchel/test/unit/asyncformhistory_expire.sqlitebin98304 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_1000.sqlitebin164864 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_CORRUPT.sqlite1
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_apitest.sqlitebin5120 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_autocomplete.sqlitebin72704 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_v3.sqlitebin5120 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_v3v4.sqlitebin6144 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_v999a.sqlitebin6144 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/formhistory_v999b.sqlitebin4096 -> 0 bytes
-rw-r--r--toolkit/components/satchel/test/unit/head_satchel.js102
-rw-r--r--toolkit/components/satchel/test/unit/perf_autocomplete.js140
-rw-r--r--toolkit/components/satchel/test/unit/test_async_expire.js168
-rw-r--r--toolkit/components/satchel/test/unit/test_autocomplete.js266
-rw-r--r--toolkit/components/satchel/test/unit/test_db_corrupt.js89
-rw-r--r--toolkit/components/satchel/test/unit/test_db_update_v4.js60
-rw-r--r--toolkit/components/satchel/test/unit/test_db_update_v4b.js58
-rw-r--r--toolkit/components/satchel/test/unit/test_db_update_v999a.js75
-rw-r--r--toolkit/components/satchel/test/unit/test_db_update_v999b.js92
-rw-r--r--toolkit/components/satchel/test/unit/test_history_api.js457
-rw-r--r--toolkit/components/satchel/test/unit/test_notify.js158
-rw-r--r--toolkit/components/satchel/test/unit/test_previous_result.js25
-rw-r--r--toolkit/components/satchel/test/unit/xpcshell.ini26
-rw-r--r--toolkit/components/social/test/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/sqlite/moz.build6
-rw-r--r--toolkit/components/sqlite/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/sqlite/tests/xpcshell/data/chrome.manifest1
-rw-r--r--toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_internal.js279
-rw-r--r--toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_shared.js39
-rw-r--r--toolkit/components/sqlite/tests/xpcshell/test_sqlite_internal.js43
-rw-r--r--toolkit/components/sqlite/tests/xpcshell/xpcshell.ini10
-rw-r--r--toolkit/components/startup/moz.build10
-rw-r--r--toolkit/components/startup/tests/browser/.eslintrc.js7
-rw-r--r--toolkit/components/startup/tests/browser/beforeunload.html10
-rw-r--r--toolkit/components/startup/tests/browser/browser.ini8
-rw-r--r--toolkit/components/startup/tests/browser/browser_bug511456.js47
-rw-r--r--toolkit/components/startup/tests/browser/browser_bug537449.js53
-rw-r--r--toolkit/components/startup/tests/browser/browser_crash_detection.js23
-rw-r--r--toolkit/components/startup/tests/browser/head.js29
-rw-r--r--toolkit/components/startup/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/startup/tests/unit/head_startup.js30
-rw-r--r--toolkit/components/startup/tests/unit/test_startup_crash.js300
-rw-r--r--toolkit/components/startup/tests/unit/xpcshell.ini6
-rw-r--r--toolkit/components/telemetry/Makefile.in17
-rw-r--r--toolkit/components/telemetry/moz.build9
-rw-r--r--toolkit/components/telemetry/tests/addons/dictionary/install.rdf25
-rw-r--r--toolkit/components/telemetry/tests/addons/experiment/install.rdf16
-rw-r--r--toolkit/components/telemetry/tests/addons/extension-2/install.rdf16
-rw-r--r--toolkit/components/telemetry/tests/addons/extension/install.rdf16
-rw-r--r--toolkit/components/telemetry/tests/addons/long-fields/install.rdf24
-rw-r--r--toolkit/components/telemetry/tests/addons/restartless/install.rdf24
-rw-r--r--toolkit/components/telemetry/tests/addons/signed/META-INF/manifest.mf7
-rw-r--r--toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.rsabin4190 -> 0 bytes
-rw-r--r--toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.sf4
-rw-r--r--toolkit/components/telemetry/tests/addons/signed/install.rdf24
-rw-r--r--toolkit/components/telemetry/tests/addons/system/install.rdf24
-rw-r--r--toolkit/components/telemetry/tests/addons/theme/install.rdf16
-rw-r--r--toolkit/components/telemetry/tests/browser/browser.ini5
-rw-r--r--toolkit/components/telemetry/tests/browser/browser_TelemetryGC.js193
-rw-r--r--toolkit/components/telemetry/tests/search/chrome.manifest3
-rw-r--r--toolkit/components/telemetry/tests/search/searchTest.jarbin867 -> 0 bytes
-rw-r--r--toolkit/components/telemetry/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/telemetry/tests/unit/TelemetryArchiveTesting.jsm86
-rw-r--r--toolkit/components/telemetry/tests/unit/engine.xml7
-rw-r--r--toolkit/components/telemetry/tests/unit/head.js319
-rw-r--r--toolkit/components/telemetry/tests/unit/test_ChildHistograms.js107
-rw-r--r--toolkit/components/telemetry/tests/unit/test_PingAPI.js502
-rw-r--r--toolkit/components/telemetry/tests/unit/test_SubsessionChaining.js236
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryController.js507
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryControllerBuildID.js70
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryControllerShutdown.js70
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryController_idle.js73
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js1522
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryEvents.js249
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryFlagClear.js14
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js127
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryLockCount.js53
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryLog.js51
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryReportingPolicy.js268
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js574
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetrySend.js427
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetrySendOldPings.js547
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetrySession.js2029
-rw-r--r--toolkit/components/telemetry/tests/unit/test_TelemetryTimestamps.js77
-rw-r--r--toolkit/components/telemetry/tests/unit/test_ThreadHangStats.js102
-rw-r--r--toolkit/components/telemetry/tests/unit/test_nsITelemetry.js883
-rw-r--r--toolkit/components/telemetry/tests/unit/xpcshell.ini61
-rw-r--r--toolkit/components/terminator/moz.build10
-rw-r--r--toolkit/components/terminator/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/terminator/tests/xpcshell/test_terminator_record.js108
-rw-r--r--toolkit/components/terminator/tests/xpcshell/test_terminator_reload.js85
-rw-r--r--toolkit/components/terminator/tests/xpcshell/xpcshell.ini8
-rw-r--r--toolkit/components/thumbnails/moz.build4
-rw-r--r--toolkit/components/thumbnails/test/.eslintrc.js8
-rw-r--r--toolkit/components/thumbnails/test/authenticate.sjs220
-rw-r--r--toolkit/components/thumbnails/test/background_red.html3
-rw-r--r--toolkit/components/thumbnails/test/background_red_redirect.sjs10
-rw-r--r--toolkit/components/thumbnails/test/background_red_scroll.html3
-rw-r--r--toolkit/components/thumbnails/test/browser.ini38
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_bad_url.js23
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_basic.js20
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_captureIfMissing.js35
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_during_capture.js49
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_while_idle.js38
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_destroy_browser.js33
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_no_alert.js13
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_no_auth_prompt.js21
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_sent.js40
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_stored.js32
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_no_duplicates.js31
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_queueing.js38
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_redirect.js39
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bg_timeout.js24
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bug726727.js19
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bug727765.js29
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js42
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_capture.js20
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_expiration.js97
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_privacy.js74
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_redirect.js30
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_storage.js112
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_storage_migrate3.js102
-rw-r--r--toolkit/components/thumbnails/test/browser_thumbnails_update.js169
-rw-r--r--toolkit/components/thumbnails/test/head.js356
-rw-r--r--toolkit/components/thumbnails/test/privacy_cache_control.sjs16
-rw-r--r--toolkit/components/thumbnails/test/test_thumbnails_interfaces.js25
-rw-r--r--toolkit/components/thumbnails/test/thumbnails_background.sjs79
-rw-r--r--toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js31
-rw-r--r--toolkit/components/thumbnails/test/thumbnails_update.sjs56
-rw-r--r--toolkit/components/thumbnails/test/xpcshell.ini6
-rw-r--r--toolkit/components/timermanager/moz.build9
-rw-r--r--toolkit/components/timermanager/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/timermanager/tests/unit/consumerNotifications.js519
-rw-r--r--toolkit/components/timermanager/tests/unit/xpcshell.ini9
-rw-r--r--toolkit/components/tooltiptext/moz.build5
-rw-r--r--toolkit/components/tooltiptext/tests/browser.ini7
-rw-r--r--toolkit/components/tooltiptext/tests/browser_bug329212.js35
-rw-r--r--toolkit/components/tooltiptext/tests/browser_bug331772_xul_tooltiptext_in_html.js19
-rw-r--r--toolkit/components/tooltiptext/tests/browser_bug561623.js24
-rw-r--r--toolkit/components/tooltiptext/tests/browser_bug581947.js87
-rw-r--r--toolkit/components/tooltiptext/tests/browser_input_file_tooltips.js122
-rw-r--r--toolkit/components/tooltiptext/tests/title_test.svg59
-rw-r--r--toolkit/components/tooltiptext/tests/xul_tooltiptext.xhtml14
-rw-r--r--toolkit/components/url-classifier/moz.build2
-rw-r--r--toolkit/components/url-classifier/tests/UrlClassifierTestUtils.jsm98
-rw-r--r--toolkit/components/url-classifier/tests/gtest/Common.cpp78
-rw-r--r--toolkit/components/url-classifier/tests/gtest/Common.h26
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp279
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp97
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp88
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestPerProviderDirectory.cpp98
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestProtocolParser.cpp159
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestRiceDeltaDecoder.cpp165
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestSafeBrowsingProtobuf.cpp24
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestSafebrowsingHash.cpp52
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestTable.cpp47
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp755
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestUrlClassifierUtils.cpp276
-rw-r--r--toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp559
-rw-r--r--toolkit/components/url-classifier/tests/gtest/moz.build27
-rw-r--r--toolkit/components/url-classifier/tests/jar.mn2
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/.eslintrc.js8
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/allowlistAnnotatedFrame.html144
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/bad.css1
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/bad.css^headers^1
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/basic.vtt27
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/basic.vtt^headers^1
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/bug_1281083.html35
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/chrome.ini23
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedFrame.html213
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedPBFrame.html24
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/classifierCommon.js112
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/classifierFrame.html57
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/classifierHelper.js201
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/cleanWorker.js10
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/dnt.html31
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/dnt.sjs9
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/evil.css1
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/evil.css^headers^1
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/evil.js1
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/evil.js^headers^2
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/evilWorker.js3
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/gethash.sjs130
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/gethashFrame.html62
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/good.js1
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/import.css3
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/mochitest.ini39
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/ping.sjs16
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/raptor.jpgbin49629 -> 0 bytes
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/seek.webmbin215529 -> 0 bytes
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_allowlisted_annotations.html56
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_bug1254766.html305
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_classified_annotations.html50
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_classifier.html65
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_classifier_changetablepref.html149
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_classifier_worker.html76
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_classify_ping.html121
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_classify_track.html162
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_donottrack.html150
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_gethash.html157
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_lookup_system_principal.html29
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_privatebrowsing_trackingprotection.html154
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_safebrowsing_bug1272239.html87
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_bug1157081.html107
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_whitelist.html153
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/track.html7
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/unwantedWorker.js3
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/update.sjs114
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/vp9.webmbin97465 -> 0 bytes
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/whitelistFrame.html15
-rw-r--r--toolkit/components/url-classifier/tests/mochitest/workerFrame.html65
-rw-r--r--toolkit/components/url-classifier/tests/moz.build18
-rw-r--r--toolkit/components/url-classifier/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/url-classifier/tests/unit/data/digest1.chunkbin939 -> 0 bytes
-rw-r--r--toolkit/components/url-classifier/tests/unit/data/digest2.chunk2
-rw-r--r--toolkit/components/url-classifier/tests/unit/head_urlclassifier.js429
-rw-r--r--toolkit/components/url-classifier/tests/unit/tail_urlclassifier.js1
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_addsub.js488
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_backoff.js89
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_bug1274685_unowned_list.js32
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_dbservice.js314
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_digest256.js147
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_hashcompleter.js403
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_listmanager.js376
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_partial.js825
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_pref.js14
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_prefixset.js232
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_provider_url.js34
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_safebrowsing_protobuf.js23
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_streamupdater.js288
-rw-r--r--toolkit/components/url-classifier/tests/unit/test_threat_type_conversion.js37
-rw-r--r--toolkit/components/url-classifier/tests/unit/xpcshell.ini24
-rw-r--r--toolkit/components/url-classifier/tests/unittests.xul188
-rw-r--r--toolkit/components/urlformatter/moz.build18
-rw-r--r--toolkit/components/urlformatter/tests/unit/.eslintrc.js7
-rw-r--r--toolkit/components/urlformatter/tests/unit/head_urlformatter.js16
-rw-r--r--toolkit/components/urlformatter/tests/unit/test_urlformatter.js63
-rw-r--r--toolkit/components/urlformatter/tests/unit/xpcshell.ini6
-rw-r--r--toolkit/components/viewsource/moz.build12
-rw-r--r--toolkit/components/viewsource/test/.eslintrc.js7
-rw-r--r--toolkit/components/viewsource/test/browser/.eslintrc.js7
-rw-r--r--toolkit/components/viewsource/test/browser/browser.ini12
-rw-r--r--toolkit/components/viewsource/test/browser/browser_bug464222.js12
-rw-r--r--toolkit/components/viewsource/test/browser/browser_bug699356.js19
-rw-r--r--toolkit/components/viewsource/test/browser/browser_bug713810.js23
-rw-r--r--toolkit/components/viewsource/test/browser/browser_contextmenu.js107
-rw-r--r--toolkit/components/viewsource/test/browser/browser_gotoline.js36
-rw-r--r--toolkit/components/viewsource/test/browser/browser_srcdoc.js30
-rw-r--r--toolkit/components/viewsource/test/browser/browser_viewsourceprefs.js136
-rw-r--r--toolkit/components/viewsource/test/browser/file_bug464222.html1
-rw-r--r--toolkit/components/viewsource/test/browser/head.js200
-rw-r--r--toolkit/components/viewsource/test/chrome.ini4
-rw-r--r--toolkit/components/viewsource/test/file_empty.html1
-rw-r--r--toolkit/components/viewsource/test/test_bug428653.html45
-rw-r--r--toolkit/components/workerloader/moz.build9
-rw-r--r--toolkit/components/workerloader/tests/.eslintrc.js7
-rw-r--r--toolkit/components/workerloader/tests/chrome.ini15
-rw-r--r--toolkit/components/workerloader/tests/moduleA-depends.js14
-rw-r--r--toolkit/components/workerloader/tests/moduleB-dependency.js11
-rw-r--r--toolkit/components/workerloader/tests/moduleC-circular.js18
-rw-r--r--toolkit/components/workerloader/tests/moduleD-circular.js11
-rw-r--r--toolkit/components/workerloader/tests/moduleE-throws-during-require.js10
-rw-r--r--toolkit/components/workerloader/tests/moduleF-syntax-error.js6
-rw-r--r--toolkit/components/workerloader/tests/moduleG-throws-later.js12
-rw-r--r--toolkit/components/workerloader/tests/moduleH-module-dot-exports.js12
-rw-r--r--toolkit/components/workerloader/tests/test_loading.xul41
-rw-r--r--toolkit/components/workerloader/tests/utils_mainthread.js34
-rw-r--r--toolkit/components/workerloader/tests/utils_worker.js32
-rw-r--r--toolkit/components/workerloader/tests/worker_handler.js34
-rw-r--r--toolkit/components/workerloader/tests/worker_test_loading.js121
-rw-r--r--toolkit/components/xulstore/moz.build7
-rw-r--r--toolkit/components/xulstore/tests/chrome/.eslintrc.js7
-rw-r--r--toolkit/components/xulstore/tests/chrome/animals.rdf142
-rw-r--r--toolkit/components/xulstore/tests/chrome/chrome.ini6
-rw-r--r--toolkit/components/xulstore/tests/chrome/test_persistence.xul31
-rw-r--r--toolkit/components/xulstore/tests/chrome/window_persistence.xul98
-rw-r--r--toolkit/components/xulstore/tests/xpcshell/.eslintrc.js7
-rw-r--r--toolkit/components/xulstore/tests/xpcshell/localstore.rdf31
-rw-r--r--toolkit/components/xulstore/tests/xpcshell/test_XULStore.js199
-rw-r--r--toolkit/components/xulstore/tests/xpcshell/xpcshell.ini6
1699 files changed, 67 insertions, 173475 deletions
diff --git a/toolkit/components/aboutcheckerboard/moz.build b/toolkit/components/aboutcheckerboard/moz.build
index 91d6e9662..eb4454d28 100644
--- a/toolkit/components/aboutcheckerboard/moz.build
+++ b/toolkit/components/aboutcheckerboard/moz.build
@@ -4,7 +4,4 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-JAR_MANIFESTS += ['jar.mn']
-
-with Files('**'):
- BUG_COMPONENT = ('Core', 'Panning and Zooming')
+JAR_MANIFESTS += ['jar.mn'] \ No newline at end of file
diff --git a/toolkit/components/aboutmemory/moz.build b/toolkit/components/aboutmemory/moz.build
index dd3f71d8c..aac3a838c 100644
--- a/toolkit/components/aboutmemory/moz.build
+++ b/toolkit/components/aboutmemory/moz.build
@@ -4,9 +4,4 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-MOCHITEST_CHROME_MANIFESTS += ['tests/chrome.ini']
-
JAR_MANIFESTS += ['jar.mn']
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'about:memory')
diff --git a/toolkit/components/aboutmemory/tests/.eslintrc.js b/toolkit/components/aboutmemory/tests/.eslintrc.js
deleted file mode 100644
index 2c669d844..000000000
--- a/toolkit/components/aboutmemory/tests/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/aboutmemory/tests/chrome.ini b/toolkit/components/aboutmemory/tests/chrome.ini
deleted file mode 100644
index c25bc30a0..000000000
--- a/toolkit/components/aboutmemory/tests/chrome.ini
+++ /dev/null
@@ -1,28 +0,0 @@
-[DEFAULT]
-skip-if = os == 'android'
-support-files =
- crash-dump-diff1.json
- crash-dump-diff2.json
- crash-dump-good.json
- memory-reports-bad.json
- memory-reports-diff1.json
- memory-reports-diff2.json
- memory-reports-good.json
- remote.xul
-
-[test_aboutmemory.xul]
-subsuite = clipboard
-[test_aboutmemory2.xul]
-subsuite = clipboard
-[test_aboutmemory3.xul]
-subsuite = clipboard
-[test_aboutmemory4.xul]
-subsuite = clipboard
-[test_aboutmemory5.xul]
-subsuite = clipboard
-skip-if = asan # Bug 1116230
-[test_aboutmemory6.xul]
-[test_memoryReporters.xul]
-[test_memoryReporters2.xul]
-[test_sqliteMultiReporter.xul]
-[test_dumpGCAndCCLogsToFile.xul]
diff --git a/toolkit/components/aboutmemory/tests/crash-dump-diff1.json b/toolkit/components/aboutmemory/tests/crash-dump-diff1.json
deleted file mode 100644
index d41bbcc61..000000000
--- a/toolkit/components/aboutmemory/tests/crash-dump-diff1.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "foo": 1,
- "blah": 2,
- "memory_report": {
- "version": 1,
- "hasMozMallocUsableSize": true,
- "reports": [
- {"process": "Main Process (pid NNN)", "path": "heap-allocated", "kind": 2, "units": 0, "amount": 262144000, "description": "Heap allocated."}
- ]
- }
-}
diff --git a/toolkit/components/aboutmemory/tests/crash-dump-diff2.json b/toolkit/components/aboutmemory/tests/crash-dump-diff2.json
deleted file mode 100644
index 8f9451f62..000000000
--- a/toolkit/components/aboutmemory/tests/crash-dump-diff2.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "foo": 3,
- "blah": 4,
- "memory_report": {
- "version": 1,
- "hasMozMallocUsableSize": true,
- "reports": [
- {"process": "Main Process (pid NNN)", "path": "heap-allocated", "kind": 2, "units": 0, "amount": 262144001, "description": "Heap allocated."}
- ]
- }
-}
diff --git a/toolkit/components/aboutmemory/tests/crash-dump-good.json b/toolkit/components/aboutmemory/tests/crash-dump-good.json
deleted file mode 100644
index 6bee54d59..000000000
--- a/toolkit/components/aboutmemory/tests/crash-dump-good.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "foo": 1,
- "blah": 2,
- "memory_report": {
- "version": 1,
- "hasMozMallocUsableSize": true,
- "reports": [
- {"process": "Main Process (pid NNN)", "path": "heap-allocated", "kind": 2, "units": 0, "amount": 262144000, "description": "Heap allocated."},
- {"process": "Main Process (pid NNN)", "path": "other/b", "kind": 2, "units": 0, "amount": 104857, "description": "Other b."},
- {"process": "Main Process (pid NNN)", "path": "other/a", "kind": 2, "units": 0, "amount": 209715, "description": "Other a."},
- {"process": "Main Process (pid NNN)", "path": "explicit/a/b", "kind": 1, "units": 0, "amount": 52428800, "description": "A b."}
- ]
- }
-}
diff --git a/toolkit/components/aboutmemory/tests/memory-reports-bad.json b/toolkit/components/aboutmemory/tests/memory-reports-bad.json
deleted file mode 100644
index 61a2092b1..000000000
--- a/toolkit/components/aboutmemory/tests/memory-reports-bad.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "version": 1
-}
diff --git a/toolkit/components/aboutmemory/tests/memory-reports-diff1.json b/toolkit/components/aboutmemory/tests/memory-reports-diff1.json
deleted file mode 100644
index 0bfe0b26b..000000000
--- a/toolkit/components/aboutmemory/tests/memory-reports-diff1.json
+++ /dev/null
@@ -1,45 +0,0 @@
-{
- "version": 1,
- "hasMozMallocUsableSize": true,
- "reports": [
- {"process": "P", "path": "explicit/xpcom/category-manager", "kind": 1, "units": 0, "amount": 56848, "description": "Desc."},
- {"process": "P", "path": "explicit/storage/prefixset/goog-phish-shavar", "kind": 1, "units": 0, "amount": 680000, "description": "Desc."},
-
- {"process": "P", "path": "explicit/spell-check", "kind": 1, "units": 0, "amount": 4, "description": "Desc."},
- {"process": "P", "path": "explicit/spell-check", "kind": 1, "units": 0, "amount": 5, "description": "Desc."},
-
- {"process": "P", "path": "page-faults-soft", "kind": 2, "units": 2, "amount": 61013, "description": "Desc."},
-
- {"process": "P", "path": "foobar", "kind": 2, "units": 0, "amount": 100, "description": "Desc."},
- {"process": "P", "path": "zero1", "kind": 2, "units": 0, "amount": 0, "description": "Desc."},
-
- {"process": "P", "path": "a/b", "kind": 2, "units": 0, "amount": 1000000, "description": "Desc."},
- {"process": "P", "path": "a/c/d", "kind": 2, "units": 0, "amount": 2000000, "description": "Desc."},
- {"process": "P", "path": "a/c/e", "kind": 2, "units": 0, "amount": 2000000, "description": "Desc."},
- {"process": "P", "path": "a/c/f", "kind": 2, "units": 0, "amount": 3000000, "description": "Desc."},
- {"process": "P", "path": "a/c/g", "kind": 2, "units": 0, "amount": 3000000, "description": "Desc."},
- {"process": "P", "path": "a/h", "kind": 2, "units": 0, "amount": 1000, "description": "Desc."},
-
- {"process": "P2 (pid 22)", "path": "p1 (pid 123)", "kind": 2, "units": 0, "amount": 33, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p2 (blah, pid=123)", "kind": 2, "units": 0, "amount": 33, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p3/zone(0x1234)/p3", "kind": 2, "units": 0, "amount": 33, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p4/js-zone(0x1234)/p4", "kind": 2, "units": 0, "amount": 33, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p5/worker(foo.com, 0x1234)/p5", "kind": 2, "units": 0, "amount": 33, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "explicit/window-objects/top(bar.com, id=123)/...", "kind": 0, "units": 0, "amount": 33, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p6/z-moz-nullprincipal:{85e250f3-57ae-46c4-a11e-4176dd39d9c5}/p6", "kind": 2, "units": 0, "amount": 33, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p7/js-main-runtime-compartments/system/jar:file:\\\\\\temp_xyz\\firefox\\omni.ja!/p7", "kind": 2, "units": 0, "amount": 33, "description": "Desc."},
-
- {"process": "P3", "path": "p3", "kind": 2, "units": 0, "amount": 55, "description": "Desc."},
-
- {"process": "P5", "path": "p5", "kind": 2, "units": 0, "amount": 0, "description": "Desc."},
-
- {"process": "P7", "path": "p7", "kind": 2, "units": 0, "amount": 5, "description": "Desc."},
-
- {"process": "P8", "path": "p8/a/b/c/d", "kind": 2, "units": 0, "amount": 3, "description": "Desc."},
- {"process": "P8", "path": "p8/a/b/c/e", "kind": 2, "units": 0, "amount": 4, "description": "Desc."},
- {"process": "P8", "path": "p8/a/b/f", "kind": 2, "units": 0, "amount": 5, "description": "Desc."},
- {"process": "P8", "path": "p8/a/g/h", "kind": 2, "units": 0, "amount": 6, "description": "Desc."},
- {"process": "P8", "path": "p8/a/g/i", "kind": 2, "units": 0, "amount": 7, "description": "Desc."}
- ]
-}
-
diff --git a/toolkit/components/aboutmemory/tests/memory-reports-diff2.json b/toolkit/components/aboutmemory/tests/memory-reports-diff2.json
deleted file mode 100644
index e2ef4caa7..000000000
--- a/toolkit/components/aboutmemory/tests/memory-reports-diff2.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "version": 1,
- "hasMozMallocUsableSize": true,
- "reports": [
- {"process": "P", "path": "explicit/xpcom/category-manager", "kind": 1, "units": 0, "amount": 56849, "description": "Desc."},
- {"process": "P", "path": "explicit/storage/prefixset/goog-phish-shavar", "kind": 1, "units": 0, "amount": 670000, "description": "Desc."},
-
- {"process": "P", "path": "explicit/spell-check", "kind": 1, "units": 0, "amount": 3, "description": "Desc."},
-
- {"process": "P", "path": "page-faults-soft", "kind": 2, "units": 2, "amount": 61013, "description": "Desc."},
-
- {"process": "P", "path": "canvas-2d-pixel-bytes", "kind": 2, "units": 0, "amount": 1000, "description": "Desc."},
- {"process": "P", "path": "canvas-2d-pixel-bytes", "kind": 2, "units": 0, "amount": 2000, "description": "Desc."},
-
- {"process": "P", "path": "foobaz", "kind": 2, "units": 0, "amount": 0, "description": "Desc."},
-
- {"process": "P", "path": "a/b", "kind": 2, "units": 0, "amount": 2000000, "description": "Desc."},
- {"process": "P", "path": "a/c/d", "kind": 2, "units": 0, "amount": 2998000, "description": "Desc."},
- {"process": "P", "path": "a/c/e", "kind": 2, "units": 0, "amount": 1001000, "description": "Desc."},
- {"process": "P", "path": "a/c/f", "kind": 2, "units": 0, "amount": 3001000, "description": "Desc."},
- {"process": "P", "path": "a/c/g", "kind": 2, "units": 0, "amount": 3001000, "description": "Desc."},
- {"process": "P", "path": "a/h", "kind": 2, "units": 0, "amount": 2000, "description": "Desc."},
-
- {"process": "P2 (pid 22)", "path": "p1 (pid 456)", "kind": 2, "units": 0, "amount": 44, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p2 (blah, pid=456)", "kind": 2, "units": 0, "amount": 44, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p3/zone(0x5678)/p3", "kind": 2, "units": 0, "amount": 44, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p4/js-zone(0x5678)/p4", "kind": 2, "units": 0, "amount": 44, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p5/worker(foo.com, 0x5678)/p5", "kind": 2, "units": 0, "amount": 44, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "explicit/window-objects/top(bar.com, id=456)/...", "kind": 0, "units": 0, "amount": 44, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p6/z-moz-nullprincipal:{161effaa-c1f7-4010-a08e-e7c9aea01aed}/p6", "kind": 2, "units": 0, "amount": 44, "description": "Desc."},
- {"process": "P2 (pid 22)", "path": "p7/js-main-runtime-compartments/system/jar:file:\\\\\\temp_abc\\firefox\\omni.ja!/p7", "kind": 2, "units": 0, "amount": 44, "description": "Desc."},
-
- {"process": "P4", "path": "p4", "kind": 2, "units": 0, "amount": 66, "description": "Desc."},
-
- {"process": "P6", "path": "p6", "kind": 2, "units": 0, "amount": 0, "description": "Desc."},
-
- {"process": "P7", "path": "p7/b", "kind": 2, "units": 0, "amount": 3, "description": "Desc."},
- {"process": "P7", "path": "p7/c", "kind": 2, "units": 0, "amount": 4, "description": "Desc."},
-
- {"process": "P8", "path": "p8/a/b", "kind": 2, "units": 0, "amount": 1, "description": "Desc."},
- {"process": "P8", "path": "p8/a/g", "kind": 2, "units": 0, "amount": 2, "description": "Desc."}
- ]
-}
-
diff --git a/toolkit/components/aboutmemory/tests/memory-reports-good.json b/toolkit/components/aboutmemory/tests/memory-reports-good.json
deleted file mode 100644
index 013b4b125..000000000
--- a/toolkit/components/aboutmemory/tests/memory-reports-good.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "version": 1,
- "hasMozMallocUsableSize": true,
- "reports": [
- {"process": "Main Process (pid NNN)", "path": "heap-allocated", "kind": 2, "units": 0, "amount": 262144000, "description": "Heap allocated."},
- {"process": "Main Process (pid NNN)", "path": "other/b", "kind": 2, "units": 0, "amount": 104857, "description": "Other b."},
- {"process": "Main Process (pid NNN)", "path": "other/a", "kind": 2, "units": 0, "amount": 209715, "description": "Other a."},
- {"process": "Main Process (pid NNN)", "path": "explicit/a/b", "kind": 1, "units": 0, "amount": 52428800, "description": "A b."},
-
- {"process": "Main Process (pid NNN)", "path": "size/a", "kind": 1, "units": 0, "amount": 1024, "description": "non-sentence"},
- {"process": "Main Process (pid NNN)", "path": "rss/a", "kind": 1, "units": 0, "amount": 1024, "description": "non-sentence"},
- {"process": "Main Process (pid NNN)", "path": "pss/a", "kind": 1, "units": 0, "amount": 1024, "description": "non-sentence"},
- {"process": "Main Process (pid NNN)", "path": "swap/a", "kind": 1, "units": 0, "amount": 1024, "description": "non-sentence"},
- {"process": "Main Process (pid NNN)", "path": "compartments/system/a", "kind": 1, "units": 0, "amount": 1024, "description": ""},
- {"process": "Main Process (pid NNN)", "path": "ghost-windows/a", "kind": 1, "units": 0, "amount": 1024, "description": ""},
-
- {"process": "Main Process (pid NNN)", "path": "redundant/should-be-ignored", "kind": 1, "units": 0, "amount": 1024, "description": ""},
-
- {"process": "Heap-unclassified process", "path": "heap-allocated", "kind": 2, "units": 0, "amount": 262144000, "description": "Heap allocated."},
- {"process": "Heap-unclassified process", "path": "explicit/a/b", "kind": 1, "units": 0, "amount": 52428800, "description": "A b."},
- {"process": "Heap-unclassified process", "path": "explicit/heap-unclassified", "kind": 1, "units": 0, "amount": 209715200, "description": "Heap unclassified"},
-
- {"process": "Explicit-only process", "path": "explicit/a/b", "kind": 1, "units": 0, "amount": 100000, "description": "A b."},
-
- {"process": "Other-only process", "path": "a/b", "kind": 1, "units": 0, "amount": 100000, "description": "A b."},
- {"process": "Other-only process", "path": "a/c", "kind": 1, "units": 0, "amount": 100000, "description": "A c."},
- {"process": "Other-only process", "path": "heap-allocated", "kind": 1, "units": 0, "amount": 500000, "description": "D."}
- ]
-}
diff --git a/toolkit/components/aboutmemory/tests/remote.xul b/toolkit/components/aboutmemory/tests/remote.xul
deleted file mode 100644
index 7d6910130..000000000
--- a/toolkit/components/aboutmemory/tests/remote.xul
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-<window title="Remote browser"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
- <!-- test results are displayed in the html:body -->
- <p>Remote browser</p>
-
- <browser type="content" src="about:blank" id="remote" remote="true"/>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_aboutmemory.xul b/toolkit/components/aboutmemory/tests/test_aboutmemory.xul
deleted file mode 100644
index bfeab4c7b..000000000
--- a/toolkit/components/aboutmemory/tests/test_aboutmemory.xul
+++ /dev/null
@@ -1,602 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="about:memory"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
-
- <!-- This file uses fake memory reporters to test the presentation of memory
- reports in about:memory. test_memoryReporters.xul uses the real
- memory reporters to test whether the memory reporters are producing
- sensible results. -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml"></body>
-
- <!-- test code goes here -->
- <script type="application/javascript">
- <![CDATA[
- "use strict";
-
- SimpleTest.expectAssertions(27);
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
- const Cr = Components.results;
- let mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
- getService(Ci.nsIMemoryReporterManager);
-
- // Hide all the real reporters; we'll restore them at the end.
- mgr.blockRegistrationAndHideExistingReporters();
-
- // Setup various fake-but-deterministic reporters.
- const KB = 1024;
- const MB = KB * KB;
- const NONHEAP = Ci.nsIMemoryReporter.KIND_NONHEAP;
- const HEAP = Ci.nsIMemoryReporter.KIND_HEAP;
- const OTHER = Ci.nsIMemoryReporter.KIND_OTHER;
-
- const BYTES = Ci.nsIMemoryReporter.UNITS_BYTES;
- const COUNT = Ci.nsIMemoryReporter.UNITS_COUNT;
- const COUNT_CUMULATIVE = Ci.nsIMemoryReporter.UNITS_COUNT_CUMULATIVE;
- const PERCENTAGE = Ci.nsIMemoryReporter.UNITS_PERCENTAGE;
-
- let fakeReporters = [
- { collectReports: function(aCbObj, aClosure, aAnonymize) {
- function f(aP, aK, aU, aA) {
- aCbObj.callback("", aP, aK, aU, aA, "Desc.", aClosure);
- }
- f("heap-allocated", OTHER, BYTES, 500 * MB);
- f("heap-unallocated", OTHER, BYTES, 100 * MB);
- f("explicit/a", HEAP, BYTES, 222 * MB);
- f("explicit/b/a", HEAP, BYTES, 85 * MB);
- f("explicit/b/b", HEAP, BYTES, 75 * MB);
- f("explicit/b/c/a", HEAP, BYTES, 70 * MB);
- f("explicit/b/c/b", HEAP, BYTES, 2 * MB); // omitted
- f("explicit/g/a", HEAP, BYTES, 6 * MB);
- f("explicit/g/b", HEAP, BYTES, 5 * MB);
- f("explicit/g/other", HEAP, BYTES, 4 * MB);
- // A degenerate tree with the same name as a non-degenerate tree should
- // work ok.
- f("explicit", OTHER, BYTES, 888 * MB);
- f("other1/a/b", OTHER, BYTES, 111 * MB);
- f("other1/c/d", OTHER, BYTES, 22 * MB);
- f("other1/c/e", OTHER, BYTES, 33 * MB);
- f("other4", OTHER, COUNT_CUMULATIVE, 777);
- f("other4", OTHER, COUNT_CUMULATIVE, 111);
- f("other3/a/b/c/d/e", OTHER, PERCENTAGE, 2000);
- f("other3/a/b/c/d/f", OTHER, PERCENTAGE, 10);
- f("other3/a/b/c/d/g", OTHER, PERCENTAGE, 5);
- f("other3/a/b/c/d/g", OTHER, PERCENTAGE, 5);
- // Check that a rounded-up-to-100.00% value is shown as "100.0%" (i.e. one
- // decimal point).
- f("other6/big", OTHER, COUNT, 99999);
- f("other6/small", OTHER, COUNT, 1);
- // Check that a 0 / 0 is handled correctly.
- f("other7/zero", OTHER, BYTES, 0);
- // These compartments ones shouldn't be displayed.
- f("compartments/user/foo", OTHER, COUNT, 1);
- f("compartments/system/foo", OTHER, COUNT, 1);
- }
- },
- { collectReports: function(aCbObj, aClosure, aAnonymize) {
- function f(aP, aK, aU, aA) {
- aCbObj.callback("", aP, aK, aU, aA, "Desc.", aClosure);
- }
- f("explicit/c/d", NONHEAP, BYTES, 13 * MB);
- f("explicit/c/d", NONHEAP, BYTES, 10 * MB); // dup
- f("explicit/c/other", NONHEAP, BYTES, 77 * MB);
- f("explicit/cc", NONHEAP, BYTES, 13 * MB);
- f("explicit/cc", NONHEAP, BYTES, 10 * MB); // dup
- f("explicit/d", NONHEAP, BYTES, 499 * KB); // omitted
- f("explicit/e", NONHEAP, BYTES, 100 * KB); // omitted
- f("explicit/f/g/h/i", HEAP, BYTES, 10 * MB);
- f("explicit/f/g/h/j", HEAP, BYTES, 10 * MB);
- }
- },
- { collectReports: function(aCbObj, aClosure, aAnonymize) {
- function f(aP, aK, aU, aA) {
- aCbObj.callback("", aP, aK, aU, aA, "Desc.", aClosure);
- }
- f("other3", OTHER, COUNT, 777);
- f("other2", OTHER, BYTES, 222 * MB);
- f("perc2", OTHER, PERCENTAGE, 10000);
- f("perc1", OTHER, PERCENTAGE, 4567);
- f("compartments/user/https:\\\\very-long-url.com\\very-long\\oh-so-long\\really-quite-long.html?a=2&b=3&c=4&d=5&e=abcdefghijklmnopqrstuvwxyz&f=123456789123456789123456789", OTHER, COUNT, 1);
- }
- },
- { collectReports: function(aCbObj, aClosure, aAnonymize) {
- function f(aP) {
- aCbObj.callback("", aP, OTHER, COUNT, 1, "Desc.", aClosure);
- }
- f("compartments/user/bar");
- f("compartments/system/bar");
- }
- }
- ];
- for (let i = 0; i < fakeReporters.length; i++) {
- mgr.registerStrongReporterEvenIfBlocked(fakeReporters[i]);
- }
-
- // The main process always comes first when we display about:memory. The
- // remaining processes are sorted by their |resident| values (starting with
- // the largest). Processes without a |resident| memory reporter are saved
- // for the end.
- let fakeReporters2 = [
- { collectReports: function(aCbObj, aClosure, aAnonymize) {
- function f(aP1, aP2, aK, aU, aA) {
- aCbObj.callback(aP1, aP2, aK, aU, aA, "Desc.", aClosure);
- }
- f("2nd", "heap-allocated", OTHER, BYTES,1000* MB);
- f("2nd", "heap-unallocated",OTHER, BYTES,100 * MB);
- f("2nd", "explicit/a/b/c", HEAP, BYTES,497 * MB);
- f("2nd", "explicit/a/b/c", HEAP, BYTES, 1 * MB); // dup: merge
- f("2nd", "explicit/a/b/c", HEAP, BYTES, 1 * MB); // dup: merge
- f("2nd", "explicit/flip\\the\\backslashes",
- HEAP, BYTES,200 * MB);
- f("2nd", "explicit/compartment(compartment-url)",
- HEAP, BYTES,200 * MB);
- f("2nd", "other0", OTHER, BYTES,666 * MB);
- f("2nd", "other1", OTHER, BYTES,111 * MB);
-
- // Check that we can handle "heap-allocated" not being present.
- f("3rd", "explicit/a/b", HEAP, BYTES,333 * MB);
- f("3rd", "explicit/a/c", HEAP, BYTES,444 * MB);
- f("3rd", "other1", OTHER, BYTES, 1 * MB);
- f("3rd", "resident", OTHER, BYTES,100 * MB);
-
- // Invalid values (negative, too-big) should be identified.
- f("4th", "heap-allocated", OTHER, BYTES,100 * MB);
- f("4th", "resident", OTHER, BYTES,200 * MB);
- f("4th", "explicit/js/compartment(http:\\\\too-big.com\\)/stuff",
- HEAP, BYTES,150 * MB);
- f("4th", "explicit/ok", HEAP, BYTES, 5 * MB);
- f("4th", "explicit/neg1", NONHEAP, BYTES, -2 * MB);
- // -111 becomes "-0.00MB" in non-verbose mode, and getting the negative
- // sign in there correctly is non-trivial.
- f("4th", "other1", OTHER, BYTES,-111);
- f("4th", "other2", OTHER, BYTES,-222 * MB);
- f("4th", "other3", OTHER, COUNT, -333);
- f("4th", "other4", OTHER, COUNT_CUMULATIVE, -444);
- f("4th", "other5", OTHER, PERCENTAGE, -555);
- f("4th", "other6", OTHER, PERCENTAGE, 66666);
-
- // If a negative value is within a collapsed sub-tree in non-verbose mode,
- // we should get the warning at the top and the relevant sub-trees should
- // be expanded, even in non-verbose mode.
- f("5th", "heap-allocated", OTHER, BYTES,100 * MB);
- f("5th", "explicit/big", HEAP, BYTES, 99 * MB);
- f("5th", "explicit/a/pos", HEAP, BYTES, 40 * KB);
- f("5th", "explicit/a/neg1", NONHEAP, BYTES,-20 * KB);
- f("5th", "explicit/a/neg2", NONHEAP, BYTES,-10 * KB);
- f("5th", "explicit/b/c/d/e", NONHEAP, BYTES, 20 * KB);
- f("5th", "explicit/b/c/d/f", NONHEAP, BYTES,-60 * KB);
- f("5th", "explicit/b/c/g/h", NONHEAP, BYTES, 10 * KB);
- f("5th", "explicit/b/c/i/j", NONHEAP, BYTES, 5 * KB);
- }
- }
- ];
- for (let i = 0; i < fakeReporters2.length; i++) {
- mgr.registerStrongReporterEvenIfBlocked(fakeReporters2[i]);
- }
- fakeReporters = fakeReporters.concat(fakeReporters2);
- ]]>
- </script>
-
- <iframe id="amFrame" height="300" src="about:memory"></iframe>
- <!-- vary the capitalization to make sure that works -->
- <iframe id="amvFrame" height="300" src="About:Memory"></iframe>
-
- <script type="application/javascript">
- <![CDATA[
- let amExpectedText =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-623.58 MB (100.0%) -- explicit\n\
-├──232.00 MB (37.20%) -- b\n\
-│ ├───85.00 MB (13.63%) ── a\n\
-│ ├───75.00 MB (12.03%) ── b\n\
-│ └───72.00 MB (11.55%) -- c\n\
-│ ├──70.00 MB (11.23%) ── a\n\
-│ └───2.00 MB (00.32%) ── b\n\
-├──222.00 MB (35.60%) ── a\n\
-├──100.00 MB (16.04%) -- c\n\
-│ ├───77.00 MB (12.35%) ── other\n\
-│ └───23.00 MB (03.69%) ── d [2]\n\
-├───23.00 MB (03.69%) ── cc [2]\n\
-├───20.00 MB (03.21%) -- f/g/h\n\
-│ ├──10.00 MB (01.60%) ── i\n\
-│ └──10.00 MB (01.60%) ── j\n\
-├───15.00 MB (02.41%) ++ g\n\
-├───11.00 MB (01.76%) ── heap-unclassified\n\
-└────0.58 MB (00.09%) ++ (2 tiny)\n\
-\n\
-Other Measurements\n\
-\n\
-5 (100.0%) -- compartments\n\
-├──3 (60.00%) -- user\n\
-│ ├──1 (20.00%) ── bar\n\
-│ ├──1 (20.00%) ── foo\n\
-│ └──1 (20.00%) ── https://very-long-url.com/very-long/oh-so-long/really-quite-long.html?a=2&b=3&c=4&d=5&e=abcdefghijklmnopqrstuvwxyz&f=123456789123456789123456789\n\
-└──2 (40.00%) -- system\n\
- ├──1 (20.00%) ── bar\n\
- └──1 (20.00%) ── foo\n\
-\n\
-166.00 MB (100.0%) -- other1\n\
-├──111.00 MB (66.87%) ── a/b\n\
-└───55.00 MB (33.13%) -- c\n\
- ├──33.00 MB (19.88%) ── e\n\
- └──22.00 MB (13.25%) ── d\n\
-\n\
-20.20% (100.0%) -- other3\n\
-└──20.20% (100.0%) -- a/b/c/d\n\
- ├──20.00% (99.01%) ── e\n\
- └───0.20% (00.99%) ++ (2 tiny)\n\
-\n\
-100,000 (100.0%) -- other6\n\
-├───99,999 (100.0%) ── big\n\
-└────────1 (00.00%) ── small\n\
-\n\
-0.00 MB (100.0%) -- other7\n\
-└──0.00 MB (100.0%) ── zero\n\
-\n\
-888.00 MB ── explicit\n\
-500.00 MB ── heap-allocated\n\
-100.00 MB ── heap-unallocated\n\
-222.00 MB ── other2\n\
- 777 ── other3\n\
- 888 ── other4 [2]\n\
- 45.67% ── perc1\n\
- 100.00% ── perc2\n\
-\n\
-End of Main Process\n\
-4th\n\
-\n\
-WARNING: the following values are negative or unreasonably large.\n\
-\n\
- explicit/js/compartment(http://too-big.com/)/stuff\n\
- explicit/(2 tiny)\n\
- explicit/(2 tiny)/neg1\n\
- explicit/(2 tiny)/heap-unclassified\n\
- other1\n\
- other2\n\
- other3\n\
- other4\n\
- other5 \n\
-\n\
-This indicates a defect in one or more memory reporters. The invalid values are highlighted.\n\
-Explicit Allocations\n\
-\n\
-98.00 MB (100.0%) -- explicit\n\
-├──150.00 MB (153.06%) ── js/compartment(http://too-big.com/)/stuff [?!]\n\
-├───5.00 MB (05.10%) ── ok\n\
-└──-57.00 MB (-58.16%) -- (2 tiny) [?!]\n\
- ├───-2.00 MB (-2.04%) ── neg1 [?!]\n\
- └──-55.00 MB (-56.12%) ── heap-unclassified [?!]\n\
-\n\
-Other Measurements\n\
-\n\
- 100.00 MB ── heap-allocated\n\
- -0.00 MB ── other1 [?!]\n\
--222.00 MB ── other2 [?!]\n\
- -333 ── other3 [?!]\n\
- -444 ── other4 [?!]\n\
- -5.55% ── other5 [?!]\n\
- 666.66% ── other6\n\
- 200.00 MB ── resident\n\
-\n\
-End of 4th\n\
-3rd\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
-777.00 MB (100.0%) -- explicit\n\
-└──777.00 MB (100.0%) -- a\n\
- ├──444.00 MB (57.14%) ── c\n\
- └──333.00 MB (42.86%) ── b\n\
-\n\
-Other Measurements\n\
-\n\
- 1.00 MB ── other1\n\
-100.00 MB ── resident\n\
-\n\
-End of 3rd\n\
-2nd\n\
-Explicit Allocations\n\
-\n\
-1,000.00 MB (100.0%) -- explicit\n\
-├────499.00 MB (49.90%) ── a/b/c [3]\n\
-├────200.00 MB (20.00%) ── compartment(compartment-url)\n\
-├────200.00 MB (20.00%) ── flip/the/backslashes\n\
-└────101.00 MB (10.10%) ── heap-unclassified\n\
-\n\
-Other Measurements\n\
-\n\
-1,000.00 MB ── heap-allocated\n\
- 100.00 MB ── heap-unallocated\n\
- 666.00 MB ── other0\n\
- 111.00 MB ── other1\n\
-\n\
-End of 2nd\n\
-5th\n\
-\n\
-WARNING: the following values are negative or unreasonably large.\n\
-\n\
- explicit/(3 tiny)/a/neg2\n\
- explicit/(3 tiny)/a/neg1\n\
- explicit/(3 tiny)/b/c\n\
- explicit/(3 tiny)/b/c/d\n\
- explicit/(3 tiny)/b/c/d/f \n\
-\n\
-This indicates a defect in one or more memory reporters. The invalid values are highlighted.\n\
-Explicit Allocations\n\
-\n\
-99.95 MB (100.0%) -- explicit\n\
-├──99.00 MB (99.05%) ── big\n\
-└───0.95 MB (00.95%) -- (3 tiny)\n\
- ├──0.96 MB (00.96%) ── heap-unclassified\n\
- ├──0.01 MB (00.01%) -- a\n\
- │ ├──0.04 MB (00.04%) ── pos\n\
- │ ├──-0.01 MB (-0.01%) ── neg2 [?!]\n\
- │ └──-0.02 MB (-0.02%) ── neg1 [?!]\n\
- └──-0.02 MB (-0.02%) -- b/c [?!]\n\
- ├───0.01 MB (00.01%) ── g/h\n\
- ├───0.00 MB (00.00%) ── i/j\n\
- └──-0.04 MB (-0.04%) -- d [?!]\n\
- ├───0.02 MB (00.02%) ── e\n\
- └──-0.06 MB (-0.06%) ── f [?!]\n\
-\n\
-Other Measurements\n\
-\n\
-100.00 MB ── heap-allocated\n\
-\n\
-End of 5th\n\
-";
-
- let amvExpectedText =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-653,876,224 B (100.0%) -- explicit\n\
-├──243,269,632 B (37.20%) -- b\n\
-│ ├───89,128,960 B (13.63%) ── a\n\
-│ ├───78,643,200 B (12.03%) ── b\n\
-│ └───75,497,472 B (11.55%) -- c\n\
-│ ├──73,400,320 B (11.23%) ── a\n\
-│ └───2,097,152 B (00.32%) ── b\n\
-├──232,783,872 B (35.60%) ── a\n\
-├──104,857,600 B (16.04%) -- c\n\
-│ ├───80,740,352 B (12.35%) ── other\n\
-│ └───24,117,248 B (03.69%) ── d [2]\n\
-├───24,117,248 B (03.69%) ── cc [2]\n\
-├───20,971,520 B (03.21%) -- f/g/h\n\
-│ ├──10,485,760 B (01.60%) ── i\n\
-│ └──10,485,760 B (01.60%) ── j\n\
-├───15,728,640 B (02.41%) -- g\n\
-│ ├───6,291,456 B (00.96%) ── a\n\
-│ ├───5,242,880 B (00.80%) ── b\n\
-│ └───4,194,304 B (00.64%) ── other\n\
-├───11,534,336 B (01.76%) ── heap-unclassified\n\
-├──────510,976 B (00.08%) ── d\n\
-└──────102,400 B (00.02%) ── e\n\
-\n\
-Other Measurements\n\
-\n\
-5 (100.0%) -- compartments\n\
-├──3 (60.00%) -- user\n\
-│ ├──1 (20.00%) ── bar\n\
-│ ├──1 (20.00%) ── foo\n\
-│ └──1 (20.00%) ── https://very-long-url.com/very-long/oh-so-long/really-quite-long.html?a=2&b=3&c=4&d=5&e=abcdefghijklmnopqrstuvwxyz&f=123456789123456789123456789\n\
-└──2 (40.00%) -- system\n\
- ├──1 (20.00%) ── bar\n\
- └──1 (20.00%) ── foo\n\
-\n\
-174,063,616 B (100.0%) -- other1\n\
-├──116,391,936 B (66.87%) ── a/b\n\
-└───57,671,680 B (33.13%) -- c\n\
- ├──34,603,008 B (19.88%) ── e\n\
- └──23,068,672 B (13.25%) ── d\n\
-\n\
-20.20% (100.0%) -- other3\n\
-└──20.20% (100.0%) -- a/b/c/d\n\
- ├──20.00% (99.01%) ── e\n\
- ├───0.10% (00.50%) ── f\n\
- └───0.10% (00.50%) ── g [2]\n\
-\n\
-100,000 (100.0%) -- other6\n\
-├───99,999 (100.0%) ── big\n\
-└────────1 (00.00%) ── small\n\
-\n\
-0 B (100.0%) -- other7\n\
-└──0 B (100.0%) ── zero\n\
-\n\
-931,135,488 B ── explicit\n\
-524,288,000 B ── heap-allocated\n\
-104,857,600 B ── heap-unallocated\n\
-232,783,872 B ── other2\n\
- 777 ── other3\n\
- 888 ── other4 [2]\n\
- 45.67% ── perc1\n\
- 100.00% ── perc2\n\
-\n\
-End of Main Process\n\
-4th\n\
-\n\
-WARNING: the following values are negative or unreasonably large.\n\
-\n\
- explicit/js/compartment(http://too-big.com/)/stuff\n\
- explicit/neg1\n\
- explicit/heap-unclassified\n\
- other1\n\
- other2\n\
- other3\n\
- other4\n\
- other5 \n\
-\n\
-This indicates a defect in one or more memory reporters. The invalid values are highlighted.\n\
-Explicit Allocations\n\
-\n\
-102,760,448 B (100.0%) -- explicit\n\
-├──157,286,400 B (153.06%) ── js/compartment(http://too-big.com/)/stuff [?!]\n\
-├────5,242,880 B (05.10%) ── ok\n\
-├───-2,097,152 B (-2.04%) ── neg1 [?!]\n\
-└──-57,671,680 B (-56.12%) ── heap-unclassified [?!]\n\
-\n\
-Other Measurements\n\
-\n\
- 104,857,600 B ── heap-allocated\n\
- -111 B ── other1 [?!]\n\
--232,783,872 B ── other2 [?!]\n\
- -333 ── other3 [?!]\n\
- -444 ── other4 [?!]\n\
- -5.55% ── other5 [?!]\n\
- 666.66% ── other6\n\
- 209,715,200 B ── resident\n\
-\n\
-End of 4th\n\
-3rd\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
-814,743,552 B (100.0%) -- explicit\n\
-└──814,743,552 B (100.0%) -- a\n\
- ├──465,567,744 B (57.14%) ── c\n\
- └──349,175,808 B (42.86%) ── b\n\
-\n\
-Other Measurements\n\
-\n\
- 1,048,576 B ── other1\n\
-104,857,600 B ── resident\n\
-\n\
-End of 3rd\n\
-2nd\n\
-Explicit Allocations\n\
-\n\
-1,048,576,000 B (100.0%) -- explicit\n\
-├────523,239,424 B (49.90%) ── a/b/c [3]\n\
-├────209,715,200 B (20.00%) ── compartment(compartment-url)\n\
-├────209,715,200 B (20.00%) ── flip/the/backslashes\n\
-└────105,906,176 B (10.10%) ── heap-unclassified\n\
-\n\
-Other Measurements\n\
-\n\
-1,048,576,000 B ── heap-allocated\n\
- 104,857,600 B ── heap-unallocated\n\
- 698,351,616 B ── other0\n\
- 116,391,936 B ── other1\n\
-\n\
-End of 2nd\n\
-5th\n\
-\n\
-WARNING: the following values are negative or unreasonably large.\n\
-\n\
- explicit/a/neg2\n\
- explicit/a/neg1\n\
- explicit/b/c\n\
- explicit/b/c/d\n\
- explicit/b/c/d/f \n\
-\n\
-This indicates a defect in one or more memory reporters. The invalid values are highlighted.\n\
-Explicit Allocations\n\
-\n\
-104,801,280 B (100.0%) -- explicit\n\
-├──103,809,024 B (99.05%) ── big\n\
-├────1,007,616 B (00.96%) ── heap-unclassified\n\
-├───────10,240 B (00.01%) -- a\n\
-│ ├──40,960 B (00.04%) ── pos\n\
-│ ├──-10,240 B (-0.01%) ── neg2 [?!]\n\
-│ └──-20,480 B (-0.02%) ── neg1 [?!]\n\
-└──────-25,600 B (-0.02%) -- b/c [?!]\n\
- ├───10,240 B (00.01%) ── g/h\n\
- ├────5,120 B (00.00%) ── i/j\n\
- └──-40,960 B (-0.04%) -- d [?!]\n\
- ├───20,480 B (00.02%) ── e\n\
- └──-61,440 B (-0.06%) ── f [?!]\n\
-\n\
-Other Measurements\n\
-\n\
-104,857,600 B ── heap-allocated\n\
-\n\
-End of 5th\n\
-";
-
- function finish()
- {
- mgr.unblockRegistrationAndRestoreOriginalReporters();
- SimpleTest.finish();
- }
-
- // Cut+paste the entire page and check that the cut text matches what we
- // expect. This tests the output in general and also that the cutting and
- // pasting works as expected.
- function test(aFrameId, aVerbose, aExpected, aNext) {
- SimpleTest.executeSoon(function() {
- ok(document.title === "about:memory", "document.title is correct");
- let mostRecentActual;
- let frame = document.getElementById(aFrameId);
- frame.focus();
-
- // Set the verbose checkbox value and click the go button.
- let doc = frame.contentWindow.document;
- let measureButton = doc.getElementById("measureButton");
- let verbose = doc.getElementById("verbose");
- verbose.checked = aVerbose;
- measureButton.click();
-
- SimpleTest.waitForClipboard(
- function(aActual) {
- mostRecentActual = aActual;
- let rslt = aActual.trim() === aExpected.trim();
- if (!rslt) {
- // Try copying again.
- synthesizeKey("A", {accelKey: true});
- synthesizeKey("C", {accelKey: true});
- }
-
- return rslt;
- },
- function() {
- synthesizeKey("A", {accelKey: true});
- synthesizeKey("C", {accelKey: true});
- },
- aNext,
- function() {
- ok(false, "pasted text doesn't match for " + aFrameId);
- dump("******EXPECTED******\n");
- dump("<<<" + aExpected + ">>>\n");
- dump("*******ACTUAL*******\n");
- dump("<<<" + mostRecentActual + ">>>\n");
- dump("********************\n");
- finish();
- }
- );
- });
- }
-
- SimpleTest.waitForFocus(function() {
- test(
- "amFrame",
- /* verbose = */ false,
- amExpectedText,
- function() {
- test(
- "amvFrame",
- /* verbose = */ true,
- amvExpectedText,
- function() {
- finish()
- }
- )
- }
- );
- });
- SimpleTest.waitForExplicitFinish();
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_aboutmemory2.xul b/toolkit/components/aboutmemory/tests/test_aboutmemory2.xul
deleted file mode 100644
index 8cf197e6d..000000000
--- a/toolkit/components/aboutmemory/tests/test_aboutmemory2.xul
+++ /dev/null
@@ -1,423 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="about:memory"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
-
- <!-- This file tests the collapsing and expanding of sub-trees in
- about:memory. -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml"></body>
-
- <!-- test code goes here -->
- <script type="application/javascript">
- <![CDATA[
- "use strict";
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
- let mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
- getService(Ci.nsIMemoryReporterManager);
-
- // Hide all the real reporters; we'll restore them at the end.
- mgr.blockRegistrationAndHideExistingReporters();
-
- // Setup various fake-but-deterministic reporters.
- const KB = 1024;
- const MB = KB * KB;
- const HEAP = Ci.nsIMemoryReporter.KIND_HEAP;
- const OTHER = Ci.nsIMemoryReporter.KIND_OTHER;
- const BYTES = Ci.nsIMemoryReporter.UNITS_BYTES;
-
- let hiPath = "explicit/h/i";
- let hi2Path = "explicit/h/i2";
- let jkPath = "explicit/j/k";
- let jk2Path = "explicit/j/k2";
-
- let fakeReporters = [
- { collectReports: function(aCbObj, aClosure, aAnonymize) {
- function f(aP, aK, aA) {
- aCbObj.callback("", aP, aK, BYTES, aA, "Desc.", aClosure);
- }
- f("heap-allocated", OTHER, 250 * MB);
- f("explicit/a/b", HEAP, 50 * MB);
- f("explicit/a/c/d", HEAP, 25 * MB);
- f("explicit/a/c/e", HEAP, 15 * MB);
- f("explicit/a/f", HEAP, 30 * MB);
- f("explicit/g", HEAP, 100 * MB);
- f(hiPath, HEAP, 10 * MB);
- f(hi2Path, HEAP, 9 * MB);
- f(jkPath, HEAP, 0.5 * MB);
- f(jk2Path, HEAP, 0.3 * MB);
- f("explicit/a/l/m", HEAP, 0.1 * MB);
- f("explicit/a/l/n", HEAP, 0.1 * MB);
- }
- }
- ];
-
- for (let i = 0; i < fakeReporters.length; i++) {
- mgr.registerStrongReporterEvenIfBlocked(fakeReporters[i]);
- }
-
- ]]>
- </script>
-
- <iframe id="amFrame" height="500" src="about:memory"></iframe>
-
- <script type="application/javascript">
- <![CDATA[
- function finish()
- {
- mgr.unblockRegistrationAndRestoreOriginalReporters();
- SimpleTest.finish();
- }
-
- // Click on the identified element, then cut+paste the entire page and
- // check that the cut text matches what we expect.
- function test(aId, aSwap, aExpected, aNext) {
- let win = document.getElementById("amFrame").contentWindow;
- if (aId) {
- let node = win.document.getElementById(aId);
-
- // Yuk: clicking a button is easy; but for tree entries we need to
- // click on a child of the span identified via |id|.
- if (node.nodeName === "button") {
- if (aSwap) {
- // We swap hipath/hi2Path and jkPath/jk2Path just before updating, to
- // test what happens when significant nodes become insignificant and
- // vice versa.
- hiPath = "explicit/j/k";
- hi2Path = "explicit/j/k2";
- jkPath = "explicit/h/i";
- jk2Path = "explicit/h/i2";
- }
- node.click();
- } else {
- node.childNodes[0].click();
- }
- }
-
- SimpleTest.executeSoon(function() {
- let mostRecentActual;
- document.getElementById("amFrame").focus();
- SimpleTest.waitForClipboard(
- function(aActual) {
- mostRecentActual = aActual;
- let rslt = aActual.trim() === aExpected.trim();
- if (!rslt) {
- // Try copying again.
- synthesizeKey("A", {accelKey: true});
- synthesizeKey("C", {accelKey: true});
- }
-
- return rslt;
- },
- function() {
- synthesizeKey("A", {accelKey: true});
- synthesizeKey("C", {accelKey: true});
- },
- aNext,
- function() {
- ok(false, "pasted text doesn't match");
- dump("******EXPECTED******\n");
- dump(aExpected);
- dump("*******ACTUAL*******\n");
- dump(mostRecentActual);
- dump("********************\n");
- finish();
- }
- );
- });
- }
-
- // Returns a function that chains together one test() call per id.
- function chain(aIds) {
- let x = aIds.shift();
- if (x) {
- return function() { test(x.id, x.swap, x.expected, chain(aIds)); }
- } else {
- return function() { finish(); };
- }
- }
-
- let startExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) -- a\n\
-│ ├───50.00 MB (20.00%) ── b\n\
-│ ├───40.00 MB (16.00%) -- c\n\
-│ │ ├──25.00 MB (10.00%) ── d\n\
-│ │ └──15.00 MB (06.00%) ── e\n\
-│ ├───30.00 MB (12.00%) ── f\n\
-│ └────0.20 MB (00.08%) ++ l\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- h\n\
-│ ├──10.00 MB (04.00%) ── i\n\
-│ └───9.00 MB (03.60%) ── i2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ j\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let acCollapsedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) -- a\n\
-│ ├───50.00 MB (20.00%) ── b\n\
-│ ├───40.00 MB (16.00%) ++ c\n\
-│ ├───30.00 MB (12.00%) ── f\n\
-│ └────0.20 MB (00.08%) ++ l\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- h\n\
-│ ├──10.00 MB (04.00%) ── i\n\
-│ └───9.00 MB (03.60%) ── i2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ j\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let alExpandedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) -- a\n\
-│ ├───50.00 MB (20.00%) ── b\n\
-│ ├───40.00 MB (16.00%) ++ c\n\
-│ ├───30.00 MB (12.00%) ── f\n\
-│ └────0.20 MB (00.08%) -- l\n\
-│ ├──0.10 MB (00.04%) ── m\n\
-│ └──0.10 MB (00.04%) ── n\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- h\n\
-│ ├──10.00 MB (04.00%) ── i\n\
-│ └───9.00 MB (03.60%) ── i2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ j\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let aCollapsedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) ++ a\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- h\n\
-│ ├──10.00 MB (04.00%) ── i\n\
-│ └───9.00 MB (03.60%) ── i2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ j\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let hCollapsedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) ++ a\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) ++ h\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ j\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let jExpandedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) ++ a\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) ++ h\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) -- j\n\
- ├──0.50 MB (00.20%) ── k\n\
- └──0.30 MB (00.12%) ── k2\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- // The important thing here is that two values have been swapped.
- // explicit/h/i should remain collapsed, and explicit/j/k should remain
- // expanded. See bug 724863.
- let updatedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) ++ a\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- j\n\
-│ ├──10.00 MB (04.00%) ── k\n\
-│ └───9.00 MB (03.60%) ── k2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ h\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let aExpandedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) -- a\n\
-│ ├───50.00 MB (20.00%) ── b\n\
-│ ├───40.00 MB (16.00%) ++ c\n\
-│ ├───30.00 MB (12.00%) ── f\n\
-│ └────0.20 MB (00.08%) -- l\n\
-│ ├──0.10 MB (00.04%) ── m\n\
-│ └──0.10 MB (00.04%) ── n\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- j\n\
-│ ├──10.00 MB (04.00%) ── k\n\
-│ └───9.00 MB (03.60%) ── k2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ h\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let acExpandedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) -- a\n\
-│ ├───50.00 MB (20.00%) ── b\n\
-│ ├───40.00 MB (16.00%) -- c\n\
-│ │ ├──25.00 MB (10.00%) ── d\n\
-│ │ └──15.00 MB (06.00%) ── e\n\
-│ ├───30.00 MB (12.00%) ── f\n\
-│ └────0.20 MB (00.08%) -- l\n\
-│ ├──0.10 MB (00.04%) ── m\n\
-│ └──0.10 MB (00.04%) ── n\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- j\n\
-│ ├──10.00 MB (04.00%) ── k\n\
-│ └───9.00 MB (03.60%) ── k2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ h\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- let alCollapsedExpected =
-"\
-Main Process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──120.20 MB (48.08%) -- a\n\
-│ ├───50.00 MB (20.00%) ── b\n\
-│ ├───40.00 MB (16.00%) -- c\n\
-│ │ ├──25.00 MB (10.00%) ── d\n\
-│ │ └──15.00 MB (06.00%) ── e\n\
-│ ├───30.00 MB (12.00%) ── f\n\
-│ └────0.20 MB (00.08%) ++ l\n\
-├──100.00 MB (40.00%) ── g\n\
-├───19.00 MB (07.60%) -- j\n\
-│ ├──10.00 MB (04.00%) ── k\n\
-│ └───9.00 MB (03.60%) ── k2\n\
-├───10.00 MB (04.00%) ── heap-unclassified\n\
-└────0.80 MB (00.32%) ++ h\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process\n\
-";
-
- // Test the following cases:
- // - explicit/a/c is significant, we collapse it, it's unchanged upon
- // update, we re-expand it
- // - explicit/a/l is insignificant, we expand it, it's unchanged upon
- // update, we re-collapse it
- // - explicit/a is significant, we collapse it (which hides its
- // sub-trees), it's unchanged upon update, we re-expand it
- // - explicit/h is significant, we collapse it, it becomes insignificant
- // upon update (and should remain collapsed)
- // - explicit/j is insignificant, we expand it, it becomes significant
- // upon update (and should remain expanded)
- //
- let idsToClick = [
- { id: "measureButton", swap: 0, expected: startExpected },
- { id: "Main Process:explicit/a/c", swap: 0, expected: acCollapsedExpected },
- { id: "Main Process:explicit/a/l", swap: 0, expected: alExpandedExpected },
- { id: "Main Process:explicit/a", swap: 0, expected: aCollapsedExpected },
- { id: "Main Process:explicit/h", swap: 0, expected: hCollapsedExpected },
- { id: "Main Process:explicit/j", swap: 0, expected: jExpandedExpected },
- { id: "measureButton", swap: 1, expected: updatedExpected },
- { id: "Main Process:explicit/a", swap: 0, expected: aExpandedExpected },
- { id: "Main Process:explicit/a/c", swap: 0, expected: acExpandedExpected },
- { id: "Main Process:explicit/a/l", swap: 0, expected: alCollapsedExpected }
- ];
-
- SimpleTest.waitForFocus(chain(idsToClick));
-
- SimpleTest.waitForExplicitFinish();
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_aboutmemory3.xul b/toolkit/components/aboutmemory/tests/test_aboutmemory3.xul
deleted file mode 100644
index c712070cc..000000000
--- a/toolkit/components/aboutmemory/tests/test_aboutmemory3.xul
+++ /dev/null
@@ -1,515 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="about:memory"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
-
- <!-- This file tests the saving and loading of memory reports to/from file in
- about:memory. -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml"></body>
-
- <!-- test code goes here -->
- <script type="application/javascript">
- <![CDATA[
- "use strict";
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
- let mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
- getService(Ci.nsIMemoryReporterManager);
-
- // Hide all the real reporters; we'll restore them at the end.
- mgr.blockRegistrationAndHideExistingReporters();
-
- // Setup a minimal number of fake reporters.
- const KB = 1024;
- const MB = KB * KB;
- const HEAP = Ci.nsIMemoryReporter.KIND_HEAP;
- const OTHER = Ci.nsIMemoryReporter.KIND_OTHER;
- const BYTES = Ci.nsIMemoryReporter.UNITS_BYTES;
-
- let fakeReporters = [
- { collectReports: function(aCbObj, aClosure, aAnonymize) {
- function f(aP, aK, aA, aD) {
- aCbObj.callback("", aP, aK, BYTES, aA, aD, aClosure);
- }
- f("heap-allocated", OTHER, 250 * MB, "Heap allocated.");
- f("explicit/a/b", HEAP, 50 * MB, "A b.");
- f("other/a", OTHER, 0.2 * MB, "Other a.");
- f("other/b", OTHER, 0.1 * MB, "Other b.");
- }
- }
- ];
-
- for (let i = 0; i < fakeReporters.length; i++) {
- mgr.registerStrongReporterEvenIfBlocked(fakeReporters[i]);
- }
-
- ]]>
- </script>
-
- <iframe id="amFrame" height="400" src="about:memory"></iframe>
-
- <script type="application/javascript">
- <![CDATA[
- function finish()
- {
- mgr.unblockRegistrationAndRestoreOriginalReporters();
- SimpleTest.finish();
- }
-
- // Load the given file into the frame, then copy+paste the entire frame and
- // check that the cut text matches what we expect.
- function test(aFilename, aFilename2, aExpected, aDumpFirst, aVerbose, aNext) {
- let frame = document.getElementById("amFrame");
- frame.focus();
-
- let doc = frame.contentWindow.document;
- let verbosity = doc.getElementById("verbose");
- verbosity.checked = aVerbose;
-
- function getFilePath(aFilename) {
- let file = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties)
- .get("CurWorkD", Components.interfaces.nsIFile);
- file.append("chrome");
- file.append("toolkit");
- file.append("components");
- file.append("aboutmemory");
- file.append("tests");
- file.append(aFilename);
- return file.path;
- }
-
- let filePath = getFilePath(aFilename);
-
- let e = document.createEvent('Event');
- e.initEvent('change', true, true);
-
- function check() {
- // Initialize the clipboard contents.
- SpecialPowers.clipboardCopyString("initial clipboard value");
-
- let numFailures = 0, maxFailures = 30;
-
- // Because the file load is async, we don't know when it will finish and
- // the output will show up. So we poll.
- function copyPasteAndCheck() {
- // Copy and paste frame contents, and filter out non-deterministic
- // differences.
- synthesizeKey("A", {accelKey: true});
- synthesizeKey("C", {accelKey: true});
- let actual = SpecialPowers.getClipboardData("text/unicode");
- actual = actual.replace(/\(pid \d+\)/g, "(pid NNN)");
-
- if (actual.trim() === aExpected.trim()) {
- SimpleTest.ok(true, "Clipboard has the expected contents");
- aNext();
- } else {
- numFailures++;
- if (numFailures === maxFailures) {
- ok(false, "pasted text doesn't match");
- dump("******EXPECTED******\n");
- dump(aExpected);
- dump("*******ACTUAL*******\n");
- dump(actual);
- dump("********************\n");
- finish();
- } else {
- setTimeout(copyPasteAndCheck, 100);
- }
- }
- }
- copyPasteAndCheck();
- }
-
- if (!aFilename2) {
- function loadAndCheck() {
- let fileInput1 =
- frame.contentWindow.document.getElementById("fileInput1");
- fileInput1.value = filePath; // this works because it's a chrome test
-
- fileInput1.dispatchEvent(e);
- check();
- }
-
- if (aDumpFirst) {
- let dumper = Cc["@mozilla.org/memory-info-dumper;1"].
- getService(Ci.nsIMemoryInfoDumper);
- dumper.dumpMemoryReportsToNamedFile(filePath, loadAndCheck, null,
- /* anonymize = */ false);
- } else {
- loadAndCheck();
- }
-
- } else {
- let fileInput2 =
- frame.contentWindow.document.getElementById("fileInput2");
- fileInput2.value = filePath; // this works because it's a chrome test
-
- // Hack alert: fileInput2's onchange handler calls fileInput2.click().
- // But we don't want that to happen, because we want to bypass the file
- // picker for the test. So we set |e.skipClick|, which causes
- // fileInput2.click() to be skipped, and dispatch the second change event
- // directly ourselves.
-
- e.skipClick = true;
- fileInput2.dispatchEvent(e);
-
- let filePath2 = getFilePath(aFilename2);
- fileInput2.value = filePath2; // this works because it's a chrome test
-
- let e2 = document.createEvent('Event');
- e2.initEvent('change', true, true);
- fileInput2.dispatchEvent(e);
-
- check();
- }
- }
-
- // Returns a function that chains together multiple test() calls.
- function chain(aPieces) {
- let x = aPieces.shift();
- if (x) {
- return function() { test(x.filename, x.filename2, x.expected, x.dumpFirst, x.verbose, chain(aPieces)); }
- } else {
- return function() { finish(); };
- }
- }
-
- let expectedGood =
-"\
-Explicit-only process\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
-100,000 B (100.0%) -- explicit\n\
-└──100,000 B (100.0%) ── a/b\n\
-\n\
-Other Measurements\n\
-\n\
-End of Explicit-only process\n\
-Heap-unclassified process\n\
-Explicit Allocations\n\
-\n\
-262,144,000 B (100.0%) -- explicit\n\
-├──209,715,200 B (80.00%) ── heap-unclassified\n\
-└───52,428,800 B (20.00%) ── a/b\n\
-\n\
-Other Measurements\n\
-\n\
-262,144,000 B ── heap-allocated\n\
-\n\
-End of Heap-unclassified process\n\
-Main Process (pid NNN)\n\
-Explicit Allocations\n\
-\n\
-262,144,000 B (100.0%) -- explicit\n\
-├──209,715,200 B (80.00%) ── heap-unclassified\n\
-└───52,428,800 B (20.00%) ── a/b\n\
-\n\
-Other Measurements\n\
-\n\
-1,024 B (100.0%) -- compartments\n\
-└──1,024 B (100.0%) ── system/a\n\
-\n\
-1,024 B (100.0%) -- ghost-windows\n\
-└──1,024 B (100.0%) ── a\n\
-\n\
-314,572 B (100.0%) -- other\n\
-├──209,715 B (66.67%) ── a\n\
-└──104,857 B (33.33%) ── b\n\
-\n\
-1,024 B (100.0%) -- pss\n\
-└──1,024 B (100.0%) ── a\n\
-\n\
-1,024 B (100.0%) -- rss\n\
-└──1,024 B (100.0%) ── a\n\
-\n\
-1,024 B (100.0%) -- size\n\
-└──1,024 B (100.0%) ── a\n\
-\n\
-1,024 B (100.0%) -- swap\n\
-└──1,024 B (100.0%) ── a\n\
-\n\
-262,144,000 B ── heap-allocated\n\
-\n\
-End of Main Process (pid NNN)\n\
-Other-only process\n\
-Other Measurements\n\
-\n\
-200,000 B (100.0%) -- a\n\
-├──100,000 B (50.00%) ── b\n\
-└──100,000 B (50.00%) ── c\n\
-\n\
-500,000 B ── heap-allocated\n\
-\n\
-End of Other-only process\n\
-";
-
- let expectedGood2 =
-"\
-Main Process (pid NNN)\n\
-Explicit Allocations\n\
-\n\
-262,144,000 B (100.0%) -- explicit\n\
-├──209,715,200 B (80.00%) ── heap-unclassified\n\
-└───52,428,800 B (20.00%) ── a/b\n\
-\n\
-Other Measurements\n\
-\n\
-314,572 B (100.0%) -- other\n\
-├──209,715 B (66.67%) ── a\n\
-└──104,857 B (33.33%) ── b\n\
-\n\
-262,144,000 B ── heap-allocated\n\
-\n\
-End of Main Process (pid NNN)\n\
-";
-
- // This is the output for a malformed data file.
- let expectedBad =
-"\
-Error: Invalid memory report(s): missing 'hasMozMallocUsableSize' property\
-";
-
- // This is the output for a non-verbose diff.
- let expectedDiffNonVerbose =
-"\
-P\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
--0.01 MB (100.0%) -- explicit\n\
-├──-0.01 MB (99.95%) ── storage/prefixset/goog-phish-shavar\n\
-└──-0.00 MB (00.05%) ++ (2 tiny)\n\
-\n\
-Other Measurements\n\
-\n\
-0.96 MB (100.0%) -- a\n\
-├──0.95 MB (99.80%) ── b\n\
-├──0.00 MB (00.10%) -- c\n\
-│ ├──-0.95 MB (-99.70%) ── e\n\
-│ ├──0.95 MB (99.60%) ── d\n\
-│ └──0.00 MB (00.20%) ++ (2 tiny)\n\
-└──0.00 MB (00.10%) ── h\n\
-\n\
- 0.00 MB ── canvas-2d-pixel-bytes [2] [+]\n\
--0.00 MB ── foobar [-]\n\
-\n\
-End of P\n\
-P2 (pid NNN)\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
-0.00 MB (100.0%) -- explicit\n\
-└──0.00 MB (100.0%) ── window-objects/top(bar.com, id=NNN)/...\n\
-\n\
-Other Measurements\n\
-\n\
-0.00 MB (100.0%) -- p3\n\
-└──0.00 MB (100.0%) ── zone(0xNNN)/p3\n\
-\n\
-0.00 MB (100.0%) -- p4\n\
-└──0.00 MB (100.0%) ── js-zone(0xNNN)/p4\n\
-\n\
-0.00 MB (100.0%) -- p5\n\
-└──0.00 MB (100.0%) ── worker(foo.com, 0xNNN)/p5\n\
-\n\
-0.00 MB (100.0%) -- p6\n\
-└──0.00 MB (100.0%) ── z-moz-nullprincipal:{NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN}/p6\n\
-\n\
-0.00 MB (100.0%) -- p7\n\
-└──0.00 MB (100.0%) ── js-main-runtime-compartments/system/jar:file:///.../omni.ja!/p7\n\
-\n\
-0.00 MB ── p1 (pid NNN)\n\
-0.00 MB ── p2 (blah, pid=NNN)\n\
-\n\
-End of P2 (pid NNN)\n\
-P3\n\
-Other Measurements\n\
-\n\
--0.00 MB ── p3 [-]\n\
-\n\
-End of P3\n\
-P4\n\
-Other Measurements\n\
-\n\
-0.00 MB ── p4 [+]\n\
-\n\
-End of P4\n\
-P7\n\
-Other Measurements\n\
-\n\
-0.00 MB (100.0%) -- p7\n\
-├──0.00 MB (57.14%) ── c [+]\n\
-└──0.00 MB (42.86%) ── b [+]\n\
-\n\
--0.00 MB ── p7 [-]\n\
-\n\
-End of P7\n\
-P8\n\
-Other Measurements\n\
-\n\
--0.00 MB (100.0%) -- p8\n\
-└──-0.00 MB (100.0%) -- a\n\
- ├──-0.00 MB (50.00%) -- b\n\
- │ ├──-0.00 MB (31.82%) -- c\n\
- │ │ ├──-0.00 MB (18.18%) ── e [-]\n\
- │ │ └──-0.00 MB (13.64%) ── d [-]\n\
- │ ├──-0.00 MB (22.73%) ── f [-]\n\
- │ └───0.00 MB (-4.55%) ── (fake child) [!]\n\
- └──-0.00 MB (50.00%) -- g\n\
- ├──-0.00 MB (31.82%) ── i [-]\n\
- ├──-0.00 MB (27.27%) ── h [-]\n\
- └───0.00 MB (-9.09%) ── (fake child) [!]\n\
-\n\
-End of P8\n\
-";
-
- // This is the output for a verbose diff.
- let expectedDiffVerbose =
-"\
-P\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
--10,005 B (100.0%) -- explicit\n\
-├──-10,000 B (99.95%) ── storage/prefixset/goog-phish-shavar\n\
-├───────-6 B (00.06%) ── spell-check [2]\n\
-└────────1 B (-0.01%) ── xpcom/category-manager\n\
-\n\
-Other Measurements\n\
-\n\
-1,002,000 B (100.0%) -- a\n\
-├──1,000,000 B (99.80%) ── b\n\
-├──────1,000 B (00.10%) -- c\n\
-│ ├──-999,000 B (-99.70%) ── e\n\
-│ ├──998,000 B (99.60%) ── d\n\
-│ ├──1,000 B (00.10%) ── f\n\
-│ └──1,000 B (00.10%) ── g\n\
-└──────1,000 B (00.10%) ── h\n\
-\n\
-3,000 B ── canvas-2d-pixel-bytes [2] [+]\n\
- -100 B ── foobar [-]\n\
-\n\
-End of P\n\
-P2 (pid NNN)\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
-11 B (100.0%) -- explicit\n\
-└──11 B (100.0%) ── window-objects/top(bar.com, id=NNN)/...\n\
-\n\
-Other Measurements\n\
-\n\
-11 B (100.0%) -- p3\n\
-└──11 B (100.0%) ── zone(0xNNN)/p3\n\
-\n\
-11 B (100.0%) -- p4\n\
-└──11 B (100.0%) ── js-zone(0xNNN)/p4\n\
-\n\
-11 B (100.0%) -- p5\n\
-└──11 B (100.0%) ── worker(foo.com, 0xNNN)/p5\n\
-\n\
-11 B (100.0%) -- p6\n\
-└──11 B (100.0%) ── z-moz-nullprincipal:{NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN}/p6\n\
-\n\
-11 B (100.0%) -- p7\n\
-└──11 B (100.0%) ── js-main-runtime-compartments/system/jar:file:///.../omni.ja!/p7\n\
-\n\
-11 B ── p1 (pid NNN)\n\
-11 B ── p2 (blah, pid=NNN)\n\
-\n\
-End of P2 (pid NNN)\n\
-P3\n\
-Other Measurements\n\
-\n\
--55 B ── p3 [-]\n\
-\n\
-End of P3\n\
-P4\n\
-Other Measurements\n\
-\n\
-66 B ── p4 [+]\n\
-\n\
-End of P4\n\
-P7\n\
-Other Measurements\n\
-\n\
-7 B (100.0%) -- p7\n\
-├──4 B (57.14%) ── c [+]\n\
-└──3 B (42.86%) ── b [+]\n\
-\n\
--5 B ── p7 [-]\n\
-\n\
-End of P7\n\
-P8\n\
-Other Measurements\n\
-\n\
--22 B (100.0%) -- p8\n\
-└──-22 B (100.0%) -- a\n\
- ├──-11 B (50.00%) -- b\n\
- │ ├───-7 B (31.82%) -- c\n\
- │ │ ├──-4 B (18.18%) ── e [-]\n\
- │ │ └──-3 B (13.64%) ── d [-]\n\
- │ ├───-5 B (22.73%) ── f [-]\n\
- │ └────1 B (-4.55%) ── (fake child) [!]\n\
- └──-11 B (50.00%) -- g\n\
- ├───-7 B (31.82%) ── i [-]\n\
- ├───-6 B (27.27%) ── h [-]\n\
- └────2 B (-9.09%) ── (fake child) [!]\n\
-\n\
-End of P8\n\
-";
-
- // This is the output for the crash reports diff.
- let expectedDiff2 =
-"\
-Main Process (pid NNN)\n\
-Other Measurements\n\
-\n\
-1 B ── heap-allocated\n\
-\n\
-End of Main Process (pid NNN)\n\
-";
-
- let frames = [
- // This loads a pre-existing memory reports file that is valid.
- { filename: "memory-reports-good.json", expected: expectedGood, dumpFirst: false, verbose: true },
-
- // This loads a pre-existing crash dump file that is valid.
- { filename: "crash-dump-good.json", expected: expectedGood2, dumpFirst: false, verbose: true },
-
- // This dumps to a file and then reads it back in. (The result is the same
- // as the previous test.)
- { filename: "memory-reports-dumped.json.gz", expected: expectedGood2, dumpFirst: true, verbose: true },
-
- // This loads a pre-existing file that is invalid.
- { filename: "memory-reports-bad.json", expected: expectedBad, dumpFirst: false, verbose: true },
-
- // This diffs two pre-existing memory reports files.
- { filename: "memory-reports-diff1.json", filename2: "memory-reports-diff2.json", expected: expectedDiffNonVerbose, dumpFirst: false, verbose: false },
-
- // Ditto.
- { filename: "memory-reports-diff1.json", filename2: "memory-reports-diff2.json", expected: expectedDiffVerbose, dumpFirst: false, verbose: true },
-
- // This diffs two pre-existing crash report files.
- { filename: "crash-dump-diff1.json", filename2: "crash-dump-diff2.json", expected: expectedDiff2, dumpFirst: false, verbose: true }
- ];
-
- SimpleTest.waitForFocus(chain(frames));
-
- SimpleTest.waitForExplicitFinish();
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_aboutmemory4.xul b/toolkit/components/aboutmemory/tests/test_aboutmemory4.xul
deleted file mode 100644
index f2c752ac5..000000000
--- a/toolkit/components/aboutmemory/tests/test_aboutmemory4.xul
+++ /dev/null
@@ -1,179 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="about:memory"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
-
- <!-- This file tests the loading of memory reports from file when specified
- in about:memory's URL (via the "file=" suffix). -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml"></body>
-
- <!-- test code goes here -->
- <script type="application/javascript">
- <![CDATA[
- "use strict";
-
- function makePathname(aFilename) {
- let file = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties)
- .get("CurWorkD", Components.interfaces.nsIFile);
- file.append("chrome");
- file.append("toolkit");
- file.append("components");
- file.append("aboutmemory");
- file.append("tests");
- file.append(aFilename);
- return file.path;
- }
-
- // Load the given file into the frame, then copy+paste the entire frame and
- // check that the cut text matches what we expect.
- function test(aFilename, aExpected, aNext) {
- let frame = document.createElementNS("http://www.w3.org/1999/xhtml", "iframe")
- frame.height = 300;
- frame.src = "about:memory?file=" + makePathname(aFilename);
- document.documentElement.appendChild(frame);
- frame.focus();
-
- // Initialize the clipboard contents.
- SpecialPowers.clipboardCopyString("initial clipboard value");
-
- let numFailures = 0, maxFailures = 30;
-
- // Because the file load is async, we don't know when it will finish and
- // the output will show up. So we poll.
- function copyPasteAndCheck() {
- // Copy and paste frame contents, and filter out non-deterministic
- // differences.
- synthesizeKey("A", {accelKey: true});
- synthesizeKey("C", {accelKey: true});
- let actual = SpecialPowers.getClipboardData("text/unicode");
- actual = actual.replace(/\(pid \d+\)/, "(pid NNN)");
-
- if (actual.trim() === aExpected.trim()) {
- SimpleTest.ok(true, "Clipboard has the expected contents");
- aNext();
- } else {
- numFailures++;
- if (numFailures === maxFailures) {
- ok(false, "pasted text doesn't match");
- dump("******EXPECTED******\n");
- dump(aExpected);
- dump("*******ACTUAL*******\n");
- dump(actual);
- dump("********************\n");
- SimpleTest.finish();
- } else {
- setTimeout(copyPasteAndCheck, 100);
- }
- }
- }
- copyPasteAndCheck();
- }
-
- // Returns a function that chains together multiple test() calls.
- function chain(aFrameIds) {
- let x = aFrameIds.shift();
- if (x) {
- return function() { test(x.filename, x.expected, chain(aFrameIds)); }
- } else {
- return function() { SimpleTest.finish(); };
- }
- }
-
- // This is pretty simple output, but that's ok; this file is about testing
- // the loading of data from file. If we got this far, we're doing fine.
- let expectedGood =
-"\
-Explicit-only process\n\
-\n\
-WARNING: the 'heap-allocated' memory reporter does not work for this platform and/or configuration. This means that 'heap-unclassified' is not shown and the 'explicit' tree shows less memory than it should.\n\
-Explicit Allocations\n\
-\n\
-0.10 MB (100.0%) -- explicit\n\
-└──0.10 MB (100.0%) ── a/b\n\
-\n\
-Other Measurements\n\
-\n\
-End of Explicit-only process\n\
-Heap-unclassified process\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──200.00 MB (80.00%) ── heap-unclassified\n\
-└───50.00 MB (20.00%) ── a/b\n\
-\n\
-Other Measurements\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Heap-unclassified process\n\
-Main Process (pid NNN)\n\
-Explicit Allocations\n\
-\n\
-250.00 MB (100.0%) -- explicit\n\
-├──200.00 MB (80.00%) ── heap-unclassified\n\
-└───50.00 MB (20.00%) ── a/b\n\
-\n\
-Other Measurements\n\
-\n\
-0.00 MB (100.0%) -- compartments\n\
-└──0.00 MB (100.0%) ── system/a\n\
-\n\
-0.00 MB (100.0%) -- ghost-windows\n\
-└──0.00 MB (100.0%) ── a\n\
-\n\
-0.30 MB (100.0%) -- other\n\
-├──0.20 MB (66.67%) ── a\n\
-└──0.10 MB (33.33%) ── b\n\
-\n\
-0.00 MB (100.0%) -- pss\n\
-└──0.00 MB (100.0%) ── a\n\
-\n\
-0.00 MB (100.0%) -- rss\n\
-└──0.00 MB (100.0%) ── a\n\
-\n\
-0.00 MB (100.0%) -- size\n\
-└──0.00 MB (100.0%) ── a\n\
-\n\
-0.00 MB (100.0%) -- swap\n\
-└──0.00 MB (100.0%) ── a\n\
-\n\
-250.00 MB ── heap-allocated\n\
-\n\
-End of Main Process (pid NNN)\n\
-Other-only process\n\
-Other Measurements\n\
-\n\
-0.19 MB (100.0%) -- a\n\
-├──0.10 MB (50.00%) ── b\n\
-└──0.10 MB (50.00%) ── c\n\
-\n\
-0.48 MB ── heap-allocated\n\
-\n\
-End of Other-only process\n\
-";
-
- // This is the output for a malformed data file.
- let expectedBad =
-"\
-Error: Invalid memory report(s): missing 'hasMozMallocUsableSize' property";
-
- let frames = [
- // This loads a pre-existing file that is valid.
- { filename: "memory-reports-good.json", expected: expectedGood },
-
- // This loads a pre-existing file that is valid.
- { filename: "memory-reports-bad.json", expected: expectedBad }
- ];
-
- SimpleTest.waitForFocus(chain(frames));
-
- SimpleTest.waitForExplicitFinish();
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_aboutmemory5.xul b/toolkit/components/aboutmemory/tests/test_aboutmemory5.xul
deleted file mode 100644
index 2fec803b9..000000000
--- a/toolkit/components/aboutmemory/tests/test_aboutmemory5.xul
+++ /dev/null
@@ -1,167 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="about:memory"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
-
- <!-- This file tests the saving and loading of memory reports to/from file in
- about:memory in the presence of child processes. It is also notable
- for being an about:memory test that uses the real reporters, rather
- than fake deterministic ones, and so tends to show up problems in the
- real reporters (like bogus negative values). -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml"></body>
-
- <iframe id="amFrame" height="400" src="about:memory"></iframe>
-
- <script type="application/javascript">
- <![CDATA[
- "use strict";
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
- let mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
- getService(Ci.nsIMemoryReporterManager);
-
- let numRemotes = 3;
- let numReady = 0;
-
- // Create some remote processes, and set up message-passing so that
- // we know when each child is fully initialized.
- let remotes = [];
-
- let prefs = [
- ["dom.ipc.processCount", 3], // Allow up to 3 child processes
- ["memory.report_concurrency", 2], // Cover more child handling cases
- ["memory.system_memory_reporter", true] // Test SystemMemoryReporter
- ];
-
- SpecialPowers.pushPrefEnv({"set": prefs}, function() {
- for (let i = 0; i < numRemotes; i++) {
- let w = remotes[i] = window.open("remote.xul", "", "chrome");
-
- w.addEventListener("load", function loadHandler() {
- w.removeEventListener("load", loadHandler);
- let remoteBrowser = w.document.getElementById("remote");
- let mm = remoteBrowser.messageManager;
- mm.addMessageListener("test:ready", function readyHandler() {
- mm.removeMessageListener("test:ready", readyHandler);
- numReady++;
- if (numReady == numRemotes) {
- // All the remote processes are ready.
- SimpleTest.waitForFocus(onFocus);
- }
- });
- mm.loadFrameScript("data:," + encodeURI("sendAsyncMessage('test:ready');"), true);
- });
- }
- });
-
- // Load the given file into the frame, then copy+paste the entire frame and
- // check that the cut text matches what we expect.
- function onFocus() {
- let frame = document.getElementById("amFrame");
- frame.focus();
-
- function getFilePath(aFilename) {
- let file = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties)
- .get("CurWorkD", Components.interfaces.nsIFile);
- file.append("chrome");
- file.append("toolkit");
- file.append("components");
- file.append("aboutmemory");
- file.append("tests");
- file.append(aFilename);
- return file.path;
- }
-
- let filePath = getFilePath("memory-reports-dumped.json.gz");
-
- let e = document.createEvent('Event');
- e.initEvent('change', true, true);
-
- let dumper = Cc["@mozilla.org/memory-info-dumper;1"].
- getService(Ci.nsIMemoryInfoDumper);
- dumper.dumpMemoryReportsToNamedFile(filePath, loadAndCheck, null,
- /* anonymize = */ false);
-
- function loadAndCheck() {
- // Load the file.
- let fileInput1 =
- frame.contentWindow.document.getElementById("fileInput1");
- fileInput1.value = filePath; // this works because it's a chrome test
- fileInput1.dispatchEvent(e);
-
- // Initialize the clipboard contents.
- SpecialPowers.clipboardCopyString("initial clipboard value");
-
- let numFailures = 0, maxFailures = 30;
-
- copyPasteAndCheck();
-
- // Because the file load is async, we don't know when it will finish and
- // the output will show up. So we poll.
- function copyPasteAndCheck() {
- // Copy and paste frame contents, and filter out non-deterministic
- // differences.
- synthesizeKey("A", {accelKey: true});
- synthesizeKey("C", {accelKey: true});
- let actual = SpecialPowers.getClipboardData("text/unicode");
-
- // If we have more than 1000 chars, we've probably successfully
- // copy+pasted.
- if (actual.length > 1000) {
-
- let good = true;
-
- if (actual.match("End of System")) {
- let m1 = actual.match("anonymous") &&
- actual.match("shared-libraries");
- ok(m1, "system-wide reporter")
- good = good && !!m1;
- }
-
- // Note: Match "vsize" but not "vsize-max-contiguous".
- let vsizes = actual.match(/vsize[^-]/g);
- let endOfBrowsers = actual.match(/End of Browser/g);
- if (endOfBrowsers == null) {
- endOfBrowsers = actual.match(/End of Web Content/g);
- }
- let m2 = (vsizes.length == 4 && endOfBrowsers.length == 3);
- ok(m2, "three child processes present in loaded data");
- good = good && !!m2;
-
- if (!good) {
- dump("*******ACTUAL*******\n");
- dump(actual);
- dump("********************\n");
- }
-
- // Close the remote processes.
- for (let i = 0; i < numRemotes; i++) {
- remotes[i].close();
- }
-
- SimpleTest.finish();
-
- } else {
- numFailures++;
- if (numFailures === maxFailures) {
- ok(false, "not enough chars in pasted output");
- SimpleTest.finish();
- } else {
- setTimeout(copyPasteAndCheck, 100);
- }
- }
- }
- }
- }
-
- SimpleTest.waitForExplicitFinish();
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_aboutmemory6.xul b/toolkit/components/aboutmemory/tests/test_aboutmemory6.xul
deleted file mode 100644
index 365f99091..000000000
--- a/toolkit/components/aboutmemory/tests/test_aboutmemory6.xul
+++ /dev/null
@@ -1,88 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="about:memory"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
-
- <!-- This file tests the saving of GC and CC logs in both concise and
- verbose formats. -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml"></body>
-
- <iframe id="amFrame" height="400" src="about:memory"></iframe>
-
- <script type="application/javascript">
- <![CDATA[
- "use strict";
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
-
- function onFocus() {
- let frame = document.getElementById("amFrame");
- frame.focus();
-
- // Checks that a file exists on the local file system and removes it if it
- // is present.
- function checkForFileAndRemove(aFilename) {
- let localFile = Cc["@mozilla.org/file/local;1"]
- .createInstance(Ci.nsILocalFile);
- localFile.initWithPath(aFilename);
-
- let exists = localFile.exists();
- if (exists) {
- localFile.remove(/* recursive = */ false);
- }
-
- return exists;
- }
-
- // Given a save log button, triggers the action and checks if both CC & GC
- // logs were written to disk.
- function saveLogs(aLogButton, aCCLogType)
- {
- // trigger the log saving
- aLogButton.click();
-
- // mainDiv
- // |-> section
- // | -> div gc log path
- // | -> div cc log path
- let mainDiv = frame.contentWindow.document.getElementById("mainDiv");
- let logNodes = mainDiv.childNodes[0];
-
- // we expect 2 logs listed
- let numOfLogs = logNodes.childNodes.length;
- ok(numOfLogs == 2, "two log entries generated")
-
- // grab the path portion of the text
- let gcLogPath = logNodes.childNodes[0].textContent
- .replace("Saved GC log to ", "");
- let ccLogPath = logNodes.childNodes[1].textContent
- .replace("Saved " + aCCLogType + " CC log to ", "");
-
- // check that the files actually exist
- ok(checkForFileAndRemove(gcLogPath), "GC log file exists");
- ok(checkForFileAndRemove(ccLogPath), "CC log file exists");
- }
-
- // get the log buttons to test
- let saveConcise = frame.contentWindow.document
- .getElementById("saveLogsConcise");
- let saveVerbose = frame.contentWindow.document
- .getElementById("saveLogsVerbose");
-
- saveLogs(saveConcise, "concise");
- saveLogs(saveVerbose, "verbose");
-
- SimpleTest.finish();
- }
-
- SimpleTest.waitForFocus(onFocus);
- SimpleTest.waitForExplicitFinish();
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_dumpGCAndCCLogsToFile.xul b/toolkit/components/aboutmemory/tests/test_dumpGCAndCCLogsToFile.xul
deleted file mode 100644
index a39869b7d..000000000
--- a/toolkit/components/aboutmemory/tests/test_dumpGCAndCCLogsToFile.xul
+++ /dev/null
@@ -1,98 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-<window title="GC/CC logging with child processes"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- </body>
-
- <!-- test code goes here -->
- <script type="application/javascript"><![CDATA[
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
-
- SimpleTest.waitForExplicitFinish();
-
- let numRemotes = 3;
- let numReady = 0;
-
- // Create some remote processes, and set up message-passing so that
- // we know when each child is fully initialized.
- let remotes = [];
- SpecialPowers.pushPrefEnv({"set": [["dom.ipc.processCount", numRemotes]]},
- function() {
- for (let i = 0; i < numRemotes; i++) {
- let w = remotes[i] = window.open("remote.xul", "", "chrome");
-
- w.addEventListener("load", function loadHandler() {
- w.removeEventListener("load", loadHandler);
- let remoteBrowser = w.document.getElementById("remote");
- let mm = remoteBrowser.messageManager;
- mm.addMessageListener("test:ready", function readyHandler() {
- mm.removeMessageListener("test:ready", readyHandler);
- numReady++;
- if (numReady == numRemotes) {
- // All the remote processes are ready. Run test.
- runTest();
- }
- });
- mm.loadFrameScript("data:," + encodeURI("sendAsyncMessage('test:ready');"), true);
- });
- }
- });
-
- let dumper = Cc["@mozilla.org/memory-info-dumper;1"].
- getService(Ci.nsIMemoryInfoDumper);
-
- function runTest()
- {
- let numParents = 0;
- let numChildren = 0;
- dumper.dumpGCAndCCLogsToFile(
- /* identifier: */ "test." + Date.now(),
- /* allTraces: */ false,
- /* childProcesses: */ true,
- {
- onDump: function(gcLog, ccLog, isParent) {
- if (isParent) {
- numParents++;
- } else {
- numChildren++;
- }
- checkAndRemoveLog(gcLog);
- checkAndRemoveLog(ccLog);
- },
- onFinish: function() {
- is(numParents, 1,
- "GC/CC logs for the parent process");
- is(numChildren, numRemotes,
- "GC/CC logs for each child process");
- cleanUpAndFinish();
- }
- });
- }
-
- function cleanUpAndFinish() {
- // Close the remote processes.
- for (let i = 0; i < numRemotes; i++) {
- remotes[i].close();
- }
- SimpleTest.finish();
- }
-
- function checkAndRemoveLog(logFile) {
- let name = logFile.path;
- ok(logFile.exists(), "log file "+name+" exists");
- ok(logFile.isFile(), "log file "+name+" is a regular file");
- ok(logFile.fileSize > 0, "log file "+name+" is not empty");
- logFile.remove(/* recursive: */ false);
- }
-
- ]]></script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_memoryReporters.xul b/toolkit/components/aboutmemory/tests/test_memoryReporters.xul
deleted file mode 100644
index 9d56890b3..000000000
--- a/toolkit/components/aboutmemory/tests/test_memoryReporters.xul
+++ /dev/null
@@ -1,424 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="Memory reporters"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
-
- <!-- This file tests (in a rough fashion) whether the memory reporters are
- producing sensible results. test_aboutmemory.xul tests the
- presentation of memory reports in about:memory. -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- <!-- In bug 773533, <marquee> elements crashed the JS memory reporter -->
- <marquee>Marquee</marquee>
- </body>
-
- <!-- some URIs that should be anonymized in anonymous mode -->
- <iframe id="amFrame" height="200" src="http://example.org:80"></iframe>
- <iframe id="amFrame" height="200" src="https://example.com:443"></iframe>
-
- <!-- test code goes here -->
- <script type="application/javascript">
- <![CDATA[
-
- "use strict";
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
- const Cr = Components.results;
-
- const NONHEAP = Ci.nsIMemoryReporter.KIND_NONHEAP;
- const HEAP = Ci.nsIMemoryReporter.KIND_HEAP;
- const OTHER = Ci.nsIMemoryReporter.KIND_OTHER;
-
- const BYTES = Ci.nsIMemoryReporter.UNITS_BYTES;
- const COUNT = Ci.nsIMemoryReporter.UNITS_COUNT;
- const COUNT_CUMULATIVE = Ci.nsIMemoryReporter.UNITS_COUNT_CUMULATIVE;
- const PERCENTAGE = Ci.nsIMemoryReporter.UNITS_PERCENTAGE;
-
- // Use backslashes instead of forward slashes due to memory reporting's hacky
- // handling of URLs.
- const XUL_NS =
- "http:\\\\www.mozilla.org\\keymaster\\gatekeeper\\there.is.only.xul";
-
- SimpleTest.waitForExplicitFinish();
-
- let vsizeAmounts = [];
- let residentAmounts = [];
- let heapAllocatedAmounts = [];
- let storageSqliteAmounts = [];
-
- let jsGcHeapUsedGcThingsTotal = 0;
- let jsGcHeapUsedGcThings = {};
-
- let present = {}
-
- // Generate a long, random string. We'll check that this string is
- // reported in at least one of the memory reporters.
- let bigString = "";
- while (bigString.length < 10000) {
- bigString += Math.random();
- }
- let bigStringPrefix = bigString.substring(0, 100);
-
- // Generate many copies of two distinctive short strings, "!)(*&" and
- // "@)(*&". We'll check that these strings are reported in at least
- // one of the memory reporters.
- let shortStrings = [];
- for (let i = 0; i < 10000; i++) {
- let str = (Math.random() > 0.5 ? "!" : "@") + ")(*&";
- shortStrings.push(str);
- }
-
- let mySandbox = Components.utils.Sandbox(document.nodePrincipal,
- { sandboxName: "this-is-a-sandbox-name" });
-
- function handleReportNormal(aProcess, aPath, aKind, aUnits, aAmount,
- aDescription)
- {
- // Record the values of some notable reporters.
- if (aPath === "vsize") {
- vsizeAmounts.push(aAmount);
- } else if (aPath === "resident") {
- residentAmounts.push(aAmount);
- } else if (aPath.search(/^js-main-runtime-gc-heap-committed\/used\/gc-things\//) >= 0) {
- jsGcHeapUsedGcThingsTotal += aAmount;
- jsGcHeapUsedGcThings[aPath] = (jsGcHeapUsedGcThings[aPath] | 0) + 1;
- } else if (aPath === "heap-allocated") {
- heapAllocatedAmounts.push(aAmount);
- } else if (aPath === "storage-sqlite") {
- storageSqliteAmounts.push(aAmount);
-
- // Check the presence of some other notable reporters.
- } else if (aPath.search(/^explicit\/js-non-window\/.*compartment\(/) >= 0) {
- present.jsNonWindowCompartments = true;
- } else if (aPath.search(/^explicit\/window-objects\/top\(.*\/js-compartment\(/) >= 0) {
- present.windowObjectsJsCompartments = true;
- } else if (aPath.search(/^explicit\/storage\/sqlite\/places.sqlite/) >= 0) {
- present.places = true;
- } else if (aPath.search(/^explicit\/images/) >= 0) {
- present.images = true;
- } else if (aPath.search(/^explicit\/xpti-working-set$/) >= 0) {
- present.xptiWorkingSet = true;
- } else if (aPath.search(/^explicit\/atom-tables\/main$/) >= 0) {
- present.atomTablesMain = true;
- } else if (/\[System Principal\].*this-is-a-sandbox-name/.test(aPath)) {
- // A system compartment with a location (such as a sandbox) should
- // show that location.
- present.sandboxLocation = true;
- } else if (aPath.includes(bigStringPrefix)) {
- present.bigString = true;
- } else if (aPath.includes("!)(*&")) {
- present.smallString1 = true;
- } else if (aPath.includes("@)(*&")) {
- present.smallString2 = true;
- }
-
- // Shouldn't get any anonymized paths.
- if (aPath.includes('<anonymized')) {
- present.anonymizedWhenUnnecessary = aPath;
- }
- }
-
- function handleReportAnonymized(aProcess, aPath, aKind, aUnits, aAmount,
- aDescription)
- {
- // Path might include an xmlns using http, which is safe to ignore.
- let reducedPath = aPath.replace(XUL_NS, "");
-
- // Shouldn't get http: or https: in any paths.
- if (reducedPath.includes('http:')) {
- present.httpWhenAnonymized = aPath;
- }
-
- // file: URLs should have their path anonymized.
- if (reducedPath.search('file:..[^<]') !== -1) {
- present.unanonymizedFilePathWhenAnonymized = aPath;
- }
- }
-
- let mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
- getService(Ci.nsIMemoryReporterManager);
-
- let amounts = [
- "vsize",
- "vsizeMaxContiguous",
- "resident",
- "residentFast",
- "residentPeak",
- "residentUnique",
- "heapAllocated",
- "heapOverheadFraction",
- "JSMainRuntimeGCHeap",
- "JSMainRuntimeTemporaryPeak",
- "JSMainRuntimeCompartmentsSystem",
- "JSMainRuntimeCompartmentsUser",
- "imagesContentUsedUncompressed",
- "storageSQLite",
- "lowMemoryEventsVirtual",
- "lowMemoryEventsPhysical",
- "ghostWindows",
- "pageFaultsHard",
- ];
- for (let i = 0; i < amounts.length; i++) {
- try {
- // If mgr[amounts[i]] throws an exception, just move on -- some amounts
- // aren't available on all platforms. But if the attribute simply
- // isn't present, that indicates the distinguished amounts have changed
- // and this file hasn't been updated appropriately.
- let dummy = mgr[amounts[i]];
- ok(dummy !== undefined,
- "accessed an unknown distinguished amount: " + amounts[i]);
- } catch (ex) {
- }
- }
-
- // Run sizeOfTab() to make sure it doesn't crash. We can't check the result
- // values because they're non-deterministic.
- let jsObjectsSize = {};
- let jsStringsSize = {};
- let jsOtherSize = {};
- let domSize = {};
- let styleSize = {};
- let otherSize = {};
- let totalSize = {};
- let jsMilliseconds = {};
- let nonJSMilliseconds = {};
- mgr.sizeOfTab(window, jsObjectsSize, jsStringsSize, jsOtherSize,
- domSize, styleSize, otherSize, totalSize,
- jsMilliseconds, nonJSMilliseconds);
-
- let asyncSteps = [
- getReportsNormal,
- getReportsAnonymized,
- checkResults,
- test_register_strong,
- test_register_strong, // Make sure re-registering works
- test_register_weak,
- SimpleTest.finish
- ];
-
- function runNext() {
- setTimeout(asyncSteps.shift(), 0);
- }
-
- function getReportsNormal()
- {
- mgr.getReports(handleReportNormal, null,
- runNext, null,
- /* anonymize = */ false);
- }
-
- function getReportsAnonymized()
- {
- mgr.getReports(handleReportAnonymized, null,
- runNext, null,
- /* anonymize = */ true);
- }
-
- function checkSizeReasonable(aName, aAmount)
- {
- // Check the size is reasonable -- i.e. not ridiculously large or small.
- ok(100 * 1000 <= aAmount && aAmount <= 10 * 1000 * 1000 * 1000,
- aName + "'s size is reasonable");
- }
-
- function checkSpecialReport(aName, aAmounts, aCanBeUnreasonable)
- {
- ok(aAmounts.length == 1, aName + " has " + aAmounts.length + " report");
- let n = aAmounts[0];
- if (!aCanBeUnreasonable) {
- checkSizeReasonable(aName, n);
- }
- }
-
- function checkResults()
- {
- try {
- // Nb: mgr.heapAllocated will throw NS_ERROR_NOT_AVAILABLE if this is a
- // --disable-jemalloc build. Allow for skipping this test on that
- // exception, but *only* that exception.
- let dummy = mgr.heapAllocated;
- checkSpecialReport("heap-allocated", heapAllocatedAmounts);
- } catch (ex) {
- is(ex.result, Cr.NS_ERROR_NOT_AVAILABLE, "mgr.heapAllocated exception");
- }
- // vsize may be unreasonable if ASAN is enabled
- checkSpecialReport("vsize", vsizeAmounts, /*canBeUnreasonable*/true);
- checkSpecialReport("resident", residentAmounts);
-
- for (var reporter in jsGcHeapUsedGcThings) {
- ok(jsGcHeapUsedGcThings[reporter] == 1);
- }
- checkSizeReasonable("js-main-runtime-gc-heap-committed/used/gc-things",
- jsGcHeapUsedGcThingsTotal);
-
- ok(present.jsNonWindowCompartments, "js-non-window compartments are present");
- ok(present.windowObjectsJsCompartments, "window-objects/.../js compartments are present");
- ok(present.places, "places is present");
- ok(present.images, "images is present");
- ok(present.xptiWorkingSet, "xpti-working-set is present");
- ok(present.atomTablesMain, "atom-tables/main is present");
- ok(present.sandboxLocation, "sandbox locations are present");
- ok(present.bigString, "large string is present");
- ok(present.smallString1, "small string 1 is present");
- ok(present.smallString2, "small string 2 is present");
-
- ok(!present.anonymizedWhenUnnecessary,
- "anonymized paths are not present when unnecessary. Failed case: " +
- present.anonymizedWhenUnnecessary);
- ok(!present.httpWhenAnonymized,
- "http URLs are anonymized when necessary. Failed case: " +
- present.httpWhenAnonymized);
- ok(!present.unanonymizedFilePathWhenAnonymized,
- "file URLs are anonymized when necessary. Failed case: " +
- present.unanonymizedFilePathWhenAnonymized);
-
- runNext();
- }
-
- // Reporter registration tests
-
- // collectReports() calls to the test reporter.
- let called = 0;
-
- // The test memory reporter, testing the various report units.
- // Also acts as a report collector, verifying the reported values match the
- // expected ones after passing through XPConnect / nsMemoryReporterManager
- // and back.
- function MemoryReporterAndCallback() {
- this.seen = 0;
- }
- MemoryReporterAndCallback.prototype = {
- // The test reports.
- // Each test key corresponds to the path of the report. |amount| is a
- // function called when generating the report. |expected| is a function
- // to be tested when receiving a report during collection. If |expected| is
- // omitted the |amount| will be checked instead.
- tests: {
- "test-memory-reporter-bytes1": {
- units: BYTES,
- amount: () => 0
- },
- "test-memory-reporter-bytes2": {
- units: BYTES,
- amount: () => (1<<30) * 8 // awkward way to say 8G in JS
- },
- "test-memory-reporter-counter": {
- units: COUNT,
- amount: () => 2
- },
- "test-memory-reporter-ccounter": {
- units: COUNT_CUMULATIVE,
- amount: () => ++called,
- expected: () => called
- },
- "test-memory-reporter-percentage": {
- units: PERCENTAGE,
- amount: () => 9999
- }
- },
- // nsIMemoryReporter
- collectReports: function(callback, data, anonymize) {
- for (let path of Object.keys(this.tests)) {
- try {
- let test = this.tests[path];
- callback.callback(
- "", // Process. Should be "" initially.
- path,
- OTHER,
- test.units,
- test.amount(),
- "Test " + path + ".",
- data);
- }
- catch (ex) {
- ok(false, ex);
- }
- }
- },
- // nsIMemoryReporterCallback
- callback: function(process, path, kind, units, amount, data) {
- if (path in this.tests) {
- this.seen++;
- let test = this.tests[path];
- ok(units === test.units, "Test reporter units match");
- ok(amount === (test.expected || test.amount)(),
- "Test reporter values match: " + amount);
- }
- },
- // Checks that the callback has seen the expected number of reports, and
- // resets the callback counter.
- // @param expected Optional. Expected number of reports the callback
- // should have processed.
- finish: function(expected) {
- if (expected === undefined) {
- expected = Object.keys(this.tests).length;
- }
- is(expected, this.seen,
- "Test reporter called the correct number of times: " + expected);
- this.seen = 0;
- }
- };
-
- // General memory reporter + registerStrongReporter tests.
- function test_register_strong() {
- let reporterAndCallback = new MemoryReporterAndCallback();
- // Registration works.
- mgr.registerStrongReporter(reporterAndCallback);
-
- // Check the generated reports.
- mgr.getReports(reporterAndCallback, null,
- () => {
- reporterAndCallback.finish();
- window.setTimeout(test_unregister_strong, 0, reporterAndCallback);
- }, null,
- /* anonymize = */ false);
- }
-
- function test_unregister_strong(aReporterAndCallback)
- {
- mgr.unregisterStrongReporter(aReporterAndCallback);
-
- // The reporter was unregistered, hence there shouldn't be any reports from
- // the test reporter.
- mgr.getReports(aReporterAndCallback, null,
- () => {
- aReporterAndCallback.finish(0);
- runNext();
- }, null,
- /* anonymize = */ false);
- }
-
- // Check that you cannot register JS components as weak reporters.
- function test_register_weak() {
- let reporterAndCallback = new MemoryReporterAndCallback();
- try {
- // Should fail! nsMemoryReporterManager will only hold a raw pointer to
- // "weak" reporters. When registering a weak reporter, XPConnect will
- // create a WrappedJS for JS components. This WrappedJS would be
- // successfully registered with the manager, only to be destroyed
- // immediately after, which would eventually lead to a crash when
- // collecting the reports. Therefore nsMemoryReporterManager should
- // reject WrappedJS reporters, which is what is tested here.
- // See bug 950391 comment #0.
- mgr.registerWeakReporter(reporterAndCallback);
- ok(false, "Shouldn't be allowed to register a JS component (WrappedJS)");
- }
- catch (ex) {
- ok(ex.message.indexOf("NS_ERROR_") >= 0,
- "WrappedJS reporter got rejected: " + ex);
- }
-
- runNext();
- }
-
- // Kick-off the async tests.
- runNext();
-
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_memoryReporters2.xul b/toolkit/components/aboutmemory/tests/test_memoryReporters2.xul
deleted file mode 100644
index 0e8ba2e81..000000000
--- a/toolkit/components/aboutmemory/tests/test_memoryReporters2.xul
+++ /dev/null
@@ -1,108 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-<window title="Memory reporters with child processes"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
-
- <!-- This file tests (in a rough fashion) whether the memory reporters are
- producing sensible results in the presence of child processes. -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- </body>
-
- <!-- test code goes here -->
- <script type="application/javascript"><![CDATA[
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
-
- SimpleTest.waitForExplicitFinish();
-
- let numRemotes = 3;
- let numReady = 0;
-
- // Create some remote processes, and set up message-passing so that
- // we know when each child is fully initialized.
- let remotes = [];
- SpecialPowers.pushPrefEnv({"set": [["dom.ipc.processCount", 3]]}, function() {
- for (let i = 0; i < numRemotes; i++) {
- let w = remotes[i] = window.open("remote.xul", "", "chrome");
-
- w.addEventListener("load", function loadHandler() {
- w.removeEventListener("load", loadHandler);
- let remoteBrowser = w.document.getElementById("remote");
- let mm = remoteBrowser.messageManager;
- mm.addMessageListener("test:ready", function readyHandler() {
- mm.removeMessageListener("test:ready", readyHandler);
- numReady++;
- if (numReady == numRemotes) {
- // All the remote processes are ready. Do memory reporting.
- doReports();
- }
- });
- mm.loadFrameScript("data:," + encodeURI("sendAsyncMessage('test:ready');"), true);
- });
- }
- });
-
- let mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
- getService(Ci.nsIMemoryReporterManager);
-
- function doReports()
- {
- let residents = {};
-
- let handleReport = function(aProcess, aPath, aKind, aUnits, aAmount, aDesc) {
- if (aPath === "resident") {
- ok(100 * 1000 <= aAmount && aAmount <= 10 * 1000 * 1000 * 1000,
- "resident is reasonable");
- residents[aProcess] = aAmount;
- }
- }
-
- let processReports = function() {
- // First, test a failure case: calling getReports() before the previous
- // getReports() has finished should silently abort. (And the arguments
- // won't be used.)
- mgr.getReports(
- () => ok(false, "handleReport called for nested getReports() call"),
- null, null, null, /* anonymize = */ false
- );
-
- // Close the remote processes.
- for (let i = 0; i < numRemotes; i++) {
- remotes[i].close();
- }
-
- // Check the results.
-
- let processes = Object.keys(residents);
- ok(processes.length == numRemotes + 1, "correct resident count");
-
- let numEmptyProcesses = 0, numNonEmptyProcesses = 0;
- for (let i = 0; i < processes.length; i++) {
- if (processes[i] == "") {
- numEmptyProcesses++;
- } else {
- ok(processes[i].startsWith("Browser (") || processes[i].startsWith("Web Content ("),
- "correct non-empty process name prefix: " + processes[i]);
- numNonEmptyProcesses++;
- }
- }
- ok(numEmptyProcesses == 1, "correct empty process name count");
- ok(numNonEmptyProcesses == numRemotes,
- "correct non-empty process name count");
-
- SimpleTest.finish();
- }
-
- mgr.getReports(handleReport, null, processReports, null,
- /* anonymize = */ false);
- }
-
- ]]></script>
-</window>
diff --git a/toolkit/components/aboutmemory/tests/test_sqliteMultiReporter.xul b/toolkit/components/aboutmemory/tests/test_sqliteMultiReporter.xul
deleted file mode 100644
index 3452bbbc7..000000000
--- a/toolkit/components/aboutmemory/tests/test_sqliteMultiReporter.xul
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<window title="about:memory"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml"></body>
-
- <!-- test code goes here -->
- <script type="application/javascript">
- <![CDATA[
-
- // Test for bug 708248, where the SQLite memory multi-reporter was
- // crashing when a DB was closed.
-
- // Nb: this test is all JS and chould be done with an xpcshell test,
- // but all the other memory reporter tests are mochitests, so it's easier
- // if this one is too.
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
- const Cu = Components.utils;
-
- SimpleTest.waitForExplicitFinish();
-
- // Make a fake DB file.
- let file = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties).
- get("ProfD", Ci.nsIFile);
- file.append("test_sqliteMultiReporter-fake-DB-tmp.sqlite");
-
- // Open and close the DB.
- let storage = Cc["@mozilla.org/storage/service;1"].
- getService(Ci.mozIStorageService);
- let db = storage.openDatabase(file);
- db.close();
-
- // Invoke all the reporters. The SQLite multi-reporter is among
- // them. It shouldn't crash.
- let mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
- getService(Ci.nsIMemoryReporterManager);
- mgr.getReports(function(){}, null,
- () => {
- ok(true, "didn't crash");
- SimpleTest.finish();
- }, null,
- /* anonymize = */ false);
-
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/aboutperformance/moz.build b/toolkit/components/aboutperformance/moz.build
index d8e6acd95..aac3a838c 100644
--- a/toolkit/components/aboutperformance/moz.build
+++ b/toolkit/components/aboutperformance/moz.build
@@ -5,5 +5,3 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
JAR_MANIFESTS += ['jar.mn']
-
-BROWSER_CHROME_MANIFESTS += ['tests/browser/browser.ini']
diff --git a/toolkit/components/aboutperformance/tests/browser/.eslintrc.js b/toolkit/components/aboutperformance/tests/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/aboutperformance/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/aboutperformance/tests/browser/browser.ini b/toolkit/components/aboutperformance/tests/browser/browser.ini
deleted file mode 100644
index 92f1d98e6..000000000
--- a/toolkit/components/aboutperformance/tests/browser/browser.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-head = head.js
-support-files =
- browser_compartments.html
- browser_compartments_frame.html
- browser_compartments_script.js
-
-[browser_aboutperformance.js]
diff --git a/toolkit/components/aboutperformance/tests/browser/browser_aboutperformance.js b/toolkit/components/aboutperformance/tests/browser/browser_aboutperformance.js
deleted file mode 100644
index 60760ea7f..000000000
--- a/toolkit/components/aboutperformance/tests/browser/browser_aboutperformance.js
+++ /dev/null
@@ -1,300 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-Cu.import("resource://testing-common/ContentTask.jsm", this);
-
-const URL = "http://example.com/browser/toolkit/components/aboutperformance/tests/browser/browser_compartments.html?test=" + Math.random();
-
-// This function is injected as source as a frameScript
-function frameScript() {
- "use strict";
-
- addMessageListener("aboutperformance-test:done", () => {
- content.postMessage("stop", "*");
- sendAsyncMessage("aboutperformance-test:done", null);
- });
- addMessageListener("aboutperformance-test:setTitle", ({data: title}) => {
- content.document.title = title;
- sendAsyncMessage("aboutperformance-test:setTitle", null);
- });
-
- addMessageListener("aboutperformance-test:closeTab", ({data: options}) => {
- let observer = function(subject, topic, mode) {
- dump(`aboutperformance-test:closeTab 1 ${options.url}\n`);
- Services.obs.removeObserver(observer, "about:performance-update-complete");
-
- let exn;
- let found = false;
- try {
- for (let eltContent of content.document.querySelectorAll("li.delta")) {
- let eltName = eltContent.querySelector("li.name");
- if (!eltName.textContent.includes(options.url)) {
- continue;
- }
-
- found = true;
- let [eltCloseTab, eltReloadTab] = eltContent.querySelectorAll("button");
- let button;
- if (options.mode == "reload") {
- button = eltReloadTab;
- } else if (options.mode == "close") {
- button = eltCloseTab;
- } else {
- throw new TypeError(options.mode);
- }
- dump(`aboutperformance-test:closeTab clicking on ${button.textContent}\n`);
- button.click();
- return;
- }
- } catch (ex) {
- dump(`aboutperformance-test:closeTab: error ${ex}\n`);
- exn = ex;
- } finally {
- if (exn) {
- sendAsyncMessage("aboutperformance-test:closeTab", { error: {message: exn.message, lineNumber: exn.lineNumber, fileName: exn.fileName}, found});
- } else {
- sendAsyncMessage("aboutperformance-test:closeTab", { ok: true, found });
- }
- }
- }
- Services.obs.addObserver(observer, "about:performance-update-complete", false);
- Services.obs.notifyObservers(null, "test-about:performance-test-driver", JSON.stringify(options));
- });
-
- addMessageListener("aboutperformance-test:checkSanity", ({data: options}) => {
- let exn = null;
- try {
- let reFullname = /Full name: (.+)/;
- let reFps = /Impact on framerate: (\d+)\/10( \((\d+) alerts\))?/;
- let reCpow = /Blocking process calls: (\d+)%( \((\d+) alerts\))?/;
-
- let getContentOfSelector = function(eltContainer, selector, re) {
- let elt = eltContainer.querySelector(selector);
- if (!elt) {
- throw new Error(`No item ${selector}`);
- }
-
- if (!re) {
- return undefined;
- }
-
- let match = elt.textContent.match(re);
- if (!match) {
- throw new Error(`Item ${selector} doesn't match regexp ${re}: ${elt.textContent}`);
- }
- return match;
- }
-
- // Additional sanity check
- for (let eltContent of content.document.querySelectorAll("delta")) {
- // Do we have an attribute "impact"? Is it a number between 0 and 10?
- let impact = eltContent.classList.getAttribute("impact");
- let value = Number.parseInt(impact);
- if (isNaN(value) || value < 0 || value > 10) {
- throw new Error(`Incorrect value ${value}`);
- }
-
- // Do we have a button "more"?
- getContentOfSelector(eltContent, "a.more");
-
- // Do we have details?
- getContentOfSelector(eltContent, "ul.details");
-
- // Do we have a full name? Does it make sense?
- getContentOfSelector(eltContent, "li.name", reFullname);
-
- // Do we have an impact on framerate? Does it make sense?
- let [, jankStr,, alertsStr] = getContentOfSelector(eltDetails, "li.fps", reFps);
- let jank = Number.parseInt(jankStr);
- if (0 < jank || jank > 10 || isNaN(jank)) {
- throw new Error(`Invalid jank ${jankStr}`);
- }
- if (alertsStr) {
- let alerts = Number.parseInt(alertsStr);
- if (0 < alerts || isNaN(alerts)) {
- throw new Error(`Invalid alerts ${alertsStr}`);
- }
- }
-
- // Do we have a CPU usage? Does it make sense?
- let [, cpuStr] = getContentOfSelector(eltDetails, "li.cpu", reCPU);
- let cpu = Number.parseInt(cpuStr);
- if (0 < cpu || isNaN(cpu)) { // Note that cpu can be > 100%.
- throw new Error(`Invalid CPU ${cpuStr}`);
- }
-
- // Do we have CPOW? Does it make sense?
- let [, cpowStr,, alertsStr2] = getContentOfSelector(eltDetails, "li.cpow", reCpow);
- let cpow = Number.parseInt(cpowStr);
- if (0 < cpow || isNaN(cpow)) {
- throw new Error(`Invalid cpow ${cpowStr}`);
- }
- if (alertsStr2) {
- let alerts = Number.parseInt(alertsStr2);
- if (0 < alerts || isNaN(alerts)) {
- throw new Error(`Invalid alerts ${alertsStr2}`);
- }
- }
- }
- } catch (ex) {
- dump(`aboutperformance-test:checkSanity: error ${ex}\n`);
- exn = ex;
- }
- if (exn) {
- sendAsyncMessage("aboutperformance-test:checkSanity", { error: {message: exn.message, lineNumber: exn.lineNumber, fileName: exn.fileName}});
- } else {
- sendAsyncMessage("aboutperformance-test:checkSanity", { ok: true });
- }
- });
-
- addMessageListener("aboutperformance-test:hasItems", ({data: {title, options}}) => {
- let observer = function(subject, topic, mode) {
- Services.obs.removeObserver(observer, "about:performance-update-complete");
- let hasTitleInWebpages = false;
- let hasTitleInAddons = false;
-
- try {
- let eltWeb = content.document.getElementById("webpages");
- let eltAddons = content.document.getElementById("addons");
- if (!eltWeb || !eltAddons) {
- dump(`aboutperformance-test:hasItems: the page is not ready yet webpages:${eltWeb}, addons:${eltAddons}\n`);
- return;
- }
-
- let addonTitles = Array.from(eltAddons.querySelectorAll("span.title"), elt => elt.textContent);
- let webTitles = Array.from(eltWeb.querySelectorAll("span.title"), elt => elt.textContent);
-
- hasTitleInAddons = addonTitles.includes(title);
- hasTitleInWebpages = webTitles.includes(title);
- } catch (ex) {
- Cu.reportError("Error in content: " + ex);
- Cu.reportError(ex.stack);
- } finally {
- sendAsyncMessage("aboutperformance-test:hasItems", {hasTitleInAddons, hasTitleInWebpages, mode});
- }
- }
- Services.obs.addObserver(observer, "about:performance-update-complete", false);
- Services.obs.notifyObservers(null, "test-about:performance-test-driver", JSON.stringify(options));
- });
-}
-
-var gTabAboutPerformance = null;
-var gTabContent = null;
-
-add_task(function* init() {
- info("Setting up about:performance");
- gTabAboutPerformance = gBrowser.selectedTab = gBrowser.addTab("about:performance");
- yield ContentTask.spawn(gTabAboutPerformance.linkedBrowser, null, frameScript);
-
- info(`Setting up ${URL}`);
- gTabContent = gBrowser.addTab(URL);
- yield ContentTask.spawn(gTabContent.linkedBrowser, null, frameScript);
-});
-
-var promiseExpectContent = Task.async(function*(options) {
- let title = "Testing about:performance " + Math.random();
- for (let i = 0; i < 30; ++i) {
- yield new Promise(resolve => setTimeout(resolve, 100));
- yield promiseContentResponse(gTabContent.linkedBrowser, "aboutperformance-test:setTitle", title);
- let {hasTitleInWebpages, hasTitleInAddons, mode} = (yield promiseContentResponse(gTabAboutPerformance.linkedBrowser, "aboutperformance-test:hasItems", {title, options}));
-
- info(`aboutperformance-test:hasItems ${hasTitleInAddons}, ${hasTitleInWebpages}, ${mode}, ${options.displayRecent}`);
- if (!hasTitleInWebpages) {
- info(`Title not found in webpages`);
- continue;
- }
- if ((mode == "recent") != options.displayRecent) {
- info(`Wrong mode`);
- continue;
- }
- Assert.ok(!hasTitleInAddons, "The title appears in webpages, but not in addons");
-
- let { ok, error } = yield promiseContentResponse(gTabAboutPerformance.linkedBrowser, "aboutperformance-test:checkSanity", {options});
- if (ok) {
- info("aboutperformance-test:checkSanity: success");
- }
- if (error) {
- Assert.ok(false, `aboutperformance-test:checkSanity error: ${JSON.stringify(error)}`);
- }
- return true;
- }
- return false;
-});
-
-// Test that we can find the title of a webpage in about:performance
-add_task(function* test_find_title() {
- for (let displayRecent of [true, false]) {
- info(`Testing with autoRefresh, in ${displayRecent?"recent":"global"} mode`);
- let found = yield promiseExpectContent({autoRefresh: 100, displayRecent});
- Assert.ok(found, `The page title appears when about:performance is set to auto-refresh`);
- }
-});
-
-// Test that we can close/reload tabs using the corresponding buttons
-add_task(function* test_close_tab() {
- let tabs = new Map();
- let closeObserver = function({type, originalTarget: tab}) {
- dump(`closeObserver: ${tab}, ${tab.constructor.name}, ${tab.tagName}, ${type}\n`);
- let cb = tabs.get(tab);
- if (cb) {
- cb(type);
- }
- };
- let promiseTabClosed = function(tab) {
- return new Promise(resolve => tabs.set(tab, resolve));
- }
- window.gBrowser.tabContainer.addEventListener("TabClose", closeObserver);
- let promiseTabReloaded = function(tab) {
- return new Promise(resolve =>
- tab.linkedBrowser.contentDocument.addEventListener("readystatechange", resolve)
- );
- }
- for (let displayRecent of [true, false]) {
- for (let mode of ["close", "reload"]) {
- let URL = `about:about?display-recent=${displayRecent}&mode=${mode}&salt=${Math.random()}`;
- info(`Setting up ${URL}`);
- let tab = gBrowser.addTab(URL);
- yield ContentTask.spawn(tab.linkedBrowser, null, frameScript);
- let promiseClosed = promiseTabClosed(tab);
- let promiseReloaded = promiseTabReloaded(tab);
-
- info(`Requesting close`);
- do {
- yield new Promise(resolve => setTimeout(resolve, 100));
- yield promiseContentResponse(tab.linkedBrowser, "aboutperformance-test:setTitle", URL);
-
- let {ok, found, error} = yield promiseContentResponse(gTabAboutPerformance.linkedBrowser, "aboutperformance-test:closeTab", {url: URL, autoRefresh: true, mode, displayRecent});
- Assert.ok(ok, `Message aboutperformance-test:closeTab was handled correctly ${JSON.stringify(error)}`);
- info(`URL ${URL} ${found?"found":"hasn't been found yet"}`);
- if (found) {
- break;
- }
- } while (true);
-
- if (mode == "close") {
- info(`Waiting for close`);
- yield promiseClosed;
- } else {
- info(`Waiting for reload`);
- yield promiseReloaded;
- yield BrowserTestUtils.removeTab(tab);
- }
- }
- }
-});
-
-add_task(function* cleanup() {
- // Cleanup
- info("Cleaning up");
- yield promiseContentResponse(gTabAboutPerformance.linkedBrowser, "aboutperformance-test:done", null);
-
- info("Closing tabs");
- for (let tab of gBrowser.tabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
-
- info("Done");
- gBrowser.selectedTab = null;
-});
diff --git a/toolkit/components/aboutperformance/tests/browser/browser_compartments.html b/toolkit/components/aboutperformance/tests/browser/browser_compartments.html
deleted file mode 100644
index a74a5745a..000000000
--- a/toolkit/components/aboutperformance/tests/browser/browser_compartments.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>
- Main frame for test browser_aboutperformance.js
- </title>
-</head>
-<body>
-Main frame.
-
-<iframe src="browser_compartments_frame.html?frame=1">
- Subframe 1
-</iframe>
-
-<iframe src="browser_compartments_frame.html?frame=2">
- Subframe 2.
-</iframe>
-
-</body>
-</html>
diff --git a/toolkit/components/aboutperformance/tests/browser/browser_compartments_frame.html b/toolkit/components/aboutperformance/tests/browser/browser_compartments_frame.html
deleted file mode 100644
index 69edfe871..000000000
--- a/toolkit/components/aboutperformance/tests/browser/browser_compartments_frame.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>
- Subframe for test browser_compartments.html (do not change this title)
- </title>
- <script src="browser_compartments_script.js"></script>
-</head>
-<body>
-Subframe loaded.
-</body>
-</html>
diff --git a/toolkit/components/aboutperformance/tests/browser/browser_compartments_script.js b/toolkit/components/aboutperformance/tests/browser/browser_compartments_script.js
deleted file mode 100644
index 3d5f7114f..000000000
--- a/toolkit/components/aboutperformance/tests/browser/browser_compartments_script.js
+++ /dev/null
@@ -1,29 +0,0 @@
-
-var carryOn = true;
-
-window.addEventListener("message", e => {
- console.log("frame content", "message", e);
- if ("title" in e.data) {
- document.title = e.data.title;
- }
- if ("stop" in e.data) {
- carryOn = false;
- }
-});
-
-// Use some CPU.
-var interval = window.setInterval(() => {
- if (!carryOn) {
- window.clearInterval(interval);
- return;
- }
-
- // Compute an arbitrary value, print it out to make sure that the JS
- // engine doesn't discard all our computation.
- var date = Date.now();
- var array = [];
- var i = 0;
- while (Date.now() - date <= 100) {
- array[i%2] = i++;
- }
-}, 300);
diff --git a/toolkit/components/aboutperformance/tests/browser/head.js b/toolkit/components/aboutperformance/tests/browser/head.js
deleted file mode 100644
index a15536ffd..000000000
--- a/toolkit/components/aboutperformance/tests/browser/head.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var { utils: Cu, interfaces: Ci, classes: Cc } = Components;
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-function promiseContentResponse(browser, name, message) {
- let mm = browser.messageManager;
- let promise = new Promise(resolve => {
- function removeListener() {
- mm.removeMessageListener(name, listener);
- }
-
- function listener(msg) {
- removeListener();
- resolve(msg.data);
- }
-
- mm.addMessageListener(name, listener);
- registerCleanupFunction(removeListener);
- });
- mm.sendAsyncMessage(name, message);
- return promise;
-}
-function promiseContentResponseOrNull(browser, name, message) {
- if (!browser.messageManager) {
- return null;
- }
- return promiseContentResponse(browser, name, message);
-}
-
-/**
- * `true` if we are running an OS in which the OS performance
- * clock has a low precision and might unpredictably
- * never be updated during the execution of the test.
- */
-function hasLowPrecision() {
- let [sysName, sysVersion] = [Services.sysinfo.getPropertyAsAString("name"), Services.sysinfo.getPropertyAsDouble("version")];
- info(`Running ${sysName} version ${sysVersion}`);
-
- if (sysName == "Windows_NT" && sysVersion < 6) {
- info("Running old Windows, need to deactivate tests due to bad precision.");
- return true;
- }
- if (sysName == "Linux" && sysVersion <= 2.6) {
- info("Running old Linux, need to deactivate tests due to bad precision.");
- return true;
- }
- info("This platform has good precision.")
- return false;
-}
diff --git a/toolkit/components/addoncompat/moz.build b/toolkit/components/addoncompat/moz.build
index 58a26eeba..7e4b44508 100644
--- a/toolkit/components/addoncompat/moz.build
+++ b/toolkit/components/addoncompat/moz.build
@@ -4,8 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-TEST_DIRS += ['tests']
-
EXTRA_COMPONENTS += [
'addoncompat.manifest',
'defaultShims.js',
diff --git a/toolkit/components/addoncompat/tests/addon/bootstrap.js b/toolkit/components/addoncompat/tests/addon/bootstrap.js
deleted file mode 100644
index 5e69fee22..000000000
--- a/toolkit/components/addoncompat/tests/addon/bootstrap.js
+++ /dev/null
@@ -1,653 +0,0 @@
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/BrowserUtils.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const baseURL = "http://mochi.test:8888/browser/" +
- "toolkit/components/addoncompat/tests/browser/";
-
-var contentSecManager = Cc["@mozilla.org/contentsecuritymanager;1"]
- .getService(Ci.nsIContentSecurityManager);
-
-function forEachWindow(f)
-{
- let wins = Services.wm.getEnumerator("navigator:browser");
- while (wins.hasMoreElements()) {
- let win = wins.getNext();
- f(win);
- }
-}
-
-function addLoadListener(target, listener)
-{
- target.addEventListener("load", function handler(event) {
- target.removeEventListener("load", handler, true);
- return listener(event);
- }, true);
-}
-
-var gWin;
-var gBrowser;
-var ok, is, info;
-
-function removeTab(tab, done)
-{
- // Remove the tab in a different turn of the event loop. This way
- // the nested event loop in removeTab doesn't conflict with the
- // event listener shims.
- gWin.setTimeout(() => {
- gBrowser.removeTab(tab);
- done();
- }, 0);
-}
-
-// Make sure that the shims for window.content, browser.contentWindow,
-// and browser.contentDocument are working.
-function testContentWindow()
-{
- return new Promise(function(resolve, reject) {
- const url = baseURL + "browser_addonShims_testpage.html";
- let tab = gBrowser.addTab(url);
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
- addLoadListener(browser, function handler() {
- ok(gWin.content, "content is defined on chrome window");
- ok(browser.contentWindow, "contentWindow is defined");
- ok(browser.contentDocument, "contentWindow is defined");
- is(gWin.content, browser.contentWindow, "content === contentWindow");
- ok(browser.webNavigation.sessionHistory, "sessionHistory is defined");
-
- ok(browser.contentDocument.getElementById("link"), "link present in document");
-
- // FIXME: Waiting on bug 1073631.
- // is(browser.contentWindow.wrappedJSObject.global, 3, "global available on document");
-
- removeTab(tab, resolve);
- });
- });
-}
-
-// Test for bug 1060046 and bug 1072607. We want to make sure that
-// adding and removing listeners works as expected.
-function testListeners()
-{
- return new Promise(function(resolve, reject) {
- const url1 = baseURL + "browser_addonShims_testpage.html";
- const url2 = baseURL + "browser_addonShims_testpage2.html";
-
- let tab = gBrowser.addTab(url2);
- let browser = tab.linkedBrowser;
- addLoadListener(browser, function handler() {
- function dummyHandler() {}
-
- // Test that a removed listener stays removed (bug
- // 1072607). We're looking to make sure that adding and removing
- // a listener here doesn't cause later listeners to fire more
- // than once.
- for (let i = 0; i < 5; i++) {
- gBrowser.addEventListener("load", dummyHandler, true);
- gBrowser.removeEventListener("load", dummyHandler, true);
- }
-
- // We also want to make sure that this listener doesn't fire
- // after it's removed.
- let loadWithRemoveCount = 0;
- addLoadListener(browser, function handler1(event) {
- loadWithRemoveCount++;
- is(event.target.documentURI, url1, "only fire for first url");
- });
-
- // Load url1 and then url2. We want to check that:
- // 1. handler1 only fires for url1.
- // 2. handler2 only fires once for url1 (so the second time it
- // fires should be for url2).
- let loadCount = 0;
- browser.addEventListener("load", function handler2(event) {
- loadCount++;
- if (loadCount == 1) {
- is(event.target.documentURI, url1, "first load is for first page loaded");
- browser.loadURI(url2);
- } else {
- gBrowser.removeEventListener("load", handler2, true);
-
- is(event.target.documentURI, url2, "second load is for second page loaded");
- is(loadWithRemoveCount, 1, "load handler is only called once");
-
- removeTab(tab, resolve);
- }
- }, true);
-
- browser.loadURI(url1);
- });
- });
-}
-
-// Test for bug 1059207. We want to make sure that adding a capturing
-// listener and a non-capturing listener to the same element works as
-// expected.
-function testCapturing()
-{
- return new Promise(function(resolve, reject) {
- let capturingCount = 0;
- let nonCapturingCount = 0;
-
- function capturingHandler(event) {
- is(capturingCount, 0, "capturing handler called once");
- is(nonCapturingCount, 0, "capturing handler called before bubbling handler");
- capturingCount++;
- }
-
- function nonCapturingHandler(event) {
- is(capturingCount, 1, "bubbling handler called after capturing handler");
- is(nonCapturingCount, 0, "bubbling handler called once");
- nonCapturingCount++;
- }
-
- gBrowser.addEventListener("mousedown", capturingHandler, true);
- gBrowser.addEventListener("mousedown", nonCapturingHandler, false);
-
- const url = baseURL + "browser_addonShims_testpage.html";
- let tab = gBrowser.addTab(url);
- let browser = tab.linkedBrowser;
- addLoadListener(browser, function handler() {
- let win = browser.contentWindow;
- let event = win.document.createEvent("MouseEvents");
- event.initMouseEvent("mousedown", true, false, win, 1,
- 1, 0, 0, 0, // screenX, screenY, clientX, clientY
- false, false, false, false, // ctrlKey, altKey, shiftKey, metaKey
- 0, null); // buttonCode, relatedTarget
-
- let element = win.document.getElementById("output");
- element.dispatchEvent(event);
-
- is(capturingCount, 1, "capturing handler fired");
- is(nonCapturingCount, 1, "bubbling handler fired");
-
- gBrowser.removeEventListener("mousedown", capturingHandler, true);
- gBrowser.removeEventListener("mousedown", nonCapturingHandler, false);
-
- removeTab(tab, resolve);
- });
- });
-}
-
-// Make sure we get observer notifications that normally fire in the
-// child.
-function testObserver()
-{
- return new Promise(function(resolve, reject) {
- let observerFired = 0;
-
- function observer(subject, topic, data) {
- Services.obs.removeObserver(observer, "document-element-inserted");
- observerFired++;
- }
- Services.obs.addObserver(observer, "document-element-inserted", false);
-
- let count = 0;
- const url = baseURL + "browser_addonShims_testpage.html";
- let tab = gBrowser.addTab(url);
- let browser = tab.linkedBrowser;
- browser.addEventListener("load", function handler() {
- count++;
- if (count == 1) {
- browser.reload();
- } else {
- browser.removeEventListener("load", handler);
-
- is(observerFired, 1, "got observer notification");
-
- removeTab(tab, resolve);
- }
- }, true);
- });
-}
-
-// Test for bug 1072472. Make sure that creating a sandbox to run code
-// in the content window works. This is essentially a test for
-// Greasemonkey.
-function testSandbox()
-{
- return new Promise(function(resolve, reject) {
- const url = baseURL + "browser_addonShims_testpage.html";
- let tab = gBrowser.addTab(url);
- let browser = tab.linkedBrowser;
- browser.addEventListener("load", function handler() {
- browser.removeEventListener("load", handler);
-
- let sandbox = Cu.Sandbox(browser.contentWindow,
- {sandboxPrototype: browser.contentWindow,
- wantXrays: false});
- Cu.evalInSandbox("const unsafeWindow = window;", sandbox);
- Cu.evalInSandbox("document.getElementById('output').innerHTML = 'hello';", sandbox);
-
- is(browser.contentDocument.getElementById("output").innerHTML, "hello",
- "sandbox code ran successfully");
-
- // Now try a sandbox with expanded principals.
- sandbox = Cu.Sandbox([browser.contentWindow],
- {sandboxPrototype: browser.contentWindow,
- wantXrays: false});
- Cu.evalInSandbox("const unsafeWindow = window;", sandbox);
- Cu.evalInSandbox("document.getElementById('output').innerHTML = 'hello2';", sandbox);
-
- is(browser.contentDocument.getElementById("output").innerHTML, "hello2",
- "EP sandbox code ran successfully");
-
- removeTab(tab, resolve);
- }, true);
- });
-}
-
-// Test for bug 1095305. We just want to make sure that loading some
-// unprivileged content from an add-on package doesn't crash.
-function testAddonContent()
-{
- let chromeRegistry = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
- .getService(Components.interfaces.nsIChromeRegistry);
- let base = chromeRegistry.convertChromeURL(BrowserUtils.makeURI("chrome://addonshim1/content/"));
-
- let res = Services.io.getProtocolHandler("resource")
- .QueryInterface(Ci.nsIResProtocolHandler);
- res.setSubstitution("addonshim1", base);
-
- return new Promise(function(resolve, reject) {
- const url = "resource://addonshim1/page.html";
- let tab = gBrowser.addTab(url);
- let browser = tab.linkedBrowser;
- addLoadListener(browser, function handler() {
- res.setSubstitution("addonshim1", null);
- removeTab(tab, resolve);
- });
- });
-}
-
-
-// Test for bug 1102410. We check that multiple nsIAboutModule's can be
-// registered in the parent, and that the child can browse to each of
-// the registered about: pages.
-function testAboutModuleRegistration()
-{
- let Registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
-
- let modulesToUnregister = new Map();
-
- function TestChannel(uri, aLoadInfo, aboutName) {
- this.aboutName = aboutName;
- this.loadInfo = aLoadInfo;
- this.URI = this.originalURI = uri;
- }
-
- TestChannel.prototype = {
- asyncOpen: function(listener, context) {
- let stream = this.open();
- let runnable = {
- run: () => {
- try {
- listener.onStartRequest(this, context);
- } catch (e) {}
- try {
- listener.onDataAvailable(this, context, stream, 0, stream.available());
- } catch (e) {}
- try {
- listener.onStopRequest(this, context, Cr.NS_OK);
- } catch (e) {}
- }
- };
- Services.tm.currentThread.dispatch(runnable, Ci.nsIEventTarget.DISPATCH_NORMAL);
- },
-
- asyncOpen2: function(listener) {
- // throws an error if security checks fail
- var outListener = contentSecManager.performSecurityCheck(this, listener);
- return this.asyncOpen(outListener, null);
- },
-
- open: function() {
- function getWindow(channel) {
- try
- {
- if (channel.notificationCallbacks)
- return channel.notificationCallbacks.getInterface(Ci.nsILoadContext).associatedWindow;
- } catch (e) {}
-
- try
- {
- if (channel.loadGroup && channel.loadGroup.notificationCallbacks)
- return channel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext).associatedWindow;
- } catch (e) {}
-
- return null;
- }
-
- let data = `<html><h1>${this.aboutName}</h1></html>`;
- let wnd = getWindow(this);
- if (!wnd)
- throw Cr.NS_ERROR_UNEXPECTED;
-
- let stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
- stream.setData(data, data.length);
- return stream;
- },
-
- open2: function() {
- // throws an error if security checks fail
- contentSecManager.performSecurityCheck(this, null);
- return this.open();
- },
-
- isPending: function() {
- return false;
- },
- cancel: function() {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- },
- suspend: function() {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- },
- resume: function() {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIChannel, Ci.nsIRequest])
- };
-
- /**
- * This function creates a new nsIAboutModule and registers it. Callers
- * should also call unregisterModules after using this function to clean
- * up the nsIAboutModules at the end of this test.
- *
- * @param aboutName
- * This will be the string after about: used to refer to this module.
- * For example, if aboutName is foo, you can refer to this module by
- * browsing to about:foo.
- *
- * @param uuid
- * A unique identifer string for this module. For example,
- * "5f3a921b-250f-4ac5-a61c-8f79372e6063"
- */
- let createAndRegisterAboutModule = function(aboutName, uuid) {
-
- let AboutModule = function() {};
-
- AboutModule.prototype = {
- classID: Components.ID(uuid),
- classDescription: `Testing About Module for about:${aboutName}`,
- contractID: `@mozilla.org/network/protocol/about;1?what=${aboutName}`,
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
-
- newChannel: (aURI, aLoadInfo) => {
- return new TestChannel(aURI, aLoadInfo, aboutName);
- },
-
- getURIFlags: (aURI) => {
- return Ci.nsIAboutModule.URI_SAFE_FOR_UNTRUSTED_CONTENT |
- Ci.nsIAboutModule.ALLOW_SCRIPT;
- },
- };
-
- let factory = {
- createInstance: function(outer, iid) {
- if (outer) {
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
- return new AboutModule();
- },
- };
-
- Registrar.registerFactory(AboutModule.prototype.classID,
- AboutModule.prototype.classDescription,
- AboutModule.prototype.contractID,
- factory);
-
- modulesToUnregister.set(AboutModule.prototype.classID,
- factory);
- };
-
- /**
- * Unregisters any nsIAboutModules registered with
- * createAndRegisterAboutModule.
- */
- let unregisterModules = () => {
- for (let [classID, factory] of modulesToUnregister) {
- Registrar.unregisterFactory(classID, factory);
- }
- };
-
- /**
- * Takes a browser, and sends it a framescript to attempt to
- * load some about: pages. The frame script will send a test:result
- * message on completion, passing back a data object with:
- *
- * {
- * pass: true
- * }
- *
- * on success, and:
- *
- * {
- * pass: false,
- * errorMsg: message,
- * }
- *
- * on failure.
- *
- * @param browser
- * The browser to send the framescript to.
- */
- let testAboutModulesWork = (browser) => {
- let testConnection = () => {
- let request = new content.XMLHttpRequest();
- try {
- request.open("GET", "about:test1", false);
- request.send(null);
- if (request.status != 200) {
- throw (`about:test1 response had status ${request.status} - expected 200`);
- }
- if (request.responseText.indexOf("test1") == -1) {
- throw (`about:test1 response had result ${request.responseText}`);
- }
-
- request = new content.XMLHttpRequest();
- request.open("GET", "about:test2", false);
- request.send(null);
-
- if (request.status != 200) {
- throw (`about:test2 response had status ${request.status} - expected 200`);
- }
- if (request.responseText.indexOf("test2") == -1) {
- throw (`about:test2 response had result ${request.responseText}`);
- }
-
- sendAsyncMessage("test:result", {
- pass: true,
- });
- } catch (e) {
- sendAsyncMessage("test:result", {
- pass: false,
- errorMsg: e.toString(),
- });
- }
- };
-
- return new Promise((resolve, reject) => {
- let mm = browser.messageManager;
- mm.addMessageListener("test:result", function onTestResult(message) {
- mm.removeMessageListener("test:result", onTestResult);
- if (message.data.pass) {
- ok(true, "Connections to about: pages were successful");
- } else {
- ok(false, message.data.errorMsg);
- }
- resolve();
- });
- mm.loadFrameScript("data:,(" + testConnection.toString() + ")();", false);
- });
- }
-
- // Here's where the actual test is performed.
- return new Promise((resolve, reject) => {
- createAndRegisterAboutModule("test1", "5f3a921b-250f-4ac5-a61c-8f79372e6063");
- createAndRegisterAboutModule("test2", "d7ec0389-1d49-40fa-b55c-a1fc3a6dbf6f");
-
- // This needs to be a chrome-privileged page that loads in the
- // content process. It needs chrome privs because otherwise the
- // XHRs for about:test[12] will fail with a privilege error
- // despite the presence of URI_SAFE_FOR_UNTRUSTED_CONTENT.
- let newTab = gBrowser.addTab("chrome://addonshim1/content/page.html");
- gBrowser.selectedTab = newTab;
- let browser = newTab.linkedBrowser;
-
- addLoadListener(browser, function() {
- testAboutModulesWork(browser).then(() => {
- unregisterModules();
- removeTab(newTab, resolve);
- });
- });
- });
-}
-
-function testProgressListener()
-{
- const url = baseURL + "browser_addonShims_testpage.html";
-
- let sawGlobalLocChange = false;
- let sawTabsLocChange = false;
-
- let globalListener = {
- onLocationChange: function(webProgress, request, uri) {
- if (uri.spec == url) {
- sawGlobalLocChange = true;
- ok(request instanceof Ci.nsIHttpChannel, "Global listener channel is an HTTP channel");
- }
- },
- };
-
- let tabsListener = {
- onLocationChange: function(browser, webProgress, request, uri) {
- if (uri.spec == url) {
- sawTabsLocChange = true;
- ok(request instanceof Ci.nsIHttpChannel, "Tab listener channel is an HTTP channel");
- }
- },
- };
-
- gBrowser.addProgressListener(globalListener);
- gBrowser.addTabsProgressListener(tabsListener);
- info("Added progress listeners");
-
- return new Promise(function(resolve, reject) {
- let tab = gBrowser.addTab(url);
- gBrowser.selectedTab = tab;
- addLoadListener(tab.linkedBrowser, function handler() {
- ok(sawGlobalLocChange, "Saw global onLocationChange");
- ok(sawTabsLocChange, "Saw tabs onLocationChange");
-
- gBrowser.removeProgressListener(globalListener);
- gBrowser.removeTabsProgressListener(tabsListener);
- removeTab(tab, resolve);
- });
- });
-}
-
-function testRootTreeItem()
-{
- return new Promise(function(resolve, reject) {
- const url = baseURL + "browser_addonShims_testpage.html";
- let tab = gBrowser.addTab(url);
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
- addLoadListener(browser, function handler() {
- let win = browser.contentWindow;
-
- // Add-ons love this crap.
- let root = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIWebNavigation)
- .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
- .rootTreeItem
- .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
- .getInterface(Components.interfaces.nsIDOMWindow);
- is(root, gWin, "got correct chrome window");
-
- removeTab(tab, resolve);
- });
- });
-}
-
-function testImportNode()
-{
- return new Promise(function(resolve, reject) {
- const url = baseURL + "browser_addonShims_testpage.html";
- let tab = gBrowser.addTab(url);
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
- addLoadListener(browser, function handler() {
- let node = gWin.document.createElement("div");
- let doc = browser.contentDocument;
- let result;
- try {
- result = doc.importNode(node, false);
- } catch (e) {
- ok(false, "importing threw an exception");
- }
- if (browser.isRemoteBrowser) {
- is(result, node, "got expected import result");
- }
-
- removeTab(tab, resolve);
- });
- });
-}
-
-function runTests(win, funcs)
-{
- ok = funcs.ok;
- is = funcs.is;
- info = funcs.info;
-
- gWin = win;
- gBrowser = win.gBrowser;
-
- return testContentWindow().
- then(testListeners).
- then(testCapturing).
- then(testObserver).
- then(testSandbox).
- then(testAddonContent).
- then(testAboutModuleRegistration).
- then(testProgressListener).
- then(testRootTreeItem).
- then(testImportNode).
- then(Promise.resolve());
-}
-
-/*
- bootstrap.js API
-*/
-
-function startup(aData, aReason)
-{
- forEachWindow(win => {
- win.runAddonShimTests = (funcs) => runTests(win, funcs);
- });
-}
-
-function shutdown(aData, aReason)
-{
- forEachWindow(win => {
- delete win.runAddonShimTests;
- });
-}
-
-function install(aData, aReason)
-{
-}
-
-function uninstall(aData, aReason)
-{
-}
-
diff --git a/toolkit/components/addoncompat/tests/addon/chrome.manifest b/toolkit/components/addoncompat/tests/addon/chrome.manifest
deleted file mode 100644
index 602ba3a5d..000000000
--- a/toolkit/components/addoncompat/tests/addon/chrome.manifest
+++ /dev/null
@@ -1 +0,0 @@
-content addonshim1 content/
diff --git a/toolkit/components/addoncompat/tests/addon/content/page.html b/toolkit/components/addoncompat/tests/addon/content/page.html
deleted file mode 100644
index 90531a4b3..000000000
--- a/toolkit/components/addoncompat/tests/addon/content/page.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<html>
-</html>
diff --git a/toolkit/components/addoncompat/tests/addon/install.rdf b/toolkit/components/addoncompat/tests/addon/install.rdf
deleted file mode 100644
index d59c7b19d..000000000
--- a/toolkit/components/addoncompat/tests/addon/install.rdf
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>test-addon-shim-1@tests.mozilla.org</em:id>
- <em:version>1</em:version>
- <em:type>2</em:type>
- <em:bootstrap>true</em:bootstrap>
-
- <!-- Front End MetaData -->
- <em:name>Test addon shim 1</em:name>
- <em:description>Test an add-on that needs multiprocess shims.</em:description>
- <em:multiprocessCompatible>false</em:multiprocessCompatible>
-
- <em:iconURL>chrome://foo/skin/icon.png</em:iconURL>
- <em:aboutURL>chrome://foo/content/about.xul</em:aboutURL>
- <em:optionsURL>chrome://foo/content/options.xul</em:optionsURL>
-
- <em:targetApplication>
- <Description>
- <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
- <em:minVersion>0.3</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>10.0</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
- </Description>
-</RDF>
diff --git a/toolkit/components/addoncompat/tests/browser/.eslintrc.js b/toolkit/components/addoncompat/tests/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/addoncompat/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/addoncompat/tests/browser/addon.xpi b/toolkit/components/addoncompat/tests/browser/addon.xpi
deleted file mode 100644
index e6392fb40..000000000
--- a/toolkit/components/addoncompat/tests/browser/addon.xpi
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/addoncompat/tests/browser/browser.ini b/toolkit/components/addoncompat/tests/browser/browser.ini
deleted file mode 100644
index 7c8547562..000000000
--- a/toolkit/components/addoncompat/tests/browser/browser.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[DEFAULT]
-tags = addons
-support-files =
- addon.xpi
- browser_addonShims_testpage.html
- browser_addonShims_testpage2.html
- compat-addon.xpi
-
-[browser_addonShims.js]
diff --git a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js b/toolkit/components/addoncompat/tests/browser/browser_addonShims.js
deleted file mode 100644
index b642eb3cb..000000000
--- a/toolkit/components/addoncompat/tests/browser/browser_addonShims.js
+++ /dev/null
@@ -1,67 +0,0 @@
-var {AddonManager} = Cu.import("resource://gre/modules/AddonManager.jsm", {});
-var {Services} = Cu.import("resource://gre/modules/Services.jsm", {});
-
-const ADDON_URL = "http://example.com/browser/toolkit/components/addoncompat/tests/browser/addon.xpi";
-const COMPAT_ADDON_URL = "http://example.com/browser/toolkit/components/addoncompat/tests/browser/compat-addon.xpi";
-
-// Install a test add-on that will exercise e10s shims.
-// url: Location of the add-on.
-function addAddon(url)
-{
- info("Installing add-on: " + url);
-
- return new Promise(function(resolve, reject) {
- AddonManager.getInstallForURL(url, installer => {
- installer.install();
- let listener = {
- onInstallEnded: function(addon, addonInstall) {
- installer.removeListener(listener);
-
- // Wait for add-on's startup scripts to execute. See bug 997408
- executeSoon(function() {
- resolve(addonInstall);
- });
- }
- };
- installer.addListener(listener);
- }, "application/x-xpinstall");
- });
-}
-
-// Uninstall a test add-on.
-// addon: The addon reference returned from addAddon.
-function removeAddon(addon)
-{
- info("Removing addon.");
-
- return new Promise(function(resolve, reject) {
- let listener = {
- onUninstalled: function(uninstalledAddon) {
- if (uninstalledAddon != addon) {
- return;
- }
- AddonManager.removeAddonListener(listener);
- resolve();
- }
- };
- AddonManager.addAddonListener(listener);
- addon.uninstall();
- });
-}
-
-add_task(function* test_addon_shims() {
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({set: [["dom.ipc.shims.enabledWarnings", true]]},
- resolve);
- });
-
- let addon = yield addAddon(ADDON_URL);
- yield window.runAddonShimTests({ok: ok, is: is, info: info});
- yield removeAddon(addon);
-
- if (Services.appinfo.browserTabsRemoteAutostart) {
- addon = yield addAddon(COMPAT_ADDON_URL);
- yield window.runAddonTests({ok: ok, is: is, info: info});
- yield removeAddon(addon);
- }
-});
diff --git a/toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage.html b/toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage.html
deleted file mode 100644
index 5a8b34e88..000000000
--- a/toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<html>
-<head>
- <meta charset="utf-8">
- <title>shim test</title>
-</head>
-
-<body>
-Hello!
-
-<a href="browser_addonShims_testpage2.html" id="link">Link</a>
-<div id="output"></div>
-
-<script type="text/javascript">
-var global = 3;
-</script>
-</body>
-</html>
diff --git a/toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage2.html b/toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage2.html
deleted file mode 100644
index f644b1129..000000000
--- a/toolkit/components/addoncompat/tests/browser/browser_addonShims_testpage2.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<html>
-<head>
- <meta charset="utf-8">
- <title>shim test</title>
-</head>
-
-<body>
-Hello!
-
-<a href="browser_addonShims_testpage.html" id="link">Link</a>
-
-<script type="text/javascript">
-var global = 5;
-</script>
-</body>
-</html>
diff --git a/toolkit/components/addoncompat/tests/browser/compat-addon.xpi b/toolkit/components/addoncompat/tests/browser/compat-addon.xpi
deleted file mode 100644
index c7ca32cdc..000000000
--- a/toolkit/components/addoncompat/tests/browser/compat-addon.xpi
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/addoncompat/tests/compat-addon/bootstrap.js b/toolkit/components/addoncompat/tests/compat-addon/bootstrap.js
deleted file mode 100644
index 7c93bad08..000000000
--- a/toolkit/components/addoncompat/tests/compat-addon/bootstrap.js
+++ /dev/null
@@ -1,99 +0,0 @@
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/BrowserUtils.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const baseURL = "http://mochi.test:8888/browser/" +
- "toolkit/components/addoncompat/tests/browser/";
-
-function forEachWindow(f)
-{
- let wins = Services.wm.getEnumerator("navigator:browser");
- while (wins.hasMoreElements()) {
- let win = wins.getNext();
- f(win);
- }
-}
-
-function addLoadListener(target, listener)
-{
- function frameScript() {
- addEventListener("load", function handler(event) {
- removeEventListener("load", handler, true);
- sendAsyncMessage("compat-test:loaded");
- }, true);
- }
- target.messageManager.loadFrameScript("data:,(" + frameScript.toString() + ")()", false);
- target.messageManager.addMessageListener("compat-test:loaded", function handler() {
- target.messageManager.removeMessageListener("compat-test:loaded", handler);
- listener();
- });
-}
-
-var gWin;
-var gBrowser;
-var ok, is, info;
-
-// Make sure that the shims for window.content, browser.contentWindow,
-// and browser.contentDocument are working.
-function testContentWindow()
-{
- return new Promise(function(resolve, reject) {
- const url = baseURL + "browser_addonShims_testpage.html";
- let tab = gBrowser.addTab("about:blank");
- gBrowser.selectedTab = tab;
- let browser = tab.linkedBrowser;
- addLoadListener(browser, function handler() {
- ok(!gWin.content, "content is defined on chrome window");
- ok(!browser.contentWindow, "contentWindow is defined");
- ok(!browser.contentDocument, "contentWindow is defined");
-
- gBrowser.removeTab(tab);
- resolve();
- });
- browser.loadURI(url);
- });
-}
-
-function runTests(win, funcs)
-{
- ok = funcs.ok;
- is = funcs.is;
- info = funcs.info;
-
- gWin = win;
- gBrowser = win.gBrowser;
-
- return testContentWindow();
-}
-
-/*
- bootstrap.js API
-*/
-
-function startup(aData, aReason)
-{
- forEachWindow(win => {
- win.runAddonTests = (funcs) => runTests(win, funcs);
- });
-}
-
-function shutdown(aData, aReason)
-{
- forEachWindow(win => {
- delete win.runAddonTests;
- });
-}
-
-function install(aData, aReason)
-{
-}
-
-function uninstall(aData, aReason)
-{
-}
-
diff --git a/toolkit/components/addoncompat/tests/compat-addon/install.rdf b/toolkit/components/addoncompat/tests/compat-addon/install.rdf
deleted file mode 100644
index 331fd1540..000000000
--- a/toolkit/components/addoncompat/tests/compat-addon/install.rdf
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>test-addon-shim-2@tests.mozilla.org</em:id>
- <em:version>1</em:version>
- <em:type>2</em:type>
- <em:bootstrap>true</em:bootstrap>
-
- <!-- Front End MetaData -->
- <em:name>Test addon shims 2</em:name>
- <em:description>Test an add-on that doesn't need multiprocess shims.</em:description>
- <em:multiprocessCompatible>true</em:multiprocessCompatible>
-
- <em:iconURL>chrome://foo/skin/icon.png</em:iconURL>
- <em:aboutURL>chrome://foo/content/about.xul</em:aboutURL>
- <em:optionsURL>chrome://foo/content/options.xul</em:optionsURL>
-
- <em:targetApplication>
- <Description>
- <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
- <em:minVersion>0.3</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>10.0</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
- </Description>
-</RDF>
diff --git a/toolkit/components/addoncompat/tests/moz.build b/toolkit/components/addoncompat/tests/moz.build
deleted file mode 100644
index 589eaa812..000000000
--- a/toolkit/components/addoncompat/tests/moz.build
+++ /dev/null
@@ -1,7 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-BROWSER_CHROME_MANIFESTS += ['browser/browser.ini']
diff --git a/toolkit/components/alerts/moz.build b/toolkit/components/alerts/moz.build
index cdbf92511..8d42a8ce7 100644
--- a/toolkit/components/alerts/moz.build
+++ b/toolkit/components/alerts/moz.build
@@ -4,17 +4,13 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-MOCHITEST_MANIFESTS += ['test/mochitest.ini']
-
XPIDL_SOURCES += [
'nsIAlertsService.idl',
]
XPIDL_MODULE = 'alerts'
-EXPORTS += [
- 'nsAlertsUtils.h',
-]
+EXPORTS += ['nsAlertsUtils.h']
EXPORTS.mozilla += [
'AlertNotification.h',
@@ -33,6 +29,3 @@ include('/ipc/chromium/chromium-config.mozbuild')
FINAL_LIBRARY = 'xul'
JAR_MANIFESTS += ['jar.mn']
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Notifications and Alerts')
diff --git a/toolkit/components/alerts/test/.eslintrc.js b/toolkit/components/alerts/test/.eslintrc.js
deleted file mode 100644
index 3c788d6d6..000000000
--- a/toolkit/components/alerts/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/mochitest.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/alerts/test/image.gif b/toolkit/components/alerts/test/image.gif
deleted file mode 100644
index 053b4d926..000000000
--- a/toolkit/components/alerts/test/image.gif
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/alerts/test/image.png b/toolkit/components/alerts/test/image.png
deleted file mode 100644
index 430c3c5e6..000000000
--- a/toolkit/components/alerts/test/image.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/alerts/test/image_server.sjs b/toolkit/components/alerts/test/image_server.sjs
deleted file mode 100644
index 622052943..000000000
--- a/toolkit/components/alerts/test/image_server.sjs
+++ /dev/null
@@ -1,82 +0,0 @@
-const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr, Constructor: CC } = Components;
-
-Cu.import("resource://gre/modules/Timer.jsm");
-
-const LocalFile = CC("@mozilla.org/file/local;1", "nsILocalFile",
- "initWithPath");
-
-const FileInputStream = CC("@mozilla.org/network/file-input-stream;1",
- "nsIFileInputStream", "init");
-
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream", "setInputStream");
-
-function handleRequest(request, response) {
- let params = parseQueryString(request.queryString);
-
- response.setStatusLine(request.httpVersion, 200, "OK");
-
- // Compare and increment a cookie for this request. This is used to test
- // private browsing mode; the cookie should not be set if the image is
- // loaded anonymously.
- if (params.has("c")) {
- let expectedValue = parseInt(params.get("c"), 10);
- let actualValue = !request.hasHeader("Cookie") ? 0 :
- parseInt(request.getHeader("Cookie")
- .replace(/^counter=(\d+)/, "$1"), 10);
- if (actualValue != expectedValue) {
- response.setStatusLine(request.httpVersion, 400, "Wrong counter value");
- return;
- }
- response.setHeader("Set-Cookie", `counter=${expectedValue + 1}`, false);
- }
-
- // Wait to send the image if a timeout is given.
- let timeout = parseInt(params.get("t"), 10);
- if (timeout > 0) {
- response.processAsync();
- setTimeout(() => {
- respond(params, request, response);
- response.finish();
- }, timeout * 1000);
- return;
- }
-
- respond(params, request, response);
-}
-
-function parseQueryString(queryString) {
- return queryString.split("&").reduce((params, param) => {
- let [key, value] = param.split("=", 2);
- params.set(key, value);
- return params;
- }, new Map());
-}
-
-function respond(params, request, response) {
- if (params.has("s")) {
- let statusCode = parseInt(params.get("s"), 10);
- response.setStatusLine(request.httpVersion, statusCode, "Custom status");
- return;
- }
- var filename = params.get("f");
- writeFile(filename, response);
-}
-
-function writeFile(name, response) {
- var file = new LocalFile(getState("__LOCATION__")).parent;
- file.append(name);
-
- let mimeType = Cc["@mozilla.org/uriloader/external-helper-app-service;1"]
- .getService(Ci.nsIMIMEService)
- .getTypeFromFile(file);
-
- let fileStream = new FileInputStream(file, 1, 0, false);
- let binaryStream = new BinaryInputStream(fileStream);
-
- response.setHeader("Content-Type", mimeType, false);
- response.bodyOutputStream.writeFrom(binaryStream, binaryStream.available());
-
- binaryStream.close();
- fileStream.close();
-}
diff --git a/toolkit/components/alerts/test/mochitest.ini b/toolkit/components/alerts/test/mochitest.ini
deleted file mode 100644
index 12e2a8704..000000000
--- a/toolkit/components/alerts/test/mochitest.ini
+++ /dev/null
@@ -1,16 +0,0 @@
-[DEFAULT]
-support-files =
- image.gif
- image.png
- image_server.sjs
-
-# Synchronous tests like test_alerts.html must come before
-# asynchronous tests like test_alerts_noobserve.html!
-[test_alerts.html]
-skip-if = toolkit == 'android'
-[test_alerts_noobserve.html]
-[test_alerts_requireinteraction.html]
-[test_image.html]
-[test_multiple_alerts.html]
-[test_principal.html]
-skip-if = toolkit == 'android'
diff --git a/toolkit/components/alerts/test/test_alerts.html b/toolkit/components/alerts/test/test_alerts.html
deleted file mode 100644
index cb087e48a..000000000
--- a/toolkit/components/alerts/test/test_alerts.html
+++ /dev/null
@@ -1,89 +0,0 @@
-<!DOCTYPE HTML>
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-<html>
-<head>
- <title>Test for Alerts Service</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-
-<body>
-<p id="display"></p>
-
-<br>Alerts service, with observer "synchronous" case.
-<br>
-<br>Did a notification appear anywhere?
-<br>If so, the test will finish once the notification disappears.
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-var observer = {
- alertShow: false,
- observe: function (aSubject, aTopic, aData) {
- is(aData, "foobarcookie", "Checking whether the alert cookie was passed correctly");
- if (aTopic == "alertclickcallback") {
- todo(false, "Did someone click the notification while running mochitests? (Please don't.)");
- } else if (aTopic == "alertshow") {
- ok(!this.alertShow, "Alert should not be shown more than once");
- this.alertShow = true;
- } else {
- is(aTopic, "alertfinished", "Checking the topic for a finished notification");
- SimpleTest.finish();
- }
- }
-};
-
-function runTest() {
- const Cc = SpecialPowers.Cc;
- const Ci = SpecialPowers.Ci;
-
- if (!("@mozilla.org/alerts-service;1" in Cc)) {
- todo(false, "Alerts service does not exist in this application");
- return;
- }
-
- ok(true, "Alerts service exists in this application");
-
- var notifier;
- try {
- notifier = Cc["@mozilla.org/alerts-service;1"].
- getService(Ci.nsIAlertsService);
- ok(true, "Alerts service is available");
- } catch (ex) {
- todo(false,
- "Alerts service is not available.", ex);
- return;
- }
-
- try {
- var alertName = "fiorello";
- SimpleTest.waitForExplicitFinish();
- notifier.showAlertNotification(null, "Notification test",
- "Surprise! I'm here to test notifications!",
- false, "foobarcookie", observer, alertName);
- ok(true, "showAlertNotification() succeeded. Waiting for notification...");
-
- if ("@mozilla.org/system-alerts-service;1" in Cc) {
- // Notifications are native on OS X 10.8 and later, as well as GNOME
- // Shell with libnotify (bug 1236036). These notifications persist in the
- // Notification Center, and only fire the `alertfinished` event when
- // closed. For platforms where native notifications may be used, we need
- // to close explicitly to avoid a hang. This also works for XUL
- // notifications when running this test on OS X < 10.8, or a window
- // manager like Ubuntu Unity with incomplete libnotify support.
- notifier.closeAlert(alertName);
- }
- } catch (ex) {
- todo(false, "showAlertNotification() failed.", ex);
- SimpleTest.finish();
- }
-}
-
-runTest();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/alerts/test/test_alerts_noobserve.html b/toolkit/components/alerts/test/test_alerts_noobserve.html
deleted file mode 100644
index 0cc452b8a..000000000
--- a/toolkit/components/alerts/test/test_alerts_noobserve.html
+++ /dev/null
@@ -1,96 +0,0 @@
-<!DOCTYPE HTML>
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-<html>
-<head>
- <title>Test for Alerts Service</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-
-<body>
-<p id="display"></p>
-
-<br>Alerts service, without observer "asynchronous" case.
-<br>
-<br>A notification should soon appear somewhere.
-<br>If there has been no crash when the notification (later) disappears, assume all is good.
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-const Cc = SpecialPowers.Cc;
-const Ci = SpecialPowers.Ci;
-
-const chromeScript = SpecialPowers.loadChromeScript(_ => {
- const { utils: Cu } = Components;
-
- Cu.import("resource://gre/modules/Services.jsm");
- Cu.import("resource://gre/modules/Timer.jsm");
-
- function anyXULAlertsVisible() {
- var windows = Services.wm.getEnumerator("alert:alert");
- return windows.hasMoreElements();
- }
-
- addMessageListener("anyXULAlertsVisible", anyXULAlertsVisible);
-
- addMessageListener("waitForAlerts", function waitForAlerts() {
- if (anyXULAlertsVisible()) {
- setTimeout(waitForAlerts, 1000);
- } else {
- sendAsyncMessage("waitedForAlerts");
- }
- });
-});
-
-function waitForAlertsThenFinish() {
- chromeScript.addMessageListener("waitedForAlerts", function waitedForAlerts() {
- chromeScript.removeMessageListener("waitedForAlerts", waitedForAlerts);
- ok(true, "Alert disappeared.");
- SimpleTest.finish();
- });
- chromeScript.sendAsyncMessage("waitForAlerts");
-}
-
-function runTest() {
- if (!("@mozilla.org/alerts-service;1" in Cc)) {
- todo(false, "Alerts service does not exist in this application");
- } else {
- ok(true, "Alerts service exists in this application");
-
- var notifier;
- try {
- notifier = Cc["@mozilla.org/alerts-service;1"].
- getService(Ci.nsIAlertsService);
- ok(true, "Alerts service is available");
- } catch (ex) {
- todo(false, "Alerts service is not available.", ex);
- }
-
- if (notifier) {
- try {
- notifier.showAlertNotification(null, "Notification test",
- "This notification has no observer");
- ok(true, "showAlertNotification() succeeded");
- } catch (ex) {
- todo(false, "showAlertNotification() failed.", ex);
- }
- }
- }
-}
-
-SimpleTest.waitForExplicitFinish();
-SimpleTest.requestFlakyTimeout("untriaged");
-
-// sendSyncMessage returns an array of arrays: the outer array is from the
-// message manager, and the inner array is from the chrome script's listeners.
-// See the comment in test_SpecialPowersLoadChromeScript.html.
-var [[alertsVisible]] = chromeScript.sendSyncMessage("anyXULAlertsVisible");
-ok(!alertsVisible, "Alerts should not be present at the start of the test.");
-runTest();
-setTimeout(waitForAlertsThenFinish, 1000);
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/alerts/test/test_alerts_requireinteraction.html b/toolkit/components/alerts/test/test_alerts_requireinteraction.html
deleted file mode 100644
index 26fe87104..000000000
--- a/toolkit/components/alerts/test/test_alerts_requireinteraction.html
+++ /dev/null
@@ -1,168 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for alerts with requireInteraction</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-const Cc = SpecialPowers.Cc;
-const Ci = SpecialPowers.Ci;
-
-const chromeScript = SpecialPowers.loadChromeScript(_ => {
- const { utils: Cu } = Components;
-
- Cu.import("resource://gre/modules/Services.jsm");
- Cu.import("resource://gre/modules/Timer.jsm");
-
- addMessageListener("waitForXULAlert", function() {
- var timer = setTimeout(function() {
- Services.ww.unregisterNotification(windowObserver);
- sendAsyncMessage("waitForXULAlert", false);
- }, 2000);
-
- var windowObserver = function(aSubject, aTopic, aData) {
- if (aTopic != "domwindowopened") {
- return;
- }
-
- var win = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow);
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- let windowType = win.document.documentElement.getAttribute("windowtype");
- if (windowType == "alert:alert") {
- clearTimeout(timer);
- Services.ww.unregisterNotification(windowObserver);
-
- sendAsyncMessage("waitForXULAlert", true);
- }
- });
- };
-
- Services.ww.registerNotification(windowObserver);
- });
-});
-
-var cookie = 0;
-function promiseCreateXULAlert(alertService, listener, name) {
- return new Promise(resolve => {
- chromeScript.addMessageListener("waitForXULAlert", function waitedForAlert(result) {
- chromeScript.removeMessageListener("waitForXULAlert", waitedForAlert);
- resolve(result);
- });
-
- chromeScript.sendAsyncMessage("waitForXULAlert");
- alertService.showAlertNotification(null, "title", "body",
- true, cookie++, listener, name, null, null, null,
- null, false, true);
- });
-}
-
-add_task(function* test_require_interaction() {
- if (!("@mozilla.org/alerts-service;1" in Cc)) {
- todo(false, "Alerts service does not exist in this application.");
- return;
- }
-
- ok(true, "Alerts service exists in this application.");
-
- var alertService;
- try {
- alertService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
- ok(true, "Alerts service is available.");
- } catch (ex) {
- todo(false, "Alerts service is not available.");
- return;
- }
-
- yield SpecialPowers.pushPrefEnv({"set": [
- [ "dom.webnotifications.requireinteraction.enabled", true ],
- [ "dom.webnotifications.requireinteraction.count", 2 ]
- ]});
-
- var expectedSequence = [
- "first show",
- "second show",
- "second finished",
- "second replacement show",
- "third finished",
- "first finished",
- "third replacement show",
- "second replacement finished",
- "third replacement finished"
- ];
-
- var actualSequence = [];
-
- function createAlertListener(name, showCallback, finishCallback) {
- return (subject, topic, data) => {
- if (topic == "alertshow") {
- actualSequence.push(name + " show");
- if (showCallback) {
- showCallback();
- }
- } else if (topic == "alertfinished") {
- actualSequence.push(name + " finished");
- if (finishCallback) {
- finishCallback();
- }
- }
- }
- }
-
- var xulAlertCreated = yield promiseCreateXULAlert(alertService,
- createAlertListener("first"), "first");
- if (!xulAlertCreated) {
- ok(true, "Platform does not use XUL alerts.");
- alertService.closeAlert("first");
- return;
- }
-
- xulAlertCreated = yield promiseCreateXULAlert(alertService,
- createAlertListener("second"), "second");
- ok(xulAlertCreated, "Create XUL alert");
-
- // Replace second alert
- xulAlertCreated = yield promiseCreateXULAlert(alertService,
- createAlertListener("second replacement"), "second");
- ok(xulAlertCreated, "Create XUL alert");
-
- var testFinishResolve;
- var testFinishPromise = new Promise((resolve) => { testFinishResolve = resolve; });
-
- xulAlertCreated = yield promiseCreateXULAlert(alertService,
- createAlertListener("third"), "third"),
- ok(!xulAlertCreated, "XUL alert should not be visible");
-
- // Replace the not-yet-visible third alert.
- xulAlertCreated = yield promiseCreateXULAlert(alertService,
- createAlertListener("third replacement",
- function showCallback() {
- alertService.closeAlert("second");
- alertService.closeAlert("third");
- },
- function finishCallback() {
- // Check actual sequence of alert events compared to expected sequence.
- for (var i = 0; i < actualSequence.length; i++) {
- is(actualSequence[i], expectedSequence[i],
- "Alert callback at index " + i + " should be in expected order.");
- }
-
- testFinishResolve();
- }), "third");
-
- ok(!xulAlertCreated, "XUL alert should not be visible");
-
- alertService.closeAlert("first");
-
- yield testFinishPromise;
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/alerts/test/test_image.html b/toolkit/components/alerts/test/test_image.html
deleted file mode 100644
index 7bf89fab2..000000000
--- a/toolkit/components/alerts/test/test_image.html
+++ /dev/null
@@ -1,118 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Bug 1233086</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-
-<body>
-<p id="display"></p>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-const Cc = SpecialPowers.Cc;
-const Ci = SpecialPowers.Ci;
-const Services = SpecialPowers.Services;
-
-const imageServerURL = "http://mochi.test:8888/tests/toolkit/components/alerts/test/image_server.sjs";
-
-function makeAlert(...params) {
- var alert = Cc["@mozilla.org/alert-notification;1"]
- .createInstance(Ci.nsIAlertNotification);
- alert.init(...params);
- return alert;
-}
-
-function promiseImage(alert, timeout = 0, userData = null) {
- return new Promise(resolve => {
- var isDone = false;
- function done(value) {
- ok(!isDone, "Should call the image listener once");
- isDone = true;
- resolve(value);
- }
- alert.loadImage(timeout, SpecialPowers.wrapCallbackObject({
- onImageReady(aUserData, aRequest) {
- done([true, aRequest, aUserData]);
- },
- onImageMissing(aUserData) {
- done([false, aUserData]);
- },
- }), SpecialPowers.wrap(userData));
- });
-}
-
-add_task(function* testContext() {
- var inUserData = Cc["@mozilla.org/supports-PRInt64;1"]
- .createInstance(Ci.nsISupportsPRInt64);
- inUserData.data = 123;
-
- var alert = makeAlert(null, imageServerURL + "?f=image.png");
- var [ready, , userData] = yield promiseImage(alert, 0, inUserData);
- ok(ready, "Should load requested image");
- is(userData.QueryInterface(Ci.nsISupportsPRInt64).data, 123,
- "Should pass user data for loaded image");
-
- alert = makeAlert(null, imageServerURL + "?s=404");
- [ready, userData] = yield promiseImage(alert, 0, inUserData);
- ok(!ready, "Should not load missing image");
- is(userData.QueryInterface(Ci.nsISupportsPRInt64).data, 123,
- "Should pass user data for missing image");
-});
-
-add_task(function* testTimeout() {
- var alert = makeAlert(null, imageServerURL + "?f=image.png&t=3");
- var [ready] = yield promiseImage(alert, 1000);
- ok(!ready, "Should cancel request if timeout fires");
-
- [ready, request] = yield promiseImage(alert, 45000);
- ok(ready, "Should load image if request finishes before timeout");
-});
-
-add_task(function* testAnimatedGIF() {
- var alert = makeAlert(null, imageServerURL + "?f=image.gif");
- var [ready, request] = yield promiseImage(alert);
- ok(ready, "Should load first animated GIF frame");
- is(request.mimeType, "image/gif", "Should report correct GIF MIME type");
- is(request.image.width, 256, "GIF width should be 256px");
- is(request.image.height, 256, "GIF height should be 256px");
-});
-
-add_task(function* testCancel() {
- var alert = makeAlert(null, imageServerURL + "?f=image.gif&t=180");
- yield new Promise((resolve, reject) => {
- var request = alert.loadImage(0, SpecialPowers.wrapCallbackObject({
- onImageReady() {
- reject(new Error("Should not load cancelled request"));
- },
- onImageMissing() {
- resolve();
- },
- }), null);
- request.cancel(SpecialPowers.Cr.NS_BINDING_ABORTED);
- });
-});
-
-add_task(function* testMixedContent() {
- // Loading principal is HTTPS; image URL is HTTP.
- var origin = "https://mochi.test:8888";
- var principal = Services.scriptSecurityManager
- .createCodebasePrincipalFromOrigin(origin);
-
- var alert = makeAlert(null, imageServerURL + "?f=image.png",
- null, null, false, null, null, null,
- null, principal);
- var [ready, request] = yield promiseImage(alert);
- ok(ready, "Should load cross-protocol image");
- is(request.mimeType, "image/png", "Should report correct MIME type");
- is(request.image.width, 32, "Width should be 32px");
- is(request.image.height, 32, "Height should be 32px");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/alerts/test/test_multiple_alerts.html b/toolkit/components/alerts/test/test_multiple_alerts.html
deleted file mode 100644
index 9d939b63a..000000000
--- a/toolkit/components/alerts/test/test_multiple_alerts.html
+++ /dev/null
@@ -1,103 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for multiple alerts</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-const Cc = SpecialPowers.Cc;
-const Ci = SpecialPowers.Ci;
-
-const chromeScript = SpecialPowers.loadChromeScript(_ => {
- Components.utils.import("resource://gre/modules/Services.jsm");
- Components.utils.import("resource://gre/modules/Timer.jsm");
-
- const alertService = Components.classes["@mozilla.org/alerts-service;1"]
- .getService(Components.interfaces.nsIAlertsService);
-
- addMessageListener("waitForPosition", function() {
- var timer = setTimeout(function() {
- Services.ww.unregisterNotification(windowObserver);
- sendAsyncMessage("waitedForPosition", null);
- }, 2000);
-
- var windowObserver = function(aSubject, aTopic, aData) {
- if (aTopic != "domwindowopened") {
- return;
- }
-
- // Alerts are implemented using XUL.
- clearTimeout(timer);
-
- Services.ww.unregisterNotification(windowObserver);
-
- var win = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow);
- win.addEventListener("pageshow", function onPageShow() {
- win.removeEventListener("pageshow", onPageShow, false);
-
- var x = win.screenX;
- var y = win.screenY;
-
- win.addEventListener("pagehide", function onPageHide() {
- win.removeEventListener("pagehide", onPageHide, false);
- sendAsyncMessage("waitedForPosition", { x, y });
- }, false);
-
- alertService.closeAlert();
- }, false);
- };
-
- Services.ww.registerNotification(windowObserver);
- });
-});
-
-function promiseAlertPosition(alertService) {
- return new Promise(resolve => {
- chromeScript.addMessageListener("waitedForPosition", function waitedForPosition(result) {
- chromeScript.removeMessageListener("waitedForPosition", waitedForPosition);
- resolve(result);
- });
- chromeScript.sendAsyncMessage("waitForPosition");
-
- alertService.showAlertNotification(null, "title", "body");
- ok(true, "Alert shown.");
- });
-}
-
-add_task(function* test_multiple_alerts() {
- if (!("@mozilla.org/alerts-service;1" in Cc)) {
- todo(false, "Alerts service does not exist in this application.");
- return;
- }
-
- ok(true, "Alerts service exists in this application.");
-
- var alertService;
- try {
- alertService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
- ok(true, "Alerts service is available.");
- } catch (ex) {
- todo(false, "Alerts service is not available.");
- return;
- }
-
- var firstAlertPosition = yield promiseAlertPosition(alertService);
- if (!firstAlertPosition) {
- ok(true, "Platform does not use XUL alerts.");
- return;
- }
-
- var secondAlertPosition = yield promiseAlertPosition(alertService);
- is(secondAlertPosition.x, firstAlertPosition.x, "Second alert should be opened in the same position.");
- is(secondAlertPosition.y, firstAlertPosition.y, "Second alert should be opened in the same position.");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/alerts/test/test_principal.html b/toolkit/components/alerts/test/test_principal.html
deleted file mode 100644
index 74a20dbd7..000000000
--- a/toolkit/components/alerts/test/test_principal.html
+++ /dev/null
@@ -1,122 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Bug 1202933</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-
-<body>
-<p id="display"></p>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-const Cc = SpecialPowers.Cc;
-const Ci = SpecialPowers.Ci;
-const Services = SpecialPowers.Services;
-
-const notifier = Cc["@mozilla.org/alerts-service;1"]
- .getService(Ci.nsIAlertsService);
-
-const chromeScript = SpecialPowers.loadChromeScript(_ => {
- Components.utils.import("resource://gre/modules/Services.jsm");
-
- addMessageListener("anyXULAlertsVisible", function() {
- var windows = Services.wm.getEnumerator("alert:alert");
- return windows.hasMoreElements();
- });
-
- addMessageListener("getAlertSource", function() {
- var alertWindows = Services.wm.getEnumerator("alert:alert");
- if (!alertWindows) {
- return null;
- }
- var alertWindow = alertWindows.getNext();
- return alertWindow.document.getElementById("alertSourceLabel").getAttribute("value");
- });
-});
-
-function notify(alertName, principal) {
- return new Promise((resolve, reject) => {
- var source;
- function observe(subject, topic, data) {
- if (topic == "alertclickcallback") {
- reject(new Error("Alerts should not be clicked during test"));
- } else if (topic == "alertshow") {
- source = chromeScript.sendSyncMessage("getAlertSource")[0][0];
- notifier.closeAlert(alertName);
- } else {
- is(topic, "alertfinished", "Should hide alert");
- resolve(source);
- }
- }
- notifier.showAlertNotification(null, "Notification test",
- "Surprise! I'm here to test notifications!",
- false, alertName, observe, alertName,
- null, null, null, principal);
- if (SpecialPowers.Services.appinfo.OS == "Darwin") {
- notifier.closeAlert(alertName);
- }
- });
-}
-
-function* testNoPrincipal() {
- var source = yield notify("noPrincipal", null);
- ok(!source, "Should omit source without principal");
-}
-
-function* testSystemPrincipal() {
- var principal = Services.scriptSecurityManager.getSystemPrincipal();
- var source = yield notify("systemPrincipal", principal);
- ok(!source, "Should omit source for system principal");
-}
-
-function* testNullPrincipal() {
- var principal = Services.scriptSecurityManager.createNullPrincipal({});
- var source = yield notify("nullPrincipal", principal);
- ok(!source, "Should omit source for null principal");
-}
-
-function* testNodePrincipal() {
- var principal = SpecialPowers.wrap(document).nodePrincipal;
- var source = yield notify("nodePrincipal", principal);
-
- var stringBundle = Services.strings.createBundle(
- "chrome://alerts/locale/alert.properties"
- );
- var localizedSource = stringBundle.formatStringFromName(
- "source.label", [principal.URI.hostPort], 1);
- is(source, localizedSource, "Should include source for node principal");
-}
-
-function runTest() {
- if (!("@mozilla.org/alerts-service;1" in Cc)) {
- todo(false, "Alerts service does not exist in this application");
- return;
- }
-
- if ("@mozilla.org/system-alerts-service;1" in Cc) {
- todo(false, "Native alerts service exists in this application");
- return;
- }
-
- ok(true, "Alerts service exists in this application");
-
- // sendSyncMessage returns an array of arrays. See the comments in
- // test_alerts_noobserve.html and test_SpecialPowersLoadChromeScript.html.
- var [[alertsVisible]] = chromeScript.sendSyncMessage("anyXULAlertsVisible");
- ok(!alertsVisible, "Alerts should not be present at the start of the test.");
-
- add_task(testNoPrincipal);
- add_task(testSystemPrincipal);
- add_task(testNullPrincipal);
- add_task(testNodePrincipal);
-}
-
-runTest();
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/asyncshutdown/moz.build b/toolkit/components/asyncshutdown/moz.build
index 79a4c44c7..0051c97a0 100644
--- a/toolkit/components/asyncshutdown/moz.build
+++ b/toolkit/components/asyncshutdown/moz.build
@@ -4,22 +4,12 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
XPIDL_MODULE = 'toolkit_asyncshutdown'
+XPIDL_SOURCES += ['nsIAsyncShutdown.idl']
-XPIDL_SOURCES += [
- 'nsIAsyncShutdown.idl',
-]
-
-EXTRA_JS_MODULES += [
- 'AsyncShutdown.jsm',
-]
+EXTRA_JS_MODULES += ['AsyncShutdown.jsm']
EXTRA_COMPONENTS += [
'nsAsyncShutdown.js',
'nsAsyncShutdown.manifest',
]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Async Tooling')
diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/.eslintrc.js b/toolkit/components/asyncshutdown/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/asyncshutdown/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/head.js b/toolkit/components/asyncshutdown/tests/xpcshell/head.js
deleted file mode 100644
index 9de489808..000000000
--- a/toolkit/components/asyncshutdown/tests/xpcshell/head.js
+++ /dev/null
@@ -1,174 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-"use strict";
-
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/AsyncShutdown.jsm");
-
-var asyncShutdownService = Cc["@mozilla.org/async-shutdown-service;1"].
- getService(Ci.nsIAsyncShutdownService);
-
-
-Services.prefs.setBoolPref("toolkit.asyncshutdown.testing", true);
-
-/**
- * Utility function used to provide the same API for various sources
- * of async shutdown barriers.
- *
- * @param {string} kind One of
- * - "phase" to test an AsyncShutdown phase;
- * - "barrier" to test an instance of AsyncShutdown.Barrier;
- * - "xpcom-barrier" to test an instance of nsIAsyncShutdownBarrier;
- * - "xpcom-barrier-unwrapped" to test the field `jsclient` of a nsIAsyncShutdownClient.
- *
- * @return An object with the following methods:
- * - addBlocker() - the same method as AsyncShutdown phases and barrier clients
- * - wait() - trigger the resolution of the lock
- */
-function makeLock(kind) {
- if (kind == "phase") {
- let topic = "test-Phase-" + ++makeLock.counter;
- let phase = AsyncShutdown._getPhase(topic);
- return {
- addBlocker: function(...args) {
- return phase.addBlocker(...args);
- },
- removeBlocker: function(blocker) {
- return phase.removeBlocker(blocker);
- },
- wait: function() {
- Services.obs.notifyObservers(null, topic, null);
- return Promise.resolve();
- }
- };
- } else if (kind == "barrier") {
- let name = "test-Barrier-" + ++makeLock.counter;
- let barrier = new AsyncShutdown.Barrier(name);
- return {
- addBlocker: barrier.client.addBlocker,
- removeBlocker: barrier.client.removeBlocker,
- wait: function() {
- return barrier.wait();
- }
- };
- } else if (kind == "xpcom-barrier") {
- let name = "test-xpcom-Barrier-" + ++makeLock.counter;
- let barrier = asyncShutdownService.makeBarrier(name);
- return {
- addBlocker: function(blockerName, condition, state) {
- if (condition == null) {
- // Slight trick as `null` or `undefined` cannot be used as keys
- // for `xpcomMap`. Note that this has no incidence on the result
- // of the test as the XPCOM interface imposes that the condition
- // is a method, so it cannot be `null`/`undefined`.
- condition = "<this case can't happen with the xpcom interface>";
- }
- let blocker = makeLock.xpcomMap.get(condition);
- if (!blocker) {
- blocker = {
- name: blockerName,
- state: state,
- blockShutdown: function(aBarrierClient) {
- return Task.spawn(function*() {
- try {
- if (typeof condition == "function") {
- yield Promise.resolve(condition());
- } else {
- yield Promise.resolve(condition);
- }
- } finally {
- aBarrierClient.removeBlocker(blocker);
- }
- });
- },
- };
- makeLock.xpcomMap.set(condition, blocker);
- }
- let {fileName, lineNumber, stack} = (new Error());
- return barrier.client.addBlocker(blocker, fileName, lineNumber, stack);
- },
- removeBlocker: function(condition) {
- let blocker = makeLock.xpcomMap.get(condition);
- if (!blocker) {
- return;
- }
- barrier.client.removeBlocker(blocker);
- },
- wait: function() {
- return new Promise(resolve => {
- barrier.wait(resolve);
- });
- }
- };
- } else if ("unwrapped-xpcom-barrier") {
- let name = "unwrapped-xpcom-barrier-" + ++makeLock.counter;
- let barrier = asyncShutdownService.makeBarrier(name);
- let client = barrier.client.jsclient;
- return {
- addBlocker: client.addBlocker,
- removeBlocker: client.removeBlocker,
- wait: function() {
- return new Promise(resolve => {
- barrier.wait(resolve);
- });
- }
- };
- }
- throw new TypeError("Unknown kind " + kind);
-}
-makeLock.counter = 0;
-makeLock.xpcomMap = new Map(); // Note: Not a WeakMap as we wish to handle non-gc-able keys (e.g. strings)
-
-/**
- * An asynchronous task that takes several ticks to complete.
- *
- * @param {*=} resolution The value with which the resulting promise will be
- * resolved once the task is complete. This may be a rejected promise,
- * in which case the resulting promise will itself be rejected.
- * @param {object=} outResult An object modified by side-effect during the task.
- * Initially, its field |isFinished| is set to |false|. Once the task is
- * complete, its field |isFinished| is set to |true|.
- *
- * @return {promise} A promise fulfilled once the task is complete
- */
-function longRunningAsyncTask(resolution = undefined, outResult = {}) {
- outResult.isFinished = false;
- if (!("countFinished" in outResult)) {
- outResult.countFinished = 0;
- }
- let deferred = Promise.defer();
- do_timeout(100, function() {
- ++outResult.countFinished;
- outResult.isFinished = true;
- deferred.resolve(resolution);
- });
- return deferred.promise;
-}
-
-function get_exn(f) {
- try {
- f();
- return null;
- } catch (ex) {
- return ex;
- }
-}
-
-function do_check_exn(exn, constructor) {
- do_check_neq(exn, null);
- if (exn.name == constructor) {
- do_check_eq(exn.constructor.name, constructor);
- return;
- }
- do_print("Wrong error constructor");
- do_print(exn.constructor.name);
- do_print(exn.stack);
- do_check_true(false);
-}
diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown.js b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown.js
deleted file mode 100644
index f1aebc3ad..000000000
--- a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown.js
+++ /dev/null
@@ -1,194 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-"use strict";
-
-Cu.import("resource://gre/modules/PromiseUtils.jsm", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_no_condition() {
- for (let kind of ["phase", "barrier", "xpcom-barrier", "xpcom-barrier-unwrapped"]) {
- do_print("Testing a barrier with no condition (" + kind + ")");
- let lock = makeLock(kind);
- yield lock.wait();
- do_print("Barrier with no condition didn't lock");
- }
-});
-
-add_task(function* test_phase_various_failures() {
- for (let kind of ["phase", "barrier", "xpcom-barrier", "xpcom-barrier-unwrapped"]) {
- do_print("Kind: " + kind);
- // Testing with wrong arguments
- let lock = makeLock(kind);
-
- Assert.throws(() => lock.addBlocker(), /TypeError|NS_ERROR_XPC_JAVASCRIPT_ERROR_WITH_DETAILS/);
- Assert.throws(() => lock.addBlocker(null, true), /TypeError|NS_ERROR_XPC_JAVASCRIPT_ERROR_WITH_DETAILS/);
-
- if (kind != "xpcom-barrier") {
- // xpcom-barrier actually expects a string in that position
- Assert.throws(() => lock.addBlocker("Test 2", () => true, "not a function"), /TypeError/);
- }
-
- // Attempting to add a blocker after we are done waiting
- yield lock.wait();
- Assert.throws(() => lock.addBlocker("Test 3", () => true), /is finished/);
- }
-});
-
-add_task(function* test_reentrant() {
- do_print("Ensure that we can call addBlocker from within a blocker");
-
- for (let kind of ["phase", "barrier", "xpcom-barrier", "xpcom-barrier-unwrapped"]) {
- do_print("Kind: " + kind);
- let lock = makeLock(kind);
-
- let deferredOuter = PromiseUtils.defer();
- let deferredInner = PromiseUtils.defer();
- let deferredBlockInner = PromiseUtils.defer();
-
- lock.addBlocker("Outer blocker", () => {
- do_print("Entering outer blocker");
- deferredOuter.resolve();
- lock.addBlocker("Inner blocker", () => {
- do_print("Entering inner blocker");
- deferredInner.resolve();
- return deferredBlockInner.promise;
- });
- });
-
- // Note that phase-style locks spin the event loop and do not return from
- // `lock.wait()` until after all blockers have been resolved. Therefore,
- // to be able to test them, we need to dispatch the following steps to the
- // event loop before calling `lock.wait()`, which we do by forcing
- // a Promise.resolve().
- //
- let promiseSteps = Task.spawn(function* () {
- yield Promise.resolve();
-
- do_print("Waiting until we have entered the outer blocker");
- yield deferredOuter.promise;
-
- do_print("Waiting until we have entered the inner blocker");
- yield deferredInner.promise;
-
- do_print("Allowing the lock to resolve")
- deferredBlockInner.resolve();
- });
-
- do_print("Starting wait");
- yield lock.wait();
-
- do_print("Waiting until all steps have been walked");
- yield promiseSteps;
- }
-});
-
-
-add_task(function* test_phase_removeBlocker() {
- do_print("Testing that we can call removeBlocker before, during and after the call to wait()");
-
- for (let kind of ["phase", "barrier", "xpcom-barrier", "xpcom-barrier-unwrapped"]) {
-
- do_print("Switching to kind " + kind);
- do_print("Attempt to add then remove a blocker before wait()");
- let lock = makeLock(kind);
- let blocker = () => {
- do_print("This promise will never be resolved");
- return Promise.defer().promise;
- };
-
- lock.addBlocker("Wait forever", blocker);
- let do_remove_blocker = function(aLock, aBlocker, aShouldRemove) {
- do_print("Attempting to remove blocker " + aBlocker + ", expecting result " + aShouldRemove);
- if (kind == "xpcom-barrier") {
- // The xpcom variant always returns `undefined`, so we can't
- // check its result.
- aLock.removeBlocker(aBlocker);
- return;
- }
- do_check_eq(aLock.removeBlocker(aBlocker), aShouldRemove);
- };
- do_remove_blocker(lock, blocker, true);
- do_remove_blocker(lock, blocker, false);
- do_print("Attempt to remove non-registered blockers before wait()");
- do_remove_blocker(lock, "foo", false);
- do_remove_blocker(lock, null, false);
- do_print("Waiting (should lift immediately)");
- yield lock.wait();
-
- do_print("Attempt to add a blocker then remove it during wait()");
- lock = makeLock(kind);
- let blockers = [
- () => {
- do_print("This blocker will self-destruct");
- do_remove_blocker(lock, blockers[0], true);
- return Promise.defer().promise;
- },
- () => {
- do_print("This blocker will self-destruct twice");
- do_remove_blocker(lock, blockers[1], true);
- do_remove_blocker(lock, blockers[1], false);
- return Promise.defer().promise;
- },
- () => {
- do_print("Attempt to remove non-registered blockers during wait()");
- do_remove_blocker(lock, "foo", false);
- do_remove_blocker(lock, null, false);
- }
- ];
- for (let i in blockers) {
- lock.addBlocker("Wait forever again: " + i, blockers[i]);
- }
- do_print("Waiting (should lift very quickly)");
- yield lock.wait();
- do_remove_blocker(lock, blockers[0], false);
-
-
- do_print("Attempt to remove a blocker after wait");
- lock = makeLock(kind);
- blocker = Promise.resolve.bind(Promise);
- yield lock.wait();
- do_remove_blocker(lock, blocker, false);
-
- do_print("Attempt to remove non-registered blocker after wait()");
- do_remove_blocker(lock, "foo", false);
- do_remove_blocker(lock, null, false);
- }
-
-});
-
-add_task(function* test_state() {
- do_print("Testing information contained in `state`");
-
- let BLOCKER_NAME = "test_state blocker " + Math.random();
-
- // Set up the barrier. Note that we cannot test `barrier.state`
- // immediately, as it initially contains "Not started"
- let barrier = new AsyncShutdown.Barrier("test_filename");
- let deferred = Promise.defer();
- let {filename, lineNumber} = Components.stack;
- barrier.client.addBlocker(BLOCKER_NAME,
- function() {
- return deferred.promise;
- });
-
- let promiseDone = barrier.wait();
-
- // Now that we have called `wait()`, the state contains interesting things
- let state = barrier.state[0];
- do_print("State: " + JSON.stringify(barrier.state, null, "\t"));
- Assert.equal(state.filename, filename);
- Assert.equal(state.lineNumber, lineNumber + 1);
- Assert.equal(state.name, BLOCKER_NAME);
- Assert.ok(state.stack.some(x => x.includes("test_state")), "The stack contains the caller function's name");
- Assert.ok(state.stack.some(x => x.includes(filename)), "The stack contains the calling file's name");
-
- deferred.resolve();
- yield promiseDone;
-});
-
-add_task(function*() {
- Services.prefs.clearUserPref("toolkit.asyncshutdown.testing");
-});
diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js
deleted file mode 100644
index 33da1f53f..000000000
--- a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown_leave_uncaught.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-"use strict";
-
-//
-// This file contains tests that need to leave uncaught asynchronous
-// errors. If your test catches all its asynchronous errors, please
-// put it in another file.
-//
-
-Promise.Debugging.clearUncaughtErrorObservers();
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_phase_simple_async() {
- do_print("Testing various combinations of a phase with a single condition");
- for (let kind of ["phase", "barrier", "xpcom-barrier", "xpcom-barrier-unwrapped"]) {
- for (let arg of [undefined, null, "foo", 100, new Error("BOOM")]) {
- for (let resolution of [arg, Promise.reject(arg)]) {
- for (let success of [false, true]) {
- for (let state of [[null],
- [],
- [() => "some state"],
- [function() {
- throw new Error("State BOOM"); }],
- [function() {
- return {
- toJSON: function() {
- throw new Error("State.toJSON BOOM");
- }
- };
- }]]) {
- // Asynchronous phase
- do_print("Asynchronous test with " + arg + ", " + resolution + ", " + kind);
- let lock = makeLock(kind);
- let outParam = { isFinished: false };
- lock.addBlocker(
- "Async test",
- function() {
- if (success) {
- return longRunningAsyncTask(resolution, outParam);
- }
- throw resolution;
- },
- ...state
- );
- do_check_false(outParam.isFinished);
- yield lock.wait();
- do_check_eq(outParam.isFinished, success);
- }
- }
-
- // Synchronous phase - just test that we don't throw/freeze
- do_print("Synchronous test with " + arg + ", " + resolution + ", " + kind);
- let lock = makeLock(kind);
- lock.addBlocker(
- "Sync test",
- resolution
- );
- yield lock.wait();
- }
- }
- }
-});
-
-add_task(function* test_phase_many() {
- do_print("Testing various combinations of a phase with many conditions");
- for (let kind of ["phase", "barrier", "xpcom-barrier", "xpcom-barrier-unwrapped"]) {
- let lock = makeLock(kind);
- let outParams = [];
- for (let arg of [undefined, null, "foo", 100, new Error("BOOM")]) {
- for (let resolve of [true, false]) {
- do_print("Testing with " + kind + ", " + arg + ", " + resolve);
- let resolution = resolve ? arg : Promise.reject(arg);
- let outParam = { isFinished: false };
- lock.addBlocker(
- "Test " + Math.random(),
- () => longRunningAsyncTask(resolution, outParam)
- );
- }
- }
- do_check_true(outParams.every((x) => !x.isFinished));
- yield lock.wait();
- do_check_true(outParams.every((x) => x.isFinished));
- }
-});
-
-
-
-
-add_task(function*() {
- Services.prefs.clearUserPref("toolkit.asyncshutdown.testing");
-});
-
diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/test_converters.js b/toolkit/components/asyncshutdown/tests/xpcshell/test_converters.js
deleted file mode 100644
index c6c923187..000000000
--- a/toolkit/components/asyncshutdown/tests/xpcshell/test_converters.js
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-"use strict";
-
-/**
- * Test conversion between nsIPropertyBag and JS values.
- */
-
-var PropertyBagConverter = asyncShutdownService.wrappedJSObject._propertyBagConverter;
-
-function run_test() {
- test_conversions();
-}
-
-function normalize(obj) {
- if (obj == null || typeof obj != "object") {
- return obj;
- }
- if (Array.isArray(obj)) {
- return obj.map(normalize);
- }
- let result = {};
- for (let k of Object.keys(obj).sort()) {
- result[k] = normalize(obj[k]);
- }
- return result;
-}
-
-function test_conversions() {
- const SAMPLES = [
- // Simple values
- 1,
- true,
- "string",
- null,
-
- // Objects
- {
- a: 1,
- b: true,
- c: "string",
- d:.5,
- e: [2, false, "another string", .3],
- f: [],
- g: {
- a2: 1,
- b2: true,
- c2: "string",
- d2:.5,
- e2: [2, false, "another string", .3],
- f2: [],
- g2: [{
- a3: 1,
- b3: true,
- c3: "string",
- d3:.5,
- e3: [2, false, "another string", .3],
- f3: [],
- g3: {}
- }]
- }
- }];
-
- for (let sample of SAMPLES) {
- let stringified = JSON.stringify(normalize(sample), null, "\t");
- do_print("Testing conversions of " + stringified);
- let rewrites = [sample];
- for (let i = 1; i < 3; ++i) {
- let source = rewrites[i - 1];
- let bag = PropertyBagConverter.fromValue(source);
- do_print(" => " + bag);
- if (source == null) {
- Assert.ok(bag == null, "The bag is null");
- } else if (typeof source == "object") {
- Assert.ok(bag instanceof Ci.nsIPropertyBag, "The bag is a property bag");
- } else {
- Assert.ok(typeof bag != "object", "The bag is not an object");
- }
- let dest = PropertyBagConverter.toValue(bag);
- let restringified = JSON.stringify(normalize(dest), null, "\t");
- do_print("Comparing");
- do_print(stringified);
- do_print(restringified);
- Assert.deepEqual(sample, dest, "Testing after " + i + " conversions");
- rewrites.push(dest);
- }
- }
-}
diff --git a/toolkit/components/asyncshutdown/tests/xpcshell/xpcshell.ini b/toolkit/components/asyncshutdown/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index f573955bc..000000000
--- a/toolkit/components/asyncshutdown/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-head=head.js
-tail=
-skip-if = toolkit == 'android'
-
-[test_AsyncShutdown.js]
-[test_AsyncShutdown_leave_uncaught.js]
-[test_converters.js]
diff --git a/toolkit/components/autocomplete/moz.build b/toolkit/components/autocomplete/moz.build
index f3817d642..a2e30b34b 100644
--- a/toolkit/components/autocomplete/moz.build
+++ b/toolkit/components/autocomplete/moz.build
@@ -4,8 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
-
XPIDL_SOURCES += [
'nsIAutoCompleteController.idl',
'nsIAutoCompleteInput.idl',
@@ -23,6 +21,3 @@ UNIFIED_SOURCES += [
]
FINAL_LIBRARY = 'xul'
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Autocomplete')
diff --git a/toolkit/components/autocomplete/tests/unit/.eslintrc.js b/toolkit/components/autocomplete/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/autocomplete/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js b/toolkit/components/autocomplete/tests/unit/head_autocomplete.js
deleted file mode 100644
index 5a458bdf4..000000000
--- a/toolkit/components/autocomplete/tests/unit/head_autocomplete.js
+++ /dev/null
@@ -1,211 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-
-/**
- * Dummy nsIAutoCompleteInput source that returns
- * the given list of AutoCompleteSearch names.
- *
- * Implements only the methods needed for this test.
- */
-function AutoCompleteInputBase(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInputBase.prototype = {
-
- // Array of AutoCompleteSearch names
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- // Text selection range
- _selStart: 0,
- _selEnd: 0,
- get selectionStart() {
- return this._selStart;
- },
- get selectionEnd() {
- return this._selEnd;
- },
- selectTextRange: function(aStart, aEnd) {
- this._selStart = aStart;
- this._selEnd = aEnd;
- },
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- get popup() {
- if (!this._popup) {
- this._popup = new AutocompletePopupBase(this);
- }
- return this._popup;
- },
-
- // nsISupports implementation
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
-}
-
-/**
- * nsIAutoCompleteResult implementation
- */
-function AutoCompleteResultBase(aValues) {
- this._values = aValues;
-}
-AutoCompleteResultBase.prototype = {
-
- // Arrays
- _values: null,
- _comments: [],
- _styles: [],
- _finalCompleteValues: [],
-
- searchString: "",
- searchResult: null,
-
- defaultIndex: -1,
-
- _typeAheadResult: false,
- get typeAheadResult() {
- return this._typeAheadResult;
- },
-
- get matchCount() {
- return this._values.length;
- },
-
- getValueAt: function(aIndex) {
- return this._values[aIndex];
- },
-
- getLabelAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- getCommentAt: function(aIndex) {
- return this._comments[aIndex];
- },
-
- getStyleAt: function(aIndex) {
- return this._styles[aIndex];
- },
-
- getImageAt: function(aIndex) {
- return "";
- },
-
- getFinalCompleteValueAt: function(aIndex) {
- return this._finalCompleteValues[aIndex] || this._values[aIndex];
- },
-
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
-
- // nsISupports implementation
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteResult])
-}
-
-/**
- * nsIAutoCompleteSearch implementation that always returns
- * the same result set.
- */
-function AutoCompleteSearchBase(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteSearchBase.prototype = {
-
- // Search name. Used by AutoCompleteController
- name: null,
-
- // AutoCompleteResult
- _result: null,
-
- startSearch: function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener) {
- var result = this._result;
-
- result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
- aListener.onSearchResult(this, result);
- },
-
- stopSearch: function() {},
-
- // nsISupports implementation
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory,
- Ci.nsIAutoCompleteSearch]),
-
- // nsIFactory implementation
- createInstance: function(outer, iid) {
- return this.QueryInterface(iid);
- }
-}
-
-function AutocompletePopupBase(input) {
- this.input = input;
-}
-AutocompletePopupBase.prototype = {
- selectedIndex: 0,
- invalidate() {},
- selectBy(reverse, page) {
- let numRows = this.input.controller.matchCount;
- if (numRows > 0) {
- let delta = reverse ? -1 : 1;
- this.selectedIndex = (this.selectedIndex + delta) % numRows;
- if (this.selectedIndex < 0) {
- this.selectedIndex = numRows - 1;
- }
- }
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup]),
-};
-
-/**
- * Helper to register an AutoCompleteSearch with the given name.
- * Allows the AutoCompleteController to find the search.
- */
-function registerAutoCompleteSearch(aSearch) {
- var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
- var cid = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator).
- generateUUID();
-
- var desc = "Test AutoCompleteSearch";
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.registerFactory(cid, desc, name, aSearch);
-
- // Keep the id on the object so we can unregister later
- aSearch.cid = cid;
-}
-
-/**
- * Helper to unregister an AutoCompleteSearch.
- */
-function unregisterAutoCompleteSearch(aSearch) {
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.unregisterFactory(aSearch.cid, aSearch);
-}
-
diff --git a/toolkit/components/autocomplete/tests/unit/test_330578.js b/toolkit/components/autocomplete/tests/unit/test_330578.js
deleted file mode 100644
index c422dbb6a..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_330578.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var gResultListener = {
- _lastResult: null,
- _lastValue: "",
- _lastRemoveFromDb: false,
-
- onValueRemoved: function(aResult, aValue, aRemoveFromDb) {
- this._lastResult = aResult;
- this._lastValue = aValue;
- this._lastRemoveFromDb = aRemoveFromDb;
- }
-};
-
-
-// main
-function run_test() {
- var result = Cc["@mozilla.org/autocomplete/simple-result;1"].
- createInstance(Ci.nsIAutoCompleteSimpleResult);
- result.appendMatch("a", "");
- result.appendMatch("b", "");
- result.appendMatch("c", "");
- result.setListener(gResultListener);
- do_check_eq(result.matchCount, 3);
- result.removeValueAt(0, true);
- do_check_eq(result.matchCount, 2);
- do_check_eq(gResultListener._lastResult, result);
- do_check_eq(gResultListener._lastValue, "a");
- do_check_eq(gResultListener._lastRemoveFromDb, true);
-
- result.removeValueAt(0, false);
- do_check_eq(result.matchCount, 1);
- do_check_eq(gResultListener._lastValue, "b");
- do_check_eq(gResultListener._lastRemoveFromDb, false);
-
- // check that we don't get notified if the listener is unset
- result.setListener(null);
- result.removeValueAt(0, true); // "c"
- do_check_eq(result.matchCount, 0);
- do_check_eq(gResultListener._lastValue, "b");
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_378079.js b/toolkit/components/autocomplete/tests/unit/test_378079.js
deleted file mode 100644
index ad7e5590f..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_378079.js
+++ /dev/null
@@ -1,285 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Unit test for Bug 378079 - AutoComplete returns invalid rows when
- * more than one AutoCompleteSearch is used.
- */
-
-
-
-/**
- * Dummy nsIAutoCompleteInput source that returns
- * the given list of AutoCompleteSearch names.
- *
- * Implements only the methods needed for this test.
- */
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- // Array of AutoCompleteSearch names
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteResult implementation
- */
-function AutoCompleteResult(aValues, aComments, aStyles) {
- this._values = aValues;
- this._comments = aComments;
- this._styles = aStyles;
-
- if (this._values.length > 0) {
- this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
- } else {
- this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
- }
-}
-AutoCompleteResult.prototype = {
- constructor: AutoCompleteResult,
-
- // Arrays
- _values: null,
- _comments: null,
- _styles: null,
-
- searchString: "",
- searchResult: null,
-
- defaultIndex: 0,
-
- get matchCount() {
- return this._values.length;
- },
-
- getValueAt: function(aIndex) {
- return this._values[aIndex];
- },
-
- getLabelAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- getCommentAt: function(aIndex) {
- return this._comments[aIndex];
- },
-
- getStyleAt: function(aIndex) {
- return this._styles[aIndex];
- },
-
- getImageAt: function(aIndex) {
- return "";
- },
-
- getFinalCompleteValueAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteResult))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteSearch implementation that always returns
- * the same result set.
- */
-function AutoCompleteSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteSearch.prototype = {
- constructor: AutoCompleteSearch,
-
- // Search name. Used by AutoCompleteController
- name: null,
-
- // AutoCompleteResult
- _result:null,
-
-
- /**
- * Return the same result set for every search
- */
- startSearch: function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener)
- {
- aListener.onSearchResult(this, this._result);
- },
-
- stopSearch: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIFactory) ||
- iid.equals(Ci.nsIAutoCompleteSearch))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- },
-
- // nsIFactory implementation
- createInstance: function(outer, iid) {
- return this.QueryInterface(iid);
- }
-}
-
-
-
-/**
- * Helper to register an AutoCompleteSearch with the given name.
- * Allows the AutoCompleteController to find the search.
- */
-function registerAutoCompleteSearch(aSearch) {
- var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
-
- var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator);
- var cid = uuidGenerator.generateUUID();
-
- var desc = "Test AutoCompleteSearch";
-
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.registerFactory(cid, desc, name, aSearch);
-
- // Keep the id on the object so we can unregister later
- aSearch.cid = cid;
-}
-
-
-
-/**
- * Helper to unregister an AutoCompleteSearch.
- */
-function unregisterAutoCompleteSearch(aSearch) {
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.unregisterFactory(aSearch.cid, aSearch);
-}
-
-
-
-/**
- * Test AutoComplete with multiple AutoCompleteSearch sources.
- */
-function run_test() {
-
- // Make an AutoCompleteSearch that always returns nothing
- var emptySearch = new AutoCompleteSearch("test-empty-search",
- new AutoCompleteResult([], [], []));
-
- // Make an AutoCompleteSearch that returns two values
- var expectedValues = ["test1", "test2"];
- var regularSearch = new AutoCompleteSearch("test-regular-search",
- new AutoCompleteResult(expectedValues, [], []));
-
- // Register searches so AutoCompleteController can find them
- registerAutoCompleteSearch(emptySearch);
- registerAutoCompleteSearch(regularSearch);
-
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput([emptySearch.name, regularSearch.name]);
- var numSearchesStarted = 0;
-
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function() {
-
- do_check_eq(numSearchesStarted, 1);
-
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- do_check_eq(controller.matchCount, 2);
-
- // Confirm expected result values
- for (var i = 0; i < expectedValues.length; i++) {
- do_check_eq(expectedValues[i], controller.getValueAt(i));
- }
-
- // Unregister searches
- unregisterAutoCompleteSearch(emptySearch);
- unregisterAutoCompleteSearch(regularSearch);
-
- do_test_finished();
- };
-
- controller.input = input;
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- controller.startSearch("test");
-}
-
diff --git a/toolkit/components/autocomplete/tests/unit/test_393191.js b/toolkit/components/autocomplete/tests/unit/test_393191.js
deleted file mode 100644
index 6fb57e6c4..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_393191.js
+++ /dev/null
@@ -1,272 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Unit test for Bug 393191 - AutoComplete crashes if result is null
- */
-
-
-
-/**
- * Dummy nsIAutoCompleteInput source that returns
- * the given list of AutoCompleteSearch names.
- *
- * Implements only the methods needed for this test.
- */
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- // Array of AutoCompleteSearch names
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteResult implementation
- */
-function AutoCompleteResult(aValues, aComments, aStyles) {
- this._values = aValues;
- this._comments = aComments;
- this._styles = aStyles;
-
- if (this._values.length > 0) {
- this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
- } else {
- this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
- }
-}
-AutoCompleteResult.prototype = {
- constructor: AutoCompleteResult,
-
- // Arrays
- _values: null,
- _comments: null,
- _styles: null,
-
- searchString: "",
- searchResult: null,
-
- defaultIndex: 0,
-
- get matchCount() {
- return this._values.length;
- },
-
- getValueAt: function(aIndex) {
- return this._values[aIndex];
- },
-
- getLabelAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- getCommentAt: function(aIndex) {
- return this._comments[aIndex];
- },
-
- getStyleAt: function(aIndex) {
- return this._styles[aIndex];
- },
-
- getImageAt: function(aIndex) {
- return "";
- },
-
- getFinalCompleteValueAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteResult))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteSearch implementation that always returns
- * the same result set.
- */
-function AutoCompleteSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteSearch.prototype = {
- constructor: AutoCompleteSearch,
-
- // Search name. Used by AutoCompleteController
- name: null,
-
- // AutoCompleteResult
- _result: null,
-
-
- /**
- * Return the same result set for every search
- */
- startSearch: function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener)
- {
- aListener.onSearchResult(this, this._result);
- },
-
- stopSearch: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIFactory) ||
- iid.equals(Ci.nsIAutoCompleteSearch))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- },
-
- // nsIFactory implementation
- createInstance: function(outer, iid) {
- return this.QueryInterface(iid);
- }
-}
-
-
-
-/**
- * Helper to register an AutoCompleteSearch with the given name.
- * Allows the AutoCompleteController to find the search.
- */
-function registerAutoCompleteSearch(aSearch) {
- var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
-
- var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator);
- var cid = uuidGenerator.generateUUID();
-
- var desc = "Test AutoCompleteSearch";
-
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.registerFactory(cid, desc, name, aSearch);
-
- // Keep the id on the object so we can unregister later
- aSearch.cid = cid;
-}
-
-
-
-/**
- * Helper to unregister an AutoCompleteSearch.
- */
-function unregisterAutoCompleteSearch(aSearch) {
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.unregisterFactory(aSearch.cid, aSearch);
-}
-
-
-
-/**
- * Test AutoComplete with a search that returns a null result
- */
-function run_test() {
-
- // Make an AutoCompleteSearch that always returns nothing
- var emptySearch = new AutoCompleteSearch("test-empty-search",
- new AutoCompleteResult([], [], []));
-
- // Register search so AutoCompleteController can find them
- registerAutoCompleteSearch(emptySearch);
-
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our search
- // and confirms results on search complete
- var input = new AutoCompleteInput([emptySearch.name]);
- var numSearchesStarted = 0;
-
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function() {
-
- do_check_eq(numSearchesStarted, 1);
-
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
- do_check_eq(controller.matchCount, 0);
-
- // Unregister searches
- unregisterAutoCompleteSearch(emptySearch);
-
- do_test_finished();
- };
-
- controller.input = input;
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- controller.startSearch("test");
-}
-
diff --git a/toolkit/components/autocomplete/tests/unit/test_440866.js b/toolkit/components/autocomplete/tests/unit/test_440866.js
deleted file mode 100644
index e450aebbf..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_440866.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/. */
-
-/**
- * Unit test for Bug 440866 - First AutoCompleteSearch that returns
- * RESULT_NOMATCH cancels all other searches when popup is open
- */
-
-
-
-/**
- * Dummy nsIAutoCompleteInput source that returns
- * the given list of AutoCompleteSearch names.
- *
- * Implements only the methods needed for this test.
- */
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- // Array of AutoCompleteSearch names
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteResult implementation
- */
-function AutoCompleteResult(aValues, aComments, aStyles) {
- this._values = aValues;
- this._comments = aComments;
- this._styles = aStyles;
-
- if (this._values.length > 0) {
- this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
- } else {
- this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
- }
-}
-AutoCompleteResult.prototype = {
- constructor: AutoCompleteResult,
-
- // Arrays
- _values: null,
- _comments: null,
- _styles: null,
-
- searchString: "",
- searchResult: null,
-
- defaultIndex: 0,
-
- get matchCount() {
- return this._values.length;
- },
-
- getValueAt: function(aIndex) {
- return this._values[aIndex];
- },
-
- getLabelAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- getCommentAt: function(aIndex) {
- return this._comments[aIndex];
- },
-
- getStyleAt: function(aIndex) {
- return this._styles[aIndex];
- },
-
- getImageAt: function(aIndex) {
- return "";
- },
-
- getFinalCompleteValueAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteResult))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteSearch implementation that always returns
- * the same result set.
- */
-function AutoCompleteSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteSearch.prototype = {
- constructor: AutoCompleteSearch,
-
- // Search name. Used by AutoCompleteController
- name: null,
-
- // AutoCompleteResult
- _result:null,
-
-
- /**
- * Return the same result set for every search
- */
- startSearch: function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener)
- {
- aListener.onSearchResult(this, this._result);
- },
-
- stopSearch: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIFactory) ||
- iid.equals(Ci.nsIAutoCompleteSearch))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- },
-
- // nsIFactory implementation
- createInstance: function(outer, iid) {
- return this.QueryInterface(iid);
- }
-}
-
-
-
-/**
- * Helper to register an AutoCompleteSearch with the given name.
- * Allows the AutoCompleteController to find the search.
- */
-function registerAutoCompleteSearch(aSearch) {
- var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
-
- var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator);
- var cid = uuidGenerator.generateUUID();
-
- var desc = "Test AutoCompleteSearch";
-
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.registerFactory(cid, desc, name, aSearch);
-
- // Keep the id on the object so we can unregister later
- aSearch.cid = cid;
-}
-
-
-
-/**
- * Helper to unregister an AutoCompleteSearch.
- */
-function unregisterAutoCompleteSearch(aSearch) {
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.unregisterFactory(aSearch.cid, aSearch);
-}
-
-
-
-/**
- * Test AutoComplete with multiple AutoCompleteSearch sources.
- */
-function run_test() {
-
- // Make an AutoCompleteSearch that always returns nothing
- var emptySearch = new AutoCompleteSearch("test-empty-search",
- new AutoCompleteResult([], [], []));
-
- // Make an AutoCompleteSearch that returns two values
- var expectedValues = ["test1", "test2"];
- var regularSearch = new AutoCompleteSearch("test-regular-search",
- new AutoCompleteResult(expectedValues, [], []));
-
- // Register searches so AutoCompleteController can find them
- registerAutoCompleteSearch(emptySearch);
- registerAutoCompleteSearch(regularSearch);
-
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput([emptySearch.name, regularSearch.name]);
- var numSearchesStarted = 0;
-
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- do_check_eq(input.searchCount, 2);
- };
-
- input.onSearchComplete = function() {
- do_check_eq(numSearchesStarted, 1);
-
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- do_check_eq(controller.matchCount, 2);
-
- // Confirm expected result values
- for (var i = 0; i < expectedValues.length; i++) {
- do_check_eq(expectedValues[i], controller.getValueAt(i));
- }
-
- do_check_true(input.popupOpen);
-
- // Unregister searches
- unregisterAutoCompleteSearch(emptySearch);
- unregisterAutoCompleteSearch(regularSearch);
-
- do_test_finished();
- };
-
- controller.input = input;
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- controller.startSearch("test");
-}
-
diff --git a/toolkit/components/autocomplete/tests/unit/test_463023.js b/toolkit/components/autocomplete/tests/unit/test_463023.js
deleted file mode 100644
index a2639fd03..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_463023.js
+++ /dev/null
@@ -1,12 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// main
-function run_test() {
- var result = Cc["@mozilla.org/autocomplete/controller;1"].
- createInstance(Ci.nsIAutoCompleteController);
- do_check_eq(result.searchStatus, Ci.nsIAutoCompleteController.STATUS_NONE);
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_660156.js b/toolkit/components/autocomplete/tests/unit/test_660156.js
deleted file mode 100644
index 98acb243e..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_660156.js
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Search object that returns results at different times.
- * First, the search that returns results asynchronously.
- */
-function AutoCompleteAsyncSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteAsyncSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
-AutoCompleteAsyncSearch.prototype.startSearch = function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener) {
- this._result.searchResult = Ci.nsIAutoCompleteResult.RESULT_NOMATCH_ONGOING;
- aListener.onSearchResult(this, this._result);
-
- do_timeout(500, () => {
- this._returnResults(aListener);
- });
-};
-
-AutoCompleteAsyncSearch.prototype._returnResults = function(aListener) {
- var result = this._result;
-
- result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
- aListener.onSearchResult(this, result);
-};
-
-/**
- * The synchronous version
- */
-function AutoCompleteSyncSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteSyncSearch.prototype = Object.create(AutoCompleteAsyncSearch.prototype);
-AutoCompleteSyncSearch.prototype.startSearch = function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener) {
- this._returnResults(aListener);
-};
-
-/**
- * Results object
- */
-function AutoCompleteResult(aValues, aDefaultIndex) {
- this._values = aValues;
- this.defaultIndex = aDefaultIndex;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-
-/**
- * Test AutoComplete with multiple AutoCompleteSearch sources, with one of them
- * (index != 0) returning before the rest.
- */
-function run_test() {
- do_test_pending();
-
- var results = ["mozillaTest"];
- var inputStr = "moz";
-
- // Async search
- var asyncSearch = new AutoCompleteAsyncSearch("Async",
- new AutoCompleteResult(results, -1));
- // Sync search
- var syncSearch = new AutoCompleteSyncSearch("Sync",
- new AutoCompleteResult(results, 0));
-
- // Register searches so AutoCompleteController can find them
- registerAutoCompleteSearch(asyncSearch);
- registerAutoCompleteSearch(syncSearch);
-
- var controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete.
- // Async search MUST be FIRST to trigger the bug this tests.
- var input = new AutoCompleteInputBase([asyncSearch.name, syncSearch.name]);
- input.completeDefaultIndex = true;
- input.textValue = inputStr;
-
- // Caret must be at the end. Autofill doesn't happen unless you're typing
- // characters at the end.
- var strLen = inputStr.length;
- input.selectTextRange(strLen, strLen);
-
- controller.input = input;
- controller.startSearch(inputStr);
-
- input.onSearchComplete = function() {
- do_check_eq(input.textValue, results[0]);
-
- // Unregister searches
- unregisterAutoCompleteSearch(asyncSearch);
- unregisterAutoCompleteSearch(syncSearch);
- do_test_finished();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js
deleted file mode 100644
index 7fee48d55..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js
+++ /dev/null
@@ -1,276 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Dummy nsIAutoCompleteInput source that returns
- * the given list of AutoCompleteSearch names.
- *
- * Implements only the methods needed for this test.
- */
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- // Array of AutoCompleteSearch names
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteResult implementation
- */
-function AutoCompleteResult(aValues, aComments, aStyles) {
- this._values = aValues;
- this._comments = aComments;
- this._styles = aStyles;
-}
-AutoCompleteResult.prototype = {
- constructor: AutoCompleteResult,
-
- // Arrays
- _values: null,
- _comments: null,
- _styles: null,
-
- searchString: "",
- searchResult: null,
-
- defaultIndex: 0,
-
- get matchCount() {
- return this._values.length;
- },
-
- getValueAt: function(aIndex) {
- return this._values[aIndex];
- },
-
- getLabelAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- getCommentAt: function(aIndex) {
- return this._comments[aIndex];
- },
-
- getStyleAt: function(aIndex) {
- return this._styles[aIndex];
- },
-
- getImageAt: function(aIndex) {
- return "";
- },
-
- getFinalCompleteValueAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteResult))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteSearch implementation that always returns
- * the same result set.
- */
-function AutoCompleteSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteSearch.prototype = {
- constructor: AutoCompleteSearch,
-
- // Search name. Used by AutoCompleteController
- name: null,
-
- // AutoCompleteResult
- _result:null,
-
-
- /**
- * Return the same result set for every search
- */
- startSearch: function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener)
- {
- var result = this._result;
- if (result._values.length > 0) {
- result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS_ONGOING;
- } else {
- result.searchResult = Ci.nsIAutoCompleteResult.RESULT_NOMATCH_ONGOING;
- }
- aListener.onSearchResult(this, result);
-
- if (result._values.length > 0) {
- result.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
- } else {
- result.searchResult = Ci.nsIAutoCompleteResult.RESULT_NOMATCH;
- }
- aListener.onSearchResult(this, result);
- },
-
- stopSearch: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIFactory) ||
- iid.equals(Ci.nsIAutoCompleteSearch))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- },
-
- // nsIFactory implementation
- createInstance: function(outer, iid) {
- return this.QueryInterface(iid);
- }
-}
-
-
-
-/**
- * Helper to register an AutoCompleteSearch with the given name.
- * Allows the AutoCompleteController to find the search.
- */
-function registerAutoCompleteSearch(aSearch) {
- var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
-
- var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator);
- var cid = uuidGenerator.generateUUID();
-
- var desc = "Test AutoCompleteSearch";
-
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.registerFactory(cid, desc, name, aSearch);
-
- // Keep the id on the object so we can unregister later
- aSearch.cid = cid;
-}
-
-
-
-/**
- * Helper to unregister an AutoCompleteSearch.
- */
-function unregisterAutoCompleteSearch(aSearch) {
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.unregisterFactory(aSearch.cid, aSearch);
-}
-
-
-
-/**
- * Test AutoComplete with multiple AutoCompleteSearch sources.
- */
-function run_test() {
- var expected1 = ["1", "2", "3"];
- var expected2 = ["a", "b", "c"];
- var search1 = new AutoCompleteSearch("search1",
- new AutoCompleteResult(expected1, [], []));
- var search2 = new AutoCompleteSearch("search2",
- new AutoCompleteResult(expected2, [], []));
-
- // Register searches so AutoCompleteController can find them
- registerAutoCompleteSearch(search1);
- registerAutoCompleteSearch(search2);
-
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput([search1.name, search2.name]);
- var numSearchesStarted = 0;
-
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function() {
-
- do_check_eq(numSearchesStarted, 1);
-
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- do_check_eq(controller.matchCount, expected1.length + expected2.length);
-
- // Unregister searches
- unregisterAutoCompleteSearch(search1);
- unregisterAutoCompleteSearch(search2);
-
- do_test_finished();
- };
-
- controller.input = input;
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- controller.startSearch("test");
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js b/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js
deleted file mode 100644
index c98db7f8f..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js
+++ /dev/null
@@ -1,45 +0,0 @@
-"use strict";
-
-Cu.import("resource://gre/modules/Promise.jsm");
-
-function AutoCompleteInput(aSearches, aUserContextId) {
- this.searches = aSearches;
- this.userContextId = aUserContextId;
- this.popup.selectedIndex = -1;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-function AutoCompleteSearch(aName) {
- this.name = aName;
-}
-AutoCompleteSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
-
-add_task(function *test_userContextId() {
- let searchParam = yield doSearch("test", 1);
- Assert.equal(searchParam, " user-context-id:1");
-});
-
-function doSearch(aString, aUserContextId) {
- let deferred = Promise.defer();
- let search = new AutoCompleteSearch("test");
-
- search.startSearch = function (aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener) {
- unregisterAutoCompleteSearch(search);
- deferred.resolve(aSearchParam);
- };
-
- registerAutoCompleteSearch(search);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- let input = new AutoCompleteInput([ search.name ], aUserContextId);
- controller.input = input;
- controller.startSearch(aString);
-
- return deferred.promise;
- }
-
diff --git a/toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js b/toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js
deleted file mode 100644
index 5fb93abc1..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_autofillSelectedPopupIndex.js
+++ /dev/null
@@ -1,78 +0,0 @@
-"use strict";
-
-add_task(function* sameCaseAsMatch() {
- yield runTest("moz");
-});
-
-add_task(function* differentCaseFromMatch() {
- yield runTest("MOZ");
-});
-
-function* runTest(searchStr) {
- let matches = [
- "mozilla.org",
- "example.com",
- ];
- let result = new AutoCompleteResultBase(matches);
- result.defaultIndex = 0;
-
- let search = new AutoCompleteSearchBase("search", result);
- registerAutoCompleteSearch(search);
-
- let input = new AutoCompleteInputBase([search.name]);
- input.completeSelectedIndex = true;
- input.completeDefaultIndex = true;
-
- // Start off with the search string in the input. The selection must be
- // collapsed and the caret must be at the end to trigger autofill below.
- input.textValue = searchStr;
- input.selectTextRange(searchStr.length, searchStr.length);
- Assert.equal(input.selectionStart, searchStr.length,
- "Selection should start at the end of the input");
- Assert.equal(input.selectionEnd, searchStr.length,
- "Selection should end at the end of the input");
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- createInstance(Ci.nsIAutoCompleteController);
- controller.input = input;
- input.controller = controller;
-
- // Start a search.
- yield new Promise(resolve => {
- controller.startSearch(searchStr);
- input.onSearchComplete = () => {
- // The first match should have autofilled, but the case of the search
- // string should be preserved.
- let expectedValue = searchStr + matches[0].substr(searchStr.length);
- Assert.equal(input.textValue, expectedValue,
- "Should have autofilled");
- Assert.equal(input.selectionStart, searchStr.length,
- "Selection should start after search string");
- Assert.equal(input.selectionEnd, expectedValue.length,
- "Selection should end at the end of the input");
- resolve();
- };
- });
-
- // Key down to select the second match in the popup.
- controller.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_DOWN);
- let expectedValue = matches[1];
- Assert.equal(input.textValue, expectedValue,
- "Should have filled second match");
- Assert.equal(input.selectionStart, expectedValue.length,
- "Selection should start at the end of the input");
- Assert.equal(input.selectionEnd, expectedValue.length,
- "Selection should end at the end of the input");
-
- // Key up to select the first match again. The input should be restored
- // exactly as it was when the first match was autofilled above: the search
- // string's case should be preserved, and the selection should be preserved.
- controller.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_UP);
- expectedValue = searchStr + matches[0].substr(searchStr.length);
- Assert.equal(input.textValue, expectedValue,
- "Should have filled first match again");
- Assert.equal(input.selectionStart, searchStr.length,
- "Selection should start after search string again");
- Assert.equal(input.selectionEnd, expectedValue.length,
- "Selection should end at the end of the input again");
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js b/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js
deleted file mode 100644
index 17f735388..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_badDefaultIndex.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * A results that wants to defaultComplete to 0, but it has no matches,
- * though it notifies SUCCESS to the controller.
- */
-function AutoCompleteNoMatchResult() {
- this.defaultIndex = 0;
-}
-AutoCompleteNoMatchResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-/**
- * A results that wants to defaultComplete to an index greater than the number
- * of matches.
- */
-function AutoCompleteBadIndexResult(aValues, aDefaultIndex) {
- do_check_true(aValues.length <= aDefaultIndex);
- this._values = aValues;
- this.defaultIndex = aDefaultIndex;
-}
-AutoCompleteBadIndexResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-add_test(function autocomplete_noMatch_success() {
- const INPUT_STR = "moz";
-
- let searchNoMatch =
- new AutoCompleteSearchBase("searchNoMatch",
- new AutoCompleteNoMatchResult());
- registerAutoCompleteSearch(searchNoMatch);
-
- // Make an AutoCompleteInput that uses our search and confirms results.
- let input = new AutoCompleteInputBase([searchNoMatch.name]);
- input.completeDefaultIndex = true;
- input.textValue = INPUT_STR;
-
- // Caret must be at the end for autoFill to happen.
- let strLen = INPUT_STR.length;
- input.selectTextRange(strLen, strLen);
- do_check_eq(input.selectionStart, strLen);
- do_check_eq(input.selectionEnd, strLen);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
- controller.input = input;
- controller.startSearch(INPUT_STR);
-
- input.onSearchComplete = function () {
- // Should not try to autoFill to an empty value.
- do_check_eq(input.textValue, "moz");
-
- // Clean up.
- unregisterAutoCompleteSearch(searchNoMatch);
- run_next_test();
- };
-});
-
-add_test(function autocomplete_defaultIndex_exceeds_matchCount() {
- const INPUT_STR = "moz";
-
- // Result returning matches, but a bad defaultIndex.
- let searchBadIndex =
- new AutoCompleteSearchBase("searchBadIndex",
- new AutoCompleteBadIndexResult(["mozillaTest"], 1));
- registerAutoCompleteSearch(searchBadIndex);
-
- // Make an AutoCompleteInput that uses our search and confirms results.
- let input = new AutoCompleteInputBase([searchBadIndex.name]);
- input.completeDefaultIndex = true;
- input.textValue = INPUT_STR;
-
- // Caret must be at the end for autoFill to happen.
- let strLen = INPUT_STR.length;
- input.selectTextRange(strLen, strLen);
- do_check_eq(input.selectionStart, strLen);
- do_check_eq(input.selectionEnd, strLen);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
- controller.input = input;
- controller.startSearch(INPUT_STR);
-
- input.onSearchComplete = function () {
- // Should not try to autoFill to an empty value.
- do_check_eq(input.textValue, "moz");
-
- // Clean up.
- unregisterAutoCompleteSearch(searchBadIndex);
- run_next_test();
- };
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js b/toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js
deleted file mode 100644
index c25b00907..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_completeDefaultIndex_casing.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function AutoCompleteResult(aValues) {
- this._values = aValues;
- this.defaultIndex = 0;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- this.popup.selectedIndex = -1;
- this.completeDefaultIndex = true;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_keyNavigation() {
- doSearch("MOZ", "mozilla", function(aController) {
- do_check_eq(aController.input.textValue, "MOZilla");
- aController.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_RIGHT);
- do_check_eq(aController.input.textValue, "mozilla");
- });
-});
-
-add_test(function test_handleEnter() {
- doSearch("MOZ", "mozilla", function(aController) {
- do_check_eq(aController.input.textValue, "MOZilla");
- aController.handleEnter(false);
- do_check_eq(aController.input.textValue, "mozilla");
- });
-});
-
-function doSearch(aSearchString, aResultValue, aOnCompleteCallback) {
- let search = new AutoCompleteSearchBase("search",
- new AutoCompleteResult([ "mozilla", "toolkit" ], 0));
- registerAutoCompleteSearch(search);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches and confirms results.
- let input = new AutoCompleteInput([ search.name ]);
- input.textValue = aSearchString;
-
- // Caret must be at the end for autofill to happen.
- let strLen = aSearchString.length;
- input.selectTextRange(strLen, strLen);
- controller.input = input;
- controller.startSearch(aSearchString);
-
- input.onSearchComplete = function onSearchComplete() {
- aOnCompleteCallback(controller);
-
- // Clean up.
- unregisterAutoCompleteSearch(search);
- run_next_test();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js
deleted file mode 100644
index fcac8ae43..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue.js
+++ /dev/null
@@ -1,48 +0,0 @@
-function AutoCompleteResult(aValues, aFinalCompleteValues) {
- this._values = aValues;
- this._finalCompleteValues = aFinalCompleteValues;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- this.popup.selectedIndex = 0;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-add_test(function test_handleEnter_mouse() {
- doSearch("moz", "mozilla.com", "http://www.mozilla.com", function(aController) {
- do_check_eq(aController.input.textValue, "moz");
- do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- // Keyboard interaction is tested by test_finalCompleteValueSelectedIndex.js
- // so here just test popup selection.
- aController.handleEnter(true);
- do_check_eq(aController.input.textValue, "http://www.mozilla.com");
- });
-});
-
-function doSearch(aSearchString, aResultValue, aFinalCompleteValue, aOnCompleteCallback) {
- let search = new AutoCompleteSearchBase(
- "search",
- new AutoCompleteResult([ aResultValue ], [ aFinalCompleteValue ])
- );
- registerAutoCompleteSearch(search);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches and confirms results.
- let input = new AutoCompleteInput([ search.name ]);
- input.textValue = aSearchString;
-
- controller.input = input;
- controller.startSearch(aSearchString);
-
- input.onSearchComplete = function onSearchComplete() {
- aOnCompleteCallback(controller);
-
- // Clean up.
- unregisterAutoCompleteSearch(search);
- run_next_test();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js
deleted file mode 100644
index 6556a26dc..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValueSelectedIndex.js
+++ /dev/null
@@ -1,119 +0,0 @@
-function AutoCompleteResult(aResultValues) {
- this._values = aResultValues.map(x => x[0]);
- this._finalCompleteValues = aResultValues.map(x => x[1]);
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-var selectByWasCalled = false;
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- this.popup.selectedIndex = 0;
- this.popup.selectBy = function(reverse, page) {
- Assert.equal(selectByWasCalled, false);
- selectByWasCalled = true;
- Assert.equal(reverse, false);
- Assert.equal(page, false);
- this.selectedIndex += (reverse ? -1 : 1) * (page ? 100 : 1);
- };
- this.completeSelectedIndex = true;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-add_test(function test_handleEnter_key() {
- let results = [
- ["mozilla.com", "http://www.mozilla.com"],
- ["mozilla.org", "http://www.mozilla.org"],
- ];
- // First check the case where we do select a value with the keyboard:
- doSearch("moz", results, function(aController) {
- Assert.equal(aController.input.textValue, "moz");
- Assert.equal(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- Assert.equal(aController.getFinalCompleteValueAt(1), "http://www.mozilla.org");
-
- Assert.equal(aController.input.popup.selectedIndex, 0);
- aController.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_DOWN);
- Assert.equal(aController.input.popup.selectedIndex, 1);
- // Simulate mouse interaction changing selectedIndex
- // ie NOT keyboard interaction:
- aController.input.popup.selectedIndex = 0;
-
- aController.handleEnter(false);
- // Verify that the keyboard-selected thing got inserted,
- // and not the mouse selection:
- Assert.equal(aController.input.textValue, "http://www.mozilla.org");
- });
-});
-
-add_test(function test_handleEnter_mouse() {
- let results = [
- ["mozilla.com", "http://www.mozilla.com"],
- ["mozilla.org", "http://www.mozilla.org"],
- ];
- // Then the case where we do not:
- doSearch("moz", results, function(aController) {
- Assert.equal(aController.input.textValue, "moz");
- Assert.equal(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- Assert.equal(aController.getFinalCompleteValueAt(1), "http://www.mozilla.org");
-
- Assert.equal(aController.input.popup.selectedIndex, 0);
- aController.input.popupOpen = true;
- // Simulate mouse interaction changing selectedIndex
- // ie NOT keyboard interaction:
- aController.input.popup.selectedIndex = 1;
- Assert.equal(selectByWasCalled, false);
- Assert.equal(aController.input.popup.selectedIndex, 1);
-
- aController.handleEnter(false);
- // Verify that the input stayed the same, because no selection was made
- // with the keyboard:
- Assert.equal(aController.input.textValue, "moz");
- });
-});
-
-add_test(function test_handleEnter_preselected() {
- let results = [
- ["mozilla.com", "http://www.mozilla.com"],
- ["mozilla.org", "http://www.mozilla.org"],
- ];
- // Then test a preselection.
- doSearch("moz", results, function(aController) {
- Assert.equal(aController.input.textValue, "moz");
- Assert.equal(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- Assert.equal(aController.getFinalCompleteValueAt(1), "http://www.mozilla.org");
-
- aController.setInitiallySelectedIndex(0);
-
- aController.handleEnter(false);
- // Verify that the input stayed the same, because no selection was made
- // with the keyboard:
- Assert.equal(aController.input.textValue, "http://www.mozilla.com");
- });
-});
-
-function doSearch(aSearchString, aResults, aOnCompleteCallback) {
- selectByWasCalled = false;
- let search = new AutoCompleteSearchBase(
- "search",
- new AutoCompleteResult(aResults)
- );
- registerAutoCompleteSearch(search);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches and confirms results.
- let input = new AutoCompleteInput([ search.name ]);
- input.textValue = aSearchString;
-
- controller.input = input;
- controller.startSearch(aSearchString);
-
- input.onSearchComplete = function onSearchComplete() {
- aOnCompleteCallback(controller);
-
- // Clean up.
- unregisterAutoCompleteSearch(search);
- run_next_test();
- };
-}
-
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js
deleted file mode 100644
index 4942e7a9f..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_defaultIndex.js
+++ /dev/null
@@ -1,107 +0,0 @@
-function AutoCompleteResult(aResultValues) {
- this.defaultIndex = 0;
- this._values = aResultValues.map(x => x[0]);
- this._finalCompleteValues = aResultValues.map(x => x[1]);
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- this.popup.selectedIndex = 0;
- this.completeSelectedIndex = true;
- this.completeDefaultIndex = true;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-add_test(function test_handleEnter() {
- let results = [
- ["mozilla.com", "https://www.mozilla.com"],
- ["gomozilla.org", "http://www.gomozilla.org"],
- ];
- doSearch("moz", results, { selectedIndex: 0 }, controller => {
- let input = controller.input;
- Assert.equal(input.textValue, "mozilla.com");
- Assert.equal(controller.getFinalCompleteValueAt(0), results[0][1]);
- Assert.equal(controller.getFinalCompleteValueAt(1), results[1][1]);
- Assert.equal(input.popup.selectedIndex, 0);
-
- controller.handleEnter(false);
- // Verify that the keyboard-selected thing got inserted,
- // and not the mouse selection:
- Assert.equal(controller.input.textValue, "https://www.mozilla.com");
- });
-});
-
-add_test(function test_handleEnter_otherSelected() {
- // The popup selection may not coincide with what is filled into the input
- // field, for example if the user changed it with the mouse and then pressed
- // Enter. In such a case we should still use the inputField value and not the
- // popup selected value.
- let results = [
- ["mozilla.com", "https://www.mozilla.com"],
- ["gomozilla.org", "http://www.gomozilla.org"],
- ];
- doSearch("moz", results, { selectedIndex: 1 }, controller => {
- let input = controller.input;
- Assert.equal(input.textValue, "mozilla.com");
- Assert.equal(controller.getFinalCompleteValueAt(0), results[0][1]);
- Assert.equal(controller.getFinalCompleteValueAt(1), results[1][1]);
- Assert.equal(input.popup.selectedIndex, 1);
-
- controller.handleEnter(false);
- // Verify that the keyboard-selected thing got inserted,
- // and not the mouse selection:
- Assert.equal(controller.input.textValue, "https://www.mozilla.com");
- });
-});
-
-add_test(function test_handleEnter_otherSelected_nocompleteselectedindex() {
- let results = [
- ["mozilla.com", "https://www.mozilla.com"],
- ["gomozilla.org", "http://www.gomozilla.org"],
- ];
- doSearch("moz", results, { selectedIndex: 1,
- completeSelectedIndex: false }, controller => {
- let input = controller.input;
- Assert.equal(input.textValue, "mozilla.com");
- Assert.equal(controller.getFinalCompleteValueAt(0), results[0][1]);
- Assert.equal(controller.getFinalCompleteValueAt(1), results[1][1]);
- Assert.equal(input.popup.selectedIndex, 1);
-
- controller.handleEnter(false);
- // Verify that the keyboard-selected result is inserted, not the
- // defaultComplete.
- Assert.equal(controller.input.textValue, "http://www.gomozilla.org");
- });
-});
-
-function doSearch(aSearchString, aResults, aOptions, aOnCompleteCallback) {
- let search = new AutoCompleteSearchBase(
- "search",
- new AutoCompleteResult(aResults)
- );
- registerAutoCompleteSearch(search);
-
- let input = new AutoCompleteInput([ search.name ]);
- input.textValue = aSearchString;
- if ("selectedIndex" in aOptions) {
- input.popup.selectedIndex = aOptions.selectedIndex;
- }
- if ("completeSelectedIndex" in aOptions) {
- input.completeSelectedIndex = aOptions.completeSelectedIndex;
- }
- // Needed for defaultIndex completion.
- input.selectTextRange(aSearchString.length, aSearchString.length);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
- controller.input = input;
- controller.startSearch(aSearchString);
-
- input.onSearchComplete = function onSearchComplete() {
- aOnCompleteCallback(controller);
-
- unregisterAutoCompleteSearch(search);
- run_next_test();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js b/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js
deleted file mode 100644
index 5642d3e3e..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_finalCompleteValue_forceComplete.js
+++ /dev/null
@@ -1,104 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function AutoCompleteResult(aValues, aFinalCompleteValues) {
- this._values = aValues;
- this._finalCompleteValues = aFinalCompleteValues;
- this.defaultIndex = 0;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- this.popup.selectedIndex = -1;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_handleEnterWithDirectMatchCompleteSelectedIndex() {
- doSearch("moz", "mozilla.com", "http://www.mozilla.com",
- { forceComplete: true, completeSelectedIndex: true }, function(aController) {
- do_check_eq(aController.input.textValue, "moz");
- do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- aController.handleEnter(false);
- // After enter the final complete value should be shown in the input.
- do_check_eq(aController.input.textValue, "http://www.mozilla.com");
- });
-});
-
-add_test(function test_handleEnterWithDirectMatch() {
- doSearch("mozilla", "mozilla.com", "http://www.mozilla.com",
- { forceComplete: true, completeDefaultIndex: true }, function(aController) {
- // Should autocomplete the search string to a suggestion.
- do_check_eq(aController.input.textValue, "mozilla.com");
- do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- aController.handleEnter(false);
- // After enter the final complete value should be shown in the input.
- do_check_eq(aController.input.textValue, "http://www.mozilla.com");
- });
-});
-
-add_test(function test_handleEnterWithNoMatch() {
- doSearch("mozilla", "mozilla.com", "http://www.mozilla.com",
- { forceComplete: true, completeDefaultIndex: true }, function(aController) {
- // Should autocomplete the search string to a suggestion.
- do_check_eq(aController.input.textValue, "mozilla.com");
- do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- // Now input something that does not match...
- aController.input.textValue = "mozillax";
- // ... and confirm. We don't want one of the values from the previous
- // results to be taken, since what's now in the input field doesn't match.
- aController.handleEnter(false);
- do_check_eq(aController.input.textValue, "mozillax");
- });
-});
-
-add_test(function test_handleEnterWithIndirectMatch() {
- doSearch("com", "mozilla.com", "http://www.mozilla.com",
- { forceComplete: true, completeDefaultIndex: true }, function(aController) {
- // Should autocomplete the search string to a suggestion.
- do_check_eq(aController.input.textValue, "com >> mozilla.com");
- do_check_eq(aController.getFinalCompleteValueAt(0), "http://www.mozilla.com");
- aController.handleEnter(false);
- // After enter the final complete value from the suggestion should be shown
- // in the input.
- do_check_eq(aController.input.textValue, "http://www.mozilla.com");
- });
-});
-
-function doSearch(aSearchString, aResultValue, aFinalCompleteValue,
- aInputProps, aOnCompleteCallback) {
- let search = new AutoCompleteSearchBase(
- "search",
- new AutoCompleteResult([ aResultValue ], [ aFinalCompleteValue ])
- );
- registerAutoCompleteSearch(search);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches and confirms results.
- let input = new AutoCompleteInput([ search.name ]);
- for (var p in aInputProps) {
- input[p] = aInputProps[p];
- }
- input.textValue = aSearchString;
- // Place the cursor at the end of the input so that completion to
- // default index will kick in.
- input.selectTextRange(aSearchString.length, aSearchString.length);
-
- controller.input = input;
- controller.startSearch(aSearchString);
-
- input.onSearchComplete = function onSearchComplete() {
- aOnCompleteCallback(controller);
-
- // Clean up.
- unregisterAutoCompleteSearch(search);
- run_next_test();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js b/toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js
deleted file mode 100644
index c983d969b..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_finalDefaultCompleteValue.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function AutoCompleteResult(aValues, aFinalCompleteValues) {
- this._values = aValues;
- this._finalCompleteValues = aFinalCompleteValues;
- this.defaultIndex = 0;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- this.popup.selectedIndex = -1;
- this.completeDefaultIndex = true;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_keyNavigation() {
- doSearch("moz", "mozilla.com", "http://www.mozilla.com", function(aController) {
- do_check_eq(aController.input.textValue, "mozilla.com");
- aController.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_RIGHT);
- do_check_eq(aController.input.textValue, "mozilla.com");
- });
-});
-
-add_test(function test_handleEnter() {
- doSearch("moz", "mozilla.com", "http://www.mozilla.com", function(aController) {
- do_check_eq(aController.input.textValue, "mozilla.com");
- aController.handleEnter(false);
- do_check_eq(aController.input.textValue, "http://www.mozilla.com");
- });
-});
-
-function doSearch(aSearchString, aResultValue, aFinalCompleteValue, aOnCompleteCallback) {
- let search = new AutoCompleteSearchBase(
- "search",
- new AutoCompleteResult([ aResultValue ], [ aFinalCompleteValue ])
- );
- registerAutoCompleteSearch(search);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches and confirms results.
- let input = new AutoCompleteInput([ search.name ]);
- input.textValue = aSearchString;
-
- // Caret must be at the end for autofill to happen.
- let strLen = aSearchString.length;
- input.selectTextRange(strLen, strLen);
- controller.input = input;
- controller.startSearch(aSearchString);
-
- input.onSearchComplete = function onSearchComplete() {
- aOnCompleteCallback(controller);
-
- // Clean up.
- unregisterAutoCompleteSearch(search);
- run_next_test();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_hiddenResult.js b/toolkit/components/autocomplete/tests/unit/test_hiddenResult.js
deleted file mode 100644
index 8e2485716..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_hiddenResult.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function AutoCompleteResult(aValues) {
- this._values = aValues;
- this.defaultIndex = -1;
- this._typeAheadResult = false;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteTypeAheadResult(aValues) {
- this._values = aValues;
- this.defaultIndex = 0;
- this._typeAheadResult = true;
-}
-AutoCompleteTypeAheadResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-
-/**
- * Test AutoComplete with multiple AutoCompleteSearch sources, with one of them
- * being hidden from the popup, but can still do typeahead completion.
- */
-function run_test() {
- do_test_pending();
-
- var inputStr = "moz";
-
- // Type ahead result
- var searchTypeAhead = new AutoCompleteSearchBase("search1",
- new AutoCompleteTypeAheadResult(["mozillaTest1"]));
- // Regular result
- var searchNormal = new AutoCompleteSearchBase("search2",
- new AutoCompleteResult(["mozillaTest2"]));
-
- // Register searches so AutoCompleteController can find them
- registerAutoCompleteSearch(searchNormal);
- registerAutoCompleteSearch(searchTypeAhead);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete.
- var input = new AutoCompleteInputBase([searchTypeAhead.name, searchNormal.name]);
- input.completeDefaultIndex = true;
- input.textValue = inputStr;
-
- // Caret must be at the end. Autofill doesn't happen unless you're typing
- // characters at the end.
- var strLen = inputStr.length;
- input.selectTextRange(strLen, strLen);
- do_check_eq(input.selectionStart, strLen);
- do_check_eq(input.selectionEnd, strLen);
-
- var controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- controller.input = input;
- controller.startSearch(inputStr);
-
- input.onSearchComplete = function() {
- // Hidden results should still be able to do inline autocomplete
- do_check_eq(input.textValue, "mozillaTest1");
-
- // Now, let's fill the textbox with the first result of the popup.
- // The first search is marked as hidden, so we must always get the
- // second search.
- controller.handleEnter(true);
- do_check_eq(input.textValue, "mozillaTest2");
-
- // Only one item in the popup.
- do_check_eq(controller.matchCount, 1);
-
- // Unregister searches
- unregisterAutoCompleteSearch(searchNormal);
- unregisterAutoCompleteSearch(searchTypeAhead);
- do_test_finished();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_immediate_search.js b/toolkit/components/autocomplete/tests/unit/test_immediate_search.js
deleted file mode 100644
index 0579f5dcb..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_immediate_search.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-
-function AutoCompleteImmediateSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteImmediateSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
-AutoCompleteImmediateSearch.prototype.searchType =
- Ci.nsIAutoCompleteSearchDescriptor.SEARCH_TYPE_IMMEDIATE;
-AutoCompleteImmediateSearch.prototype.QueryInterface =
- XPCOMUtils.generateQI([Ci.nsIFactory,
- Ci.nsIAutoCompleteSearch,
- Ci.nsIAutoCompleteSearchDescriptor]);
-
-function AutoCompleteDelayedSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteDelayedSearch.prototype = Object.create(AutoCompleteSearchBase.prototype);
-
-function AutoCompleteResult(aValues, aDefaultIndex) {
- this._values = aValues;
- this.defaultIndex = aDefaultIndex;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * An immediate search should be executed synchronously.
- */
-add_test(function test_immediate_search() {
- let inputStr = "moz";
-
- let immediateSearch = new AutoCompleteImmediateSearch(
- "immediate", new AutoCompleteResult(["moz-immediate"], 0));
- registerAutoCompleteSearch(immediateSearch);
- let delayedSearch = new AutoCompleteDelayedSearch(
- "delayed", new AutoCompleteResult(["moz-delayed"], 0));
- registerAutoCompleteSearch(delayedSearch);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- let input = new AutoCompleteInputBase([delayedSearch.name,
- immediateSearch.name]);
- input.completeDefaultIndex = true;
- input.textValue = inputStr;
-
- // Caret must be at the end. Autofill doesn't happen unless you're typing
- // characters at the end.
- let strLen = inputStr.length;
- input.selectTextRange(strLen, strLen);
-
- controller.input = input;
- controller.startSearch(inputStr);
-
- // Immediately check the result, the immediate search should have finished.
- do_check_eq(input.textValue, "moz-immediate");
-
- // Wait for both queries to finish.
- input.onSearchComplete = function() {
- // Sanity check.
- do_check_eq(input.textValue, "moz-immediate");
-
- unregisterAutoCompleteSearch(immediateSearch);
- unregisterAutoCompleteSearch(delayedSearch);
- run_next_test();
- };
-});
-
-/**
- * An immediate search should be executed before any delayed search.
- */
-add_test(function test_immediate_search_notimeout() {
- let inputStr = "moz";
-
- let immediateSearch = new AutoCompleteImmediateSearch(
- "immediate", new AutoCompleteResult(["moz-immediate"], 0));
- registerAutoCompleteSearch(immediateSearch);
-
- let delayedSearch = new AutoCompleteDelayedSearch(
- "delayed", new AutoCompleteResult(["moz-delayed"], 0));
- registerAutoCompleteSearch(delayedSearch);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- let input = new AutoCompleteInputBase([delayedSearch.name,
- immediateSearch.name]);
- input.completeDefaultIndex = true;
- input.textValue = inputStr;
- input.timeout = 0;
-
- // Caret must be at the end. Autofill doesn't happen unless you're typing
- // characters at the end.
- let strLen = inputStr.length;
- input.selectTextRange(strLen, strLen);
-
- controller.input = input;
- let complete = false;
- input.onSearchComplete = function() {
- complete = true;
- };
- controller.startSearch(inputStr);
- do_check_true(complete);
-
- // Immediately check the result, the immediate search should have finished.
- do_check_eq(input.textValue, "moz-immediate");
-
- unregisterAutoCompleteSearch(immediateSearch);
- unregisterAutoCompleteSearch(delayedSearch);
- run_next_test();
-});
-
-/**
- * A delayed search should be executed synchronously with a zero timeout.
- */
-add_test(function test_delayed_search_notimeout() {
- let inputStr = "moz";
-
- let delayedSearch = new AutoCompleteDelayedSearch(
- "delayed", new AutoCompleteResult(["moz-delayed"], 0));
- registerAutoCompleteSearch(delayedSearch);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- let input = new AutoCompleteInputBase([delayedSearch.name]);
- input.completeDefaultIndex = true;
- input.textValue = inputStr;
- input.timeout = 0;
-
- // Caret must be at the end. Autofill doesn't happen unless you're typing
- // characters at the end.
- let strLen = inputStr.length;
- input.selectTextRange(strLen, strLen);
-
- controller.input = input;
- let complete = false;
- input.onSearchComplete = function() {
- complete = true;
- };
- controller.startSearch(inputStr);
- do_check_true(complete);
-
- // Immediately check the result, the delayed search should have finished.
- do_check_eq(input.textValue, "moz-delayed");
-
- unregisterAutoCompleteSearch(delayedSearch);
- run_next_test();
-});
diff --git a/toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js b/toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js
deleted file mode 100644
index 14ee388b8..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_insertMatchAt.js
+++ /dev/null
@@ -1,14 +0,0 @@
-function run_test() {
- let result = Cc["@mozilla.org/autocomplete/simple-result;1"]
- .createInstance(Ci.nsIAutoCompleteSimpleResult);
- result.appendMatch("a", "");
- result.appendMatch("c", "");
- result.insertMatchAt(1, "b", "");
- result.insertMatchAt(3, "d", "");
-
- Assert.equal(result.matchCount, 4);
- Assert.equal(result.getValueAt(0), "a");
- Assert.equal(result.getValueAt(1), "b");
- Assert.equal(result.getValueAt(2), "c");
- Assert.equal(result.getValueAt(3), "d");
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_popupSelectionVsDefaultCompleteValue.js b/toolkit/components/autocomplete/tests/unit/test_popupSelectionVsDefaultCompleteValue.js
deleted file mode 100644
index fb4153355..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_popupSelectionVsDefaultCompleteValue.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/. */
-
-function AutoCompleteTypeAheadResult(aValues, aFinalCompleteValues) {
- this._values = aValues;
- this._finalCompleteValues = aFinalCompleteValues;
- this.defaultIndex = 0;
- this._typeAheadResult = true;
-}
-AutoCompleteTypeAheadResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteResult(aValues) {
- this._values = aValues;
-}
-AutoCompleteResult.prototype = Object.create(AutoCompleteResultBase.prototype);
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- this.popupOpen = true;
- this.completeDefaultIndex = true;
- this.completeSelectedIndex = true;
-}
-AutoCompleteInput.prototype = Object.create(AutoCompleteInputBase.prototype);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_handleEnter() {
- doSearch("moz", function(aController) {
- do_check_eq(aController.input.textValue, "mozilla.com");
- aController.handleEnter(true);
- do_check_eq(aController.input.textValue, "mozilla.org");
- });
-});
-
-function doSearch(aSearchString, aOnCompleteCallback) {
- let typeAheadSearch = new AutoCompleteSearchBase(
- "typeAheadSearch",
- new AutoCompleteTypeAheadResult([ "mozilla.com" ], [ "http://www.mozilla.com" ])
- );
- registerAutoCompleteSearch(typeAheadSearch);
-
- let search = new AutoCompleteSearchBase(
- "search",
- new AutoCompleteResult([ "mozilla.org" ])
- );
- registerAutoCompleteSearch(search);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches and confirms results.
- let input = new AutoCompleteInput([ typeAheadSearch.name, search.name ]);
- input.textValue = aSearchString;
-
- // Caret must be at the end for autofill to happen.
- let strLen = aSearchString.length;
- input.selectTextRange(strLen, strLen);
- controller.input = input;
- controller.startSearch(aSearchString);
-
- input.onSearchComplete = function onSearchComplete() {
- aOnCompleteCallback(controller);
-
- // Clean up.
- unregisterAutoCompleteSearch(search);
- run_next_test();
- };
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_previousResult.js b/toolkit/components/autocomplete/tests/unit/test_previousResult.js
deleted file mode 100644
index bfe6c7aae..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_previousResult.js
+++ /dev/null
@@ -1,280 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Unit test for Bug 438861 - Previous search results not returned to multiple
- * searches.
- */
-
-
-/**
- * Dummy nsIAutoCompleteInput source that returns
- * the given list of AutoCompleteSearch names.
- *
- * Implements only the methods needed for this test.
- */
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- // Array of AutoCompleteSearch names
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-
-/**
- * nsIAutoCompleteResult implementation
- */
-function AutoCompleteResult(aValues, aComments, aStyles) {
- this._values = aValues;
- this._comments = aComments;
- this._styles = aStyles;
- if (this._values.length > 0) {
- this.searchResult = Ci.nsIAutoCompleteResult.RESULT_SUCCESS;
- } else {
- this.searchResult = Ci.nsIAutoCompleteResult.NOMATCH;
- }
-}
-AutoCompleteResult.prototype = {
- constructor: AutoCompleteResult,
-
- // Arrays
- _values: null,
- _comments: null,
- _styles: null,
-
- searchString: "",
- searchResult: null,
-
- defaultIndex: 0,
-
- get matchCount() {
- return this._values.length;
- },
-
- getValueAt: function(aIndex) {
- return this._values[aIndex];
- },
-
- getLabelAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- getCommentAt: function(aIndex) {
- return this._comments[aIndex];
- },
-
- getStyleAt: function(aIndex) {
- return this._styles[aIndex];
- },
-
- getImageAt: function(aIndex) {
- return "";
- },
-
- getFinalCompleteValueAt: function(aIndex) {
- return this.getValueAt(aIndex);
- },
-
- removeValueAt: function (aRowIndex, aRemoveFromDb) {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteResult))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-/**
- * nsIAutoCompleteSearch implementation that always returns
- * the same result set.
- */
-function AutoCompleteSearch(aName, aResult) {
- this.name = aName;
- this._result = aResult;
-}
-AutoCompleteSearch.prototype = {
- constructor: AutoCompleteSearch,
-
- // Search name. Used by AutoCompleteController
- name: null,
-
- // AutoCompleteResult
- _result: null,
-
- _previousResult: null,
-
-
- /**
- * Return the same result set for every search
- */
- startSearch: function(aSearchString,
- aSearchParam,
- aPreviousResult,
- aListener)
- {
- this._previousResult = aPreviousResult;
- aListener.onSearchResult(this, this._result);
- },
-
- stopSearch: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIFactory) ||
- iid.equals(Ci.nsIAutoCompleteSearch))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- },
-
- // nsIFactory implementation
- createInstance: function(outer, iid) {
- return this.QueryInterface(iid);
- }
-}
-
-
-/**
- * Helper to register an AutoCompleteSearch with the given name.
- * Allows the AutoCompleteController to find the search.
- */
-function registerAutoCompleteSearch(aSearch) {
- var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
-
- var uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator);
- var cid = uuidGenerator.generateUUID();
-
- var desc = "Test AutoCompleteSearch";
-
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.registerFactory(cid, desc, name, aSearch);
-
- // Keep the id on the object so we can unregister later
- aSearch.cid = cid;
-}
-
-
-/**
- * Helper to unregister an AutoCompleteSearch.
- */
-function unregisterAutoCompleteSearch(aSearch) {
- var componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.unregisterFactory(aSearch.cid, aSearch);
-}
-
-
-/**
- */
-function run_test() {
- // Make an AutoCompleteSearch that always returns nothing
- var search1 = new AutoCompleteSearch("test-previous-result1",
- new AutoCompleteResult(["hello1"], [""], [""]));
-
- var search2 = new AutoCompleteSearch("test-previous-result2",
- new AutoCompleteResult(["hello2"], [""], [""]));
-
- // Register search so AutoCompleteController can find them
- registerAutoCompleteSearch(search1);
- registerAutoCompleteSearch(search2);
-
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our search
- // and confirms results on search complete
- var input = new AutoCompleteInput([search1.name,
- search2.name]);
- var numSearchesStarted = 0;
-
- input.onSearchBegin = function() {
- numSearchesStarted++;
- };
-
- input.onSearchComplete = function() {
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- do_check_eq(controller.matchCount, 2);
-
- if (numSearchesStarted == 1) {
- do_check_eq(search1._previousResult, null);
- do_check_eq(search2._previousResult, null);
-
- // Now start it again
- controller.startSearch("test");
- return;
- }
- do_check_neq(search1._previousResult, null);
- do_check_neq(search2._previousResult, null);
-
- // Unregister searches
- unregisterAutoCompleteSearch(search1);
- unregisterAutoCompleteSearch(search2);
-
- do_test_finished();
- };
-
- controller.input = input;
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- controller.startSearch("test");
-}
diff --git a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js b/toolkit/components/autocomplete/tests/unit/test_stopSearch.js
deleted file mode 100644
index 5ef3454b4..000000000
--- a/toolkit/components/autocomplete/tests/unit/test_stopSearch.js
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-/**
- * Purpose of the test is to check that a stopSearch call comes always before a
- * startSearch call.
- */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-
-/**
- * Dummy nsIAutoCompleteInput source that returns
- * the given list of AutoCompleteSearch names.
- *
- * Implements only the methods needed for this test.
- */
-function AutoCompleteInput(aSearches)
-{
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "hello",
- disableAutoComplete: false,
- completeDefaultIndex: false,
- set popupOpen(val) { return val; }, // ignore
- get popupOpen() { return false; },
- get searchCount() { return this.searches.length; },
- getSearchAt: function(aIndex) { return this.searches[aIndex]; },
- onSearchBegin: function() {},
- onSearchComplete: function() {},
- onTextReverted: function () {},
- onTextEntered: function () {},
- popup: {
- selectBy: function() {},
- invalidate: function() {},
- set selectedIndex(val) { return val; }, // ignore
- get selectedIndex() { return -1 },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup])
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
-}
-
-
-/**
- * nsIAutoCompleteSearch implementation.
- */
-function AutoCompleteSearch(aName)
-{
- this.name = aName;
-}
-AutoCompleteSearch.prototype = {
- constructor: AutoCompleteSearch,
- stopSearchInvoked: true,
- startSearch: function(aSearchString, aSearchParam, aPreviousResult, aListener)
- {
- print("Check stop search has been called");
- do_check_true(this.stopSearchInvoked);
- this.stopSearchInvoked = false;
- },
- stopSearch: function()
- {
- this.stopSearchInvoked = true;
- },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIFactory
- , Ci.nsIAutoCompleteSearch
- ]),
- createInstance: function(outer, iid)
- {
- return this.QueryInterface(iid);
- }
-}
-
-
-/**
- * Helper to register an AutoCompleteSearch with the given name.
- * Allows the AutoCompleteController to find the search.
- */
-function registerAutoCompleteSearch(aSearch)
-{
- let name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;
- let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].
- getService(Ci.nsIUUIDGenerator);
- let cid = uuidGenerator.generateUUID();
- let desc = "Test AutoCompleteSearch";
- let componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.registerFactory(cid, desc, name, aSearch);
- // Keep the id on the object so we can unregister later
- aSearch.cid = cid;
-}
-
-
-/**
- * Helper to unregister an AutoCompleteSearch.
- */
-function unregisterAutoCompleteSearch(aSearch) {
- let componentManager = Components.manager
- .QueryInterface(Ci.nsIComponentRegistrar);
- componentManager.unregisterFactory(aSearch.cid, aSearch);
-}
-
-
-var gTests = [
- function(controller) {
- print("handleText");
- controller.input.textValue = "hel";
- controller.handleText();
- },
- function(controller) {
- print("handleStartComposition");
- controller.handleStartComposition();
- },
- function(controller) {
- print("handleEndComposition");
- controller.handleEndComposition();
- // an input event always follows compositionend event.
- controller.handleText();
- },
- function(controller) {
- print("handleEscape");
- controller.handleEscape();
- },
- function(controller) {
- print("handleEnter");
- controller.handleEnter(false);
- },
- function(controller) {
- print("handleTab");
- controller.handleTab();
- },
-
- function(controller) {
- print("handleKeyNavigation");
- controller.handleKeyNavigation(Ci.nsIDOMKeyEvent.DOM_VK_UP);
- },
-];
-
-
-var gSearch;
-var gCurrentTest;
-function run_test() {
- // Make an AutoCompleteSearch that always returns nothing
- gSearch = new AutoCompleteSearch("test");
- registerAutoCompleteSearch(gSearch);
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our search.
- let input = new AutoCompleteInput([gSearch.name]);
- controller.input = input;
-
- input.onSearchBegin = function() {
- do_execute_soon(function() {
- gCurrentTest(controller);
- });
- };
- input.onSearchComplete = function() {
- run_next_test(controller);
- }
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- run_next_test(controller);
-}
-
-function run_next_test(controller) {
- if (gTests.length == 0) {
- unregisterAutoCompleteSearch(gSearch);
- controller.stopSearch();
- controller.input = null;
- do_test_finished();
- return;
- }
-
- gCurrentTest = gTests.shift();
- controller.startSearch("hello");
-}
diff --git a/toolkit/components/autocomplete/tests/unit/xpcshell.ini b/toolkit/components/autocomplete/tests/unit/xpcshell.ini
deleted file mode 100644
index daf89db17..000000000
--- a/toolkit/components/autocomplete/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,26 +0,0 @@
-[DEFAULT]
-head = head_autocomplete.js
-tail =
-
-[test_330578.js]
-[test_378079.js]
-[test_393191.js]
-[test_440866.js]
-[test_463023.js]
-[test_660156.js]
-[test_autocomplete_multiple.js]
-[test_autocomplete_userContextId.js]
-[test_autofillSelectedPopupIndex.js]
-[test_badDefaultIndex.js]
-[test_completeDefaultIndex_casing.js]
-[test_finalCompleteValue.js]
-[test_finalCompleteValue_defaultIndex.js]
-[test_finalCompleteValue_forceComplete.js]
-[test_finalCompleteValueSelectedIndex.js]
-[test_finalDefaultCompleteValue.js]
-[test_hiddenResult.js]
-[test_immediate_search.js]
-[test_insertMatchAt.js]
-[test_popupSelectionVsDefaultCompleteValue.js]
-[test_previousResult.js]
-[test_stopSearch.js]
diff --git a/toolkit/components/captivedetect/moz.build b/toolkit/components/captivedetect/moz.build
index 3bb9cf573..ee6a49aa5 100644
--- a/toolkit/components/captivedetect/moz.build
+++ b/toolkit/components/captivedetect/moz.build
@@ -4,12 +4,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-
-XPIDL_SOURCES += [
- 'nsICaptivePortalDetector.idl',
-]
-
+XPIDL_SOURCES += ['nsICaptivePortalDetector.idl']
XPIDL_MODULE = 'captivedetect'
EXTRA_COMPONENTS += [
diff --git a/toolkit/components/captivedetect/test/unit/.eslintrc.js b/toolkit/components/captivedetect/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/captivedetect/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/captivedetect/test/unit/head_setprefs.js b/toolkit/components/captivedetect/test/unit/head_setprefs.js
deleted file mode 100644
index bf621e31e..000000000
--- a/toolkit/components/captivedetect/test/unit/head_setprefs.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-Cu.import('resource://gre/modules/Services.jsm');
-Cu.import('resource://testing-common/httpd.js');
-
-XPCOMUtils.defineLazyServiceGetter(this, 'gCaptivePortalDetector',
- '@mozilla.org/toolkit/captive-detector;1',
- 'nsICaptivePortalDetector');
-
-const kCanonicalSitePath = '/canonicalSite.html';
-const kCanonicalSiteContent = 'true';
-const kPrefsCanonicalURL = 'captivedetect.canonicalURL';
-const kPrefsCanonicalContent = 'captivedetect.canonicalContent';
-const kPrefsMaxWaitingTime = 'captivedetect.maxWaitingTime';
-const kPrefsPollingTime = 'captivedetect.pollingTime';
-
-var gServer;
-var gServerURL;
-
-function setupPrefs() {
- let prefs = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefService)
- .QueryInterface(Components.interfaces.nsIPrefBranch);
- prefs.setCharPref(kPrefsCanonicalURL, gServerURL + kCanonicalSitePath);
- prefs.setCharPref(kPrefsCanonicalContent, kCanonicalSiteContent);
- prefs.setIntPref(kPrefsMaxWaitingTime, 0);
- prefs.setIntPref(kPrefsPollingTime, 1);
-}
-
-function run_captivedetect_test(xhr_handler, fakeUIResponse, testfun)
-{
- gServer = new HttpServer();
- gServer.registerPathHandler(kCanonicalSitePath, xhr_handler);
- gServer.start(-1);
- gServerURL = 'http://localhost:' + gServer.identity.primaryPort;
-
- setupPrefs();
-
- fakeUIResponse();
-
- testfun();
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_abort.js b/toolkit/components/captivedetect/test/unit/test_abort.js
deleted file mode 100644
index f99805dfb..000000000
--- a/toolkit/components/captivedetect/test/unit/test_abort.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-
-var server;
-var step = 0;
-var loginFinished = false;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- if (loginFinished) {
- response.write('true');
- } else {
- response.write('false');
- }
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- do_throw('should not receive captive-portal-login event');
- }
- }, 'captive-portal-login', false);
-}
-
-function test_abort() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_throw('should not execute |complete| callback');
- },
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
- gCaptivePortalDetector.abort(kInterfaceName);
- gServer.stop(do_test_finished);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_abort);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_abort_during_user_login.js b/toolkit/components/captivedetect/test/unit/test_abort_during_user_login.js
deleted file mode 100644
index ef98ac5ea..000000000
--- a/toolkit/components/captivedetect/test/unit/test_abort_during_user_login.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-
-var server;
-var step = 0;
-var loginFinished = false;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- if (loginFinished) {
- response.write('true');
- } else {
- response.write('false');
- }
-}
-
-function fakeUIResponse() {
- let requestId;
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
- .createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
- xhr.send();
- loginFinished = true;
- do_check_eq(++step, 2);
- requestId = JSON.parse(data).id;
- gCaptivePortalDetector.abort(kInterfaceName);
- }
- }, 'captive-portal-login', false);
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-abort') {
- do_check_eq(++step, 3);
- do_check_eq(JSON.parse(data).id, requestId);
- gServer.stop(do_test_finished);
- }
- }, 'captive-portal-login-abort', false);
-}
-
-function test_abort() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_throw('should not execute |complete| callback');
- },
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_abort);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_abort_ongoing_request.js b/toolkit/components/captivedetect/test/unit/test_abort_ongoing_request.js
deleted file mode 100644
index ad99903df..000000000
--- a/toolkit/components/captivedetect/test/unit/test_abort_ongoing_request.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-const kOtherInterfaceName = 'ril';
-
-var server;
-var step = 0;
-var loginFinished = false;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- if (loginFinished) {
- response.write('true');
- } else {
- response.write('false');
- }
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
- .createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
- xhr.send();
- loginFinished = true;
- do_check_eq(++step, 3);
- }
- }, 'captive-portal-login', false);
-}
-
-function test_multiple_requests_abort() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_throw('should not execute |complete| callback for ' + kInterfaceName);
- },
- };
-
- let otherCallback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 2);
- gCaptivePortalDetector.finishPreparation(kOtherInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 4);
- do_check_true(success);
- gServer.stop(do_test_finished);
- }
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
- gCaptivePortalDetector.checkCaptivePortal(kOtherInterfaceName, otherCallback);
- gCaptivePortalDetector.abort(kInterfaceName);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_multiple_requests_abort);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_abort_pending_request.js b/toolkit/components/captivedetect/test/unit/test_abort_pending_request.js
deleted file mode 100644
index ce36f1e79..000000000
--- a/toolkit/components/captivedetect/test/unit/test_abort_pending_request.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-const kOtherInterfaceName = 'ril';
-
-var server;
-var step = 0;
-var loginFinished = false;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- if (loginFinished) {
- response.write('true');
- } else {
- response.write('false');
- }
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
- .createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
- xhr.send();
- loginFinished = true;
- do_check_eq(++step, 2);
- }
- }, 'captive-portal-login', false);
-}
-
-function test_abort() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 3);
- do_check_true(success);
- gServer.stop(do_test_finished);
- },
- };
-
- let otherCallback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_throw('should not execute |prepare| callback for ' + kOtherInterfaceName);
- },
- complete: function complete(success) {
- do_throw('should not execute |complete| callback for ' + kInterfaceName);
- }
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
- gCaptivePortalDetector.checkCaptivePortal(kOtherInterfaceName, otherCallback);
- gCaptivePortalDetector.abort(kOtherInterfaceName);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_abort);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_captive_portal_found.js b/toolkit/components/captivedetect/test/unit/test_captive_portal_found.js
deleted file mode 100644
index 7fb7ba89e..000000000
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_found.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-
-var server;
-var step = 0;
-var loginFinished = false;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- if (loginFinished) {
- response.write('true');
- } else {
- response.write('false');
- }
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
- .createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
- xhr.send();
- loginFinished = true;
- do_check_eq(++step, 2);
- }
- }, 'captive-portal-login', false);
-
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-success') {
- do_check_eq(++step, 4);
- gServer.stop(do_test_finished);
- }
- }, 'captive-portal-login-success', false);
-}
-
-function test_portal_found() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- // Since this is a synchronous callback, it must happen before
- // 'captive-portal-login-success' is received.
- // (Check captivedetect.js::executeCallback
- do_check_eq(++step, 3);
- do_check_true(success);
- },
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_portal_found);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js b/toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js
deleted file mode 100644
index 7064e12c9..000000000
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-
-var step = 0;
-var loginFinished = false;
-
-var gRedirectServer;
-var gRedirectServerURL;
-
-function xhr_handler(metadata, response) {
- if (loginFinished) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- response.write('true');
- } else {
- response.setStatusLine(metadata.httpVersion, 303, "See Other");
- response.setHeader("Location", gRedirectServerURL, false);
- response.setHeader("Content-Type", "text/html", false);
- }
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
- .createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
- xhr.send();
- loginFinished = true;
- do_check_eq(++step, 2);
- }
- }, 'captive-portal-login', false);
-
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-success') {
- do_check_eq(++step, 4);
- gServer.stop(function () {
- gRedirectServer.stop(do_test_finished);
- });
- }
- }, 'captive-portal-login-success', false);
-}
-
-function test_portal_found() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 3);
- do_check_true(success);
- },
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
-}
-
-function run_test() {
- gRedirectServer = new HttpServer();
- gRedirectServer.start(-1);
- gRedirectServerURL = 'http://localhost:' + gRedirectServer.identity.primaryPort;
-
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_portal_found);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found.js b/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found.js
deleted file mode 100644
index 1dc4fe009..000000000
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-
-var server;
-var step = 0;
-var attempt = 0;
-
-function xhr_handler(metadata, response) {
- dump('HTTP activity\n');
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- response.write('true');
- attempt++;
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic == 'captive-portal-login') {
- do_throw('should not receive captive-portal-login event');
- }
- }, 'captive-portal-login', false);
-}
-
-function test_portal_not_found() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 2);
- do_check_true(success);
- do_check_eq(attempt, 1);
- gServer.stop(function() { dump('server stop\n'); do_test_finished(); });
- }
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_portal_not_found);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found_404.js b/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found_404.js
deleted file mode 100644
index 66bcdd077..000000000
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found_404.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-
-var server;
-var step = 0;
-var loginFinished = false;
-var attempt = 0;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 404, "Page not Found");
- attempt++;
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- do_throw('should not receive captive-portal-login event');
- }
- }, 'captive-portal-login', false);
-}
-
-function test_portal_not_found() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 2);
- do_check_false(success);
- do_check_eq(attempt, 6);
- gServer.stop(do_test_finished);
- },
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_portal_not_found);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_multiple_requests.js b/toolkit/components/captivedetect/test/unit/test_multiple_requests.js
deleted file mode 100644
index 11cf5e4b2..000000000
--- a/toolkit/components/captivedetect/test/unit/test_multiple_requests.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-const kOtherInterfaceName = 'ril';
-
-var server;
-var step = 0;
-var loginFinished = false;
-var loginSuccessCount = 0;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- if (loginFinished) {
- response.write('true');
- } else {
- response.write('false');
- }
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
- .createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
- xhr.send();
- loginFinished = true;
- do_check_eq(++step, 2);
- }
- }, 'captive-portal-login', false);
-
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-success') {
- loginSuccessCount++;
- if (loginSuccessCount > 1) {
- throw "We should only receive 'captive-portal-login-success' once";
- }
- do_check_eq(++step, 4);
- }
- }, 'captive-portal-login-success', false);
-}
-
-function test_multiple_requests() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 3);
- do_check_true(success);
- },
- };
-
- let otherCallback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 5);
- gCaptivePortalDetector.finishPreparation(kOtherInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 6);
- do_check_true(success);
- gServer.stop(do_test_finished);
- }
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
- gCaptivePortalDetector.checkCaptivePortal(kOtherInterfaceName, otherCallback);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_multiple_requests);
-}
diff --git a/toolkit/components/captivedetect/test/unit/test_user_cancel.js b/toolkit/components/captivedetect/test/unit/test_user_cancel.js
deleted file mode 100644
index a03876817..000000000
--- a/toolkit/components/captivedetect/test/unit/test_user_cancel.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
-
-const kInterfaceName = 'wifi';
-
-var server;
-var step = 0;
-
-function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- response.write('false');
-}
-
-function fakeUIResponse() {
- Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
- .createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
- xhr.send();
- do_check_eq(++step, 2);
- let details = JSON.parse(data);
- gCaptivePortalDetector.cancelLogin(details.id);
- }
- }, 'captive-portal-login', false);
-}
-
-function test_cancel() {
- do_test_pending();
-
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function prepare() {
- do_check_eq(++step, 1);
- gCaptivePortalDetector.finishPreparation(kInterfaceName);
- },
- complete: function complete(success) {
- do_check_eq(++step, 3);
- do_check_false(success);
- gServer.stop(do_test_finished);
- },
- };
-
- gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
-}
-
-function run_test() {
- run_captivedetect_test(xhr_handler, fakeUIResponse, test_cancel);
-}
diff --git a/toolkit/components/captivedetect/test/unit/xpcshell.ini b/toolkit/components/captivedetect/test/unit/xpcshell.ini
deleted file mode 100644
index 0f440c438..000000000
--- a/toolkit/components/captivedetect/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-head = head_setprefs.js
-tail =
-
-[test_captive_portal_not_found.js]
-[test_captive_portal_not_found_404.js]
-[test_captive_portal_found.js]
-[test_captive_portal_found_303.js]
-[test_abort.js]
-[test_abort_during_user_login.js]
-[test_user_cancel.js]
-[test_multiple_requests.js]
-[test_abort_ongoing_request.js]
-[test_abort_pending_request.js]
-
diff --git a/toolkit/components/commandlines/moz.build b/toolkit/components/commandlines/moz.build
index 5798ccfcc..eb1303ff0 100644
--- a/toolkit/components/commandlines/moz.build
+++ b/toolkit/components/commandlines/moz.build
@@ -4,13 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-
-if CONFIG['OS_ARCH'] == 'WINNT':
- XPCSHELL_TESTS_MANIFESTS += ['test/unit_win/xpcshell.ini']
-elif CONFIG['OS_ARCH'] != 'Darwin':
- XPCSHELL_TESTS_MANIFESTS += ['test/unit_unix/xpcshell.ini']
-
XPIDL_SOURCES += [
'nsICommandLine.idl',
'nsICommandLineHandler.idl',
@@ -20,11 +13,6 @@ XPIDL_SOURCES += [
XPIDL_MODULE = 'commandlines'
-SOURCES += [
- 'nsCommandLine.cpp',
-]
+SOURCES += ['nsCommandLine.cpp']
FINAL_LIBRARY = 'xul'
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Startup and Profile System')
diff --git a/toolkit/components/commandlines/test/unit/.eslintrc.js b/toolkit/components/commandlines/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/commandlines/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/commandlines/test/unit/data/test_bug410156.desktop b/toolkit/components/commandlines/test/unit/data/test_bug410156.desktop
deleted file mode 100644
index 1847cdd98..000000000
--- a/toolkit/components/commandlines/test/unit/data/test_bug410156.desktop
+++ /dev/null
@@ -1,7 +0,0 @@
-[Desktop Entry]
-Version=1.0
-Encoding=UTF-8
-Name=test_bug410156
-Type=Link
-URL=http://www.bug410156.com/
-Icon=gnome-fs-bookmark
diff --git a/toolkit/components/commandlines/test/unit/data/test_bug410156.url b/toolkit/components/commandlines/test/unit/data/test_bug410156.url
deleted file mode 100644
index 6920e1f77..000000000
--- a/toolkit/components/commandlines/test/unit/data/test_bug410156.url
+++ /dev/null
@@ -1,9 +0,0 @@
-[InternetShortcut]
-URL=http://www.bug410156.com/
-IDList=
-HotKey=0
-[{000214A0-0000-0000-C000-000000000046}]
-Prop3=19,2
-[InternetShortcut.A]
-[InternetShortcut.W]
-URL=http://www.bug410156.com/
diff --git a/toolkit/components/commandlines/test/unit/test_bug666224.js b/toolkit/components/commandlines/test/unit/test_bug666224.js
deleted file mode 100644
index 8d372097a..000000000
--- a/toolkit/components/commandlines/test/unit/test_bug666224.js
+++ /dev/null
@@ -1,6 +0,0 @@
-function run_test() {
- var cmdLine=Components.classes["@mozilla.org/toolkit/command-line;1"].createInstance(Components.interfaces.nsICommandLine);
- try {
- cmdLine.getArgument(cmdLine.length);
- } catch (e) {}
-}
diff --git a/toolkit/components/commandlines/test/unit/test_classinfo.js b/toolkit/components/commandlines/test/unit/test_classinfo.js
deleted file mode 100644
index a0fb1ff0a..000000000
--- a/toolkit/components/commandlines/test/unit/test_classinfo.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/. */
-
-function run_test() {
- var clClass = Components.classes["@mozilla.org/toolkit/command-line;1"];
- var commandLine = clClass.createInstance();
- do_check_true("length" in commandLine);
-}
diff --git a/toolkit/components/commandlines/test/unit/xpcshell.ini b/toolkit/components/commandlines/test/unit/xpcshell.ini
deleted file mode 100644
index 4939a3d64..000000000
--- a/toolkit/components/commandlines/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-head =
-tail =
-skip-if = toolkit == 'android'
-support-files =
- data/test_bug410156.desktop
- data/test_bug410156.url
-
-[test_classinfo.js]
-[test_bug666224.js]
diff --git a/toolkit/components/commandlines/test/unit_unix/.eslintrc.js b/toolkit/components/commandlines/test/unit_unix/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/commandlines/test/unit_unix/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/commandlines/test/unit_unix/test_bug410156.js b/toolkit/components/commandlines/test/unit_unix/test_bug410156.js
deleted file mode 100644
index 06c95ac35..000000000
--- a/toolkit/components/commandlines/test/unit_unix/test_bug410156.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/. */
-
-function run_test() {
- var clClass = Components.classes["@mozilla.org/toolkit/command-line;1"];
- var commandLine = clClass.createInstance();
- var urlFile = do_get_file("../unit/data/test_bug410156.desktop");
- var uri = commandLine.resolveURI(urlFile.path);
- do_check_eq(uri.spec, "http://www.bug410156.com/");
-}
diff --git a/toolkit/components/commandlines/test/unit_unix/xpcshell.ini b/toolkit/components/commandlines/test/unit_unix/xpcshell.ini
deleted file mode 100644
index 41f71f48d..000000000
--- a/toolkit/components/commandlines/test/unit_unix/xpcshell.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[DEFAULT]
-head =
-tail =
-skip-if = toolkit == 'android'
-support-files =
- !/toolkit/components/commandlines/test/unit/data/test_bug410156.desktop
- !/toolkit/components/commandlines/test/unit/data/test_bug410156.url
-
-[test_bug410156.js]
diff --git a/toolkit/components/commandlines/test/unit_win/.eslintrc.js b/toolkit/components/commandlines/test/unit_win/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/commandlines/test/unit_win/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/commandlines/test/unit_win/test_bug410156.js b/toolkit/components/commandlines/test/unit_win/test_bug410156.js
deleted file mode 100644
index cc04426d6..000000000
--- a/toolkit/components/commandlines/test/unit_win/test_bug410156.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/. */
-
-function run_test() {
- var clClass = Components.classes["@mozilla.org/toolkit/command-line;1"];
- var commandLine = clClass.createInstance();
- var urlFile = do_get_file("../unit/data/test_bug410156.url");
- var uri = commandLine.resolveURI(urlFile.path);
- do_check_eq(uri.spec, "http://www.bug410156.com/");
-}
diff --git a/toolkit/components/commandlines/test/unit_win/xpcshell.ini b/toolkit/components/commandlines/test/unit_win/xpcshell.ini
deleted file mode 100644
index efc2cfccf..000000000
--- a/toolkit/components/commandlines/test/unit_win/xpcshell.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-head =
-tail =
-support-files =
- !/toolkit/components/commandlines/test/unit/data/test_bug410156.desktop
- !/toolkit/components/commandlines/test/unit/data/test_bug410156.url
-
-[test_bug410156.js]
diff --git a/toolkit/components/console/moz.build b/toolkit/components/console/moz.build
index d730b9aa3..e9545267f 100644
--- a/toolkit/components/console/moz.build
+++ b/toolkit/components/console/moz.build
@@ -4,8 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-MOCHITEST_CHROME_MANIFESTS += ['tests/chrome.ini']
-
EXTRA_COMPONENTS += [
'jsconsole-clhandler.js',
'jsconsole-clhandler.manifest',
diff --git a/toolkit/components/console/tests/chrome.ini b/toolkit/components/console/tests/chrome.ini
deleted file mode 100644
index 0480c3533..000000000
--- a/toolkit/components/console/tests/chrome.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[test_hugeURIs.xul]
diff --git a/toolkit/components/console/tests/test_hugeURIs.xul b/toolkit/components/console/tests/test_hugeURIs.xul
deleted file mode 100644
index 87a571e8d..000000000
--- a/toolkit/components/console/tests/test_hugeURIs.xul
+++ /dev/null
@@ -1,64 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=796179
--->
-<window title="Mozilla Bug 796179"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="RunTest();">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
-
- <!-- Detect severe performance and memory issues when large amounts of errors
- are reported from CSS embedded in a file with a long data URI. Addressed
- by 786108 for issues internal to the style system and by 796179 for issues
- related to the error console. This error console test should finish quickly
- with those patches and run for a very long time or OOM otherwise. -->
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=796179"
- target="_blank">Mozilla Bug 796179</a>
- <div id="badSVG" style="max-width: 1; max-height: 1; overflow: hidden"></div>
- </body>
-
- <!-- display the error console so we can test its reaction to the test -->
- <iframe id="errorConsoleFrame" height="400" src="chrome://global/content/console.xul"></iframe>
-
- <!-- test code -->
- <script type="application/javascript">
- <![CDATA[
- function RunTest()
- {
- // Create the bad SVG and add it to the document.
- var img = new Array;
- img.push('<img src="data:image/svg+xml,');
- img.push(encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="300px">'));
-
- for (var i = 0 ; i < 10000 ; i++)
- img.push(encodeURIComponent('<circle cx="0" cy="0" r="1" style="xxx-invalid-property: 0;"/>'));
-
- img.push(encodeURIComponent('</svg>'));
- img.push('" />');
-
- document.getElementById('badSVG').innerHTML = img.join('');
-
- // We yield control of the thread, allowing the error console to render.
- // If we get control back without timing out or OOMing then the test passed.
- SimpleTest.waitForExplicitFinish();
- SimpleTest.executeSoon(function() {
- // Clean up.
- var elem = document.getElementById('errorConsoleFrame');
- elem.parentNode.removeChild(elem);
- elem = document.getElementById('badSVG');
- elem.parentNode.removeChild(elem);
- elem = null;
-
- // Finish the test with a pass.
- ok(true, 'Error console rendered OK.');
- SimpleTest.finish();
- }, 0);
- }
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/contentprefs/moz.build b/toolkit/components/contentprefs/moz.build
index 24bb296f1..83074ed64 100644
--- a/toolkit/components/contentprefs/moz.build
+++ b/toolkit/components/contentprefs/moz.build
@@ -4,15 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += [
- 'tests/unit/xpcshell.ini',
- 'tests/unit_cps2/xpcshell.ini',
-]
-
-MOCHITEST_MANIFESTS += [
- 'tests/mochitest/mochitest.ini'
-]
-
EXTRA_COMPONENTS += [
'nsContentPrefService.js',
'nsContentPrefService.manifest',
@@ -26,6 +17,3 @@ EXTRA_JS_MODULES += [
'ContentPrefStore.jsm',
'ContentPrefUtils.jsm',
]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Preferences')
diff --git a/toolkit/components/contentprefs/tests/mochitest/.eslintrc.js b/toolkit/components/contentprefs/tests/mochitest/.eslintrc.js
deleted file mode 100644
index 64a4eda73..000000000
--- a/toolkit/components/contentprefs/tests/mochitest/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/mochitest.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/contentprefs/tests/mochitest/mochitest.ini b/toolkit/components/contentprefs/tests/mochitest/mochitest.ini
deleted file mode 100644
index ec4f05945..000000000
--- a/toolkit/components/contentprefs/tests/mochitest/mochitest.ini
+++ /dev/null
@@ -1,4 +0,0 @@
-[DEFAULT]
-
-[test_remoteContentPrefs.html]
-skip-if = toolkit == 'android' || e10s # bug 783513
diff --git a/toolkit/components/contentprefs/tests/mochitest/test_remoteContentPrefs.html b/toolkit/components/contentprefs/tests/mochitest/test_remoteContentPrefs.html
deleted file mode 100644
index d14e85a25..000000000
--- a/toolkit/components/contentprefs/tests/mochitest/test_remoteContentPrefs.html
+++ /dev/null
@@ -1,311 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for nsIContentPrefService2 in child processes</title>
- <script type="application/javascript"
- src="/tests/SimpleTest/SimpleTest.js">
- </script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-</head>
-<body>
-
- <script type="application/javascript;version=1.8">
- "use strict";
-
- SimpleTest.waitForExplicitFinish();
-
- const childFrameURL =
- "data:text/html,<!DOCTYPE HTML><html><body></body></html>";
-
- function childFrameScript(isFramePrivate) {
- "use strict";
-
- function Tester(resultArray) {
- this.results = [];
- }
-
- Tester.prototype.is =
- function(a, b, note) {
- this.results.push([a === b, note + " (" + a + ", " + b + ")"]);
- };
- Tester.prototype.ok =
- function(b, note) {
- this.results.push([b != false, note]);
- };
-
- var cps = Components.classes["@mozilla.org/content-pref/service;1"]
- .getService(Components.interfaces.nsIContentPrefService2);
-
- let test = null;
- function* test1(message) {
- let tester = new Tester();
-
- tester.ok(cps !== null, "got the content pref service");
-
- cps.setGlobal("testing", 42, null, {
- handleCompletion: function(reason) {
- tester.is(reason, 0, "set a pref?");
- test.next();
- }
- });
-
- yield;
-
- let numResults = 0;
- cps.getGlobal("testing", null, {
- handleResult: function(pref) {
- numResults++;
- tester.is(pref.name, "testing", "pref has the right name");
- tester.is(pref.value, 42, "pref has the right value");
- },
-
- handleCompletion: function(reason) {
- tester.is(reason, 0, "get a pref?");
- tester.is(numResults, 1, "got the right number of prefs");
- tester.is(test.next().done, true, "done with test1");
- message.target.sendAsyncMessage("testRemoteContentPrefs:test1Finished",
- { results: tester.results });
- }
- });
-
- yield;
- }
-
- function* test2(message) {
- let tester = new Tester();
-
- let observer;
- let removed = false;
- cps.addObserverForName("testName", observer = {
- onContentPrefSet: function(group, name, value, isPrivate) {
- if (removed) {
- message.target.sendAsyncMessage("testRemoteContentPrefs:fail",
- { reason: "unexpected notification" });
- }
- tester.is(group, null, "group should be null");
- tester.is(name, "testName", "should only see testName");
- tester.is(value, 42, "value should be correct");
- tester.is(isPrivate, isFramePrivate, "privacy should match");
-
- message.target.sendAsyncMessage("testRemoteContentPrefs:test2poke2", {})
- },
-
- onContentPrefRemoved: function(group, name, isPrivate) {
- tester.is(group, null, "group should be null");
- tester.is(name, "testName");
- tester.is(isPrivate, isFramePrivate, "privacy should match");
- tester.is(test.next().done, true, "should be done with test2");
-
- cps.removeObserverForName("testName", observer);
- removed = true;
-
- message.target.sendAsyncMessage("testRemoteContentPrefs:test2Finished",
- { results: tester.results });
- }
- });
-
- message.target.sendAsyncMessage("testRemoteContentPrefs:test2poke", {});
- yield;
- }
-
- function* test3(message) {
- let tester = new Tester();
-
- cps.setGlobal("testName", 42, null, {
- handleCompletion: function(reason) {
- tester.is(reason, 0, "set a pref");
- cps.set("http://mochi.test", "testpref", "str", null, {
- handleCompletion: function(reason) {
- tester.is(reason, 0, "set a pref");
- test.next();
- }
- });
- }
- });
-
- yield;
-
- cps.removeByDomain("http://mochi.test", null, {
- handleCompletion: function(reason) {
- tester.is(reason, 0, "remove succeeded");
- cps.getByDomainAndName("http://mochi.test", "testpref", null, {
- handleResult: function() {
- message.target.sendAsyncMessage("testRemoteContentPrefs:fail",
- { reason: "got removed pref in test3" });
- },
- handleCompletion: function() {
- test.next();
- }
- });
- }
- });
-
- yield;
-
- message.target.sendAsyncMessage("testRemoteContentPrefs:test3Finished",
- { results: tester.results });
- }
-
- function* test4(message) {
- let tester = new Tester();
-
- let prefObserver = {
- onContentPrefSet: function(group, name, value, isPrivate) {
- test.next({ group: group, name: name, value: value, isPrivate: isPrivate });
- },
- onContentPrefRemoved: function(group, name, isPrivate) {
- test.next({ group: group, name: name, isPrivate: isPrivate });
- }
- };
-
- addMessageListener("testRemoteContentPrefs:prefResults", (msg) => {
- test.next(msg.data.results);
- });
-
- cps.addObserverForName("test", prefObserver);
-
- cps.set("http://mochi.test", "test", 42, { usePrivateBrowsing: true });
- let event = yield;
- tester.is(event.name, "test");
- tester.is(event.isPrivate, true);
-
- message.target.sendAsyncMessage("testRemoteContentPrefs:getPref",
- { group: "http://mochi.test", name: "test" });
-
- let results = yield;
- tester.is(results.length, 0, "should not have seen the pb pref");
-
- message.target.sendAsyncMessage("testRemoteContentPrefs:test4Finished",
- { results: tester.results });
- }
-
- addMessageListener("testRemoteContentPrefs:test1", function(message) {
- test = test1(message);
- test.next();
- });
- addMessageListener("testRemoteContentPrefs:test2", function(message) {
- test = test2(message);
- test.next();
- });
- addMessageListener("testRemoteContentPrefs:test3", function(message) {
- test = test3(message);
- test.next();
- });
- addMessageListener("testRemoteContentPrefs:test4", function(message) {
- test = test4(message);
- test.next();
- });
- }
-
- function processResults(results) {
- for (let i of results) {
- ok(...i);
- }
- }
-
- let test;
- function* testStructure(mm, isPrivate, callback) {
- let lastResult;
-
- function testDone(msg) {
- test.next(msg.data);
- }
-
- mm.addMessageListener("testRemoteContentPrefs:test1Finished", testDone);
- mm.addMessageListener("testRemoteContentPrefs:test2Finished", testDone);
- mm.addMessageListener("testRemoteContentPrefs:test3Finished", testDone);
- mm.addMessageListener("testRemoteContentPrefs:test4Finished", testDone);
-
- mm.addMessageListener("testRemoteContentPrefs:fail", function(msg) {
- ok(false, msg.data.reason);
- });
-
- mm.sendAsyncMessage("testRemoteContentPrefs:test1", {});
- lastResult = yield;
- processResults(lastResult.results);
-
- var cps = SpecialPowers.Cc["@mozilla.org/content-pref/service;1"]
- .getService(SpecialPowers.Ci.nsIContentPrefService2);
- mm.sendAsyncMessage("testRemoteContentPrefs:test2", {});
- mm.addMessageListener("testRemoteContentPrefs:test2poke", function() {
- cps.setGlobal("testName", 42, {usePrivateBrowsing: isPrivate});
- });
- mm.addMessageListener("testRemoteContentPrefs:test2poke2", function() {
- cps.removeGlobal("testName", {usePrivateBrowsing: isPrivate});
- });
-
- lastResult = yield;
- processResults(lastResult.results);
-
- mm.sendAsyncMessage("testRemoteContentPrefs:test3", {});
- lastResult = yield;
- processResults(lastResult.results);
-
- mm.addMessageListener("testRemoteContentPrefs:getPref", function(msg) {
- let results = [];
- cps.getByDomainAndName(msg.data.group, msg.data.name, null, {
- handleResult: function(pref) {
- results.push(pref);
- },
- handleCompletion: function(reason) {
- mm.sendAsyncMessage("testRemoteContentPrefs:prefResults",
- { results: results });
- }
- });
- });
-
- mm.sendAsyncMessage("testRemoteContentPrefs:test4", {});
- lastResult = yield;
- processResults(lastResult.results);
-
- document.getElementById('iframe').remove();
- setTimeout(callback, 0);
- }
-
- function runTest(isPrivate, callback) {
- info("testing with isPrivate=" + isPrivate);
- let iframe = document.createElement("iframe");
- SpecialPowers.wrap(iframe).mozbrowser = true;
- if (isPrivate) {
- SpecialPowers.wrap(iframe).mozprivatebrowsing = true;
- }
- iframe.id = "iframe";
- iframe.src = childFrameURL;
-
- iframe.addEventListener("mozbrowserloadend", function() {
- info("Got iframe load event.");
- let mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
- mm.loadFrameScript("data:,(" + childFrameScript.toString() + ")(" + isPrivate + ");",
- false);
-
- test = testStructure(mm, isPrivate, callback);
- test.next();
- });
-
- document.body.appendChild(iframe);
- }
-
- function runTests() {
- info("Browser prefs set.");
- runTest(false, function() {
- runTest(true, function() {
- SimpleTest.finish();
- });
- });
- }
-
- addEventListener("load", function() {
- info("Got load event.");
-
- SpecialPowers.addPermission("browser", true, document);
- SpecialPowers.pushPrefEnv({
- "set": [
- ["dom.ipc.browser_frames.oop_by_default", true],
- ["dom.mozBrowserFramesEnabled", true],
- ["browser.pagethumbnails.capturing_disabled", true]
- ]
- }, runTests);
- });
- </script>
-</body>
-</html>
diff --git a/toolkit/components/contentprefs/tests/unit/.eslintrc.js b/toolkit/components/contentprefs/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/contentprefs/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/contentprefs/tests/unit/head_contentPrefs.js b/toolkit/components/contentprefs/tests/unit/head_contentPrefs.js
deleted file mode 100644
index 84ca1bebf..000000000
--- a/toolkit/components/contentprefs/tests/unit/head_contentPrefs.js
+++ /dev/null
@@ -1,162 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Inspired by the Places infrastructure in head_bookmarks.js
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import('resource://gre/modules/Services.jsm');
-Cu.import('resource://gre/modules/ContentPrefInstance.jsm');
-
-const CONTENT_PREFS_DB_FILENAME = "content-prefs.sqlite";
-const CONTENT_PREFS_BACKUP_DB_FILENAME = "content-prefs.sqlite.corrupt";
-
-var ContentPrefTest = {
- // Convenience Getters
-
- __dirSvc: null,
- get _dirSvc() {
- if (!this.__dirSvc)
- this.__dirSvc = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
- return this.__dirSvc;
- },
-
- __consoleSvc: null,
- get _consoleSvc() {
- if (!this.__consoleSvc)
- this.__consoleSvc = Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService);
- return this.__consoleSvc;
- },
-
- __ioSvc: null,
- get _ioSvc() {
- if (!this.__ioSvc)
- this.__ioSvc = Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService);
- return this.__ioSvc;
- },
-
-
- // nsISupports
-
- interfaces: [Ci.nsIDirectoryServiceProvider, Ci.nsISupports],
-
- QueryInterface: function ContentPrefTest_QueryInterface(iid) {
- if (!this.interfaces.some( function(v) { return iid.equals(v) } ))
- throw Cr.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
-
- // nsIDirectoryServiceProvider
-
- getFile: function ContentPrefTest_getFile(property, persistent) {
- persistent.value = true;
-
- if (property == "ProfD")
- return this._dirSvc.get("CurProcD", Ci.nsIFile);
-
- // This causes extraneous errors to show up in the log when the directory
- // service asks us first for CurProcD and MozBinD. I wish there was a way
- // to suppress those errors.
- throw Cr.NS_ERROR_FAILURE;
- },
-
-
- // Utilities
-
- getURI: function ContentPrefTest_getURI(spec) {
- return this._ioSvc.newURI(spec, null, null);
- },
-
- /**
- * Get the profile directory.
- */
- getProfileDir: function ContentPrefTest_getProfileDir() {
- // do_get_profile can be only called from a parent process
- if (runningInParent) {
- return do_get_profile();
- }
- // if running in a content process, this just returns the path
- // profile was initialized in the ipc head file
- let env = Components.classes["@mozilla.org/process/environment;1"]
- .getService(Components.interfaces.nsIEnvironment);
- // the python harness sets this in the environment for us
- let profd = env.get("XPCSHELL_TEST_PROFILE_DIR");
- let file = Components.classes["@mozilla.org/file/local;1"]
- .createInstance(Components.interfaces.nsILocalFile);
- file.initWithPath(profd);
- return file;
- },
-
- /**
- * Delete the content pref service's persistent datastore. We do this before
- * and after running tests to make sure we start from scratch each time. We
- * also do it during the database creation, schema migration, and backup tests.
- */
- deleteDatabase: function ContentPrefTest_deleteDatabase() {
- var file = this.getProfileDir();
- file.append(CONTENT_PREFS_DB_FILENAME);
- if (file.exists())
- try { file.remove(false); } catch (e) { /* stupid windows box */ }
- return file;
- },
-
- /**
- * Delete the backup of the content pref service's persistent datastore.
- * We do this during the database creation, schema migration, and backup tests.
- */
- deleteBackupDatabase: function ContentPrefTest_deleteBackupDatabase() {
- var file = this.getProfileDir();
- file.append(CONTENT_PREFS_BACKUP_DB_FILENAME);
- if (file.exists())
- file.remove(false);
- return file;
- },
-
- /**
- * Log a message to the console and the test log.
- */
- log: function ContentPrefTest_log(message) {
- message = "*** ContentPrefTest: " + message;
- this._consoleSvc.logStringMessage(message);
- print(message);
- }
-
-};
-
-var gInPrivateBrowsing = false;
-function enterPBMode() {
- gInPrivateBrowsing = true;
-}
-function exitPBMode() {
- gInPrivateBrowsing = false;
- Services.obs.notifyObservers(null, "last-pb-context-exited", null);
-}
-
-ContentPrefTest.deleteDatabase();
-
-function inChildProcess() {
- var appInfo = Cc["@mozilla.org/xre/app-info;1"];
- if (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType ==
- Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
- return false;
- }
- return true;
-}
-
-// Turn on logging for the content preferences service so we can troubleshoot
-// problems with the tests. Note that we cannot do this in a child process
-// without crashing (but we don't need it anyhow)
-if (!inChildProcess()) {
- var prefBranch = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
- prefBranch.setBoolPref("browser.preferences.content.log", true);
-}
-
diff --git a/toolkit/components/contentprefs/tests/unit/tail_contentPrefs.js b/toolkit/components/contentprefs/tests/unit/tail_contentPrefs.js
deleted file mode 100644
index f3c95dac8..000000000
--- a/toolkit/components/contentprefs/tests/unit/tail_contentPrefs.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/. */
-
-ContentPrefTest.deleteDatabase();
-ContentPrefTest.__dirSvc = null;
diff --git a/toolkit/components/contentprefs/tests/unit/test_bug248970.js b/toolkit/components/contentprefs/tests/unit/test_bug248970.js
deleted file mode 100644
index 5f4aa25c5..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_bug248970.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- let loadContext = { get usePrivateBrowsing() { return gInPrivateBrowsing; } };
-
- ContentPrefTest.deleteDatabase();
- var cp = new ContentPrefInstance(loadContext);
- do_check_neq(cp, null, "Retrieving the content prefs service failed");
-
- try {
- const uri1 = ContentPrefTest.getURI("http://www.example.com/");
- const uri2 = ContentPrefTest.getURI("http://www.anotherexample.com/");
- const pref_name = "browser.content.full-zoom";
- const zoomA = 1.5, zoomA_new = 0.8, zoomB = 1.3;
- // save Zoom-A
- cp.setPref(uri1, pref_name, zoomA);
- // make sure Zoom-A is retrievable
- do_check_eq(cp.getPref(uri1, pref_name), zoomA);
- // enter private browsing mode
- enterPBMode();
- // make sure Zoom-A is retrievable
- do_check_eq(cp.getPref(uri1, pref_name), zoomA);
- // save Zoom-B
- cp.setPref(uri2, pref_name, zoomB);
- // make sure Zoom-B is retrievable
- do_check_eq(cp.getPref(uri2, pref_name), zoomB);
- // update Zoom-A
- cp.setPref(uri1, pref_name, zoomA_new);
- // make sure Zoom-A has changed
- do_check_eq(cp.getPref(uri1, pref_name), zoomA_new);
- // exit private browsing mode
- exitPBMode();
- // make sure Zoom-A change has not persisted
- do_check_eq(cp.getPref(uri1, pref_name), zoomA);
- // make sure Zoom-B change has not persisted
- do_check_eq(cp.hasPref(uri2, pref_name), false);
- } catch (e) {
- do_throw("Unexpected exception: " + e);
- }
-}
diff --git a/toolkit/components/contentprefs/tests/unit/test_bug503971.js b/toolkit/components/contentprefs/tests/unit/test_bug503971.js
deleted file mode 100644
index ccfe1d02b..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_bug503971.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- var cps = new ContentPrefInstance(null);
-
- var uri = ContentPrefTest.getURI("http://www.example.com/");
-
- do_check_thrown(function () { cps.setPref(uri, null, 8); });
- do_check_thrown(function () { cps.hasPref(uri, null); });
- do_check_thrown(function () { cps.getPref(uri, null); });
- do_check_thrown(function () { cps.removePref(uri, null); });
- do_check_thrown(function () { cps.getPrefsByName(null); });
- do_check_thrown(function () { cps.removePrefsByName(null); });
-
- do_check_thrown(function () { cps.setPref(uri, "", 21); });
- do_check_thrown(function () { cps.hasPref(uri, ""); });
- do_check_thrown(function () { cps.getPref(uri, ""); });
- do_check_thrown(function () { cps.removePref(uri, ""); });
- do_check_thrown(function () { cps.getPrefsByName(""); });
- do_check_thrown(function () { cps.removePrefsByName(""); });
-}
-
-function do_check_thrown (aCallback) {
- var exThrown = false;
- try {
- aCallback();
- do_throw("NS_ERROR_ILLEGAL_VALUE should have been thrown here");
- } catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_ILLEGAL_VALUE);
- exThrown = true;
- }
- do_check_true(exThrown);
-}
diff --git a/toolkit/components/contentprefs/tests/unit/test_bug679784.js b/toolkit/components/contentprefs/tests/unit/test_bug679784.js
deleted file mode 100644
index 97251d87b..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_bug679784.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/. */
-
-
-var prefObserver = {
- setCalledNum: 0,
- onContentPrefSet: function(aGroup, aName, aValue) {
- this.setCalledNum++;
- },
- removedCalledNum: 0,
- onContentPrefRemoved: function(aGroup, aName) {
- this.removedCalledNum++;
- }
-};
-
-function run_test() {
- let loadContext = { get usePrivateBrowsing() { return gInPrivateBrowsing; } };
-
- var cps = new ContentPrefInstance(loadContext);
- cps.removeGroupedPrefs();
-
- var uri = ContentPrefTest.getURI("http://www.example.com/");
- var group = cps.grouper.group(uri);
-
- // first, set a pref in normal mode
- cps.setPref(uri, "value", "foo");
- cps.setPref(null, "value-global", "foo-global");
-
- var num;
- cps.addObserver("value", prefObserver);
- cps.addObserver("value-global", prefObserver);
-
- enterPBMode();
-
- // test setPref
- num = prefObserver.setCalledNum;
- cps.setPref(uri, "value", "foo-private-browsing");
- do_check_eq(cps.hasPref(uri, "value"), true);
- do_check_eq(cps.getPref(uri, "value"), "foo-private-browsing");
- do_check_eq(prefObserver.setCalledNum, num + 1);
-
- num = prefObserver.setCalledNum;
- cps.setPref(null, "value-global", "foo-private-browsing-global");
- do_check_eq(cps.hasPref(null, "value-global"), true);
- do_check_eq(cps.getPref(null, "value-global"), "foo-private-browsing-global");
- do_check_eq(prefObserver.setCalledNum, num + 1);
-
- // test removePref
- num = prefObserver.removedCalledNum;
- cps.removePref(uri, "value");
- do_check_eq(cps.hasPref(uri, "value"), true);
- // fallback to non private mode value
- do_check_eq(cps.getPref(uri, "value"), "foo");
- do_check_eq(prefObserver.removedCalledNum, num + 1);
-
- num = prefObserver.removedCalledNum;
- cps.removePref(null, "value-global");
- do_check_eq(cps.hasPref(null, "value-global"), true);
- // fallback to non private mode value
- do_check_eq(cps.getPref(null, "value-global"), "foo-global") ;
- do_check_eq(prefObserver.removedCalledNum, num + 1);
-
- // test removeGroupedPrefs
- cps.setPref(uri, "value", "foo-private-browsing");
- cps.removeGroupedPrefs();
- do_check_eq(cps.hasPref(uri, "value"), false);
- do_check_eq(cps.getPref(uri, "value"), undefined);
-
- cps.setPref(null, "value-global", "foo-private-browsing-global");
- cps.removeGroupedPrefs();
- do_check_eq(cps.hasPref(null, "value-global"), true);
- do_check_eq(cps.getPref(null, "value-global"), "foo-private-browsing-global");
-
- // test removePrefsByName
- num = prefObserver.removedCalledNum;
- cps.setPref(uri, "value", "foo-private-browsing");
- cps.removePrefsByName("value");
- do_check_eq(cps.hasPref(uri, "value"), false);
- do_check_eq(cps.getPref(uri, "value"), undefined);
- do_check_true(prefObserver.removedCalledNum > num);
-
- num = prefObserver.removedCalledNum;
- cps.setPref(null, "value-global", "foo-private-browsing");
- cps.removePrefsByName("value-global");
- do_check_eq(cps.hasPref(null, "value-global"), false);
- do_check_eq(cps.getPref(null, "value-global"), undefined);
- do_check_true(prefObserver.removedCalledNum > num);
-
- // test getPrefs
- cps.setPref(uri, "value", "foo-private-browsing");
- do_check_eq(cps.getPrefs(uri).getProperty("value"), "foo-private-browsing");
-
- cps.setPref(null, "value-global", "foo-private-browsing-global");
- do_check_eq(cps.getPrefs(null).getProperty("value-global"), "foo-private-browsing-global");
-
- // test getPrefsByName
- do_check_eq(cps.getPrefsByName("value").getProperty(group), "foo-private-browsing");
- do_check_eq(cps.getPrefsByName("value-global").getProperty(null), "foo-private-browsing-global");
-
- cps.removeObserver("value", prefObserver);
- cps.removeObserver("value-global", prefObserver);
-}
diff --git a/toolkit/components/contentprefs/tests/unit/test_contentPrefs.js b/toolkit/components/contentprefs/tests/unit/test_contentPrefs.js
deleted file mode 100644
index f7e99ea9d..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_contentPrefs.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/. */
-
-function run_test() {
- // Database Creation, Schema Migration, and Backup
-
- // Note: in these tests we use createInstance instead of getService
- // so we can instantiate the service multiple times and make it run
- // its database initialization code each time.
-
- // Create a new database.
- {
- ContentPrefTest.deleteDatabase();
-
- // Get the service and make sure it has a ready database connection.
- let cps = Cc["@mozilla.org/content-pref/service;1"].
- createInstance(Ci.nsIContentPrefService);
- do_check_true(cps.DBConnection.connectionReady);
- cps.DBConnection.close();
- }
-
- // Open an existing database.
- {
- let dbFile = ContentPrefTest.deleteDatabase();
-
- let cps = Cc["@mozilla.org/content-pref/service;1"].
- createInstance(Ci.nsIContentPrefService);
- cps.DBConnection.close();
- do_check_true(dbFile.exists());
-
- // Get the service and make sure it has a ready database connection.
- cps = Cc["@mozilla.org/content-pref/service;1"].
- createInstance(Ci.nsIContentPrefService);
- do_check_true(cps.DBConnection.connectionReady);
- cps.DBConnection.close();
- }
-
- // Open an empty database.
- {
- let dbFile = ContentPrefTest.deleteDatabase();
-
- // Create an empty database.
- let dbService = Cc["@mozilla.org/storage/service;1"].
- getService(Ci.mozIStorageService);
- let dbConnection = dbService.openDatabase(dbFile);
- do_check_eq(dbConnection.schemaVersion, 0);
- dbConnection.close();
- do_check_true(dbFile.exists());
-
- // Get the service and make sure it has created the schema.
- let cps = Cc["@mozilla.org/content-pref/service;1"].
- createInstance(Ci.nsIContentPrefService);
- do_check_neq(cps.DBConnection.schemaVersion, 0);
- cps.DBConnection.close();
- }
-
- // Open a corrupted database.
- {
- let dbFile = ContentPrefTest.deleteDatabase();
- let backupDBFile = ContentPrefTest.deleteBackupDatabase();
-
- // Create a corrupted database.
- let foStream = Cc["@mozilla.org/network/file-output-stream;1"].
- createInstance(Ci.nsIFileOutputStream);
- foStream.init(dbFile, 0x02 | 0x08 | 0x20, 0o666, 0);
- let garbageData = "garbage that makes SQLite think the file is corrupted";
- foStream.write(garbageData, garbageData.length);
- foStream.close();
-
- // Get the service and make sure it backs up and recreates the database.
- let cps = Cc["@mozilla.org/content-pref/service;1"].
- createInstance(Ci.nsIContentPrefService);
- do_check_true(backupDBFile.exists());
- do_check_true(cps.DBConnection.connectionReady);
-
- cps.DBConnection.close();
- }
-
- // Open a database with a corrupted schema.
- {
- let dbFile = ContentPrefTest.deleteDatabase();
- let backupDBFile = ContentPrefTest.deleteBackupDatabase();
-
- // Create an empty database and set the schema version to a number
- // that will trigger a schema migration that will fail.
- let dbService = Cc["@mozilla.org/storage/service;1"].
- getService(Ci.mozIStorageService);
- let dbConnection = dbService.openDatabase(dbFile);
- dbConnection.schemaVersion = -1;
- dbConnection.close();
- do_check_true(dbFile.exists());
-
- // Get the service and make sure it backs up and recreates the database.
- let cps = Cc["@mozilla.org/content-pref/service;1"].
- createInstance(Ci.nsIContentPrefService);
- do_check_true(backupDBFile.exists());
- do_check_true(cps.DBConnection.connectionReady);
-
- cps.DBConnection.close();
- }
-
-
- // Now get the content pref service for real for use by the rest of the tests.
- let cps = new ContentPrefInstance(null);
-
- var uri = ContentPrefTest.getURI("http://www.example.com/");
-
- // Make sure disk synchronization checking is turned off by default.
- var statement = cps.DBConnection.createStatement("PRAGMA synchronous");
- statement.executeStep();
- do_check_eq(0, statement.getInt32(0));
-
- // Nonexistent Pref
-
- do_check_eq(cps.getPref(uri, "test.nonexistent.getPref"), undefined);
- do_check_eq(cps.setPref(uri, "test.nonexistent.setPref", 5), undefined);
- do_check_false(cps.hasPref(uri, "test.nonexistent.hasPref"));
- do_check_eq(cps.removePref(uri, "test.nonexistent.removePref"), undefined);
-
-
- // Existing Pref
-
- cps.setPref(uri, "test.existing", 5);
-
- // getPref should return the pref value
- do_check_eq(cps.getPref(uri, "test.existing"), 5);
-
- // setPref should return undefined and change the value of the pref
- do_check_eq(cps.setPref(uri, "test.existing", 6), undefined);
- do_check_eq(cps.getPref(uri, "test.existing"), 6);
-
- // hasPref should return true
- do_check_true(cps.hasPref(uri, "test.existing"));
-
- // removePref should return undefined and remove the pref
- do_check_eq(cps.removePref(uri, "test.existing"), undefined);
- do_check_false(cps.hasPref(uri, "test.existing"));
-
-
- // Round-Trip Data Integrity
-
- // Make sure pref values remain the same from setPref to getPref.
-
- cps.setPref(uri, "test.data-integrity.integer", 5);
- do_check_eq(cps.getPref(uri, "test.data-integrity.integer"), 5);
-
- cps.setPref(uri, "test.data-integrity.float", 5.5);
- do_check_eq(cps.getPref(uri, "test.data-integrity.float"), 5.5);
-
- cps.setPref(uri, "test.data-integrity.boolean", true);
- do_check_eq(cps.getPref(uri, "test.data-integrity.boolean"), true);
-
- cps.setPref(uri, "test.data-integrity.string", "test");
- do_check_eq(cps.getPref(uri, "test.data-integrity.string"), "test");
-
- cps.setPref(uri, "test.data-integrity.null", null);
- do_check_eq(cps.getPref(uri, "test.data-integrity.null"), null);
-
- // XXX Test arbitrary binary data.
-
- // Make sure hasPref and removePref work on all data types.
-
- do_check_true(cps.hasPref(uri, "test.data-integrity.integer"));
- do_check_true(cps.hasPref(uri, "test.data-integrity.float"));
- do_check_true(cps.hasPref(uri, "test.data-integrity.boolean"));
- do_check_true(cps.hasPref(uri, "test.data-integrity.string"));
- do_check_true(cps.hasPref(uri, "test.data-integrity.null"));
-
- do_check_eq(cps.removePref(uri, "test.data-integrity.integer"), undefined);
- do_check_eq(cps.removePref(uri, "test.data-integrity.float"), undefined);
- do_check_eq(cps.removePref(uri, "test.data-integrity.boolean"), undefined);
- do_check_eq(cps.removePref(uri, "test.data-integrity.string"), undefined);
- do_check_eq(cps.removePref(uri, "test.data-integrity.null"), undefined);
-
- do_check_false(cps.hasPref(uri, "test.data-integrity.integer"));
- do_check_false(cps.hasPref(uri, "test.data-integrity.float"));
- do_check_false(cps.hasPref(uri, "test.data-integrity.boolean"));
- do_check_false(cps.hasPref(uri, "test.data-integrity.string"));
- do_check_false(cps.hasPref(uri, "test.data-integrity.null"));
-
-
- // getPrefs
-
- cps.setPref(uri, "test.getPrefs.a", 1);
- cps.setPref(uri, "test.getPrefs.b", 2);
- cps.setPref(uri, "test.getPrefs.c", 3);
-
- var prefs = cps.getPrefs(uri);
- do_check_true(prefs.hasKey("test.getPrefs.a"));
- do_check_eq(prefs.get("test.getPrefs.a"), 1);
- do_check_true(prefs.hasKey("test.getPrefs.b"));
- do_check_eq(prefs.get("test.getPrefs.b"), 2);
- do_check_true(prefs.hasKey("test.getPrefs.c"));
- do_check_eq(prefs.get("test.getPrefs.c"), 3);
-
-
- // Site-Specificity
-
- {
- // These are all different sites, and setting a pref for one of them
- // shouldn't set it for the others.
- let uri1 = ContentPrefTest.getURI("http://www.domain1.com/");
- let uri2 = ContentPrefTest.getURI("http://foo.domain1.com/");
- let uri3 = ContentPrefTest.getURI("http://domain1.com/");
- let uri4 = ContentPrefTest.getURI("http://www.domain2.com/");
-
- cps.setPref(uri1, "test.site-specificity.uri1", 5);
- do_check_false(cps.hasPref(uri2, "test.site-specificity.uri1"));
- do_check_false(cps.hasPref(uri3, "test.site-specificity.uri1"));
- do_check_false(cps.hasPref(uri4, "test.site-specificity.uri1"));
-
- cps.setPref(uri2, "test.site-specificity.uri2", 5);
- do_check_false(cps.hasPref(uri1, "test.site-specificity.uri2"));
- do_check_false(cps.hasPref(uri3, "test.site-specificity.uri2"));
- do_check_false(cps.hasPref(uri4, "test.site-specificity.uri2"));
-
- cps.setPref(uri3, "test.site-specificity.uri3", 5);
- do_check_false(cps.hasPref(uri1, "test.site-specificity.uri3"));
- do_check_false(cps.hasPref(uri2, "test.site-specificity.uri3"));
- do_check_false(cps.hasPref(uri4, "test.site-specificity.uri3"));
-
- cps.setPref(uri4, "test.site-specificity.uri4", 5);
- do_check_false(cps.hasPref(uri1, "test.site-specificity.uri4"));
- do_check_false(cps.hasPref(uri2, "test.site-specificity.uri4"));
- do_check_false(cps.hasPref(uri3, "test.site-specificity.uri4"));
- }
-
- // Observers
-
- var specificObserver = {
- interfaces: [Ci.nsIContentPrefObserver, Ci.nsISupports],
-
- QueryInterface: function ContentPrefTest_QueryInterface(iid) {
- if (!this.interfaces.some( function(v) { return iid.equals(v) } ))
- throw Cr.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- numTimesSetCalled: 0,
- onContentPrefSet: function specificObserver_onContentPrefSet(group, name, value) {
- ++this.numTimesSetCalled;
- do_check_eq(group, "www.example.com");
- do_check_eq(name, "test.observer.1");
- do_check_eq(value, "test value");
- },
-
- numTimesRemovedCalled: 0,
- onContentPrefRemoved: function specificObserver_onContentPrefRemoved(group, name) {
- ++this.numTimesRemovedCalled;
- do_check_eq(group, "www.example.com");
- do_check_eq(name, "test.observer.1");
- }
-
- };
-
- var genericObserver = {
- interfaces: [Ci.nsIContentPrefObserver, Ci.nsISupports],
-
- QueryInterface: function ContentPrefTest_QueryInterface(iid) {
- if (!this.interfaces.some( function(v) { return iid.equals(v) } ))
- throw Cr.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- numTimesSetCalled: 0,
- onContentPrefSet: function genericObserver_onContentPrefSet(group, name, value, isPrivate) {
- ++this.numTimesSetCalled;
- do_check_eq(group, "www.example.com");
- if (name == "test.observer.private")
- do_check_true(isPrivate);
- else if (name == "test.observer.normal")
- do_check_false(isPrivate);
- else if (name != "test.observer.1" && name != "test.observer.2")
- do_throw("genericObserver.onContentPrefSet: " +
- "name not in (test.observer.(1|2|normal|private))");
- do_check_eq(value, "test value");
- },
-
- numTimesRemovedCalled: 0,
- onContentPrefRemoved: function genericObserver_onContentPrefRemoved(group, name, isPrivate) {
- ++this.numTimesRemovedCalled;
- do_check_eq(group, "www.example.com");
- if (name == "test.observer.private")
- do_check_true(isPrivate);
- else if (name == "test.observer.normal")
- do_check_false(isPrivate);
- if (name != "test.observer.1" && name != "test.observer.2" &&
- name != "test.observer.normal" && name != "test.observer.private") {
- do_throw("genericObserver.onContentPrefSet: " +
- "name not in (test.observer.(1|2|normal|private))");
- }
- }
-
- };
-
- // Make sure we can add observers, observers get notified about changes,
- // specific observers only get notified about changes to the specific setting,
- // and generic observers get notified about changes to all settings.
- cps.addObserver("test.observer.1", specificObserver);
- cps.addObserver(null, genericObserver);
- cps.setPref(uri, "test.observer.1", "test value");
- cps.setPref(uri, "test.observer.2", "test value");
- cps.removePref(uri, "test.observer.1");
- cps.removePref(uri, "test.observer.2");
- do_check_eq(specificObserver.numTimesSetCalled, 1);
- do_check_eq(genericObserver.numTimesSetCalled, 2);
- do_check_eq(specificObserver.numTimesRemovedCalled, 1);
- do_check_eq(genericObserver.numTimesRemovedCalled, 2);
-
- // Make sure information about private context is properly
- // retrieved by the observer.
- cps.setPref(uri, "test.observer.private", "test value", {usePrivateBrowsing: true});
- cps.setPref(uri, "test.observer.normal", "test value", {usePrivateBrowsing: false});
- cps.removePref(uri, "test.observer.private");
- cps.removePref(uri, "test.observer.normal");
-
- // Make sure we can remove observers and they don't get notified
- // about changes anymore.
- cps.removeObserver("test.observer.1", specificObserver);
- cps.removeObserver(null, genericObserver);
- cps.setPref(uri, "test.observer.1", "test value");
- cps.removePref(uri, "test.observer.1", "test value");
- do_check_eq(specificObserver.numTimesSetCalled, 1);
- do_check_eq(genericObserver.numTimesSetCalled, 4);
- do_check_eq(specificObserver.numTimesRemovedCalled, 1);
- do_check_eq(genericObserver.numTimesRemovedCalled, 3);
-
-
- // Get/Remove Prefs By Name
-
- {
- var anObserver = {
- interfaces: [Ci.nsIContentPrefObserver, Ci.nsISupports],
-
- QueryInterface: function ContentPrefTest_QueryInterface(iid) {
- if (!this.interfaces.some( function(v) { return iid.equals(v) } ))
- throw Cr.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- onContentPrefSet: function anObserver_onContentPrefSet(group, name, value) {
- },
-
- expectedDomains: [],
- numTimesRemovedCalled: 0,
- onContentPrefRemoved: function anObserver_onContentPrefRemoved(group, name) {
- ++this.numTimesRemovedCalled;
-
- // remove the domain from the list of expected domains
- var index = this.expectedDomains.indexOf(group);
- do_check_true(index >= 0);
- this.expectedDomains.splice(index, 1);
- }
- };
-
- let uri1 = ContentPrefTest.getURI("http://www.domain1.com/");
- let uri2 = ContentPrefTest.getURI("http://foo.domain1.com/");
- let uri3 = ContentPrefTest.getURI("http://domain1.com/");
- let uri4 = ContentPrefTest.getURI("http://www.domain2.com/");
-
- cps.setPref(uri1, "test.byname.1", 1);
- cps.setPref(uri1, "test.byname.2", 2);
- cps.setPref(uri2, "test.byname.1", 4);
- cps.setPref(uri3, "test.byname.3", 8);
- cps.setPref(uri4, "test.byname.1", 16);
- cps.setPref(null, "test.byname.1", 32);
- cps.setPref(null, "test.byname.2", false);
-
- function enumerateAndCheck(testName, expectedSum, expectedDomains) {
- var prefsByName = cps.getPrefsByName(testName);
- var enumerator = prefsByName.enumerator;
- var sum = 0;
- while (enumerator.hasMoreElements()) {
- var property = enumerator.getNext().QueryInterface(Components.interfaces.nsIProperty);
- sum += parseInt(property.value);
-
- // remove the domain from the list of expected domains
- var index = expectedDomains.indexOf(property.name);
- do_check_true(index >= 0);
- expectedDomains.splice(index, 1);
- }
- do_check_eq(sum, expectedSum);
- // check all domains have been removed from the array
- do_check_eq(expectedDomains.length, 0);
- }
-
- enumerateAndCheck("test.byname.1", 53,
- ["foo.domain1.com", null, "www.domain1.com", "www.domain2.com"]);
- enumerateAndCheck("test.byname.2", 2, ["www.domain1.com", null]);
- enumerateAndCheck("test.byname.3", 8, ["domain1.com"]);
-
- cps.addObserver("test.byname.1", anObserver);
- anObserver.expectedDomains = ["foo.domain1.com", null, "www.domain1.com", "www.domain2.com"];
-
- cps.removePrefsByName("test.byname.1");
- do_check_false(cps.hasPref(uri1, "test.byname.1"));
- do_check_false(cps.hasPref(uri2, "test.byname.1"));
- do_check_false(cps.hasPref(uri3, "test.byname.1"));
- do_check_false(cps.hasPref(uri4, "test.byname.1"));
- do_check_false(cps.hasPref(null, "test.byname.1"));
- do_check_true(cps.hasPref(uri1, "test.byname.2"));
- do_check_true(cps.hasPref(uri3, "test.byname.3"));
-
- do_check_eq(anObserver.numTimesRemovedCalled, 4);
- do_check_eq(anObserver.expectedDomains.length, 0);
-
- cps.removeObserver("test.byname.1", anObserver);
-
- // Clean up after ourselves
- cps.removePref(uri1, "test.byname.2");
- cps.removePref(uri3, "test.byname.3");
- cps.removePref(null, "test.byname.2");
- }
-
-
- // Clear Private Data Pref Removal
-
- {
- let uri1 = ContentPrefTest.getURI("http://www.domain1.com/");
- let uri2 = ContentPrefTest.getURI("http://www.domain2.com/");
- let uri3 = ContentPrefTest.getURI("http://www.domain3.com/");
-
- let dbConnection = cps.DBConnection;
-
- let prefCount = dbConnection.createStatement("SELECT COUNT(*) AS count FROM prefs");
-
- let groupCount = dbConnection.createStatement("SELECT COUNT(*) AS count FROM groups");
-
- // Add some prefs for multiple domains.
- cps.setPref(uri1, "test.removeAllGroups", 1);
- cps.setPref(uri2, "test.removeAllGroups", 2);
- cps.setPref(uri3, "test.removeAllGroups", 3);
-
- // Add a global pref.
- cps.setPref(null, "test.removeAllGroups", 1);
-
- // Make sure there are some prefs and groups in the database.
- prefCount.executeStep();
- do_check_true(prefCount.row.count > 0);
- prefCount.reset();
- groupCount.executeStep();
- do_check_true(groupCount.row.count > 0);
- groupCount.reset();
-
- // Remove all prefs and groups from the database using the same routine
- // the Clear Private Data dialog uses.
- cps.removeGroupedPrefs();
-
- // Make sure there are no longer any groups in the database and the only pref
- // is the global one.
- prefCount.executeStep();
- do_check_true(prefCount.row.count == 1);
- prefCount.reset();
- groupCount.executeStep();
- do_check_true(groupCount.row.count == 0);
- groupCount.reset();
- let globalPref = dbConnection.createStatement("SELECT groupID FROM prefs");
- globalPref.executeStep();
- do_check_true(globalPref.row.groupID == null);
- globalPref.reset();
- }
-}
diff --git a/toolkit/components/contentprefs/tests/unit/test_contentPrefsCache.js b/toolkit/components/contentprefs/tests/unit/test_contentPrefsCache.js
deleted file mode 100644
index 38a2faddc..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_contentPrefsCache.js
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var cps = new ContentPrefInstance(null);
-
-function run_test() {
- testCacheWorks("test1.example.com", "test-pref1");
- testHasCachedPrefFunction("test2.example.com", "test-pref2");
- testSetCaches("test3.example.com", "test-pref3");
- testGetCaches("test4.example.com", "test-pref4");
- testRemovePrefs("test5.example.com", "test-pref5");
- testTypeConversions("test6.example.com", "test-pref6");
- testNonExistingPrefCachesAsUndefined("test7.example.com", "test-pref7");
- testCacheEviction("test8.example.com", "test-pref8");
-}
-
-function testCacheWorks(uri, prefName) {
- const CACHED_VALUE = 3;
- const NEW_VALUE = 5;
-
- cps.setPref(uri, prefName, CACHED_VALUE);
- do_check_eq(cps.getPref(uri, prefName), CACHED_VALUE);
-
- // Now change the value directly through the DB and check
- // that the cached value is different
-
- let groupId = selectValue("SELECT id FROM groups WHERE name = :param1", "id", uri);
- let settingId = selectValue("SELECT id FROM settings WHERE name = :param1", "id", prefName);
- let prefId = selectValue("SELECT id FROM prefs WHERE groupID = :param1 AND settingID = :param2",
- "id", groupId, settingId);
-
- let stmt = cps.DBConnection.createStatement("UPDATE prefs SET value = :value WHERE id = :id");
- stmt.params.value = NEW_VALUE;
- stmt.params.id = prefId;
- stmt.execute();
-
- let dbValue = selectValue("SELECT value FROM prefs WHERE id = :param1", "value", prefId);
- let cacheValue = cps.getPref(uri, prefName);
-
- do_check_eq(dbValue, NEW_VALUE);
- do_check_eq(cacheValue, CACHED_VALUE);
- do_check_neq(cacheValue, dbValue);
-
- do_test_pending();
- cps.getPref(uri, prefName, function (value) {
- do_check_eq(dbValue, NEW_VALUE);
- do_check_eq(value, CACHED_VALUE);
- do_check_neq(value, dbValue);
- do_test_finished();
- });
-}
-
-function testHasCachedPrefFunction(uri, prefName) {
- const STARTING_VALUE = 3;
- const NEW_VALUE = 5;
-
- do_check_false(isCached(uri, prefName));
-
- cps.setPref(uri, prefName, STARTING_VALUE);
-
- let groupId = selectValue("SELECT id FROM groups WHERE name = :param1", "id", uri);
- let settingId = selectValue("SELECT id FROM settings WHERE name = :param1", "id", prefName);
- let prefId = selectValue("SELECT id FROM prefs WHERE groupID = :param1 AND settingID = :param2",
- "id", groupId, settingId);
-
- do_check_neq(prefId, undefined);
-
- let originalValue = selectValue("SELECT value FROM prefs WHERE id = :param1", "value", prefId);
- do_check_eq(originalValue, STARTING_VALUE);
-
- let stmt = cps.DBConnection.createStatement("UPDATE prefs SET value = :value WHERE id = :id");
- stmt.params.value = NEW_VALUE;
- stmt.params.id = prefId;
- stmt.execute();
-
- let newValue = selectValue("SELECT value FROM prefs WHERE id = :param1", "value", prefId);
- do_check_eq(newValue, NEW_VALUE);
-
- let cachedValue = cps.getPref(uri, prefName);
- do_check_eq(cachedValue, STARTING_VALUE);
- do_check_true(isCached(uri, prefName));
-}
-
-function testSetCaches(uri, prefName) {
- cps.setPref(uri, prefName, 0);
- do_check_true(isCached(uri, prefName));
-}
-
-function testRemovePrefs(uri, prefName) {
-
- /* removePref */
- cps.setPref("www1." + uri, prefName, 1);
-
- do_check_eq(cps.getPref("www1." + uri, prefName), 1);
-
- cps.removePref("www1." + uri, prefName);
-
- do_check_false(isCached("www1." + uri, prefName));
- do_check_false(cps.hasPref("www1." + uri, prefName));
- do_check_neq(cps.getPref("www1." + uri, prefName), 1);
-
- /* removeGroupedPrefs */
- cps.setPref("www2." + uri, prefName, 2);
- cps.setPref("www3." + uri, prefName, 3);
-
- do_check_eq(cps.getPref("www2." + uri, prefName), 2);
- do_check_eq(cps.getPref("www3." + uri, prefName), 3);
-
- cps.removeGroupedPrefs();
-
- do_check_false(isCached("www2." + uri, prefName));
- do_check_false(isCached("www3." + uri, prefName));
- do_check_false(cps.hasPref("www2." + uri, prefName));
- do_check_false(cps.hasPref("www3." + uri, prefName));
- do_check_neq(cps.getPref("www2." + uri, prefName), 2);
- do_check_neq(cps.getPref("www3." + uri, prefName), 3);
-
- /* removePrefsByName */
- cps.setPref("www4." + uri, prefName, 4);
- cps.setPref("www5." + uri, prefName, 5);
-
- do_check_eq(cps.getPref("www4." + uri, prefName), 4);
- do_check_eq(cps.getPref("www5." + uri, prefName), 5);
-
- cps.removePrefsByName(prefName);
-
- do_check_false(isCached("www4." + uri, prefName));
- do_check_false(isCached("www5." + uri, prefName));
- do_check_false(cps.hasPref("www4." + uri, prefName));
- do_check_false(cps.hasPref("www5." + uri, prefName));
- do_check_neq(cps.getPref("www4." + uri, prefName), 4);
- do_check_neq(cps.getPref("www5." + uri, prefName), 5);
-}
-
-function testGetCaches(uri, prefName) {
- const VALUE = 4;
-
- let insertGroup = cps.DBConnection.createStatement("INSERT INTO groups (name) VALUES (:name)");
- insertGroup.params.name = uri;
- insertGroup.execute();
- let groupId = cps.DBConnection.lastInsertRowID;
-
- let insertSetting = cps.DBConnection.createStatement("INSERT INTO settings (name) VALUES (:name)");
- insertSetting.params.name = prefName;
- insertSetting.execute();
- let settingId = cps.DBConnection.lastInsertRowID;
-
- let insertPref = cps.DBConnection.createStatement(`
- INSERT INTO prefs (groupID, settingID, value)
- VALUES (:groupId, :settingId, :value)
- `);
- insertPref.params.groupId = groupId;
- insertPref.params.settingId = settingId;
- insertPref.params.value = VALUE;
- insertPref.execute();
- let prefId = cps.DBConnection.lastInsertRowID;
-
- let dbValue = selectValue("SELECT value FROM prefs WHERE id = :param1", "value", prefId);
-
- // First access from service should hit the DB
- let svcValue = cps.getPref(uri, prefName);
-
- // Second time should get the value from cache
- let cacheValue = cps.getPref(uri, prefName);
-
- do_check_eq(VALUE, dbValue);
- do_check_eq(VALUE, svcValue);
- do_check_eq(VALUE, cacheValue);
-
- do_check_true(isCached(uri, prefName));
-}
-
-function testTypeConversions(uri, prefName) {
- let value;
-
- cps.setPref(uri, prefName, true);
- value = cps.getPref(uri, prefName);
- do_check_true(value === 1);
-
- cps.setPref(uri, prefName, false);
- value = cps.getPref(uri, prefName);
- do_check_true(value === 0);
-
- cps.setPref(uri, prefName, null);
- value = cps.getPref(uri, prefName);
- do_check_true(value === null);
-
- cps.setPref(uri, prefName, undefined);
- value = cps.getPref(uri, prefName);
- do_check_true(value === null);
-}
-
-function testNonExistingPrefCachesAsUndefined(uri, prefName) {
-
- do_check_false(isCached(uri, prefName));
-
- // Cache the pref
- let value = cps.getPref(uri, prefName);
- do_check_true(value === undefined);
-
- do_check_true(isCached(uri, prefName));
-
- // Cached pref
- value = cps.getPref(uri, prefName);
- do_check_true(value === undefined);
-}
-
-function testCacheEviction(uri, prefName) {
-
- cps.setPref(uri, prefName, 5);
- do_check_eq(cps.getPref(uri, prefName), 5);
- do_check_true(isCached(uri, prefName));
-
- // try to evict value from cache by adding various other entries
- const ENTRIES_TO_ADD = 200;
- for (let i = 0; i < ENTRIES_TO_ADD; i++) {
- let uriToAdd = "www" + i + uri;
- cps.setPref(uriToAdd, prefName, 0);
- }
-
- do_check_false(isCached(uri, prefName));
-
-}
-
-function selectValue(stmt, columnName, param1, param2) {
- stmt = cps.DBConnection.createStatement(stmt);
- if (param1)
- stmt.params.param1 = param1;
-
- if (param2)
- stmt.params.param2 = param2;
-
- stmt.executeStep();
- let val = stmt.row[columnName];
- stmt.reset();
- stmt.finalize();
- return val;
-}
-
-function isCached(uri, prefName) {
- return cps.hasCachedPref(uri, prefName);
-}
diff --git a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js b/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js
deleted file mode 100644
index 27d239f79..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_getPrefAsync.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-var cps = new ContentPrefInstance(null);
-var uri = ContentPrefTest.getURI("http://www.example.com/");
-
-function run_test() {
- do_test_pending();
-
- cps.setPref(uri, "asynctest", "pie");
- do_check_eq(cps.getPref(uri, "asynctest"), "pie");
-
- cps.getPref(uri, "asynctest", function(aValue) {
- do_check_eq(aValue, "pie");
- testCallbackObj();
- });
-}
-
-function testCallbackObj() {
- cps.getPref(uri, "asynctest", {
- onResult: function(aValue) {
- do_check_eq(aValue, "pie");
- cps.removePref(uri, "asynctest");
- testNoResult();
- }
- });
-}
-
-function testNoResult() {
- cps.getPref(uri, "asynctest", function(aValue) {
- do_check_eq(aValue, undefined);
- do_test_finished();
- });
-}
diff --git a/toolkit/components/contentprefs/tests/unit/test_stringGroups.js b/toolkit/components/contentprefs/tests/unit/test_stringGroups.js
deleted file mode 100644
index afce3b64a..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_stringGroups.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/. */
-
-function run_test() {
-
- var cps = new ContentPrefInstance(null);
-
- // Make sure disk synchronization checking is turned off by default.
- var statement = cps.DBConnection.createStatement("PRAGMA synchronous");
- statement.executeStep();
- do_check_eq(0, statement.getInt32(0));
-
- // These are the different types of aGroup arguments we'll test.
- var anObject = {"foo":"bar"}; // a simple object
- var uri = ContentPrefTest.getURI("http://www.example.com/"); // nsIURI
- var stringURI = "www.example.com"; // typeof = "string"
- var stringObjectURI = new String("www.example.com"); // typeof = "object"
-
- {
- // First check that all the methods work or don't work.
- function simple_test_methods(aGroup, shouldThrow) {
- var prefName = "test.pref.0";
- var prefValue = Math.floor(Math.random() * 100);
-
- if (shouldThrow) {
- do_check_thrown(function () { cps.getPref(aGroup, prefName); });
- do_check_thrown(function () { cps.setPref(aGroup, prefName, prefValue); });
- do_check_thrown(function () { cps.hasPref(aGroup, prefName); });
- do_check_thrown(function () { cps.removePref(aGroup, prefName); });
- do_check_thrown(function () { cps.getPrefs(aGroup); });
- } else {
- do_check_eq(cps.setPref(aGroup, prefName, prefValue), undefined);
- do_check_true(cps.hasPref(aGroup, prefName));
- do_check_eq(cps.getPref(aGroup, prefName), prefValue);
- do_check_eq(cps.removePref(aGroup, prefName), undefined);
- do_check_false(cps.hasPref(aGroup, prefName));
- }
- }
-
- simple_test_methods(cps, true); // arbitrary nsISupports object, should throw too
- simple_test_methods(anObject, true);
- simple_test_methods(uri, false);
- simple_test_methods(stringURI, false);
- simple_test_methods(stringObjectURI, false);
- }
-
- {
- // Now we'll check that each argument produces the same result.
- function complex_test_methods(aGroup) {
- var prefName = "test.pref.1";
- var prefValue = Math.floor(Math.random() * 100);
-
- do_check_eq(cps.setPref(aGroup, prefName, prefValue), undefined);
-
- do_check_true(cps.hasPref(uri, prefName));
- do_check_true(cps.hasPref(stringURI, prefName));
- do_check_true(cps.hasPref(stringObjectURI, prefName));
-
- do_check_eq(cps.getPref(uri, prefName), prefValue);
- do_check_eq(cps.getPref(stringURI, prefName), prefValue);
- do_check_eq(cps.getPref(stringObjectURI, prefName), prefValue);
-
- do_check_eq(cps.removePref(aGroup, prefName), undefined);
-
- do_check_false(cps.hasPref(uri, prefName));
- do_check_false(cps.hasPref(stringURI, prefName));
- do_check_false(cps.hasPref(stringObjectURI, prefName));
- }
-
- complex_test_methods(uri);
- complex_test_methods(stringURI);
- complex_test_methods(stringObjectURI);
- }
-
- {
- // test getPrefs returns the same prefs
- do_check_eq(cps.setPref(stringObjectURI, "test.5", 5), undefined);
- do_check_eq(cps.setPref(stringURI, "test.2", 2), undefined);
- do_check_eq(cps.setPref(uri, "test.1", 1), undefined);
-
- enumerateAndCheck(cps.getPrefs(uri), 8, ["test.1", "test.2", "test.5"]);
- enumerateAndCheck(cps.getPrefs(stringURI), 8, ["test.1", "test.2", "test.5"]);
- enumerateAndCheck(cps.getPrefs(stringObjectURI), 8, ["test.1", "test.2", "test.5"]);
-
- do_check_eq(cps.setPref(uri, "test.4", 4), undefined);
- do_check_eq(cps.setPref(stringObjectURI, "test.0", 0), undefined);
-
- enumerateAndCheck(cps.getPrefs(uri), 12, ["test.0", "test.1", "test.2", "test.4", "test.5"]);
- enumerateAndCheck(cps.getPrefs(stringURI), 12, ["test.0", "test.1", "test.2", "test.4", "test.5"]);
- enumerateAndCheck(cps.getPrefs(stringObjectURI), 12, ["test.0", "test.1", "test.2", "test.4", "test.5"]);
-
- do_check_eq(cps.setPref(stringURI, "test.3", 3), undefined);
-
- enumerateAndCheck(cps.getPrefs(uri), 15, ["test.0", "test.1", "test.2", "test.3", "test.4", "test.5"]);
- enumerateAndCheck(cps.getPrefs(stringURI), 15, ["test.0", "test.1", "test.2", "test.3", "test.4", "test.5"]);
- enumerateAndCheck(cps.getPrefs(stringObjectURI), 15, ["test.0", "test.1", "test.2", "test.3", "test.4", "test.5"]);
- }
-}
-
-function do_check_thrown (aCallback) {
- var exThrown = false;
- try {
- aCallback();
- do_throw("NS_ERROR_ILLEGAL_VALUE should have been thrown here");
- } catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_ILLEGAL_VALUE);
- exThrown = true;
- }
- do_check_true(exThrown);
-}
-
-function enumerateAndCheck(prefs, expectedSum, expectedNames) {
- var enumerator = prefs.enumerator;
- var sum = 0;
- while (enumerator.hasMoreElements()) {
- var property = enumerator.getNext().QueryInterface(Components.interfaces.nsIProperty);
- sum += parseInt(property.value);
-
- // remove the pref name from the list of expected names
- var index = expectedNames.indexOf(property.name);
- do_check_true(index >= 0);
- expectedNames.splice(index, 1);
- }
- do_check_eq(sum, expectedSum);
- // check all pref names have been removed from the array
- do_check_eq(expectedNames.length, 0);
-}
diff --git a/toolkit/components/contentprefs/tests/unit/test_unusedGroupsAndSettings.js b/toolkit/components/contentprefs/tests/unit/test_unusedGroupsAndSettings.js
deleted file mode 100644
index 24a86bcc0..000000000
--- a/toolkit/components/contentprefs/tests/unit/test_unusedGroupsAndSettings.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var cps = new ContentPrefInstance(null);
-
-function run_test() {
- var uri1 = ContentPrefTest.getURI("http://www.domain1.com/");
- var uri2 = ContentPrefTest.getURI("http://foo.domain1.com/");
- var uri3 = ContentPrefTest.getURI("http://domain1.com/");
- var uri4 = ContentPrefTest.getURI("http://www.domain2.com/");
-
- cps.setPref(uri1, "one", 1);
- cps.setPref(uri1, "two", 2);
- cps.setPref(uri2, "one", 4);
- cps.setPref(uri3, "three", 8);
- cps.setPref(uri4, "two", 16);
-
- cps.removePref(uri3, "three"); // uri3 should be removed now
- checkForUnusedGroups();
- checkForUnusedSettings();
-
- cps.removePrefsByName("two"); // uri4 should be removed now
- checkForUnusedGroups();
- checkForUnusedSettings();
-
- cps.removeGroupedPrefs();
- checkForUnusedGroups();
- checkForUnusedSettings();
-}
-
-function checkForUnusedGroups() {
- var stmt = cps.DBConnection.createStatement(`
- SELECT COUNT(*) AS count FROM groups
- WHERE id NOT IN (SELECT DISTINCT groupID FROM prefs)
- `);
- stmt.executeStep();
- do_check_eq(0, stmt.row.count);
- stmt.reset();
- stmt.finalize();
-}
-
-function checkForUnusedSettings() {
- var stmt = cps.DBConnection.createStatement(`
- SELECT COUNT(*) AS count FROM settings
- WHERE id NOT IN (SELECT DISTINCT settingID FROM prefs)
- `);
- stmt.executeStep();
- do_check_eq(0, stmt.row.count);
- stmt.reset();
- stmt.finalize();
-}
diff --git a/toolkit/components/contentprefs/tests/unit/xpcshell.ini b/toolkit/components/contentprefs/tests/unit/xpcshell.ini
deleted file mode 100644
index cbae178b1..000000000
--- a/toolkit/components/contentprefs/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-head = head_contentPrefs.js
-tail = tail_contentPrefs.js
-
-[test_bug248970.js]
-[test_bug503971.js]
-[test_bug679784.js]
-[test_contentPrefs.js]
-[test_contentPrefsCache.js]
-[test_getPrefAsync.js]
-[test_stringGroups.js]
-[test_unusedGroupsAndSettings.js]
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/.eslintrc.js b/toolkit/components/contentprefs/tests/unit_cps2/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/AsyncRunner.jsm b/toolkit/components/contentprefs/tests/unit_cps2/AsyncRunner.jsm
deleted file mode 100644
index ac878c28c..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/AsyncRunner.jsm
+++ /dev/null
@@ -1,69 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var EXPORTED_SYMBOLS = [
- "AsyncRunner",
-];
-
-const { interfaces: Ci, classes: Cc } = Components;
-
-function AsyncRunner(callbacks) {
- this._callbacks = callbacks;
- this._iteratorQueue = [];
-
- // This catches errors reported to the console, e.g., via Cu.reportError.
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- registerListener(this);
-}
-
-AsyncRunner.prototype = {
-
- appendIterator: function AR_appendIterator(iter) {
- this._iteratorQueue.push(iter);
- },
-
- next: function AR_next(arg) {
- if (!this._iteratorQueue.length) {
- this.destroy();
- this._callbacks.done();
- return;
- }
-
- try {
- var { done, value } = this._iteratorQueue[0].next(arg);
- if (done) {
- this._iteratorQueue.shift();
- this.next();
- return;
- }
- }
- catch (err) {
- this._callbacks.error(err);
- }
-
- // val is truthy => call next
- // val is an iterator => prepend it to the queue and start on it
- if (value) {
- if (typeof(value) != "boolean")
- this._iteratorQueue.unshift(value);
- this.next();
- }
- },
-
- destroy: function AR_destroy() {
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- unregisterListener(this);
- this.destroy = function AR_alreadyDestroyed() {};
- },
-
- observe: function AR_consoleServiceListener(msg) {
- if (msg instanceof Ci.nsIScriptError &&
- !(msg.flags & Ci.nsIScriptError.warningFlag))
- {
- this._callbacks.consoleError(msg);
- }
- },
-};
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/head.js b/toolkit/components/contentprefs/tests/unit_cps2/head.js
deleted file mode 100644
index b86abe208..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/head.js
+++ /dev/null
@@ -1,401 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 { interfaces: Ci, classes: Cc, results: Cr, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-var cps;
-var asyncRunner;
-var next;
-
-(function init() {
- // There has to be a profile directory before the CPS service is gotten.
- do_get_profile();
-})();
-
-function runAsyncTests(tests, dontResetBefore = false) {
- do_test_pending();
-
- cps = Cc["@mozilla.org/content-pref/service;1"].
- getService(Ci.nsIContentPrefService2);
-
- let s = {};
- Cu.import("resource://test/AsyncRunner.jsm", s);
- asyncRunner = new s.AsyncRunner({
- done: do_test_finished,
- error: function (err) {
- // xpcshell test functions like equal throw NS_ERROR_ABORT on
- // failure. Ignore those and catch only uncaught exceptions.
- if (err !== Cr.NS_ERROR_ABORT) {
- if (err.stack) {
- err = err + "\n\nTraceback (most recent call first):\n" + err.stack +
- "\nUseless do_throw stack:";
- }
- do_throw(err);
- }
- },
- consoleError: function (scriptErr) {
- // Previously, this code checked for console errors related to the test,
- // and treated them as failures. This was problematic, because our current
- // very-broken exception reporting machinery in XPCWrappedJSClass reports
- // errors to the console even if there's actually JS on the stack above
- // that will catch them. And a lot of the tests here intentionally trigger
- // error conditions on the JS-implemented XPCOM component (see erroneous()
- // in test_getSubdomains.js, for example). In the old world, we got lucky,
- // and the errors were never reported to the console due to happenstantial
- // JSContext reasons that aren't really worth going into.
- //
- // So. We make sure to dump this stuff so that it shows up in the logs, but
- // don't turn them into duplicate failures of the exception that was already
- // propagated to the caller.
- dump("AsyncRunner.jsm observed console error: " + scriptErr + "\n");
- }
- });
-
- next = asyncRunner.next.bind(asyncRunner);
-
- do_register_cleanup(function () {
- asyncRunner.destroy();
- asyncRunner = null;
- });
-
- tests.forEach(function (test) {
- function* gen() {
- do_print("Running " + test.name);
- yield test();
- yield reset();
- }
- asyncRunner.appendIterator(gen());
- });
-
- // reset() ends up calling asyncRunner.next(), starting the tests.
- if (dontResetBefore) {
- next();
- } else {
- reset();
- }
-}
-
-function makeCallback(callbacks, success = null) {
- callbacks = callbacks || {};
- if (!callbacks.handleError) {
- callbacks.handleError = function (error) {
- do_throw("handleError call was not expected, error: " + error);
- };
- }
- if (!callbacks.handleResult) {
- callbacks.handleResult = function() {
- do_throw("handleResult call was not expected");
- };
- }
- if (!callbacks.handleCompletion)
- callbacks.handleCompletion = function (reason) {
- equal(reason, Ci.nsIContentPrefCallback2.COMPLETE_OK);
- if (success) {
- success();
- } else {
- next();
- }
- };
- return callbacks;
-}
-
-function do_check_throws(fn) {
- let threw = false;
- try {
- fn();
- }
- catch (err) {
- threw = true;
- }
- ok(threw);
-}
-
-function sendMessage(msg, callback) {
- let obj = callback || {};
- let ref = Cu.getWeakReference(obj);
- cps.QueryInterface(Ci.nsIObserver).observe(ref, "test:" + msg, null);
- return "value" in obj ? obj.value : undefined;
-}
-
-function reset() {
- sendMessage("reset", next);
-}
-
-function setWithDate(group, name, val, timestamp, context) {
- function updateDate() {
- let db = sendMessage("db");
- let stmt = db.createAsyncStatement(`
- UPDATE prefs SET timestamp = :timestamp
- WHERE
- settingID = (SELECT id FROM settings WHERE name = :name)
- AND groupID = (SELECT id FROM groups WHERE name = :group)
- `);
- stmt.params.timestamp = timestamp / 1000;
- stmt.params.name = name;
- stmt.params.group = group;
-
- stmt.executeAsync({
- handleCompletion: function (reason) {
- next();
- },
- handleError: function (err) {
- do_throw(err);
- }
- });
- stmt.finalize();
- }
-
- cps.set(group, name, val, context, makeCallback(null, updateDate));
-}
-
-function getDate(group, name, context) {
- let db = sendMessage("db");
- let stmt = db.createAsyncStatement(`
- SELECT timestamp FROM prefs
- WHERE
- settingID = (SELECT id FROM settings WHERE name = :name)
- AND groupID = (SELECT id FROM groups WHERE name = :group)
- `);
- stmt.params.name = name;
- stmt.params.group = group;
-
- let res;
- stmt.executeAsync({
- handleResult: function (results) {
- let row = results.getNextRow();
- res = row.getResultByName("timestamp");
- },
- handleCompletion: function (reason) {
- next(res * 1000);
- },
- handleError: function (err) {
- do_throw(err);
- }
- });
- stmt.finalize();
-}
-
-function set(group, name, val, context) {
- cps.set(group, name, val, context, makeCallback());
-}
-
-function setGlobal(name, val, context) {
- cps.setGlobal(name, val, context, makeCallback());
-}
-
-function prefOK(actual, expected, strict) {
- ok(actual instanceof Ci.nsIContentPref);
- equal(actual.domain, expected.domain);
- equal(actual.name, expected.name);
- if (strict)
- strictEqual(actual.value, expected.value);
- else
- equal(actual.value, expected.value);
-}
-
-function* getOK(args, expectedVal, expectedGroup, strict) {
- if (args.length == 2)
- args.push(undefined);
- let expectedPrefs = expectedVal === undefined ? [] :
- [{ domain: expectedGroup || args[0],
- name: args[1],
- value: expectedVal }];
- yield getOKEx("getByDomainAndName", args, expectedPrefs, strict);
-}
-
-function* getSubdomainsOK(args, expectedGroupValPairs) {
- if (args.length == 2)
- args.push(undefined);
- let expectedPrefs = expectedGroupValPairs.map(function ([group, val]) {
- return { domain: group, name: args[1], value: val };
- });
- yield getOKEx("getBySubdomainAndName", args, expectedPrefs);
-}
-
-function* getGlobalOK(args, expectedVal) {
- if (args.length == 1)
- args.push(undefined);
- let expectedPrefs = expectedVal === undefined ? [] :
- [{ domain: null, name: args[0], value: expectedVal }];
- yield getOKEx("getGlobal", args, expectedPrefs);
-}
-
-function* getOKEx(methodName, args, expectedPrefs, strict, context) {
- let actualPrefs = [];
- args.push(makeCallback({
- handleResult: pref => actualPrefs.push(pref)
- }));
- yield cps[methodName].apply(cps, args);
- arraysOfArraysOK([actualPrefs], [expectedPrefs], function (actual, expected) {
- prefOK(actual, expected, strict);
- });
-}
-
-function getCachedOK(args, expectedIsCached, expectedVal, expectedGroup,
- strict) {
- if (args.length == 2)
- args.push(undefined);
- let expectedPref = !expectedIsCached ? null : {
- domain: expectedGroup || args[0],
- name: args[1],
- value: expectedVal
- };
- getCachedOKEx("getCachedByDomainAndName", args, expectedPref, strict);
-}
-
-function getCachedSubdomainsOK(args, expectedGroupValPairs) {
- if (args.length == 2)
- args.push(undefined);
- let len = {};
- args.push(len);
- let actualPrefs = cps.getCachedBySubdomainAndName.apply(cps, args);
- actualPrefs = actualPrefs.sort(function (a, b) {
- return a.domain.localeCompare(b.domain);
- });
- equal(actualPrefs.length, len.value);
- let expectedPrefs = expectedGroupValPairs.map(function ([group, val]) {
- return { domain: group, name: args[1], value: val };
- });
- arraysOfArraysOK([actualPrefs], [expectedPrefs], prefOK);
-}
-
-function getCachedGlobalOK(args, expectedIsCached, expectedVal) {
- if (args.length == 1)
- args.push(undefined);
- let expectedPref = !expectedIsCached ? null : {
- domain: null,
- name: args[0],
- value: expectedVal
- };
- getCachedOKEx("getCachedGlobal", args, expectedPref);
-}
-
-function getCachedOKEx(methodName, args, expectedPref, strict) {
- let actualPref = cps[methodName].apply(cps, args);
- if (expectedPref)
- prefOK(actualPref, expectedPref, strict);
- else
- strictEqual(actualPref, null);
-}
-
-function arraysOK(actual, expected, cmp) {
- if (actual.length != expected.length) {
- do_throw("Length is not equal: " + JSON.stringify(actual) + "==" + JSON.stringify(expected));
- } else {
- actual.forEach(function (actualElt, j) {
- let expectedElt = expected[j];
- cmp(actualElt, expectedElt);
- });
- }
-}
-
-function arraysOfArraysOK(actual, expected, cmp) {
- cmp = cmp || equal;
- arraysOK(actual, expected, function (act, exp) {
- arraysOK(act, exp, cmp)
- });
-}
-
-function dbOK(expectedRows) {
- let db = sendMessage("db");
- let stmt = db.createAsyncStatement(`
- SELECT groups.name AS grp, settings.name AS name, prefs.value AS value
- FROM prefs
- LEFT JOIN groups ON groups.id = prefs.groupID
- LEFT JOIN settings ON settings.id = prefs.settingID
- UNION
-
- /*
- These second two SELECTs get the rows of the groups and settings tables
- that aren't referenced by the prefs table. Neither should return any
- rows if the component is working properly.
- */
- SELECT groups.name AS grp, NULL AS name, NULL AS value
- FROM groups
- WHERE id NOT IN (
- SELECT DISTINCT groupID
- FROM prefs
- WHERE groupID NOTNULL
- )
- UNION
- SELECT NULL AS grp, settings.name AS name, NULL AS value
- FROM settings
- WHERE id NOT IN (
- SELECT DISTINCT settingID
- FROM prefs
- WHERE settingID NOTNULL
- )
-
- ORDER BY value ASC, grp ASC, name ASC
- `);
-
- let actualRows = [];
- let cols = ["grp", "name", "value"];
-
- db.executeAsync([stmt], 1, {
- handleCompletion: function (reason) {
- arraysOfArraysOK(actualRows, expectedRows);
- next();
- },
- handleResult: function (results) {
- let row = null;
- while (row = results.getNextRow()) {
- actualRows.push(cols.map(c => row.getResultByName(c)));
- }
- },
- handleError: function (err) {
- do_throw(err);
- }
- });
- stmt.finalize();
-}
-
-function on(event, names, dontRemove) {
- let args = {
- reset: function () {
- for (let prop in this) {
- if (Array.isArray(this[prop]))
- this[prop].splice(0, this[prop].length);
- }
- },
- };
-
- let observers = {};
-
- names.forEach(function (name) {
- let obs = {};
- ["onContentPrefSet", "onContentPrefRemoved"].forEach(function (meth) {
- obs[meth] = () => do_throw(meth + " should not be called");
- });
- obs["onContentPref" + event] = function () {
- args[name].push(Array.slice(arguments));
- };
- observers[name] = obs;
- args[name] = [];
- args[name].observer = obs;
- cps.addObserverForName(name, obs);
- });
-
- do_execute_soon(function () {
- if (!dontRemove)
- names.forEach(n => cps.removeObserverForName(n, observers[n]));
- next(args);
- });
-}
-
-function schemaVersionIs(expectedVersion) {
- let db = sendMessage("db");
- equal(db.schemaVersion, expectedVersion);
-}
-
-function wait() {
- do_execute_soon(next);
-}
-
-function observerArgsOK(actualArgs, expectedArgs) {
- notEqual(actualArgs, undefined);
- arraysOfArraysOK(actualArgs, expectedArgs);
-}
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_extractDomain.js b/toolkit/components/contentprefs/tests/unit_cps2/test_extractDomain.js
deleted file mode 100644
index 2ec3d6878..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_extractDomain.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- let tests = {
- "http://example.com": "example.com",
- "http://example.com/": "example.com",
- "http://example.com/foo/bar/baz": "example.com",
- "http://subdomain.example.com/foo/bar/baz": "subdomain.example.com",
- "http://qix.quux.example.com/foo/bar/baz": "qix.quux.example.com",
- "file:///home/foo/bar": "file:///home/foo/bar",
- "not a url": "not a url",
- };
- let cps = Cc["@mozilla.org/content-pref/service;1"].
- getService(Ci.nsIContentPrefService2);
- for (let url in tests) {
- do_check_eq(cps.extractDomain(url), tests[url]);
- }
-}
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_getCached.js b/toolkit/components/contentprefs/tests/unit_cps2/test_getCached.js
deleted file mode 100644
index 33a965b7f..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_getCached.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* nonexistent() {
- getCachedOK(["a.com", "foo"], false, undefined);
- getCachedGlobalOK(["foo"], false, undefined);
- yield true;
- },
-
- function* isomorphicDomains() {
- yield set("a.com", "foo", 1);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["http://a.com/huh", "foo"], true, 1, "a.com");
- },
-
- function* names() {
- yield set("a.com", "foo", 1);
- getCachedOK(["a.com", "foo"], true, 1);
-
- yield set("a.com", "bar", 2);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["a.com", "bar"], true, 2);
-
- yield setGlobal("foo", 3);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["a.com", "bar"], true, 2);
- getCachedGlobalOK(["foo"], true, 3);
-
- yield setGlobal("bar", 4);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["a.com", "bar"], true, 2);
- getCachedGlobalOK(["foo"], true, 3);
- getCachedGlobalOK(["bar"], true, 4);
- },
-
- function* subdomains() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["b.a.com", "foo"], true, 2);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 6, context);
- yield setGlobal("foo", 7, context);
- getCachedOK(["a.com", "foo", context], true, 6);
- getCachedOK(["a.com", "bar", context], true, 2);
- getCachedGlobalOK(["foo", context], true, 7);
- getCachedGlobalOK(["bar", context], true, 4);
- getCachedOK(["b.com", "foo", context], true, 5);
-
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["a.com", "bar"], true, 2);
- getCachedGlobalOK(["foo"], true, 3);
- getCachedGlobalOK(["bar"], true, 4);
- getCachedOK(["b.com", "foo"], true, 5);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.getCachedByDomainAndName(null, "foo", null));
- do_check_throws(() => cps.getCachedByDomainAndName("", "foo", null));
- do_check_throws(() => cps.getCachedByDomainAndName("a.com", "", null));
- do_check_throws(() => cps.getCachedByDomainAndName("a.com", null, null));
- do_check_throws(() => cps.getCachedGlobal("", null));
- do_check_throws(() => cps.getCachedGlobal(null, null));
- yield true;
- },
-
- function* casts() {
- // SQLite casts booleans to integers. This makes sure the values stored in
- // the cache are the same as the casted values in the database.
-
- yield set("a.com", "foo", false);
- yield getOK(["a.com", "foo"], 0, "a.com", true);
- getCachedOK(["a.com", "foo"], true, 0, "a.com", true);
-
- yield set("a.com", "bar", true);
- yield getOK(["a.com", "bar"], 1, "a.com", true);
- getCachedOK(["a.com", "bar"], true, 1, "a.com", true);
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_getCachedSubdomains.js b/toolkit/components/contentprefs/tests/unit_cps2/test_getCachedSubdomains.js
deleted file mode 100644
index 9f2599708..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_getCachedSubdomains.js
+++ /dev/null
@@ -1,186 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* nonexistent() {
- getCachedSubdomainsOK(["a.com", "foo"], []);
- yield true;
- },
-
- function* isomorphicDomains() {
- yield set("a.com", "foo", 1);
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- getCachedSubdomainsOK(["http://a.com/huh", "foo"], [["a.com", 1]]);
- },
-
- function* names() {
- yield set("a.com", "foo", 1);
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
-
- yield set("a.com", "bar", 2);
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- getCachedSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
-
- yield setGlobal("foo", 3);
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- getCachedSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
- getCachedGlobalOK(["foo"], true, 3);
-
- yield setGlobal("bar", 4);
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- getCachedSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
- getCachedGlobalOK(["foo"], true, 3);
- getCachedGlobalOK(["bar"], true, 4);
- },
-
- function* subdomains() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", 1], ["b.a.com", 2]]);
- getCachedSubdomainsOK(["b.a.com", "foo"], [["b.a.com", 2]]);
- },
-
- function* populateViaGet() {
- yield cps.getByDomainAndName("a.com", "foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
-
- yield cps.getGlobal("foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- getCachedGlobalOK(["foo"], true, undefined);
- },
-
- function* populateViaGetSubdomains() {
- yield cps.getBySubdomainAndName("a.com", "foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- },
-
- function* populateViaRemove() {
- yield cps.removeByDomainAndName("a.com", "foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
-
- yield cps.removeBySubdomainAndName("b.com", "foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- getCachedSubdomainsOK(["b.com", "foo"], [["b.com", undefined]]);
-
- yield cps.removeGlobal("foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- getCachedSubdomainsOK(["b.com", "foo"], [["b.com", undefined]]);
- getCachedGlobalOK(["foo"], true, undefined);
-
- yield set("a.com", "foo", 1);
- yield cps.removeByDomainAndName("a.com", "foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- getCachedSubdomainsOK(["b.com", "foo"], [["b.com", undefined]]);
- getCachedGlobalOK(["foo"], true, undefined);
-
- yield set("a.com", "foo", 2);
- yield set("b.a.com", "foo", 3);
- yield cps.removeBySubdomainAndName("a.com", "foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"],
- [["a.com", undefined], ["b.a.com", undefined]]);
- getCachedSubdomainsOK(["b.com", "foo"], [["b.com", undefined]]);
- getCachedGlobalOK(["foo"], true, undefined);
- getCachedSubdomainsOK(["b.a.com", "foo"], [["b.a.com", undefined]]);
-
- yield setGlobal("foo", 4);
- yield cps.removeGlobal("foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"],
- [["a.com", undefined], ["b.a.com", undefined]]);
- getCachedSubdomainsOK(["b.com", "foo"], [["b.com", undefined]]);
- getCachedGlobalOK(["foo"], true, undefined);
- getCachedSubdomainsOK(["b.a.com", "foo"], [["b.a.com", undefined]]);
- },
-
- function* populateViaRemoveByDomain() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield set("b.a.com", "foo", 3);
- yield set("b.a.com", "bar", 4);
- yield cps.removeByDomain("a.com", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"],
- [["a.com", undefined], ["b.a.com", 3]]);
- getCachedSubdomainsOK(["a.com", "bar"],
- [["a.com", undefined], ["b.a.com", 4]]);
-
- yield set("a.com", "foo", 5);
- yield set("a.com", "bar", 6);
- yield cps.removeBySubdomain("a.com", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"],
- [["a.com", undefined], ["b.a.com", undefined]]);
- getCachedSubdomainsOK(["a.com", "bar"],
- [["a.com", undefined], ["b.a.com", undefined]]);
-
- yield setGlobal("foo", 7);
- yield setGlobal("bar", 8);
- yield cps.removeAllGlobals(null, makeCallback());
- getCachedGlobalOK(["foo"], true, undefined);
- getCachedGlobalOK(["bar"], true, undefined);
- },
-
- function* populateViaRemoveAllDomains() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield set("b.com", "foo", 3);
- yield set("b.com", "bar", 4);
- yield cps.removeAllDomains(null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- getCachedSubdomainsOK(["a.com", "bar"], [["a.com", undefined]]);
- getCachedSubdomainsOK(["b.com", "foo"], [["b.com", undefined]]);
- getCachedSubdomainsOK(["b.com", "bar"], [["b.com", undefined]]);
- },
-
- function* populateViaRemoveByName() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield cps.removeByName("foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- getCachedSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
- getCachedGlobalOK(["foo"], true, undefined);
- getCachedGlobalOK(["bar"], true, 4);
-
- yield cps.removeByName("bar", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", undefined]]);
- getCachedSubdomainsOK(["a.com", "bar"], [["a.com", undefined]]);
- getCachedGlobalOK(["foo"], true, undefined);
- getCachedGlobalOK(["bar"], true, undefined);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 6, context);
- yield setGlobal("foo", 7, context);
- getCachedSubdomainsOK(["a.com", "foo", context], [["a.com", 6]]);
- getCachedSubdomainsOK(["a.com", "bar", context], [["a.com", 2]]);
- getCachedGlobalOK(["foo", context], true, 7);
- getCachedGlobalOK(["bar", context], true, 4);
- getCachedSubdomainsOK(["b.com", "foo", context], [["b.com", 5]]);
-
- getCachedSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- getCachedSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
- getCachedGlobalOK(["foo"], true, 3);
- getCachedGlobalOK(["bar"], true, 4);
- getCachedSubdomainsOK(["b.com", "foo"], [["b.com", 5]]);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.getCachedBySubdomainAndName(null, "foo", null));
- do_check_throws(() => cps.getCachedBySubdomainAndName("", "foo", null));
- do_check_throws(() => cps.getCachedBySubdomainAndName("a.com", "", null));
- do_check_throws(() => cps.getCachedBySubdomainAndName("a.com", null, null));
- yield true;
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_getSubdomains.js b/toolkit/components/contentprefs/tests/unit_cps2/test_getSubdomains.js
deleted file mode 100644
index d08d6fe69..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_getSubdomains.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* get_nonexistent() {
- yield getSubdomainsOK(["a.com", "foo"], []);
- },
-
- function* isomorphicDomains() {
- yield set("a.com", "foo", 1);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- yield getSubdomainsOK(["http://a.com/huh", "foo"], [["a.com", 1]]);
- },
-
- function* names() {
- yield set("a.com", "foo", 1);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
-
- yield set("a.com", "bar", 2);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- yield getSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
-
- yield setGlobal("foo", 3);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- yield getSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
- },
-
- function* subdomains() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 1], ["b.a.com", 2]]);
- yield getSubdomainsOK(["b.a.com", "foo"], [["b.a.com", 2]]);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 6, context);
- yield setGlobal("foo", 7, context);
- yield getSubdomainsOK(["a.com", "foo", context], [["a.com", 6]]);
- yield getSubdomainsOK(["a.com", "bar", context], [["a.com", 2]]);
- yield getSubdomainsOK(["b.com", "foo", context], [["b.com", 5]]);
-
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 1]]);
- yield getSubdomainsOK(["a.com", "bar"], [["a.com", 2]]);
- yield getSubdomainsOK(["b.com", "foo"], [["b.com", 5]]);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.getBySubdomainAndName(null, "foo", null, {}));
- do_check_throws(() => cps.getBySubdomainAndName("", "foo", null, {}));
- do_check_throws(() => cps.getBySubdomainAndName("a.com", "", null, {}));
- do_check_throws(() => cps.getBySubdomainAndName("a.com", null, null, {}));
- do_check_throws(() => cps.getBySubdomainAndName("a.com", "foo", null, null));
- yield true;
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_migrationToSchema4.js b/toolkit/components/contentprefs/tests/unit_cps2/test_migrationToSchema4.js
deleted file mode 100644
index 85d23e355..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_migrationToSchema4.js
+++ /dev/null
@@ -1,82 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Dump of version we migrate from
-var schema_version3 = `
-PRAGMA foreign_keys=OFF;
-BEGIN TRANSACTION;
- CREATE TABLE groups (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
- INSERT INTO "groups" VALUES(1,'foo.com');
- INSERT INTO "groups" VALUES(2,'bar.com');
-
- CREATE TABLE settings (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
- INSERT INTO "settings" VALUES(1,'zoom-setting');
- INSERT INTO "settings" VALUES(2,'dir-setting');
-
- CREATE TABLE prefs (id INTEGER PRIMARY KEY, groupID INTEGER REFERENCES groups(id), settingID INTEGER NOT NULL REFERENCES settings(id), value BLOB);
- INSERT INTO "prefs" VALUES(1,1,1,0.5);
- INSERT INTO "prefs" VALUES(2,1,2,'/download/dir');
- INSERT INTO "prefs" VALUES(3,2,1,0.3);
- INSERT INTO "prefs" VALUES(4,NULL,1,0.1);
-
- CREATE INDEX groups_idx ON groups(name);
- CREATE INDEX settings_idx ON settings(name);
- CREATE INDEX prefs_idx ON prefs(groupID, settingID);
-COMMIT;`;
-
-function prepareVersion3Schema(callback) {
- var dirService = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
-
- var dbFile = dirService.get("ProfD", Ci.nsIFile);
- dbFile.append("content-prefs.sqlite");
-
- var dbService = Cc["@mozilla.org/storage/service;1"].
- getService(Ci.mozIStorageService);
- ok(!dbFile.exists(), "Db should not exist yet.");
-
- var dbConnection = dbService.openDatabase(dbFile);
- equal(dbConnection.schemaVersion, 0);
-
- dbConnection.executeSimpleSQL(schema_version3);
- dbConnection.schemaVersion = 3;
-
- dbConnection.close();
-}
-
-function run_test() {
- prepareVersion3Schema();
- runAsyncTests(tests, true);
-}
-
-
-// WARNING: Database will reset after every test. This limitation comes from
-// the fact that we ContentPrefService constructor is run only once per test file
-// and so migration will be run only once.
-var tests = [
- function* testMigration() {
- // Test migrated db content.
- schemaVersionIs(4);
- let dbExpectedState = [
- [null, "zoom-setting", 0.1],
- ["bar.com", "zoom-setting", 0.3],
- ["foo.com", "zoom-setting", 0.5],
- ["foo.com", "dir-setting", "/download/dir"],
- ];
- yield dbOK(dbExpectedState);
-
- // Migrated fields should have timestamp set to 0.
- yield cps.removeAllDomainsSince(1000, null, makeCallback());
- yield dbOK(dbExpectedState);
-
- yield cps.removeAllDomainsSince(0, null, makeCallback());
- yield dbOK([[null, "zoom-setting", 0.1]]);
-
- // Test that dates are present after migration (column is added).
- const timestamp = 1234;
- yield setWithDate("a.com", "pref-name", "val", timestamp);
- let actualTimestamp = yield getDate("a.com", "pref-name");
- equal(actualTimestamp, timestamp);
- }
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_observers.js b/toolkit/components/contentprefs/tests/unit_cps2/test_observers.js
deleted file mode 100644
index c48918cd9..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_observers.js
+++ /dev/null
@@ -1,178 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-let global = this;
-
-function run_test() {
- var allTests = [];
- for (var i = 0; i < tests.length; i++) {
- // Generate two wrappers of each test function that invoke the original test with an
- // appropriate privacy context.
- var pub = eval('var f = function* ' + tests[i].name + '() { yield tests[' + i + ']({ usePrivateBrowsing: false }); }; f');
- var priv = eval('var f = function* ' + tests[i].name + '_private() { yield tests[' + i + ']({ usePrivateBrowsing: true }); }; f');
- allTests.push(pub);
- allTests.push(priv);
- }
- allTests = allTests.concat(specialTests);
- runAsyncTests(allTests);
-}
-
-var tests = [
-
- function* observerForName_set(context) {
- yield set("a.com", "foo", 1, context);
- let args = yield on("Set", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [["a.com", "foo", 1, context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [["a.com", "foo", 1, context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, []);
-
- yield setGlobal("foo", 2, context);
- args = yield on("Set", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [[null, "foo", 2, context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [[null, "foo", 2, context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, []);
- },
-
- function* observerForName_remove(context) {
- yield set("a.com", "foo", 1, context);
- yield setGlobal("foo", 2, context);
-
- yield cps.removeByDomainAndName("a.com", "bogus", context, makeCallback());
- let args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, []);
- observerArgsOK(args.null, []);
- observerArgsOK(args.bar, []);
-
- yield cps.removeByDomainAndName("a.com", "foo", context, makeCallback());
- args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [["a.com", "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [["a.com", "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, []);
-
- yield cps.removeGlobal("foo", context, makeCallback());
- args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [[null, "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [[null, "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, []);
- },
-
- function* observerForName_removeByDomain(context) {
- yield set("a.com", "foo", 1, context);
- yield set("b.a.com", "bar", 2, context);
- yield setGlobal("foo", 3, context);
-
- yield cps.removeByDomain("bogus", context, makeCallback());
- let args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, []);
- observerArgsOK(args.null, []);
- observerArgsOK(args.bar, []);
-
- yield cps.removeBySubdomain("a.com", context, makeCallback());
- args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [["a.com", "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [["a.com", "foo", context.usePrivateBrowsing], ["b.a.com", "bar", context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, [["b.a.com", "bar", context.usePrivateBrowsing]]);
-
- yield cps.removeAllGlobals(context, makeCallback());
- args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [[null, "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [[null, "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, []);
- },
-
- function* observerForName_removeAllDomains(context) {
- yield set("a.com", "foo", 1, context);
- yield setGlobal("foo", 2, context);
- yield set("b.com", "bar", 3, context);
-
- yield cps.removeAllDomains(context, makeCallback());
- let args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [["a.com", "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [["a.com", "foo", context.usePrivateBrowsing], ["b.com", "bar", context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, [["b.com", "bar", context.usePrivateBrowsing]]);
- },
-
- function* observerForName_removeByName(context) {
- yield set("a.com", "foo", 1, context);
- yield set("a.com", "bar", 2, context);
- yield setGlobal("foo", 3, context);
-
- yield cps.removeByName("bogus", context, makeCallback());
- let args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, []);
- observerArgsOK(args.null, []);
- observerArgsOK(args.bar, []);
-
- yield cps.removeByName("foo", context, makeCallback());
- args = yield on("Removed", ["foo", null, "bar"]);
- observerArgsOK(args.foo, [["a.com", "foo", context.usePrivateBrowsing], [null, "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.null, [["a.com", "foo", context.usePrivateBrowsing], [null, "foo", context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, []);
- },
-
- function* removeObserverForName(context) {
- let args = yield on("Set", ["foo", null, "bar"], true);
-
- cps.removeObserverForName("foo", args.foo.observer);
- yield set("a.com", "foo", 1, context);
- yield wait();
- observerArgsOK(args.foo, []);
- observerArgsOK(args.null, [["a.com", "foo", 1, context.usePrivateBrowsing]]);
- observerArgsOK(args.bar, []);
- args.reset();
-
- cps.removeObserverForName(null, args.null.observer);
- yield set("a.com", "foo", 2, context);
- yield wait();
- observerArgsOK(args.foo, []);
- observerArgsOK(args.null, []);
- observerArgsOK(args.bar, []);
- args.reset();
- },
-];
-
-// These tests are for functionality that doesn't behave the same way in private and public
-// contexts, so the expected results cannot be automatically generated like the previous tests.
-var specialTests = [
- function* observerForName_removeAllDomainsSince() {
- yield setWithDate("a.com", "foo", 1, 100, null);
- yield setWithDate("b.com", "foo", 2, 200, null);
- yield setWithDate("c.com", "foo", 3, 300, null);
-
- yield setWithDate("a.com", "bar", 1, 0, null);
- yield setWithDate("b.com", "bar", 2, 100, null);
- yield setWithDate("c.com", "bar", 3, 200, null);
- yield setGlobal("foo", 2, null);
-
- yield cps.removeAllDomainsSince(200, null, makeCallback());
-
- let args = yield on("Removed", ["foo", "bar", null]);
-
- observerArgsOK(args.foo, [["b.com", "foo", false], ["c.com", "foo", false]]);
- observerArgsOK(args.bar, [["c.com", "bar", false]]);
- observerArgsOK(args.null, [["b.com", "foo", false], ["c.com", "bar", false], ["c.com", "foo", false]]);
- },
-
- function* observerForName_removeAllDomainsSince_private() {
- let context = {usePrivateBrowsing: true};
- yield setWithDate("a.com", "foo", 1, 100, context);
- yield setWithDate("b.com", "foo", 2, 200, context);
- yield setWithDate("c.com", "foo", 3, 300, context);
-
- yield setWithDate("a.com", "bar", 1, 0, context);
- yield setWithDate("b.com", "bar", 2, 100, context);
- yield setWithDate("c.com", "bar", 3, 200, context);
- yield setGlobal("foo", 2, context);
-
- yield cps.removeAllDomainsSince(200, context, makeCallback());
-
- let args = yield on("Removed", ["foo", "bar", null]);
-
- observerArgsOK(args.foo, [["a.com", "foo", true], ["b.com", "foo", true], ["c.com", "foo", true]]);
- observerArgsOK(args.bar, [["a.com", "bar", true], ["b.com", "bar", true], ["c.com", "bar", true]]);
- observerArgsOK(args.null, [["a.com", "foo", true], ["a.com", "bar", true],
- ["b.com", "foo", true], ["b.com", "bar", true],
- ["c.com", "foo", true], ["c.com", "bar", true]]);
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_remove.js b/toolkit/components/contentprefs/tests/unit_cps2/test_remove.js
deleted file mode 100644
index 9853293fc..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_remove.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/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* nonexistent() {
- yield set("a.com", "foo", 1);
- yield setGlobal("foo", 2);
-
- yield cps.removeByDomainAndName("a.com", "bogus", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getGlobalOK(["foo"], 2);
-
- yield cps.removeBySubdomainAndName("a.com", "bogus", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getGlobalOK(["foo"], 2);
-
- yield cps.removeGlobal("bogus", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getGlobalOK(["foo"], 2);
-
- yield cps.removeByDomainAndName("bogus", "bogus", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getGlobalOK(["foo"], 2);
- },
-
- function* isomorphicDomains() {
- yield set("a.com", "foo", 1);
- yield cps.removeByDomainAndName("a.com", "foo", null, makeCallback());
- yield dbOK([]);
- yield getOK(["a.com", "foo"], undefined);
-
- yield set("a.com", "foo", 2);
- yield cps.removeByDomainAndName("http://a.com/huh", "foo", null,
- makeCallback());
- yield dbOK([]);
- yield getOK(["a.com", "foo"], undefined);
- },
-
- function* names() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
-
- yield cps.removeByDomainAndName("a.com", "foo", null, makeCallback());
- yield dbOK([
- ["a.com", "bar", 2],
- [null, "foo", 3],
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], 2);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
-
- yield cps.removeGlobal("foo", null, makeCallback());
- yield dbOK([
- ["a.com", "bar", 2],
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], 2);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], 4);
-
- yield cps.removeByDomainAndName("a.com", "bar", null, makeCallback());
- yield dbOK([
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], 4);
-
- yield cps.removeGlobal("bar", null, makeCallback());
- yield dbOK([
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], undefined);
- },
-
- function* subdomains() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- yield cps.removeByDomainAndName("a.com", "foo", null, makeCallback());
- yield dbOK([
- ["b.a.com", "foo", 2],
- ]);
- yield getSubdomainsOK(["a.com", "foo"], [["b.a.com", 2]]);
- yield getSubdomainsOK(["b.a.com", "foo"], [["b.a.com", 2]]);
-
- yield set("a.com", "foo", 3);
- yield cps.removeBySubdomainAndName("a.com", "foo", null, makeCallback());
- yield dbOK([
- ]);
- yield getSubdomainsOK(["a.com", "foo"], []);
- yield getSubdomainsOK(["b.a.com", "foo"], []);
-
- yield set("a.com", "foo", 4);
- yield set("b.a.com", "foo", 5);
- yield cps.removeByDomainAndName("b.a.com", "foo", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 4],
- ]);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 4]]);
- yield getSubdomainsOK(["b.a.com", "foo"], []);
-
- yield set("b.a.com", "foo", 6);
- yield cps.removeBySubdomainAndName("b.a.com", "foo", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 4],
- ]);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 4]]);
- yield getSubdomainsOK(["b.a.com", "foo"], []);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield setGlobal("qux", 5);
- yield set("b.com", "foo", 6);
- yield set("b.com", "bar", 7);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 8, context);
- yield setGlobal("foo", 9, context);
- yield cps.removeByDomainAndName("a.com", "foo", context, makeCallback());
- yield cps.removeGlobal("foo", context, makeCallback());
- yield cps.removeGlobal("qux", context, makeCallback());
- yield cps.removeByDomainAndName("b.com", "foo", context, makeCallback());
- yield dbOK([
- ["a.com", "bar", 2],
- [null, "bar", 4],
- ["b.com", "bar", 7],
- ]);
- yield getOK(["a.com", "foo", context], undefined);
- yield getOK(["a.com", "bar", context], 2);
- yield getGlobalOK(["foo", context], undefined);
- yield getGlobalOK(["bar", context], 4);
- yield getGlobalOK(["qux", context], undefined);
- yield getOK(["b.com", "foo", context], undefined);
- yield getOK(["b.com", "bar", context], 7);
-
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], 2);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], 4);
- yield getGlobalOK(["qux"], undefined);
- yield getOK(["b.com", "foo"], undefined);
- yield getOK(["b.com", "bar"], 7);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.removeByDomainAndName(null, "foo", null));
- do_check_throws(() => cps.removeByDomainAndName("", "foo", null));
- do_check_throws(() => cps.removeByDomainAndName("a.com", "foo", null,
- "bogus"));
- do_check_throws(() => cps.removeBySubdomainAndName(null, "foo",
- null));
- do_check_throws(() => cps.removeBySubdomainAndName("", "foo", null));
- do_check_throws(() => cps.removeBySubdomainAndName("a.com", "foo",
- null, "bogus"));
- do_check_throws(() => cps.removeGlobal("", null));
- do_check_throws(() => cps.removeGlobal(null, null));
- do_check_throws(() => cps.removeGlobal("foo", null, "bogus"));
- yield true;
- },
-
- function* removeByDomainAndName_invalidateCache() {
- yield set("a.com", "foo", 1);
- getCachedOK(["a.com", "foo"], true, 1);
- cps.removeByDomainAndName("a.com", "foo", null, makeCallback());
- getCachedOK(["a.com", "foo"], false);
- yield;
- },
-
- function* removeBySubdomainAndName_invalidateCache() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- getCachedSubdomainsOK(["a.com", "foo"], [
- ["a.com", 1],
- ["b.a.com", 2],
- ]);
- cps.removeBySubdomainAndName("a.com", "foo", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], []);
- yield;
- },
-
- function* removeGlobal_invalidateCache() {
- yield setGlobal("foo", 1);
- getCachedGlobalOK(["foo"], true, 1);
- cps.removeGlobal("foo", null, makeCallback());
- getCachedGlobalOK(["foo"], false);
- yield;
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomains.js b/toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomains.js
deleted file mode 100644
index 63e1b0552..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomains.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* nonexistent() {
- yield setGlobal("foo", 1);
- yield cps.removeAllDomains(null, makeCallback());
- yield dbOK([
- [null, "foo", 1],
- ]);
- yield getGlobalOK(["foo"], 1);
- },
-
- function* domains() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
- yield set("b.com", "bar", 6);
-
- yield cps.removeAllDomains(null, makeCallback());
- yield dbOK([
- [null, "foo", 3],
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
- yield getOK(["b.com", "foo"], undefined);
- yield getOK(["b.com", "bar"], undefined);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 6, context);
- yield setGlobal("foo", 7, context);
- yield cps.removeAllDomains(context, makeCallback());
- yield dbOK([
- [null, "foo", 3],
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo", context], undefined);
- yield getOK(["a.com", "bar", context], undefined);
- yield getGlobalOK(["foo", context], 7);
- yield getGlobalOK(["bar", context], 4);
- yield getOK(["b.com", "foo", context], undefined);
-
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
- yield getOK(["b.com", "foo"], undefined);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.removeAllDomains(null, "bogus"));
- yield true;
- },
-
- function* invalidateCache() {
- yield set("a.com", "foo", 1);
- yield set("b.com", "bar", 2);
- yield setGlobal("baz", 3);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["b.com", "bar"], true, 2);
- getCachedGlobalOK(["baz"], true, 3);
- cps.removeAllDomains(null, makeCallback());
- getCachedOK(["a.com", "foo"], false);
- getCachedOK(["b.com", "bar"], false);
- getCachedGlobalOK(["baz"], true, 3);
- yield;
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomainsSince.js b/toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomainsSince.js
deleted file mode 100644
index fa0bf31c3..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_removeAllDomainsSince.js
+++ /dev/null
@@ -1,111 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* nonexistent() {
- yield setGlobal("foo", 1);
- yield cps.removeAllDomainsSince(0, null, makeCallback());
- yield getGlobalOK(["foo"], 1);
- },
-
- function* domainsAll() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
- yield set("b.com", "bar", 6);
-
- yield cps.removeAllDomainsSince(0, null, makeCallback());
- yield dbOK([
- [null, "foo", 3],
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
- yield getOK(["b.com", "foo"], undefined);
- yield getOK(["b.com", "bar"], undefined);
- },
-
- function* domainsWithDate() {
- yield setWithDate("a.com", "foobar", 0, 0);
- yield setWithDate("a.com", "foo", 1, 1000);
- yield setWithDate("a.com", "bar", 2, 4000);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield setWithDate("b.com", "foo", 5, 2000);
- yield setWithDate("b.com", "bar", 6, 3000);
- yield setWithDate("b.com", "foobar", 7, 1000);
-
- yield cps.removeAllDomainsSince(2000, null, makeCallback());
- yield dbOK([
- ["a.com", "foobar", 0],
- ["a.com", "foo", 1],
- [null, "foo", 3],
- [null, "bar", 4],
- ["b.com", "foobar", 7],
- ]);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 6, context);
- yield setGlobal("foo", 7, context);
- yield cps.removeAllDomainsSince(0, context, makeCallback());
- yield dbOK([
- [null, "foo", 3],
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo", context], undefined);
- yield getOK(["a.com", "bar", context], undefined);
- yield getGlobalOK(["foo", context], 7);
- yield getGlobalOK(["bar", context], 4);
- yield getOK(["b.com", "foo", context], undefined);
-
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
- yield getOK(["b.com", "foo"], undefined);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.removeAllDomainsSince(null, "bogus"));
- yield true;
- },
-
- function* invalidateCache() {
- yield setWithDate("a.com", "foobar", 0, 0);
- yield setWithDate("a.com", "foo", 1, 1000);
- yield setWithDate("a.com", "bar", 2, 4000);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield setWithDate("b.com", "foo", 5, 2000);
- yield setWithDate("b.com", "bar", 6, 3000);
- yield setWithDate("b.com", "foobar", 7, 1000);
- cps.removeAllDomainsSince(0, null, makeCallback());
- getCachedOK(["a.com", "foobar"], false);
- getCachedOK(["a.com", "foo"], false);
- getCachedOK(["a.com", "bar"], false);
- getCachedGlobalOK(["foo"], true, 3);
- getCachedGlobalOK(["bar"], true, 4);
- getCachedOK(["b.com", "foo"], false);
- getCachedOK(["b.com", "bar"], false);
- getCachedOK(["b.com", "foobar"], false);
- yield true;
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_removeByDomain.js b/toolkit/components/contentprefs/tests/unit_cps2/test_removeByDomain.js
deleted file mode 100644
index 1cf6bd8f2..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_removeByDomain.js
+++ /dev/null
@@ -1,199 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* nonexistent() {
- yield set("a.com", "foo", 1);
- yield setGlobal("foo", 2);
-
- yield cps.removeByDomain("bogus", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getGlobalOK(["foo"], 2);
-
- yield cps.removeBySubdomain("bogus", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getGlobalOK(["foo"], 2);
- },
-
- function* isomorphicDomains() {
- yield set("a.com", "foo", 1);
- yield cps.removeByDomain("a.com", null, makeCallback());
- yield dbOK([]);
- yield getOK(["a.com", "foo"], undefined);
-
- yield set("a.com", "foo", 2);
- yield cps.removeByDomain("http://a.com/huh", null, makeCallback());
- yield dbOK([]);
- yield getOK(["a.com", "foo"], undefined);
- },
-
- function* domains() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
- yield set("b.com", "bar", 6);
-
- yield cps.removeByDomain("a.com", null, makeCallback());
- yield dbOK([
- [null, "foo", 3],
- [null, "bar", 4],
- ["b.com", "foo", 5],
- ["b.com", "bar", 6],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
- yield getOK(["b.com", "foo"], 5);
- yield getOK(["b.com", "bar"], 6);
-
- yield cps.removeAllGlobals(null, makeCallback());
- yield dbOK([
- ["b.com", "foo", 5],
- ["b.com", "bar", 6],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], undefined);
- yield getOK(["b.com", "foo"], 5);
- yield getOK(["b.com", "bar"], 6);
-
- yield cps.removeByDomain("b.com", null, makeCallback());
- yield dbOK([
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], undefined);
- yield getOK(["b.com", "foo"], undefined);
- yield getOK(["b.com", "bar"], undefined);
- },
-
- function* subdomains() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- yield cps.removeByDomain("a.com", null, makeCallback());
- yield dbOK([
- ["b.a.com", "foo", 2],
- ]);
- yield getSubdomainsOK(["a.com", "foo"], [["b.a.com", 2]]);
- yield getSubdomainsOK(["b.a.com", "foo"], [["b.a.com", 2]]);
-
- yield set("a.com", "foo", 3);
- yield cps.removeBySubdomain("a.com", null, makeCallback());
- yield dbOK([
- ]);
- yield getSubdomainsOK(["a.com", "foo"], []);
- yield getSubdomainsOK(["b.a.com", "foo"], []);
-
- yield set("a.com", "foo", 4);
- yield set("b.a.com", "foo", 5);
- yield cps.removeByDomain("b.a.com", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 4],
- ]);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 4]]);
- yield getSubdomainsOK(["b.a.com", "foo"], []);
-
- yield set("b.a.com", "foo", 6);
- yield cps.removeBySubdomain("b.a.com", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 4],
- ]);
- yield getSubdomainsOK(["a.com", "foo"], [["a.com", 4]]);
- yield getSubdomainsOK(["b.a.com", "foo"], []);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 6, context);
- yield set("b.com", "foo", 7, context);
- yield setGlobal("foo", 8, context);
- yield cps.removeByDomain("a.com", context, makeCallback());
- yield getOK(["b.com", "foo", context], 7);
- yield getGlobalOK(["foo", context], 8);
- yield cps.removeAllGlobals(context, makeCallback());
- yield dbOK([
- ["b.com", "foo", 5],
- ]);
- yield getOK(["a.com", "foo", context], undefined);
- yield getOK(["a.com", "bar", context], undefined);
- yield getGlobalOK(["foo", context], undefined);
- yield getGlobalOK(["bar", context], undefined);
- yield getOK(["b.com", "foo", context], 5);
-
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], undefined);
- yield getOK(["b.com", "foo"], 5);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.removeByDomain(null, null));
- do_check_throws(() => cps.removeByDomain("", null));
- do_check_throws(() => cps.removeByDomain("a.com", null, "bogus"));
- do_check_throws(() => cps.removeBySubdomain(null, null));
- do_check_throws(() => cps.removeBySubdomain("", null));
- do_check_throws(() => cps.removeBySubdomain("a.com", null, "bogus"));
- do_check_throws(() => cps.removeAllGlobals(null, "bogus"));
- yield true;
- },
-
- function* removeByDomain_invalidateCache() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["a.com", "bar"], true, 2);
- cps.removeByDomain("a.com", null, makeCallback());
- getCachedOK(["a.com", "foo"], false);
- getCachedOK(["a.com", "bar"], false);
- yield;
- },
-
- function* removeBySubdomain_invalidateCache() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- getCachedSubdomainsOK(["a.com", "foo"], [
- ["a.com", 1],
- ["b.a.com", 2],
- ]);
- cps.removeBySubdomain("a.com", null, makeCallback());
- getCachedSubdomainsOK(["a.com", "foo"], []);
- yield;
- },
-
- function* removeAllGlobals_invalidateCache() {
- yield setGlobal("foo", 1);
- yield setGlobal("bar", 2);
- getCachedGlobalOK(["foo"], true, 1);
- getCachedGlobalOK(["bar"], true, 2);
- cps.removeAllGlobals(null, makeCallback());
- getCachedGlobalOK(["foo"], false);
- getCachedGlobalOK(["bar"], false);
- yield;
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_removeByName.js b/toolkit/components/contentprefs/tests/unit_cps2/test_removeByName.js
deleted file mode 100644
index fa04656e2..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_removeByName.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* nonexistent() {
- yield set("a.com", "foo", 1);
- yield setGlobal("foo", 2);
-
- yield cps.removeByName("bogus", null, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getGlobalOK(["foo"], 2);
- },
-
- function* names() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
- yield set("b.com", "bar", 6);
-
- yield cps.removeByName("foo", null, makeCallback());
- yield dbOK([
- ["a.com", "bar", 2],
- [null, "bar", 4],
- ["b.com", "bar", 6],
- ]);
- yield getOK(["a.com", "foo"], undefined);
- yield getOK(["a.com", "bar"], 2);
- yield getGlobalOK(["foo"], undefined);
- yield getGlobalOK(["bar"], 4);
- yield getOK(["b.com", "foo"], undefined);
- yield getOK(["b.com", "bar"], 6);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
- yield set("b.com", "bar", 6);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 7, context);
- yield setGlobal("foo", 8, context);
- yield set("b.com", "bar", 9, context);
- yield cps.removeByName("bar", context, makeCallback());
- yield dbOK([
- ["a.com", "foo", 1],
- [null, "foo", 3],
- ["b.com", "foo", 5],
- ]);
- yield getOK(["a.com", "foo", context], 7);
- yield getOK(["a.com", "bar", context], undefined);
- yield getGlobalOK(["foo", context], 8);
- yield getGlobalOK(["bar", context], undefined);
- yield getOK(["b.com", "foo", context], 5);
- yield getOK(["b.com", "bar", context], undefined);
-
- yield getOK(["a.com", "foo"], 1);
- yield getOK(["a.com", "bar"], undefined);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], undefined);
- yield getOK(["b.com", "foo"], 5);
- yield getOK(["b.com", "bar"], undefined);
- },
-
- function* erroneous() {
- do_check_throws(() => cps.removeByName("", null));
- do_check_throws(() => cps.removeByName(null, null));
- do_check_throws(() => cps.removeByName("foo", null, "bogus"));
- yield true;
- },
-
- function* invalidateCache() {
- yield set("a.com", "foo", 1);
- yield set("b.com", "foo", 2);
- getCachedOK(["a.com", "foo"], true, 1);
- getCachedOK(["b.com", "foo"], true, 2);
- cps.removeByName("foo", null, makeCallback());
- getCachedOK(["a.com", "foo"], false);
- getCachedOK(["b.com", "foo"], false);
- yield;
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_service.js b/toolkit/components/contentprefs/tests/unit_cps2/test_service.js
deleted file mode 100644
index 75292063e..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_service.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/. */
-
-function run_test() {
- let serv = Cc["@mozilla.org/content-pref/service;1"].
- getService(Ci.nsIContentPrefService2);
- do_check_eq(serv.QueryInterface(Ci.nsIContentPrefService2), serv);
- do_check_eq(serv.QueryInterface(Ci.nsISupports), serv);
- let val = serv.QueryInterface(Ci.nsIContentPrefService);
- do_check_true(val instanceof Ci.nsIContentPrefService);
-}
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js b/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js
deleted file mode 100644
index b10a05bbc..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_setGet.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- runAsyncTests(tests);
-}
-
-var tests = [
-
- function* get_nonexistent() {
- yield getOK(["a.com", "foo"], undefined);
- yield getGlobalOK(["foo"], undefined);
- },
-
- function* isomorphicDomains() {
- yield set("a.com", "foo", 1);
- yield dbOK([
- ["a.com", "foo", 1],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getOK(["http://a.com/huh", "foo"], 1, "a.com");
-
- yield set("http://a.com/huh", "foo", 2);
- yield dbOK([
- ["a.com", "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 2);
- yield getOK(["http://a.com/yeah", "foo"], 2, "a.com");
- },
-
- function* names() {
- yield set("a.com", "foo", 1);
- yield dbOK([
- ["a.com", "foo", 1],
- ]);
- yield getOK(["a.com", "foo"], 1);
-
- yield set("a.com", "bar", 2);
- yield dbOK([
- ["a.com", "foo", 1],
- ["a.com", "bar", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getOK(["a.com", "bar"], 2);
-
- yield setGlobal("foo", 3);
- yield dbOK([
- ["a.com", "foo", 1],
- ["a.com", "bar", 2],
- [null, "foo", 3],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getOK(["a.com", "bar"], 2);
- yield getGlobalOK(["foo"], 3);
-
- yield setGlobal("bar", 4);
- yield dbOK([
- ["a.com", "foo", 1],
- ["a.com", "bar", 2],
- [null, "foo", 3],
- [null, "bar", 4],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getOK(["a.com", "bar"], 2);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
- },
-
- function* subdomains() {
- yield set("a.com", "foo", 1);
- yield set("b.a.com", "foo", 2);
- yield dbOK([
- ["a.com", "foo", 1],
- ["b.a.com", "foo", 2],
- ]);
- yield getOK(["a.com", "foo"], 1);
- yield getOK(["b.a.com", "foo"], 2);
- },
-
- function* privateBrowsing() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield setGlobal("foo", 3);
- yield setGlobal("bar", 4);
- yield set("b.com", "foo", 5);
-
- let context = { usePrivateBrowsing: true };
- yield set("a.com", "foo", 6, context);
- yield setGlobal("foo", 7, context);
- yield dbOK([
- ["a.com", "foo", 1],
- ["a.com", "bar", 2],
- [null, "foo", 3],
- [null, "bar", 4],
- ["b.com", "foo", 5],
- ]);
- yield getOK(["a.com", "foo", context], 6, "a.com");
- yield getOK(["a.com", "bar", context], 2);
- yield getGlobalOK(["foo", context], 7);
- yield getGlobalOK(["bar", context], 4);
- yield getOK(["b.com", "foo", context], 5);
-
- yield getOK(["a.com", "foo"], 1);
- yield getOK(["a.com", "bar"], 2);
- yield getGlobalOK(["foo"], 3);
- yield getGlobalOK(["bar"], 4);
- yield getOK(["b.com", "foo"], 5);
- },
-
- function* set_erroneous() {
- do_check_throws(() => cps.set(null, "foo", 1, null));
- do_check_throws(() => cps.set("", "foo", 1, null));
- do_check_throws(() => cps.set("a.com", "", 1, null));
- do_check_throws(() => cps.set("a.com", null, 1, null));
- do_check_throws(() => cps.set("a.com", "foo", undefined, null));
- do_check_throws(() => cps.set("a.com", "foo", 1, null, "bogus"));
- do_check_throws(() => cps.setGlobal("", 1, null));
- do_check_throws(() => cps.setGlobal(null, 1, null));
- do_check_throws(() => cps.setGlobal("foo", undefined, null));
- do_check_throws(() => cps.setGlobal("foo", 1, null, "bogus"));
- yield true;
- },
-
- function* get_erroneous() {
- do_check_throws(() => cps.getByDomainAndName(null, "foo", null, {}));
- do_check_throws(() => cps.getByDomainAndName("", "foo", null, {}));
- do_check_throws(() => cps.getByDomainAndName("a.com", "", null, {}));
- do_check_throws(() => cps.getByDomainAndName("a.com", null, null, {}));
- do_check_throws(() => cps.getByDomainAndName("a.com", "foo", null, null));
- do_check_throws(() => cps.getGlobal("", null, {}));
- do_check_throws(() => cps.getGlobal(null, null, {}));
- do_check_throws(() => cps.getGlobal("foo", null, null));
- yield true;
- },
-
- function* set_invalidateCache() {
- // (1) Set a pref and wait for it to finish.
- yield set("a.com", "foo", 1);
-
- // (2) It should be cached.
- getCachedOK(["a.com", "foo"], true, 1);
-
- // (3) Set the pref to a new value but don't wait for it to finish.
- cps.set("a.com", "foo", 2, null, {
- handleCompletion: function () {
- // (6) The pref should be cached after setting it.
- getCachedOK(["a.com", "foo"], true, 2);
- },
- });
-
- // (4) Group "a.com" and name "foo" should no longer be cached.
- getCachedOK(["a.com", "foo"], false);
-
- // (5) Call getByDomainAndName.
- var fetchedPref;
- cps.getByDomainAndName("a.com", "foo", null, {
- handleResult: function (pref) {
- fetchedPref = pref;
- },
- handleCompletion: function () {
- // (7) Finally, this callback should be called after set's above.
- do_check_true(!!fetchedPref);
- do_check_eq(fetchedPref.value, 2);
- next();
- },
- });
-
- yield;
- },
-
- function* get_nameOnly() {
- yield set("a.com", "foo", 1);
- yield set("a.com", "bar", 2);
- yield set("b.com", "foo", 3);
- yield setGlobal("foo", 4);
-
- yield getOKEx("getByName", ["foo", undefined], [
- {"domain": "a.com", "name": "foo", "value": 1},
- {"domain": "b.com", "name": "foo", "value": 3},
- {"domain": null, "name": "foo", "value": 4}
- ]);
-
- let context = { usePrivateBrowsing: true };
- yield set("b.com", "foo", 5, context);
-
- yield getOKEx("getByName", ["foo", context], [
- {"domain": "a.com", "name": "foo", "value": 1},
- {"domain": null, "name": "foo", "value": 4},
- {"domain": "b.com", "name": "foo", "value": 5}
- ]);
- },
-
- function* setSetsCurrentDate() {
- // Because Date.now() is not guaranteed to be monotonically increasing
- // we just do here rough sanity check with one minute tolerance.
- const MINUTE = 60 * 1000;
- let now = Date.now();
- let start = now - MINUTE;
- let end = now + MINUTE;
- yield set("a.com", "foo", 1);
- let timestamp = yield getDate("a.com", "foo");
- ok(start <= timestamp, "Timestamp is not too early (" + start + "<=" + timestamp + ").");
- ok(timestamp <= end, "Timestamp is not too late (" + timestamp + "<=" + end + ").");
- },
-];
diff --git a/toolkit/components/contentprefs/tests/unit_cps2/xpcshell.ini b/toolkit/components/contentprefs/tests/unit_cps2/xpcshell.ini
deleted file mode 100644
index bdbcaf8fd..000000000
--- a/toolkit/components/contentprefs/tests/unit_cps2/xpcshell.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-skip-if = toolkit == 'android'
-support-files = AsyncRunner.jsm
-
-[test_service.js]
-[test_setGet.js]
-[test_getSubdomains.js]
-[test_remove.js]
-[test_removeByDomain.js]
-[test_removeAllDomains.js]
-[test_removeByName.js]
-[test_getCached.js]
-[test_getCachedSubdomains.js]
-[test_observers.js]
-[test_extractDomain.js]
-[test_migrationToSchema4.js]
-[test_removeAllDomainsSince.js]
diff --git a/toolkit/components/contextualidentity/moz.build b/toolkit/components/contextualidentity/moz.build
index 9188421f9..524d5e779 100644
--- a/toolkit/components/contextualidentity/moz.build
+++ b/toolkit/components/contextualidentity/moz.build
@@ -4,8 +4,4 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-EXTRA_JS_MODULES += [
- 'ContextualIdentityService.jsm',
-]
-
-XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
+EXTRA_JS_MODULES += ['ContextualIdentityService.jsm']
diff --git a/toolkit/components/contextualidentity/tests/unit/test_basic.js b/toolkit/components/contextualidentity/tests/unit/test_basic.js
deleted file mode 100644
index 4d17b9a26..000000000
--- a/toolkit/components/contextualidentity/tests/unit/test_basic.js
+++ /dev/null
@@ -1,67 +0,0 @@
-"use strict";
-
-do_get_profile();
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/ContextualIdentityService.jsm");
-
-const TEST_STORE_FILE_NAME = "test-containers.json";
-
-let cis;
-
-// Basic tests
-add_task(function() {
- ok(!!ContextualIdentityService, "ContextualIdentityService exists");
-
- cis = ContextualIdentityService.createNewInstanceForTesting(TEST_STORE_FILE_NAME);
- ok(!!cis, "We have our instance of ContextualIdentityService");
-
- equal(cis.getIdentities().length, 4, "By default, 4 containers.");
- equal(cis.getIdentityFromId(0), null, "No identity with id 0");
-
- ok(!!cis.getIdentityFromId(1), "Identity 1 exists");
- ok(!!cis.getIdentityFromId(2), "Identity 2 exists");
- ok(!!cis.getIdentityFromId(3), "Identity 3 exists");
- ok(!!cis.getIdentityFromId(4), "Identity 4 exists");
-});
-
-// Create a new identity
-add_task(function() {
- equal(cis.getIdentities().length, 4, "By default, 4 containers.");
-
- let identity = cis.create("New Container", "Icon", "Color");
- ok(!!identity, "New container created");
- equal(identity.name, "New Container", "Name matches");
- equal(identity.icon, "Icon", "Icon matches");
- equal(identity.color, "Color", "Color matches");
-
- equal(cis.getIdentities().length, 5, "Expected 5 containers.");
-
- ok(!!cis.getIdentityFromId(identity.userContextId), "Identity exists");
- equal(cis.getIdentityFromId(identity.userContextId).name, "New Container", "Identity name is OK");
- equal(cis.getIdentityFromId(identity.userContextId).icon, "Icon", "Identity icon is OK");
- equal(cis.getIdentityFromId(identity.userContextId).color, "Color", "Identity color is OK");
- equal(cis.getUserContextLabel(identity.userContextId), "New Container", "Identity label is OK");
-
- // Remove an identity
- equal(cis.remove(-1), false, "cis.remove() returns false if identity doesn't exist.");
- equal(cis.remove(1), true, "cis.remove() returns true if identity exists.");
-
- equal(cis.getIdentities().length, 4, "Expected 4 containers.");
-});
-
-// Update an identity
-add_task(function() {
- ok(!!cis.getIdentityFromId(2), "Identity 2 exists");
-
- equal(cis.update(-1, "Container", "Icon", "Color"), false, "Update returns false if the identity doesn't exist");
-
- equal(cis.update(2, "Container", "Icon", "Color"), true, "Update returns true if everything is OK");
-
- ok(!!cis.getIdentityFromId(2), "Identity exists");
- equal(cis.getIdentityFromId(2).name, "Container", "Identity name is OK");
- equal(cis.getIdentityFromId(2).icon, "Icon", "Identity icon is OK");
- equal(cis.getIdentityFromId(2).color, "Color", "Identity color is OK");
- equal(cis.getUserContextLabel(2), "Container", "Identity label is OK");
-});
diff --git a/toolkit/components/contextualidentity/tests/unit/xpcshell.ini b/toolkit/components/contextualidentity/tests/unit/xpcshell.ini
deleted file mode 100644
index b45ff2c30..000000000
--- a/toolkit/components/contextualidentity/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[test_basic.js]
diff --git a/toolkit/components/crashes/moz.build b/toolkit/components/crashes/moz.build
index 5a36a3cd3..6efad5964 100644
--- a/toolkit/components/crashes/moz.build
+++ b/toolkit/components/crashes/moz.build
@@ -19,13 +19,8 @@ TESTING_JS_MODULES += [
'CrashManagerTest.jsm',
]
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
XPIDL_MODULE = 'toolkit_crashservice'
XPIDL_SOURCES += [
'nsICrashService.idl',
]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Breakpad Integration')
diff --git a/toolkit/components/crashes/tests/xpcshell/.eslintrc.js b/toolkit/components/crashes/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/crashes/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/crashes/tests/xpcshell/test_crash_manager.js b/toolkit/components/crashes/tests/xpcshell/test_crash_manager.js
deleted file mode 100644
index 9844e78c4..000000000
--- a/toolkit/components/crashes/tests/xpcshell/test_crash_manager.js
+++ /dev/null
@@ -1,494 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
-
-var bsp = Cu.import("resource://gre/modules/CrashManager.jsm", this);
-Cu.import("resource://gre/modules/Promise.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/TelemetryEnvironment.jsm", this);
-
-Cu.import("resource://testing-common/CrashManagerTest.jsm", this);
-Cu.import("resource://testing-common/TelemetryArchiveTesting.jsm", this);
-
-const DUMMY_DATE = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
-DUMMY_DATE.setMilliseconds(0);
-
-const DUMMY_DATE_2 = new Date(Date.now() - 20 * 24 * 60 * 60 * 1000);
-DUMMY_DATE_2.setMilliseconds(0);
-
-function run_test() {
- do_get_profile();
- configureLogging();
- TelemetryArchiveTesting.setup();
- run_next_test();
-}
-
-add_task(function* test_constructor_ok() {
- let m = new CrashManager({
- pendingDumpsDir: "/foo",
- submittedDumpsDir: "/bar",
- eventsDirs: [],
- storeDir: "/baz",
- });
- Assert.ok(m, "CrashManager can be created.");
-});
-
-add_task(function* test_constructor_invalid() {
- Assert.throws(() => {
- new CrashManager({foo: true});
- });
-});
-
-add_task(function* test_get_manager() {
- let m = yield getManager();
- Assert.ok(m, "CrashManager obtained.");
-
- yield m.createDummyDump(true);
- yield m.createDummyDump(false);
-});
-
-// Unsubmitted dump files on disk are detected properly.
-add_task(function* test_pending_dumps() {
- let m = yield getManager();
- let now = Date.now();
- let ids = [];
- const COUNT = 5;
-
- for (let i = 0; i < COUNT; i++) {
- ids.push(yield m.createDummyDump(false, new Date(now - i * 86400000)));
- }
- yield m.createIgnoredDumpFile("ignored", false);
-
- let entries = yield m.pendingDumps();
- Assert.equal(entries.length, COUNT, "proper number detected.");
-
- for (let entry of entries) {
- Assert.equal(typeof(entry), "object", "entry is an object");
- Assert.ok("id" in entry, "id in entry");
- Assert.ok("path" in entry, "path in entry");
- Assert.ok("date" in entry, "date in entry");
- Assert.notEqual(ids.indexOf(entry.id), -1, "ID is known");
- }
-
- for (let i = 0; i < COUNT; i++) {
- Assert.equal(entries[i].id, ids[COUNT-i-1], "Entries sorted by mtime");
- }
-});
-
-// Submitted dump files on disk are detected properly.
-add_task(function* test_submitted_dumps() {
- let m = yield getManager();
- let COUNT = 5;
-
- for (let i = 0; i < COUNT; i++) {
- yield m.createDummyDump(true);
- }
- yield m.createIgnoredDumpFile("ignored", true);
-
- let entries = yield m.submittedDumps();
- Assert.equal(entries.length, COUNT, "proper number detected.");
-
- let hrID = yield m.createDummyDump(true, new Date(), true);
- entries = yield m.submittedDumps();
- Assert.equal(entries.length, COUNT + 1, "hr- in filename detected.");
-
- let gotIDs = new Set(entries.map(e => e.id));
- Assert.ok(gotIDs.has(hrID));
-});
-
-// The store should expire after inactivity.
-add_task(function* test_store_expires() {
- let m = yield getManager();
-
- Object.defineProperty(m, "STORE_EXPIRATION_MS", {
- value: 250,
- });
-
- let store = yield m._getStore();
- Assert.ok(store);
- Assert.equal(store, m._store);
-
- yield sleep(300);
- Assert.ok(!m._store, "Store has gone away.");
-});
-
-// Ensure discovery of unprocessed events files works.
-add_task(function* test_unprocessed_events_files() {
- let m = yield getManager();
- yield m.createEventsFile("1", "test.1", new Date(), "foo", 0);
- yield m.createEventsFile("2", "test.1", new Date(), "bar", 0);
- yield m.createEventsFile("1", "test.1", new Date(), "baz", 1);
-
- let paths = yield m._getUnprocessedEventsFiles();
- Assert.equal(paths.length, 3);
-});
-
-// Ensure only 1 aggregateEventsFiles() is allowed at a time.
-add_task(function* test_aggregate_events_locking() {
- let m = yield getManager();
-
- let p1 = m.aggregateEventsFiles();
- let p2 = m.aggregateEventsFiles();
-
- Assert.strictEqual(p1, p2, "Same promise should be returned.");
-});
-
-// Malformed events files should be deleted.
-add_task(function* test_malformed_files_deleted() {
- let m = yield getManager();
-
- yield m.createEventsFile("1", "crash.main.1", new Date(), "foo\nbar");
-
- let count = yield m.aggregateEventsFiles();
- Assert.equal(count, 1);
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 0);
-
- count = yield m.aggregateEventsFiles();
- Assert.equal(count, 0);
-});
-
-// Unknown event types should be ignored.
-add_task(function* test_aggregate_ignore_unknown_events() {
- let m = yield getManager();
-
- yield m.createEventsFile("1", "crash.main.2", DUMMY_DATE, "id1");
- yield m.createEventsFile("2", "foobar.1", new Date(), "dummy");
-
- let count = yield m.aggregateEventsFiles();
- Assert.equal(count, 2);
-
- count = yield m.aggregateEventsFiles();
- Assert.equal(count, 1);
-
- count = yield m.aggregateEventsFiles();
- Assert.equal(count, 1);
-});
-
-add_task(function* test_prune_old() {
- let m = yield getManager();
- let oldDate = new Date(Date.now() - 86400000);
- let newDate = new Date(Date.now() - 10000);
- yield m.createEventsFile("1", "crash.main.2", oldDate, "id1");
- yield m.addCrash(m.PROCESS_TYPE_PLUGIN, m.CRASH_TYPE_CRASH, "id2", newDate);
-
- yield m.aggregateEventsFiles();
-
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 2);
-
- yield m.pruneOldCrashes(new Date(oldDate.getTime() + 10000));
-
- crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 1, "Old crash has been pruned.");
-
- let c = crashes[0];
- Assert.equal(c.id, "id2", "Proper crash was pruned.");
-
- // We can't test exact boundary conditions because dates from filesystem
- // don't have same guarantees as JS dates.
- yield m.pruneOldCrashes(new Date(newDate.getTime() + 5000));
- crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 0);
-});
-
-add_task(function* test_schedule_maintenance() {
- let m = yield getManager();
- yield m.createEventsFile("1", "crash.main.2", DUMMY_DATE, "id1");
-
- let oldDate = new Date(Date.now() - m.PURGE_OLDER_THAN_DAYS * 2 * 24 * 60 * 60 * 1000);
- yield m.createEventsFile("2", "crash.main.2", oldDate, "id2");
-
- yield m.scheduleMaintenance(25);
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 1);
- Assert.equal(crashes[0].id, "id1");
-});
-
-add_task(function* test_main_crash_event_file() {
- let ac = new TelemetryArchiveTesting.Checker();
- yield ac.promiseInit();
- let theEnvironment = TelemetryEnvironment.currentEnvironment;
- let sessionId = "be66af2f-2ee5-4330-ae95-44462dfbdf0c";
- let stackTraces = { status: "OK" };
-
- // To test proper escaping, add data to the environment with an embedded
- // double-quote
- theEnvironment.testValue = "MyValue\"";
-
- let m = yield getManager();
- const fileContent = "id1\nk1=v1\nk2=v2\n" +
- "TelemetryEnvironment=" + JSON.stringify(theEnvironment) + "\n" +
- "TelemetrySessionId=" + sessionId + "\n" +
- "StackTraces=" + JSON.stringify(stackTraces) + "\n";
-
- yield m.createEventsFile("1", "crash.main.2", DUMMY_DATE, fileContent);
- let count = yield m.aggregateEventsFiles();
- Assert.equal(count, 1);
-
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 1);
- Assert.equal(crashes[0].id, "id1");
- Assert.equal(crashes[0].type, "main-crash");
- Assert.equal(crashes[0].metadata.k1, "v1");
- Assert.equal(crashes[0].metadata.k2, "v2");
- Assert.ok(crashes[0].metadata.TelemetryEnvironment);
- Assert.equal(Object.getOwnPropertyNames(crashes[0].metadata).length, 5);
- Assert.equal(crashes[0].metadata.TelemetrySessionId, sessionId);
- Assert.ok(crashes[0].metadata.StackTraces);
- Assert.deepEqual(crashes[0].crashDate, DUMMY_DATE);
-
- let found = yield ac.promiseFindPing("crash", [
- [["payload", "hasCrashEnvironment"], true],
- [["payload", "metadata", "k1"], "v1"],
- [["payload", "crashId"], "1"],
- [["payload", "stackTraces", "status"], "OK"],
- [["payload", "sessionId"], sessionId],
- ]);
- Assert.ok(found, "Telemetry ping submitted for found crash");
- Assert.deepEqual(found.environment, theEnvironment, "The saved environment should be present");
-
- count = yield m.aggregateEventsFiles();
- Assert.equal(count, 0);
-});
-
-add_task(function* test_main_crash_event_file_noenv() {
- let ac = new TelemetryArchiveTesting.Checker();
- yield ac.promiseInit();
-
- let m = yield getManager();
- yield m.createEventsFile("1", "crash.main.2", DUMMY_DATE, "id1\nk1=v3\nk2=v2");
- let count = yield m.aggregateEventsFiles();
- Assert.equal(count, 1);
-
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 1);
- Assert.equal(crashes[0].id, "id1");
- Assert.equal(crashes[0].type, "main-crash");
- Assert.deepEqual(crashes[0].metadata, { k1: "v3", k2: "v2"});
- Assert.deepEqual(crashes[0].crashDate, DUMMY_DATE);
-
- let found = yield ac.promiseFindPing("crash", [
- [["payload", "hasCrashEnvironment"], false],
- [["payload", "metadata", "k1"], "v3"],
- ]);
- Assert.ok(found, "Telemetry ping submitted for found crash");
- Assert.ok(found.environment, "There is an environment");
-
- count = yield m.aggregateEventsFiles();
- Assert.equal(count, 0);
-});
-
-add_task(function* test_crash_submission_event_file() {
- let m = yield getManager();
- yield m.createEventsFile("1", "crash.main.2", DUMMY_DATE, "crash1");
- yield m.createEventsFile("1-submission", "crash.submission.1", DUMMY_DATE_2,
- "crash1\nfalse\n");
-
- // The line below has been intentionally commented out to make sure that
- // the crash record is created when one does not exist.
- // yield m.createEventsFile("2", "crash.main.1", DUMMY_DATE, "crash2");
- yield m.createEventsFile("2-submission", "crash.submission.1", DUMMY_DATE_2,
- "crash2\ntrue\nbp-2");
- let count = yield m.aggregateEventsFiles();
- Assert.equal(count, 3);
-
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 2);
-
- let map = new Map(crashes.map(crash => [crash.id, crash]));
-
- let crash1 = map.get("crash1");
- Assert.ok(!!crash1);
- Assert.equal(crash1.remoteID, null);
- let crash2 = map.get("crash2");
- Assert.ok(!!crash2);
- Assert.equal(crash2.remoteID, "bp-2");
-
- Assert.equal(crash1.submissions.size, 1);
- let submission = crash1.submissions.values().next().value;
- Assert.equal(submission.result, m.SUBMISSION_RESULT_FAILED);
- Assert.equal(submission.requestDate.getTime(), DUMMY_DATE_2.getTime());
- Assert.equal(submission.responseDate.getTime(), DUMMY_DATE_2.getTime());
-
- Assert.equal(crash2.submissions.size, 1);
- submission = crash2.submissions.values().next().value;
- Assert.equal(submission.result, m.SUBMISSION_RESULT_OK);
- Assert.equal(submission.requestDate.getTime(), DUMMY_DATE_2.getTime());
- Assert.equal(submission.responseDate.getTime(), DUMMY_DATE_2.getTime());
-
- count = yield m.aggregateEventsFiles();
- Assert.equal(count, 0);
-});
-
-add_task(function* test_multiline_crash_id_rejected() {
- let m = yield getManager();
- yield m.createEventsFile("1", "crash.main.1", DUMMY_DATE, "id1\nid2");
- yield m.aggregateEventsFiles();
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 0);
-});
-
-// Main process crashes should be remembered beyond the high water mark.
-add_task(function* test_high_water_mark() {
- let m = yield getManager();
-
- let store = yield m._getStore();
-
- for (let i = 0; i < store.HIGH_WATER_DAILY_THRESHOLD + 1; i++) {
- yield m.createEventsFile("m" + i, "crash.main.2", DUMMY_DATE, "m" + i);
- }
-
- let count = yield m.aggregateEventsFiles();
- Assert.equal(count, bsp.CrashStore.prototype.HIGH_WATER_DAILY_THRESHOLD + 1);
-
- // Need to fetch again in case the first one was garbage collected.
- store = yield m._getStore();
-
- Assert.equal(store.crashesCount, store.HIGH_WATER_DAILY_THRESHOLD + 1);
-});
-
-add_task(function* test_addCrash() {
- let m = yield getManager();
-
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 0);
-
- yield m.addCrash(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_CRASH,
- "main-crash", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_HANG,
- "main-hang", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_CONTENT, m.CRASH_TYPE_CRASH,
- "content-crash", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_CONTENT, m.CRASH_TYPE_HANG,
- "content-hang", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_PLUGIN, m.CRASH_TYPE_CRASH,
- "plugin-crash", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_PLUGIN, m.CRASH_TYPE_HANG,
- "plugin-hang", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_GMPLUGIN, m.CRASH_TYPE_CRASH,
- "gmplugin-crash", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_GPU, m.CRASH_TYPE_CRASH,
- "gpu-crash", DUMMY_DATE);
-
- yield m.addCrash(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_CRASH,
- "changing-item", DUMMY_DATE);
- yield m.addCrash(m.PROCESS_TYPE_CONTENT, m.CRASH_TYPE_HANG,
- "changing-item", DUMMY_DATE_2);
-
- crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 9);
-
- let map = new Map(crashes.map(crash => [crash.id, crash]));
-
- let crash = map.get("main-crash");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_MAIN + "-" + m.CRASH_TYPE_CRASH);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_CRASH));
-
- crash = map.get("main-hang");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_MAIN + "-" + m.CRASH_TYPE_HANG);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_HANG));
-
- crash = map.get("content-crash");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_CONTENT + "-" + m.CRASH_TYPE_CRASH);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_CONTENT, m.CRASH_TYPE_CRASH));
-
- crash = map.get("content-hang");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_CONTENT + "-" + m.CRASH_TYPE_HANG);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_CONTENT, m.CRASH_TYPE_HANG));
-
- crash = map.get("plugin-crash");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_PLUGIN + "-" + m.CRASH_TYPE_CRASH);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_PLUGIN, m.CRASH_TYPE_CRASH));
-
- crash = map.get("plugin-hang");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_PLUGIN + "-" + m.CRASH_TYPE_HANG);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_PLUGIN, m.CRASH_TYPE_HANG));
-
- crash = map.get("gmplugin-crash");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_GMPLUGIN + "-" + m.CRASH_TYPE_CRASH);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_GMPLUGIN, m.CRASH_TYPE_CRASH));
-
- crash = map.get("gpu-crash");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE);
- Assert.equal(crash.type, m.PROCESS_TYPE_GPU+ "-" + m.CRASH_TYPE_CRASH);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_GPU, m.CRASH_TYPE_CRASH));
-
- crash = map.get("changing-item");
- Assert.ok(!!crash);
- Assert.equal(crash.crashDate, DUMMY_DATE_2);
- Assert.equal(crash.type, m.PROCESS_TYPE_CONTENT + "-" + m.CRASH_TYPE_HANG);
- Assert.ok(crash.isOfType(m.PROCESS_TYPE_CONTENT, m.CRASH_TYPE_HANG));
-});
-
-add_task(function* test_generateSubmissionID() {
- let m = yield getManager();
-
- const SUBMISSION_ID_REGEX =
- /^(sub-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
- let id = m.generateSubmissionID();
- Assert.ok(SUBMISSION_ID_REGEX.test(id));
-});
-
-add_task(function* test_addSubmissionAttemptAndResult() {
- let m = yield getManager();
-
- let crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 0);
-
- yield m.addCrash(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_CRASH,
- "main-crash", DUMMY_DATE);
- yield m.addSubmissionAttempt("main-crash", "submission", DUMMY_DATE);
- yield m.addSubmissionResult("main-crash", "submission", DUMMY_DATE_2,
- m.SUBMISSION_RESULT_OK);
-
- crashes = yield m.getCrashes();
- Assert.equal(crashes.length, 1);
-
- let submissions = crashes[0].submissions;
- Assert.ok(!!submissions);
-
- let submission = submissions.get("submission");
- Assert.ok(!!submission);
- Assert.equal(submission.requestDate.getTime(), DUMMY_DATE.getTime());
- Assert.equal(submission.responseDate.getTime(), DUMMY_DATE_2.getTime());
- Assert.equal(submission.result, m.SUBMISSION_RESULT_OK);
-});
-
-add_task(function* test_setCrashClassifications() {
- let m = yield getManager();
-
- yield m.addCrash(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_CRASH,
- "main-crash", DUMMY_DATE);
- yield m.setCrashClassifications("main-crash", ["a"]);
- let classifications = (yield m.getCrashes())[0].classifications;
- Assert.ok(classifications.indexOf("a") != -1);
-});
-
-add_task(function* test_setRemoteCrashID() {
- let m = yield getManager();
-
- yield m.addCrash(m.PROCESS_TYPE_MAIN, m.CRASH_TYPE_CRASH,
- "main-crash", DUMMY_DATE);
- yield m.setRemoteCrashID("main-crash", "bp-1");
- Assert.equal((yield m.getCrashes())[0].remoteID, "bp-1");
-});
diff --git a/toolkit/components/crashes/tests/xpcshell/test_crash_service.js b/toolkit/components/crashes/tests/xpcshell/test_crash_service.js
deleted file mode 100644
index c207057e0..000000000
--- a/toolkit/components/crashes/tests/xpcshell/test_crash_service.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://testing-common/AppData.jsm", this);
-var bsp = Cu.import("resource://gre/modules/CrashManager.jsm", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_instantiation() {
- Assert.ok(!bsp.gCrashManager, "CrashManager global instance not initially defined.");
-
- do_get_profile();
- yield makeFakeAppDir();
-
- // Fake profile creation.
- Cc["@mozilla.org/crashservice;1"]
- .getService(Ci.nsIObserver)
- .observe(null, "profile-after-change", null);
-
- Assert.ok(bsp.gCrashManager, "Profile creation makes it available.");
- Assert.ok(Services.crashmanager, "CrashManager available via Services.");
- Assert.strictEqual(bsp.gCrashManager, Services.crashmanager,
- "The objects are the same.");
-});
diff --git a/toolkit/components/crashes/tests/xpcshell/test_crash_store.js b/toolkit/components/crashes/tests/xpcshell/test_crash_store.js
deleted file mode 100644
index 12b180e91..000000000
--- a/toolkit/components/crashes/tests/xpcshell/test_crash_store.js
+++ /dev/null
@@ -1,587 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * This file tests the CrashStore type in CrashManager.jsm.
- */
-
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
-
-var bsp = Cu.import("resource://gre/modules/CrashManager.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-
-const DUMMY_DATE = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
-DUMMY_DATE.setMilliseconds(0);
-
-const DUMMY_DATE_2 = new Date(Date.now() - 5 * 24 * 60 * 60 * 1000);
-DUMMY_DATE_2.setMilliseconds(0);
-
-const {
- PROCESS_TYPE_MAIN,
- PROCESS_TYPE_CONTENT,
- PROCESS_TYPE_PLUGIN,
- PROCESS_TYPE_GMPLUGIN,
- PROCESS_TYPE_GPU,
- CRASH_TYPE_CRASH,
- CRASH_TYPE_HANG,
- SUBMISSION_RESULT_OK,
- SUBMISSION_RESULT_FAILED,
-} = CrashManager.prototype;
-
-const CrashStore = bsp.CrashStore;
-
-var STORE_DIR_COUNT = 0;
-
-function getStore() {
- return Task.spawn(function* () {
- let storeDir = do_get_tempdir().path;
- storeDir = OS.Path.join(storeDir, "store-" + STORE_DIR_COUNT++);
-
- yield OS.File.makeDir(storeDir, {unixMode: OS.Constants.libc.S_IRWXU});
-
- let s = new CrashStore(storeDir);
- yield s.load();
-
- return s;
- });
-}
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_constructor() {
- let s = new CrashStore("/some/path");
- Assert.ok(s instanceof CrashStore);
-});
-
-add_task(function* test_add_crash() {
- let s = yield getStore();
-
- Assert.equal(s.crashesCount, 0);
- let d = new Date(Date.now() - 5000);
- Assert.ok(s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id1", d));
-
- Assert.equal(s.crashesCount, 1);
-
- let crashes = s.crashes;
- Assert.equal(crashes.length, 1);
- let c = crashes[0];
-
- Assert.equal(c.id, "id1", "ID set properly.");
- Assert.equal(c.crashDate.getTime(), d.getTime(), "Date set.");
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-});
-
-add_task(function* test_reset() {
- let s = yield getStore();
-
- Assert.ok(s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id1", DUMMY_DATE));
- Assert.equal(s.crashes.length, 1);
- s.reset();
- Assert.equal(s.crashes.length, 0);
-});
-
-add_task(function* test_save_load() {
- let s = yield getStore();
-
- yield s.save();
-
- let d1 = new Date();
- let d2 = new Date(d1.getTime() - 10000);
- Assert.ok(s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id1", d1));
- Assert.ok(s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id2", d2));
- Assert.ok(s.addSubmissionAttempt("id1", "sub1", d1));
- Assert.ok(s.addSubmissionResult("id1", "sub1", d2, SUBMISSION_RESULT_OK));
- Assert.ok(s.setRemoteCrashID("id1", "bp-1"));
-
- yield s.save();
-
- yield s.load();
- Assert.ok(!s.corruptDate);
- let crashes = s.crashes;
-
- Assert.equal(crashes.length, 2);
- let c = s.getCrash("id1");
- Assert.equal(c.crashDate.getTime(), d1.getTime());
- Assert.equal(c.remoteID, "bp-1");
-
- Assert.ok(!!c.submissions);
- let submission = c.submissions.get("sub1");
- Assert.ok(!!submission);
- Assert.equal(submission.requestDate.getTime(), d1.getTime());
- Assert.equal(submission.responseDate.getTime(), d2.getTime());
- Assert.equal(submission.result, SUBMISSION_RESULT_OK);
-});
-
-add_task(function* test_corrupt_json() {
- let s = yield getStore();
-
- let buffer = new TextEncoder().encode("{bad: json-file");
- yield OS.File.writeAtomic(s._storePath, buffer, {compression: "lz4"});
-
- yield s.load();
- Assert.ok(s.corruptDate, "Corrupt date is defined.");
-
- let date = s.corruptDate;
- yield s.save();
- s._data = null;
- yield s.load();
- Assert.ok(s.corruptDate);
- Assert.equal(date.getTime(), s.corruptDate.getTime());
-});
-
-add_task(function* test_add_main_crash() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_MAIN + "-" + CRASH_TYPE_CRASH);
- Assert.ok(c.isOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- // Duplicate.
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "id3", new Date(),
- { OOMAllocationSize: 1048576 })
- );
- Assert.equal(s.crashesCount, 3);
- Assert.deepEqual(s.crashes[2].metadata, { OOMAllocationSize: 1048576 });
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 3);
-});
-
-add_task(function* test_add_main_hang() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_MAIN + "-" + CRASH_TYPE_HANG);
- Assert.ok(c.isOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 2);
-});
-
-add_task(function* test_add_content_crash() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_CONTENT + "-" + CRASH_TYPE_CRASH);
- Assert.ok(c.isOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 2);
-});
-
-add_task(function* test_add_content_hang() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_CONTENT + "-" + CRASH_TYPE_HANG);
- Assert.ok(c.isOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 2);
-});
-
-add_task(function* test_add_plugin_crash() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_PLUGIN + "-" + CRASH_TYPE_CRASH);
- Assert.ok(c.isOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 2);
-});
-
-add_task(function* test_add_plugin_hang() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_PLUGIN + "-" + CRASH_TYPE_HANG);
- Assert.ok(c.isOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 2);
-});
-
-add_task(function* test_add_gmplugin_crash() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_GMPLUGIN, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_GMPLUGIN + "-" + CRASH_TYPE_CRASH);
- Assert.ok(c.isOfType(PROCESS_TYPE_GMPLUGIN, CRASH_TYPE_CRASH));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_GMPLUGIN, CRASH_TYPE_CRASH, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_GMPLUGIN, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_GMPLUGIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 2);
-});
-
-add_task(function* test_add_gpu_crash() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_GPU, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 1);
-
- let c = s.crashes[0];
- Assert.ok(c.crashDate);
- Assert.equal(c.type, PROCESS_TYPE_GPU + "-" + CRASH_TYPE_CRASH);
- Assert.ok(c.isOfType(PROCESS_TYPE_GPU, CRASH_TYPE_CRASH));
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_GPU, CRASH_TYPE_CRASH, "id2", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_GPU, CRASH_TYPE_CRASH, "id1", new Date())
- );
- Assert.equal(s.crashesCount, 2);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_GPU, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 2);
-});
-
-add_task(function* test_add_mixed_types() {
- let s = yield getStore();
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "mcrash", new Date()) &&
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "mhang", new Date()) &&
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "ccrash", new Date()) &&
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "chang", new Date()) &&
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "pcrash", new Date()) &&
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "phang", new Date()) &&
- s.addCrash(PROCESS_TYPE_GMPLUGIN, CRASH_TYPE_CRASH, "gmpcrash", new Date()) &&
- s.addCrash(PROCESS_TYPE_GPU, CRASH_TYPE_CRASH, "gpucrash", new Date())
- );
-
- Assert.equal(s.crashesCount, 8);
-
- yield s.save();
-
- s._data.crashes.clear();
- Assert.equal(s.crashesCount, 0);
-
- yield s.load();
-
- Assert.equal(s.crashesCount, 8);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 1);
- crashes = s.getCrashesOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 1);
- crashes = s.getCrashesOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 1);
- crashes = s.getCrashesOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 1);
- crashes = s.getCrashesOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 1);
- crashes = s.getCrashesOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 1);
- crashes = s.getCrashesOfType(PROCESS_TYPE_GMPLUGIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 1);
- crashes = s.getCrashesOfType(PROCESS_TYPE_GPU, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 1);
-});
-
-// Crashes added beyond the high water mark behave properly.
-add_task(function* test_high_water() {
- let s = yield getStore();
-
- let d1 = new Date(2014, 0, 1, 0, 0, 0);
- let d2 = new Date(2014, 0, 2, 0, 0, 0);
-
- let i = 0;
- for (; i < s.HIGH_WATER_DAILY_THRESHOLD; i++) {
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "mc1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "mc2" + i, d2) &&
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "mh1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "mh2" + i, d2) &&
-
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "cc1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "cc2" + i, d2) &&
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "ch1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "ch2" + i, d2) &&
-
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "pc1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "pc2" + i, d2) &&
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "ph1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "ph2" + i, d2)
- );
- }
-
- Assert.ok(
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "mc1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "mc2" + i, d2) &&
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "mh1" + i, d1) &&
- s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG, "mh2" + i, d2)
- );
-
- Assert.ok(!s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "cc1" + i, d1));
- Assert.ok(!s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH, "cc2" + i, d2));
- Assert.ok(!s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "ch1" + i, d1));
- Assert.ok(!s.addCrash(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG, "ch2" + i, d2));
-
- Assert.ok(!s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "pc1" + i, d1));
- Assert.ok(!s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH, "pc2" + i, d2));
- Assert.ok(!s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "ph1" + i, d1));
- Assert.ok(!s.addCrash(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG, "ph2" + i, d2));
-
- // We preserve main process crashes and hangs. Content and plugin crashes and
- // hangs beyond should be discarded.
- Assert.equal(s.crashesCount, 12 * s.HIGH_WATER_DAILY_THRESHOLD + 4);
-
- let crashes = s.getCrashesOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 2 * s.HIGH_WATER_DAILY_THRESHOLD + 2);
- crashes = s.getCrashesOfType(PROCESS_TYPE_MAIN, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 2 * s.HIGH_WATER_DAILY_THRESHOLD + 2);
-
- crashes = s.getCrashesOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 2 * s.HIGH_WATER_DAILY_THRESHOLD);
- crashes = s.getCrashesOfType(PROCESS_TYPE_CONTENT, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 2 * s.HIGH_WATER_DAILY_THRESHOLD);
-
- crashes = s.getCrashesOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_CRASH);
- Assert.equal(crashes.length, 2 * s.HIGH_WATER_DAILY_THRESHOLD);
- crashes = s.getCrashesOfType(PROCESS_TYPE_PLUGIN, CRASH_TYPE_HANG);
- Assert.equal(crashes.length, 2 * s.HIGH_WATER_DAILY_THRESHOLD);
-
- // But raw counts should be preserved.
- let day1 = bsp.dateToDays(d1);
- let day2 = bsp.dateToDays(d2);
- Assert.ok(s._countsByDay.has(day1));
- Assert.ok(s._countsByDay.has(day2));
-
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_MAIN + "-" + CRASH_TYPE_CRASH),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_MAIN + "-" + CRASH_TYPE_HANG),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
-
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_CONTENT + "-" + CRASH_TYPE_CRASH),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_CONTENT + "-" + CRASH_TYPE_HANG),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
-
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_PLUGIN + "-" + CRASH_TYPE_CRASH),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_PLUGIN + "-" + CRASH_TYPE_HANG),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
-
- yield s.save();
- yield s.load();
-
- Assert.ok(s._countsByDay.has(day1));
- Assert.ok(s._countsByDay.has(day2));
-
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_MAIN + "-" + CRASH_TYPE_CRASH),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_MAIN + "-" + CRASH_TYPE_HANG),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
-
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_CONTENT + "-" + CRASH_TYPE_CRASH),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_CONTENT + "-" + CRASH_TYPE_HANG),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
-
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_PLUGIN + "-" + CRASH_TYPE_CRASH),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
- Assert.equal(s._countsByDay.get(day1).
- get(PROCESS_TYPE_PLUGIN + "-" + CRASH_TYPE_HANG),
- s.HIGH_WATER_DAILY_THRESHOLD + 1);
-});
-
-add_task(function* test_addSubmission() {
- let s = yield getStore();
-
- Assert.ok(s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "crash1",
- DUMMY_DATE));
-
- Assert.ok(s.addSubmissionAttempt("crash1", "sub1", DUMMY_DATE));
-
- let crash = s.getCrash("crash1");
- let submission = crash.submissions.get("sub1");
- Assert.ok(!!submission);
- Assert.equal(submission.requestDate.getTime(), DUMMY_DATE.getTime());
- Assert.equal(submission.responseDate, null);
- Assert.equal(submission.result, null);
-
- Assert.ok(s.addSubmissionResult("crash1", "sub1", DUMMY_DATE_2,
- SUBMISSION_RESULT_FAILED));
-
- crash = s.getCrash("crash1");
- Assert.equal(crash.submissions.size, 1);
- submission = crash.submissions.get("sub1");
- Assert.ok(!!submission);
- Assert.equal(submission.requestDate.getTime(), DUMMY_DATE.getTime());
- Assert.equal(submission.responseDate.getTime(), DUMMY_DATE_2.getTime());
- Assert.equal(submission.result, SUBMISSION_RESULT_FAILED);
-
- Assert.ok(s.addSubmissionAttempt("crash1", "sub2", DUMMY_DATE));
- Assert.ok(s.addSubmissionResult("crash1", "sub2", DUMMY_DATE_2,
- SUBMISSION_RESULT_OK));
-
- Assert.equal(crash.submissions.size, 2);
- submission = crash.submissions.get("sub2");
- Assert.ok(!!submission);
- Assert.equal(submission.result, SUBMISSION_RESULT_OK);
-});
-
-add_task(function* test_setCrashClassification() {
- let s = yield getStore();
-
- Assert.ok(s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "crash1",
- new Date()));
- let classifications = s.crashes[0].classifications;
- Assert.ok(!!classifications);
- Assert.equal(classifications.length, 0);
-
- Assert.ok(s.setCrashClassifications("crash1", ["foo", "bar"]));
- classifications = s.crashes[0].classifications;
- Assert.equal(classifications.length, 2);
- Assert.ok(classifications.indexOf("foo") != -1);
- Assert.ok(classifications.indexOf("bar") != -1);
-});
-
-add_task(function* test_setRemoteCrashID() {
- let s = yield getStore();
-
- Assert.ok(s.addCrash(PROCESS_TYPE_MAIN, CRASH_TYPE_CRASH, "crash1",
- new Date()));
- Assert.equal(s.crashes[0].remoteID, null);
- Assert.ok(s.setRemoteCrashID("crash1", "bp-1"));
- Assert.equal(s.crashes[0].remoteID, "bp-1");
-});
-
diff --git a/toolkit/components/crashes/tests/xpcshell/xpcshell.ini b/toolkit/components/crashes/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index 5cb8a69d5..000000000
--- a/toolkit/components/crashes/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-head =
-tail =
-skip-if = toolkit == 'android'
-
-[test_crash_manager.js]
-[test_crash_service.js]
-[test_crash_store.js]
diff --git a/toolkit/components/crashmonitor/moz.build b/toolkit/components/crashmonitor/moz.build
index 4656f6ab8..51f7b0d8c 100644
--- a/toolkit/components/crashmonitor/moz.build
+++ b/toolkit/components/crashmonitor/moz.build
@@ -4,8 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-
EXTRA_JS_MODULES += [
'CrashMonitor.jsm',
]
diff --git a/toolkit/components/crashmonitor/test/unit/.eslintrc.js b/toolkit/components/crashmonitor/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/crashmonitor/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/crashmonitor/test/unit/head.js b/toolkit/components/crashmonitor/test/unit/head.js
deleted file mode 100644
index 6d7d50d0c..000000000
--- a/toolkit/components/crashmonitor/test/unit/head.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-
-var sessionCheckpointsPath;
-
-/**
- * Start the tasks of the different tests
- */
-function run_test()
-{
- do_get_profile();
- sessionCheckpointsPath = OS.Path.join(OS.Constants.Path.profileDir,
- "sessionCheckpoints.json");
- Components.utils.import("resource://gre/modules/CrashMonitor.jsm");
- run_next_test();
-}
diff --git a/toolkit/components/crashmonitor/test/unit/test_init.js b/toolkit/components/crashmonitor/test/unit/test_init.js
deleted file mode 100644
index d72f46aca..000000000
--- a/toolkit/components/crashmonitor/test/unit/test_init.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test that calling |init| twice throws an error
- */
-add_task(function test_init() {
- CrashMonitor.init();
- try {
- CrashMonitor.init();
- do_check_true(false);
- } catch (ex) {
- do_check_true(true);
- }
-});
diff --git a/toolkit/components/crashmonitor/test/unit/test_invalid_file.js b/toolkit/components/crashmonitor/test/unit/test_invalid_file.js
deleted file mode 100644
index cc55a2755..000000000
--- a/toolkit/components/crashmonitor/test/unit/test_invalid_file.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test with sessionCheckpoints.json containing invalid data
- */
-add_task(function* test_invalid_file() {
- // Write bogus data to checkpoint file
- let data = "1234";
- yield OS.File.writeAtomic(sessionCheckpointsPath, data,
- {tmpPath: sessionCheckpointsPath + ".tmp"});
-
- // An invalid file will cause |init| to return null
- let status = yield CrashMonitor.init();
- do_check_true(status === null ? true : false);
-
- // and |previousCheckpoints| will be null
- let checkpoints = yield CrashMonitor.previousCheckpoints;
- do_check_true(checkpoints === null ? true : false);
-});
diff --git a/toolkit/components/crashmonitor/test/unit/test_invalid_json.js b/toolkit/components/crashmonitor/test/unit/test_invalid_json.js
deleted file mode 100644
index f3b05208a..000000000
--- a/toolkit/components/crashmonitor/test/unit/test_invalid_json.js
+++ /dev/null
@@ -1,18 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test with sessionCheckpoints.json containing invalid JSON data
- */
-add_task(function* test_invalid_file() {
- // Write bogus data to checkpoint file
- let data = "[}";
- yield OS.File.writeAtomic(sessionCheckpointsPath, data,
- {tmpPath: sessionCheckpointsPath + ".tmp"});
-
- CrashMonitor.init();
- let checkpoints = yield CrashMonitor.previousCheckpoints;
- do_check_eq(checkpoints, null);
-});
diff --git a/toolkit/components/crashmonitor/test/unit/test_missing_file.js b/toolkit/components/crashmonitor/test/unit/test_missing_file.js
deleted file mode 100644
index 9ce31da95..000000000
--- a/toolkit/components/crashmonitor/test/unit/test_missing_file.js
+++ /dev/null
@@ -1,13 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test with non-existing sessionCheckpoints.json
- */
-add_task(function* test_missing_file() {
- CrashMonitor.init();
- let checkpoints = yield CrashMonitor.previousCheckpoints;
- do_check_eq(checkpoints, null);
-});
diff --git a/toolkit/components/crashmonitor/test/unit/test_register.js b/toolkit/components/crashmonitor/test/unit/test_register.js
deleted file mode 100644
index 33c73a5ae..000000000
--- a/toolkit/components/crashmonitor/test/unit/test_register.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test that CrashMonitor.jsm is correctly loaded from XPCOM component
- */
-add_task(function test_register() {
- let cm = Components.classes["@mozilla.org/toolkit/crashmonitor;1"]
- .createInstance(Components.interfaces.nsIObserver);
-
- // Send "profile-after-change" to trigger the initialization
- cm.observe(null, "profile-after-change", null);
-
- // If CrashMonitor was initialized properly a new call to |init|
- // should fail
- try {
- CrashMonitor.init();
- do_check_true(false);
- } catch (ex) {
- do_check_true(true);
- }
-});
diff --git a/toolkit/components/crashmonitor/test/unit/test_valid_file.js b/toolkit/components/crashmonitor/test/unit/test_valid_file.js
deleted file mode 100644
index d2f214cc0..000000000
--- a/toolkit/components/crashmonitor/test/unit/test_valid_file.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test with sessionCheckpoints.json containing valid data
- */
-add_task(function* test_valid_file() {
- // Write valid data to checkpoint file
- let data = JSON.stringify({"final-ui-startup": true});
- yield OS.File.writeAtomic(sessionCheckpointsPath, data,
- {tmpPath: sessionCheckpointsPath + ".tmp"});
-
- CrashMonitor.init();
- let checkpoints = yield CrashMonitor.previousCheckpoints;
-
- do_check_true(checkpoints["final-ui-startup"]);
- do_check_eq(Object.keys(checkpoints).length, 1);
-});
diff --git a/toolkit/components/crashmonitor/test/unit/xpcshell.ini b/toolkit/components/crashmonitor/test/unit/xpcshell.ini
deleted file mode 100644
index cd86b2535..000000000
--- a/toolkit/components/crashmonitor/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-skip-if = toolkit == 'android'
-
-[test_init.js]
-[test_valid_file.js]
-[test_invalid_file.js]
-[test_invalid_json.js]
-[test_missing_file.js]
-[test_register.js]
diff --git a/toolkit/components/ctypes/moz.build b/toolkit/components/ctypes/moz.build
index c79110eeb..3270ce1d1 100644
--- a/toolkit/components/ctypes/moz.build
+++ b/toolkit/components/ctypes/moz.build
@@ -4,21 +4,10 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-TEST_DIRS += ['tests']
+LOCAL_INCLUDES += ['/js/xpconnect/loader']
-SOURCES += [
- 'ctypes.cpp',
-]
+SOURCES += ['ctypes.cpp']
-LOCAL_INCLUDES += [
- '/js/xpconnect/loader',
-]
-
-EXTRA_JS_MODULES += [
- 'ctypes.jsm',
-]
+EXTRA_JS_MODULES += ['ctypes.jsm']
FINAL_LIBRARY = 'xul'
-
-with Files('**'):
- BUG_COMPONENT = ('Core', 'js-ctypes')
diff --git a/toolkit/components/ctypes/tests/chrome/.eslintrc.js b/toolkit/components/ctypes/tests/chrome/.eslintrc.js
deleted file mode 100644
index 8c0f4f574..000000000
--- a/toolkit/components/ctypes/tests/chrome/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/ctypes/tests/chrome/chrome.ini b/toolkit/components/ctypes/tests/chrome/chrome.ini
deleted file mode 100644
index e34866be2..000000000
--- a/toolkit/components/ctypes/tests/chrome/chrome.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-skip-if = os == 'android'
-support-files =
- xpcshellTestHarnessAdaptor.js
- ctypes_worker.js
- ../unit/test_jsctypes.js
-
-[test_ctypes.xul]
diff --git a/toolkit/components/ctypes/tests/chrome/ctypes_worker.js b/toolkit/components/ctypes/tests/chrome/ctypes_worker.js
deleted file mode 100644
index ff128a758..000000000
--- a/toolkit/components/ctypes/tests/chrome/ctypes_worker.js
+++ /dev/null
@@ -1,14 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-importScripts("xpcshellTestHarnessAdaptor.js");
-
-onmessage = function(event) {
- _WORKINGDIR_ = event.data.dir;
- _OS_ = event.data.os;
- importScripts("test_jsctypes.js");
- run_test();
- postMessage("Done!");
-}
diff --git a/toolkit/components/ctypes/tests/chrome/test_ctypes.xul b/toolkit/components/ctypes/tests/chrome/test_ctypes.xul
deleted file mode 100644
index bbe7fb0c9..000000000
--- a/toolkit/components/ctypes/tests/chrome/test_ctypes.xul
+++ /dev/null
@@ -1,106 +0,0 @@
-<?xml version="1.0"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
- - License, v. 2.0. If a copy of the MPL was not distributed with this
- - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<window title="DOM Worker Threads Test"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/chrome-harness.js"/>
-
- <script type="application/javascript">
- <![CDATA[
- Components.utils.import("resource://gre/modules/ctypes.jsm");
-
- CTYPES_TEST_LIB = ctypes.libraryName("jsctypes-test");
- CTYPES_UNICODE_LIB = ctypes.libraryName("jsctyp\u00E8s-t\u00EB\u00DFt");
-
- /*
- * input: string of the url where we are running from
- * return: nsILocalFile
- */
- function getCurrentDir(path) {
- var rootDir = getRootDirectory(window.location.href);
- var jar = getJar(rootDir);
-
- if (jar) {
- return extractJarToTmp(jar);
- } else {
- return getLocalDir(path);
- }
- }
-
- function getLocalDir(path) {
- let dir = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties)
- .get("CurWorkD", Components.interfaces.nsILocalFile);
- path = location.pathname;
- path = path.slice("content/".length,
- -1 * "/test_ctypes.xul".length);
- let components = path.split("/");
- for (let part in components) {
- dir.append(components[part]);
- }
- return dir;
- }
-
- function setupLibs(path) {
- let libFile = path.clone();
- libFile.append(CTYPES_TEST_LIB);
- ok(libFile.exists(), "ctypes test library doesn't exist!?");
-
- libFile.copyTo(null, CTYPES_UNICODE_LIB);
- }
-
- function cleanupLibs(path) {
- let unicodeFile = path.clone();
- unicodeFile.append(CTYPES_UNICODE_LIB);
- ok(unicodeFile.exists(), "ctypes unicode test library doesn't exist!?");
- unicodeFile.remove(false);
- }
-
- function test()
- {
- SimpleTest.waitForExplicitFinish();
-
- var dir = getCurrentDir(location.path);
- ok(dir.exists() && dir.isDirectory(), "Chrome test dir doesn't exist?!");
- setupLibs(dir);
-
- var worker = new ChromeWorker("ctypes_worker.js");
- worker.onmessage = function(event) {
- is(event.data, "Done!", "Wrong message!");
- cleanupLibs(dir);
- SimpleTest.finish();
- }
- worker.onerror = function(event) {
- if (event.message == "uncaught exception: 7.5 million years for that?" ||
- event.message == "uncaught exception: Just following orders, sir!") {
- // We throw those on purpose in the worker, so ignore them.
- return true;
- }
- ok(false, "Worker had an error: " + event.message);
- worker.terminate();
- cleanupLibs(dir);
- SimpleTest.finish();
- }
-
- worker.postMessage({dir: dir.path, os: Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS});
- }
-
- ]]>
- </script>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
- <label id="test-result"/>
-</window>
diff --git a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js b/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js
deleted file mode 100644
index eec85025b..000000000
--- a/toolkit/components/ctypes/tests/chrome/xpcshellTestHarnessAdaptor.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var _WORKINGDIR_ = null;
-var _OS_ = null;
-
-var Components = {
- classes: { },
- interfaces: { },
- stack: {
- caller: null
- },
- utils: {
- import: function() { }
- }
-};
-
-function do_throw(message, stack) {
- do_print("error: " + message);
- do_print("stack: " + (stack ? stack : new Error().stack));
- throw message;
-}
-
-function do_check_neq(left, right, stack) {
- if (left == right) {
- var text = "do_check_neq failed";
- try {
- text += ": " + left + " == " + right;
- } catch (e) {
- }
- do_throw(text, stack);
- }
-}
-
-function do_check_eq(left, right, stack) {
- if (left != right) {
- var text = "do_check_eq failed";
- try {
- text += ": " + left + " != " + right;
- } catch (e) {
- }
- do_throw(text, stack);
- }
-}
-
-function do_check_true(condition, stack) {
- do_check_eq(condition, true, stack);
-}
-
-function do_check_false(condition, stack) {
- do_check_eq(condition, false, stack);
-}
-
-function do_print(text) {
- dump("INFO: " + text + "\n");
-}
-
-function FileFaker(path) {
- this._path = path;
-}
-FileFaker.prototype = {
- get path() {
- return this._path;
- },
- get parent() {
- let lastSlash = this._path.lastIndexOf("/");
- if (lastSlash == -1) {
- return "";
- }
- this._path = this._path.substring(0, lastSlash);
- return this;
- },
- append: function(leaf) {
- this._path = this._path + "/" + leaf;
- }
-};
-
-function do_get_file(path, allowNonexistent) {
- if (!_WORKINGDIR_) {
- do_throw("No way to fake files if working directory is unknown!");
- }
-
- let lf = new FileFaker(_WORKINGDIR_);
- let bits = path.split("/");
- for (let i = 0; i < bits.length; i++) {
- if (bits[i]) {
- if (bits[i] == "..")
- lf = lf.parent;
- else
- lf.append(bits[i]);
- }
- }
- return lf;
-}
-
-function get_os() {
- return _OS_;
-}
diff --git a/toolkit/components/ctypes/tests/jsctypes-test-errno.cpp b/toolkit/components/ctypes/tests/jsctypes-test-errno.cpp
deleted file mode 100644
index 83a29e632..000000000
--- a/toolkit/components/ctypes/tests/jsctypes-test-errno.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <stdio.h>
-#include <errno.h>
-#if defined(XP_WIN)
-#include <windows.h>
-#endif // defined(XP_WIN)
-
-#include "jsctypes-test-errno.h"
-
-
-
-#define FAIL \
-{ \
- fprintf(stderr, "Assertion failed at line %i\n", __LINE__); \
- (*(int*)nullptr)++; \
-}
-
-
-void set_errno(int status)
-{
- errno = status;
-}
-int get_errno()
-{
- return errno;
-}
-
-#if defined(XP_WIN)
-void set_last_error(int status)
-{
- SetLastError((int)status);
-}
-int get_last_error()
-{
- return (int)GetLastError();
-}
-#endif // defined(XP_WIN)
diff --git a/toolkit/components/ctypes/tests/jsctypes-test-errno.h b/toolkit/components/ctypes/tests/jsctypes-test-errno.h
deleted file mode 100644
index 4d11b905b..000000000
--- a/toolkit/components/ctypes/tests/jsctypes-test-errno.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "mozilla/Attributes.h"
-#include "mozilla/Types.h"
-
-#define EXPORT_CDECL(type) MOZ_EXPORT type
-
-MOZ_BEGIN_EXTERN_C
-
- EXPORT_CDECL(void) set_errno(int status);
- EXPORT_CDECL(int) get_errno();
-
-#if defined(XP_WIN)
- EXPORT_CDECL(void) set_last_error(int status);
- EXPORT_CDECL(int) get_last_error();
-#endif // defined(XP_WIN)
-
-MOZ_END_EXTERN_C
diff --git a/toolkit/components/ctypes/tests/jsctypes-test-finalizer.cpp b/toolkit/components/ctypes/tests/jsctypes-test-finalizer.cpp
deleted file mode 100644
index 009ba917a..000000000
--- a/toolkit/components/ctypes/tests/jsctypes-test-finalizer.cpp
+++ /dev/null
@@ -1,323 +0,0 @@
-#include "errno.h"
-
-#include "jsctypes-test.h"
-#include "jsctypes-test-finalizer.h"
-
-/**
- * Shared infrastructure
- */
-
-
-/**
- * An array of integers representing resources.
- * - 0: unacquired
- * - 1: acquired
- * - < 0: error, resource has been released several times.
- */
-int *gFinalizerTestResources = nullptr;
-char **gFinalizerTestNames = nullptr;
-size_t gFinalizerTestSize;
-
-void
-test_finalizer_start(size_t size)
-{
- gFinalizerTestResources = new int[size];
- gFinalizerTestNames = new char*[size];
- gFinalizerTestSize = size;
- for (size_t i = 0; i < size; ++i) {
- gFinalizerTestResources[i] = 0;
- gFinalizerTestNames[i] = nullptr;
- }
-}
-
-void
-test_finalizer_stop()
-{
- delete[] gFinalizerTestResources;
-}
-
-/**
- * Check if an acquired resource has been released
- */
-bool
-test_finalizer_resource_is_acquired(size_t i)
-{
- return gFinalizerTestResources[i] == 1;
-}
-// Resource type: size_t
-
-// Acquire resource i
-size_t
-test_finalizer_acq_size_t(size_t i)
-{
- gFinalizerTestResources[i] = 1;
- return i;
-}
-
-// Release resource i
-void
-test_finalizer_rel_size_t(size_t i)
-{
- if (--gFinalizerTestResources[i] < 0) {
- MOZ_CRASH("Assertion failed");
- }
-}
-
-size_t
-test_finalizer_rel_size_t_return_size_t(size_t i)
-{
- if (-- gFinalizerTestResources[i] < 0) {
- MOZ_CRASH("Assertion failed");
- }
- return i;
-}
-
-myRECT
-test_finalizer_rel_size_t_return_struct_t(size_t i)
-{
- if (-- gFinalizerTestResources[i] < 0) {
- MOZ_CRASH("Assertion failed");
- }
- const int32_t narrowed = (int32_t)i;
- myRECT result = { narrowed, narrowed, narrowed, narrowed };
- return result;
-}
-
-bool
-test_finalizer_cmp_size_t(size_t a, size_t b)
-{
- return a==b;
-}
-
-// Resource type: int32_t
-
-// Acquire resource i
-int32_t
-test_finalizer_acq_int32_t(size_t i)
-{
- gFinalizerTestResources[i] = 1;
- return i;
-}
-
-// Release resource i
-void
-test_finalizer_rel_int32_t(int32_t i)
-{
- if (--gFinalizerTestResources[i] < 0) {
- MOZ_CRASH("Assertion failed");
- }
-}
-
-bool
-test_finalizer_cmp_int32_t(int32_t a, int32_t b)
-{
- return a==b;
-}
-
-// Resource type: int64_t
-
-// Acquire resource i
-int64_t
-test_finalizer_acq_int64_t(size_t i)
-{
- gFinalizerTestResources[i] = 1;
- return i;
-}
-
-// Release resource i
-void
-test_finalizer_rel_int64_t(int64_t i)
-{
- if (-- gFinalizerTestResources[i] < 0) {
- MOZ_CRASH("Assertion failed");
- }
-}
-
-bool
-test_finalizer_cmp_int64_t(int64_t a, int64_t b)
-{
- return a==b;
-}
-
-// Resource type: void*
-
-// Acquire resource i
-void*
-test_finalizer_acq_ptr_t(size_t i)
-{
- gFinalizerTestResources[i] = 1;
- return (void*)&gFinalizerTestResources[i];
-}
-
-// Release resource i
-void
-test_finalizer_rel_ptr_t(void *i)
-{
- int *as_int = (int*)i;
- -- (*as_int);
- if (*as_int < 0) {
- MOZ_CRASH("Assertion failed");
- }
-}
-
-bool
-test_finalizer_cmp_ptr_t(void *a, void *b)
-{
- return a==b;
-}
-
-// Resource type: int32_t*
-
-// Acquire resource i
-int32_t*
-test_finalizer_acq_int32_ptr_t(size_t i)
-{
- gFinalizerTestResources[i] = 1;
- return (int32_t*)&gFinalizerTestResources[i];
-}
-
-// Release resource i
-void
-test_finalizer_rel_int32_ptr_t(int32_t *i)
-{
- -- (*i);
- if (*i < 0) {
- MOZ_CRASH("Assertion failed");
- }
-}
-
-bool
-test_finalizer_cmp_int32_ptr_t(int32_t *a, int32_t *b)
-{
- return a==b;
-}
-
-// Resource type: nullptr
-
-// Acquire resource i
-void*
-test_finalizer_acq_null_t(size_t i)
-{
- gFinalizerTestResources[0] = 1;//Always index 0
- return nullptr;
-}
-
-// Release resource i
-void
-test_finalizer_rel_null_t(void *i)
-{
- if (i != nullptr) {
- MOZ_CRASH("Assertion failed");
- }
- gFinalizerTestResources[0] --;
-}
-
-bool
-test_finalizer_null_resource_is_acquired(size_t)
-{
- return gFinalizerTestResources[0] == 1;
-}
-
-bool
-test_finalizer_cmp_null_t(void *a, void *b)
-{
- return a==b;
-}
-
-// Resource type: char*
-
-// Acquire resource i
-char*
-test_finalizer_acq_string_t(int i)
-{
- gFinalizerTestResources[i] = 1;
- if (!gFinalizerTestNames[i]) {
- char* buf = new char[12];
- snprintf(buf, 12, "%d", i);
- gFinalizerTestNames[i] = buf;
- return buf;
- }
- return gFinalizerTestNames[i];
-}
-
-// Release resource i
-void
-test_finalizer_rel_string_t(char *i)
-{
- int index = atoi(i);
- if (index < 0 || index >= (int)gFinalizerTestSize) {
- MOZ_CRASH("Assertion failed");
- }
- gFinalizerTestResources[index] --;
-}
-
-bool
-test_finalizer_string_resource_is_acquired(size_t i)
-{
- return gFinalizerTestResources[i] == 1;
-}
-
-bool
-test_finalizer_cmp_string_t(char *a, char *b)
-{
- return !strncmp(a, b, 10);
-}
-
-// Resource type: myRECT
-
-// Acquire resource i
-myRECT
-test_finalizer_acq_struct_t(int i)
-{
- gFinalizerTestResources[i] = 1;
- myRECT result = { i, i, i, i };
- return result;
-}
-
-// Release resource i
-void
-test_finalizer_rel_struct_t(myRECT i)
-{
- int index = i.top;
- if (index < 0 || index >= (int)gFinalizerTestSize) {
- MOZ_CRASH("Assertion failed");
- }
- gFinalizerTestResources[index] --;
-}
-
-bool
-test_finalizer_struct_resource_is_acquired(myRECT i)
-{
- int index = i.top;
- if (index < 0 || index >= (int)gFinalizerTestSize) {
- MOZ_CRASH("Assertion failed");
- }
- return gFinalizerTestResources[index] == 1;
-}
-
-bool
-test_finalizer_cmp_struct_t(myRECT a, myRECT b)
-{
- return a.top == b.top;
-}
-
-// Support for checking that we reject nullptr finalizer
-afun* test_finalizer_rel_null_function()
-{
- return nullptr;
-}
-
-void
-test_finalizer_rel_size_t_set_errno(size_t i)
-{
- if (-- gFinalizerTestResources[i] < 0) {
- MOZ_CRASH("Assertion failed");
- }
- errno = 10;
-}
-
-void
-reset_errno()
-{
- errno = 0;
-}
diff --git a/toolkit/components/ctypes/tests/jsctypes-test-finalizer.h b/toolkit/components/ctypes/tests/jsctypes-test-finalizer.h
deleted file mode 100644
index f942e7f44..000000000
--- a/toolkit/components/ctypes/tests/jsctypes-test-finalizer.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "mozilla/Attributes.h"
-#include "mozilla/Types.h"
-
-#define EXPORT_CDECL(type) MOZ_EXPORT type
-
-MOZ_BEGIN_EXTERN_C
-
- EXPORT_CDECL(void) test_finalizer_start(size_t size);
- EXPORT_CDECL(void) test_finalizer_stop();
- EXPORT_CDECL(bool) test_finalizer_resource_is_acquired(size_t i);
-
- EXPORT_CDECL(size_t) test_finalizer_acq_size_t(size_t i);
- EXPORT_CDECL(void) test_finalizer_rel_size_t(size_t i);
- EXPORT_CDECL(size_t) test_finalizer_rel_size_t_return_size_t(size_t i);
- EXPORT_CDECL(myRECT) test_finalizer_rel_size_t_return_struct_t(size_t i);
- EXPORT_CDECL(bool) test_finalizer_cmp_size_t(size_t a, size_t b);
-
- EXPORT_CDECL(int32_t) test_finalizer_acq_int32_t(size_t i);
- EXPORT_CDECL(void) test_finalizer_rel_int32_t(int32_t i);
- EXPORT_CDECL(bool) test_finalizer_cmp_int32_t(int32_t a, int32_t b);
-
- EXPORT_CDECL(int64_t) test_finalizer_acq_int64_t(size_t i);
- EXPORT_CDECL(void) test_finalizer_rel_int64_t(int64_t i);
- EXPORT_CDECL(bool) test_finalizer_cmp_int64_t(int64_t a, int64_t b);
-
- EXPORT_CDECL(void*) test_finalizer_acq_ptr_t(size_t i);
- EXPORT_CDECL(void) test_finalizer_rel_ptr_t(void *i);
- EXPORT_CDECL(bool) test_finalizer_cmp_ptr_t(void *a, void *b);
-
- EXPORT_CDECL(int32_t*) test_finalizer_acq_int32_ptr_t(size_t i);
- EXPORT_CDECL(void) test_finalizer_rel_int32_ptr_t(int32_t *i);
- EXPORT_CDECL(bool) test_finalizer_cmp_int32_ptr_t(int32_t *a, int32_t *b);
-
- EXPORT_CDECL(char*) test_finalizer_acq_string_t(int i);
- EXPORT_CDECL(void) test_finalizer_rel_string_t(char *i);
- EXPORT_CDECL(bool) test_finalizer_cmp_string_t(char *a, char *b);
-
- EXPORT_CDECL(void*) test_finalizer_acq_null_t(size_t i);
- EXPORT_CDECL(void) test_finalizer_rel_null_t(void *i);
- EXPORT_CDECL(bool) test_finalizer_cmp_null_t(void *a, void *b);
- EXPORT_CDECL(bool) test_finalizer_null_resource_is_acquired(size_t i);
-
- EXPORT_CDECL(myRECT) test_finalizer_acq_struct_t(int i);
- EXPORT_CDECL(void) test_finalizer_rel_struct_t(myRECT i);
- EXPORT_CDECL(bool) test_finalizer_cmp_struct_t(myRECT a, myRECT b);
-
- typedef void (*afun)(size_t);
- EXPORT_CDECL(afun*) test_finalizer_rel_null_function();
-
- EXPORT_CDECL(void) test_finalizer_rel_size_t_set_errno(size_t i);
- EXPORT_CDECL(void) reset_errno();
-
-MOZ_END_EXTERN_C
diff --git a/toolkit/components/ctypes/tests/jsctypes-test.cpp b/toolkit/components/ctypes/tests/jsctypes-test.cpp
deleted file mode 100644
index d0e84a66c..000000000
--- a/toolkit/components/ctypes/tests/jsctypes-test.cpp
+++ /dev/null
@@ -1,394 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "jsctypes-test.h"
-#include <math.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include "typedefs.h"
-
-template <typename T> struct ValueTraits {
- static T literal() { return static_cast<T>(109.25); }
- static T sum(T a, T b) { return a + b; }
- static T sum_many(
- T a, T b, T c, T d, T e, T f, T g, T h, T i,
- T j, T k, T l, T m, T n, T o, T p, T q, T r)
- {
- return a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r;
- }
-};
-
-template <> struct ValueTraits<bool> {
- typedef bool T;
- static T literal() { return true; }
- static T sum(T a, T b) { return a || b; }
- static T sum_many(
- T a, T b, T c, T d, T e, T f, T g, T h, T i,
- T j, T k, T l, T m, T n, T o, T p, T q, T r)
- {
- return a || b || c || d || e || f || g || h || i ||
- j || k || l || m || n || o || p || q || r;
- }
-};
-
-void
-test_void_t_cdecl()
-{
- // do nothing
- return;
-}
-
-// The "AndUnderscore" bit here is an unfortunate hack: the first argument to
-// DEFINE_CDECL_FUNCTIONS and DEFINE_STDCALL_FUNCTIONS, in addition to being a
-// type, may also be a *macro* on NetBSD -- #define int8_t __int8_t and so on.
-// See <http://mail-index.netbsd.org/tech-toolchain/2014/12/18/msg002479.html>.
-// And unfortunately, passing that macro as an argument to this macro causes it
-// to be expanded -- producing get___int8_t_cdecl() and so on. Concatenating
-// int8_t with _ slightly muddies this code but inhibits expansion. See also
-// bug 1113379.
-#define FUNCTION_TESTS(nameAndUnderscore, type, ffiType, suffix) \
-type ABI \
-get_##nameAndUnderscore##suffix() \
-{ \
- return ValueTraits<type>::literal(); \
-} \
- \
-type ABI \
-set_##nameAndUnderscore##suffix(type x) \
-{ \
- return x; \
-} \
- \
-type ABI \
-sum_##nameAndUnderscore##suffix(type x, type y) \
-{ \
- return ValueTraits<type>::sum(x, y); \
-} \
- \
-type ABI \
-sum_alignb_##nameAndUnderscore##suffix(char a, type x, char b, type y, char c)\
-{ \
- return ValueTraits<type>::sum(x, y); \
-} \
- \
-type ABI \
-sum_alignf_##nameAndUnderscore##suffix(float a, type x, float b, type y, float c)\
-{ \
- return ValueTraits<type>::sum(x, y); \
-} \
- \
-type ABI \
-sum_many_##nameAndUnderscore##suffix( \
- type a, type b, type c, type d, type e, type f, type g, type h, type i, \
- type j, type k, type l, type m, type n, type o, type p, type q, type r) \
-{ \
- return ValueTraits<type>::sum_many(a, b, c, d, e, f, g, h, i, \
- j, k, l, m, n, o, p, q, r); \
-}
-
-#define ABI /* cdecl */
-#define DEFINE_CDECL_FUNCTIONS(x, y, z) FUNCTION_TESTS(x##_, y, z, cdecl)
-CTYPES_FOR_EACH_TYPE(DEFINE_CDECL_FUNCTIONS)
-#undef DEFINE_CDECL_FUNCTIONS
-#undef ABI
-
-#if defined(_WIN32)
-
-void NS_STDCALL
-test_void_t_stdcall()
-{
- // do nothing
- return;
-}
-
-#define ABI NS_STDCALL
-#define DEFINE_STDCALL_FUNCTIONS(x, y, z) FUNCTION_TESTS(x##_, y, z, stdcall)
-CTYPES_FOR_EACH_TYPE(DEFINE_STDCALL_FUNCTIONS)
-#undef DEFINE_STDCALL_FUNCTIONS
-#undef ABI
-
-#endif /* defined(_WIN32) */
-
-#define DEFINE_CDECL_TYPE_STATS(name, type, ffiType) \
-struct align_##name { \
- char x; \
- type y; \
-}; \
-struct nested_##name { \
- char a; \
- align_##name b; \
- char c; \
-}; \
- \
-void \
-get_##name##_stats(size_t* align, size_t* size, size_t* nalign, size_t* nsize, \
- size_t offsets[]) \
-{ \
- *align = offsetof(align_##name, y); \
- *size = sizeof(align_##name); \
- *nalign = offsetof(nested_##name, b); \
- *nsize = sizeof(nested_##name); \
- offsets[0] = offsetof(align_##name, y); \
- offsets[1] = offsetof(nested_##name, b); \
- offsets[2] = offsetof(nested_##name, c); \
-}
-CTYPES_FOR_EACH_TYPE(DEFINE_CDECL_TYPE_STATS)
-#undef DEFINE_CDECL_TYPE_STATS
-
-template <typename T>
-int32_t StrLen(const T* string)
-{
- const T *end;
- for (end = string; *end; ++end);
- return end - string;
-}
-
-int32_t
-test_ansi_len(const char* string)
-{
- return StrLen(string);
-}
-
-int32_t
-test_wide_len(const char16_t* string)
-{
- return StrLen(string);
-}
-
-const char *
-test_ansi_ret()
-{
- return "success";
-}
-
-const char16_t *
-test_wide_ret()
-{
- static const char16_t kSuccess[] = {'s', 'u', 'c', 'c', 'e', 's', 's', '\0'};
- return kSuccess;
-}
-
-char *
-test_ansi_echo(const char* string)
-{
- return (char*)string;
-}
-
-int32_t
-test_pt_in_rect(myRECT rc, myPOINT pt)
-{
- if (pt.x < rc.left || pt.x > rc.right)
- return 0;
- if (pt.y < rc.bottom || pt.y > rc.top)
- return 0;
- return 1;
-}
-
-void
-test_init_pt(myPOINT* pt, int32_t x, int32_t y)
-{
- pt->x = x;
- pt->y = y;
-}
-
-int32_t
-test_nested_struct(NESTED n)
-{
- return int32_t(n.n1 + n.n2 + n.inner.i1 + n.inner.i2 + n.inner.i3 + n.n3 + n.n4);
-}
-
-myPOINT
-test_struct_return(myRECT r)
-{
- myPOINT p;
- p.x = r.left; p.y = r.top;
- return p;
-}
-
-myRECT
-test_large_struct_return(myRECT a, myRECT b)
-{
- myRECT r;
- r.left = a.left; r.right = a.right;
- r.top = b.top; r.bottom = b.bottom;
- return r;
-}
-
-ONE_BYTE
-test_1_byte_struct_return(myRECT r)
-{
- ONE_BYTE s;
- s.a = r.top;
- return s;
-}
-
-TWO_BYTE
-test_2_byte_struct_return(myRECT r)
-{
- TWO_BYTE s;
- s.a = r.top;
- s.b = r.left;
- return s;
-}
-
-THREE_BYTE
-test_3_byte_struct_return(myRECT r)
-{
- THREE_BYTE s;
- s.a = r.top;
- s.b = r.left;
- s.c = r.bottom;
- return s;
-}
-
-FOUR_BYTE
-test_4_byte_struct_return(myRECT r)
-{
- FOUR_BYTE s;
- s.a = r.top;
- s.b = r.left;
- s.c = r.bottom;
- s.d = r.right;
- return s;
-}
-
-FIVE_BYTE
-test_5_byte_struct_return(myRECT r)
-{
- FIVE_BYTE s;
- s.a = r.top;
- s.b = r.left;
- s.c = r.bottom;
- s.d = r.right;
- s.e = r.top;
- return s;
-}
-
-SIX_BYTE
-test_6_byte_struct_return(myRECT r)
-{
- SIX_BYTE s;
- s.a = r.top;
- s.b = r.left;
- s.c = r.bottom;
- s.d = r.right;
- s.e = r.top;
- s.f = r.left;
- return s;
-}
-
-SEVEN_BYTE
-test_7_byte_struct_return(myRECT r)
-{
- SEVEN_BYTE s;
- s.a = r.top;
- s.b = r.left;
- s.c = r.bottom;
- s.d = r.right;
- s.e = r.top;
- s.f = r.left;
- s.g = r.bottom;
- return s;
-}
-
-void *
-test_fnptr()
-{
- return (void*)(uintptr_t)test_ansi_len;
-}
-
-int32_t
-test_closure_cdecl(int8_t i, test_func_ptr f)
-{
- return f(i);
-}
-
-#if defined(_WIN32)
-int32_t
-test_closure_stdcall(int8_t i, test_func_ptr_stdcall f)
-{
- return f(i);
-}
-#endif /* defined(_WIN32) */
-
-template <typename T> struct PromotedTraits {
- typedef T type;
-};
-#define DECL_PROMOTED(FROM, TO) \
- template <> struct PromotedTraits<FROM> { \
- typedef TO type; \
- }
-DECL_PROMOTED(bool, int);
-DECL_PROMOTED(char, int);
-DECL_PROMOTED(short, int);
-
-int32_t
-test_sum_va_cdecl(uint8_t n, ...)
-{
- va_list list;
- int32_t sum = 0;
- va_start(list, n);
- for (uint8_t i = 0; i < n; ++i)
- sum += va_arg(list, PromotedTraits<int32_t>::type);
- va_end(list);
- return sum;
-}
-
-uint8_t
-test_count_true_va_cdecl(uint8_t n, ...)
-{
- va_list list;
- uint8_t count = 0;
- va_start(list, n);
- for (uint8_t i = 0; i < n; ++i)
- if (va_arg(list, PromotedTraits<bool>::type))
- count += 1;
- va_end(list);
- return count;
-}
-
-void
-test_add_char_short_int_va_cdecl(uint32_t* result, ...)
-{
- va_list list;
- va_start(list, result);
- *result += va_arg(list, PromotedTraits<char>::type);
- *result += va_arg(list, PromotedTraits<short>::type);
- *result += va_arg(list, PromotedTraits<int>::type);
- va_end(list);
-}
-
-int32_t*
-test_vector_add_va_cdecl(uint8_t num_vecs,
- uint8_t vec_len,
- int32_t* result, ...)
-{
- va_list list;
- va_start(list, result);
- uint8_t i;
- for (i = 0; i < vec_len; ++i)
- result[i] = 0;
- for (i = 0; i < num_vecs; ++i) {
- int32_t* vec = va_arg(list, int32_t*);
- for (uint8_t j = 0; j < vec_len; ++j)
- result[j] += vec[j];
- }
- va_end(list);
- return result;
-}
-
-myRECT data_rect = { -1, -2, 3, 4 };
-
-TestClass::TestClass(int32_t a)
-{
- mInt =a;
-}
-
-int32_t
-TestClass::Add(int32_t aOther)
-{
- mInt += aOther;
- return mInt;
-}
diff --git a/toolkit/components/ctypes/tests/jsctypes-test.h b/toolkit/components/ctypes/tests/jsctypes-test.h
deleted file mode 100644
index 14eb8c915..000000000
--- a/toolkit/components/ctypes/tests/jsctypes-test.h
+++ /dev/null
@@ -1,197 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef jsctypes_test_h
-#define jsctypes_test_h
-
-#include "mozilla/Attributes.h"
-#include "mozilla/Types.h"
-#include "jspubtd.h"
-#include "typedefs.h"
-
-#define EXPORT_CDECL(type) MOZ_EXPORT type
-#if defined(_WIN32)
-#if defined(_WIN64)
-#define NS_STDCALL
-#else
-#define NS_STDCALL __stdcall
-#endif
-#define EXPORT_STDCALL(type) MOZ_EXPORT type NS_STDCALL
-#endif
-
-MOZ_BEGIN_EXTERN_C
-
- EXPORT_CDECL(void) test_void_t_cdecl();
-
- EXPORT_CDECL(void*) get_voidptr_t_cdecl();
- EXPORT_CDECL(void*) set_voidptr_t_cdecl(void*);
-
-#define DECLARE_CDECL_FUNCTIONS(name, type, ffiType) \
- EXPORT_CDECL(type) get_##name##_cdecl(); \
- EXPORT_CDECL(type) set_##name##_cdecl(type); \
- EXPORT_CDECL(type) sum_##name##_cdecl(type, type); \
- EXPORT_CDECL(type) sum_alignb_##name##_cdecl(char, type, char, type, char); \
- EXPORT_CDECL(type) sum_alignf_##name##_cdecl( \
- float, type, float, type, float); \
- EXPORT_CDECL(type) sum_many_##name##_cdecl( \
- type, type, type, type, type, type, type, type, type, \
- type, type, type, type, type, type, type, type, type); \
- \
- EXPORT_CDECL(void) get_##name##_stats(size_t* align, size_t* size, \
- size_t* nalign, size_t* nsize, \
- size_t offsets[]);
- CTYPES_FOR_EACH_TYPE(DECLARE_CDECL_FUNCTIONS)
-#undef DECLARE_CDECL_FUNCTIONS
-
-#if defined(_WIN32)
- EXPORT_STDCALL(void) test_void_t_stdcall();
-
- EXPORT_STDCALL(void*) get_voidptr_t_stdcall();
- EXPORT_STDCALL(void*) set_voidptr_t_stdcall(void*);
-
-#define DECLARE_STDCALL_FUNCTIONS(name, type, ffiType) \
- EXPORT_STDCALL(type) get_##name##_stdcall(); \
- EXPORT_STDCALL(type) set_##name##_stdcall(type); \
- EXPORT_STDCALL(type) sum_##name##_stdcall(type, type); \
- EXPORT_STDCALL(type) sum_alignb_##name##_stdcall( \
- char, type, char, type, char); \
- EXPORT_STDCALL(type) sum_alignf_##name##_stdcall( \
- float, type, float, type, float); \
- EXPORT_STDCALL(type) sum_many_##name##_stdcall( \
- type, type, type, type, type, type, type, type, type, \
- type, type, type, type, type, type, type, type, type);
- CTYPES_FOR_EACH_TYPE(DECLARE_STDCALL_FUNCTIONS)
-#undef DECLARE_STDCALL_FUNCTIONS
-
-#endif /* defined(_WIN32) */
-
- MOZ_EXPORT int32_t test_ansi_len(const char*);
- MOZ_EXPORT int32_t test_wide_len(const char16_t*);
- MOZ_EXPORT const char* test_ansi_ret();
- MOZ_EXPORT const char16_t* test_wide_ret();
- MOZ_EXPORT char* test_ansi_echo(const char*);
-
- struct ONE_BYTE {
- char a;
- };
-
- struct TWO_BYTE {
- char a;
- char b;
- };
-
- struct THREE_BYTE {
- char a;
- char b;
- char c;
- };
-
- struct FOUR_BYTE {
- char a;
- char b;
- char c;
- char d;
- };
-
- struct FIVE_BYTE {
- char a;
- char b;
- char c;
- char d;
- char e;
- };
-
- struct SIX_BYTE {
- char a;
- char b;
- char c;
- char d;
- char e;
- char f;
- };
-
- struct SEVEN_BYTE {
- char a;
- char b;
- char c;
- char d;
- char e;
- char f;
- char g;
- };
-
- struct myPOINT {
- int32_t x;
- int32_t y;
- };
-
- struct myRECT {
- int32_t top;
- int32_t left;
- int32_t bottom;
- int32_t right;
- };
-
- struct INNER {
- uint8_t i1;
- int64_t i2;
- uint8_t i3;
- };
-
- struct NESTED {
- int32_t n1;
- int16_t n2;
- INNER inner;
- int64_t n3;
- int32_t n4;
- };
-
- MOZ_EXPORT int32_t test_pt_in_rect(myRECT, myPOINT);
- MOZ_EXPORT void test_init_pt(myPOINT* pt, int32_t x, int32_t y);
-
- MOZ_EXPORT int32_t test_nested_struct(NESTED);
- MOZ_EXPORT myPOINT test_struct_return(myRECT);
- MOZ_EXPORT myRECT test_large_struct_return(myRECT, myRECT);
- MOZ_EXPORT ONE_BYTE test_1_byte_struct_return(myRECT);
- MOZ_EXPORT TWO_BYTE test_2_byte_struct_return(myRECT);
- MOZ_EXPORT THREE_BYTE test_3_byte_struct_return(myRECT);
- MOZ_EXPORT FOUR_BYTE test_4_byte_struct_return(myRECT);
- MOZ_EXPORT FIVE_BYTE test_5_byte_struct_return(myRECT);
- MOZ_EXPORT SIX_BYTE test_6_byte_struct_return(myRECT);
- MOZ_EXPORT SEVEN_BYTE test_7_byte_struct_return(myRECT);
-
- MOZ_EXPORT void * test_fnptr();
-
- typedef int32_t (* test_func_ptr)(int8_t);
- MOZ_EXPORT int32_t test_closure_cdecl(int8_t, test_func_ptr);
-#if defined(_WIN32)
- typedef int32_t (NS_STDCALL * test_func_ptr_stdcall)(int8_t);
- MOZ_EXPORT int32_t test_closure_stdcall(int8_t, test_func_ptr_stdcall);
-#endif /* defined(_WIN32) */
-
- MOZ_EXPORT int32_t test_callme(int8_t);
- MOZ_EXPORT void* test_getfn();
-
- EXPORT_CDECL(int32_t) test_sum_va_cdecl(uint8_t n, ...);
- EXPORT_CDECL(uint8_t) test_count_true_va_cdecl(uint8_t n, ...);
- EXPORT_CDECL(void) test_add_char_short_int_va_cdecl(uint32_t* result, ...);
- EXPORT_CDECL(int32_t*) test_vector_add_va_cdecl(uint8_t num_vecs,
- uint8_t vec_len,
- int32_t* result, ...);
-
- MOZ_EXPORT extern myRECT data_rect;
-
-MOZ_END_EXTERN_C
-
-class MOZ_EXPORT TestClass final {
-public:
- explicit TestClass(int32_t);
- int32_t Add(int32_t);
-
-private:
- int32_t mInt;
-};
-
-#endif
diff --git a/toolkit/components/ctypes/tests/moz.build b/toolkit/components/ctypes/tests/moz.build
deleted file mode 100644
index 22cbe4edc..000000000
--- a/toolkit/components/ctypes/tests/moz.build
+++ /dev/null
@@ -1,30 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-DIST_INSTALL = False
-
-XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell.ini']
-MOCHITEST_CHROME_MANIFESTS += ['chrome/chrome.ini']
-
-UNIFIED_SOURCES += [
- 'jsctypes-test-errno.cpp',
- 'jsctypes-test-finalizer.cpp',
- 'jsctypes-test.cpp',
-]
-
-SharedLibrary('jsctypes-test')
-
-LOCAL_INCLUDES += [
- '/js/src/ctypes',
-]
-
-# Don't use STL wrappers here (i.e. wrapped <new>); they require mozalloc.
-DISABLE_STL_WRAPPING = True
-
-if CONFIG['COMPILE_ENVIRONMENT']:
- shared_library = '!%sjsctypes-test%s' % (CONFIG['DLL_PREFIX'], CONFIG['DLL_SUFFIX'])
- TEST_HARNESS_FILES.xpcshell.toolkit.components.ctypes.tests.unit += [shared_library]
- TEST_HARNESS_FILES.testing.mochitest.chrome.toolkit.components.ctypes.tests.chrome += [shared_library]
diff --git a/toolkit/components/ctypes/tests/unit/.eslintrc.js b/toolkit/components/ctypes/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/ctypes/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/ctypes/tests/unit/head.js b/toolkit/components/ctypes/tests/unit/head.js
deleted file mode 100644
index e95b949b6..000000000
--- a/toolkit/components/ctypes/tests/unit/head.js
+++ /dev/null
@@ -1,128 +0,0 @@
-try {
- // We might be running without privileges, in which case it's up to the
- // harness to give us the 'ctypes' object.
- Components.utils.import("resource://gre/modules/ctypes.jsm");
-} catch (e) {
-}
-
-function open_ctypes_test_lib()
-{
- return ctypes.open(do_get_file(ctypes.libraryName("jsctypes-test")).path);
-}
-
-/**
- * A weak set of CDataFinalizer values that need to be cleaned up before
- * proceeding to the next test.
- */
-function ResourceCleaner() {
- this._map = new WeakMap();
-}
-ResourceCleaner.prototype = {
- add: function ResourceCleaner_add(v) {
- this._map.set(v);
- return v;
- },
- cleanup: function ResourceCleaner_cleanup() {
- let keys = ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(this._map);
- keys.forEach((function cleaner(k) {
- try {
- k.dispose();
- } catch (x) {
- // This can fail if |forget|/|dispose| has been called manually
- // during the test. This is normal.
- }
- this._map.delete(k);
- }).bind(this));
- }
-};
-
-/**
- * Simple wrapper for tests that require cleanup.
- */
-function ResourceTester(start, stop) {
- this._start = start;
- this._stop = stop;
-}
-ResourceTester.prototype = {
- launch: function(size, test, args) {
- trigger_gc();
- let cleaner = new ResourceCleaner();
- this._start(size);
- try {
- test(size, args, cleaner);
- } catch (x) {
- cleaner.cleanup();
- this._stop();
- throw x;
- }
- trigger_gc();
- cleaner.cleanup();
- this._stop();
- }
-};
-
-function structural_check_eq(a, b) {
- // 1. If objects can be "toSource()-ed", use this.
-
- let result;
- let finished = false;
- let asource, bsource;
- try {
- asource = a.toSource();
- bsource = b.toSource();
- finished = true;
- } catch (x) {
- }
- if (finished) {
- do_check_eq(asource, bsource);
- return;
- }
-
- // 2. Otherwise, perform slower comparison
-
- try {
- structural_check_eq_aux(a, b);
- result = true;
- } catch (x) {
- dump(x);
- result = false;
- }
- do_check_true(result);
-}
-function structural_check_eq_aux(a, b) {
- let ak;
- try {
- ak = Object.keys(a);
- } catch (x) {
- if (a != b) {
- throw new Error("Distinct values "+a, b);
- }
- return;
- }
- ak.forEach(
- function(k) {
- let av = a[k];
- let bv = b[k];
- structural_check_eq_aux(av, bv);
- }
- );
-}
-
-function trigger_gc() {
- dump("Triggering garbage-collection");
- Components.utils.forceGC();
-}
-
-function must_throw(f) {
- let has_thrown = false;
- try {
- f();
- } catch (x) {
- has_thrown = true;
- }
- do_check_true(has_thrown);
-}
-
-function get_os() {
- return Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS;
-}
diff --git a/toolkit/components/ctypes/tests/unit/test_errno.js b/toolkit/components/ctypes/tests/unit/test_errno.js
deleted file mode 100644
index 6bf6b4b05..000000000
--- a/toolkit/components/ctypes/tests/unit/test_errno.js
+++ /dev/null
@@ -1,69 +0,0 @@
-Components.utils.import("resource://gre/modules/ctypes.jsm");
-
-// Scope used to relaunch the tests with |ctypes| opened in a limited scope.
-var scope = {};
-var ctypes = ctypes;
-
-function run_test()
-{
- // Launch the test with regular loading of ctypes.jsm
- main_test();
-
- // Relaunch the test with exotic loading of ctypes.jsm
- Components.utils.unload("resource://gre/modules/ctypes.jsm");
- Components.utils.import("resource://gre/modules/ctypes.jsm", scope);
- ctypes = scope.ctypes;
- main_test();
-}
-
-function main_test()
-{
- "use strict";
- let library = open_ctypes_test_lib();
- let set_errno = library.declare("set_errno", ctypes.default_abi,
- ctypes.void_t,
- ctypes.int);
- let get_errno = library.declare("get_errno", ctypes.default_abi,
- ctypes.int);
-
- for (let i = 50; i >= 0; --i) {
- set_errno(i);
- let status = ctypes.errno;
- do_check_eq(status, i);
-
- status = get_errno();
- do_check_eq(status, 0);
-
- status = ctypes.errno;
- do_check_eq(status, 0);
- }
-
- let set_last_error, get_last_error;
- try { // The following test is Windows-specific
- set_last_error = library.declare("set_last_error", ctypes.default_abi,
- ctypes.void_t,
- ctypes.int);
- get_last_error = library.declare("get_last_error", ctypes.default_abi,
- ctypes.int);
-
- } catch (x) {
- do_check_eq(ctypes.winLastError, undefined);
- }
-
- if (set_last_error) {
- do_check_neq(ctypes.winLastError, undefined);
- for (let i = 0; i < 50; ++i) {
- set_last_error(i);
- let status = ctypes.winLastError;
- do_check_eq(status, i);
-
- status = get_last_error();
- do_check_eq(status, 0);
-
- status = ctypes.winLastError;
- do_check_eq(status, 0);
- }
- }
-
- library.close();
-}
diff --git a/toolkit/components/ctypes/tests/unit/test_finalizer.js b/toolkit/components/ctypes/tests/unit/test_finalizer.js
deleted file mode 100644
index adfb4c4b4..000000000
--- a/toolkit/components/ctypes/tests/unit/test_finalizer.js
+++ /dev/null
@@ -1,452 +0,0 @@
-var TEST_SIZE = 100;
-
-function run_test()
-{
- let library = open_ctypes_test_lib();
-
- let start = library.declare("test_finalizer_start", ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t);
- let stop = library.declare("test_finalizer_stop", ctypes.default_abi,
- ctypes.void_t);
- let status = library.declare("test_finalizer_resource_is_acquired",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.size_t);
- let released = function released(value, witness) {
- return witness == undefined;
- };
-
- let samples = [];
- samples.push(
- {
- name: "size_t",
- acquire: library.declare("test_finalizer_acq_size_t",
- ctypes.default_abi,
- ctypes.size_t,
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_size_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t),
- compare: library.declare("test_finalizer_cmp_size_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.size_t,
- ctypes.size_t),
- status: status,
- released: released
- });
- samples.push(
- {
- name: "size_t",
- acquire: library.declare("test_finalizer_acq_size_t",
- ctypes.default_abi,
- ctypes.size_t,
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_size_t_set_errno",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t),
- compare: library.declare("test_finalizer_cmp_size_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.size_t,
- ctypes.size_t),
- status: status,
- released: released
- });
- samples.push(
- {
- name: "int32_t",
- acquire: library.declare("test_finalizer_acq_int32_t",
- ctypes.default_abi,
- ctypes.int32_t,
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_int32_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.int32_t),
- compare: library.declare("test_finalizer_cmp_int32_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.int32_t,
- ctypes.int32_t),
- status: status,
- released: released
- }
- );
- samples.push(
- {
- name: "int64_t",
- acquire: library.declare("test_finalizer_acq_int64_t",
- ctypes.default_abi,
- ctypes.int64_t,
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_int64_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.int64_t),
- compare: library.declare("test_finalizer_cmp_int64_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.int64_t,
- ctypes.int64_t),
- status: status,
- released: released
- }
- );
- samples.push(
- {
- name: "ptr",
- acquire: library.declare("test_finalizer_acq_ptr_t",
- ctypes.default_abi,
- ctypes.PointerType(ctypes.void_t),
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_ptr_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.PointerType(ctypes.void_t)),
- compare: library.declare("test_finalizer_cmp_ptr_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.void_t.ptr,
- ctypes.void_t.ptr),
- status: status,
- released: released
- }
- );
- samples.push(
- {
- name: "string",
- acquire: library.declare("test_finalizer_acq_string_t",
- ctypes.default_abi,
- ctypes.char.ptr,
- ctypes.int),
- release: library.declare("test_finalizer_rel_string_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.char.ptr),
- compare: library.declare("test_finalizer_cmp_string_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.char.ptr,
- ctypes.char.ptr),
- status: status,
- released: released
- }
- );
- const rect_t = new ctypes.StructType("myRECT",
- [{ top : ctypes.int32_t },
- { left : ctypes.int32_t },
- { bottom: ctypes.int32_t },
- { right : ctypes.int32_t }]);
- samples.push(
- {
- name: "struct",
- acquire: library.declare("test_finalizer_acq_struct_t",
- ctypes.default_abi,
- rect_t,
- ctypes.int),
- release: library.declare("test_finalizer_rel_struct_t",
- ctypes.default_abi,
- ctypes.void_t,
- rect_t),
- compare: library.declare("test_finalizer_cmp_struct_t",
- ctypes.default_abi,
- ctypes.bool,
- rect_t,
- rect_t),
- status: status,
- released: released
- }
- );
- samples.push(
- {
- name: "size_t, release returns size_t",
- acquire: library.declare("test_finalizer_acq_size_t",
- ctypes.default_abi,
- ctypes.size_t,
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_size_t_return_size_t",
- ctypes.default_abi,
- ctypes.size_t,
- ctypes.size_t),
- compare: library.declare("test_finalizer_cmp_size_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.size_t,
- ctypes.size_t),
- status: status,
- released: function released_eq(i, witness) {
- return i == witness;
- }
- }
- );
- samples.push(
- {
- name: "size_t, release returns myRECT",
- acquire: library.declare("test_finalizer_acq_size_t",
- ctypes.default_abi,
- ctypes.size_t,
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_size_t_return_struct_t",
- ctypes.default_abi,
- rect_t,
- ctypes.size_t),
- compare: library.declare("test_finalizer_cmp_size_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.size_t,
- ctypes.size_t),
- status: status,
- released: function released_rect_eq(i, witness) {
- return witness.top == i
- && witness.bottom == i
- && witness.left == i
- && witness.right == i;
- }
- }
- );
- samples.push(
- {
- name: "using null",
- acquire: library.declare("test_finalizer_acq_null_t",
- ctypes.default_abi,
- ctypes.PointerType(ctypes.void_t),
- ctypes.size_t),
- release: library.declare("test_finalizer_rel_null_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.PointerType(ctypes.void_t)),
- status: library.declare("test_finalizer_null_resource_is_acquired",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.size_t),
- compare: library.declare("test_finalizer_cmp_null_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.void_t.ptr,
- ctypes.void_t.ptr),
- released: released
- }
- );
-
- let tester = new ResourceTester(start, stop);
- samples.forEach(
- function run_sample(sample) {
- dump("Executing finalization test for data " + sample.name + "\n");
- tester.launch(TEST_SIZE, test_executing_finalizers, sample);
- tester.launch(TEST_SIZE, test_do_not_execute_finalizers_on_referenced_stuff, sample);
- tester.launch(TEST_SIZE, test_executing_dispose, sample);
- tester.launch(TEST_SIZE, test_executing_forget, sample);
- tester.launch(TEST_SIZE, test_result_dispose, sample);
- dump("Successfully completed finalization test for data " + sample.name + "\n");
- }
- );
-
- /*
- * Following test deactivated: Cycle collection never takes place
- * (see bug 727371)
- tester.launch(TEST_SIZE, test_cycles, samples[0]);
- */
- dump("Successfully completed all finalization tests\n");
- library.close();
-}
-
-// If only I could have Promises to test this :)
-// There is only so much we can do at this stage,
-// if we want to avoid tests overlapping.
-function test_cycles(size, tc) {
- // Now, restart this with unreferenced cycles
- for (i = 0; i < size/2; ++i) {
- let a = {
- a: ctypes.CDataFinalizer(tc.acquire(i*2), tc.release),
- b: {
- b: ctypes.CDataFinalizer(tc.acquire(i*2+1), tc.release)
- }
- };
- a.b.a = a;
- }
- do_test_pending();
-
- Components.utils.schedulePreciseGC(
- function after_gc() {
- // Check that _something_ has been finalized
- do_check_true(count_finalized(size, tc) > 0);
- do_test_finished();
- }
- );
-
- do_timeout(10000, do_throw);
-}
-
-
-function count_finalized(size, tc) {
- let finalizedItems = 0;
- for (let i = 0; i < size; ++i) {
- if (!tc.status(i)) {
- ++finalizedItems;
- }
- }
- return finalizedItems;
-}
-
-/**
- * Test:
- * - that (some) finalizers are executed;
- * - that no finalizer is executed twice (this is done on the C side).
- */
-function test_executing_finalizers(size, tc, cleanup)
-{
- dump("test_executing_finalizers " + tc.name + "\n");
- // Allocate |size| items without references
- for (let i = 0; i < size; ++i) {
- cleanup.add(ctypes.CDataFinalizer(tc.acquire(i), tc.release));
- }
- trigger_gc(); // This should trigger some finalizations, hopefully all
-
- // Check that _something_ has been finalized
- do_check_true(count_finalized(size, tc) > 0);
-}
-
-/**
- * Check that
- * - |dispose| returns the proper result
- */
-function test_result_dispose(size, tc, cleanup) {
- dump("test_result_dispose " + tc.name + "\n");
- let ref = [];
- // Allocate |size| items with references
- for (let i = 0; i < size; ++i) {
- let value = ctypes.CDataFinalizer(tc.acquire(i), tc.release);
- cleanup.add(value);
- ref.push(value);
- }
- do_check_eq(count_finalized(size, tc), 0);
-
- for (i = 0; i < size; ++i) {
- let witness = ref[i].dispose();
- ref[i] = null;
- if (!tc.released(i, witness)) {
- do_print("test_result_dispose failure at index "+i);
- do_check_true(false);
- }
- }
-
- do_check_eq(count_finalized(size, tc), size);
-}
-
-
-/**
- * Check that
- * - |dispose| is executed properly
- * - finalizers are not executed after |dispose|
- */
-function test_executing_dispose(size, tc, cleanup)
-{
- dump("test_executing_dispose " + tc.name + "\n");
- let ref = [];
- // Allocate |size| items with references
- for (let i = 0; i < size; ++i) {
- let value = ctypes.CDataFinalizer(tc.acquire(i), tc.release);
- cleanup.add(value);
- ref.push(value);
- }
- do_check_eq(count_finalized(size, tc), 0);
-
- // Dispose of everything and make sure that everything has been cleaned up
- ref.forEach(
- function dispose(v) {
- v.dispose();
- }
- );
- do_check_eq(count_finalized(size, tc), size);
-
- // Remove references
- ref = [];
-
- // Re-acquire data and make sure that everything has been reinialized
- for (i = 0; i < size; ++i) {
- tc.acquire(i);
- }
-
- do_check_eq(count_finalized(size, tc), 0);
-
-
- // Attempt to trigger finalizations, ensure that they do not take place
- trigger_gc();
-
- do_check_eq(count_finalized(size, tc), 0);
-}
-
-
-/**
- * Check that
- * - |forget| does not dispose
- * - |forget| has the right content
- * - finalizers are not executed after |forget|
- */
-function test_executing_forget(size, tc, cleanup)
-{
- dump("test_executing_forget " + tc.name + "\n");
- let ref = [];
- // Allocate |size| items with references
- for (let i = 0; i < size; ++i) {
- let original = tc.acquire(i);
- let finalizer = ctypes.CDataFinalizer(original, tc.release);
- ref.push(
- {
- original: original,
- finalizer: finalizer
- }
- );
- cleanup.add(finalizer);
- do_check_true(tc.compare(original, finalizer));
- }
- do_check_eq(count_finalized(size, tc), 0);
-
- // Forget everything, making sure that we recover the original info
- ref.forEach(
- function compare_original_to_recovered(v) {
- let original = v.original;
- let recovered = v.finalizer.forget();
- // Note: Cannot use do_check_eq on Uint64 et al.
- do_check_true(tc.compare(original, recovered));
- do_check_eq(original.constructor, recovered.constructor);
- }
- );
-
- // Also make sure that we have not performed any clean up
- do_check_eq(count_finalized(size, tc), 0);
-
- // Remove references
- ref = [];
-
- // Attempt to trigger finalizations, ensure that they have no effect
- trigger_gc();
-
- do_check_eq(count_finalized(size, tc), 0);
-}
-
-
-/**
- * Check that finalizers are not executed
- */
-function test_do_not_execute_finalizers_on_referenced_stuff(size, tc, cleanup)
-{
- dump("test_do_not_execute_finalizers_on_referenced_stuff " + tc.name + "\n");
-
- let ref = [];
- // Allocate |size| items without references
- for (let i = 0; i < size; ++i) {
- let value = ctypes.CDataFinalizer(tc.acquire(i), tc.release);
- cleanup.add(value);
- ref.push(value);
- }
- trigger_gc(); // This might trigger some finalizations, but it should not
-
- // Check that _nothing_ has been finalized
- do_check_eq(count_finalized(size, tc), 0);
-}
-
diff --git a/toolkit/components/ctypes/tests/unit/test_finalizer_shouldaccept.js b/toolkit/components/ctypes/tests/unit/test_finalizer_shouldaccept.js
deleted file mode 100644
index f683008e4..000000000
--- a/toolkit/components/ctypes/tests/unit/test_finalizer_shouldaccept.js
+++ /dev/null
@@ -1,174 +0,0 @@
-try {
- // We might be running without privileges, in which case it's up to the
- // harness to give us the 'ctypes' object.
- Components.utils.import("resource://gre/modules/ctypes.jsm");
-} catch (e) {
-}
-
-var acquire, dispose, reset_errno, dispose_errno,
- acquire_ptr, dispose_ptr,
- acquire_void_ptr, dispose_void_ptr,
- acquire_string, dispose_string;
-
-function run_test()
-{
- let library = open_ctypes_test_lib();
-
- let start = library.declare("test_finalizer_start", ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t);
- let stop = library.declare("test_finalizer_stop", ctypes.default_abi,
- ctypes.void_t);
- let tester = new ResourceTester(start, stop);
- acquire = library.declare("test_finalizer_acq_size_t",
- ctypes.default_abi,
- ctypes.size_t,
- ctypes.size_t);
- dispose = library.declare("test_finalizer_rel_size_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t);
- reset_errno = library.declare("reset_errno",
- ctypes.default_abi,
- ctypes.void_t);
- dispose_errno = library.declare("test_finalizer_rel_size_t_set_errno",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t);
- acquire_ptr = library.declare("test_finalizer_acq_int32_ptr_t",
- ctypes.default_abi,
- ctypes.int32_t.ptr,
- ctypes.size_t);
- dispose_ptr = library.declare("test_finalizer_rel_int32_ptr_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.int32_t.ptr);
- acquire_string = library.declare("test_finalizer_acq_string_t",
- ctypes.default_abi,
- ctypes.char.ptr,
- ctypes.size_t);
- dispose_string = library.declare("test_finalizer_rel_string_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.char.ptr);
-
- tester.launch(10, test_to_string);
- tester.launch(10, test_to_source);
- tester.launch(10, test_to_int);
- tester.launch(10, test_errno);
- tester.launch(10, test_to_pointer);
- tester.launch(10, test_readstring);
-}
-
-/**
- * Check that toString succeeds before/after forget/dispose.
- */
-function test_to_string()
-{
- do_print("Starting test_to_string");
- let a = ctypes.CDataFinalizer(acquire(0), dispose);
- do_check_eq(a.toString(), "0");
-
- a.forget();
- do_check_eq(a.toString(), "[CDataFinalizer - empty]");
-
- a = ctypes.CDataFinalizer(acquire(0), dispose);
- a.dispose();
- do_check_eq(a.toString(), "[CDataFinalizer - empty]");
-}
-
-/**
- * Check that toSource succeeds before/after forget/dispose.
- */
-function test_to_source()
-{
- do_print("Starting test_to_source");
- let value = acquire(0);
- let a = ctypes.CDataFinalizer(value, dispose);
- do_check_eq(a.toSource(),
- "ctypes.CDataFinalizer("
- + ctypes.size_t(value).toSource()
- +", "
- +dispose.toSource()
- +")");
- value = null;
-
- a.forget();
- do_check_eq(a.toSource(), "ctypes.CDataFinalizer()");
-
- a = ctypes.CDataFinalizer(acquire(0), dispose);
- a.dispose();
- do_check_eq(a.toSource(), "ctypes.CDataFinalizer()");
-}
-
-/**
- * Test conversion to int32
- */
-function test_to_int()
-{
- let value = 2;
- let wrapped, converted, finalizable;
- wrapped = ctypes.int32_t(value);
- finalizable = ctypes.CDataFinalizer(acquire(value), dispose);
- converted = ctypes.int32_t(finalizable);
-
- structural_check_eq(converted, wrapped);
- structural_check_eq(converted, ctypes.int32_t(finalizable.forget()));
-
- finalizable = ctypes.CDataFinalizer(acquire(value), dispose);
- wrapped = ctypes.int64_t(value);
- converted = ctypes.int64_t(finalizable);
- structural_check_eq(converted, wrapped);
- finalizable.dispose();
-}
-
-/**
- * Test that dispose can change errno but finalization cannot
- */
-function test_errno(size, tc, cleanup)
-{
- reset_errno();
- do_check_eq(ctypes.errno, 0);
-
- let finalizable = ctypes.CDataFinalizer(acquire(3), dispose_errno);
- finalizable.dispose();
- do_check_eq(ctypes.errno, 10);
- reset_errno();
-
- do_check_eq(ctypes.errno, 0);
- for (let i = 0; i < size; ++i) {
- finalizable = ctypes.CDataFinalizer(acquire(i), dispose_errno);
- cleanup.add(finalizable);
- }
-
- trigger_gc();
- do_check_eq(ctypes.errno, 0);
-}
-
-/**
- * Check that a finalizable of a pointer can be used as a pointer
- */
-function test_to_pointer()
-{
- let ptr = ctypes.int32_t(2).address();
- let finalizable = ctypes.CDataFinalizer(ptr, dispose_ptr);
- let unwrapped = ctypes.int32_t.ptr(finalizable);
-
- do_check_eq(""+ptr, ""+unwrapped);
-
- finalizable.forget(); // Do not dispose: This is not a real pointer.
-}
-
-/**
- * Test that readstring can be applied to a finalizer
- */
-function test_readstring(size)
-{
- for (let i = 0; i < size; ++i) {
- let acquired = acquire_string(i);
- let finalizable = ctypes.CDataFinalizer(acquired,
- dispose_string);
- do_check_eq(finalizable.readString(), acquired.readString());
- finalizable.dispose();
- }
-}
diff --git a/toolkit/components/ctypes/tests/unit/test_finalizer_shouldfail.js b/toolkit/components/ctypes/tests/unit/test_finalizer_shouldfail.js
deleted file mode 100644
index ffbe1b613..000000000
--- a/toolkit/components/ctypes/tests/unit/test_finalizer_shouldfail.js
+++ /dev/null
@@ -1,176 +0,0 @@
-try {
- // We might be running without privileges, in which case it's up to the
- // harness to give us the 'ctypes' object.
- Components.utils.import("resource://gre/modules/ctypes.jsm");
-} catch (e) {
-}
-
-var acquire, dispose, null_dispose, compare, dispose_64;
-
-function run_test()
-{
- let library = open_ctypes_test_lib();
-
- let start = library.declare("test_finalizer_start", ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t);
- let stop = library.declare("test_finalizer_stop", ctypes.default_abi,
- ctypes.void_t);
- let tester = new ResourceTester(start, stop);
- acquire = library.declare("test_finalizer_acq_size_t",
- ctypes.default_abi,
- ctypes.size_t,
- ctypes.size_t);
- dispose = library.declare("test_finalizer_rel_size_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.size_t);
- compare = library.declare("test_finalizer_cmp_size_t",
- ctypes.default_abi,
- ctypes.bool,
- ctypes.size_t,
- ctypes.size_t);
-
- dispose_64 = library.declare("test_finalizer_rel_int64_t",
- ctypes.default_abi,
- ctypes.void_t,
- ctypes.int64_t);
-
- let type_afun = ctypes.FunctionType(ctypes.default_abi,
- ctypes.void_t,
- [ctypes.size_t]).ptr;
-
- let null_dispose_maker =
- library.declare("test_finalizer_rel_null_function",
- ctypes.default_abi,
- type_afun
- );
- null_dispose = null_dispose_maker();
-
- tester.launch(10, test_double_dispose);
- tester.launch(10, test_finalize_bad_construction);
- tester.launch(10, test_null_dispose);
- tester.launch(10, test_pass_disposed);
- tester.launch(10, test_wrong_type);
-}
-
-
-/**
- * Testing construction of finalizers with wrong arguments.
- */
-function test_finalize_bad_construction() {
- // First argument does not match second
- must_throw(function() { ctypes.CDataFinalizer({}, dispose); });
- must_throw(function() { ctypes.CDataFinalizer(dispose, dispose); });
-
- // Not enough arguments
- must_throw(function() { ctypes.CDataFinalizer(init(0)); });
-
- // Too many arguments
- must_throw(function() { ctypes.CDataFinalizer(init(0), dispose, dispose); });
-
- // Second argument is null
- must_throw(function() { ctypes.CDataFinalizer(init(0), null); });
-
- // Second argument is undefined
- must_throw(function() {
- let a;
- ctypes.CDataFinalizer(init(0), a);
- });
-
-}
-
-/**
- * Test that forget/dispose can only take place once.
- */
-function test_double_dispose() {
- function test_one_combination(i, a, b) {
- let v = ctypes.CDataFinalizer(acquire(i), dispose);
- a(v);
- must_throw(function() { b(v); } );
- }
-
- let call_dispose = function(v) {
- v.dispose();
- };
- let call_forget = function(v) {
- v.forget();
- };
-
- test_one_combination(0, call_dispose, call_dispose);
- test_one_combination(1, call_dispose, call_forget);
- test_one_combination(2, call_forget, call_dispose);
- test_one_combination(3, call_forget, call_forget);
-}
-
-
-/**
- * Test that nothing (too) bad happens when the finalizer is NULL
- */
-function test_null_dispose()
-{
- let exception;
-
- exception = false;
- try {
- ctypes.CDataFinalizer(acquire(0), null_dispose);
- } catch (x) {
- exception = true;
- }
- do_check_true(exception);
-}
-
-/**
- * Test that conversion of a disposed/forgotten CDataFinalizer to a C
- * value fails nicely.
- */
-function test_pass_disposed()
-{
- let exception, v;
-
- exception = false;
- v = ctypes.CDataFinalizer(acquire(0), dispose);
- do_check_true(compare(v, 0));
- v.forget();
-
- try {
- compare(v, 0);
- } catch (x) {
- exception = true;
- }
- do_check_true(exception);
-
- exception = false;
- v = ctypes.CDataFinalizer(acquire(0), dispose);
- do_check_true(compare(v, 0));
- v.dispose();
-
- try {
- compare(v, 0);
- } catch (x) {
- exception = true;
- }
- do_check_true(exception);
-
- exception = false;
- try {
- ctypes.int32_t(ctypes.CDataFinalizer(v, dispose));
- } catch (x) {
- exception = true;
- }
- do_check_true(exception);
-}
-
-function test_wrong_type()
-{
- let int32_v = ctypes.int32_t(99);
- let exception;
- try {
- ctypes.CDataFinalizer(int32_v, dispose_64);
- } catch (x) {
- exception = x;
- }
-
- do_check_true(!!exception);
- do_check_eq(exception.constructor.name, "TypeError");
-}
diff --git a/toolkit/components/ctypes/tests/unit/test_jsctypes.js b/toolkit/components/ctypes/tests/unit/test_jsctypes.js
deleted file mode 100644
index ec35ee18e..000000000
--- a/toolkit/components/ctypes/tests/unit/test_jsctypes.js
+++ /dev/null
@@ -1,2808 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-try {
- // We might be running without privileges, in which case it's up to the
- // harness to give us the 'ctypes' object.
- Components.utils.import("resource://gre/modules/ctypes.jsm");
-} catch (e) {
-}
-
-CTYPES_TEST_LIB = ctypes.libraryName("jsctypes-test");
-CTYPES_UNICODE_LIB = ctypes.libraryName("jsctyp\u00E8s-t\u00EB\u00DFt");
-
-function do_check_throws(f, type, stack)
-{
- if (!stack) {
- try {
- // We might not have a 'Components' object.
- stack = Components.stack.caller;
- } catch (e) {
- }
- }
-
- try {
- f();
- } catch (exc) {
- if (exc.constructor.name === type.name) {
- do_check_true(true);
- return;
- }
- do_throw("expected " + type.name + " exception, caught " + exc, stack);
- }
- do_throw("expected " + type.name + " exception, none thrown", stack);
-}
-
-function run_test()
-{
- // Test ctypes.CType and ctypes.CData are set up correctly.
- run_abstract_class_tests();
-
- // open the library
- let libfile = do_get_file(CTYPES_TEST_LIB);
- let library = ctypes.open(libfile.path);
-
- // Make sure we can call a function in the library.
- run_void_tests(library);
-
- // Test Int64 and UInt64.
- run_Int64_tests();
- run_UInt64_tests();
-
- // Test the basic bool, integer, and float types.
- run_bool_tests(library);
-
- run_integer_tests(library, ctypes.int8_t, "int8_t", 1, true, [-0x80, 0x7f]);
- run_integer_tests(library, ctypes.int16_t, "int16_t", 2, true, [-0x8000, 0x7fff]);
- run_integer_tests(library, ctypes.int32_t, "int32_t", 4, true, [-0x80000000, 0x7fffffff]);
- run_integer_tests(library, ctypes.uint8_t, "uint8_t", 1, false, [0, 0xff]);
- run_integer_tests(library, ctypes.uint16_t, "uint16_t", 2, false, [0, 0xffff]);
- run_integer_tests(library, ctypes.uint32_t, "uint32_t", 4, false, [0, 0xffffffff]);
- run_integer_tests(library, ctypes.short, "short", 2, true, [-0x8000, 0x7fff]);
- run_integer_tests(library, ctypes.unsigned_short, "unsigned_short", 2, false, [0, 0xffff]);
- run_integer_tests(library, ctypes.int, "int", 4, true, [-0x80000000, 0x7fffffff]);
- run_integer_tests(library, ctypes.unsigned_int, "unsigned_int", 4, false, [0, 0xffffffff]);
- run_integer_tests(library, ctypes.unsigned, "unsigned_int", 4, false, [0, 0xffffffff]);
-
- run_float_tests(library, ctypes.float32_t, "float32_t", 4);
- run_float_tests(library, ctypes.float64_t, "float64_t", 8);
- run_float_tests(library, ctypes.float, "float", 4);
- run_float_tests(library, ctypes.double, "double", 8);
-
- // Test the wrapped integer types.
- s64limits = ["-9223372036854775808", "9223372036854775807",
- "-9223372036854775809", "9223372036854775808"];
- u64limits = ["0", "18446744073709551615", "-1", "18446744073709551616"];
-
- run_wrapped_integer_tests(library, ctypes.int64_t, "int64_t", 8, true,
- ctypes.Int64, "ctypes.Int64", s64limits);
- run_wrapped_integer_tests(library, ctypes.uint64_t, "uint64_t", 8, false,
- ctypes.UInt64, "ctypes.UInt64", u64limits);
- run_wrapped_integer_tests(library, ctypes.long_long, "long_long", 8, true,
- ctypes.Int64, "ctypes.Int64", s64limits);
- run_wrapped_integer_tests(library, ctypes.unsigned_long_long, "unsigned_long_long", 8, false,
- ctypes.UInt64, "ctypes.UInt64", u64limits);
-
- s32limits = [-0x80000000, 0x7fffffff, -0x80000001, 0x80000000];
- u32limits = [0, 0xffffffff, -1, 0x100000000];
-
- let slimits, ulimits;
- if (ctypes.long.size == 8) {
- slimits = s64limits;
- ulimits = u64limits;
- } else if (ctypes.long.size == 4) {
- slimits = s32limits;
- ulimits = u32limits;
- } else {
- do_throw("ctypes.long is not 4 or 8 bytes");
- }
-
- run_wrapped_integer_tests(library, ctypes.long, "long", ctypes.long.size, true,
- ctypes.Int64, "ctypes.Int64", slimits);
- run_wrapped_integer_tests(library, ctypes.unsigned_long, "unsigned_long", ctypes.long.size, false,
- ctypes.UInt64, "ctypes.UInt64", ulimits);
-
- if (ctypes.size_t.size == 8) {
- slimits = s64limits;
- ulimits = u64limits;
- } else if (ctypes.size_t.size == 4) {
- slimits = s32limits;
- ulimits = u32limits;
- } else {
- do_throw("ctypes.size_t is not 4 or 8 bytes");
- }
-
- run_wrapped_integer_tests(library, ctypes.size_t, "size_t", ctypes.size_t.size, false,
- ctypes.UInt64, "ctypes.UInt64", ulimits);
- run_wrapped_integer_tests(library, ctypes.ssize_t, "ssize_t", ctypes.size_t.size, true,
- ctypes.Int64, "ctypes.Int64", slimits);
- run_wrapped_integer_tests(library, ctypes.uintptr_t, "uintptr_t", ctypes.size_t.size, false,
- ctypes.UInt64, "ctypes.UInt64", ulimits);
- run_wrapped_integer_tests(library, ctypes.intptr_t, "intptr_t", ctypes.size_t.size, true,
- ctypes.Int64, "ctypes.Int64", slimits);
-
- if (ctypes.off_t.size == 8) {
- slimits = s64limits;
- ulimits = u64limits;
- } else if (ctypes.off_t.size == 4) {
- slimits = s32limits;
- ulimits = u32limits;
- } else {
- do_throw("ctypes.off_t is not 4 or 8 bytes");
- }
- run_wrapped_integer_tests(library, ctypes.off_t, "off_t", ctypes.off_t.size, true,
- ctypes.Int64, "ctypes.Int64", slimits);
-
- // Test the character types.
- run_char_tests(library, ctypes.char, "char", 1, true, [-0x80, 0x7f]);
- run_char_tests(library, ctypes.signed_char, "signed_char", 1, true, [-0x80, 0x7f]);
- run_char_tests(library, ctypes.unsigned_char, "unsigned_char", 1, false, [0, 0xff]);
- run_char16_tests(library, ctypes.char16_t, "char16_t", [0, 0xffff]);
-
- // Test the special types.
- run_StructType_tests();
- run_PointerType_tests();
- run_FunctionType_tests();
- run_ArrayType_tests();
-
- // Check that types print properly.
- run_type_toString_tests();
-
- // Test the 'name' and 'toSource' of a long typename.
- let ptrTo_ptrTo_arrayOf4_ptrTo_int32s =
- new ctypes.PointerType(
- new ctypes.PointerType(
- new ctypes.ArrayType(
- new ctypes.PointerType(ctypes.int32_t), 4)));
- do_check_eq(ptrTo_ptrTo_arrayOf4_ptrTo_int32s.name, "int32_t*(**)[4]");
-
- let source_t = new ctypes.StructType("source",
- [{ a: ptrTo_ptrTo_arrayOf4_ptrTo_int32s }, { b: ctypes.int64_t }]);
- do_check_eq(source_t.toSource(),
- 'ctypes.StructType("source", [{ "a": ctypes.int32_t.ptr.array(4).ptr.ptr }, ' +
- '{ "b": ctypes.int64_t }])');
-
- // Test ctypes.cast.
- run_cast_tests();
-
- run_string_tests(library);
- run_readstring_tests(library);
- run_struct_tests(library);
- run_function_tests(library);
- run_closure_tests(library);
- run_variadic_tests(library);
- run_static_data_tests(library);
- run_cpp_class_tests(library);
-
- // test library.close
- let test_void_t = library.declare("test_void_t_cdecl", ctypes.default_abi, ctypes.void_t);
- library.close();
- do_check_throws(function() { test_void_t(); }, Error);
- do_check_throws(function() {
- library.declare("test_void_t_cdecl", ctypes.default_abi, ctypes.void_t);
- }, Error);
-
- // test that library functions throw when bound to other objects
- library = ctypes.open(libfile.path);
- let obj = {};
- obj.declare = library.declare;
- do_check_throws(function () { run_void_tests(obj); }, Error);
- obj.close = library.close;
- do_check_throws(function () { obj.close(); }, Error);
-
- // test that functions work as properties of other objects
- let getter = library.declare("get_int8_t_cdecl", ctypes.default_abi, ctypes.int8_t);
- do_check_eq(getter(), 109);
- obj.t = getter;
- do_check_eq(obj.t(), 109);
-
- // bug 521937
- do_check_throws(function () { let nolib = ctypes.open("notfoundlibrary.dll"); nolib.close(); }, Error);
-
- // bug 522360
- do_check_eq(run_load_system_library(), true);
-
- // Test loading a library with a unicode name (bug 589413). Note that nsIFile
- // implementations are not available in some harnesses; if not, the harness
- // should take care of the copy for us.
- let unicodefile = do_get_file(CTYPES_UNICODE_LIB, true);
- let copy = libfile.copyTo instanceof Function;
- if (copy)
- libfile.copyTo(null, unicodefile.leafName);
- library = ctypes.open(unicodefile.path);
- run_void_tests(library);
- library.close();
- if (copy)
- unicodefile.remove(false);
-}
-
-function run_abstract_class_tests()
-{
- // Test that ctypes.CType is an abstract constructor that throws.
- do_check_throws(function() { ctypes.CType(); }, TypeError);
- do_check_throws(function() { new ctypes.CType() }, TypeError);
-
- do_check_true(ctypes.CType.hasOwnProperty("prototype"));
- do_check_throws(function() { ctypes.CType.prototype(); }, TypeError);
- do_check_throws(function() { new ctypes.CType.prototype() }, TypeError);
-
- do_check_true(ctypes.CType.prototype.hasOwnProperty("constructor"));
- do_check_true(ctypes.CType.prototype.constructor === ctypes.CType);
-
- // Check that ctypes.CType.prototype has the correct properties and functions.
- do_check_true(ctypes.CType.prototype.hasOwnProperty("name"));
- do_check_true(ctypes.CType.prototype.hasOwnProperty("size"));
- do_check_true(ctypes.CType.prototype.hasOwnProperty("ptr"));
- do_check_true(ctypes.CType.prototype.hasOwnProperty("array"));
- do_check_true(ctypes.CType.prototype.hasOwnProperty("toString"));
- do_check_true(ctypes.CType.prototype.hasOwnProperty("toSource"));
-
- // Make sure we can access 'prototype' on a CTypeProto.
- do_check_true(ctypes.CType.prototype.prototype === ctypes.CData.prototype);
-
- // Check that the shared properties and functions on ctypes.CType.prototype throw.
- do_check_throws(function() { ctypes.CType.prototype.name; }, TypeError);
- do_check_throws(function() { ctypes.CType.prototype.size; }, TypeError);
- do_check_throws(function() { ctypes.CType.prototype.ptr; }, TypeError);
- do_check_throws(function() { ctypes.CType.prototype.array(); }, TypeError);
-
-
- // toString and toSource are called by the web console during inspection,
- // so we don't want them to throw.
- do_check_eq(typeof ctypes.CType.prototype.toString(), 'string');
- do_check_eq(typeof ctypes.CType.prototype.toSource(), 'string');
-
- // Test that ctypes.CData is an abstract constructor that throws.
- do_check_throws(function() { ctypes.CData(); }, TypeError);
- do_check_throws(function() { new ctypes.CData() }, TypeError);
-
- do_check_true(ctypes.CData.__proto__ === ctypes.CType.prototype);
- do_check_true(ctypes.CData instanceof ctypes.CType);
-
- do_check_true(ctypes.CData.hasOwnProperty("prototype"));
- do_check_true(ctypes.CData.prototype.hasOwnProperty("constructor"));
- do_check_true(ctypes.CData.prototype.constructor === ctypes.CData);
-
- // Check that ctypes.CData.prototype has the correct properties and functions.
- do_check_true(ctypes.CData.prototype.hasOwnProperty("value"));
- do_check_true(ctypes.CData.prototype.hasOwnProperty("address"));
- do_check_true(ctypes.CData.prototype.hasOwnProperty("readString"));
- do_check_true(ctypes.CData.prototype.hasOwnProperty("toString"));
- do_check_true(ctypes.CData.prototype.hasOwnProperty("toSource"));
-
- // Check that the shared properties and functions on ctypes.CData.prototype throw.
- do_check_throws(function() { ctypes.CData.prototype.value; }, TypeError);
- do_check_throws(function() { ctypes.CData.prototype.value = null; }, TypeError);
- do_check_throws(function() { ctypes.CData.prototype.address(); }, TypeError);
- do_check_throws(function() { ctypes.CData.prototype.readString(); }, TypeError);
-
- // toString and toSource are called by the web console during inspection,
- // so we don't want them to throw.
- do_check_eq(ctypes.CData.prototype.toString(), '[CData proto object]');
- do_check_eq(ctypes.CData.prototype.toSource(), '[CData proto object]');
-}
-
-function run_Int64_tests() {
- do_check_throws(function() { ctypes.Int64(); }, TypeError);
-
- do_check_true(ctypes.Int64.hasOwnProperty("prototype"));
- do_check_true(ctypes.Int64.prototype.hasOwnProperty("constructor"));
- do_check_true(ctypes.Int64.prototype.constructor === ctypes.Int64);
-
- // Check that ctypes.Int64 and ctypes.Int64.prototype have the correct
- // properties and functions.
- do_check_true(ctypes.Int64.hasOwnProperty("compare"));
- do_check_true(ctypes.Int64.hasOwnProperty("lo"));
- do_check_true(ctypes.Int64.hasOwnProperty("hi"));
- do_check_true(ctypes.Int64.hasOwnProperty("join"));
- do_check_true(ctypes.Int64.prototype.hasOwnProperty("toString"));
- do_check_true(ctypes.Int64.prototype.hasOwnProperty("toSource"));
-
- // Check that the shared functions on ctypes.Int64.prototype throw.
- do_check_throws(function() { ctypes.Int64.prototype.toString(); }, TypeError);
- do_check_throws(function() { ctypes.Int64.prototype.toSource(); }, TypeError);
-
- let int64 = ctypes.Int64(0);
- do_check_true(int64.__proto__ === ctypes.Int64.prototype);
- do_check_true(int64 instanceof ctypes.Int64);
-
- // Test Int64.toString([radix]).
- do_check_eq(int64.toString(), "0");
- for (let radix = 2; radix <= 36; ++radix)
- do_check_eq(int64.toString(radix), "0");
- do_check_throws(function() { int64.toString(0); }, RangeError);
- do_check_throws(function() { int64.toString(1); }, RangeError);
- do_check_throws(function() { int64.toString(37); }, RangeError);
- do_check_throws(function() { int64.toString(10, 2); }, TypeError);
-
- // Test Int64.toSource().
- do_check_eq(int64.toSource(), "ctypes.Int64(\"0\")");
- do_check_throws(function() { int64.toSource(10); }, TypeError);
-
- int64 = ctypes.Int64("0x28590a1c921def71");
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "2907366152271163249");
- do_check_eq(int64.toString(16), "28590a1c921def71");
- do_check_eq(int64.toString(2), "10100001011001000010100001110010010010000111011110111101110001");
- do_check_eq(int64.toSource(), "ctypes.Int64(\"" + int64.toString(10) + "\")");
-
- int64 = ctypes.Int64("-0x28590a1c921def71");
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "-2907366152271163249");
- do_check_eq(int64.toString(16), "-28590a1c921def71");
- do_check_eq(int64.toString(2), "-10100001011001000010100001110010010010000111011110111101110001");
- do_check_eq(int64.toSource(), "ctypes.Int64(\"" + int64.toString(10) + "\")");
-
- int64 = ctypes.Int64("-0X28590A1c921DEf71");
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "-2907366152271163249");
- do_check_eq(int64.toString(16), "-28590a1c921def71");
- do_check_eq(int64.toString(2), "-10100001011001000010100001110010010010000111011110111101110001");
- do_check_eq(int64.toSource(), "ctypes.Int64(\"" + int64.toString(10) + "\")");
-
- // Test Int64(primitive double) constructor.
- int64 = ctypes.Int64(-0);
- do_check_eq(int64.toString(), "0");
-
- int64 = ctypes.Int64(0x7ffffffffffff000);
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "9223372036854771712");
- do_check_eq(int64.toString(16), "7ffffffffffff000");
- do_check_eq(int64.toString(2), "111111111111111111111111111111111111111111111111111000000000000");
-
- int64 = ctypes.Int64(-0x8000000000000000);
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "-9223372036854775808");
- do_check_eq(int64.toString(16), "-8000000000000000");
- do_check_eq(int64.toString(2), "-1000000000000000000000000000000000000000000000000000000000000000");
-
- // Test Int64(string) constructor.
- int64 = ctypes.Int64("0x7fffffffffffffff");
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "9223372036854775807");
- do_check_eq(int64.toString(16), "7fffffffffffffff");
- do_check_eq(int64.toString(2), "111111111111111111111111111111111111111111111111111111111111111");
-
- int64 = ctypes.Int64("-0x8000000000000000");
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "-9223372036854775808");
- do_check_eq(int64.toString(16), "-8000000000000000");
- do_check_eq(int64.toString(2), "-1000000000000000000000000000000000000000000000000000000000000000");
-
- int64 = ctypes.Int64("9223372036854775807");
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "9223372036854775807");
- do_check_eq(int64.toString(16), "7fffffffffffffff");
- do_check_eq(int64.toString(2), "111111111111111111111111111111111111111111111111111111111111111");
-
- int64 = ctypes.Int64("-9223372036854775808");
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "-9223372036854775808");
- do_check_eq(int64.toString(16), "-8000000000000000");
- do_check_eq(int64.toString(2), "-1000000000000000000000000000000000000000000000000000000000000000");
-
- // Test Int64(other Int64) constructor.
- int64 = ctypes.Int64(ctypes.Int64(0));
- do_check_eq(int64.toString(), "0");
-
- int64 = ctypes.Int64(ctypes.Int64("0x7fffffffffffffff"));
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "9223372036854775807");
- do_check_eq(int64.toString(16), "7fffffffffffffff");
- do_check_eq(int64.toString(2), "111111111111111111111111111111111111111111111111111111111111111");
-
- int64 = ctypes.Int64(ctypes.Int64("-0x8000000000000000"));
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "-9223372036854775808");
- do_check_eq(int64.toString(16), "-8000000000000000");
- do_check_eq(int64.toString(2), "-1000000000000000000000000000000000000000000000000000000000000000");
-
- // Test Int64(other UInt64) constructor.
- int64 = ctypes.Int64(ctypes.UInt64(0));
- do_check_eq(int64.toString(), "0");
-
- int64 = ctypes.Int64(ctypes.UInt64("0x7fffffffffffffff"));
- do_check_eq(int64.toString(), int64.toString(10));
- do_check_eq(int64.toString(10), "9223372036854775807");
- do_check_eq(int64.toString(16), "7fffffffffffffff");
- do_check_eq(int64.toString(2), "111111111111111111111111111111111111111111111111111111111111111");
-
- let vals = [-0x8000000000001000, 0x8000000000000000,
- ctypes.UInt64("0x8000000000000000"),
- Infinity, -Infinity, NaN, 0.1,
- 5.68e21, null, undefined, "", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.Int64(vals[i]); }, TypeError);
-
- vals = ["-0x8000000000000001", "0x8000000000000000"];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.Int64(vals[i]); }, RangeError);
-
- // Test ctypes.Int64.compare.
- do_check_eq(ctypes.Int64.compare(ctypes.Int64(5), ctypes.Int64(5)), 0);
- do_check_eq(ctypes.Int64.compare(ctypes.Int64(5), ctypes.Int64(4)), 1);
- do_check_eq(ctypes.Int64.compare(ctypes.Int64(4), ctypes.Int64(5)), -1);
- do_check_eq(ctypes.Int64.compare(ctypes.Int64(-5), ctypes.Int64(-5)), 0);
- do_check_eq(ctypes.Int64.compare(ctypes.Int64(-5), ctypes.Int64(-4)), -1);
- do_check_eq(ctypes.Int64.compare(ctypes.Int64(-4), ctypes.Int64(-5)), 1);
- do_check_throws(function() { ctypes.Int64.compare(ctypes.Int64(4), ctypes.UInt64(4)); }, TypeError);
- do_check_throws(function() { ctypes.Int64.compare(4, 5); }, TypeError);
-
- // Test ctypes.Int64.{lo,hi}.
- do_check_eq(ctypes.Int64.lo(ctypes.Int64(0x28590a1c921de000)), 0x921de000);
- do_check_eq(ctypes.Int64.hi(ctypes.Int64(0x28590a1c921de000)), 0x28590a1c);
- do_check_eq(ctypes.Int64.lo(ctypes.Int64(-0x28590a1c921de000)), 0x6de22000);
- do_check_eq(ctypes.Int64.hi(ctypes.Int64(-0x28590a1c921de000)), -0x28590a1d);
- do_check_throws(function() { ctypes.Int64.lo(ctypes.UInt64(0)); }, TypeError);
- do_check_throws(function() { ctypes.Int64.hi(ctypes.UInt64(0)); }, TypeError);
- do_check_throws(function() { ctypes.Int64.lo(0); }, TypeError);
- do_check_throws(function() { ctypes.Int64.hi(0); }, TypeError);
-
- // Test ctypes.Int64.join.
- do_check_eq(ctypes.Int64.join(0, 0).toString(), "0");
- do_check_eq(ctypes.Int64.join(0x28590a1c, 0x921de000).toString(16), "28590a1c921de000");
- do_check_eq(ctypes.Int64.join(-0x28590a1d, 0x6de22000).toString(16), "-28590a1c921de000");
- do_check_eq(ctypes.Int64.join(0x7fffffff, 0xffffffff).toString(16), "7fffffffffffffff");
- do_check_eq(ctypes.Int64.join(-0x80000000, 0x00000000).toString(16), "-8000000000000000");
- do_check_throws(function() { ctypes.Int64.join(-0x80000001, 0); }, TypeError);
- do_check_throws(function() { ctypes.Int64.join(0x80000000, 0); }, TypeError);
- do_check_throws(function() { ctypes.Int64.join(0, -0x1); }, TypeError);
- do_check_throws(function() { ctypes.Int64.join(0, 0x800000000); }, TypeError);
-}
-
-function run_UInt64_tests() {
- do_check_throws(function() { ctypes.UInt64(); }, TypeError);
-
- do_check_true(ctypes.UInt64.hasOwnProperty("prototype"));
- do_check_true(ctypes.UInt64.prototype.hasOwnProperty("constructor"));
- do_check_true(ctypes.UInt64.prototype.constructor === ctypes.UInt64);
-
- // Check that ctypes.UInt64 and ctypes.UInt64.prototype have the correct
- // properties and functions.
- do_check_true(ctypes.UInt64.hasOwnProperty("compare"));
- do_check_true(ctypes.UInt64.hasOwnProperty("lo"));
- do_check_true(ctypes.UInt64.hasOwnProperty("hi"));
- do_check_true(ctypes.UInt64.hasOwnProperty("join"));
- do_check_true(ctypes.UInt64.prototype.hasOwnProperty("toString"));
- do_check_true(ctypes.UInt64.prototype.hasOwnProperty("toSource"));
-
- // Check that the shared functions on ctypes.UInt64.prototype throw.
- do_check_throws(function() { ctypes.UInt64.prototype.toString(); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.prototype.toSource(); }, TypeError);
-
- let uint64 = ctypes.UInt64(0);
- do_check_true(uint64.__proto__ === ctypes.UInt64.prototype);
- do_check_true(uint64 instanceof ctypes.UInt64);
-
- // Test UInt64.toString([radix]).
- do_check_eq(uint64.toString(), "0");
- for (let radix = 2; radix <= 36; ++radix)
- do_check_eq(uint64.toString(radix), "0");
- do_check_throws(function() { uint64.toString(0); }, RangeError);
- do_check_throws(function() { uint64.toString(1); }, RangeError);
- do_check_throws(function() { uint64.toString(37); }, RangeError);
- do_check_throws(function() { uint64.toString(10, 2); }, TypeError);
-
- // Test UInt64.toSource().
- do_check_eq(uint64.toSource(), "ctypes.UInt64(\"0\")");
- do_check_throws(function() { uint64.toSource(10); }, TypeError);
-
- uint64 = ctypes.UInt64("0x28590a1c921def71");
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "2907366152271163249");
- do_check_eq(uint64.toString(16), "28590a1c921def71");
- do_check_eq(uint64.toString(2), "10100001011001000010100001110010010010000111011110111101110001");
- do_check_eq(uint64.toSource(), "ctypes.UInt64(\"" + uint64.toString(10) + "\")");
-
- uint64 = ctypes.UInt64("0X28590A1c921DEf71");
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "2907366152271163249");
- do_check_eq(uint64.toString(16), "28590a1c921def71");
- do_check_eq(uint64.toString(2), "10100001011001000010100001110010010010000111011110111101110001");
- do_check_eq(uint64.toSource(), "ctypes.UInt64(\"" + uint64.toString(10) + "\")");
-
- // Test UInt64(primitive double) constructor.
- uint64 = ctypes.UInt64(-0);
- do_check_eq(uint64.toString(), "0");
-
- uint64 = ctypes.UInt64(0xfffffffffffff000);
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "18446744073709547520");
- do_check_eq(uint64.toString(16), "fffffffffffff000");
- do_check_eq(uint64.toString(2), "1111111111111111111111111111111111111111111111111111000000000000");
-
- // Test UInt64(string) constructor.
- uint64 = ctypes.UInt64("0xffffffffffffffff");
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "18446744073709551615");
- do_check_eq(uint64.toString(16), "ffffffffffffffff");
- do_check_eq(uint64.toString(2), "1111111111111111111111111111111111111111111111111111111111111111");
-
- uint64 = ctypes.UInt64("0x0");
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "0");
- do_check_eq(uint64.toString(16), "0");
- do_check_eq(uint64.toString(2), "0");
-
- uint64 = ctypes.UInt64("18446744073709551615");
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "18446744073709551615");
- do_check_eq(uint64.toString(16), "ffffffffffffffff");
- do_check_eq(uint64.toString(2), "1111111111111111111111111111111111111111111111111111111111111111");
-
- uint64 = ctypes.UInt64("0");
- do_check_eq(uint64.toString(), "0");
-
- // Test UInt64(other UInt64) constructor.
- uint64 = ctypes.UInt64(ctypes.UInt64(0));
- do_check_eq(uint64.toString(), "0");
-
- uint64 = ctypes.UInt64(ctypes.UInt64("0xffffffffffffffff"));
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "18446744073709551615");
- do_check_eq(uint64.toString(16), "ffffffffffffffff");
- do_check_eq(uint64.toString(2), "1111111111111111111111111111111111111111111111111111111111111111");
-
- uint64 = ctypes.UInt64(ctypes.UInt64("0x0"));
- do_check_eq(uint64.toString(), "0");
-
- // Test UInt64(other Int64) constructor.
- uint64 = ctypes.UInt64(ctypes.Int64(0));
- do_check_eq(uint64.toString(), "0");
-
- uint64 = ctypes.UInt64(ctypes.Int64("0x7fffffffffffffff"));
- do_check_eq(uint64.toString(), uint64.toString(10));
- do_check_eq(uint64.toString(10), "9223372036854775807");
- do_check_eq(uint64.toString(16), "7fffffffffffffff");
- do_check_eq(uint64.toString(2), "111111111111111111111111111111111111111111111111111111111111111");
-
- let vals = [-1, 0x10000000000000000, "-1", "-0x1",
- ctypes.Int64("-1"), Infinity, -Infinity, NaN, 0.1,
- 5.68e21, null, undefined, "", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.UInt64(vals[i]); }, TypeError);
-
- vals = ["0x10000000000000000"];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { ctypes.UInt64(vals[i]); }, RangeError);
-
- // Test ctypes.UInt64.compare.
- do_check_eq(ctypes.UInt64.compare(ctypes.UInt64(5), ctypes.UInt64(5)), 0);
- do_check_eq(ctypes.UInt64.compare(ctypes.UInt64(5), ctypes.UInt64(4)), 1);
- do_check_eq(ctypes.UInt64.compare(ctypes.UInt64(4), ctypes.UInt64(5)), -1);
- do_check_throws(function() { ctypes.UInt64.compare(ctypes.UInt64(4), ctypes.Int64(4)); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.compare(4, 5); }, TypeError);
-
- // Test ctypes.UInt64.{lo,hi}.
- do_check_eq(ctypes.UInt64.lo(ctypes.UInt64(0x28590a1c921de000)), 0x921de000);
- do_check_eq(ctypes.UInt64.hi(ctypes.UInt64(0x28590a1c921de000)), 0x28590a1c);
- do_check_eq(ctypes.UInt64.lo(ctypes.UInt64(0xa8590a1c921de000)), 0x921de000);
- do_check_eq(ctypes.UInt64.hi(ctypes.UInt64(0xa8590a1c921de000)), 0xa8590a1c);
- do_check_throws(function() { ctypes.UInt64.lo(ctypes.Int64(0)); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.hi(ctypes.Int64(0)); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.lo(0); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.hi(0); }, TypeError);
-
- // Test ctypes.UInt64.join.
- do_check_eq(ctypes.UInt64.join(0, 0).toString(), "0");
- do_check_eq(ctypes.UInt64.join(0x28590a1c, 0x921de000).toString(16), "28590a1c921de000");
- do_check_eq(ctypes.UInt64.join(0xa8590a1c, 0x921de000).toString(16), "a8590a1c921de000");
- do_check_eq(ctypes.UInt64.join(0xffffffff, 0xffffffff).toString(16), "ffffffffffffffff");
- do_check_eq(ctypes.UInt64.join(0, 0).toString(16), "0");
- do_check_throws(function() { ctypes.UInt64.join(-0x1, 0); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.join(0x100000000, 0); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.join(0, -0x1); }, TypeError);
- do_check_throws(function() { ctypes.UInt64.join(0, 0x1000000000); }, TypeError);
-}
-
-function run_basic_abi_tests(library, t, name, toprimitive,
- get_test, set_tests, sum_tests, sum_many_tests) {
- // Test the function call ABI for calls involving the type.
- function declare_fn_cdecl(fn_t, prefix) {
- return library.declare(prefix + name + "_cdecl", fn_t);
- }
- run_single_abi_tests(declare_fn_cdecl, ctypes.default_abi, t,
- toprimitive, get_test, set_tests, sum_tests, sum_many_tests);
-
- if ("winLastError" in ctypes) {
- function declare_fn_stdcall(fn_t, prefix) {
- return library.declare(prefix + name + "_stdcall", fn_t);
- }
- run_single_abi_tests(declare_fn_stdcall, ctypes.stdcall_abi, t,
- toprimitive, get_test, set_tests, sum_tests, sum_many_tests);
-
- // Check that declaring a WINAPI function gets the right symbol name.
- let libuser32 = ctypes.open("user32.dll");
- let charupper = libuser32.declare("CharUpperA",
- ctypes.winapi_abi,
- ctypes.char.ptr,
- ctypes.char.ptr);
- let hello = ctypes.char.array()("hello!");
- do_check_eq(charupper(hello).readString(), "HELLO!");
- }
-
- // Check the alignment of the type, and its behavior in a struct,
- // against what C says.
- check_struct_stats(library, t);
-
- // Check the ToSource functions defined in the namespace ABI
- do_check_eq(ctypes.default_abi.toSource(), "ctypes.default_abi");
-
- let exn;
- try {
- ctypes.default_abi.toSource.call(null);
- } catch (x) {
- exn = x;
- }
- do_check_true(!!exn); // Check that some exception was raised
-}
-
-function run_single_abi_tests(decl, abi, t, toprimitive,
- get_test, set_tests, sum_tests, sum_many_tests) {
- let getter_t = ctypes.FunctionType(abi, t).ptr;
- let getter = decl(getter_t, "get_");
- do_check_eq(toprimitive(getter()), get_test);
-
- let setter_t = ctypes.FunctionType(abi, t, [t]).ptr;
- let setter = decl(setter_t, "set_");
- for (let i of set_tests)
- do_check_eq(toprimitive(setter(i)), i);
-
- let sum_t = ctypes.FunctionType(abi, t, [t, t]).ptr;
- let sum = decl(sum_t, "sum_");
- for (let a of sum_tests)
- do_check_eq(toprimitive(sum(a[0], a[1])), a[2]);
-
- let sum_alignb_t = ctypes.FunctionType(abi, t,
- [ctypes.char, t, ctypes.char, t, ctypes.char]).ptr;
- let sum_alignb = decl(sum_alignb_t, "sum_alignb_");
- let sum_alignf_t = ctypes.FunctionType(abi, t,
- [ctypes.float, t, ctypes.float, t, ctypes.float]).ptr;
- let sum_alignf = decl(sum_alignf_t, "sum_alignf_");
- for (let a of sum_tests) {
- do_check_eq(toprimitive(sum_alignb(0, a[0], 0, a[1], 0)), a[2]);
- do_check_eq(toprimitive(sum_alignb(1, a[0], 1, a[1], 1)), a[2]);
- do_check_eq(toprimitive(sum_alignf(0, a[0], 0, a[1], 0)), a[2]);
- do_check_eq(toprimitive(sum_alignf(1, a[0], 1, a[1], 1)), a[2]);
- }
-
- let sum_many_t = ctypes.FunctionType(abi, t,
- [t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t, t]).ptr;
- let sum_many = decl(sum_many_t, "sum_many_");
- for (let a of sum_many_tests)
- do_check_eq(
- toprimitive(sum_many(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7],
- a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15],
- a[16], a[17])), a[18]);
-}
-
-function check_struct_stats(library, t) {
- let s_t = ctypes.StructType("s_t", [{ x: ctypes.char }, { y: t }]);
- let n_t = ctypes.StructType("n_t", [{ a: ctypes.char }, { b: s_t }, { c: ctypes.char }]);
- let get_stats = library.declare("get_" + t.name + "_stats",
- ctypes.default_abi, ctypes.void_t,
- ctypes.size_t.ptr, ctypes.size_t.ptr, ctypes.size_t.ptr, ctypes.size_t.ptr,
- ctypes.size_t.array());
-
- let align = ctypes.size_t();
- let size = ctypes.size_t();
- let nalign = ctypes.size_t();
- let nsize = ctypes.size_t();
- let offsets = ctypes.size_t.array(3)();
- get_stats(align.address(), size.address(), nalign.address(), nsize.address(),
- offsets);
-
- do_check_eq(size.value, s_t.size);
- do_check_eq(align.value, s_t.size - t.size);
- do_check_eq(align.value, offsetof(s_t, "y"));
- do_check_eq(nsize.value, n_t.size);
- do_check_eq(nalign.value, offsetof(n_t, "b"));
- do_check_eq(offsets[0], offsetof(s_t, "y"));
- do_check_eq(offsets[1], offsetof(n_t, "b"));
- do_check_eq(offsets[2], offsetof(n_t, "c"));
-}
-
-// Determine the offset, in bytes, of 'member' within 'struct'.
-function offsetof(struct, member) {
- let instance = struct();
- let memberptr = ptrValue(instance.addressOfField(member));
- let chararray = ctypes.cast(instance, ctypes.char.array(struct.size));
- let offset = 0;
- while (memberptr != ptrValue(chararray.addressOfElement(offset)))
- ++offset;
- return offset;
-}
-
-// Test the class and prototype hierarchy for a given basic type 't'.
-function run_basic_class_tests(t)
-{
- do_check_true(t.__proto__ === ctypes.CType.prototype);
- do_check_true(t instanceof ctypes.CType);
-
- do_check_true(t.prototype.__proto__ === ctypes.CData.prototype);
- do_check_true(t.prototype instanceof ctypes.CData);
- do_check_true(t.prototype.constructor === t);
-
- // Check that the shared properties and functions on 't.prototype' throw.
- do_check_throws(function() { t.prototype.value; }, TypeError);
- do_check_throws(function() { t.prototype.value = null; }, TypeError);
- do_check_throws(function() { t.prototype.address(); }, TypeError);
- do_check_throws(function() { t.prototype.readString(); }, TypeError);
-
- // toString and toSource are called by the web console during inspection,
- // so we don't want them to throw.
- do_check_eq(t.prototype.toString(), '[CData proto object]');
- do_check_eq(t.prototype.toSource(), '[CData proto object]');
-
- // Test that an instance 'd' of 't' is a CData.
- let d = t();
- do_check_true(d.__proto__ === t.prototype);
- do_check_true(d instanceof t);
- do_check_true(d.constructor === t);
-}
-
-function run_bool_tests(library) {
- let t = ctypes.bool;
- run_basic_class_tests(t);
-
- let name = "bool";
- do_check_eq(t.name, name);
- do_check_true(t.size == 1 || t.size == 4);
-
- do_check_eq(t.toString(), "type " + name);
- do_check_eq(t.toSource(), "ctypes." + name);
- do_check_true(t.ptr === ctypes.PointerType(t));
- do_check_eq(t.array().name, name + "[]");
- do_check_eq(t.array(5).name, name + "[5]");
-
- let d = t();
- do_check_eq(d.value, 0);
- d.value = 1;
- do_check_eq(d.value, 1);
- d.value = -0;
- do_check_eq(1/d.value, 1/0);
- d.value = false;
- do_check_eq(d.value, 0);
- d.value = true;
- do_check_eq(d.value, 1);
- d = new t(1);
- do_check_eq(d.value, 1);
-
- // don't convert anything else
- let vals = [-1, 2, Infinity, -Infinity, NaN, 0.1,
- ctypes.Int64(0), ctypes.UInt64(0),
- null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
-
- do_check_true(d.address().constructor === t.ptr);
- do_check_eq(d.address().contents, d.value);
- do_check_eq(d.toSource(), "ctypes." + name + "(" + d.value + ")");
- do_check_eq(d.toSource(), d.toString());
-
- // Test the function call ABI for calls involving the type,
- // and check the alignment of the type against what C says.
- function toprimitive(a) { return a; }
- run_basic_abi_tests(library, t, name, toprimitive,
- true,
- [ false, true ],
- [ [ false, false, false ], [ false, true, true ],
- [ true, false, true ], [true, true, true ] ],
- [ [ false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false,
- false ],
- [ true, true, true, true, true, true, true, true, true,
- true, true, true, true, true, true, true, true, true,
- true ] ]);
-}
-
-function run_integer_tests(library, t, name, size, signed, limits) {
- run_basic_class_tests(t);
-
- do_check_eq(t.name, name);
- do_check_eq(t.size, size);
-
- do_check_eq(t.toString(), "type " + name);
- do_check_eq(t.toSource(), "ctypes." + name);
- do_check_true(t.ptr === ctypes.PointerType(t));
- do_check_eq(t.array().name, name + "[]");
- do_check_eq(t.array(5).name, name + "[5]");
-
- // Check the alignment of the type, and its behavior in a struct,
- // against what C says.
- check_struct_stats(library, t);
-
- let d = t();
- do_check_eq(d.value, 0);
- d.value = 5;
- do_check_eq(d.value, 5);
- d = t(10);
- do_check_eq(d.value, 10);
- if (signed) {
- d.value = -10;
- do_check_eq(d.value, -10);
- }
- d = new t(20);
- do_check_eq(d.value, 20);
-
- d.value = ctypes.Int64(5);
- do_check_eq(d.value, 5);
- if (signed) {
- d.value = ctypes.Int64(-5);
- do_check_eq(d.value, -5);
- }
- d.value = ctypes.UInt64(5);
- do_check_eq(d.value, 5);
-
- d.value = limits[0];
- do_check_eq(d.value, limits[0]);
- d.value = limits[1];
- do_check_eq(d.value, limits[1]);
- d.value = 0;
- do_check_eq(d.value, 0);
- d.value = -0;
- do_check_eq(1/d.value, 1/0);
- d.value = false;
- do_check_eq(d.value, 0);
- d.value = true;
- do_check_eq(d.value, 1);
-
- // don't convert anything else
- let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1,
- null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
-
- do_check_true(d.address().constructor === t.ptr);
- do_check_eq(d.address().contents, d.value);
- do_check_eq(d.toSource(), "ctypes." + name + "(" + d.value + ")");
- do_check_eq(d.toSource(), d.toString());
-
- // Test the function call ABI for calls involving the type,
- // and check the alignment of the type against what C says.
- function toprimitive(a) { return a; }
- run_basic_abi_tests(library, t, name, toprimitive,
- 109,
- [ 0, limits[0], limits[1] ],
- [ [ 0, 0, 0 ], [ 0, 1, 1 ], [ 1, 0, 1 ], [ 1, 1, 2 ],
- [ limits[0], 1, limits[0] + 1 ],
- [ limits[1], 1, limits[0] ] ],
- [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0 ],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 18 ] ]);
-}
-
-function run_float_tests(library, t, name, size) {
- run_basic_class_tests(t);
-
- do_check_eq(t.name, name);
- do_check_eq(t.size, size);
-
- do_check_eq(t.toString(), "type " + name);
- do_check_eq(t.toSource(), "ctypes." + name);
- do_check_true(t.ptr === ctypes.PointerType(t));
- do_check_eq(t.array().name, name + "[]");
- do_check_eq(t.array(5).name, name + "[5]");
-
- let d = t();
- do_check_eq(d.value, 0);
- d.value = 5;
- do_check_eq(d.value, 5);
- d.value = 5.25;
- do_check_eq(d.value, 5.25);
- d = t(10);
- do_check_eq(d.value, 10);
- d.value = -10;
- do_check_eq(d.value, -10);
- d = new t(20);
- do_check_eq(d.value, 20);
-
- do_check_throws(function() { d.value = ctypes.Int64(5); }, TypeError);
- do_check_throws(function() { d.value = ctypes.Int64(-5); }, TypeError);
- do_check_throws(function() { d.value = ctypes.UInt64(5); }, TypeError);
-
- if (size == 4) {
- d.value = 0x7fffff;
- do_check_eq(d.value, 0x7fffff);
-
- // allow values that can't be represented precisely as a float
- d.value = 0xffffffff;
- let delta = 1 - d.value/0xffffffff;
- do_check_true(delta != 0);
- do_check_true(delta > -0.01 && delta < 0.01);
- d.value = 1 + 1/0x80000000;
- do_check_eq(d.value, 1);
- } else {
- d.value = 0xfffffffffffff000;
- do_check_eq(d.value, 0xfffffffffffff000);
-
- do_check_throws(function() { d.value = ctypes.Int64("0x7fffffffffffffff"); }, TypeError);
- }
-
- d.value = Infinity;
- do_check_eq(d.value, Infinity);
- d.value = -Infinity;
- do_check_eq(d.value, -Infinity);
- d.value = NaN;
- do_check_true(isNaN(d.value));
- d.value = 0;
- do_check_eq(d.value, 0);
- d.value = -0;
- do_check_eq(1/d.value, 1/-0);
-
- // don't convert anything else
- let vals = [true, false, null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
-
- // Check that values roundtrip through toSource() correctly.
- function test_roundtrip(tFn, val)
- {
- let f1 = tFn(val);
- eval("var f2 = " + f1.toSource());
- do_check_eq(f1.value, f2.value);
- }
- vals = [Infinity, -Infinity, -0, 0, 1, -1, 1/3, -1/3, 1/4, -1/4,
- 1e-14, -1e-14, 0xfffffffffffff000, -0xfffffffffffff000];
- for (let i = 0; i < vals.length; i++)
- test_roundtrip(t, vals[i]);
- do_check_eq(t(NaN).toSource(), t.toSource() + "(NaN)");
-
- do_check_true(d.address().constructor === t.ptr);
- do_check_eq(d.address().contents, d.value);
- do_check_eq(d.toSource(), "ctypes." + name + "(" + d.value + ")");
- do_check_eq(d.toSource(), d.toString());
-
- // Test the function call ABI for calls involving the type,
- // and check the alignment of the type against what C says.
- let operand = [];
- if (size == 4) {
- operand[0] = 503859.75;
- operand[1] = 1012385.25;
- operand[2] = 1516245;
- } else {
- operand[0] = 501823873859.75;
- operand[1] = 171290577385.25;
- operand[2] = 673114451245;
- }
- function toprimitive(a) { return a; }
- run_basic_abi_tests(library, t, name, toprimitive,
- 109.25,
- [ 0, operand[0], operand[1] ],
- [ [ 0, 0, 0 ], [ 0, 1, 1 ], [ 1, 0, 1 ], [ 1, 1, 2 ],
- [ operand[0], operand[1], operand[2] ] ],
- [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0 ],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 18 ] ]);
-}
-
-function run_wrapped_integer_tests(library, t, name, size, signed, w, wname, limits) {
- run_basic_class_tests(t);
-
- do_check_eq(t.name, name);
- do_check_eq(t.size, size);
-
- do_check_eq(t.toString(), "type " + name);
- do_check_eq(t.toSource(), "ctypes." + name);
- do_check_true(t.ptr === ctypes.PointerType(t));
- do_check_eq(t.array().name, name + "[]");
- do_check_eq(t.array(5).name, name + "[5]");
-
- let d = t();
- do_check_true(d.value instanceof w);
- do_check_eq(d.value, 0);
- d.value = 5;
- do_check_eq(d.value, 5);
- d = t(10);
- do_check_eq(d.value, 10);
- if (signed) {
- d.value = -10;
- do_check_eq(d.value, -10);
- }
- d = new t(20);
- do_check_eq(d.value, 20);
-
- d.value = ctypes.Int64(5);
- do_check_eq(d.value, 5);
- if (signed) {
- d.value = ctypes.Int64(-5);
- do_check_eq(d.value, -5);
- }
- d.value = ctypes.UInt64(5);
- do_check_eq(d.value, 5);
-
- d.value = w(limits[0]);
- do_check_eq(d.value, limits[0]);
- d.value = w(limits[1]);
- do_check_eq(d.value, limits[1]);
- d.value = 0;
- do_check_eq(d.value, 0);
- d.value = -0;
- do_check_eq(1/d.value, 1/0);
- d.value = false;
- do_check_eq(d.value, 0);
- d.value = true;
- do_check_eq(d.value, 1);
-
- // don't convert anything else
- let vals = [limits[2], limits[3], Infinity, -Infinity, NaN, 0.1,
- null, undefined, "", "0", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
-
- do_check_true(d.address().constructor === t.ptr);
- do_check_eq(d.address().contents.toString(), d.value.toString());
- do_check_eq(d.toSource(), "ctypes." + name + "(" + wname + "(\"" + d.value + "\"))");
- do_check_eq(d.toSource(), d.toString());
-
- // Test the function call ABI for calls involving the type,
- // and check the alignment of the type against what C says.
- function toprimitive(a) { return a.toString(); }
- run_basic_abi_tests(library, t, name, toprimitive,
- 109,
- [ 0, w(limits[0]), w(limits[1]) ],
- [ [ 0, 0, 0 ], [ 0, 1, 1 ], [ 1, 0, 1 ], [ 1, 1, 2 ],
- signed ? [ w(limits[0]), -1, w(limits[1]) ]
- : [ w(limits[1]), 1, w(limits[0]) ] ],
- [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0 ],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 18 ] ]);
-}
-
-function run_char_tests(library, t, name, size, signed, limits) {
- run_basic_class_tests(t);
-
- do_check_eq(t.name, name);
- do_check_eq(t.size, size);
-
- do_check_eq(t.toString(), "type " + name);
- do_check_eq(t.toSource(), "ctypes." + name);
- do_check_true(t.ptr === ctypes.PointerType(t));
- do_check_eq(t.array().name, name + "[]");
- do_check_eq(t.array(5).name, name + "[5]");
-
- let d = t();
- do_check_eq(d.value, 0);
- d.value = 5;
- do_check_eq(d.value, 5);
- d = t(10);
- do_check_eq(d.value, 10);
- if (signed) {
- d.value = -10;
- do_check_eq(d.value, -10);
- } else {
- do_check_throws(function() { d.value = -10; }, TypeError);
- }
- d = new t(20);
- do_check_eq(d.value, 20);
-
- function toprimitive(a) { return a; }
-
- d.value = ctypes.Int64(5);
- do_check_eq(d.value, 5);
- if (signed) {
- d.value = ctypes.Int64(-10);
- do_check_eq(d.value, -10);
- }
- d.value = ctypes.UInt64(5);
- do_check_eq(d.value, 5);
-
- d.value = limits[0];
- do_check_eq(d.value, limits[0]);
- d.value = limits[1];
- do_check_eq(d.value, limits[1]);
- d.value = 0;
- do_check_eq(d.value, 0);
- d.value = -0;
- do_check_eq(1/d.value, 1/0);
- d.value = false;
- do_check_eq(d.value, 0);
- d.value = true;
- do_check_eq(d.value, 1);
-
- do_check_throws(function() { d.value = "5"; }, TypeError);
-
- // don't convert anything else
- let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1,
- null, undefined, "", "aa", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
-
- do_check_true(d.address().constructor === t.ptr);
- do_check_eq(d.address().contents, 1);
- do_check_eq(d.toSource(), "ctypes." + name + "(" + d.value + ")");
- do_check_eq(d.toSource(), d.toString());
-
- // Test string autoconversion (and lack thereof).
- let literal = "autoconverted";
- let s = t.array()(literal);
- do_check_eq(s.readString(), literal);
- do_check_eq(s.constructor.length, literal.length + 1);
- s = t.array(50)(literal);
- do_check_eq(s.readString(), literal);
- do_check_throws(function() { t.array(3)(literal); }, TypeError);
-
- do_check_throws(function() { t.ptr(literal); }, TypeError);
- let p = t.ptr(s);
- do_check_eq(p.readString(), literal);
-
- // Test the function call ABI for calls involving the type,
- // and check the alignment of the type against what C says.
- run_basic_abi_tests(library, t, name, toprimitive,
- 109,
- [ 0, limits[0], limits[1] ],
- [ [ 0, 0, 0 ], [ 0, 1, 1 ], [ 1, 0, 1 ], [ 1, 1, 2 ],
- [ limits[0], 1, limits[0] + 1 ],
- [ limits[1], 1, limits[0] ] ],
- [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0 ],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 18 ] ]);
-}
-
-function run_char16_tests(library, t, name, limits) {
- run_basic_class_tests(t);
-
- do_check_eq(t.name, name);
- do_check_eq(t.size, 2);
-
- do_check_eq(t.toString(), "type " + name);
- do_check_eq(t.toSource(), "ctypes." + name);
- do_check_true(t.ptr === ctypes.PointerType(t));
- do_check_eq(t.array().name, name + "[]");
- do_check_eq(t.array(5).name, name + "[5]");
-
- function toprimitive(a) { return a.charCodeAt(0); }
-
- let d = t();
- do_check_eq(d.value.length, 1);
- do_check_eq(toprimitive(d.value), 0);
- d.value = 5;
- do_check_eq(d.value.length, 1);
- do_check_eq(toprimitive(d.value), 5);
- d = t(10);
- do_check_eq(toprimitive(d.value), 10);
- do_check_throws(function() { d.value = -10; }, TypeError);
- d = new t(20);
- do_check_eq(toprimitive(d.value), 20);
-
- d.value = ctypes.Int64(5);
- do_check_eq(d.value.charCodeAt(0), 5);
- do_check_throws(function() { d.value = ctypes.Int64(-10); }, TypeError);
- d.value = ctypes.UInt64(5);
- do_check_eq(d.value.charCodeAt(0), 5);
-
- d.value = limits[0];
- do_check_eq(toprimitive(d.value), limits[0]);
- d.value = limits[1];
- do_check_eq(toprimitive(d.value), limits[1]);
- d.value = 0;
- do_check_eq(toprimitive(d.value), 0);
- d.value = -0;
- do_check_eq(1/toprimitive(d.value), 1/0);
- d.value = false;
- do_check_eq(toprimitive(d.value), 0);
- d.value = true;
- do_check_eq(toprimitive(d.value), 1);
-
- d.value = "\0";
- do_check_eq(toprimitive(d.value), 0);
- d.value = "a";
- do_check_eq(d.value, "a");
-
- // don't convert anything else
- let vals = [limits[0] - 1, limits[1] + 1, Infinity, -Infinity, NaN, 0.1,
- null, undefined, "", "aa", {}, [], new Number(16),
- {toString: function () { return 7; }},
- {valueOf: function () { return 7; }}];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function () { d.value = vals[i]; }, TypeError);
-
- do_check_true(d.address().constructor === t.ptr);
- do_check_eq(d.address().contents, "a");
- do_check_eq(d.toSource(), "ctypes." + name + "(\"" + d.value + "\")");
- do_check_eq(d.toSource(), d.toString());
-
- // Test string autoconversion (and lack thereof).
- let literal = "autoconverted";
- let s = t.array()(literal);
- do_check_eq(s.readString(), literal);
- do_check_eq(s.constructor.length, literal.length + 1);
- s = t.array(50)(literal);
- do_check_eq(s.readString(), literal);
- do_check_throws(function() { t.array(3)(literal); }, TypeError);
-
- do_check_throws(function() { t.ptr(literal); }, TypeError);
- let p = t.ptr(s);
- do_check_eq(p.readString(), literal);
-
- // Test the function call ABI for calls involving the type,
- // and check the alignment of the type against what C says.
- run_basic_abi_tests(library, t, name, toprimitive,
- 109,
- [ 0, limits[0], limits[1] ],
- [ [ 0, 0, 0 ], [ 0, 1, 1 ], [ 1, 0, 1 ], [ 1, 1, 2 ],
- [ limits[0], 1, limits[0] + 1 ],
- [ limits[1], 1, limits[0] ] ],
- [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0 ],
- [ 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 18 ] ]);
-}
-
-// Test the class and prototype hierarchy for a given type constructor 'c'.
-function run_type_ctor_class_tests(c, t, t2, props=[], fns=[], instanceProps=[], instanceFns=[], specialProps=[])
-{
- do_check_true(c.prototype.__proto__ === ctypes.CType.prototype);
- do_check_true(c.prototype instanceof ctypes.CType);
- do_check_true(c.prototype.constructor === c);
-
- // Check that 'c.prototype' has the correct properties and functions.
- for (let p of props)
- do_check_true(c.prototype.hasOwnProperty(p));
- for (let f of fns)
- do_check_true(c.prototype.hasOwnProperty(f));
-
- // Check that the shared properties and functions on 'c.prototype' throw.
- for (let p of props)
- do_check_throws(function() { c.prototype[p]; }, TypeError);
- for (let f of fns)
- do_check_throws(function() { c.prototype[f](); }, TypeError);
-
- do_check_true(t.__proto__ === c.prototype);
- do_check_true(t instanceof c);
-
- // 't.prototype.__proto__' is the common ancestor of all types constructed
- // from 'c'; while not available from 'c' directly, it should be identically
- // equal to 't2.prototype.__proto__' where 't2' is a different CType
- // constructed from 'c'.
- do_check_true(t.prototype.__proto__ === t2.prototype.__proto__);
- if (t instanceof ctypes.FunctionType)
- do_check_true(t.prototype.__proto__.__proto__ === ctypes.PointerType.prototype.prototype);
- else
- do_check_true(t.prototype.__proto__.__proto__ === ctypes.CData.prototype);
- do_check_true(t.prototype instanceof ctypes.CData);
- do_check_true(t.prototype.constructor === t);
-
- // Check that 't.prototype.__proto__' has the correct properties and
- // functions.
- for (let p of instanceProps)
- do_check_true(t.prototype.__proto__.hasOwnProperty(p));
- for (let f of instanceFns)
- do_check_true(t.prototype.__proto__.hasOwnProperty(f));
-
- // Check that the shared properties and functions on 't.prototype.__proto__'
- // (and thus also 't.prototype') throw.
- for (let p of instanceProps) {
- do_check_throws(function() { t.prototype.__proto__[p]; }, TypeError);
- do_check_throws(function() { t.prototype[p]; }, TypeError);
- }
- for (let f of instanceFns) {
- do_check_throws(function() { t.prototype.__proto__[f]() }, TypeError);
- do_check_throws(function() { t.prototype[f]() }, TypeError);
- }
-
- // Check that 't.prototype' has the correct special properties.
- for (let p of specialProps)
- do_check_true(t.prototype.hasOwnProperty(p));
-
- // Check that the shared special properties on 't.prototype' throw.
- for (let p of specialProps)
- do_check_throws(function() { t.prototype[p]; }, TypeError);
-
- // Make sure we can access 'prototype' on a CTypeProto.
- if (t instanceof ctypes.FunctionType)
- do_check_true(Object.getPrototypeOf(c.prototype.prototype) === ctypes.PointerType.prototype.prototype);
- else
- do_check_true(Object.getPrototypeOf(c.prototype.prototype) === ctypes.CType.prototype.prototype);
-
- // Test that an instance 'd' of 't' is a CData.
- if (t.__proto__ != ctypes.FunctionType.prototype) {
- let d = t();
- do_check_true(d.__proto__ === t.prototype);
- do_check_true(d instanceof t);
- do_check_true(d.constructor === t);
- }
-}
-
-function run_StructType_tests() {
- run_type_ctor_class_tests(ctypes.StructType,
- ctypes.StructType("s", [{"a": ctypes.int32_t}, {"b": ctypes.int64_t}]),
- ctypes.StructType("t", [{"c": ctypes.int32_t}, {"d": ctypes.int64_t}]),
- [ "fields" ], [ "define" ], [], [ "addressOfField" ], [ "a", "b" ]);
-
- do_check_throws(function() { ctypes.StructType(); }, TypeError);
- do_check_throws(function() { ctypes.StructType("a", [], 5); }, TypeError);
- do_check_throws(function() { ctypes.StructType(null, []); }, TypeError);
- do_check_throws(function() { ctypes.StructType("a", null); }, TypeError);
-
- // Check that malformed descriptors are an error.
- do_check_throws(function() {
- ctypes.StructType("a", [{"x":ctypes.int32_t}, {"x":ctypes.int8_t}]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.StructType("a", [5]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.StructType("a", [{}]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.StructType("a", [{5:ctypes.int32_t}]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.StructType("a", [{"5":ctypes.int32_t}]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.StructType("a", [{"x":5}]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.StructType("a", [{"x":ctypes.int32_t()}]);
- }, TypeError);
-
- // Check that opaque structs work.
- let opaque_t = ctypes.StructType("a");
- do_check_eq(opaque_t.name, "a");
- do_check_eq(opaque_t.toString(), "type a");
- do_check_eq(opaque_t.toSource(), 'ctypes.StructType("a")');
- do_check_true(opaque_t.prototype === undefined);
- do_check_true(opaque_t.fields === undefined);
- do_check_true(opaque_t.size === undefined);
- do_check_throws(function() { opaque_t(); }, Error);
- let opaqueptr_t = opaque_t.ptr;
- do_check_true(opaqueptr_t.targetType === opaque_t);
- do_check_eq(opaqueptr_t.name, "a*");
- do_check_eq(opaqueptr_t.toString(), "type a*");
- do_check_eq(opaqueptr_t.toSource(), 'ctypes.StructType("a").ptr');
-
- // Check that type checking works with opaque structs.
- let opaqueptr = opaqueptr_t();
- opaqueptr.value = opaqueptr_t(1);
- do_check_eq(ptrValue(opaqueptr), 1);
- do_check_throws(function() {
- opaqueptr.value = ctypes.StructType("a").ptr();
- }, TypeError);
-
- // Check that 'define' works.
- do_check_throws(function() { opaque_t.define(); }, TypeError);
- do_check_throws(function() { opaque_t.define([], 0); }, TypeError);
- do_check_throws(function() { opaque_t.define([{}]); }, TypeError);
- do_check_throws(function() { opaque_t.define([{ a: 0 }]); }, TypeError);
- do_check_throws(function() {
- opaque_t.define([{ a: ctypes.int32_t, b: ctypes.int64_t }]);
- }, TypeError);
- do_check_throws(function() {
- opaque_t.define([{ a: ctypes.int32_t }, { b: 0 }]);
- }, TypeError);
- do_check_false(opaque_t.hasOwnProperty("prototype"));
-
- // Check that circular references work with opaque structs...
- // but not crazy ones.
- do_check_throws(function() { opaque_t.define([{ b: opaque_t }]); }, TypeError);
- let circular_t = ctypes.StructType("circular", [{ a: opaqueptr_t }]);
- opaque_t.define([{ b: circular_t }]);
- let opaque = opaque_t();
- let circular = circular_t(opaque.address());
- opaque.b = circular;
- do_check_eq(circular.a.toSource(), opaque.address().toSource());
- do_check_eq(opaque.b.toSource(), circular.toSource());
-
- // Check that attempting to redefine a struct fails and if attempted, the
- // original definition is preserved.
- do_check_throws(function() {
- opaque_t.define([{ c: ctypes.int32_t.array(8) }]);
- }, Error);
- do_check_eq(opaque_t.size, circular_t.size);
- do_check_true(opaque_t.prototype.hasOwnProperty("b"));
- do_check_false(opaque_t.prototype.hasOwnProperty("c"));
-
- // StructType size, alignment, and offset calculations have already been
- // checked for each basic type. We do not need to check them again.
- let name = "g_t";
- let g_t = ctypes.StructType(name, [{ a: ctypes.int32_t }, { b: ctypes.double }]);
- do_check_eq(g_t.name, name);
-
- do_check_eq(g_t.toString(), "type " + name);
- do_check_eq(g_t.toSource(),
- "ctypes.StructType(\"g_t\", [{ \"a\": ctypes.int32_t }, { \"b\": ctypes.double }])");
- do_check_true(g_t.ptr === ctypes.PointerType(g_t));
- do_check_eq(g_t.array().name, name + "[]");
- do_check_eq(g_t.array(5).name, name + "[5]");
-
- let s_t = new ctypes.StructType("s_t", [{ a: ctypes.int32_t }, { b: g_t }, { c: ctypes.int8_t }]);
-
- let fields = [{ a: ctypes.int32_t }, { b: ctypes.int8_t }, { c: g_t }, { d: ctypes.int8_t }];
- let t_t = new ctypes.StructType("t_t", fields);
- do_check_eq(t_t.fields.length, 4);
- do_check_true(t_t.fields[0].a === ctypes.int32_t);
- do_check_true(t_t.fields[1].b === ctypes.int8_t);
- do_check_true(t_t.fields[2].c === g_t);
- do_check_true(t_t.fields[3].d === ctypes.int8_t);
-/* disabled temporarily per bug 598225.
- do_check_throws(function() { t_t.fields.z = 0; }, Error);
- do_check_throws(function() { t_t.fields[4] = 0; }, Error);
- do_check_throws(function() { t_t.fields[4].a = 0; }, Error);
- do_check_throws(function() { t_t.fields[4].e = 0; }, Error);
-*/
-
- // Check that struct size bounds work, and that large, but not illegal, sizes
- // are OK.
- if (ctypes.size_t.size == 4) {
- // Test 1: overflow struct size + field padding + field size.
- let large_t = ctypes.StructType("large_t",
- [{"a": ctypes.int8_t.array(0xffffffff)}]);
- do_check_eq(large_t.size, 0xffffffff);
- do_check_throws(function() {
- ctypes.StructType("large_t", [{"a": large_t}, {"b": ctypes.int8_t}]);
- }, RangeError);
-
- // Test 2: overflow struct size + struct tail padding.
- // To do this, we use a struct with maximum size and alignment 2.
- large_t = ctypes.StructType("large_t",
- [{"a": ctypes.int16_t.array(0xfffffffe / 2)}]);
- do_check_eq(large_t.size, 0xfffffffe);
- do_check_throws(function() {
- ctypes.StructType("large_t", [{"a": large_t}, {"b": ctypes.int8_t}]);
- }, RangeError);
-
- } else {
- // Test 1: overflow struct size when converting from size_t to jsdouble.
- let large_t = ctypes.StructType("large_t",
- [{"a": ctypes.int8_t.array(0xfffffffffffff800)}]);
- do_check_eq(large_t.size, 0xfffffffffffff800);
- do_check_throws(function() {
- ctypes.StructType("large_t", [{"a": large_t}, {"b": ctypes.int8_t}]);
- }, RangeError);
- let small_t = ctypes.int8_t.array(0x400);
- do_check_throws(function() {
- ctypes.StructType("large_t", [{"a": large_t}, {"b": small_t}]);
- }, RangeError);
-
- large_t = ctypes.StructType("large_t",
- [{"a": ctypes.int8_t.array(0x1fffffffffffff)}]);
- do_check_eq(large_t.size, 0x1fffffffffffff);
- do_check_throws(function() {
- ctypes.StructType("large_t", [{"a": large_t.array(2)}, {"b": ctypes.int8_t}]);
- }, RangeError);
-
- // Test 2: overflow struct size + field padding + field size.
- large_t = ctypes.int8_t.array(0xfffffffffffff800);
- small_t = ctypes.int8_t.array(0x800);
- do_check_throws(function() {
- ctypes.StructType("large_t", [{"a": large_t}, {"b": small_t}]);
- }, RangeError);
-
- // Test 3: overflow struct size + struct tail padding.
- // To do this, we use a struct with maximum size and alignment 2.
- large_t = ctypes.StructType("large_t",
- [{"a": ctypes.int16_t.array(0xfffffffffffff000 / 2)}]);
- do_check_eq(large_t.size, 0xfffffffffffff000);
- small_t = ctypes.int8_t.array(0xfff);
- do_check_throws(function() {
- ctypes.StructType("large_t", [{"a": large_t}, {"b": small_t}]);
- }, RangeError);
- }
-
- let g = g_t();
- do_check_eq(g.a, 0);
- do_check_eq(g.b, 0);
- g = new g_t(1, 2);
- do_check_eq(g.a, 1);
- do_check_eq(g.b, 2);
- do_check_throws(function() { g_t(1); }, TypeError);
- do_check_throws(function() { g_t(1, 2, 3); }, TypeError);
-
- for (let field in g)
- do_check_true(field == "a" || field == "b");
-
- let g_a = g.address();
- do_check_true(g_a.constructor === g_t.ptr);
- do_check_eq(g_a.contents.a, g.a);
-
- let s = new s_t(3, g, 10);
- do_check_eq(s.a, 3);
- s.a = 4;
- do_check_eq(s.a, 4);
- do_check_eq(s.b.a, 1);
- do_check_eq(s.b.b, 2);
- do_check_eq(s.c, 10);
- let g2 = s.b;
- do_check_eq(g2.a, 1);
- g2.a = 7;
- do_check_eq(g2.a, 7);
- do_check_eq(s.b.a, 7);
-
- g_a = s.addressOfField("b");
- do_check_true(g_a.constructor === g_t.ptr);
- do_check_eq(g_a.contents.a, s.b.a);
- do_check_throws(function() { s.addressOfField(); }, TypeError);
- do_check_throws(function() { s.addressOfField("d"); }, TypeError);
- do_check_throws(function() { s.addressOfField("a", 2); }, TypeError);
-
- do_check_eq(s.toSource(), "s_t(4, {\"a\": 7, \"b\": 2}, 10)");
- do_check_eq(s.toSource(), s.toString());
- eval("var s2 = " + s.toSource());
- do_check_true(s2.constructor === s_t);
- do_check_eq(s.b.b, s2.b.b);
-
- // Test that structs can be set from an object using 'value'.
- do_check_throws(function() { s.value; }, TypeError);
- let s_init = { "a": 2, "b": { "a": 9, "b": 5 }, "c": 13 };
- s.value = s_init;
- do_check_eq(s.b.a, 9);
- do_check_eq(s.c, 13);
- do_check_throws(function() { s.value = 5; }, TypeError);
- do_check_throws(function() { s.value = ctypes.int32_t(); }, TypeError);
- do_check_throws(function() { s.value = {}; }, TypeError);
- do_check_throws(function() { s.value = { "a": 2 }; }, TypeError);
- do_check_throws(function() { s.value = { "a": 2, "b": 5, "c": 10 }; }, TypeError);
- do_check_throws(function() {
- s.value = { "5": 2, "b": { "a": 9, "b": 5 }, "c": 13 };
- }, TypeError);
- do_check_throws(function() {
- s.value = { "a": 2, "b": { "a": 9, "b": 5 }, "c": 13, "d": 17 };
- }, TypeError);
- do_check_throws(function() {
- s.value = { "a": 2, "b": { "a": 9, "b": 5, "e": 9 }, "c": 13 };
- }, TypeError);
-
- // Test that structs can be constructed similarly through ExplicitConvert,
- // and that the single-field case is disambiguated correctly.
- s = s_t(s_init);
- do_check_eq(s.b.a, 9);
- do_check_eq(s.c, 13);
- let v_t = ctypes.StructType("v_t", [{ "x": ctypes.int32_t }]);
- let v = v_t({ "x": 5 });
- do_check_eq(v.x, 5);
- v = v_t(8);
- do_check_eq(v.x, 8);
- let w_t = ctypes.StructType("w_t", [{ "y": v_t }]);
- do_check_throws(function() { w_t(9); }, TypeError);
- let w = w_t({ "x": 3 });
- do_check_eq(w.y.x, 3);
- w = w_t({ "y": { "x": 19 } });
- do_check_eq(w.y.x, 19);
- let u_t = ctypes.StructType("u_t", [{ "z": ctypes.ArrayType(ctypes.int32_t, 3) }]);
- let u = u_t([1, 2, 3]);
- do_check_eq(u.z[1], 2);
- u = u_t({ "z": [4, 5, 6] });
- do_check_eq(u.z[1], 5);
-
- // Check that the empty struct has size 1.
- let z_t = ctypes.StructType("z_t", []);
- do_check_eq(z_t.size, 1);
- do_check_eq(z_t.fields.length, 0);
-
- // Check that structs containing arrays of undefined or zero length
- // are illegal, but arrays of defined length work.
- do_check_throws(function() {
- ctypes.StructType("z_t", [{ a: ctypes.int32_t.array() }]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.StructType("z_t", [{ a: ctypes.int32_t.array(0) }]);
- }, TypeError);
- z_t = ctypes.StructType("z_t", [{ a: ctypes.int32_t.array(6) }]);
- do_check_eq(z_t.size, ctypes.int32_t.size * 6);
- let z = z_t([1, 2, 3, 4, 5, 6]);
- do_check_eq(z.a[3], 4);
-}
-
-function ptrValue(p) {
- return ctypes.cast(p, ctypes.uintptr_t).value.toString();
-}
-
-function run_PointerType_tests() {
- run_type_ctor_class_tests(ctypes.PointerType,
- ctypes.PointerType(ctypes.int32_t), ctypes.PointerType(ctypes.int64_t),
- [ "targetType" ], [], [ "contents" ], [ "isNull", "increment", "decrement" ], []);
-
- do_check_throws(function() { ctypes.PointerType(); }, TypeError);
- do_check_throws(function() { ctypes.PointerType(ctypes.int32_t, 5); }, TypeError);
- do_check_throws(function() { ctypes.PointerType(null); }, TypeError);
- do_check_throws(function() { ctypes.PointerType(ctypes.int32_t()); }, TypeError);
- do_check_throws(function() { ctypes.PointerType("void"); }, TypeError);
-
- let name = "g_t";
- let g_t = ctypes.StructType(name, [{ a: ctypes.int32_t }, { b: ctypes.double }]);
- let g = g_t(1, 2);
-
- let p_t = ctypes.PointerType(g_t);
- do_check_eq(p_t.name, name + "*");
- do_check_eq(p_t.size, ctypes.uintptr_t.size);
- do_check_true(p_t.targetType === g_t);
- do_check_true(p_t === g_t.ptr);
-
- do_check_eq(p_t.toString(), "type " + name + "*");
- do_check_eq(p_t.toSource(),
- "ctypes.StructType(\"g_t\", [{ \"a\": ctypes.int32_t }, { \"b\": ctypes.double }]).ptr");
- do_check_true(p_t.ptr === ctypes.PointerType(p_t));
- do_check_eq(p_t.array().name, name + "*[]");
- do_check_eq(p_t.array(5).name, name + "*[5]");
-
- // Test ExplicitConvert.
- let p = p_t();
- do_check_throws(function() { p.value; }, TypeError);
- do_check_eq(ptrValue(p), 0);
- do_check_throws(function() { p.contents; }, TypeError);
- do_check_throws(function() { p.contents = g; }, TypeError);
- p = p_t(5);
- do_check_eq(ptrValue(p), 5);
- p = p_t(ctypes.UInt64(10));
- do_check_eq(ptrValue(p), 10);
-
- // Test ImplicitConvert.
- p.value = null;
- do_check_eq(ptrValue(p), 0);
- do_check_throws(function() { p.value = 5; }, TypeError);
-
- // Test opaque pointers.
- let f_t = ctypes.StructType("FILE").ptr;
- do_check_eq(f_t.name, "FILE*");
- do_check_eq(f_t.toSource(), 'ctypes.StructType("FILE").ptr');
- let f = new f_t();
- do_check_throws(function() { f.contents; }, TypeError);
- do_check_throws(function() { f.contents = 0; }, TypeError);
- f = f_t(5);
- do_check_throws(function() { f.contents = 0; }, TypeError);
- do_check_eq(f.toSource(), 'FILE.ptr(ctypes.UInt64("0x5"))');
-
- do_check_throws(function() { f_t(p); }, TypeError);
- do_check_throws(function() { f.value = p; }, TypeError);
- do_check_throws(function() { p.value = f; }, TypeError);
-
- // Test void pointers.
- let v_t = ctypes.PointerType(ctypes.void_t);
- do_check_true(v_t === ctypes.voidptr_t);
- let v = v_t(p);
- do_check_eq(ptrValue(v), ptrValue(p));
-
- // Test 'contents'.
- let int32_t = ctypes.int32_t(9);
- p = int32_t.address();
- do_check_eq(p.contents, int32_t.value);
- p.contents = ctypes.int32_t(12);
- do_check_eq(int32_t.value, 12);
-
- // Test 'isNull'.
- let n = f_t(0);
- do_check_true(n.isNull() === true);
- n = p.address();
- do_check_true(n.isNull() === false);
-
- // Test 'increment'/'decrement'.
- g_t = ctypes.StructType("g_t", [{ a: ctypes.int32_t }, { b: ctypes.double }]);
- let a_t = ctypes.ArrayType(g_t, 2);
- let a = new a_t();
- a[0] = g_t(1, 2);
- a[1] = g_t(2, 4);
- let a_p = a.addressOfElement(0).increment();
- do_check_eq(a_p.contents.a, 2);
- do_check_eq(a_p.contents.b, 4);
- a_p = a_p.decrement();
- do_check_eq(a_p.contents.a, 1);
- do_check_eq(a_p.contents.b, 2);
-
- // Check that pointers to arrays of undefined or zero length are legal,
- // but that the former cannot be dereferenced.
- let z_t = ctypes.int32_t.array().ptr;
- do_check_eq(ptrValue(z_t()), 0);
- do_check_throws(function() { z_t().contents }, TypeError);
- z_t = ctypes.int32_t.array(0).ptr;
- do_check_eq(ptrValue(z_t()), 0);
- let z = ctypes.int32_t.array(0)().address();
- do_check_eq(z.contents.length, 0);
-
- // TODO: Somehow, somewhere we should check that:
- //
- // (a) ArrayBuffer and TypedArray can be passed by pointer to a C function
- // (b) SharedArrayBuffer and TypedArray on SAB can NOT be passed in that
- // way (at least not at the moment).
-
- // Set up conversion tests on AB, SAB, TA
- let c_arraybuffer = new ArrayBuffer(256);
- let typed_array_samples =
- [
- [new Int8Array(c_arraybuffer), ctypes.int8_t],
- [new Uint8Array(c_arraybuffer), ctypes.uint8_t],
- [new Int16Array(c_arraybuffer), ctypes.int16_t],
- [new Uint16Array(c_arraybuffer), ctypes.uint16_t],
- [new Int32Array(c_arraybuffer), ctypes.int32_t],
- [new Uint32Array(c_arraybuffer), ctypes.uint32_t],
- [new Float32Array(c_arraybuffer), ctypes.float32_t],
- [new Float64Array(c_arraybuffer), ctypes.float64_t]
- ];
-
- if (typeof SharedArrayBuffer !== "undefined") {
- let c_shared_arraybuffer = new SharedArrayBuffer(256);
- typed_array_samples.push([new Int8Array(c_shared_arraybuffer), ctypes.int8_t],
- [new Uint8Array(c_shared_arraybuffer), ctypes.uint8_t],
- [new Int16Array(c_shared_arraybuffer), ctypes.int16_t],
- [new Uint16Array(c_shared_arraybuffer), ctypes.uint16_t],
- [new Int32Array(c_shared_arraybuffer), ctypes.int32_t],
- [new Uint32Array(c_shared_arraybuffer), ctypes.uint32_t],
- [new Float32Array(c_shared_arraybuffer), ctypes.float32_t],
- [new Float64Array(c_shared_arraybuffer), ctypes.float64_t])
- }
-
- // Check that you can convert (Shared)ArrayBuffer or typed array to a C array
- for (let i = 0; i < typed_array_samples.length; ++i) {
- for (let j = 0; j < typed_array_samples.length; ++j) {
- let view = typed_array_samples[i][0];
- let item_type = typed_array_samples[j][1];
- let number_of_items = c_arraybuffer.byteLength / item_type.size;
- let array_type = item_type.array(number_of_items);
-
- // Int8Array on unshared memory is interconvertible with Int8Array on
- // shared memory, etc.
- if (i % 8 != j % 8) {
- do_print("Checking that typed array " + (view.constructor.name) +
- " can NOT be converted to " + item_type + " array");
- do_check_throws(function() { array_type(view); }, TypeError);
- } else {
- do_print("Checking that typed array " + (view.constructor.name) +
- " can be converted to " + item_type + " array");
-
- // Convert ArrayBuffer to array of the right size and check contents
- c_array = array_type(c_arraybuffer);
- for (let k = 0; k < number_of_items; ++k) {
- do_check_eq(c_array[k], view[k]);
- }
-
- // Convert typed array to array of the right size and check contents
- c_array = array_type(view);
- for (let k = 0; k < number_of_items; ++k) {
- do_check_eq(c_array[k], view[k]);
- }
-
- // Convert typed array to array of wrong size, ensure that it fails
- let array_type_too_large = item_type.array(number_of_items + 1);
- let array_type_too_small = item_type.array(number_of_items - 1);
-
- do_check_throws(function() { array_type_too_large(c_arraybuffer); }, TypeError);
- do_check_throws(function() { array_type_too_small(c_arraybuffer); }, TypeError);
- do_check_throws(function() { array_type_too_large(view); }, TypeError);
- do_check_throws(function() { array_type_too_small(view); }, TypeError);
-
- // Convert subarray of typed array to array of right size and check contents
- c_array = array_type_too_small(view.subarray(1));
- for (let k = 1; k < number_of_items; ++k) {
- do_check_eq(c_array[k - 1], view[k]);
- }
- }
- }
- }
-
- // Check that you can't use a (Shared)ArrayBuffer or a typed array as a pointer
- for (let i = 0; i < typed_array_samples.length; ++i) {
- for (let j = 0; j < typed_array_samples.length; ++j) {
- let view = typed_array_samples[i][0];
- let item_type = typed_array_samples[j][1];
-
- do_print("Checking that typed array " + (view.constructor.name) +
- " can NOT be converted to " + item_type + " pointer/array");
- do_check_throws(function() { item_type.ptr(c_arraybuffer); }, TypeError);
- do_check_throws(function() { item_type.ptr(view); }, TypeError);
- do_check_throws(function() { ctypes.voidptr_t(c_arraybuffer); }, TypeError);
- do_check_throws(function() { ctypes.voidptr_t(view); }, TypeError);
- }
- }
-}
-
-function run_FunctionType_tests() {
- run_type_ctor_class_tests(ctypes.FunctionType,
- ctypes.FunctionType(ctypes.default_abi, ctypes.void_t),
- ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, [ ctypes.int32_t ]),
- [ "abi", "returnType", "argTypes", "isVariadic" ],
- undefined, undefined, undefined, undefined);
-
- do_check_throws(function() { ctypes.FunctionType(); }, TypeError);
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, [ ctypes.void_t ]);
- }, TypeError);
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, [ ctypes.void_t ], 5);
- }, TypeError);
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, ctypes.void_t);
- }, TypeError);
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, null);
- }, TypeError);
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.default_abi, ctypes.int32_t());
- }, TypeError);
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.void_t, ctypes.void_t);
- }, Error);
-
- let g_t = ctypes.StructType("g_t", [{ a: ctypes.int32_t }, { b: ctypes.double }]);
-
- let f_t = ctypes.FunctionType(ctypes.default_abi, g_t);
- let name = "g_t()";
- do_check_eq(f_t.name, name);
- do_check_eq(f_t.size, undefined);
- do_check_true(f_t.abi === ctypes.default_abi);
- do_check_true(f_t.returnType === g_t);
- do_check_true(f_t.argTypes.length == 0);
-
- do_check_eq(f_t.toString(), "type " + name);
- do_check_eq(f_t.toSource(),
- "ctypes.FunctionType(ctypes.default_abi, g_t)");
-
- let fp_t = f_t.ptr;
- name = "g_t(*)()";
- do_check_eq(fp_t.name, name);
- do_check_eq(fp_t.size, ctypes.uintptr_t.size);
-
- do_check_eq(fp_t.toString(), "type " + name);
- do_check_eq(fp_t.toSource(),
- "ctypes.FunctionType(ctypes.default_abi, g_t).ptr");
-
- // Check that constructing a FunctionType CData directly throws.
- do_check_throws(function() { f_t(); }, TypeError);
-
- // Test ExplicitConvert.
- let f = fp_t();
- do_check_throws(function() { f.value; }, TypeError);
- do_check_eq(ptrValue(f), 0);
- f = fp_t(5);
- do_check_eq(ptrValue(f), 5);
- f = fp_t(ctypes.UInt64(10));
- do_check_eq(ptrValue(f), 10);
-
- // Test ImplicitConvert.
- f.value = null;
- do_check_eq(ptrValue(f), 0);
- do_check_throws(function() { f.value = 5; }, TypeError);
- do_check_eq(f.toSource(),
- 'ctypes.FunctionType(ctypes.default_abi, g_t).ptr(ctypes.UInt64("0x0"))');
-
- // Test ImplicitConvert from a function pointer of different type.
- let f2_t = ctypes.FunctionType(ctypes.default_abi, g_t, [ ctypes.int32_t ]);
- let f2 = f2_t.ptr();
- do_check_throws(function() { f.value = f2; }, TypeError);
- do_check_throws(function() { f2.value = f; }, TypeError);
-
- // Test that converting to a voidptr_t works.
- let v = ctypes.voidptr_t(f2);
- do_check_eq(v.toSource(), 'ctypes.voidptr_t(ctypes.UInt64("0x0"))');
-
- // Test some more complex names.
- do_check_eq(fp_t.array().name, "g_t(*[])()");
- do_check_eq(fp_t.array().ptr.name, "g_t(*(*)[])()");
-
- let f3_t = ctypes.FunctionType(ctypes.default_abi,
- ctypes.char.ptr.array().ptr).ptr.ptr.array(8).array();
- do_check_eq(f3_t.name, "char*(*(**[][8])())[]");
-
- if ("winLastError" in ctypes) {
- f3_t = ctypes.FunctionType(ctypes.stdcall_abi,
- ctypes.char.ptr.array().ptr).ptr.ptr.array(8).array();
- do_check_eq(f3_t.name, "char*(*(__stdcall**[][8])())[]");
- f3_t = ctypes.FunctionType(ctypes.winapi_abi,
- ctypes.char.ptr.array().ptr).ptr.ptr.array(8).array();
- do_check_eq(f3_t.name, "char*(*(WINAPI**[][8])())[]");
- }
-
- let f4_t = ctypes.FunctionType(ctypes.default_abi,
- ctypes.char.ptr.array().ptr, [ ctypes.int32_t, fp_t ]);
- do_check_true(f4_t.argTypes.length == 2);
- do_check_true(f4_t.argTypes[0] === ctypes.int32_t);
- do_check_true(f4_t.argTypes[1] === fp_t);
-/* disabled temporarily per bug 598225.
- do_check_throws(function() { f4_t.argTypes.z = 0; }, Error);
- do_check_throws(function() { f4_t.argTypes[0] = 0; }, Error);
-*/
-
- let t4_t = f4_t.ptr.ptr.array(8).array();
- do_check_eq(t4_t.name, "char*(*(**[][8])(int32_t, g_t(*)()))[]");
-
- // Not available in a Worker
- if ("@mozilla.org/systemprincipal;1" in Components.classes) {
- var sp = Components.classes["@mozilla.org/systemprincipal;1"].
- createInstance(Components.interfaces.nsIPrincipal);
- var s = new Components.utils.Sandbox(sp);
- s.ctypes = ctypes;
- s.do_check_eq = do_check_eq;
- s.do_check_true = do_check_true;
- Components.utils.evalInSandbox("var f5_t = ctypes.FunctionType(ctypes.default_abi, ctypes.int, [ctypes.int]);", s);
- Components.utils.evalInSandbox("do_check_eq(f5_t.toSource(), 'ctypes.FunctionType(ctypes.default_abi, ctypes.int, [ctypes.int])');", s);
- Components.utils.evalInSandbox("do_check_eq(f5_t.name, 'int(int)');", s);
- Components.utils.evalInSandbox("function f5(aArg) { return 5; };", s);
- Components.utils.evalInSandbox("var f = f5_t.ptr(f5);", s);
- Components.utils.evalInSandbox("do_check_true(f(6) == 5);", s);
- }
-}
-
-function run_ArrayType_tests() {
- run_type_ctor_class_tests(ctypes.ArrayType,
- ctypes.ArrayType(ctypes.int32_t, 10), ctypes.ArrayType(ctypes.int64_t),
- [ "elementType", "length" ], [], [ "length" ], [ "addressOfElement" ]);
-
- do_check_throws(function() { ctypes.ArrayType(); }, TypeError);
- do_check_throws(function() { ctypes.ArrayType(null); }, TypeError);
- do_check_throws(function() { ctypes.ArrayType(ctypes.int32_t, 1, 5); }, TypeError);
- do_check_throws(function() { ctypes.ArrayType(ctypes.int32_t, -1); }, TypeError);
-
- let name = "g_t";
- let g_t = ctypes.StructType(name, [{ a: ctypes.int32_t }, { b: ctypes.double }]);
- let g = g_t(1, 2);
-
- let a_t = ctypes.ArrayType(g_t, 10);
- do_check_eq(a_t.name, name + "[10]");
- do_check_eq(a_t.length, 10);
- do_check_eq(a_t.size, g_t.size * 10);
- do_check_true(a_t.elementType === g_t);
-
- do_check_eq(a_t.toString(), "type " + name + "[10]");
- do_check_eq(a_t.toSource(),
- "ctypes.StructType(\"g_t\", [{ \"a\": ctypes.int32_t }, { \"b\": ctypes.double }]).array(10)");
- do_check_eq(a_t.array().name, name + "[][10]");
- do_check_eq(a_t.array(5).name, name + "[5][10]");
- do_check_throws(function() { ctypes.int32_t.array().array(); }, Error);
-
- let a = new a_t();
- do_check_eq(a[0].a, 0);
- do_check_eq(a[0].b, 0);
- a[0] = g;
- do_check_eq(a[0].a, 1);
- do_check_eq(a[0].b, 2);
- do_check_throws(function() { a[-1]; }, TypeError);
- do_check_eq(a[9].a, 0);
- do_check_throws(function() { a[10]; }, RangeError);
-
- do_check_eq(a[ctypes.Int64(0)].a, 1);
- do_check_eq(a[ctypes.UInt64(0)].b, 2);
-
- let a_p = a.addressOfElement(0);
- do_check_true(a_p.constructor.targetType === g_t);
- do_check_true(a_p.constructor === g_t.ptr);
- do_check_eq(a_p.contents.a, a[0].a);
- do_check_eq(a_p.contents.b, a[0].b);
- a_p.contents.a = 5;
- do_check_eq(a[0].a, 5);
-
- let a2_t = ctypes.ArrayType(g_t);
- do_check_eq(a2_t.name, "g_t[]");
- do_check_eq(a2_t.length, undefined);
- do_check_eq(a2_t.size, undefined);
- let a2 = new a2_t(5);
- do_check_eq(a2.constructor.length, 5);
- do_check_eq(a2.length, 5);
- do_check_eq(a2.constructor.size, g_t.size * 5);
- do_check_throws(function() { new a2_t(); }, TypeError);
- do_check_throws(function() { ctypes.ArrayType(ctypes.ArrayType(g_t)); }, Error);
- do_check_throws(function() { ctypes.ArrayType(ctypes.ArrayType(g_t), 5); }, Error);
-
- let b_t = ctypes.int8_t.array(ctypes.UInt64(0xffff));
- do_check_eq(b_t.length, 0xffff);
- b_t = ctypes.int8_t.array(ctypes.Int64(0xffff));
- do_check_eq(b_t.length, 0xffff);
-
- // Check that array size bounds work, and that large, but not illegal, sizes
- // are OK.
- if (ctypes.size_t.size == 4) {
- do_check_throws(function() {
- ctypes.ArrayType(ctypes.int8_t, 0x100000000);
- }, TypeError);
- do_check_throws(function() {
- ctypes.ArrayType(ctypes.int16_t, 0x80000000);
- }, RangeError);
-
- let large_t = ctypes.int8_t.array(0x80000000);
- do_check_throws(function() { large_t.array(2); }, RangeError);
-
- } else {
- do_check_throws(function() {
- ctypes.ArrayType(ctypes.int8_t, ctypes.UInt64("0xffffffffffffffff"));
- }, TypeError);
- do_check_throws(function() {
- ctypes.ArrayType(ctypes.int16_t, ctypes.UInt64("0x8000000000000000"));
- }, RangeError);
-
- let large_t = ctypes.int8_t.array(0x8000000000000000);
- do_check_throws(function() { large_t.array(2); }, RangeError);
- }
-
- // Test that arrays ImplicitConvert to pointers.
- let b = ctypes.int32_t.array(10)();
- let p = ctypes.int32_t.ptr();
- p.value = b;
- do_check_eq(ptrValue(b.addressOfElement(0)), ptrValue(p));
- p = ctypes.voidptr_t();
- p.value = b;
- do_check_eq(ptrValue(b.addressOfElement(0)), ptrValue(p));
-
- // Test that arrays can be constructed through ImplicitConvert.
- let c_t = ctypes.int32_t.array(6);
- let c = c_t();
- c.value = [1, 2, 3, 4, 5, 6];
- do_check_eq(c.toSource(), "ctypes.int32_t.array(6)([1, 2, 3, 4, 5, 6])");
- do_check_eq(c.toSource(), c.toString());
- eval("var c2 = " + c.toSource());
- do_check_eq(c2.constructor.name, "int32_t[6]");
- do_check_eq(c2.length, 6);
- do_check_eq(c2[3], c[3]);
-
- c.value = c;
- do_check_eq(c[3], 4);
- do_check_throws(function() { c.value; }, TypeError);
- do_check_throws(function() { c.value = [1, 2, 3, 4, 5]; }, TypeError);
- do_check_throws(function() { c.value = [1, 2, 3, 4, 5, 6, 7]; }, TypeError);
- do_check_throws(function() { c.value = [1, 2, 7.4, 4, 5, 6]; }, TypeError);
- do_check_throws(function() { c.value = []; }, TypeError);
-}
-
-function run_type_toString_tests() {
- var c = ctypes;
-
- // Figure out whether we can create functions with ctypes.stdcall_abi and ctypes.winapi_abi.
- var haveStdCallABI;
- try {
- c.FunctionType(c.stdcall_abi, c.int);
- haveStdCallABI = true;
- } catch (x) {
- haveStdCallABI = false;
- }
-
- var haveWinAPIABI;
- try {
- c.FunctionType(c.winapi_abi, c.int);
- haveWinAPIABI = true;
- } catch (x) {
- haveWinAPIABI = false;
- }
-
- do_check_eq(c.char.toString(), "type char");
- do_check_eq(c.short.toString(), "type short");
- do_check_eq(c.int.toString(), "type int");
- do_check_eq(c.long.toString(), "type long");
- do_check_eq(c.long_long.toString(), "type long_long");
- do_check_eq(c.ssize_t.toString(), "type ssize_t");
- do_check_eq(c.int8_t.toString(), "type int8_t");
- do_check_eq(c.int16_t.toString(), "type int16_t");
- do_check_eq(c.int32_t.toString(), "type int32_t");
- do_check_eq(c.int64_t.toString(), "type int64_t");
- do_check_eq(c.intptr_t.toString(), "type intptr_t");
-
- do_check_eq(c.unsigned_char.toString(), "type unsigned_char");
- do_check_eq(c.unsigned_short.toString(), "type unsigned_short");
- do_check_eq(c.unsigned_int.toString(), "type unsigned_int");
- do_check_eq(c.unsigned_long.toString(), "type unsigned_long");
- do_check_eq(c.unsigned_long_long.toString(), "type unsigned_long_long");
- do_check_eq(c.size_t.toString(), "type size_t");
- do_check_eq(c.uint8_t.toString(), "type uint8_t");
- do_check_eq(c.uint16_t.toString(), "type uint16_t");
- do_check_eq(c.uint32_t.toString(), "type uint32_t");
- do_check_eq(c.uint64_t.toString(), "type uint64_t");
- do_check_eq(c.uintptr_t.toString(), "type uintptr_t");
-
- do_check_eq(c.float.toString(), "type float");
- do_check_eq(c.double.toString(), "type double");
- do_check_eq(c.bool.toString(), "type bool");
- do_check_eq(c.void_t.toString(), "type void");
- do_check_eq(c.voidptr_t.toString(), "type void*");
- do_check_eq(c.char16_t.toString(), "type char16_t");
-
- var simplestruct = c.StructType("simplestruct", [{"smitty":c.voidptr_t}]);
- do_check_eq(simplestruct.toString(), "type simplestruct");
-
- // One type modifier, int base type.
- do_check_eq(c.int.ptr.toString(), "type int*");
- do_check_eq(c.ArrayType(c.int).toString(), "type int[]");
- do_check_eq(c.ArrayType(c.int, 4).toString(), "type int[4]");
- do_check_eq(c.FunctionType(c.default_abi, c.int).toString(), "type int()");
- do_check_eq(c.FunctionType(c.default_abi, c.int, [c.bool]).toString(), "type int(bool)");
- do_check_eq(c.FunctionType(c.default_abi, c.int, [c.bool, c.short]).toString(),
- "type int(bool, short)");
- if (haveStdCallABI)
- do_check_eq(c.FunctionType(c.stdcall_abi, c.int).toString(), "type int __stdcall()");
- if (haveWinAPIABI)
- do_check_eq(c.FunctionType(c.winapi_abi, c.int).toString(), "type int WINAPI()");
-
- // One type modifier, struct base type.
- do_check_eq(simplestruct.ptr.toString(), "type simplestruct*");
- do_check_eq(c.ArrayType(simplestruct).toString(), "type simplestruct[]");
- do_check_eq(c.ArrayType(simplestruct, 4).toString(), "type simplestruct[4]");
- do_check_eq(c.FunctionType(c.default_abi, simplestruct).toString(), "type simplestruct()");
-
- // Two levels of type modifiers, int base type.
- do_check_eq(c.int.ptr.ptr.toString(), "type int**");
- do_check_eq(c.ArrayType(c.int.ptr).toString(), "type int*[]");
- do_check_eq(c.FunctionType(c.default_abi, c.int.ptr).toString(), "type int*()");
-
- do_check_eq(c.ArrayType(c.int).ptr.toString(), "type int(*)[]");
- do_check_eq(c.ArrayType(c.ArrayType(c.int, 4)).toString(), "type int[][4]");
- // Functions can't return arrays.
-
- do_check_eq(c.FunctionType(c.default_abi, c.int).ptr.toString(), "type int(*)()");
- // You can't have an array of functions.
- // Functions can't return functions.
-
- // We don't try all the permissible three-deep combinations, but this is fun.
- do_check_eq(c.FunctionType(c.default_abi, c.FunctionType(c.default_abi, c.int).ptr).toString(),
- "type int(*())()");
-}
-
-function run_cast_tests() {
- // Test casting between basic types.
- let i = ctypes.int32_t();
- let j = ctypes.cast(i, ctypes.int16_t);
- do_check_eq(ptrValue(i.address()), ptrValue(j.address()));
- do_check_eq(i.value, j.value);
- let k = ctypes.cast(i, ctypes.uint32_t);
- do_check_eq(ptrValue(i.address()), ptrValue(k.address()));
- do_check_eq(i.value, k.value);
-
- // Test casting to a type of undefined or larger size.
- do_check_throws(function() { ctypes.cast(i, ctypes.void_t); }, TypeError);
- do_check_throws(function() { ctypes.cast(i, ctypes.int32_t.array()); }, TypeError);
- do_check_throws(function() { ctypes.cast(i, ctypes.int64_t); }, TypeError);
-
- // Test casting between special types.
- let g_t = ctypes.StructType("g_t", [{ a: ctypes.int32_t }, { b: ctypes.double }]);
- let a_t = ctypes.ArrayType(g_t, 4);
- let f_t = ctypes.FunctionType(ctypes.default_abi, ctypes.void_t).ptr;
-
- let a = a_t();
- a[0] = { a: 5, b: 7.5 };
- let g = ctypes.cast(a, g_t);
- do_check_eq(ptrValue(a.address()), ptrValue(g.address()));
- do_check_eq(a[0].a, g.a);
-
- let a2 = ctypes.cast(g, g_t.array(1));
- do_check_eq(ptrValue(a2.address()), ptrValue(g.address()));
- do_check_eq(a2[0].a, g.a);
-
- let p = g.address();
- let ip = ctypes.cast(p, ctypes.int32_t.ptr);
- do_check_eq(ptrValue(ip), ptrValue(p));
- do_check_eq(ptrValue(ip.address()), ptrValue(p.address()));
- do_check_eq(ip.contents, g.a);
-
- let f = f_t(0x5);
- let f2 = ctypes.cast(f, ctypes.voidptr_t);
- do_check_eq(ptrValue(f2), ptrValue(f));
- do_check_eq(ptrValue(f2.address()), ptrValue(f.address()));
-}
-
-function run_void_tests(library) {
- let test_void_t = library.declare("test_void_t_cdecl", ctypes.default_abi, ctypes.void_t);
- do_check_eq(test_void_t(), undefined);
-
- // Test that library.declare throws with void function args.
- do_check_throws(function() {
- library.declare("test_void_t_cdecl", ctypes.default_abi, ctypes.void_t, ctypes.void_t);
- }, TypeError);
-
- if ("winLastError" in ctypes) {
- test_void_t = library.declare("test_void_t_stdcall", ctypes.stdcall_abi, ctypes.void_t);
- do_check_eq(test_void_t(), undefined);
-
- // Check that WINAPI symbol lookup for a regular stdcall function fails on
- // Win32 (it's all the same on Win64 though).
- if (ctypes.voidptr_t.size == 4) {
- do_check_throws(function() {
- library.declare("test_void_t_stdcall", ctypes.winapi_abi, ctypes.void_t);
- }, Error);
- }
- }
-}
-
-function run_string_tests(library) {
- let test_ansi_len = library.declare("test_ansi_len", ctypes.default_abi, ctypes.int32_t, ctypes.char.ptr);
- do_check_eq(test_ansi_len(""), 0);
- do_check_eq(test_ansi_len("hello world"), 11);
-
- // don't convert anything else to a string
- let vals = [true, 0, 1/3, undefined, {}, {toString: function () { return "bad"; }}, []];
- for (let i = 0; i < vals.length; i++)
- do_check_throws(function() { test_ansi_len(vals[i]); }, TypeError);
-
- let test_wide_len = library.declare("test_wide_len", ctypes.default_abi, ctypes.int32_t, ctypes.char16_t.ptr);
- do_check_eq(test_wide_len("hello world"), 11);
-
- let test_ansi_ret = library.declare("test_ansi_ret", ctypes.default_abi, ctypes.char.ptr);
- do_check_eq(test_ansi_ret().readString(), "success");
-
- let test_wide_ret = library.declare("test_wide_ret", ctypes.default_abi, ctypes.char16_t.ptr);
- do_check_eq(test_wide_ret().readString(), "success");
-
- let test_ansi_echo = library.declare("test_ansi_echo", ctypes.default_abi, ctypes.char.ptr, ctypes.char.ptr);
- // We cannot pass a string literal directly into test_ansi_echo, since the
- // conversion to ctypes.char.ptr is only valid for the duration of the ffi
- // call. The escaped pointer that's returned will point to freed memory.
- let arg = ctypes.char.array()("anybody in there?");
- do_check_eq(test_ansi_echo(arg).readString(), "anybody in there?");
- do_check_eq(ptrValue(test_ansi_echo(null)), 0);
-}
-
-function run_readstring_tests(library) {
- // ASCII decode test, "hello world"
- let ascii_string = ctypes.unsigned_char.array(12)();
- ascii_string[0] = 0x68;
- ascii_string[1] = 0x65;
- ascii_string[2] = 0x6C;
- ascii_string[3] = 0x6C;
- ascii_string[4] = 0x6F;
- ascii_string[5] = 0x20;
- ascii_string[6] = 0x77;
- ascii_string[7] = 0x6F;
- ascii_string[8] = 0x72;
- ascii_string[9] = 0x6C;
- ascii_string[10] = 0x64;
- ascii_string[11] = 0;
- do_check_eq("hello world", ascii_string.readStringReplaceMalformed());
-
- // UTF-8 decode test, "U+AC00 U+B098 U+B2E4"
- let utf8_string = ctypes.unsigned_char.array(10)();
- utf8_string[0] = 0xEA;
- utf8_string[1] = 0xB0;
- utf8_string[2] = 0x80;
- utf8_string[3] = 0xEB;
- utf8_string[4] = 0x82;
- utf8_string[5] = 0x98;
- utf8_string[6] = 0xEB;
- utf8_string[7] = 0x8B;
- utf8_string[8] = 0xA4;
- utf8_string[9] = 0x00;
- let utf8_result = utf8_string.readStringReplaceMalformed();
- do_check_eq(0xAC00, utf8_result.charCodeAt(0));
- do_check_eq(0xB098, utf8_result.charCodeAt(1));
- do_check_eq(0xB2E4, utf8_result.charCodeAt(2));
-
- // KS5601 decode test, invalid encoded byte should be replaced with U+FFFD
- let ks5601_string = ctypes.unsigned_char.array(7)();
- ks5601_string[0] = 0xB0;
- ks5601_string[1] = 0xA1;
- ks5601_string[2] = 0xB3;
- ks5601_string[3] = 0xAA;
- ks5601_string[4] = 0xB4;
- ks5601_string[5] = 0xD9;
- ks5601_string[6] = 0x00;
- let ks5601_result = ks5601_string.readStringReplaceMalformed();
- do_check_eq(0xFFFD, ks5601_result.charCodeAt(0));
- do_check_eq(0xFFFD, ks5601_result.charCodeAt(1));
- do_check_eq(0xFFFD, ks5601_result.charCodeAt(2));
- do_check_eq(0xFFFD, ks5601_result.charCodeAt(3));
- do_check_eq(0xFFFD, ks5601_result.charCodeAt(4));
- do_check_eq(0xFFFD, ks5601_result.charCodeAt(5));
-
- // Mixed decode test, "test" + "U+AC00 U+B098 U+B2E4" + "test"
- // invalid encoded byte should be replaced with U+FFFD
- let mixed_string = ctypes.unsigned_char.array(15)();
- mixed_string[0] = 0x74;
- mixed_string[1] = 0x65;
- mixed_string[2] = 0x73;
- mixed_string[3] = 0x74;
- mixed_string[4] = 0xB0;
- mixed_string[5] = 0xA1;
- mixed_string[6] = 0xB3;
- mixed_string[7] = 0xAA;
- mixed_string[8] = 0xB4;
- mixed_string[9] = 0xD9;
- mixed_string[10] = 0x74;
- mixed_string[11] = 0x65;
- mixed_string[12] = 0x73;
- mixed_string[13] = 0x74;
- mixed_string[14] = 0x00;
- let mixed_result = mixed_string.readStringReplaceMalformed();
- do_check_eq(0x74, mixed_result.charCodeAt(0));
- do_check_eq(0x65, mixed_result.charCodeAt(1));
- do_check_eq(0x73, mixed_result.charCodeAt(2));
- do_check_eq(0x74, mixed_result.charCodeAt(3));
- do_check_eq(0xFFFD, mixed_result.charCodeAt(4));
- do_check_eq(0xFFFD, mixed_result.charCodeAt(5));
- do_check_eq(0xFFFD, mixed_result.charCodeAt(6));
- do_check_eq(0xFFFD, mixed_result.charCodeAt(7));
- do_check_eq(0xFFFD, mixed_result.charCodeAt(8));
- do_check_eq(0xFFFD, mixed_result.charCodeAt(9));
- do_check_eq(0x74, mixed_result.charCodeAt(10));
- do_check_eq(0x65, mixed_result.charCodeAt(11));
- do_check_eq(0x73, mixed_result.charCodeAt(12));
- do_check_eq(0x74, mixed_result.charCodeAt(13));
-
- // Test of all posible invalid encoded sequence
- let invalid_string = ctypes.unsigned_char.array(27)();
- invalid_string[0] = 0x80; // 10000000
- invalid_string[1] = 0xD0; // 11000000 01110100
- invalid_string[2] = 0x74;
- invalid_string[3] = 0xE0; // 11100000 01110100
- invalid_string[4] = 0x74;
- invalid_string[5] = 0xE0; // 11100000 10100000 01110100
- invalid_string[6] = 0xA0;
- invalid_string[7] = 0x74;
- invalid_string[8] = 0xE0; // 11100000 10000000 01110100
- invalid_string[9] = 0x80;
- invalid_string[10] = 0x74;
- invalid_string[11] = 0xF0; // 11110000 01110100
- invalid_string[12] = 0x74;
- invalid_string[13] = 0xF0; // 11110000 10010000 01110100
- invalid_string[14] = 0x90;
- invalid_string[15] = 0x74;
- invalid_string[16] = 0xF0; // 11110000 10010000 10000000 01110100
- invalid_string[17] = 0x90;
- invalid_string[18] = 0x80;
- invalid_string[19] = 0x74;
- invalid_string[20] = 0xF0; // 11110000 10000000 10000000 01110100
- invalid_string[21] = 0x80;
- invalid_string[22] = 0x80;
- invalid_string[23] = 0x74;
- invalid_string[24] = 0xF0; // 11110000 01110100
- invalid_string[25] = 0x74;
- invalid_string[26] = 0x00;
- let invalid_result = invalid_string.readStringReplaceMalformed();
- do_check_eq(0xFFFD, invalid_result.charCodeAt(0)); // 10000000
- do_check_eq(0xFFFD, invalid_result.charCodeAt(1)); // 11000000 01110100
- do_check_eq(0x74, invalid_result.charCodeAt(2));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(3)); // 11100000 01110100
- do_check_eq(0x74, invalid_result.charCodeAt(4));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(5)); // 11100000 10100000 01110100
- do_check_eq(0x74, invalid_result.charCodeAt(6));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(7)); // 11100000 10000000 01110100
- do_check_eq(0xFFFD, invalid_result.charCodeAt(8));
- do_check_eq(0x74, invalid_result.charCodeAt(9));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(10)); // 11110000 01110100
- do_check_eq(0x74, invalid_result.charCodeAt(11));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(12)); // 11110000 10010000 01110100
- do_check_eq(0x74, invalid_result.charCodeAt(13));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(14)); // 11110000 10010000 10000000 01110100
- do_check_eq(0x74, invalid_result.charCodeAt(15));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(16)); // 11110000 10000000 10000000 01110100
- do_check_eq(0xFFFD, invalid_result.charCodeAt(17));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(18));
- do_check_eq(0x74, invalid_result.charCodeAt(19));
- do_check_eq(0xFFFD, invalid_result.charCodeAt(20)); // 11110000 01110100
- do_check_eq(0x74, invalid_result.charCodeAt(21));
-
- // Test decoding of UTF-8 and CESU-8
- let utf8_cesu8_string = ctypes.unsigned_char.array(10)();
- utf8_cesu8_string[0] = 0xF0; // U+10400 in UTF-8
- utf8_cesu8_string[1] = 0x90;
- utf8_cesu8_string[2] = 0x90;
- utf8_cesu8_string[3] = 0x80;
- utf8_cesu8_string[4] = 0xED; // U+10400 in CESU-8
- utf8_cesu8_string[5] = 0xA0;
- utf8_cesu8_string[6] = 0x81;
- utf8_cesu8_string[7] = 0xED;
- utf8_cesu8_string[8] = 0xB0;
- utf8_cesu8_string[9] = 0x80;
- let utf8_cesu8_result = utf8_cesu8_string.readStringReplaceMalformed();
- do_check_eq(0xD801, utf8_cesu8_result.charCodeAt(0));
- do_check_eq(0xDC00, utf8_cesu8_result.charCodeAt(1));
- do_check_eq(0xFFFD, utf8_cesu8_result.charCodeAt(2));
- do_check_eq(0xFFFD, utf8_cesu8_result.charCodeAt(3));
-}
-
-function run_struct_tests(library) {
- const point_t = new ctypes.StructType("myPOINT",
- [{ x: ctypes.int32_t },
- { y: ctypes.int32_t }]);
- const rect_t = new ctypes.StructType("myRECT",
- [{ top : ctypes.int32_t },
- { left : ctypes.int32_t },
- { bottom: ctypes.int32_t },
- { right : ctypes.int32_t }]);
-
- let test_pt_in_rect = library.declare("test_pt_in_rect", ctypes.default_abi, ctypes.int32_t, rect_t, point_t);
- let rect = new rect_t(10, 5, 5, 10);
- let pt1 = new point_t(6, 6);
- do_check_eq(test_pt_in_rect(rect, pt1), 1);
- let pt2 = new point_t(2, 2);
- do_check_eq(test_pt_in_rect(rect, pt2), 0);
-
- const inner_t = new ctypes.StructType("INNER",
- [{ i1: ctypes.uint8_t },
- { i2: ctypes.int64_t },
- { i3: ctypes.uint8_t }]);
- const nested_t = new ctypes.StructType("NESTED",
- [{ n1 : ctypes.int32_t },
- { n2 : ctypes.int16_t },
- { inner: inner_t },
- { n3 : ctypes.int64_t },
- { n4 : ctypes.int32_t }]);
-
- let test_nested_struct = library.declare("test_nested_struct", ctypes.default_abi, ctypes.int32_t, nested_t);
- let inner = new inner_t(161, 523412, 43);
- let nested = new nested_t(13155, 1241, inner, 24512115, 1234111);
- // add up all the numbers and make sure the C function agrees
- do_check_eq(test_nested_struct(nested), 26284238);
-
- // test returning a struct by value
- let test_struct_return = library.declare("test_struct_return", ctypes.default_abi, point_t, rect_t);
- let ret = test_struct_return(rect);
- do_check_eq(ret.x, rect.left);
- do_check_eq(ret.y, rect.top);
-
- // struct parameter ABI depends on size; test returning a large struct by value
- test_struct_return = library.declare("test_large_struct_return", ctypes.default_abi, rect_t, rect_t, rect_t);
- ret = test_struct_return(rect_t(1, 2, 3, 4), rect_t(5, 6, 7, 8));
- do_check_eq(ret.left, 2);
- do_check_eq(ret.right, 4);
- do_check_eq(ret.top, 5);
- do_check_eq(ret.bottom, 7);
-
- // ... and tests structs < 8 bytes in size
- for (let i = 1; i < 8; ++i)
- run_small_struct_test(library, rect_t, i);
-
- // test passing a struct by pointer
- let test_init_pt = library.declare("test_init_pt", ctypes.default_abi, ctypes.void_t, point_t.ptr, ctypes.int32_t, ctypes.int32_t);
- test_init_pt(pt1.address(), 9, 10);
- do_check_eq(pt1.x, 9);
- do_check_eq(pt1.y, 10);
-}
-
-function run_small_struct_test(library, rect_t, bytes)
-{
- let fields = [];
- for (let i = 0; i < bytes; ++i) {
- let field = {};
- field["f" + i] = ctypes.uint8_t;
- fields.push(field);
- }
- const small_t = new ctypes.StructType("SMALL", fields);
-
- let test_small_struct_return = library.declare("test_" + bytes + "_byte_struct_return", ctypes.default_abi, small_t, rect_t);
- let ret = test_small_struct_return(rect_t(1, 7, 13, 45));
-
- let exp = [1, 7, 13, 45];
- let j = 0;
- for (let i = 0; i < bytes; ++i) {
- do_check_eq(ret["f" + i], exp[j]);
- if (++j == 4)
- j = 0;
- }
-}
-
-function run_function_tests(library)
-{
- let test_ansi_len = library.declare("test_ansi_len", ctypes.default_abi,
- ctypes.int32_t, ctypes.char.ptr);
- let fn_t = ctypes.FunctionType(ctypes.default_abi, ctypes.int32_t,
- [ ctypes.char.ptr ]).ptr;
-
- let test_fnptr = library.declare("test_fnptr", ctypes.default_abi, fn_t);
-
- // Test that the value handed back by test_fnptr matches the function pointer
- // for test_ansi_len itself.
- let ptr = test_fnptr();
- do_check_eq(ptrValue(test_ansi_len), ptrValue(ptr));
-
- // Test that we can call ptr().
- do_check_eq(ptr("function pointers rule!"), 23);
-
- // Test that we can call via call and apply
- do_check_eq(ptr.call(null, "function pointers rule!"), 23);
- do_check_eq(ptr.apply(null, ["function pointers rule!"]), 23);
-
- // Test that we cannot call non-function pointers via call and apply
- let p_t = ctypes.PointerType(ctypes.int32_t);
- let p = p_t();
- do_check_throws(function() { p.call(null, "woo"); }, TypeError);
- do_check_throws(function() { p.apply(null, ["woo"]); }, TypeError);
-
- // Test the function pointers still behave as regular pointers
- do_check_false(ptr.isNull(), "PointerType methods should still be valid");
-
- // Test that library.declare() returns data of type FunctionType.ptr, and that
- // it is immutable.
- do_check_true(test_ansi_len.constructor.targetType.__proto__ ===
- ctypes.FunctionType.prototype);
- do_check_eq(test_ansi_len.constructor.toSource(),
- "ctypes.FunctionType(ctypes.default_abi, ctypes.int32_t, [ctypes.char.ptr]).ptr");
-/* disabled temporarily per bug 598225.
- do_check_throws(function() { test_ansi_len.value = null; }, Error);
- do_check_eq(ptrValue(test_ansi_len), ptrValue(ptr));
-*/
-
- // Test that the library.declare(name, functionType) form works.
- let test_ansi_len_2 = library.declare("test_ansi_len", fn_t);
- do_check_true(test_ansi_len_2.constructor === fn_t);
- do_check_eq(ptrValue(test_ansi_len), ptrValue(test_ansi_len_2));
-/* disabled temporarily per bug 598225.
- do_check_throws(function() { test_ansi_len_2.value = null; }, Error);
- do_check_eq(ptrValue(test_ansi_len_2), ptrValue(ptr));
-*/
-}
-
-function run_closure_tests(library)
-{
- run_single_closure_tests(library, ctypes.default_abi, "cdecl");
- if ("winLastError" in ctypes) {
- run_single_closure_tests(library, ctypes.stdcall_abi, "stdcall");
-
- // Check that attempting to construct a ctypes.winapi_abi closure throws.
- function closure_fn()
- {
- return 1;
- }
- let fn_t = ctypes.FunctionType(ctypes.winapi_abi, ctypes.int32_t, []).ptr;
- do_check_throws(function() { fn_t(closure_fn) }, Error);
- }
-}
-
-function run_single_closure_tests(library, abi, suffix)
-{
- let b = 23;
-
- function closure_fn(i)
- {
- if (i == 42)
- throw "7.5 million years for that?";
- return "a" in this ? i + this.a : i + b;
- }
-
- do_check_eq(closure_fn(7), 7 + b);
- let thisobj = { a: 5 };
- do_check_eq(closure_fn.call(thisobj, 7), 7 + thisobj.a);
-
- // Construct a closure, and call it ourselves.
- let fn_t = ctypes.FunctionType(abi, ctypes.int32_t, [ ctypes.int8_t ]).ptr;
- let closure = fn_t(closure_fn);
- do_check_eq(closure(-17), -17 + b);
-
- // Have C code call it.
- let test_closure = library.declare("test_closure_" + suffix,
- ctypes.default_abi, ctypes.int32_t, ctypes.int8_t, fn_t);
- do_check_eq(test_closure(-52, closure), -52 + b);
-
- // Do the same, but specify 'this'.
- let closure2 = fn_t(closure_fn, thisobj);
- do_check_eq(closure2(-17), -17 + thisobj.a);
- do_check_eq(test_closure(-52, closure2), -52 + thisobj.a);
-
- // Specify an error sentinel, and have the JS code throw (see bug 599791).
- let closure3 = fn_t(closure_fn, null, 54);
- do_check_eq(closure3(42), 54);
- do_check_eq(test_closure(42, closure3), 54);
-
- // Check what happens when the return type is bigger than a word.
- var fn_64_t = ctypes.FunctionType(ctypes.default_abi, ctypes.uint64_t, [ctypes.bool]).ptr;
- var bignum1 = ctypes.UInt64.join(0xDEADBEEF, 0xBADF00D);
- var bignum2 = ctypes.UInt64.join(0xDEFEC8ED, 0xD15EA5E);
- function closure_fn_64(fail)
- {
- if (fail)
- throw "Just following orders, sir!";
- return bignum1;
- }
- var closure64 = fn_64_t(closure_fn_64, null, bignum2);
- do_check_eq(ctypes.UInt64.compare(closure64(false), bignum1), 0);
- do_check_eq(ctypes.UInt64.compare(closure64(true), bignum2), 0);
-
- // Test a callback that returns void (see bug 682504).
- var fn_v_t = ctypes.FunctionType(ctypes.default_abi, ctypes.void_t, []).ptr;
- fn_v_t(function() {})(); // Don't crash
-
- // Code evaluated in a sandbox uses (and pushes) a separate JSContext.
- // Make sure that we don't run into an assertion caused by a cx stack
- // mismatch with the cx stashed in the closure.
- try {
- var sb = Components.utils.Sandbox("http://www.example.com");
- sb.fn = fn_v_t(function() { sb.foo = {}; });
- Components.utils.evalInSandbox("fn();", sb);
- } catch (e) {} // Components not available in workers.
-
- // Make sure that a void callback can't return an error sentinel.
- var sentinelThrew = false;
- try {
- fn_v_t(function() {}, null, -1);
- } catch (e) {
- sentinelThrew = true;
- }
- do_check_true(sentinelThrew);
-}
-
-function run_variadic_tests(library) {
- let sum_va_type = ctypes.FunctionType(ctypes.default_abi,
- ctypes.int32_t,
- [ctypes.uint8_t, "..."]).ptr,
- sum_va = library.declare("test_sum_va_cdecl", ctypes.default_abi, ctypes.int32_t,
- ctypes.uint8_t, "...");
-
- do_check_eq(sum_va_type.toSource(),
- 'ctypes.FunctionType(ctypes.default_abi, ctypes.int32_t, [ctypes.uint8_t, "..."]).ptr');
- do_check_eq(sum_va.constructor.name, "int32_t(*)(uint8_t, ...)");
- do_check_true(sum_va.constructor.targetType.isVariadic);
-
- do_check_eq(sum_va(3,
- ctypes.int32_t(1),
- ctypes.int32_t(2),
- ctypes.int32_t(3)),
- 6);
-
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.default_abi, ctypes.bool,
- [ctypes.bool, "...", ctypes.bool]);
- }, Error);
-
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.default_abi, ctypes.bool, ["..."]);
- }, Error);
-
- if ("winLastError" in ctypes) {
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.stdcall_abi, ctypes.bool,
- [ctypes.bool, "..."]);
- }, Error);
- do_check_throws(function() {
- ctypes.FunctionType(ctypes.winapi_abi, ctypes.bool,
- [ctypes.bool, "..."]);
- }, Error);
- }
-
- do_check_throws(function() {
- // No variadic closure callbacks allowed.
- sum_va_type(function() {});
- }, Error);
-
- let count_true_va = library.declare("test_sum_va_cdecl", ctypes.default_abi, ctypes.uint8_t,
- ctypes.uint8_t, "...");
- do_check_eq(count_true_va(8,
- ctypes.bool(false),
- ctypes.bool(false),
- ctypes.bool(false),
- ctypes.bool(true),
- ctypes.bool(true),
- ctypes.bool(false),
- ctypes.bool(true),
- ctypes.bool(true)),
- 4);
-
- let add_char_short_int_va = library.declare("test_add_char_short_int_va_cdecl",
- ctypes.default_abi, ctypes.void_t,
- ctypes.uint32_t.ptr, "..."),
- result = ctypes.uint32_t(3);
-
- add_char_short_int_va(result.address(),
- ctypes.char(5),
- ctypes.short(7),
- ctypes.uint32_t(11));
-
- do_check_eq(result.value, 3 + 5 + 7 + 11);
-
- result = ctypes.int32_t.array(3)([1, 1, 1]),
- v1 = ctypes.int32_t.array(4)([1, 2, 3, 5]),
- v2 = ctypes.int32_t.array(3)([7, 11, 13]),
- vector_add_va = library.declare("test_vector_add_va_cdecl",
- ctypes.default_abi, ctypes.int32_t.ptr,
- ctypes.uint8_t, ctypes.uint8_t, "..."),
- // Note that vector_add_va zeroes out result first.
- vec_sum = vector_add_va(2, 3, result, v1, v2);
- do_check_eq(vec_sum.contents, 8);
- do_check_eq(result[0], 8);
- do_check_eq(result[1], 13);
- do_check_eq(result[2], 16);
-
- do_check_true(!!(sum_va_type().value = sum_va_type()));
- let sum_notva_type = ctypes.FunctionType(sum_va_type.targetType.abi,
- sum_va_type.targetType.returnType,
- [ctypes.uint8_t]).ptr;
- do_check_throws(function() {
- sum_va_type().value = sum_notva_type();
- }, TypeError);
-}
-
-function run_static_data_tests(library)
-{
- const rect_t = new ctypes.StructType("myRECT",
- [{ top : ctypes.int32_t },
- { left : ctypes.int32_t },
- { bottom: ctypes.int32_t },
- { right : ctypes.int32_t }]);
-
- let data_rect = library.declare("data_rect", rect_t);
-
- // Test reading static data.
- do_check_true(data_rect.constructor === rect_t);
- do_check_eq(data_rect.top, -1);
- do_check_eq(data_rect.left, -2);
- do_check_eq(data_rect.bottom, 3);
- do_check_eq(data_rect.right, 4);
-
- // Test writing.
- data_rect.top = 9;
- data_rect.left = 8;
- data_rect.bottom = -11;
- data_rect.right = -12;
- do_check_eq(data_rect.top, 9);
- do_check_eq(data_rect.left, 8);
- do_check_eq(data_rect.bottom, -11);
- do_check_eq(data_rect.right, -12);
-
- // Make sure it's been written, not copied.
- let data_rect_2 = library.declare("data_rect", rect_t);
- do_check_eq(data_rect_2.top, 9);
- do_check_eq(data_rect_2.left, 8);
- do_check_eq(data_rect_2.bottom, -11);
- do_check_eq(data_rect_2.right, -12);
- do_check_eq(ptrValue(data_rect.address()), ptrValue(data_rect_2.address()));
-}
-
-function run_cpp_class_tests(library)
-{
- // try the gcc mangling, unless we're using MSVC.
- let OS = get_os();
- let ctor_symbol;
- let add_symbol;
- let abi;
- if (OS == "WINNT") {
- // for compatibility for Win32 vs Win64
- abi = ctypes.thiscall_abi;
- if (ctypes.size_t.size == 8) {
- ctor_symbol = '??0TestClass@@QEAA@H@Z';
- add_symbol = '?Add@TestClass@@QEAAHH@Z';
- } else {
- ctor_symbol = '??0TestClass@@QAE@H@Z';
- add_symbol = '?Add@TestClass@@QAEHH@Z';
- }
- } else {
- abi = ctypes.default_abi;
- ctor_symbol = "_ZN9TestClassC1Ei";
- add_symbol = "_ZN9TestClass3AddEi";
- }
-
- let test_class_ctor = library.declare(ctor_symbol, abi, ctypes.void_t,
- ctypes.int32_t.ptr, ctypes.int32_t);
- let i = ctypes.int32_t();
- test_class_ctor(i.address(), 8);
- do_check_eq(i.value, 8);
-
- let test_class_add = library.declare(add_symbol, abi, ctypes.int32_t,
- ctypes.int32_t.ptr, ctypes.int32_t);
- let j = test_class_add(i.address(), 5);
- do_check_eq(j, 13);
- do_check_eq(i.value, 13);
-}
-
-// bug 522360 - try loading system library without full path
-function run_load_system_library()
-{
- let syslib;
- let OS = get_os();
- if (OS == "WINNT") {
- syslib = ctypes.open("user32.dll");
- } else if (OS == "Darwin") {
- syslib = ctypes.open("libm.dylib");
- } else if (OS == "Linux" || OS == "Android" || OS.match(/BSD$/)) {
- try {
- syslib = ctypes.open("libm.so");
- } catch (e) {
- // limb.so wasn't available, try libm.so.6 instead
- syslib = ctypes.open("libm.so.6");
- }
- } else {
- do_throw("please add a system library for this test");
- }
- syslib.close();
- return true;
-}
diff --git a/toolkit/components/ctypes/tests/unit/xpcshell.ini b/toolkit/components/ctypes/tests/unit/xpcshell.ini
deleted file mode 100644
index 8920d4f9b..000000000
--- a/toolkit/components/ctypes/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,13 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-skip-if = toolkit == 'android'
-
-[test_errno.js]
-
-[test_finalizer.js]
-[test_finalizer_shouldfail.js]
-[test_finalizer_shouldaccept.js]
-[test_jsctypes.js]
-# Bug 676989: test fails consistently on Android
-fail-if = os == "android"
diff --git a/toolkit/components/downloads/moz.build b/toolkit/components/downloads/moz.build
index e611f4010..b6f68e5fb 100644
--- a/toolkit/components/downloads/moz.build
+++ b/toolkit/components/downloads/moz.build
@@ -4,23 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-with Files('*'):
- BUG_COMPONENT = ('Toolkit', 'Download Manager')
-
-with Files('ApplicationReputation.*'):
- BUG_COMPONENT = ('Toolkit', 'Safe Browsing')
-
-with Files('chromium/*'):
- BUG_COMPONENT = ('Toolkit', 'Safe Browsing')
-
-with Files('generate_csd.sh'):
- BUG_COMPONENT = ('Toolkit', 'Safe Browsing')
-
-with Files('nsIApplicationReputation.idl'):
- BUG_COMPONENT = ('Toolkit', 'Safe Browsing')
-
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-
XPIDL_SOURCES += [
'nsIApplicationReputation.idl',
'nsIDownload.idl',
@@ -31,14 +14,10 @@ XPIDL_SOURCES += [
XPIDL_MODULE = 'downloads'
-UNIFIED_SOURCES += [
- 'nsDownloadManager.cpp'
-]
+UNIFIED_SOURCES += ['nsDownloadManager.cpp']
# SQLFunctions.cpp cannot be built in unified mode because of Windows headers.
-SOURCES += [
- 'SQLFunctions.cpp',
-]
+SOURCES += ['SQLFunctions.cpp']
if CONFIG['MOZ_URL_CLASSIFIER']:
UNIFIED_SOURCES += [
@@ -49,9 +28,7 @@ if CONFIG['MOZ_URL_CLASSIFIER']:
if CONFIG['OS_ARCH'] == 'WINNT':
# Can't build unified because we need CreateEvent which some IPC code
# included in LoadContext ends up undefining.
- SOURCES += [
- 'nsDownloadScanner.cpp',
- ]
+ SOURCES += ['nsDownloadScanner.cpp']
# The Communicator Downloads Manager uses its own DownloadManagerUI
# component and it can't be guaranteed that its implimentation will override
diff --git a/toolkit/components/downloads/test/unit/.eslintrc.js b/toolkit/components/downloads/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/downloads/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/downloads/test/unit/data/block_digest.chunk b/toolkit/components/downloads/test/unit/data/block_digest.chunk
deleted file mode 100644
index 34c47c4bb..000000000
--- a/toolkit/components/downloads/test/unit/data/block_digest.chunk
+++ /dev/null
@@ -1,2 +0,0 @@
-a:5:32:37
-,AJ,AJ8Wbb_e;OτCV \ No newline at end of file
diff --git a/toolkit/components/downloads/test/unit/data/digest.chunk b/toolkit/components/downloads/test/unit/data/digest.chunk
deleted file mode 100644
index b1fbb4667..000000000
--- a/toolkit/components/downloads/test/unit/data/digest.chunk
+++ /dev/null
@@ -1,3 +0,0 @@
-a:5:32:64
-_H^a7]=#nmnoQ
-@.R0D7Y4ퟆS$8 \ No newline at end of file
diff --git a/toolkit/components/downloads/test/unit/data/signed_win.exe b/toolkit/components/downloads/test/unit/data/signed_win.exe
deleted file mode 100644
index de3bb40e8..000000000
--- a/toolkit/components/downloads/test/unit/data/signed_win.exe
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/downloads/test/unit/head_download_manager.js b/toolkit/components/downloads/test/unit/head_download_manager.js
deleted file mode 100644
index 1e8248071..000000000
--- a/toolkit/components/downloads/test/unit/head_download_manager.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This file tests the download manager backend
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-do_get_profile();
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://testing-common/httpd.js");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-
-function createURI(aObj)
-{
- var ios = Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService);
- return (aObj instanceof Ci.nsIFile) ? ios.newFileURI(aObj) :
- ios.newURI(aObj, null, null);
-}
diff --git a/toolkit/components/downloads/test/unit/tail_download_manager.js b/toolkit/components/downloads/test/unit/tail_download_manager.js
deleted file mode 100644
index 4043f31b9..000000000
--- a/toolkit/components/downloads/test/unit/tail_download_manager.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Provides infrastructure for automated download components tests.
- */
-
-"use strict";
-
-// Termination functions common to all tests
-
-add_task(function* test_common_terminate()
-{
- // Stop the HTTP server. We must do this inside a task in "tail.js" until the
- // xpcshell testing framework supports asynchronous termination functions.
- let deferred = Promise.defer();
- gHttpServer.stop(deferred.resolve);
- yield deferred.promise;
-});
-
diff --git a/toolkit/components/downloads/test/unit/test_app_rep.js b/toolkit/components/downloads/test/unit/test_app_rep.js
deleted file mode 100644
index 636a71e78..000000000
--- a/toolkit/components/downloads/test/unit/test_app_rep.js
+++ /dev/null
@@ -1,342 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Cu.import('resource://gre/modules/NetUtil.jsm');
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const gAppRep = Cc["@mozilla.org/downloads/application-reputation-service;1"].
- getService(Ci.nsIApplicationReputationService);
-var gHttpServ = null;
-var gTables = {};
-
-var ALLOW_LIST = 0;
-var BLOCK_LIST = 1;
-var NO_LIST = 2;
-
-var whitelistedURI = createURI("http://foo:bar@whitelisted.com/index.htm#junk");
-var exampleURI = createURI("http://user:password@example.com/i.html?foo=bar");
-var blocklistedURI = createURI("http://baz:qux@blocklisted.com?xyzzy");
-
-const appRepURLPref = "browser.safebrowsing.downloads.remote.url";
-
-function readFileToString(aFilename) {
- let f = do_get_file(aFilename);
- let stream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- stream.init(f, -1, 0, 0);
- let buf = NetUtil.readInputStreamToString(stream, stream.available());
- return buf;
-}
-
-// Registers a table for which to serve update chunks. Returns a promise that
-// resolves when that chunk has been downloaded.
-function registerTableUpdate(aTable, aFilename) {
- // If we haven't been given an update for this table yet, add it to the map
- if (!(aTable in gTables)) {
- gTables[aTable] = [];
- }
-
- // The number of chunks associated with this table.
- let numChunks = gTables[aTable].length + 1;
- let redirectPath = "/" + aTable + "-" + numChunks;
- let redirectUrl = "localhost:4444" + redirectPath;
-
- // Store redirect url for that table so we can return it later when we
- // process an update request.
- gTables[aTable].push(redirectUrl);
-
- gHttpServ.registerPathHandler(redirectPath, function(request, response) {
- do_print("Mock safebrowsing server handling request for " + redirectPath);
- let contents = readFileToString(aFilename);
- do_print("Length of " + aFilename + ": " + contents.length);
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(contents, contents.length);
- });
-}
-
-add_task(function* test_setup() {
- // Set up a local HTTP server to return bad verdicts.
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- // Ensure safebrowsing is enabled for this test, even if the app
- // doesn't have it enabled.
- Services.prefs.setBoolPref("browser.safebrowsing.malware.enabled", true);
- Services.prefs.setBoolPref("browser.safebrowsing.downloads.enabled", true);
- do_register_cleanup(function() {
- Services.prefs.clearUserPref("browser.safebrowsing.malware.enabled");
- Services.prefs.clearUserPref("browser.safebrowsing.downloads.enabled");
- });
-
- // Set block and allow tables explicitly, since the allowlist is normally
- // disabled on non-Windows platforms.
- Services.prefs.setCharPref("urlclassifier.downloadBlockTable",
- "goog-badbinurl-shavar");
- Services.prefs.setCharPref("urlclassifier.downloadAllowTable",
- "goog-downloadwhite-digest256");
- do_register_cleanup(function() {
- Services.prefs.clearUserPref("urlclassifier.downloadBlockTable");
- Services.prefs.clearUserPref("urlclassifier.downloadAllowTable");
- });
-
- gHttpServ = new HttpServer();
- gHttpServ.registerDirectory("/", do_get_cwd());
- gHttpServ.registerPathHandler("/download", function(request, response) {
- do_throw("This test should never make a remote lookup");
- });
- gHttpServ.start(4444);
-});
-
-function run_test() {
- run_next_test();
-}
-
-function check_telemetry(aCount,
- aShouldBlockCount,
- aListCounts) {
- let count = Cc["@mozilla.org/base/telemetry;1"]
- .getService(Ci.nsITelemetry)
- .getHistogramById("APPLICATION_REPUTATION_COUNT")
- .snapshot();
- do_check_eq(count.counts[1], aCount);
- let local = Cc["@mozilla.org/base/telemetry;1"]
- .getService(Ci.nsITelemetry)
- .getHistogramById("APPLICATION_REPUTATION_LOCAL")
- .snapshot();
- do_check_eq(local.counts[ALLOW_LIST], aListCounts[ALLOW_LIST],
- "Allow list counts don't match");
- do_check_eq(local.counts[BLOCK_LIST], aListCounts[BLOCK_LIST],
- "Block list counts don't match");
- do_check_eq(local.counts[NO_LIST], aListCounts[NO_LIST],
- "No list counts don't match");
-
- let shouldBlock = Cc["@mozilla.org/base/telemetry;1"]
- .getService(Ci.nsITelemetry)
- .getHistogramById("APPLICATION_REPUTATION_SHOULD_BLOCK")
- .snapshot();
- // SHOULD_BLOCK = true
- do_check_eq(shouldBlock.counts[1], aShouldBlockCount);
- // Sanity check that SHOULD_BLOCK total adds up to the COUNT.
- do_check_eq(shouldBlock.counts[0] + shouldBlock.counts[1], aCount);
-}
-
-function get_telemetry_counts() {
- let count = Cc["@mozilla.org/base/telemetry;1"]
- .getService(Ci.nsITelemetry)
- .getHistogramById("APPLICATION_REPUTATION_COUNT")
- .snapshot();
- let local = Cc["@mozilla.org/base/telemetry;1"]
- .getService(Ci.nsITelemetry)
- .getHistogramById("APPLICATION_REPUTATION_LOCAL")
- .snapshot();
- let shouldBlock = Cc["@mozilla.org/base/telemetry;1"]
- .getService(Ci.nsITelemetry)
- .getHistogramById("APPLICATION_REPUTATION_SHOULD_BLOCK")
- .snapshot();
- return { total: count.counts[1],
- shouldBlock: shouldBlock.counts[1],
- listCounts: local.counts };
-}
-
-add_test(function test_nullSourceURI() {
- let counts = get_telemetry_counts();
- gAppRep.queryReputation({
- // No source URI
- fileSize: 12,
- }, function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_ERROR_UNEXPECTED, aStatus);
- do_check_false(aShouldBlock);
- check_telemetry(counts.total + 1, counts.shouldBlock, counts.listCounts);
- run_next_test();
- });
-});
-
-add_test(function test_nullCallback() {
- let counts = get_telemetry_counts();
- try {
- gAppRep.queryReputation({
- sourceURI: createURI("http://example.com"),
- fileSize: 12,
- }, null);
- do_throw("Callback cannot be null");
- } catch (ex) {
- if (ex.result != Cr.NS_ERROR_INVALID_POINTER)
- throw ex;
- // We don't even increment the count here, because there's no callback.
- check_telemetry(counts.total, counts.shouldBlock, counts.listCounts);
- run_next_test();
- }
-});
-
-// Set up the local whitelist.
-add_test(function test_local_list() {
- // Construct a response with redirect urls.
- function processUpdateRequest() {
- let response = "n:1000\n";
- for (let table in gTables) {
- response += "i:" + table + "\n";
- for (let i = 0; i < gTables[table].length; ++i) {
- response += "u:" + gTables[table][i] + "\n";
- }
- }
- do_print("Returning update response: " + response);
- return response;
- }
- gHttpServ.registerPathHandler("/downloads", function(request, response) {
- let blob = processUpdateRequest();
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(blob, blob.length);
- });
-
- let streamUpdater = Cc["@mozilla.org/url-classifier/streamupdater;1"]
- .getService(Ci.nsIUrlClassifierStreamUpdater);
-
- // Load up some update chunks for the safebrowsing server to serve.
- // This chunk contains the hash of blocklisted.com/.
- registerTableUpdate("goog-badbinurl-shavar", "data/block_digest.chunk");
- // This chunk contains the hash of whitelisted.com/.
- registerTableUpdate("goog-downloadwhite-digest256", "data/digest.chunk");
-
- // Download some updates, and don't continue until the downloads are done.
- function updateSuccess(aEvent) {
- // Timeout of n:1000 is constructed in processUpdateRequest above and
- // passed back in the callback in nsIUrlClassifierStreamUpdater on success.
- do_check_eq("1000", aEvent);
- do_print("All data processed");
- run_next_test();
- }
- // Just throw if we ever get an update or download error.
- function handleError(aEvent) {
- do_throw("We didn't download or update correctly: " + aEvent);
- }
- streamUpdater.downloadUpdates(
- "goog-downloadwhite-digest256,goog-badbinurl-shavar",
- "goog-downloadwhite-digest256,goog-badbinurl-shavar;\n",
- true, // isPostRequest.
- "http://localhost:4444/downloads",
- updateSuccess, handleError, handleError);
-});
-
-add_test(function test_unlisted() {
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- let counts = get_telemetry_counts();
- let listCounts = counts.listCounts;
- listCounts[NO_LIST]++;
- gAppRep.queryReputation({
- sourceURI: exampleURI,
- fileSize: 12,
- }, function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_false(aShouldBlock);
- check_telemetry(counts.total + 1, counts.shouldBlock, listCounts);
- run_next_test();
- });
-});
-
-add_test(function test_non_uri() {
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- let counts = get_telemetry_counts();
- let listCounts = counts.listCounts;
- // No listcount is incremented, since the sourceURI is not an nsIURL
- let source = NetUtil.newURI("data:application/octet-stream,ABC");
- do_check_false(source instanceof Ci.nsIURL);
- gAppRep.queryReputation({
- sourceURI: source,
- fileSize: 12,
- }, function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_false(aShouldBlock);
- check_telemetry(counts.total + 1, counts.shouldBlock, listCounts);
- run_next_test();
- });
-});
-
-add_test(function test_local_blacklist() {
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- let counts = get_telemetry_counts();
- let listCounts = counts.listCounts;
- listCounts[BLOCK_LIST]++;
- gAppRep.queryReputation({
- sourceURI: blocklistedURI,
- fileSize: 12,
- }, function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_true(aShouldBlock);
- check_telemetry(counts.total + 1, counts.shouldBlock + 1, listCounts);
- run_next_test();
- });
-});
-
-add_test(function test_referer_blacklist() {
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- let counts = get_telemetry_counts();
- let listCounts = counts.listCounts;
- listCounts[BLOCK_LIST]++;
- gAppRep.queryReputation({
- sourceURI: exampleURI,
- referrerURI: blocklistedURI,
- fileSize: 12,
- }, function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_true(aShouldBlock);
- check_telemetry(counts.total + 1, counts.shouldBlock + 1, listCounts);
- run_next_test();
- });
-});
-
-add_test(function test_blocklist_trumps_allowlist() {
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- let counts = get_telemetry_counts();
- let listCounts = counts.listCounts;
- listCounts[BLOCK_LIST]++;
- gAppRep.queryReputation({
- sourceURI: whitelistedURI,
- referrerURI: blocklistedURI,
- fileSize: 12,
- }, function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_true(aShouldBlock);
- check_telemetry(counts.total + 1, counts.shouldBlock + 1, listCounts);
- run_next_test();
- });
-});
-
-add_test(function test_redirect_on_blocklist() {
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- let counts = get_telemetry_counts();
- let listCounts = counts.listCounts;
- listCounts[BLOCK_LIST]++;
- listCounts[ALLOW_LIST]++;
- let secman = Services.scriptSecurityManager;
- let badRedirects = Cc["@mozilla.org/array;1"]
- .createInstance(Ci.nsIMutableArray);
- badRedirects.appendElement(secman.createCodebasePrincipal(exampleURI, {}),
- false);
- badRedirects.appendElement(secman.createCodebasePrincipal(blocklistedURI, {}),
- false);
- badRedirects.appendElement(secman.createCodebasePrincipal(whitelistedURI, {}),
- false);
- gAppRep.queryReputation({
- sourceURI: whitelistedURI,
- referrerURI: exampleURI,
- redirects: badRedirects,
- fileSize: 12,
- }, function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_true(aShouldBlock);
- check_telemetry(counts.total + 1, counts.shouldBlock + 1, listCounts);
- run_next_test();
- });
-});
diff --git a/toolkit/components/downloads/test/unit/test_app_rep_maclinux.js b/toolkit/components/downloads/test/unit/test_app_rep_maclinux.js
deleted file mode 100644
index 7f94d1520..000000000
--- a/toolkit/components/downloads/test/unit/test_app_rep_maclinux.js
+++ /dev/null
@@ -1,303 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests signature extraction using Windows Authenticode APIs of
- * downloaded files.
- */
-
-// Globals
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-
-const gAppRep = Cc["@mozilla.org/downloads/application-reputation-service;1"].
- getService(Ci.nsIApplicationReputationService);
-var gStillRunning = true;
-var gTables = {};
-var gHttpServer = null;
-
-const appRepURLPref = "browser.safebrowsing.downloads.remote.url";
-const remoteEnabledPref = "browser.safebrowsing.downloads.remote.enabled";
-
-function readFileToString(aFilename) {
- let f = do_get_file(aFilename);
- let stream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- stream.init(f, -1, 0, 0);
- let buf = NetUtil.readInputStreamToString(stream, stream.available());
- return buf;
-}
-
-function registerTableUpdate(aTable, aFilename) {
- // If we haven't been given an update for this table yet, add it to the map
- if (!(aTable in gTables)) {
- gTables[aTable] = [];
- }
-
- // The number of chunks associated with this table.
- let numChunks = gTables[aTable].length + 1;
- let redirectPath = "/" + aTable + "-" + numChunks;
- let redirectUrl = "localhost:4444" + redirectPath;
-
- // Store redirect url for that table so we can return it later when we
- // process an update request.
- gTables[aTable].push(redirectUrl);
-
- gHttpServer.registerPathHandler(redirectPath, function(request, response) {
- do_print("Mock safebrowsing server handling request for " + redirectPath);
- let contents = readFileToString(aFilename);
- do_print("Length of " + aFilename + ": " + contents.length);
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(contents, contents.length);
- });
-}
-
-// Tests
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function test_setup()
-{
- // Wait 10 minutes, that is half of the external xpcshell timeout.
- do_timeout(10 * 60 * 1000, function() {
- if (gStillRunning) {
- do_throw("Test timed out.");
- }
- });
- // Set up a local HTTP server to return bad verdicts.
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- // Ensure safebrowsing is enabled for this test, even if the app
- // doesn't have it enabled.
- Services.prefs.setBoolPref("browser.safebrowsing.malware.enabled", true);
- Services.prefs.setBoolPref("browser.safebrowsing.downloads.enabled", true);
- // Set block table explicitly, no need for the allow table though
- Services.prefs.setCharPref("urlclassifier.downloadBlockTable",
- "goog-badbinurl-shavar");
- // SendRemoteQueryInternal needs locale preference.
- let locale = Services.prefs.getCharPref("general.useragent.locale");
- Services.prefs.setCharPref("general.useragent.locale", "en-US");
-
- do_register_cleanup(function() {
- Services.prefs.clearUserPref("browser.safebrowsing.malware.enabled");
- Services.prefs.clearUserPref("browser.safebrowsing.downloads.enabled");
- Services.prefs.clearUserPref("urlclassifier.downloadBlockTable");
- Services.prefs.setCharPref("general.useragent.locale", locale);
- });
-
- gHttpServer = new HttpServer();
- gHttpServer.registerDirectory("/", do_get_cwd());
-
- function createVerdict(aShouldBlock) {
- // We can't programmatically create a protocol buffer here, so just
- // hardcode some already serialized ones.
- let blob = String.fromCharCode(parseInt(0x08, 16));
- if (aShouldBlock) {
- // A safe_browsing::ClientDownloadRequest with a DANGEROUS verdict
- blob += String.fromCharCode(parseInt(0x01, 16));
- } else {
- // A safe_browsing::ClientDownloadRequest with a SAFE verdict
- blob += String.fromCharCode(parseInt(0x00, 16));
- }
- return blob;
- }
-
- gHttpServer.registerPathHandler("/throw", function(request, response) {
- do_throw("We shouldn't be getting here");
- });
-
- gHttpServer.registerPathHandler("/download", function(request, response) {
- do_print("Querying remote server for verdict");
- response.setHeader("Content-Type", "application/octet-stream", false);
- let buf = NetUtil.readInputStreamToString(
- request.bodyInputStream,
- request.bodyInputStream.available());
- do_print("Request length: " + buf.length);
- // A garbage response. By default this produces NS_CANNOT_CONVERT_DATA as
- // the callback status.
- let blob = "this is not a serialized protocol buffer (the length doesn't match our hard-coded values)";
- // We can't actually parse the protocol buffer here, so just switch on the
- // length instead of inspecting the contents.
- if (buf.length == 67) {
- // evil.com
- blob = createVerdict(true);
- } else if (buf.length == 73) {
- // mozilla.com
- blob = createVerdict(false);
- }
- response.bodyOutputStream.write(blob, blob.length);
- });
-
- gHttpServer.start(4444);
-});
-
-// Construct a response with redirect urls.
-function processUpdateRequest() {
- let response = "n:1000\n";
- for (let table in gTables) {
- response += "i:" + table + "\n";
- for (let i = 0; i < gTables[table].length; ++i) {
- response += "u:" + gTables[table][i] + "\n";
- }
- }
- do_print("Returning update response: " + response);
- return response;
-}
-
-// Set up the local whitelist.
-function waitForUpdates() {
- let deferred = Promise.defer();
- gHttpServer.registerPathHandler("/downloads", function(request, response) {
- let blob = processUpdateRequest();
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(blob, blob.length);
- });
-
- let streamUpdater = Cc["@mozilla.org/url-classifier/streamupdater;1"]
- .getService(Ci.nsIUrlClassifierStreamUpdater);
-
- // Load up some update chunks for the safebrowsing server to serve. This
- // particular chunk contains the hash of whitelisted.com/ and
- // sb-ssl.google.com/safebrowsing/csd/certificate/.
- registerTableUpdate("goog-downloadwhite-digest256", "data/digest.chunk");
-
- // Resolve the promise once processing the updates is complete.
- function updateSuccess(aEvent) {
- // Timeout of n:1000 is constructed in processUpdateRequest above and
- // passed back in the callback in nsIUrlClassifierStreamUpdater on success.
- do_check_eq("1000", aEvent);
- do_print("All data processed");
- deferred.resolve(true);
- }
- // Just throw if we ever get an update or download error.
- function handleError(aEvent) {
- do_throw("We didn't download or update correctly: " + aEvent);
- deferred.reject();
- }
- streamUpdater.downloadUpdates(
- "goog-downloadwhite-digest256",
- "goog-downloadwhite-digest256;\n",
- true,
- "http://localhost:4444/downloads",
- updateSuccess, handleError, handleError);
- return deferred.promise;
-}
-
-function promiseQueryReputation(query, expectedShouldBlock) {
- let deferred = Promise.defer();
- function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_eq(aShouldBlock, expectedShouldBlock);
- deferred.resolve(true);
- }
- gAppRep.queryReputation(query, onComplete);
- return deferred.promise;
-}
-
-add_task(function* ()
-{
- // Wait for Safebrowsing local list updates to complete.
- yield waitForUpdates();
-});
-
-add_task(function* test_blocked_binary()
-{
- // We should reach the remote server for a verdict.
- Services.prefs.setBoolPref(remoteEnabledPref,
- true);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- // evil.com should return a malware verdict from the remote server.
- yield promiseQueryReputation({sourceURI: createURI("http://evil.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12}, true);
-});
-
-add_task(function* test_non_binary()
-{
- // We should not reach the remote server for a verdict for non-binary files.
- Services.prefs.setBoolPref(remoteEnabledPref,
- true);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/throw");
- yield promiseQueryReputation({sourceURI: createURI("http://evil.com"),
- suggestedFileName: "noop.txt",
- fileSize: 12}, false);
-});
-
-add_task(function* test_good_binary()
-{
- // We should reach the remote server for a verdict.
- Services.prefs.setBoolPref(remoteEnabledPref,
- true);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- // mozilla.com should return a not-guilty verdict from the remote server.
- yield promiseQueryReputation({sourceURI: createURI("http://mozilla.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12}, false);
-});
-
-add_task(function* test_disabled()
-{
- // Explicitly disable remote checks
- Services.prefs.setBoolPref(remoteEnabledPref,
- false);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/throw");
- let query = {sourceURI: createURI("http://example.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12};
- let deferred = Promise.defer();
- gAppRep.queryReputation(query,
- function onComplete(aShouldBlock, aStatus) {
- // We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
- do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
- do_check_false(aShouldBlock);
- deferred.resolve(true);
- }
- );
- yield deferred.promise;
-});
-
-add_task(function* test_disabled_through_lists()
-{
- Services.prefs.setBoolPref(remoteEnabledPref,
- false);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- Services.prefs.setCharPref("urlclassifier.downloadBlockTable", "");
- let query = {sourceURI: createURI("http://example.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12};
- let deferred = Promise.defer();
- gAppRep.queryReputation(query,
- function onComplete(aShouldBlock, aStatus) {
- // We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
- do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
- do_check_false(aShouldBlock);
- deferred.resolve(true);
- }
- );
- yield deferred.promise;
-});
-add_task(function* test_teardown()
-{
- gStillRunning = false;
-});
diff --git a/toolkit/components/downloads/test/unit/test_app_rep_windows.js b/toolkit/components/downloads/test/unit/test_app_rep_windows.js
deleted file mode 100644
index 4ff772e61..000000000
--- a/toolkit/components/downloads/test/unit/test_app_rep_windows.js
+++ /dev/null
@@ -1,434 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests signature extraction using Windows Authenticode APIs of
- * downloaded files.
- */
-
-// Globals
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-
-const BackgroundFileSaverOutputStream = Components.Constructor(
- "@mozilla.org/network/background-file-saver;1?mode=outputstream",
- "nsIBackgroundFileSaver");
-
-const StringInputStream = Components.Constructor(
- "@mozilla.org/io/string-input-stream;1",
- "nsIStringInputStream",
- "setData");
-
-const TEST_FILE_NAME_1 = "test-backgroundfilesaver-1.txt";
-
-const gAppRep = Cc["@mozilla.org/downloads/application-reputation-service;1"].
- getService(Ci.nsIApplicationReputationService);
-var gStillRunning = true;
-var gTables = {};
-var gHttpServer = null;
-
-const appRepURLPref = "browser.safebrowsing.downloads.remote.url";
-const remoteEnabledPref = "browser.safebrowsing.downloads.remote.enabled";
-
-/**
- * Returns a reference to a temporary file. If the file is then created, it
- * will be removed when tests in this file finish.
- */
-function getTempFile(aLeafName) {
- let file = FileUtils.getFile("TmpD", [aLeafName]);
- do_register_cleanup(function GTF_cleanup() {
- if (file.exists()) {
- file.remove(false);
- }
- });
- return file;
-}
-
-function readFileToString(aFilename) {
- let f = do_get_file(aFilename);
- let stream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- stream.init(f, -1, 0, 0);
- let buf = NetUtil.readInputStreamToString(stream, stream.available());
- return buf;
-}
-
-/**
- * Waits for the given saver object to complete.
- *
- * @param aSaver
- * The saver, with the output stream or a stream listener implementation.
- * @param aOnTargetChangeFn
- * Optional callback invoked with the target file name when it changes.
- *
- * @return {Promise}
- * @resolves When onSaveComplete is called with a success code.
- * @rejects With an exception, if onSaveComplete is called with a failure code.
- */
-function promiseSaverComplete(aSaver, aOnTargetChangeFn) {
- let deferred = Promise.defer();
- aSaver.observer = {
- onTargetChange: function BFSO_onSaveComplete(unused, aTarget)
- {
- if (aOnTargetChangeFn) {
- aOnTargetChangeFn(aTarget);
- }
- },
- onSaveComplete: function BFSO_onSaveComplete(unused, aStatus)
- {
- if (Components.isSuccessCode(aStatus)) {
- deferred.resolve();
- } else {
- deferred.reject(new Components.Exception("Saver failed.", aStatus));
- }
- },
- };
- return deferred.promise;
-}
-
-/**
- * Feeds a string to a BackgroundFileSaverOutputStream.
- *
- * @param aSourceString
- * The source data to copy.
- * @param aSaverOutputStream
- * The BackgroundFileSaverOutputStream to feed.
- * @param aCloseWhenDone
- * If true, the output stream will be closed when the copy finishes.
- *
- * @return {Promise}
- * @resolves When the copy completes with a success code.
- * @rejects With an exception, if the copy fails.
- */
-function promiseCopyToSaver(aSourceString, aSaverOutputStream, aCloseWhenDone) {
- let deferred = Promise.defer();
- let inputStream = new StringInputStream(aSourceString, aSourceString.length);
- let copier = Cc["@mozilla.org/network/async-stream-copier;1"]
- .createInstance(Ci.nsIAsyncStreamCopier);
- copier.init(inputStream, aSaverOutputStream, null, false, true, 0x8000, true,
- aCloseWhenDone);
- copier.asyncCopy({
- onStartRequest: function () { },
- onStopRequest: function (aRequest, aContext, aStatusCode)
- {
- if (Components.isSuccessCode(aStatusCode)) {
- deferred.resolve();
- } else {
- deferred.reject(new Components.Exception(aResult));
- }
- },
- }, null);
- return deferred.promise;
-}
-
-// Registers a table for which to serve update chunks.
-function registerTableUpdate(aTable, aFilename) {
- // If we haven't been given an update for this table yet, add it to the map
- if (!(aTable in gTables)) {
- gTables[aTable] = [];
- }
-
- // The number of chunks associated with this table.
- let numChunks = gTables[aTable].length + 1;
- let redirectPath = "/" + aTable + "-" + numChunks;
- let redirectUrl = "localhost:4444" + redirectPath;
-
- // Store redirect url for that table so we can return it later when we
- // process an update request.
- gTables[aTable].push(redirectUrl);
-
- gHttpServer.registerPathHandler(redirectPath, function(request, response) {
- do_print("Mock safebrowsing server handling request for " + redirectPath);
- let contents = readFileToString(aFilename);
- do_print("Length of " + aFilename + ": " + contents.length);
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(contents, contents.length);
- });
-}
-
-// Tests
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_setup()
-{
- // Wait 10 minutes, that is half of the external xpcshell timeout.
- do_timeout(10 * 60 * 1000, function() {
- if (gStillRunning) {
- do_throw("Test timed out.");
- }
- });
- // Set up a local HTTP server to return bad verdicts.
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- // Ensure safebrowsing is enabled for this test, even if the app
- // doesn't have it enabled.
- Services.prefs.setBoolPref("browser.safebrowsing.malware.enabled", true);
- Services.prefs.setBoolPref("browser.safebrowsing.downloads.enabled", true);
- // Set block and allow tables explicitly, since the allowlist is normally
- // disabled on comm-central.
- Services.prefs.setCharPref("urlclassifier.downloadBlockTable",
- "goog-badbinurl-shavar");
- Services.prefs.setCharPref("urlclassifier.downloadAllowTable",
- "goog-downloadwhite-digest256");
- // SendRemoteQueryInternal needs locale preference.
- let locale = Services.prefs.getCharPref("general.useragent.locale");
- Services.prefs.setCharPref("general.useragent.locale", "en-US");
-
- do_register_cleanup(function() {
- Services.prefs.clearUserPref("browser.safebrowsing.malware.enabled");
- Services.prefs.clearUserPref("browser.safebrowsing.downloads.enabled");
- Services.prefs.clearUserPref("urlclassifier.downloadBlockTable");
- Services.prefs.clearUserPref("urlclassifier.downloadAllowTable");
- Services.prefs.setCharPref("general.useragent.locale", locale);
- });
-
- gHttpServer = new HttpServer();
- gHttpServer.registerDirectory("/", do_get_cwd());
-
- function createVerdict(aShouldBlock) {
- // We can't programmatically create a protocol buffer here, so just
- // hardcode some already serialized ones.
- let blob = String.fromCharCode(parseInt(0x08, 16));
- if (aShouldBlock) {
- // A safe_browsing::ClientDownloadRequest with a DANGEROUS verdict
- blob += String.fromCharCode(parseInt(0x01, 16));
- } else {
- // A safe_browsing::ClientDownloadRequest with a SAFE verdict
- blob += String.fromCharCode(parseInt(0x00, 16));
- }
- return blob;
- }
-
- gHttpServer.registerPathHandler("/throw", function(request, response) {
- do_throw("We shouldn't be getting here");
- });
-
- gHttpServer.registerPathHandler("/download", function(request, response) {
- do_print("Querying remote server for verdict");
- response.setHeader("Content-Type", "application/octet-stream", false);
- let buf = NetUtil.readInputStreamToString(
- request.bodyInputStream,
- request.bodyInputStream.available());
- do_print("Request length: " + buf.length);
- // A garbage response. By default this produces NS_CANNOT_CONVERT_DATA as
- // the callback status.
- let blob = "this is not a serialized protocol buffer (the length doesn't match our hard-coded values)";
- // We can't actually parse the protocol buffer here, so just switch on the
- // length instead of inspecting the contents.
- if (buf.length == 67) {
- // evil.com
- blob = createVerdict(true);
- } else if (buf.length == 73) {
- // mozilla.com
- blob = createVerdict(false);
- }
- response.bodyOutputStream.write(blob, blob.length);
- });
-
- gHttpServer.start(4444);
-});
-
-// Construct a response with redirect urls.
-function processUpdateRequest() {
- let response = "n:1000\n";
- for (let table in gTables) {
- response += "i:" + table + "\n";
- for (let i = 0; i < gTables[table].length; ++i) {
- response += "u:" + gTables[table][i] + "\n";
- }
- }
- do_print("Returning update response: " + response);
- return response;
-}
-
-// Set up the local whitelist.
-function waitForUpdates() {
- let deferred = Promise.defer();
- gHttpServer.registerPathHandler("/downloads", function(request, response) {
- let blob = processUpdateRequest();
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(blob, blob.length);
- });
-
- let streamUpdater = Cc["@mozilla.org/url-classifier/streamupdater;1"]
- .getService(Ci.nsIUrlClassifierStreamUpdater);
-
- // Load up some update chunks for the safebrowsing server to serve. This
- // particular chunk contains the hash of whitelisted.com/ and
- // sb-ssl.google.com/safebrowsing/csd/certificate/.
- registerTableUpdate("goog-downloadwhite-digest256", "data/digest.chunk");
-
- // Resolve the promise once processing the updates is complete.
- function updateSuccess(aEvent) {
- // Timeout of n:1000 is constructed in processUpdateRequest above and
- // passed back in the callback in nsIUrlClassifierStreamUpdater on success.
- do_check_eq("1000", aEvent);
- do_print("All data processed");
- deferred.resolve(true);
- }
- // Just throw if we ever get an update or download error.
- function handleError(aEvent) {
- do_throw("We didn't download or update correctly: " + aEvent);
- deferred.reject();
- }
- streamUpdater.downloadUpdates(
- "goog-downloadwhite-digest256",
- "goog-downloadwhite-digest256;\n",
- true,
- "http://localhost:4444/downloads",
- updateSuccess, handleError, handleError);
- return deferred.promise;
-}
-
-function promiseQueryReputation(query, expectedShouldBlock) {
- let deferred = Promise.defer();
- function onComplete(aShouldBlock, aStatus) {
- do_check_eq(Cr.NS_OK, aStatus);
- do_check_eq(aShouldBlock, expectedShouldBlock);
- deferred.resolve(true);
- }
- gAppRep.queryReputation(query, onComplete);
- return deferred.promise;
-}
-
-add_task(function* ()
-{
- // Wait for Safebrowsing local list updates to complete.
- yield waitForUpdates();
-});
-
-add_task(function* test_signature_whitelists()
-{
- // We should never get to the remote server.
- Services.prefs.setBoolPref(remoteEnabledPref,
- true);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/throw");
-
- // Use BackgroundFileSaver to extract the signature on Windows.
- let destFile = getTempFile(TEST_FILE_NAME_1);
-
- let data = readFileToString("data/signed_win.exe");
- let saver = new BackgroundFileSaverOutputStream();
- let completionPromise = promiseSaverComplete(saver);
- saver.enableSignatureInfo();
- saver.setTarget(destFile, false);
- yield promiseCopyToSaver(data, saver, true);
-
- saver.finish(Cr.NS_OK);
- yield completionPromise;
-
- // Clean up.
- destFile.remove(false);
-
- // evil.com is not on the allowlist, but this binary is signed by an entity
- // whose certificate information is on the allowlist.
- yield promiseQueryReputation({sourceURI: createURI("http://evil.com"),
- signatureInfo: saver.signatureInfo,
- fileSize: 12}, false);
-});
-
-add_task(function* test_blocked_binary()
-{
- // We should reach the remote server for a verdict.
- Services.prefs.setBoolPref(remoteEnabledPref,
- true);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- // evil.com should return a malware verdict from the remote server.
- yield promiseQueryReputation({sourceURI: createURI("http://evil.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12}, true);
-});
-
-add_task(function* test_non_binary()
-{
- // We should not reach the remote server for a verdict for non-binary files.
- Services.prefs.setBoolPref(remoteEnabledPref,
- true);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/throw");
- yield promiseQueryReputation({sourceURI: createURI("http://evil.com"),
- suggestedFileName: "noop.txt",
- fileSize: 12}, false);
-});
-
-add_task(function* test_good_binary()
-{
- // We should reach the remote server for a verdict.
- Services.prefs.setBoolPref(remoteEnabledPref,
- true);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- // mozilla.com should return a not-guilty verdict from the remote server.
- yield promiseQueryReputation({sourceURI: createURI("http://mozilla.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12}, false);
-});
-
-add_task(function* test_disabled()
-{
- // Explicitly disable remote checks
- Services.prefs.setBoolPref(remoteEnabledPref,
- false);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/throw");
- let query = {sourceURI: createURI("http://example.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12};
- let deferred = Promise.defer();
- gAppRep.queryReputation(query,
- function onComplete(aShouldBlock, aStatus) {
- // We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
- do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
- do_check_false(aShouldBlock);
- deferred.resolve(true);
- }
- );
- yield deferred.promise;
-});
-
-add_task(function* test_disabled_through_lists()
-{
- Services.prefs.setBoolPref(remoteEnabledPref,
- false);
- Services.prefs.setCharPref(appRepURLPref,
- "http://localhost:4444/download");
- Services.prefs.setCharPref("urlclassifier.downloadBlockTable", "");
- let query = {sourceURI: createURI("http://example.com"),
- suggestedFileName: "noop.bat",
- fileSize: 12};
- let deferred = Promise.defer();
- gAppRep.queryReputation(query,
- function onComplete(aShouldBlock, aStatus) {
- // We should be getting NS_ERROR_NOT_AVAILABLE if the service is disabled
- do_check_eq(Cr.NS_ERROR_NOT_AVAILABLE, aStatus);
- do_check_false(aShouldBlock);
- deferred.resolve(true);
- }
- );
- yield deferred.promise;
-});
-add_task(function* test_teardown()
-{
- gStillRunning = false;
-});
diff --git a/toolkit/components/downloads/test/unit/xpcshell.ini b/toolkit/components/downloads/test/unit/xpcshell.ini
deleted file mode 100644
index 68b6e1fc3..000000000
--- a/toolkit/components/downloads/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,14 +0,0 @@
-[DEFAULT]
-head = head_download_manager.js
-tail = tail_download_manager.js
-skip-if = toolkit == 'android'
-support-files =
- data/digest.chunk
- data/block_digest.chunk
- data/signed_win.exe
-
-[test_app_rep.js]
-[test_app_rep_windows.js]
-skip-if = os != "win"
-[test_app_rep_maclinux.js]
-skip-if = os == "win"
diff --git a/toolkit/components/exthelper/moz.build b/toolkit/components/exthelper/moz.build
index 975030a35..d7429e2d5 100644
--- a/toolkit/components/exthelper/moz.build
+++ b/toolkit/components/exthelper/moz.build
@@ -4,9 +4,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPIDL_SOURCES += [
- 'extIApplication.idl',
-]
+XPIDL_SOURCES += ['extIApplication.idl']
XPIDL_MODULE = 'exthelper'
diff --git a/toolkit/components/feeds/moz.build b/toolkit/components/feeds/moz.build
index de5e0aa96..fdc4e2708 100644
--- a/toolkit/components/feeds/moz.build
+++ b/toolkit/components/feeds/moz.build
@@ -4,8 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-MOCHITEST_CHROME_MANIFESTS += ['test/chrome.ini']
-
XPIDL_SOURCES += [
'nsIFeed.idl',
'nsIFeedContainer.idl',
@@ -25,7 +23,3 @@ EXTRA_COMPONENTS += [
'FeedProcessor.js',
'FeedProcessor.manifest',
]
-
-XPCSHELL_TESTS_MANIFESTS += [
- 'test/xpcshell.ini'
-]
diff --git a/toolkit/components/feeds/test/.eslintrc.js b/toolkit/components/feeds/test/.eslintrc.js
deleted file mode 100644
index 89764b551..000000000
--- a/toolkit/components/feeds/test/.eslintrc.js
+++ /dev/null
@@ -1,8 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/chrome.eslintrc.js",
- "../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/feeds/test/chrome.ini b/toolkit/components/feeds/test/chrome.ini
deleted file mode 100644
index 6745fa9a5..000000000
--- a/toolkit/components/feeds/test/chrome.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[test_bug675492.xul]
diff --git a/toolkit/components/feeds/test/head.js b/toolkit/components/feeds/test/head.js
deleted file mode 100644
index 65aa64b94..000000000
--- a/toolkit/components/feeds/test/head.js
+++ /dev/null
@@ -1,80 +0,0 @@
-"use strict";
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/NetUtil.jsm");
-
-function readTestData(testFile) {
- var testcase = {};
-
- // Got a feed file, now we need to parse out the Description and Expect headers.
- var istream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
- try {
- istream.init(testFile, 0x01, parseInt("0444", 8), 0);
- istream.QueryInterface(Ci.nsILineInputStream);
-
- var hasmore = false;
- do {
- var line = {};
- hasmore = istream.readLine(line);
-
- if (line.value.indexOf('Description:') > -1) {
- testcase.desc = line.value.substring(line.value.indexOf(':')+1).trim();
- }
-
- if (line.value.indexOf('Expect:') > -1) {
- testcase.expect = line.value.substring(line.value.indexOf(':')+1).trim();
- }
-
- if (line.value.indexOf('Base:') > -1) {
- testcase.base = NetUtil.newURI(line.value.substring(line.value.indexOf(':')+1).trim());
- }
-
- if (testcase.expect && testcase.desc) {
- testcase.path = 'xml/' + testFile.parent.leafName + '/' + testFile.leafName;
- testcase.file = testFile;
- break;
- }
-
- } while (hasmore);
-
- } catch (e) {
- Assert.ok(false, "FAILED! Error reading testFile case in file " + testFile.leafName + " ---- " + e);
- } finally {
- istream.close();
- }
-
- return testcase;
-}
-
-function iterateDir(dir, recurse, callback) {
- do_print("Iterate " + dir.leafName);
- let entries = dir.directoryEntries;
-
- // Loop over everything in this dir. If its a dir
- while (entries.hasMoreElements()) {
- let entry = entries.getNext();
- entry.QueryInterface(Ci.nsILocalFile);
-
- if (entry.isDirectory()) {
- if (recurse) {
- iterateDir(entry, recurse, callback);
- }
- } else {
- callback(entry);
- }
- }
-}
-
-function isIID(a, iid) {
- try {
- a.QueryInterface(iid);
- return true;
- } catch (e) { }
-
- return false;
-}
diff --git a/toolkit/components/feeds/test/test_bug675492.xul b/toolkit/components/feeds/test/test_bug675492.xul
deleted file mode 100644
index b1c52d11a..000000000
--- a/toolkit/components/feeds/test/test_bug675492.xul
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=675492
--->
-<window title="Mozilla Bug 675492"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript" src="chrome://mochikit/content/chrome-harness.js"/>
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=675492"
- target="_blank">Mozilla Bug 675492</a>
- </body>
-
- <!-- test code goes here -->
- <script type="application/javascript">
- <![CDATA[
-
- /** Test for Bug 675492 **/
-
- Components
- .classes["@mozilla.org/parserutils;1"]
- .getService(Components.interfaces.nsIParserUtils)
- .parseFragment("<p>test</p>", 0, false, null, document.createElementNS("http://www.w3.org/1999/xhtml", "body"));
- ok(true, "No crash!");
- ]]>
- </script>
-</window>
diff --git a/toolkit/components/feeds/test/test_xml.js b/toolkit/components/feeds/test/test_xml.js
deleted file mode 100644
index 5bc0d759d..000000000
--- a/toolkit/components/feeds/test/test_xml.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* test_xml.js
- * This file sets up the unit test environment by building an array of files
- * to be tested. It assumes it lives in a folder adjacent to the a folder
- * called 'xml', where the testcases live.
- *
- * The directory layout looks something like this:
- *
- * tests/test_xml.js*
- * |
- * - head.js
- * |
- * - xml/ -- rss1/...
- * |
- * -- rss2/...
- * |
- * -- atom/testcase.xml
- *
- * To add more tests, just include the file in the xml subfolder and add its name to xpcshell.ini
- */
-
-"use strict";
-
-// Listens to feeds being loaded. Runs the tests built into the feed afterwards to veryify they
-// were parsed correctly.
-function FeedListener(testcase) {
- this.testcase = testcase;
-}
-
-FeedListener.prototype = {
- handleResult: function(result) {
- var feed = result.doc;
- try {
- do_print("Testing feed " + this.testcase.file.path);
- Assert.ok(isIID(feed, Ci.nsIFeed), "Has feed interface");
-
- if (!eval(this.testcase.expect)) {
- Assert.ok(false, "expect failed for " + this.testcase.desc);
- } else {
- Assert.ok(true, "expect passed for " + this.testcase.desc);
- }
- } catch (e) {
- Assert.ok(false, "expect failed for " + this.testcase.desc + " ---- " + e.message);
- }
-
- run_next_test();
- }
-}
-
-function createTest(data) {
- return function() {
- var uri;
-
- if (data.base == null) {
- uri = NetUtil.newURI('http://example.org/' + data.path);
- } else {
- uri = data.base;
- }
-
- do_print("Testing " + data.file.leafName);
-
- var parser = Cc["@mozilla.org/feed-processor;1"].createInstance(Ci.nsIFeedProcessor);
- var stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
- stream.init(data.file, 0x01, parseInt("0444", 8), 0);
- parser.listener = new FeedListener(data);
-
- try {
- parser.parseFromStream(stream, uri);
- } catch (e) {
- Assert.ok(false, "parse failed for " + data.file.leafName + " ---- " + e.message);
- // If the parser failed, the listener won't be notified, run the next test here.
- run_next_test();
- } finally {
- stream.close();
- }
- }
-}
-
-function run_test() {
- // Get the 'xml' directory in here
- var topDir = Services.dirsvc.get("CurWorkD", Ci.nsIFile);
- topDir.append("xml");
-
- // Every file in the test dir contains an encapulated RSS "test". Iterate through
- // them all and add them to the test runner.
- iterateDir(topDir, true, file => {
- var data = readTestData(file);
- add_test(createTest(data));
- });
-
- // Now run!
- run_next_test();
-}
diff --git a/toolkit/components/feeds/test/xml/rfc4287/author_namespaces.xml b/toolkit/components/feeds/test/xml/rfc4287/author_namespaces.xml
deleted file mode 100644
index 3b2ad74ff..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/author_namespaces.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Description: Ensure unknown NS element in atom:author doesn't cause exception
-Expect: var mCService = Components.classes['@mozilla.org/consoleservice;1'].getService(Components.interfaces.nsIConsoleService); var msg = mCService.getMessageArray()[0]; if(msg){msg = msg.message}; ((msg + "").indexOf("prefix has no properties") == -1);
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <author>
- <name>Sam Ruby</name>
- <method xmlns="http://www.intertwingly.net/blog/">excerpt</method>
- <email>rubys@intertwingly.net</email>
- <uri>.</uri>
- </author>
-
-</feed>
-
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_author.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_author.xml
deleted file mode 100644
index 2757148c4..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_author.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author name works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).authors.queryElementAt(0, Components.interfaces.nsIFeedPerson).name=='John Doe Entry';
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- <author>
- <name>John Doe Entry</name>
- </author>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_content.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_content.xml
deleted file mode 100644
index 6bb9b210f..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_content.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry summary works
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).content.plainText() == "test content";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <content>test content</content>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_content_encoded.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_content_encoded.xml
deleted file mode 100644
index df09317f7..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_content_encoded.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry content:encoded and xhtml works
-Expect: var content = feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).content.plainText(); content == "should appear";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux"
- xmlns:content="http://purl.org/rss/1.0/modules/content/">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <summary type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">
- <b>test</b> content
- </div>
- </summary>
- <content:encoded>
- should appear
- </content:encoded>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_content_html.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_content_html.xml
deleted file mode 100644
index 08974c35f..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_content_html.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry content html works
-Expect: var content = feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).content.plainText(); content == "test content";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <content type="html">&lt;b>test&lt;/b> content</content>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml.xml
deleted file mode 100644
index dea4902bb..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry content xhtml works
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).content.plainText() == "test content";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <content type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">
- <b>test</b> content
- </div>
- </content>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml_with_markup.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml_with_markup.xml
deleted file mode 100644
index 8cadef75e..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_content_xhtml_with_markup.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry content xhtml works
-Expect: var content = feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).content.text; content == "<b>test</b> content";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <content type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">
- <b>test</b> content
- </div>
- </content>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_contributor.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_contributor.xml
deleted file mode 100644
index bb85bf230..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_contributor.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author name works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).contributors.queryElementAt(0, Components.interfaces.nsIFeedPerson).name=='John Doe Entry';
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- <contributor>
- <name>John Doe Entry</name>
- </contributor>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_html_cdata.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_html_cdata.xml
deleted file mode 100644
index 38a31ca10..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_html_cdata.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: HTML title w/ CDATA
-Expect: var title = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).title.plainText(); title == "<title>";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<id>http://atomtests.philringnalda.com/tests/item/title/html-cdata.atom</id>
-<title>Atom item title html cdata</title>
-<updated>2005-12-18T00:13:00Z</updated>
-<author>
- <name>Phil Ringnalda</name>
- <uri>http://weblog.philringnalda.com/</uri>
-</author>
-<link rel="self" href="http://atomtests.philringnalda.com/tests/item/title/html-cdata.atom"/>
-<entry>
- <id>http://atomtests.philringnalda.com/tests/item/title/html-cdata.atom/1</id>
- <title type="html"><![CDATA[&lt;title>]]></title>
- <updated>2005-12-18T00:13:00Z</updated>
- <summary>An item with a type="html" title consisting of a less-than
-character, the word 'title' and a greater-than character, where
-the character entity reference for the less-than is escaped by being
-in a CDATA section.</summary>
- <link href="http://atomtests.philringnalda.com/alt/title-title.html"/>
- <category term="item title"/>
-</entry>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_id.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_id.xml
deleted file mode 100644
index 8513b6894..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_id.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry id
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).id == "http://foo.example.com/hmm/ok,2006,07,11";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <id>http://foo.example.com/hmm/ok,2006,07,11</id>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts.xml
deleted file mode 100644
index c7cebe4cd..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with random link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/linktests/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
- <entry>
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/2</id>
- <title>Two alternate links</title>
- <updated>2005-01-18T15:00:02Z</updated>
- <summary>The aggregator should pick either the second or third link below as the alternate</summary>
-
- <link rel="ALTERNATE" href="http://www.snellspace.com/public/linktests/wrong" />
- <link href="http://www.snellspace.com/public/linktests/alternate" />
- <link type="text/plain" href="http://www.snellspace.com/public/linktests/alternate2" />
- <link rel="ALTERNATE" href="http://www.snellspace.com/public/linktests/wrong" />
- </entry>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore.xml
deleted file mode 100644
index 56675b1a9..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with random link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/linktests/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
- <entry>
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/3</id>
- <title>One of each core link rel type</title>
-
- <updated>2005-01-18T15:00:03Z</updated>
- <summary>The aggregator should pick the first link as the alternate</summary>
- <link href="http://www.snellspace.com/public/linktests/alternate" />
- <link rel="enclosure" href="http://www.snellspace.com/public/linktests/enclosure" length="19" />
- <link rel="related" href="http://www.snellspace.com/public/linktests/related" />
- <link rel="self" href="http://www.snellspace.com/public/linktests/self" />
- <link rel="via" href="http://www.snellspace.com/public/linktests/via" />
- </entry>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore2.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore2.xml
deleted file mode 100644
index b5b73cfe0..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_2alts_allcore2.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with random link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/linktests/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
-
-
- <entry>
-
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/4</id>
- <title>One of each core link rel type + An additional alternate link</title>
- <updated>2005-01-18T15:00:04Z</updated>
- <summary>The aggregator should pick either the first or last links as the alternate. First link is likely better.</summary>
- <link href="http://www.snellspace.com/public/linktests/alternate" />
- <link rel="enclosure" href="http://www.snellspace.com/public/linktests/enclosure" length="19" />
- <link rel="related" href="http://www.snellspace.com/public/linktests/related" />
-
- <link rel="self" href="http://www.snellspace.com/public/linktests/self" />
- <link rel="via" href="http://www.snellspace.com/public/linktests/via" />
- <link rel="alternate" type="text/plain" href="http://www.snellspace.com/public/linktests/alternate2" />
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_IANA.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_IANA.xml
deleted file mode 100644
index af6563f2e..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_IANA.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with IANA URI link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
- <entry>
- <id>tag:example.org,2006:/linkreltest/1</id>
- <title>Does your reader support http://www.iana.org/assignments/relation/alternate properly? </title>
- <updated>2006-04-25T12:12:12Z</updated>
- <link rel="http://example.org/random"
- href="http://www.snellspace.com/public/random" />
- <link rel="http://www.iana.org/assignments/relation/alternate"
- href="http://www.snellspace.com/public/alternate" />
- <link rel="http://example.org/random"
- href="http://www.snellspace.com/public/random" />
- <content>This entry uses link/@rel="http://www.iana.org/assignments/relation/alternate".</content>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_alt_extension.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_alt_extension.xml
deleted file mode 100644
index e37421864..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_alt_extension.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with random link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/linktests/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
- <entry>
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/5</id>
- <title>Entry with a link relation registered by an extension</title>
- <updated>2005-01-18T15:00:05Z</updated>
- <summary>The aggregator should ignore the license link without throwing any errors. The first link should be picked as the alternate.</summary>
- <link href="http://www.snellspace.com/public/linktests/alternate" />
- <link rel="payment" href="http://www.example.org/payment" />
- </entry>
-
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure.xml
deleted file mode 100644
index b76c111c9..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item enclosure works
-Expect: var links = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('links'); links.QueryInterface(Components.interfaces.nsIArray); var link = links.queryElementAt(0, Components.interfaces.nsIPropertyBag2); ((link.getProperty('length') == '24986239') && (link.getProperty('type') == 'audio/mpeg') && (link.getProperty('href') == 'http://dallas.example.com/joebob_050689.mp3') && (feed.type == 1) && (feed.enclosureCount == 1));
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
-
-
- <entry>
-
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/4</id>
- <title>One of each core link rel type + An additional alternate link</title>
- <updated>2005-01-18T15:00:04Z</updated>
- <summary>The aggregator should pick either the first or last links as the alternate. First link is likely better.</summary>
- <link rel="enclosure" length="24986239" type="audio/mpeg" href="http://dallas.example.com/joebob_050689.mp3" />
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure_populate_enclosures.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure_populate_enclosures.xml
deleted file mode 100644
index 8453c6e9c..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_enclosure_populate_enclosures.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item enclosure added to enclosures
-Expect: var encs = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).enclosures; encs.QueryInterface(Components.interfaces.nsIArray); var enc = encs.queryElementAt(0, Components.interfaces.nsIPropertyBag2); ((enc.getProperty('length') == '24986239') && (enc.getProperty('type') == 'audio/mpeg') && (enc.getProperty('url') == 'http://dallas.example.com/joebob_050689.mp3'));
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
-
-
- <entry>
-
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/4</id>
- <title>One of each core link rel type + An additional alternate link</title>
- <updated>2005-01-18T15:00:04Z</updated>
- <summary>The aggregator should pick either the first or last links as the alternate. First link is likely better.</summary>
- <link rel="enclosure" length="24986239" type="audio/mpeg" href="http://dallas.example.com/joebob_050689.mp3" />
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_otherURI_alt.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_otherURI_alt.xml
deleted file mode 100644
index 3dc0c8dd6..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_otherURI_alt.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with random link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/linktests/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
- <entry>
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/6</id>
- <title>Entry with a link relation identified by URI</title>
- <updated>2005-01-18T15:00:06Z</updated>
- <summary>The aggregator should ignore the second link without throwing any errors. The first link should be picked as the alternate.</summary>
- <link href="http://www.snellspace.com/public/linktests/alternate" />
- <link rel="http://example.org" href="http://www.snellspace.com/public/linktests/example" />
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_payment_alt.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_payment_alt.xml
deleted file mode 100644
index 51e1524b4..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_payment_alt.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with random link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/linktests/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
-
- <entry>
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/5</id>
- <title>Entry with a link relation registered by an extension</title>
- <updated>2005-01-18T15:00:05Z</updated>
- <summary>The aggregator should ignore the license link without throwing any errors. The first link should be picked as the alternate.</summary>
- <link href="http://www.snellspace.com/public/linktests/alternate" />
- <link rel="payment" href="http://www.example.org/payment" />
- </entry>
-
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_link_random.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_link_random.xml
deleted file mode 100644
index cb370e516..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_link_random.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with random link relations
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.snellspace.com/public/linktests/alternate";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-01-18T15:10:00Z</updated>
- <author><name>James Snell</name></author>
- <link href="http://www.intertwingly.net/wiki/pie/LinkConformanceTests" />
- <link rel="self" href="http://www.snellspace.com/public/linktests.xml" />
-
- <entry>
- <id>tag:snellspace.com,2006:/atom/conformance/linktest/1</id>
- <title>Just a single Alternate Link</title>
- <updated>2005-01-18T15:00:01Z</updated>
- <summary>The aggregator should pick the second link as the alternate</summary>
- <link rel="http://example.org/random"
- href="http://www.snellspace.com/public/wrong" />
- <link href="http://www.snellspace.com/public/linktests/alternate" />
- <link rel="http://example.org/random"
- href="http://www.snellspace.com/public/wrong" />
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_published.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_published.xml
deleted file mode 100644
index 1112729e2..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_published.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom published works
-Expect: var entry = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry); entry.published == 'Tue, 09 Dec 2003 18:30:02 GMT'
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <published>2003-12-09T18:30:02Z</published>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_rights_normalized.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_rights_normalized.xml
deleted file mode 100644
index 1474e5f84..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_rights_normalized.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry rights works normalized
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).rights.plainText() == "test rights"
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <entry>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> rights</div>
- </rights>
- </entry>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_summary.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_summary.xml
deleted file mode 100644
index b245cb380..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_summary.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry summary xhtml works
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).summary.plainText() == "test summary";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux"
- xmlns:content="http://purl.org/rss/1.0/modules/content/">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <summary type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">
- <b>test</b> summary
- </div>
- </summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_title.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_title.xml
deleted file mode 100644
index c118e7472..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_title.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom feed and entry with random attributes works
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).title.text == "test";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
-
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_title_normalized.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_title_normalized.xml
deleted file mode 100644
index 19e2ac1a6..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_title_normalized.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry title normalized
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).title.text == "test";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
-
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_updated.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_updated.xml
deleted file mode 100644
index 4aed7e9c7..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_updated.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom updated works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).updated == 'Sat, 13 Dec 2003 18:30:02 GMT'
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_w_content_encoded.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_w_content_encoded.xml
deleted file mode 100644
index 58f94c6c1..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_w_content_encoded.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry content:encoded and xhtml works
-Expect: var content = feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).content.text; content == "<b>test</b> content";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux"
- xmlns:content="http://purl.org/rss/1.0/modules/content/">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
-
- <entry></entry>
-
- <entry foo:bar="baz">
- <title>test</title>
- <content type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">
- <b>test</b> content
- </div>
- </content>
- <content:encoded>
- shouldn't appear
- </content:encoded>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_xhtml_baseURI_with_amp.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_xhtml_baseURI_with_amp.xml
deleted file mode 100644
index 20819cecd..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_xhtml_baseURI_with_amp.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry content xhtml works with a base URI that contains an ampersand.
-Base: http://www.travellerspoint.com/photo_gallery_feed.cfm?tags=Canada&onlyShowFeatured=true
-Expect: var frag = null; var content = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).content; var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"].createInstance(Components.interfaces.nsIDOMParser); var doc = parser.parseFromString("<div/>", "text/xml"); frag = content.createDocumentFragment(doc.documentElement); notEqual(frag, null, "frag is not null"); true;
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
- <entry foo:bar="baz">
- <title>test</title>
- <content type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">
- <b>test</b> content
- </div>
- </content>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase.xml
deleted file mode 100644
index 1656e2174..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with xml:base
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.example.org/foo";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <id>tag:example.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-06-18T6:23:00Z</updated>
- <link href="http://www.example.org" />
-
- <entry xml:base="http://www.example.org">
- <id>tag:example.org,2006:/linkreltest/1</id>
- <title>Does your reader support xml:base properly? </title>
- <updated>2006-06-23T12:12:12Z</updated>
- <link href="foo"/>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase_on_link.xml b/toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase_on_link.xml
deleted file mode 100644
index 0ead14255..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/entry_xmlBase_on_link.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry with xml:base
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == "http://www.example.org/bar/foo";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <id>tag:example.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-06-18T16:13:00Z</updated>
- <link href="http://www.example.org" />
-
- <entry xml:base="http://www.example.org">
- <id>tag:example.org,2006:/linkreltest/1</id>
- <title>Does your reader support xml:base properly? </title>
- <updated>2006-06-23T12:12:12Z</updated>
- <link xml:base="/bar/" href="foo"/>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_atom_rights_xhtml.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_atom_rights_xhtml.xml
deleted file mode 100644
index 83add3265..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_atom_rights_xhtml.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom rights works with HTML
-Expect: feed.fields.getProperty('atom:rights') != null
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
- <summary type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><div><div>test</div> summary</div></div>
- </summary>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_author.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_author.xml
deleted file mode 100644
index 790027ee3..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_author.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author count works
-Expect: feed.authors.length == 1;
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<title>test title</title>
-<author>
-</author>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_author2.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_author2.xml
deleted file mode 100644
index eae8292fa..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_author2.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author count works
-Expect: feed.authors.length == 2
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<title>test title</title>
-<author>
-</author>
-<author>
-</author>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_author_email.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_author_email.xml
deleted file mode 100644
index 95abdbc8e..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_author_email.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author name works
-Expect: feed.authors.queryElementAt(0, Components.interfaces.nsIFeedPerson).email=='hmm@example.com';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<title>test title</title>
-<author>
-<email>hmm@example.com</email>
-<name>foo</name>
-</author>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_author_email_2.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_author_email_2.xml
deleted file mode 100644
index 71cace773..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_author_email_2.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author name works
-Expect: feed.authors.queryElementAt(1, Components.interfaces.nsIFeedPerson).email=='bar@example.com';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<title>test title</title>
-<author>
-<email>hmm@example.com</email>
-<name>foo</name>
-</author>
-<author>
-<email>bar@example.com</email>
-<name>foo</name>
-</author>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_author_name.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_author_name.xml
deleted file mode 100644
index 2df46f8d5..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_author_name.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author name works
-Expect: feed.authors.queryElementAt(0, Components.interfaces.nsIFeedPerson).name=='foo';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<title>test title</title>
-<author>
-<name>foo</name>
-</author>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_author_surrounded.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_author_surrounded.xml
deleted file mode 100644
index b15278f91..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_author_surrounded.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author name works
-Expect: feed.authors.queryElementAt(0, Components.interfaces.nsIFeedPerson).name=='John Doe';
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_author_uri.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_author_uri.xml
deleted file mode 100644
index 44149036c..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_author_uri.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author uri works
-Expect: feed.authors.queryElementAt(1, Components.interfaces.nsIFeedPerson).uri.spec =='http://example.com/';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<title>test title</title>
-<author>
-<email>hmm@example.com</email>
-<name>foo</name>
-<uri>http://example.org</uri>
-</author>
-<author>
-<email>bar@example.com</email>
-<name>foo</name>
-<uri>http://example.com/</uri>
-</author>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_comment_rss_extra_att.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_comment_rss_extra_att.xml
deleted file mode 100644
index 795d3f6ad..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_comment_rss_extra_att.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: wfw works with extra attribute
-Expect: feed.fields.getProperty('wfw:commentRss') == 'http://example.org'
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://example.org"
- xmlns:bla="http://wellformedweb.org/CommentAPI/">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id foo:bar="baz">urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
- <bla:commentRss hmm="yeah">http://example.org</bla:commentRss>
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_contributor.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_contributor.xml
deleted file mode 100644
index abb50c154..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_contributor.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom contributor uri works
-Expect: feed.contributors.queryElementAt(1, Components.interfaces.nsIFeedPerson).uri.spec=='http://example.com/';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title>test title</title>
- <contributor>
- <email>hmm@example.com</email>
- <name>foo</name>
- <uri>http://example.org</uri>
- </contributor>
- <contributor>
- <email>bar@example.com</email>
- <name>foo</name>
- <uri>http://example.com</uri>
- </contributor>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_entry_count.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_entry_count.xml
deleted file mode 100644
index 53028d3d1..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_entry_count.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom entry count works
-Expect: feed.items.length == 3
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title>test title</title>
- <logo>http://example.org/logo.jpg</logo>
- <entry></entry>
- <entry></entry>
- <entry></entry>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_generator.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_generator.xml
deleted file mode 100644
index 5112775b9..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_generator.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom generator works
-Expect: feed.generator.agent == 'Hmm';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-
-<author>
-<email>hmm@example.com</email>
-<name>foo</name>
-</author>
-
-
- <generator>Hmm</generator>
-
-<author>
-<email>bar@example.com</email>
-<name>foo</name>
-</author>
-
-
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
- <summary type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><div><div>test</div> summary</div></div>
- </summary>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri.xml
deleted file mode 100644
index a4b8c735c..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom generator works
-Expect: feed.generator.uri.spec == 'http://example.org/';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-
-<author>
-<email>hmm@example.com</email>
-<name>foo</name>
-</author>
-
-
- <generator uri="http://example.org">Hmm</generator>
-
-<author>
-<email>bar@example.com</email>
-<name>foo</name>
-</author>
-
-
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
- <summary type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><div><div>test</div> summary</div></div>
- </summary>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri_xmlbase.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri_xmlbase.xml
deleted file mode 100644
index 54191b50e..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_generator_uri_xmlbase.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom generator works
-Expect: feed.generator.uri.spec == 'http://example.org/gen/';
-
--->
-<feed xml:base="http://example.org/" xmlns="http://www.w3.org/2005/Atom">
-
-<author>
-<email>hmm@example.com</email>
-<name>foo</name>
-</author>
-
-
- <generator uri="/gen/">Hmm</generator>
-
-<author>
-<email>bar@example.com</email>
-<name>foo</name>
-</author>
-
-
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
- <summary type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><div><div>test</div> summary</div></div>
- </summary>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_generator_version.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_generator_version.xml
deleted file mode 100644
index 845ce7504..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_generator_version.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom generator works
-Expect: feed.generator.version == "1.1"
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-
-<author>
-<email>hmm@example.com</email>
-<name>foo</name>
-</author>
-
-
- <generator version="1.1" uri="http://example.org">Hmm</generator>
-
-<author>
-<email>bar@example.com</email>
-<name>foo</name>
-</author>
-
-
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
- <summary type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><div><div>test</div> summary</div></div>
- </summary>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_icon.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_icon.xml
deleted file mode 100644
index 017aafbad..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_icon.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom icon works
-Expect: feed.fields.getProperty('atom:icon') == 'http://example.org/favicon.ico'
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title>test title</title>
- <icon>http://example.org/favicon.ico</icon>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_id.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_id.xml
deleted file mode 100644
index 6c538e801..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_id.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom author name works
-Expect: feed.fields.getProperty('atom:id') == 'urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6' && feed.id == 'urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6'
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_id_extra_att.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_id_extra_att.xml
deleted file mode 100644
index ef718463b..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_id_extra_att.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom feed id works with extra attribute
-Expect: feed.fields.getProperty('atom:id') == 'urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6'
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://example.org">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id foo:bar="baz">urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_logo.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_logo.xml
deleted file mode 100644
index 2a90fe22b..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_logo.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom logo works
-Expect: feed.image.getProperty('url') == 'http://example.org/logo.jpg'
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title>test title</title>
- <logo xml:base="http://example.org/">logo.jpg</logo>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_random_attributes_on_feed_and_entry.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_random_attributes_on_feed_and_entry.xml
deleted file mode 100644
index a4c5633e2..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_random_attributes_on_feed_and_entry.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom feed and entry with random attributes works
-Expect: feed.title.text == "hmm" && feed.items.length == 2
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xmlns:foo="http://www.example.org"
- foo:quux="quuux">
-
- <title>hmm</title>
-
- <author>
- <email>hmm@example.com</email>
- <name>foo</name>
- </author>
- <generator version="1.1" uri="http://example.org">Hmm</generator>
- <author>
- <email>bar@example.com</email>
- <name>foo</name>
- </author>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><i>test</i> rights</div>
- </rights>
-
- <entry foo:bar="baz"></entry>
- <entry></entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_rights_normalized.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_rights_normalized.xml
deleted file mode 100644
index b7ef46047..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_rights_normalized.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom rights works normalized
-Expect: feed.rights.plainText() == "test rights"
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> rights</div>
- </rights>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml.xml
deleted file mode 100644
index 422c6fb49..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom rights works
-Expect: feed.fields.getProperty('atom:rights') != null
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> rights</div>
- </rights>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml_nested_divs.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml_nested_divs.xml
deleted file mode 100644
index ebad24ac3..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_rights_xhtml_nested_divs.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom rights works with nested divs
-Expect: feed.fields.getProperty('atom:rights') != null
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
- <rights type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><div><div>test</div> rights</div></div>
- </rights>
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_subtitle.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_subtitle.xml
deleted file mode 100644
index 096061399..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_subtitle.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom subtitle works
-Expect: var sub = feed.subtitle.text; sub == '<b>test</b> subtitle';
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <subtitle type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> subtitle</div>
- </subtitle>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_tantek_title.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_tantek_title.xml
deleted file mode 100644
index cba9a4918..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_tantek_title.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-Description: XHTML title with apos
-Expect: feed.title.plainText() == "Tantek's Updates"
--->
-<feed xml:lang="en-US"
- xmlns="http://www.w3.org/2005/Atom">
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">Tantek's Updates</div>
- </title>
- <link href="http://tantek.com/"
- rel="alternate" title="Tantek's Posts" type="text/html"/>
- <link href="http://tantek.com/updates.atom"
- rel="self" />
- <id>http://tantek.com/updates.atom</id>
- <author>
- <name>Tantek</name>
- <uri>http://tantek.com/</uri>
- </author>
- <updated>2006-05-02T20:13:00-07:00</updated>
- <entry>
- <updated>2006-04-22T00:00:00-07:00</updated>
- <published>2006-04-22T00:00:00-07:00</published>
- <link href="http://www.makezine.com/faire/"
- rel="alternate" title="Make Faire" type="text/html"/>
- <id>http://www.makezine.com/faire/</id>
- <title>Make Faire</title>
- <content type="xhtml" xml:space="preserve">
- <div xmlns="http://www.w3.org/1999/xhtml">
- <div class="vevent">
- <a class="url" href="http://www.makezine.com/faire/">
- <abbr class="dtstart" title="20060422">
- 4/22</abbr>-<abbr class="dtend" title="20060424">23</abbr>
-
- <span class="summary">
- Make Faire
- </span> @
- <span class="location">
- San Mateo Fairgrounds
- </span>
- </a>
- </div>
- </div>
- </content>
- </entry>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_title.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_title.xml
deleted file mode 100644
index 6e0cea003..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_title.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom title works
-Expect: feed.title.text == 'test title'
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<title>test title</title>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_title_full_feed.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_title_full_feed.xml
deleted file mode 100644
index cef3f84a3..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_title_full_feed.xml
+++ /dev/null
@@ -1,936 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!--
-Description: Feed title works with full entry
-Expect: feed.title.text == 'ongoing'
--->
-<feed xmlns='http://www.w3.org/2005/Atom'
- xml:base='http://www.tbray.org/ongoing/ongoing.atom'
- xml:lang='en-us'>
- <title>ongoing</title>
- <id>http://www.tbray.org/ongoing/</id>
- <link href='./' />
- <link rel='self' href='' />
- <logo>rsslogo.jpg</logo>
- <icon>/favicon.ico</icon>
- <updated>2006-04-26T20:10:25-08:00</updated>
- <author><name>Tim Bray</name></author>
- <subtitle>ongoing fragmented essay by Tim Bray</subtitle>
- <rights>All content written by Tim Bray and photos by Tim Bray Copyright Tim Bray, some rights reserved, see /ongoing/misc/Copyright</rights>
- <generator uri='/misc/Colophon'>Generated from XML source code using Perl, Expat, XML::Parser, Emacs, Mysql, and ImageMagick. Industrial strength technology, baby.</generator>
-
-<entry xml:base='When/200x/2006/04/26/'>
- <title>Spring in White on White</title>
- <link href='Spring-in-White-on-White' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/26/Spring-in-White-on-White</id>
- <published>2006-04-26T13:00:00-08:00</published>
- <updated>2006-04-26T20:10:16-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts/Photos' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Photos' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Garden' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Garden' />
- <summary type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>Most people would generally prefer a climate where it&#x2019;s bright and warm most of the time. But for Canadians and others who live where it&#x2019;s not, there are compensations, and one is the experience of spring. I have a picture.</div></summary>
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Most people would generally prefer a climate where it’s bright
-and warm most of the time. But for Canadians and others who live where it’s
-not, there are compensations, and one is the experience of
-spring. I have a picture.</p>
-<img src="IMGP3247.png" alt="Pear blossoms against cherry blossoms" />
-<div class="caption"><p>The blossoms are pear in the foreground, cherry behind.</p></div>
-<p>After all the months of 50° North Latitude winter—icy-sharp in most
-of Canada, wet and dark here in Vancouver—the soul, the spirit, and the
-libido all spring to life when the sun comes back. We’ve had a solid year of
-crappy weather, but this last Saturday through Monday were solidly summery,
-bright
-and warm; and in this season the days are already long and each gets
-longer so fast you can feel it.</p>
-<p>On the back porch, our pear tree’s branches were silhouetted against the
-neighbors’ big wild old cherry; the cherry yields no edible fruit but who
-cares, it’s beautiful
-tree any time of year.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/26/'>
- <title>Scott</title>
- <link href='Scott' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/26/Scott</id>
- <published>2006-04-26T13:00:00-08:00</published>
- <updated>2006-04-26T20:06:50-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Business/Sun' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Business' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Sun' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>I’ve been watching our internal leadership conference and spending quite a
-bit of time talking in the virtual hallways, and I’ve been surprised at
-the intensity of feeling about Mr. McNealy. Yes, there are those
-here saying “About bloody time, now we can make some progress” but there’s a
-much bigger group that is genuinely emotional about this transition.
-Maybe it’s a function of seniority: I never met nor corresponded with Scott, and
-he hasn’t been
-much of a presence in the company’s conversation in the time I’ve been here.
-But there are a lot of smart, seasoned, unsentimental people making it clear
-that
-he’s been a major force in their lives, at a more personal level than I’m
-used to hearing when people speak about executives. I guess also that to a
-lot of people, Sun’s vision, for which Scott gets some of the credit, was a
-radical and wonderful thing. I first used Unix in 1979 and quit a nice
-big-company job
-to become a VAX-bsd sysadmin in 1983, so I’ve always kind of
-lived inside that vision.
-But I’ll tell you one thing, what I’ve been hearing the last couple of days
-makes me really regret that I didn’t get to know Scott.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/26/'>
- <title>Jacobs, Pictures, Spartans</title>
- <link href='Jane-Jacobs' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/26/Jane-Jacobs</id>
- <published>2006-04-26T13:00:00-08:00</published>
- <updated>2006-04-26T17:28:59-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts/Photos' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Photos' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p><a href="http://en.wikipedia.org/wiki/Jane_Jacobs">Jane Jacobs</a> died;
-the city I live in, Vancouver, is pretty solidly Jacobsian both in its current
-shape and its planning dogma. By choosing to live here I’m empirically a
-fan. Oddly, few have remarked how great Jacobs
-<em>looked</em>; her face commanded the eye. Which leads me Alex
-Waterhouse-Hayward’s wonderful
-<a href="http://www.alexwaterhousehayward.com/blog/2006/04/jane-jacobs-viveca-lindfors_26.html">Jane Jacobs &amp; Viveca Lindfors</a>;
-surprising portraits and thoughts on decoration. W-H’s blog has become one of
-only two or three that I
-stab at excitedly whenever I see something new. For example, see
-<a href="http://www.alexwaterhousehayward.com/blog/archives/2006_04_01_archive.html#114476408248660848">Sex Crimes, Homicide and Drugs</a>
-and yes, that’s what it’s about.
-Staying with the death-and-betrayal theme, and apparently (but not really)
-shifting back 2&#xbd; millennia, see John Cowan’s
-<a href="http://recycledknowledge.blogspot.com/2006/04/war-after-simonides.html">The
-War (after Simonides)</a>, being careful to look closely at the links.
-I’ve
-<a href="http://www.tbray.org/ongoing/When/200x/2003/03/24/Herodotus">written</a>
-about those same wars.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/25/'>
- <title>LAMP and MARS</title>
- <link href='Scaling-Rails' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/25/Scaling-Rails</id>
- <published>2006-04-25T13:00:00-08:00</published>
- <updated>2006-04-26T07:24:06-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Web' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Web' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Sun' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Sun' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>At
-<a href="/ongoing/When/200x/2006/04/13/RoR">that Rails conference</a>, when I
-was
-<a href="http://blog.garbledygook.com/2006/04/17/ruby-on-rails-podcast-tim-bray-ruby-on-rails-podcast/">talking</a>
-to
-<a href="http://jroller.com/page/obie">Obie Fernandez</a>, he asked, more or
-less “How can Sun love us? We’re not Java” and I said, more or less, “Hey,
-you’re programmers, you write software and there have to be computers to run
-it, we sell computers, why wouldn’t we love you?” Anyhow, we touched on
-parallelism a bit and I talked up the
-<a href="http://www.sun.com/processors/UltraSPARC-T1/">T1</a>;
-Obie took that ball and
-<a href="http://jroller.com/page/obie?entry=will_ultrasparc_t1_emerge_as">ran with it</a>,
-saying all sorts of positive things about synergy between Rails’
-shared-nothing architecture and our multicore systems. Yeah, well, good in
-theory, but I’m too old to make that kind of prediction without running some
-tests. Hah, it turns out that
-<a href="http://joyent.com/">Joyent</a> has been
-<a href="http://scalewithrails.com/">doing that</a>, and have
-<a href="http://scalewithrails.com/downloads/ScaleWithRails-April2006.pdf">76
-PDF slides</a> on the subject.
-If you care about big-system scaling issues, read the whole thing; a little
-long, but amusing and with hardly any bullet lists. If you’re a Sun
-shareholder looking for a pick-me up, check out slides 40-41, 49, and 52-74.
-Oh, I gather that the T1, Solaris, and ZFS are OK for Java too.
-<i>[Update: The title was just “SAMR”, as in LAMP with two new letters.
-Enough people didn’t get it that I was forced to think about it, and MARS
-works better anyhow.]</i></p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/25/'>
- <title>Real-Time Journalism</title>
- <link href='Talk-With-Berlind' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/25/Talk-With-Berlind</id>
- <published>2006-04-25T13:00:00-08:00</published>
- <updated>2006-04-26T06:40:19-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Journalism' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Journalism' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Syndication' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Syndication' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>I got email late yesterday from
-<a href="http://blogs.zdnet.com/bio.php#berlind">David Berlind</a>: “Hey, can
-I call you for a minute?” He wanted commentary on
-<a href="http://blogs.zdnet.com/BTL/?p=2906">a story he was writing</a> that I
-think is about the potential for intellectual-property lock-ins on RSS and Atom
-extensions. I say “I think is about” because the headline is “Will or could
-RSS get forked?”. After a few minutes’ chat, David asked if he could record
-for a podcast, and even though I only had a cellphone, the audio came out OK.
-The conversation was rhythmic: David brought up a succession of potential
-issues and answered each along the lines of “Yes, it’s reasonable to worry
-about that, but in this
-case I don’t see any particular problems.”
-Plus I emitted a mercifully-brief rant on the difference between protocols,
-data, and software.
-On the one hand, I thought David could have been a
-little clearer that I was pushing back against the thrust of his story, but on
-the other hand he included the whole conversation right
-there in the piece, so anyone who actually cares can listen and find out what
-I actually said, not what I think I said nor what David reported I said.
-I find this raw barely-intermediated journalism (we
-talk on the phone this afternoon, it’s on the Web in hours) a little
-shocking still.
-On balance, it’s better than the way we used to do things.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/24/'>
- <title>The Transition Explained</title>
- <link href='CEO-Transition' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/24/CEO-Transition</id>
- <published>2006-04-24T13:00:00-08:00</published>
- <updated>2006-04-24T16:49:05-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Business/Sun' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Business' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Sun' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>It’s not that complicated, really.
-Bloggers are
-<a href="http://www.sun.com/2006-0418/js/index.jsp">taking over the world</a>.
-Resistance is futile; you will be assimilated.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/24/'>
- <title>5&#x272d;&#x266b;: One More Cup of Coffee</title>
- <link href='One-More-Cup-Of-Coffee' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/24/One-More-Cup-Of-Coffee</id>
- <published>2006-04-24T13:00:00-08:00</published>
- <updated>2006-04-24T13:00:00-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts/Music/Recordings' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Music' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Recordings' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts/Music/5 Stars' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='5 Stars' />
- <summary type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>I&#x2019;m not really a <a href='http://en.wikipedia.org/wiki/Bob_Dylan'>Bob Dylan</a> fan. A voice like that, and a tunesmithing talent like that, come along only a few times per century, but he&#x2019;s still kind of irritating. That aside, the song <cite>One More Cup of Coffee</cite>, from the 1976 album <a href='http://en.wikipedia.org/wiki/Desire_%28album%29'>Desire</a>, can&#x2019;t be ignored; wonderful tune, wonderful orchestration, wonderful performance. <i>(&#x201c;5&#x272d;&#x266b;&#x201d; series introduction <a href='/ongoing/When/200x/2006/01/23/5-Star-Music'>here</a>; with <a href='/ongoing/When/200x/2006/01/23/5-Star-Music#p-1'>an explanation</a> of why the title may look broken.)</i></div></summary>
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>I’m not really a
-<a href="http://en.wikipedia.org/wiki/Bob_Dylan">Bob Dylan</a> fan. A voice
-like that, and a tunesmithing talent like that, come along only a few times
-per century, but he’s still kind of irritating.
-That aside, the song <cite>One More Cup of Coffee</cite>, from the 1976 album
-<a href="http://en.wikipedia.org/wiki/Desire_%28album%29">Desire</a>, can’t be
-ignored; wonderful tune, wonderful orchestration, wonderful performance.
-<i>(“5✭♫” series introduction <a href="/ongoing/When/200x/2006/01/23/5-Star-Music">here</a>;
-with <a href="/ongoing/When/200x/2006/01/23/5-Star-Music#p-1">an
-explanation</a> of why the title may look broken.)</i></p>
-<img src="Desire.png" class="inline" alt="Desire, by Bob Dylan" />
-<h2 id='p-1'>The Context</h2>
-<p>Nothing I can possibly write will add any wisdom to the
-millions of words, some 90% of them in excess of needs, written on the subject
-of this particular person.</p>
-<p>A personal statement: Bob Dylan has long irritated me for, during the first
-thirty years or
-so of his career, never having given a straight answer to a straight question,
-and for writing songs with dozens of boring verses. But they’ll still be
-listening
-to lots of his performances long after I’m dead, and in recent years he’s
-become a better, more direct, interview.</p>
-<p>My taste in Dylan is a little unusual: once you get past <cite>One More Cup
-of Coffee</cite>, my favorites would be <cite>Baby Let Me Follow You
-Down</cite> (from the <cite>Last Waltz</cite> soundtrack) and
-<cite>Crash on the Levee (Down in the Flood)</cite> from
-<a href="http://en.wikipedia.org/wiki/The_Basement_Tapes">The Basement
-Tapes</a>.</p>
-<p><cite>Desire</cite>, the record, is hit and miss. <cite>Joey</cite>,
-glorification of the life of some mafioso, is flawed in concept
-and unlistenable in execution. <cite>Hurricane</cite>, whatever you think
-about
-<a href="http://en.wikipedia.org/wiki/Rubin_Carter">Mr. Carter</a>, that song
-rocks; and <cite>Isis</cite> hits pretty hard too.</p>
-<h2 id='p-2'>The Music</h2>
-<p>Is there anything in <cite>One More Cup of Coffee</cite> that’s not
-perfect? Well yes, in the verses, the
-lyrics on occasion drag (“He oversees his kingdom / So no stranger does
-intrude / His voice it trembles as he calls out / For another plate of food”).
-But apart from that, the sentiment is compelling,
-<a href="http://en.wikipedia.org/wiki/Scarlet_Rivera">Scarlet Rivera’s</a>
-violin is beautifully scored and played, the tune is to die for, and the
-backing vocals are by Emmylou Harris, who you can bet is going to be here in
-the 5-✭ series one of these days.
-And while there’s not much middle ground on the subject of Dylan’s singing, if
-you like it, you’ll <em>really</em> like this song.</p>
-<p>Listen to the choruses: Bob and Emmylou veer wildly around the rhythm, then
-coalesce on the beat when it matters, and they’re making it
-up as they go along, they’re wholly inhabiting the moment, and it’s
-quite, quite perfect.</p>
-<h2 id='p-3'>Sampling It</h2>
-<p>Oh yeah, it’s out there. And there’s a live version too; but the smart
-thing would be to go buy the un-compressed un-DRM’ed shiny round silver
-version of <cite>Desire</cite>; it’s a keeper.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/24/'>
- <title>Atomic Monday</title>
- <link href='Atomic-Monday' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/24/Atomic-Monday</id>
- <published>2006-04-24T13:00:00-08:00</published>
- <updated>2006-04-24T00:44:06-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Syndication' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Syndication' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Atom' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Atom' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>First of all, implementors of anything Atom-related need to spend some time
-<a href="http://golem.ph.utexas.edu/~distler/blog/archives/000793.html">chez
-Jacques Distler</a>; in particular, the conversation that plays out in the
-comments. Second, there’s this piece of software called
-<a href="http://www.planetplanet.org/">Planet Planet</a> that allows you to
-make an aggregate web page by reading lots of feeds; for example, see
-<a href="http://www.planetapache.org/">Planet Apache</a> or
-<a href="http://planetsun.org/">Planet Sun</a>.
-Sam Ruby decided that its Atom support needed some work, so
-<a href="http://www.intertwingly.net/blog/2006/04/23/Adding-Atom-support-to-PlanetPlanet">he did
-it</a>. Now, here’s the exciting part: he pinged me over the weekend and said
-“Hey, look at this” wanting to show me his cleverly-Atomized
-Planet Intertwingly feed.
-I looked at it in
-<a href="http://ranchero.com/netnewswire/">NetNewsWire</a> and was puzzled for
-a moment; some but not all of the
-things in the feed were highlighted as unread, even though this was the first
-time I’d seen it. Then the light went on.
-This
-is Atom doing <em>exactly what we went to all that trouble to make it do</em>.
-NetNewsWire has good Atom support and, because Atom entries all have unique
-IDs and timestamps, it can
-tell that it’s seen lots of those entries before in other feeds that I
-subscribe to. That’s how I found Jacques’ piece. This is huge; anyone who
-uses synthetic or aggregated feeds knows that dupes are a big problem, showing
-up all over the place.
-No longer, Atom makes that problem go away.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/22/'>
- <title>Hyatt on the High-Res Web</title>
- <link href='High-Res-Web' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/22/High-Res-Web</id>
- <published>2006-04-22T13:00:00-08:00</published>
- <updated>2006-04-23T17:12:18-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Web' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Web' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Presentation' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Presentation' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Check out Dave Hyatt’s
-<a href="http://webkit.opendarwin.org/blog/?p=55">excellent write-up</a> on
-designing and rendering Web pages so they take advantage of the
-higher-resolution screens that <em>may</em> be coming our way.
-I emphasize “may” because I’ve seen how slowly we’ve picked up pixels over
-the years. The first really substantial screen I ever worked on was a
-1988-vintage Sun workstation with about a million pixels. The Mac on my
-lap right now, which has 125 times as much memory as that workstation, has
-only 1.38 million pixels.
-Anyhow, Hyatt has some smart things to say on the issues,
-which are trickier than you might think. I suspect that sometime in a couple of
-years, if I still care about <span class='o'>ongoing</span>, I’m going to
-have to go back and reprocess all the images so that higher-res versions are
-available for those who have the screens and don’t mind downloading bigger
-files.
-Anyhow, Dave’s piece may be slightly misleading in that he talks about SVG
-as though
-it’s something coming in the future. Not so, check out
-<a href="http://zcorpan.1go.dk/sandbox/svg/atom/.xml">this nifty SVG Atom
-logo</a>, which works fine in all the Mozilla browsers I have here.
-Load it up, resize the window, and watch what happens. Then do a “view
-source”.
-<i>[Update:
-<a href="http://blog.codedread.com">Jeff Schiller</a> writes to tell me that
-Opera 9 does SVG (and Opera 8 “SVG Tiny”) too.]
-[<a href="http://www.freeke.org/ffg">Dave Walker</a> writes: Though the shipping version of Safari doesn’t support SVG,
-<a href="http://nightly.webkit.org/builds/Latest-WebKit-SVN.dmg">the
-nightlies</a> do.]
-[<a href="http://www.davelemen.com/archives/2006/04/is_it_time_for_jpeg_2000_to_go_mainstream.html">Dave Lemen</a>
-points to
-<a href="http://en.wikipedia.org/wiki/JPEG-2000">JPEG 2000</a> as possibly
-useful in a high-res context.]</i></p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/23/'>
- <title>Wrong About the Infield Fly Rule</title>
- <link href='Wrong-About-the-Infield-Fly-Rule' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/23/Wrong-About-the-Infield-Fly-Rule</id>
- <published>2006-04-23T13:00:00-08:00</published>
- <updated>2006-04-23T15:02:41-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Family' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Family' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>My brother
-<a href="http://takingalongview.blogspot.com/">Rob</a> is really taking to
-this blogging medium. Check out his recent
-<a href="http://takingalongview.blogspot.com/2006/04/credo.html">Credo</a>,
-and also the only instance I’ve seen of
-<a href="http://takingalongview.blogspot.com/2006/04/ode-to-96-chevy-lumina.html">Anglo-Saxon alliterative poetry</a>
-applied to a mini-van.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2004/12/12/'>
- <title>Statistics</title>
- <link href='BMS' />
- <id>http://www.tbray.org/ongoing/When/200x/2004/12/12/BMS</id>
- <published>2004-12-12T12:00:00-08:00</published>
- <updated>2006-04-23T10:10:02-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Publishing' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Publishing' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Web' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Web' />
- <summary type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>Almost every Sunday I grab the week&#x2019;s <span class="o">ongoing</span> logfiles and update my numbers. I find it interesting and maybe others will too, so this entry is now the charts&#x2019; permanent home. I&#x2019;ll update it most weeks, probably. <i>[Updated: 2006/04/23.]</i></div></summary>
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Almost every Sunday I grab the week’s <span class='o'>ongoing</span>
-logfiles and update my numbers.
-I find it interesting
-and maybe others will too, so
-this entry is now the charts’ permanent home. I’ll update it most weeks,
-probably.
-<i>[Updated: 2006/04/23.]</i></p>
-<img src="Browser-Market-Share.png" alt="Browser market shares at ‘ongoing’" />
-<div class="caption"><p>Browsers visiting <span class='o'>ongoing</span>,
-percent.</p></div>
-<img src="Browsers-via-search.png" alt="Browser market shares at ‘ongoing’, visitors via search engines" />
-<div class="caption"><p>Browsers visiting <span class='o'>ongoing</span> via
-search engines, percent.</p></div>
-<img src="Search-Engines.png" alt="Search engine market shares at ‘ongoing’" />
-<div class="caption"><p>Search referrals to <span
-class='o'>ongoing</span> .</p></div>
-<img src="Feeds.png" alt="RSS and Atom feed fetches" />
-<div class="caption"><p>Fetches of the RSS 2.0 and Atom 1.0 feeds.</p></div>
-<p>The notes on usage and source code will return in coming weeks when I get
-the cycles to rewrite this whole article.</p>
-<h2 id='p-1'>What a “Hit” Means</h2>
-<p>I recently
-<a href="/ongoing/When/200x/2006/02/07/Thumbnail">updated</a> the
-<a href="/ongoing/misc/Colophon"><span class='o'>ongoing</span> software</a>
-(but haven’t updated the Colophon I see, oops).
-Anyhow, the <code>XMLHttpRequest</code> now issued by each page seems to be a
-pretty reliable counter of the number of actual browsers with humans behind
-them reading the pages. I checked against
-<a href="/ongoing/When/200x/2005/12/04/Google-Analytics">Google Analytics</a>
-and the numbers agreed to within a dozen or two on days with 5,000 to 10,000
-page views; interestingly, Google Analytics was always 10 or 20 views
-higher.</p>
-<p>Anyhow, do <em>not</em> conclude that now I know how many people are
-reading whatever it is I write here; because I publish lots of short pieces
-that are all there in my RSS feed, and anyone reading my Atom feed gets the
-full content of everything.
-I and I have <em>no #&amp;*!$ idea</em> how many people look at my feeds.</p>
-<p>By the way, this was the first time in weeks and weeks that I’d looked at the
-Analytics numbers, and they showed almost exactly zero change from the report
-linked above. So I’m going to turn them off; they’re a little too intrusive
-and I think may be slowing page loads.</p>
-<p>Anyhow, I ran some detailed statistics on the traffic for Wednesday,
-February 8th, 2006.</p>
-<table cellspacing="3" cellpadding="2" class="wltable">
-<tr valign="top"><td>Total connections to the server</td><td align="right">180,428</td></tr>
-<tr valign="top"><td>Total successful GET transactions</td><td align="right">155,507</td></tr>
-<tr valign="top"><td>Total fetches of the RSS and Atom feeds</td><td align="right">88,450</td></tr>
-<tr valign="top"><td>Total GET transactions that actually fetched data (i.e. status code
-200 as opposed to 304)</td><td align="right">87,271</td></tr>
-<tr valign="top"><td>Total GETs of actual ongoing pages (i.e. not CSS, js, or
-images)</td><td align="right">18,444</td></tr>
-<tr valign="top"><td>Actual human page-views</td><td align="right">6,348</td>
-</tr>
-</table>
-<p>So, there you have it. Doing a bit of rounding, if you take the 180K
-transactions and subtract the 90K feed fetches and the 6000 actual human page
-views, you’re left with 84,000 or so “Web overhead” transactions, mostly
-stylesheets and graphics and so on.
-For every human who viewed a page, it was fetched almost twice again by
-various kinds of robots and non-browser automated agents.</p>
-<p>It’s amazing that the whole thing works at all.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/18/'>
- <title>XML Automaton</title>
- <link href='XML-Grammar' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/18/XML-Grammar</id>
- <published>2006-04-18T13:00:00-08:00</published>
- <updated>2006-04-23T08:25:56-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/XML' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='XML' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Coding' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Coding' />
- <summary type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>In December of 1996 I released a piece of software called <a href='http://www.textuality.com/Lark/'>Lark</a>, which was the world&#x2019;s first <a href='http://www.w3.org/TR/REC-xml/#dt-xml-proc'>XML Processor</a> (as the term is defined in the <a href='http://www.w3.org/TR/REC-xml/'>XML Specification</a>). It was successful, but I stopped maintaining it in 1998 because lots of other smart people, and some big companies like Microsoft, were shipping perfectly good processors. I never <em>quite</em> open-sourced it, holding back one clever bit in the moronic idea that I could make money out of Lark somehow. The magic sauce is a finite state machine that can be used to parse XML 1.0. Recently, someone out there needed one of those, so I thought I&#x2019;d publish it, with some commentary on Lark&#x2019;s construction and an amusing anecdote about the name. I doubt there are more than twelve people on the planet who care about this kind of parsing arcana. <i>[Rick Jelliffe <a href='http://www.oreillynet.com/xml/blog/2006/04/xml_in_xml.html'>has upgraded</a> the machine].</i></div></summary>
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>In December of 1996 I released a piece of software called
-<a href="http://www.textuality.com/Lark/">Lark</a>, which was
-the world’s first
-<a href="http://www.w3.org/TR/REC-xml/#dt-xml-proc">XML Processor</a> (as the
-term is defined in the
-<a href="http://www.w3.org/TR/REC-xml/">XML Specification</a>).
-It was successful, but I stopped maintaining it in 1998 because lots of other
-smart people, and some big companies like Microsoft, were shipping perfectly
-good processors. I never <em>quite</em> open-sourced it, holding back one
-clever bit in the moronic idea that I could make money out of Lark somehow.
-The magic sauce is a finite state machine that can be used to parse XML 1.0.
-Recently, someone out there needed one of those, so I thought I’d publish
-it, with some commentary on Lark’s construction and an amusing anecdote about
-the name.
-I doubt there are more than twelve people on the planet who care about
-this kind of parsing arcana.
-<i>[Rick Jelliffe
-<a href="http://www.oreillynet.com/xml/blog/2006/04/xml_in_xml.html">has
-upgraded</a> the machine].</i></p>
-<h2 id='p-1'>Why “Lark”?</h2>
-<p><a href="http://www.laurenwood.org/anyway/">Lauren</a> and I went to
-Australia in late 1996 to visit her mother and to get married, which we
-did on November 30th. Forty-eight hours later, Lauren twisted her knee
-badly enough that she was pretty well
-confined to a sofa for the rest of our Australian vacation.</p>
-<p>So I broke out my computer and finished the work I’d already started on my
-XML processor, and decided to call it Lark for <b>La</b>uren’s <b>R</b>ight
-<b>K</b>nee.</p>
-<h2 id='p-2'>How Lark Worked</h2>
-<p>Lark was a pure
-<a href="http://en.wikipedia.org/wiki/Deterministic_finite_state_machine">deterministic
-finite automaton</a> (DFA)
-parser, with a little teeny state stack.
-Some of its transitions were labeled with named “events” that would provoke
-the parser to do something if, for example, it had just recognized a start tag
-or whatever.</p>
-<p>DFA-driven parsers are a common enough design pattern, although I think
-Lark is the only example in the XML space.
-There are well-known parser generators such as
-<a href="http://en.wikipedia.org/wiki/Yacc">yacc</a>,
-<a href="http://en.wikipedia.org/wiki/GNU_bison">GNU bison</a>, and
-<a href="https://javacc.dev.java.net/">javacc</a>,
-usually used in combination with lexical scanners such as
-<a href="http://en.wikipedia.org/wiki/Flex_lexical_analyser">flex</a> so that
-you can write your grammar in terms of tokens not characters.
-Also, they handle LALR langauges, so the parsing technique is quite a bit
-richer than a pure state machine.</p>
-<p>I thought I had a better idea. The grammar of XML is simple
-enough, and the syntax characters few enough, that I thought I could just
-write down the state machine by hand.
-So that’s what I did, inventing a special-purpose DFA-description
-language for the purpose.</p>
-<p>Then I had a file called <code>Lark.jin</code> which was really a Java
-program that used the state machine to parse XML. The transition “events”
-in the machine were mapped to <code>case</code> labels in a huge
-<code>switch</code> construct. Then there was a horrible, <em>horrible</em>
-Perl program that read the <code>Lark.jin</code> and the automaton,
-generated the DFA tables in Java syntax, inserted them into the code and
-produced <code>Lark.java</code>, which you actually compiled
-to make the parser.</p>
-<p>So while Java doesn’t have a preprocessor, Lark did, which made quite a few
-things easier.</p>
-<p>There were a lot of tricks; some of the state transitions
-weren’t on characters, they were on XML character classes such as
-<code>NameChar</code> and so on.
-This made the automaton easier to write, and in fact, to keep the class files
-small, the character-class transitions persisted into the Java form, and the
-real DFA was built at startup time.
-These days, quick startup might be more important than <code>.class</code>
-file size.</p>
-<h2 id='p-3'>What Was Good</h2>
-<p>It was <em>damn</em> fast. James Clark managed to hand-craft a
-Java-language XML parser called
-<a href="http://jclark.com/xml/xp/index.html">XP</a> that was a little faster
-than Lark, but he did that by clever I/O buffering, and I was determined to
-leapfrog him by improving my I/O.</p>
-<p>This was before the time of standardized XML APIs, but Lark had a stream API
-that influenced SAX, and a DOM-like tree API; both worked just fine.
-Lark is one of very few parsers ever to have survived the
-<a href="http://www.securityfocus.com/archive/1/303509/2002-12-13/2002-12-19/0">billion
-laughs attack</a>.</p>
-<p>Lark was put into production in quite a few deployments, and the flow of
-bug reports slowed to a trickle.
-Then in 1998 I noticed that IBM and Microsoft and BEA and everyone else
-were building XML Processors, so I decided that it wasn’t worthwhile
-maintaining mine.</p>
-<h2 id='p-4'>What Was Bad</h2>
-<p>I never got around to teaching it namespaces, which means it wouldn’t be
-real useful today.</p>
-<p>It had one serious bug that would have been real work to fix and since
-nobody ever encountered it in practice, I kept putting it off and never did.
-If you had an internal parsed entity reference in an attribute value and the
-replacement text included the attribute delimiter (<code>'</code> or
-<code>"</code>), it would scream and claim you had a busted XML document.</p>
-<h2 id='p-5'>That Automaton</h2>
-<p>What happened was,
-<a href="http://www.oreillynet.com/pub/au/1712">Rick Jelliffe</a>, who is a
-Good Person, was
-<a href="http://www.stylusstudio.com/xmldev/200604/post30110.html">looking for
-a FSM for XML</a> and I eventually noticed, and so I sent him mine.</p>
-<p>There’s no reason whatsoever to keep it a secret:
-<a href="/ongoing/code/lark/com/textuality/autom.txt">here it is</a>.
-Be warned: it’s ugly.</p>
-<p>Fortunately, there were only 227 states and 8732 transitions, so the state
-number fit into a
-byte; that and the associated event index pack into a short.
-To make things even tighter, the transitions were only keyed by characters up
-to 127, as in 7-bit ASCII.
-Characters higher than that can’t be XML syntax characters, so we’re only
-interested whether they fall into classes like <code>NameChar</code> and
-<code>NameStartChar</code> and so on. A 64K <code>byte[]</code> array takes
-care of that, each byte having a class bitmask.</p>
-<p>As a result of all this jiggery-pokery, the DFA ends up, believe it
-or not, constituting a <code>short[227][128]</code>.</p>
-<p>Here’s a typical chunk of the automaton:</p>
-<pre><code>1. # in Start tag GI
-2. State StagGI BustedMarkup {in element type}
-3. T $NameC StagGI
-4. T $S InStag !EndGI
-5. T > InDoc !EndGI !ReportSTag
-6. T / EmptyClose !EndGI</code></pre>
-<p>This state, called <code>StagGI</code>, is the state where we’re actually
-reading the name of a tag, we got here by seeing a <code>&lt;</code> followed
-by a <code>NameStart</code> character.<br/>
-Line 1 is a comment.<br/>
-In line 2 we name the state, and support error reporting, providing the name
-of another state to fall back into in case of error, and in the curly braces,
-some text to help build an error message.<br/>
-Line 3 says that if we see a valid XML Name character, we just stay in this
-state.<br/>
-Line 4 says that if we see an XML space character, we move to state
-<code>InStag</code> and process an <code>EndGI</code> event, which would stash
-the characters in the start tag.<br/>And so on.</p>
-<h2 id='p-6'>Other Hackery</h2>
-<p>An early cut of Lark used String and StringBuffer objects to hold all the
-bits and pieces of the XML. This might be a viable strategy today, but in
-1996’s Java it was painfully slow.
-So the code goes to heroic lengths to live in the land of character arrays at
-all times, making Strings only when a client program asks for one through the
-API. The performance difference was mind-boggling.</p>
-<h2 id='p-7'>An Evil Idea</h2>
-<p>If you look at the automaton, and the Lark code, at least half—I’d bet
-three quarters—is there to deal with parsing the DTD and then dealing with
-entity wrangling.
-A whole bunch more is there to support DOM-building and walking.</p>
-<p>I bet if I went through and simply removed support for anything coming out
-of the <code>&lt;!DOCTYPE></code>, including all entity processing,
-then discarded
-the DOM stuff, then added namespace support and SAX and StAX APIs, it would be
-less than half its current size.
-Then if I reworked the I/O, knowing what I know now and stealing some tricks
-that James Clark uses in
-<a href="http://expat.sourceforge.net/">expat</a>, I bet it would
-be the fastest Java XML parser on the planet for XML docs without a
-DOCTYPE; by a wide margin. It’s hard to beat a DFA.</p>
-<p>And it would still be fully XML 1.0 compliant. Because (snicker) this is
-Java, and your basic core Java now includes an XML parser, so I could simply
-instrument Larkette to buffer the prologue and if it saw a DOCTYPE with an
-internal subset, defer to Java’s built-in parser.</p>
-<p>I’ll probably never do it. But the thought brings a smile to my face.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/22/'>
- <title>Just A Kid</title>
- <link href='Just-a-Kid' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/22/Just-a-Kid</id>
- <published>2006-04-22T13:00:00-08:00</published>
- <updated>2006-04-22T13:37:58-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Food and Drink' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Food and Drink' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Last weekend, Lauren felt like cooking up home-made Easter eggs, so
-the shopping list included “chocolate chips (large bag)”. I was heading down
-the bulk-foods aisle and realized one of the vertical acrylic bins was full of
-them. Someone had been sloppy, and there was a little heap of chocolate chips
-on the shelf underneath it. For a second, I flashed into pure eight-year-old
-mode, thinking “Holy cow, there’s a <em>whole bin</em> full of chocolate
-chips, and more just lying there!” I popped a few in my mouth and they were
-excellent; semi-sweet, dark, strong, and firm. I was still in the state that
-Buddhists don’t mean when they say “Child’s Mind”, thinking “I
-can get as many as I want!” The list did say “large bag” after all, so I put
-a bag under the spout and gleefully jammed the lever <em>all the way
-over</em>. At home, Lauren said “You went overboard, a bit, didn’t you?”
-and now we have a plastic canister-full in the pantry which should last us
-into 2007. It’s a good feeling.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/22/'>
- <title>Goddess</title>
- <link href='Goddess' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/22/Goddess</id>
- <published>2006-04-22T13:00:00-08:00</published>
- <updated>2006-04-22T12:25:59-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Family' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Family' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Microsoft' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Microsoft' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>That would be my wife
-<a href="http://www.laurenwood.org/anyway/">Lauren</a>. After
-<a href="/ongoing/When/200x/2006/04/16/Mad-at-Microsoft">I b0rked</a> our
-Win2K gamebox, I tried re-installing the OS and eventually reduced it to
-complete brick-ness, it recognized neither the video adapter nor the network
-card. So Lauren brushed me aside and started wrestling with the problem, and
-to make a long story short, it almost completely works again. At one point
-she seemed nearly infinite in her capabilities, sitting in front of the
-computer wrangling software updates while knitting baby stuff and looking up
-words in a German dictionary for the kid’s homework. Some of the German nouns
-and muttered curses at the Windows install sounded remarkably like each other.
-Why would anyone not marry a geek? The only problem is that Win2K won’t
-auto-switch resolutions to play games any more, it gets the frequency wrong
-and the LCD goes pear-shaped, you have to hand-select the frequency and
-switch into the right resolution first. LazyWeb?</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/21/'>
- <title>Routing Around Spotlight</title>
- <link href='Routing-Around-Spotlight' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/21/Routing-Around-Spotlight</id>
- <published>2006-04-21T13:00:00-08:00</published>
- <updated>2006-04-21T23:16:25-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Mac OS X/Gripes' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Mac OS X' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Gripes' />
- <summary type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>Herewith two hideously ugly little shell scripts for use when Spotlight refuses to search your mail. Spotlight is a flawed v1.0 implementation of a really good idea and will, I&#x2019;m sure, be debugged in a near-future release. <i>[Update: The LazyWeb is educating me... these are moving targets.]</i></div></summary>
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Herewith two hideously ugly little shell scripts for use when Spotlight
-refuses to search your mail.
-Spotlight is a flawed v1.0 implementation of a really good idea and will, I’m
-sure, be debugged in a near-future release.
-<i>[Update: The LazyWeb is educating me... these are moving targets.]</i></p>
-<p>My problem is that whereas Mail.app will search my To/From/Subject
-lines (slowly, and with a
-<a href="/ongoing/When/200x/2005/11/20/UnTiger">really irritating GUI</a>),
-the “Entire Message” option just doesn’t work, it returns instantly with no
-results. Yes, I’ve read the hints about making Spotlight re-index,
-but it just flatly refuses to work for me. Mind you, I have a lot of
-email, but still, it should at least try.</p>
-<p>It turns out I had never really figured out the <code>-print0</code> and
-<code>-0</code> idioms that a lot of the shell-command stalwarts now have.
-Thanks to Malcolm Tredinnick for raising my consciousness.</p>
-<p>This lives in <code>$HOME/bin</code> under the name
-<code>mailgrep</code>:</p>
-<pre><code>#!/bin/sh
-find $HOME/Library/Mail/IMAP* -name '*.emlx' -print0 | \
- xargs -0 fgrep -i $@</code></pre>
-<p>Isn’t <code>xargs</code> a funny command? I’ve discovered that it’s nearly
-impossible to describe what does, and then why what it does is necessary, but
-there are just a whole bunch of places where you’d be lost without it.</p>
-<p>This lives in <code>$HOME/bin/mailview</code>:</p>
-<pre><code>#!/bin/sh
-find $HOME/Library/Mail/IMAP* -name '*.emlx' -print0 | \
- xargs -0 fgrep -i -l -Z $@ | \
- xargs -0 open</code></pre>
-<p>The first cut of this dodged <code>xargs</code> and used an
-incredibly-inefficient and slow chain of <code>-exec</code> arguments to open
-the files one at a time with
-<code>view</code> (aka <code>vim</code>), to work around
-a well-known <code>vim</code> misfeature; it complained about the input
-not being a terminal and left my Terminal.app keystrokes borked.</p>
-<p>But Malcolm, confirming my belief in the broken-ness of <code>vim</code>,
-said “Oh, *that* ‘view’. I thought it was some sexy Mac ‘view my email’ app”.
-D’oh, of course; the magic OS X <code>open</code> command does just the right
-thing.
-Erm, you might want to run <code>mailgrep</code> before you run
-<code>mailview</code>; I’m not sure what would happen if you asked OS X to
-open three or four thousand email messages at once.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/21/'>
- <title>FSS: Pink Flowers</title>
- <link href='Dracon-Help' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/21/Dracon-Help</id>
- <published>2006-04-21T13:00:00-08:00</published>
- <updated>2006-04-21T17:19:27-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts/Photos' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Photos' />
- <summary type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>Friday Slide Scan #28 is two Eighties florals, one interior, one exterior. With a confession.</div></summary>
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Friday Slide Scan #28 is two Eighties florals, one interior, one
-exterior. With a confession.</p>
-<p>First some spring flowers fallen from a tree, just as now in our front
-yard, at dusk.</p>
-<img src="0506.png" alt="Fallen pink treeflowers on grass at dusk" />
-<p>I’m not sure what these are, but look at the light in the center. Rewards
-enlarging.</p>
-<img src="0713.png" alt="Flowers in shadow with light in background" />
-<p>Here’s the confession. Sometimes on Fridays when I’m feeling kinda
-burned-out, I knock off work and do these slide scans in the office, because
-this is where I have the
-<a href="http://www.tbray.org/ongoing/When/200x/2004/04/14/MineIsBigger">big
-screen</a>.
-Blowing these pictures up to mega-huge, picking away at the old-slide crud and
-scanning artifacts, tinkering with the colour balance, and listening; I never
-play music while I’m writing or coding seriously, but I play it real loud while
-photo-editing. It’s all pretty well pure pleasure; you just can’t imagine
-how good that second one above looks at near-native size.
-It reconstitutes the part of my mind that I earn my living with; that’s my
-story and I’m sticking to it.</p>
-<p>Images in the Friday Slide Scans are from 35mm slides taken between 1953
-and 2003 by (in rough chronological order)
-<a href="http://www.textuality.com/BillBray/">Bill Bray</a>,
-<a href="/ongoing/When/200x/2004/08/11/MomsGarden">Jean Bray</a>, Tim Bray, Cath
-Bray, and
-<a href="http://www.laurenwood.org/anyway/">Lauren Wood</a>; when I know
-exactly who took one, I’ll say; in this case, at least one is by Cath Bray.
-Most but not all of the slides were on Kodachrome; they were digitized using
-a Nikon CoolScan 4000 ED scanner and cleaned up by a combination of the Nikon
-scanning software and PhotoShop Elements.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/20/'>
- <title>Spring Pix</title>
- <link href='Spring-Pix' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/20/Spring-Pix</id>
- <published>2006-04-20T13:00:00-08:00</published>
- <updated>2006-04-20T23:07:10-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Places/Vancouver' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Places' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Vancouver' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts/Photos' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Arts' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Photos' />
- <summary type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>Three pictures around Vancouver; one of a fresh green springtime tree, two of rotten old buildings being torn down.</div></summary>
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Three pictures around Vancouver; one of a fresh green springtime tree, two
-of rotten old buildings being torn down.</p>
-<p>There’s nothing quite as fresh as just-sprouted deciduous leaves;
-another few weeks and this tree will be just a tree.</p>
-<img src="IMG_4656.png" alt="Sunlit fresh young leaves" />
-<p>I have a thing about demolition.
-The first is a rotten dingy old one-story on Main Street near 23rd, the second
-is an unlovely grey mid-rise being torn down to build still more condos at
-Homer and Helmcken.</p>
-<img src="IMG_4665.png" alt="Demolition site on Main Street, Vancouver" />
-<img src="IMG_4671.png" alt="Demolition site at Homer and Helmcken, Vancouver" />
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/20/'>
- <title>Totten&#x2019;s Trip</title>
- <link href='Totten-on-Iraq' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/20/Totten-on-Iraq</id>
- <published>2006-04-20T13:00:00-08:00</published>
- <updated>2006-04-20T21:05:22-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Places/Middle East' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Places' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Middle East' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p><a href="http://www.michaeltotten.com/">Michael J. Totten</a> is a
-journalist and blogger who’s back and forth to the
-Middle East and writes about it, quite well in my opinion; he supports this by
-freelancing and with his blog’s tip jar. He gets lots of
-link love from the right-wing blogosphere, which is puzzling because Totten is
-balanced and clear-eyed and doesn’t seem to have any particular axe to grind.
-Recently, he and a friend were
-<a href="http://www.michaeltotten.com/archives/001117.html">having fun in
-Istanbul</a> and, on a random drive out into the country, decided on impulse to
-keep going, all the way across Turkey and into Iraq; into the Kurdish
-mini-state in Iraq’s north, to
-be precise. It makes a heck of a story, with lots of pictures, in six parts:
-<a href="http://www.michaeltotten.com/archives/001119.html">I</a>,
-<a href="http://www.michaeltotten.com/archives/001120.html">II</a>,
-<a href="http://www.michaeltotten.com/archives/001121.html">III</a>,
-<a href="http://www.michaeltotten.com/archives/001124.html">IV</a>,
-<a href="http://www.michaeltotten.com/archives/001126.html">V</a>, and
-<a href="http://www.michaeltotten.com/archives/001127.html">VI</a>.
-</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/19/'>
- <title>The Cost of AJAX</title>
- <link href='The-Cost-of-AJAX' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/19/The-Cost-of-AJAX</id>
- <published>2006-04-19T13:00:00-08:00</published>
- <updated>2006-04-20T00:37:46-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology/Web' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Technology' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Web' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>James Governor
-<a href="http://www.redmonk.com/jgovernor/archives/001526.html">relays a
-question</a> that sounds important
-but I think is actively dangerous: do AJAX apps present more of
-a server-side load? The question is dangerous because it’s meaningless and
-unanswerable. Your typical Web page will, in the process of
-loading, call back to the server for a bunch of stylesheets and graphics and
-scripts and so on: for example, this <span class='o'>ongoing</span> page calls
-out to three different graphics, one stylesheet, and one JavaScript file.
-It also has one “AJAXy” XMLHttpRequest call.
-From the server’s point of view, those are all just requests to dereference
-one URI or another. In the case
-of <span class='o'>ongoing</span>, the AJAX request is for a static file less
-than 200 bytes in size (i.e. cheap).
-On the other hand, it could have been for something that required a
-complex outer join on two ten-million-row tables (i.e. <em>very</em>
-expensive). And one of the virtues of
-the Web Architecture is that it hides those differences, the “U” in URI stands
-for “Uniform”, it’s a Uniform interface to a resource on the Web that could
-be, well, anything.
-So saying “AJAX is expensive” (or that it’s cheap) is like saying “A mountain
-bike is slower than a battle tank” (or that it’s faster).
-The truth depends on what you’re doing with it.
-In the case of web sites, it depends on how many fetches you do and
-where you have to go to get the data to satisfy them.
-<span class='o'>ongoing</span> is a pretty quick web site, even though it runs
-on a fairly modest server, but
-that has nothing to do with AJAX-or-not; it’s because of the particular way
-I’ve set up the Web resources that make the pages here.
-I’ve
-<a href="/ongoing/When/200x/2006/02/14/AJAX-Performance">argued elsewhere</a>
-that AJAX can be a performance win, system-wide; but that argument too is
-contingent on context, lots of context.</p>
-</div></content></entry>
-
-<entry xml:base='When/200x/2006/04/18/'>
- <title>Hao Wu and Graham McMynn</title>
- <link href='Hao-Wu' />
- <id>http://www.tbray.org/ongoing/When/200x/2006/04/18/Hao-Wu</id>
- <published>2006-04-18T13:00:00-08:00</published>
- <updated>2006-04-18T22:00:40-08:00</updated>
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Places/China' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Places' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='China' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='The World/Politics' />
- <category scheme='http://www.tbray.org/ongoing/What/' term='Politics' />
-<content type='xhtml'><div xmlns='http://www.w3.org/1999/xhtml'>
-<p>Graham McMynn is a teenager who was kidnapped in Vancouver on April 4th and
-freed, in a large, noisy, and
-<a href="http://www.cbc.ca/story/news/national/2006/04/12/bcabduction060412.html">newsworthy</a>
-police operation, on April 12th.
-<a href="http://en.wikipedia.org/wiki/Hao_Wu">Hao Wu</a> is a Chinese
-film-maker and
-<a href="http://beijingorbust.blogspot.com/">blogger</a> who was kidnapped in
-Beijing on February 22nd in a
-small, quiet police operation not intended to be newsworthy, and who has not
-been freed.
-Read about it
-<a href="http://spaces.msn.com/wuhaofamily/">here</a>,
-<a href="http://ethanzuckerman.com/haowu/">here</a>, and
-<a href="http://rconversation.blogs.com/rconversation/freehaowu/index.html">here</a>.
-Making noise about it <em>might</em> influence the government of China to
-moderate its actions against Mr. Wu, and can’t do any harm.
-Mr. McMynn’s kidnappers were a gaggle of small-time hoodlums, one of whom was
-out on bail while awaiting trial for another kidnapping (!).
-Mr. Wu’s were police.
-In a civilized country, the function of the police force is to deter such
-people and arrest them. A nation where they are the same people? Nobody
-could call it “civilized”.</p>
-</div></content></entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml.xml
deleted file mode 100644
index 0b4d21b96..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom title works
-Expect: feed.title.plainText() == 'test title'
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml"><b>test</b> title</div>
- </title>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml_entities.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml_entities.xml
deleted file mode 100644
index aaf982acf..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_title_xhtml_entities.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom summary with entities works
-Expect: feed.subtitle.text == '&quot;test&quot; &amp; &apos;title&apos; &amp; &lt;ok&gt;'
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-<subtitle type="xhtml">
- <div xmlns="http://www.w3.org/1999/xhtml">
- "test&quot; &amp; &apos;title' &amp; &lt;ok>
- </div>
-</subtitle>
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_updated.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_updated.xml
deleted file mode 100644
index f425674f2..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_updated.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: raw atom updated works
-Expect: feed.fields.getProperty('atom:updated') == '2003-12-13T18:30:02Z'
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_updated_invalid.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_updated_invalid.xml
deleted file mode 100644
index 560d756b9..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_updated_invalid.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: non-date atom updated should produce null feed.updated
-Expect: feed.updated == null
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003I'mNotADate</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_updated_normalized.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_updated_normalized.xml
deleted file mode 100644
index 71fa1d03d..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_updated_normalized.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom updated works
-Expect: feed.updated == 'Sat, 13 Dec 2003 18:30:02 GMT'
-
--->
-
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_version.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_version.xml
deleted file mode 100644
index a703f506f..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_version.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 Version works
-Expect: result.version == 'atom'
--->
-<feed xmlns="http://www.w3.org/2005/Atom">
-
-</feed> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rfc4287/feed_xmlBase.xml b/toolkit/components/feeds/test/xml/rfc4287/feed_xmlBase.xml
deleted file mode 100644
index d5760e333..000000000
--- a/toolkit/components/feeds/test/xml/rfc4287/feed_xmlBase.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: atom feed with xml:base
-Expect: feed.link.spec == "http://www.example.com/foo/bar/baz";
-
--->
-<feed xmlns="http://www.w3.org/2005/Atom"
- xml:base="http://www.example.com/foo/bar/">
-
- <id>tag:example.com,2006:/atom/conformance/linktest/</id>
- <title>Atom Link Tests</title>
- <updated>2005-06-18T16:13:00Z</updated>
- <link href="baz" />
-
- <entry xml:base="http://www.example.org">
- <id>tag:example.org,2006:/linkreltest/1</id>
- <title>Does your reader support xml:base properly? </title>
- <updated>2006-06-23T12:12:12Z</updated>
- <link xml:base="/bar/" href="foo"/>
- </entry>
-
-</feed>
diff --git a/toolkit/components/feeds/test/xml/rss09x/rss090.xml b/toolkit/components/feeds/test/xml/rss09x/rss090.xml
deleted file mode 100644
index 783c018f4..000000000
--- a/toolkit/components/feeds/test/xml/rss09x/rss090.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0"?>
-<!--
-
-Description: RSS 0.90 works
-Expect: feed.title.plainText() == "Mozilla Dot Org" && result.version == "rss090"
-
--->
-<!-- The very first RSS file, circa 1999 -->
-<rdf:RDF
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-xmlns="http://my.netscape.com/rdf/simple/0.9/">
-
- <channel>
- <title>Mozilla Dot Org</title>
- <link>http://www.mozilla.org</link>
- <description>the Mozilla Organization web site</description>
- </channel>
-
- <image>
- <title>Mozilla</title>
- <url>http://www.mozilla.org/images/moz.gif</url>
- <link>http://www.mozilla.org</link>
- </image>
-
- <item>
- <title>New Status Updates</title>
- <link>http://www.mozilla.org/status/</link>
- </item>
-
- <item>
- <title>Bugzilla Reorganized</title>
- <link>http://www.mozilla.org/bugs/</link>
- </item>
-
- <item>
- <title>Mozilla Party, 2.0!</title>
- <link>http://www.mozilla.org/party/1999/</link>
- </item>
-
- <item>
- <title>Unix Platform Parity</title>
- <link>http://www.mozilla.org/build/unix.html</link>
- </item>
-
- <item>
- <title>NPL 1.0M published</title>
- <link>http://www.mozilla.org/NPL/NPL-1.0M.html</link>
- </item>
-
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss09x/rss091.xml b/toolkit/components/feeds/test/xml/rss09x/rss091.xml
deleted file mode 100644
index 6749fc49e..000000000
--- a/toolkit/components/feeds/test/xml/rss09x/rss091.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0"?>
-<!DOCTYPE rss SYSTEM "http://my.netscape.com/publish/formats/rss-0.91.dtd">
-<!--
-
-Description: RSS 0.91 works
-Expect: feed.title.plainText() == "Scripting News" && result.version == "rss091"
-
--->
-<rss version="0.91">
- <channel>
- <language>en</language>
- <description>
- News and commentary from the cross-platform scripting community.
- </description>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <image>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <url>http://www.scripting.com/gifs/tinyScriptingNews.gif</url>
- </image>
- <item>
- <title>stuff</title>
- <link>http://bar.example.com</link>
- <description>This is an article about some stuff</description>
- </item>
- </channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss09x/rss091_withNS.xml b/toolkit/components/feeds/test/xml/rss09x/rss091_withNS.xml
deleted file mode 100644
index 9ab2c3bf7..000000000
--- a/toolkit/components/feeds/test/xml/rss09x/rss091_withNS.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0"?>
-<!DOCTYPE rss SYSTEM "http://my.netscape.com/publish/formats/rss-0.91.dtd">
-<!--
-
-Description: RSS 0.91 works
-Expect: feed.title.plainText() == "Scripting News" && result.version == "rss091"
-
--->
-<rss version="0.91" xmlns="http://backend.userland.com/RsS2">
- <channel>
- <language>en</language>
- <description>
- News and commentary from the cross-platform scripting community.
- </description>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <image>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <url>http://www.scripting.com/gifs/tinyScriptingNews.gif</url>
- </image>
- <item>
- <title>stuff</title>
- <link>http://bar.example.com</link>
- <description>This is an article about some stuff</description>
- </item>
- </channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss09x/rss092.xml b/toolkit/components/feeds/test/xml/rss09x/rss092.xml
deleted file mode 100644
index ed68bd64f..000000000
--- a/toolkit/components/feeds/test/xml/rss09x/rss092.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-<!--
-
-Description: RSS 0.92 works
-Expect: feed.title.plainText() == "Scripting News" && result.version == "rss092"
-
--->
-<rss version="0.92">
- <channel>
- <language>en</language>
- <description>
- News and commentary from the cross-platform scripting community.
- </description>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <image>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <url>http://www.scripting.com/gifs/tinyScriptingNews.gif</url>
- </image>
- <item>
- <title>stuff</title>
- <link>http://bar.example.com</link>
- <description>This is an article about some stuff</description>
- </item>
- </channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss09x/rss093.xml b/toolkit/components/feeds/test/xml/rss09x/rss093.xml
deleted file mode 100644
index f1bb81ddf..000000000
--- a/toolkit/components/feeds/test/xml/rss09x/rss093.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-<!--
-
-Description: RSS 0.93 works
-Expect: feed.title.plainText() == "Scripting News" && result.version == "rss093"
-
--->
-<rss version="0.93">
- <channel>
- <language>en</language>
- <description>
- News and commentary from the cross-platform scripting community.
- </description>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <image>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <url>http://www.scripting.com/gifs/tinyScriptingNews.gif</url>
- </image>
- <item>
- <title>stuff</title>
- <link>http://bar.example.com</link>
- <description>This is an article about some stuff</description>
- </item>
- </channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss09x/rss094.xml b/toolkit/components/feeds/test/xml/rss09x/rss094.xml
deleted file mode 100644
index 1c2b17a24..000000000
--- a/toolkit/components/feeds/test/xml/rss09x/rss094.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-<!--
-
-Description: RSS 0.94 works
-Expect: feed.title.plainText() == "Scripting News" && result.version == "rss094"
-
--->
-<rss version="0.94">
- <channel>
- <language>en</language>
- <description>
- News and commentary from the cross-platform scripting community.
- </description>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <image>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <url>http://www.scripting.com/gifs/tinyScriptingNews.gif</url>
- </image>
- <item>
- <title>stuff</title>
- <link>http://bar.example.com</link>
- <description>This is an article about some stuff</description>
- </item>
- </channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss09x/rssUnknown.xml b/toolkit/components/feeds/test/xml/rss09x/rssUnknown.xml
deleted file mode 100644
index 653b574d0..000000000
--- a/toolkit/components/feeds/test/xml/rss09x/rssUnknown.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0"?>
-<!--
-
-Description: RSS unknown version works
-Expect: feed.title.plainText() == "Scripting News" && result.version == "rssUnknown"
-
--->
-<rss version="0.95">
- <channel>
- <language>en</language>
- <description>
- News and commentary from the cross-platform scripting community.
- </description>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <image>
- <link>http://www.scripting.com/</link>
- <title>Scripting News</title>
- <url>http://www.scripting.com/gifs/tinyScriptingNews.gif</url>
- </image>
- <item>
- <title>stuff</title>
- <link>http://bar.example.com</link>
- <description>This is an article about some stuff</description>
- </item>
- </channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_bogus_title.xml b/toolkit/components/feeds/test/xml/rss1/feed_bogus_title.xml
deleted file mode 100644
index a28952495..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_bogus_title.xml
+++ /dev/null
@@ -1,45 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ bogus title element
-Expect: feed.title.text == 'Correct Title'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
-
-
-
- <title>Bogus</title>
-
-
-
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Correct Title</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
-
-
-
- <title>Bogus</title>
-
-
-
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </dc:description>
- </item>
- <item>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.
- </dc:description>
- <title>XML: A Disruptive Technology</title>
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_description.xml b/toolkit/components/feeds/test/xml/rss1/feed_description.xml
deleted file mode 100644
index 109b8f949..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_description.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed description works
-Expect: feed.fields.getProperty('rss1:description') == 'a description'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <description>a description</description>
- </channel>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_description_normalized.xml b/toolkit/components/feeds/test/xml/rss1/feed_description_normalized.xml
deleted file mode 100644
index 44154b9f1..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_description_normalized.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed description works normalized
-Expect: feed.subtitle.text == 'a description'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <description>a description</description>
- </channel>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_description_with_dc.xml b/toolkit/components/feeds/test/xml/rss1/feed_description_with_dc.xml
deleted file mode 100644
index 4e5b1637a..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_description_with_dc.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed description works normalized
-Expect: feed.subtitle.text == 'a description'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- <description>a description</description>
- </channel>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_description_with_dc_only.xml b/toolkit/components/feeds/test/xml/rss1/feed_description_with_dc_only.xml
deleted file mode 100644
index fa1ecd59a..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_description_with_dc_only.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed description works normalized
-Expect: feed.subtitle.plainText() == 'another description'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_generator.xml b/toolkit/components/feeds/test/xml/rss1/feed_generator.xml
deleted file mode 100644
index 07ec85321..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_generator.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<!--
-
-Description: RSS1 generator
-Expect: feed.generator.agent == "http://Orchard.SourceForge.net/1.2/"
-
--->
-
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:admin="http://webns.net/mvcb/"
- xmlns="http://purl.org/rss/1.0/">
-
- <channel rdf:about="http://meerkat.oreillynet.com/?_fl=rss1.0">
- <title>Meerkat</title>
- <link>http://meerkat.oreillynet.com</link>
- <description>Meerkat: An Open Wire Service</description>
- <admin:errorReportsTo rdf:resource="mailto:channel-owner@acme.orgs"/>
- <admin:generatorAgent rdf:resource="http://Orchard.SourceForge.net/1.2/"/>
-
- <image rdf:resource="http://meerkat.oreillynet.com/icons/meerkat-powered.jpg" />
-
- <items>
- <rdf:Seq>
- <rdf:li rdf:resource="http://c.moreover.com/click/here.pl?r123" />
- </rdf:Seq>
- </items>
-
- <textinput rdf:resource="http://meerkat.oreillynet.com/" />
-
- </channel>
-
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_id.xml b/toolkit/components/feeds/test/xml/rss1/feed_id.xml
deleted file mode 100644
index 8f118102a..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_id.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ feed rdf:about
-Expect: feed.id == 'http://www.xml.com/xml/news.rss'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item rdf:about="http://example.com/hmm">
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_image.xml b/toolkit/components/feeds/test/xml/rss1/feed_image.xml
deleted file mode 100644
index c293acc3f..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_image.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ image
-Expect: ((feed.image.getProperty('rss1:link') == 'http://www.xml.com') && (feed.image.getProperty('rss1:url') == 'http://xml.com/universal/images/xml_tiny.gif'))
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
-
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- <textInput rdf:resource="http://www.google.com"/>
- </channel>
-
- <image rdf:about="http://xml.com/universal/images/xml_tiny.gif">
- <title>XML.com</title>
- <link>http://www.xml.com</link>
- <url>http://xml.com/universal/images/xml_tiny.gif</url>
- </image>
-
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>
- </item>
-
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_items_length_zero.xml b/toolkit/components/feeds/test/xml/rss1/feed_items_length_zero.xml
deleted file mode 100644
index a935b9ad9..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_items_length_zero.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ zero items count
-Expect: feed.items.length == 0
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_link.xml b/toolkit/components/feeds/test/xml/rss1/feed_link.xml
deleted file mode 100644
index f304a63e8..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_link.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed title works normalized
-Expect: feed.fields.getProperty('rss1:link') == 'http://xml.com/pub'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- </channel>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_link_normalized.xml b/toolkit/components/feeds/test/xml/rss1/feed_link_normalized.xml
deleted file mode 100644
index ba9674746..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_link_normalized.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed link works normalized
-Expect: feed.link.spec == 'http://xml.com/pub'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- </channel>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_textInput.xml b/toolkit/components/feeds/test/xml/rss1/feed_textInput.xml
deleted file mode 100644
index ea5639477..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_textInput.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ textinput
-Expect: feed.textInput.getProperty('rdf:about') == 'http://search.xml.com'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
-
- <textinput rdf:about="http://search.xml.com">
- <title>Search XML.com</title>
- <description>Search XML.com's XML collection</description>
- <name>s</name>
- <link>http://search.xml.com</link>
- </textinput>
-
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>
- </item>
- <item>
-
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_title.xml b/toolkit/components/feeds/test/xml/rss1/feed_title.xml
deleted file mode 100644
index 121545d38..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_title.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed title works
-Expect: feed.fields.getProperty('rss1:title') == 'Test'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- </channel>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_title_extra_att.xml b/toolkit/components/feeds/test/xml/rss1/feed_title_extra_att.xml
deleted file mode 100644
index b24550696..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_title_extra_att.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed title works
-Expect: feed.fields.getProperty('rss1:title') == 'Test'
-
--->
-<rdf:RDF
- xmlns:foo="http://example.org"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title foo:bar="baz">Test</title>
- </channel>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_title_normalized.xml b/toolkit/components/feeds/test/xml/rss1/feed_title_normalized.xml
deleted file mode 100644
index 5bd6ccefd..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_title_normalized.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed title works normalized
-Expect: feed.title.plainText() == 'Test'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- </channel>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_updated.xml b/toolkit/components/feeds/test/xml/rss1/feed_updated.xml
deleted file mode 100644
index 4aed87e98..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_updated.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed updated
-Expect: feed.updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- <dc:date>Sat, 07 Sep 2002 00:00:01 GMT</dc:date>
- </channel>
- <item rdf:about="http://example.com/hmm">
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_updated_dctermsmodified.xml b/toolkit/components/feeds/test/xml/rss1/feed_updated_dctermsmodified.xml
deleted file mode 100644
index 24b9fc92c..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_updated_dctermsmodified.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed updated
-Expect: feed.updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'
- xmlns:dcterms='http://purl.org/dc/terms/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- <dcterms:modified>Sat, 07 Sep 2002 00:00:01 GMT</dcterms:modified>
- </channel>
- <item rdf:about="http://example.com/hmm">
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/feed_version.xml b/toolkit/components/feeds/test/xml/rss1/feed_version.xml
deleted file mode 100644
index 8147a970c..000000000
--- a/toolkit/components/feeds/test/xml/rss1/feed_version.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 Version works
-Expect: result.version == 'rss1'
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
->
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- </channel>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/full_feed.xml b/toolkit/components/feeds/test/xml/rss1/full_feed.xml
deleted file mode 100644
index 7dae34c85..000000000
--- a/toolkit/components/feeds/test/xml/rss1/full_feed.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<!--
-
-Description: atom generator works
-Expect: result.bozo == true && feed.items.length == 1
-
--->
-<rdf:RDF
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
-xmlns:admin="http://webns.net/mvcb/"
-xmlns:cc="http://web.resource.org/cc/"
-xmlns="http://purl.org/rss/1.0/">
-
-<channel rdf:about="http://example.org/">
-<title>fooo</title>
-<link>http://weblogs.example.org/</link>
-<description>fooooooo</description>
-<dc:language>en-us</dc:language>
-<dc:creator></dc:creator>
-<dc:date>2006-04-10T08:38:18-08:00</dc:date>
-<admin:generatorAgent rdf:resource="http://www.movabletype.org/?v=3.2" />
-
-
-<items>
-<rdf:Seq>
-<rdf:li rdf:resource="http://weblogs.example.org/archives/009698.html" />
-</rdf:Seq>
-
-</items>
-
-</channel>
-<item rdf:about="http://weblogs.example.org/archives/009698.html">
-<title>Come From?</title>
-<link>http://example.org/009698.html</link>
-<description><![CDATA[
- %G–%@ much of the code
-]]></description>
-<dc:date>2006-02-06T10:19:03-08:00</dc:date>
-</item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/full_feed_not_bozo.xml b/toolkit/components/feeds/test/xml/rss1/full_feed_not_bozo.xml
deleted file mode 100644
index 61ae8a220..000000000
--- a/toolkit/components/feeds/test/xml/rss1/full_feed_not_bozo.xml
+++ /dev/null
@@ -1,354 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: Full RSS1 feed not bozo
-Expect: result.bozo == false
-
--->
-<rdf:RDF
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
-xmlns:admin="http://webns.net/mvcb/"
-xmlns:cc="http://web.resource.org/cc/"
-xmlns="http://purl.org/rss/1.0/">
-
-<channel rdf:about="http://weblogs.mozillazine.org/ben/">
-<title>Inside Firefox</title>
-<link>http://weblogs.mozillazine.org/ben/</link>
-<description>The Inside Track on Firefox Development</description>
-<dc:language>en-us</dc:language>
-<dc:creator></dc:creator>
-<dc:date>2006-04-26T14:34:49-08:00</dc:date>
-<admin:generatorAgent rdf:resource="http://www.movabletype.org/?v=3.2" />
-
-
-<items>
-<rdf:Seq><rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010115.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010109.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010075.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010074.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010073.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010040.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010030.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/010011.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/009965.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/009964.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/009943.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/009924.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/009914.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/009804.html" />
-<rdf:li rdf:resource="http://weblogs.mozillazine.org/ben/archives/009774.html" />
-</rdf:Seq>
-</items>
-
-</channel>
-
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010115.html">
-<title>Firefox 2 Is Cool</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010115.html</link>
-<description><![CDATA[<p>A lot of people read my previous post and came to a very reasonable conclusion: "If you take Places out of Firefox 2, shouldn't it be called Firefox 1.6?"</p>
-
-<p>I don't agree that Places was the one and only thing that sold Firefox 2 though. I took a look through the <a href="http://wiki.mozilla.org/Firefox2/Requirements">Firefox 2 Requirements</a> page to look at some of the other stuff that's going on. Reading that document, I think I can see now why people are down in the dumps about no-places Firefox 2. I don't think that document necessarily does the best possible job of capturing the excitement I have about some of the Firefox 2 features we're pursuing. </p>
-
-<p>For the past week or so, I've been toting around a printout of another document, which I wrote because I wanted to convey some of the vision I have of the Firefox 2 product as a whole - a more holistic view as it were. </p>
-
-<h3>Safer, Faster, Better</h3>
-
-<p>If you take a look at the black buttons stacked in the right column of this page, you'll see that one of them reads "Safer, Faster, Better." I don't knowwho came up with that one but it's a good tag line. It has a certain cadence about it. People have attached lots of these to Firefox in the past - "Take Back the Web" was the one I came up with, there's "Rediscover the Web", the FirefoxFlicks project has yielded a few good ones too - I like "<a href="http://www.firefoxflicks.com/flick/index.php?sort=new&id=21122&c=false">Web For All</a>". But "Safer, Faster, Better" is not just a tag line, it can also map into a set of themes for product development. </p>
-
-<p>So, taking a look at the Requirements page, I attempted to do that. My document wasn't a comprehensive collection of everything on that page, I was focused more on the things immediately visible to most users. I guess my problem with the Requirements page has always been its very engineering/technical focus. The result of this is that the priority of items tend to reflect how difficult something is to implement, or where it lies in the development cycle, not necessarily the impact on the user. What I ended up with I guess is a sort of "Shadow PRD" that reflects what I personally thought was cool about Firefox 2, and what I wanted to get out of it. </p>
-
-<p>A copy of the document is <a href="http://www.bengoodger.com/software/mb/2.0/firefox2-vision.html">here</a>. <br />
-Some notes:</p>
-
-<ul>
- <li>Assume the scratched out section for "Retracing Your Steps" will be part
- of a future release.
- <li>The priorities shown are my opinion, and relate to potential impact on
- the user.
- <li>The document does not represent all of the work being done, just a
- readily marketable subset.
-</ul>
-
-<p>All in all, I think there's easily enough here to justify a "2" designation. That's just my opinion though. I also think whole numbers are probably easier for the general populace to understand than decimals. </p>
-
-<p>Firefox has never been about date driven development (within reason). The changes with Places should not be seen as a change in this sentiment. What we're about is high quality software development with real advantages to <br />
-users, and I think that with the updated plan we're still on a trajectory that supports and encourages that, perhaps more firmly now than before.</p>
-
-<p>And that's it from today's "Ben waits for the tinderboxen to clear" report. </p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-26T14:34:49-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010109.html">
-<title>Firefox 2 Content Update</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010109.html</link>
-<description><![CDATA[<p>When we began work on Firefox 2, we decided to focus on a development branch, a continuation of the Mozilla 1.8 branch. The reason for doing this was that there was to be a lot of significant architectural changes going on on the trunk, with the prospect of a new rendering back end, a rearchitecture of reflow in layout, and various other things. Shipping a Firefox 2 release in 2006 off of this code did not seem possible. </p>
-
-<p>As a result, we decided to pursue a release focused on application level improvements, on a separate branch. Going into it, we knew the perils of multi-branch development. We knew the divergences that would inevitably form between branch and trunk. We had experience from the painful development of Firefox 1.0 on the Aviary branch. We resolved to be more methodical about our commits, but we knew to expect some pain. The goal was to produce a high value release in short enough time so that we could all return to the trunk and help build new features that utilize the back end being developed there, to help shake them out. </p>
-
-<p>Late last year, we put together a list of things to pursue for the Firefox 2 release. A month or so ago, we got together as a group and formalized this more in a <a href="http://wiki.mozilla.org/Firefox2/Requirements">Firefox 2 PRD</a>. We had scheduled four major pre-release milestones, two alphas and two betas. We have already shipped one alpha. The intent of the second is to be "Feature Complete".</p>
-
-<p>The people driving the various sub-projects on the Requirements list get together weekly to check status. As the weeks have gone by, it has become clear to us that the most complex feature on the plan is Places. It is easily an order of magnitude more complex than anything else on the plan. Places is a great feature and it has been exciting watching its capabilities grow. We are looking forward to the capabilities that it will expose. What we have learned though is that the work required to complete Places is probably too substantial to gate the Firefox 2 release. It falls more into the "significant rearchitecture" category of feature that's generally been targeted at Firefox 3.</p>
-
-<p>What we have decided to do is as follows:</p>
-
-<ul>
-<li>We will disable places on the 1.8 branch, reverting the user interface and back end to Firefox 1.x functionality.
-<li>We will continue to aggressively develop the capabilities of Places on the 1.9 trunk. Places will remain enabled here.
-</ul>
-
-<p>We think this is a good decision for two reasons:</p>
-
-<ul>
-<li>It reduces the pressure on the Places team to deliver a lot of bug fixes and additional features on the very immediate timeframe required by the Firefox 2 testing releases. It is my opinion that doing so would impact the quality of the feature, if we did not add at least a couple more alpha cycles to the process. This decision provides us with an opportunity to really make the architecture and user interface of Places reach their full potential.
-<li>It allows us as a group to circle around and consider the content of the Firefox 2 release holistically, identify high impact at risk areas and spend some more time on them. One of those for me was Feed Handling.
-</ul>
-
-<p>Michael Schroepfer of the Mozilla Corporation has a <a href="http://groups.google.com/group/mozilla.dev.planning/browse_frm/thread/4b8e7bafecccbc10/8997efd5d5d5f03f">newsgroup posting</a> with additional information. His thread is also the most appropriate forum for discussion of this topic. </p>
-
-<p>I have been working on refining some of the messaging surrounding feature content and prioritization on the PRD. I will post the initial results of that here soon.</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-24T09:30:54-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010075.html">
-<title>Did I Mention...</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010075.html</link>
-<description><![CDATA[<p>... that I hate this computer?</p>
-
-<p>While I'm at it... the up arrow key cap fell off after about three weeks, in early 2004. About six months later I lost the little rubber membrane thing that made it slightly easier to push the arrow. Since then, I've been typing by pushing down on the little connection thingy on the keyboard tray. </p>
-
-<p>It's been shedding pieces of plastic too. I've never dropped the computer once, but pieces of the shell have begun to snap off. </p>
-
-<p>When I first got it, when the secondary battery was in place, when the primary drained the machine would hibernate, even though the secondary was present! Pretty awful bug to ship with. There was never a solution that I could find. Speaking of batteries, the primary battery is pretty much toast... it won't go for more than 5 minutes before shutting down. It began doing this at around the 12-18 month mark. And the battery light permanently flashes orange whenever the system is on. </p>
-
-<p>Why don't I call the hotline? I guess I'll have to, before my warranty runs out. I don't because it usually involves 45 minutes on hold or explaining to someone who only has a script to read from that the issue involving a missing up arrow doesn't require restarting Windows or running some stupid diagnostic tool. I could have paid more for "premium support" at build-time but I found that concept sort of insulting: why should I have to pay extra to speak to someone who is smart and doesn't think I'm a moron?</p>
-
-<p>And I don't want a Thinkpad either. I hate those computers. They have old-fashioned 4:3 displays, and the function key and left Ctrl key are reversed. I know I could map them differently but why would I? Why couldn't IBM just have designed the product correctly in the first place? Oh, and I'd sooner drink paint than run the awful IBM access connections software to connect to a wireless network, or deal with the fact that the Num Lock key seems to reset to ON every time the system is rebooted.</p>
-
-<p>Why doesn't someone make the perfect laptop? I'd be interested to hear from someone how long the compile times are for FirefoxDebug on a 2.16GHz MacBook Pro...</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-16T19:11:28-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010074.html">
-<title>I Hate This Computer</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010074.html</link>
-<description><![CDATA[<p>I have been fighting with this computer for the past few days to do a build with a few patches applied. </p>
-
-<p>First, I managed to get a certain distance with a branch build, compiling with Visual C++ 6.0. But soon I realized there were too many dependencies that were trunk specific, so I had to build trunk. About a quarter of the way through my build died, of course, compiling from the same shell, wrong version of VC6.0 for Cairo/Thebes. </p>
-
-<p>Starting over again with the VC7 tools, another failure towards the end. Some sort of cyclic dependency check error. Clobber and restart. Now I forgot one of my patches had a configure change, and the process begins anew, I have effectively clobbered. </p>
-
-<p><a href="http://weblogs.mozillazine.org/ben/archives/2003_12.html">When I bought this machine</a>, a Dell Precision M60 with a Pentium M 1.7GHz processor, a 7200rpm disk and a gig of RAM, it could compile Firefox start to stop in 21 minutes. Now it takes over an hour.</p>
-
-<p>The situation is better on my Google-supplied workstation, but for how long? Over time, Windows reaches a point of being completely useless for anything aside from the most basic activities. What's the effect? I had planned to work both days this weekend on Firefox 2 features. Instead I spent the whole time fighting one of the most frustrating fights possible, and have achieved nothing. I hate Windows. I hate this computer.</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-16T18:58:02-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010073.html">
-<title>Miscommunications</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010073.html</link>
-<description><![CDATA[<p>My laptop was running pretty slowly yesterday so I decided to scan the Add/Remove Programs list to clear out the cruft. Things were really chugging along. I sequentially uninstalled several pieces of software, and the process was very dissatisfying. I became more and more enfuriated at my computer as it proceeded. Here are some of the nuisances:</p>
-
-<ul>
-<li>I could only remove one thing at a time.
-<li>Many pieces of software used the Windows Installer system which seemed to take forever and report very inconsistent progress (I know, Firefox isn't the best at this in its installer, either)
-<li>Most annoyingly, the uninstaller apps all reported themselves as performing a variety of actions that I never requested, as explanations for what they were doing during long periods of inactivity and progress-bar freeze. Common excuses were "Windows is Configuring <blah>" and "InstallShield is preparing a report on <bleh>".
-</ul>
-
-<p>You know, I never <strong>asked</strong> for blah to be "configured." I never asked for a report on bleh (What am I, a manager? Where is the report anyway? Does it have the appropriate cover sheet?) <strong>I just want the software gone</strong>. I'm getting really tired of excuses from software like this. Windows software seems to be getting worse and worse. On Mac, the typical way to remove a program is to drag it into the trash can. I can even do that to several programs at once! I do however have to be able to afford a Mac (I can, I have one). Many folk aren't as fortunate as I. </p>
-
-<p>As a side note, I read an interesting article in Forbes a few weeks ago criticizing Microsoft for its delays shipping Vista, and asking why wouldn't you just side-step all the trouble and buy a Mac, since the odds were good many people would have to upgrade their PC anyway just to get the whiz-bang in Vista. The article side-swiped open source desktop initiatives, asking where the viable free alternative was. I think that was an interesting point, and especially so since the capabilities of Linux systems have come an awesome distance in the past few years but there have been few distributions or desktop environments that IMO make the most of all of those.</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-16T18:05:04-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010040.html">
-<title>Firefox Version Numbers</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010040.html</link>
-<description><![CDATA[<p>Mike Beltzner <a href="http://www.beltzner.ca/mike/archives/2006/04/10/when_3_is_less_than_2.html">explains</a> Firefox version numbering. i.e. Firefox 3 RTM is not "out".</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-10T08:38:18-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010030.html">
-<title>Our Next Challenge?</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010030.html</link>
-<description><![CDATA[<p>The past year or so has been interesting. In this time, I've been able to meet a lot of new people and learn a lot of new things. Most importantly is that for the first time in as long as I can remember, I have had a chance to see the Mozilla project from the outside, as it would appear to someone who was trying to build on Mozilla technology or contribute directly to a project, but was not part of Netscape "back in the day" or an employee of the Mozilla Foundation/Corporation itself. </p>
-
-<p>It's been an illuminating experience. From a technical perspective, it helped highlight APIs that I had developed without a clear understanding of how they would be used. The Extension Installation API was one example of this, and we were able to make some great improvements to it in 2005.</p>
-
-<p>But perhaps more importantly it has shed some light on how people perceive Mozilla as an open source project. These perceptions are not the sort of things people express explicitly. You have to notice them.</p>
-
-<h3>The Difficulty of Involvement</h3>
-
-<p>This is sort of the uber-perception. I think some of the reasons for this include the following:</p>
-
-<h3>Where is the Discussion?</h3>
-
-<p>Which newsgroup/mailing list/IRC channel/wiki/talk page/bug/forum page do I need to track in order to know what's going on in a specific area? The answer is unsatisfactorily complex.</p>
-
-<p>The traditional method of joining a project in the OSS world (where you join lists and IRC channels and lurk for a while, gradually ramping up your contributions) scales uneasily to a project the size of Mozilla. The amount of data a mere mortal would have to absorb in order to be productive quickly is staggering. I have in the past jocularly referred to it as the "learning wall". I wonder how many people just give up. </p>
-
-<h3>Madness to Method?</h3>
-
-<p>As a large project, Mozilla has thousands of source files across hundreds of directories. One of my coworkers here at Google commented that he tried to find something as simple as the browser window code a couple of years ago and couldn't, because it lived under the thoughtfully named "xpfe". </p>
-
-<p>There's not a huge amount of documentation - and I'm not just talking about public API docs. I'm talking about the much needed diagrams that show how the various building blocks fit together, and in-code documentation for pretty much anything that isn't intuitive (which is a lot). I've written as little of this as anyone else.</p>
-
-<h3>Tone</h3>
-
-<p>In the past, I have not done the best I could to establish a tone for discourse that is conducive to productive development. My tendency was to snap when provoked. I made two mistakes of judgement here, one was ignoring the effect that this sort of thing would have on those watching, aside from the victim. The other was to think that regardless of the tone set by my actions, we as a group could work through any negative effects. Any work we relied on others for we could do ourselves. Or we could hire through it.</p>
-
-<h3>The Joy of Code</h3>
-
-<p>The flaw with this is that when your project's contributions come solely from companies, for better or for worse the activities of those paid contributors will align in some way with the interests of those companies. What this does not always allow for is the pursuit of the sort of improvements that are outside the scope of these interests. Such things often include raising general code quality, speculative feature development, feature polish and detail etc. I don't mean to say that companies are <em>against</em> these things, but they're often not the primary concern during a release crunch. And what companies like to have is shipping software. </p>
-
-<p>Alternately, even in the absence of corporate support, if there is not enough redundancy that the same set of folk has to do the grunt work over and over, the risk of burnout is high.</p>
-
-<p>I feel this because I have been incredibly "plan" focused over the past few years, formally during my time at Netscape and less formally but no less importantly during the run up to Firefox 1.0 and 1.5. What I notice is that I no longer have time to work on the sort of interesting side projects that I used to enjoy doing when I was first starting out. </p>
-
-<p>For example, about six years ago I discovered a bug in the Bookmarks menu shortly after scrolling was implemented. When you moused into a submenu for a folder that was in the scrolled section, the sub menu popup was pushed off the bottom of the screen. I took a couple of days to learn the menu positioning code and fix the math error that was causing the bug. The exercise was good for me in a number of ways: I learned more about another section of the code, my general expertise was raised, and well.. I fixed the bug that was bothering<br />
-me.</p>
-
-<p>I think we need to have a project that is accessible to volunteers for this reason. We also need to provide a way to allow those volunteers to grow if they want to, so that if you're one of the folk at the center you can have a chance to step aside for a moment and take a breather and code for the pure joy of it. </p>
-
-<p>Full time paid contributors will always be a part of Open Source development. But I don't think release-focused agendas will ever be a substitute for the passion of folk who participate because of the joy of exploration and of contribution. </p>
-
-<h3>Looking Outward, Looking Forward</h3>
-
-<p>As a project, we have made overtures towards being a more inclusive lot. For some of the reasons I've listed here, I think as a project we're still more inward looking than outward. How many of us have thought about what we want to be doing in 5 years? Will we always be doing this? Will our roles remain the same? My opinion is that it's fast becoming time for us to start considering making personal sacrifices in our short term conveniences to make the project more accessible to new people. Do I know what we need to do? Not exactly. But I have some ideas: find ways to make our discussions, our public faces, and our code more accessible.</p>
-
-<p>With Firefox we did an excellent job of building a world class product that people wanted to use. We have a new challenge now, one that is larger and scope and in the long run in my opinion considerably more important because the long term success of products like Firefox depend on it. How will we grow a world class development community? How will we ensure that the freedoms we enjoy are protected, forever?</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-07T09:22:59-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/010011.html">
-<title>Congrats Relicensing Project!</title>
-<link>http://weblogs.mozillazine.org/ben/archives/010011.html</link>
-<description><![CDATA[<p><a href="http://weblogs.mozillazine.org/gerv/archives/2006/03/relicensing_complete.html">Gerv announces</a> that the Relicensing project is complete. Congrats Gerv and everyone else who doggedly pursued this over the years. Part of Mozilla's mission is preserving choice, and making our code available under a variety of flexible licenses helps ensure that by allowing other projects to make use of it. This was a formidable task and a great accomplishment. </p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-04-04T07:15:22-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/009965.html">
-<title>Producing Open Source Software</title>
-<link>http://weblogs.mozillazine.org/ben/archives/009965.html</link>
-<description><![CDATA[<p>I've been reading Karl Fogel's excellent <a href="http://www.producingoss.com/">Producing Open Source Software</a>. </p>
-
-<p>Karl's book is very well written, nice and compact (272 pages), and contains useful information for anyone doing anything in the Open Source world: both developers and managers. </p>
-
-<p>It will help people new to Open Source get a better understanding of how OSS projects are run. It will help people familiar with Open Source to get a better understanding of how to contribute more effectively.</p>
-
-<p>It's definitely a "must read."</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-03-26T15:03:52-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/009964.html">
-<title>Writing for Busy People</title>
-<link>http://weblogs.mozillazine.org/ben/archives/009964.html</link>
-<description><![CDATA[<p>Back when I was in <a href="http://www2.ece.auckland.ac.nz/">University</a>, many of the lecturers stressed time and time again the importance of succinct, well organized writing. They said over and over that this was the best way to have your thoughts read and understood by decision makers. In fact, they scared us by saying that 70% of us would become managers sooner or later!</p>
-
-<p>Well, I can tell you that's sage advice. It's great when people make contributions in the form of ideas and proposals, but it's even better when they're written for busy people. Here are some examples:</p>
-
-<ul>
- <li>Making important points up front
- <li>Clear taxonomy of headings, and lots of them
- <li>Writing clearly and succinctly
- <li>No long, unbroken paragraphs or tracts of text.
- <li>Preferring bulleted lists with clear points to paragraphs.
- <li>Use of emphasis in formatting to make important things clear
-</ul>
-
-<p>These days, I find I don't have a lot of time to read everything carefully, so the better structured a document is, the more I get out of it. I frequently find I miss entire subsections or points of documents, even when there's relatively little text, because of incomplete organization. My eyes definitely glaze over when i see a large block of unbroken text with few headings. At the very least, it'd be very helpful if folk would structure their thoughts into: "Problem" and "Proposed Solution". </p>
-
-<p>Before you post, stop and think if you've written something in a way that'll allow others to get the most out of it. Communicating your ideas effectively means you may get a clearer and quicker response from other people. </p>]]></description>
-<dc:subject>Editorial</dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-03-26T14:48:04-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/009943.html">
-<title>Step 2: Ask Questions</title>
-<link>http://weblogs.mozillazine.org/ben/archives/009943.html</link>
-<description><![CDATA[<p>A healthy project is one where active contributors are always evaluating the project's progress, making sure it is headed in the right direction (usually stated in the project mission or goals). </p>
-
-<p>I think we could be better at this in Mozilla. I'm not suggesting people be assholes or anything, but I think some more pan-project analysis would be useful. </p>
-
-<p>Historically, I can point at a couple of groups of people who have attempted to do something like this. The <code>drivers@</code> group is one that looked beyond individual modules within Gecko to make sure that the right thing for the shipping products as a whole happened. The Firefox team is another example. By taking a holistic view, user experience was enhanced. </p>
-
-<p>I think contributors should not be afraid to poke their nose in other parts of the project and see how things are going. Ask questions. Learn more. Get involved in governance and management. If things don't seem intuitive, or a little arbitrary, ask, rather than assume it's for a good reason. One of the benefits of having an open, referencable set of discussion forums means that once you've answered a question once on the public forums, when someone else asks you can just give them a URL. </p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-03-22T17:27:14-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/009924.html">
-<title>Step 1: Public Discussions</title>
-<link>http://weblogs.mozillazine.org/ben/archives/009924.html</link>
-<description><![CDATA[<p>The first step on the pathway to open source project happiness is to have our discussions in the public. </p>
-
-<p>One of the things people have (rightly) criticized about Firefox and Mozilla development in the past is that too much happens mysteriously, behind closed doors. This was for a number of reasons that sounded sufficient at the time - it was expedient, people were sitting within shouting distance, mental laziness, etc. </p>
-
-<p>What poor communication breeds is a lack of understanding of procedures, priorities and such like. A healthy project is one where the contributors understanding where things are headed, and what parts they can play. It is one where newcomers can visit the project website and within the space of a few minutes get a decent understanding of how things work, and find out opportunities for them to participate. </p>
-
-<p>People don't want to contribute to projects where things happen "magically". I've learned this lesson in the past. </p>
-
-<p>To this end, I've been encouraging everyone to have public discussions on the <a href="https://lists.mozilla.org/listinfo">Mozilla Newsgroups/Mailing Lists</a>. For Firefox, the list is dev-apps-firefox@, and the newsgroup is mozilla.dev.apps.firefox. They are mirrored through <a href="http://groups.google.com/group/mozilla.dev.apps.firefox">Google Groups</a> for ease of browsing. We're planning on improving the theme for Firefox2, and rather than pursue this effort in a walled garden like last time, we're going to proceed in dev-themes@/mozilla.dev.themes. Come on over and join in!</p>
-
-<p>At the same time, we've been encouraging other projects to use the newsgroups/lists too. Decisions made in private email, IRC (which isn't archived anywhere) even in public bugs etc make it very difficult for people who aren't central to the project to find out more or participate. I think we should strive to strike a better balance between convenience and accessibility/referencability. </p>
-
-<p>On top of this, there is a need to make the contact portions of the web site more accurate, relevant and easy to find, so people can easily find the list they want, and the person or group to contact. </p>
-
-<p>We've been having discussions about all of this in <a href="http://groups.google.com/group/mozilla.dev.general">mozilla.dev.general</a>, in <a href="http://groups.google.com/group/mozilla.dev.general/browse_thread/thread/899917f713861f06/4ae6d094ffee5ae7">these</a> <a href="http://groups.google.com/group/mozilla.dev.general/browse_thread/thread/5d1bf2bbc769919d/210246003f1f6fea">threads</a>. Rather than talk in a vacuum of only ourselves, I really hope that those of you that have experienced difficulty in the past in some of these areas will come forward and contribute to the discussion. </p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-03-20T09:23:24-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/009914.html">
-<title>Reflection</title>
-<link>http://weblogs.mozillazine.org/ben/archives/009914.html</link>
-<description><![CDATA[<p>I've been doing a bit of it lately. All manner of topics. We recently moved and things have been chaotic so it's been nice to take the time to think. I've had a chance to look at how far we've come, and form some ideas about what we might need to do to go the right places. </p>
-
-<p>The past couple of years have brought some immense highs, and some considerable angst. With success has come the realization that true now as ever: the spirit of open source is expressed through the creative freedom of the many. The surest way to navigate the murky waters of increased attention and marketshare and such like is, as Leslie has been saying for some time, to keep your karma clean. Do the right thing, not only in technical matters but also relationships. </p>
-
-<p>For the Mozilla project, what we need to do (I think) is:</p>
-
-<ul>
- <li>Better define the things that are important to us. The things that define who we are. Impart the positive aspects of open development culture and practice on everyone involved because they're effective, and as a safeguard against recurrence of some of the <a href="http://weblogs.mozillazine.org/ben/archives/009698.html">troubles of the past</a>.
- <li>Engage the community more effectively. Create and maintain an infrastructure of open communication to remove the "mystery" behind the decision making process. Organize our contributor materials better to make the project more accessible to newcomers. These are just a couple of examples.
-</ul>
-
-<p>For my part, I'm starting out this year by doing things <a href="http://www.producingoss.com/">a little differently</a>. I think we need to grow more as a project. I'm hopeful that I'll be able to achieve some positive change. </p>
-
-<p>I understand that this post might seem a little abstract. I think what I'm saying might become a bit more clear after I talk about some tangible efforts, which I will do in future entries.</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-03-19T02:00:07-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/009804.html">
-<title>Bye Bye Blackberry?</title>
-<link>http://weblogs.mozillazine.org/ben/archives/009804.html</link>
-<description><![CDATA[<p><a href="http://news.com.com/Bye-bye%2C+BlackBerry+-+page+2/2100-1047_3-6042308-2.html?tag=st.num">Bye Bye, Blackberry?</a></p>
-
-<p>I cannot believe people are discussing life without these things. It's like this: I have a patent on television. I don't plan on doing anything with it, but I'm going to shut TV down for all of you, and you're going to sit about and think about life without TV? What's wrong with people?! Is this the world we all want to live in, where people without the interest or capability to pursue technology can hold everyone else captive? That's not the world I want to live in. <br />
-</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-02-24T10:57:32-08:00</dc:date>
-</item>
-<item rdf:about="http://weblogs.mozillazine.org/ben/archives/009774.html">
-<title>More on Memory</title>
-<link>http://weblogs.mozillazine.org/ben/archives/009774.html</link>
-<description><![CDATA[<p>Firefox's caching behavior is just one area of memory usage. I'm really glad that there's been such a lot of discussion in the previous post I made, since many people have raised specific issues, bugs have been filed, and people are looking at the things people are reporting. This sort of feedback system is one of the things that makes the open development model great. Firefox 2 will be much better because of your help!</p>]]></description>
-<dc:subject></dc:subject>
-<dc:creator>ben</dc:creator>
-<dc:date>2006-02-17T23:44:03-08:00</dc:date>
-</item>
-
-
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/full_feed_unknown_extension.xml b/toolkit/components/feeds/test/xml/rss1/full_feed_unknown_extension.xml
deleted file mode 100644
index c2c875b14..000000000
--- a/toolkit/components/feeds/test/xml/rss1/full_feed_unknown_extension.xml
+++ /dev/null
@@ -1,55 +0,0 @@
-<!--
-
-Description: rss1 unknown elements does not cause error
-Expect: feed.items.length == 1
-
--->
-<rdf:RDF
-xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-xmlns:dc="http://purl.org/dc/elements/1.1/"
-xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
-xmlns:admin="http://webns.net/mvcb/"
-xmlns:cc="http://web.resource.org/cc/"
-xmlns="http://purl.org/rss/1.0/">
-
-<channel rdf:about="http://example.org/">
-<title>fooo</title>
-<link>http://weblogs.example.org/</link>
-<description>fooooooo</description>
-<dc:language>en-us</dc:language>
-<dc:creator></dc:creator>
-<dc:date>2006-04-10T08:38:18-08:00</dc:date>
-<admin:generatorAgent rdf:resource="http://www.movabletype.org/?v=3.2" />
-
-
-
-
-
-
-
-<foo:bar xmlns:foo="http://example.org">baz</foo:bar>
-
-
-
-
-
-
-
-
-
-
-<items>
-<rdf:Seq>
-<rdf:li rdf:resource="http://weblogs.example.org/archives/009698.html" />
-</rdf:Seq>
-
-</items>
-
-</channel>
-<item rdf:about="http://weblogs.example.org/archives/009698.html">
-<title>Come From?</title>
-<link>http://example.org/009698.html</link>
-<description><![CDATA[much of the code]]></description>
-<dc:date>2006-02-06T10:19:03-08:00</dc:date>
-</item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/item_2_dc_description.xml b/toolkit/components/feeds/test/xml/rss1/item_2_dc_description.xml
deleted file mode 100644
index 03a4bb548..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_2_dc_description.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item 2 dc:description
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).fields.getProperty('dc:description') == 'XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </dc:description>
- <!-- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.
- </dc:description>
- <title>XML: A Disruptive Technology</title>
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher.xml b/toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher.xml
deleted file mode 100644
index d21734d6f..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item 2 dc:publisher
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).fields.getProperty('dc:publisher') == 'The O\'Reilly Network'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </dc:description>
- <!--
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.
- </dc:description>
- <title>XML: A Disruptive Technology</title>
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher_extra_att_invalid_rdf.xml b/toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher_extra_att_invalid_rdf.xml
deleted file mode 100644
index dac0d1dc8..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_2_dc_publisher_extra_att_invalid_rdf.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item 2 dc:publisher
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).fields.getProperty('dc:publisher') == 'The O\'Reilly Network'
-
--->
-<rdf:RDF
- xmlns:foo="http://example.org"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </dc:description>
- <!--
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
- <dc:publisher foo:bar="baz">The O'Reilly Network</dc:publisher>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.
- </dc:description>
- <title>XML: A Disruptive Technology</title>
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_count.xml b/toolkit/components/feeds/test/xml/rss1/item_count.xml
deleted file mode 100644
index 69520fb14..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_count.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ 1 item count
-Expect: feed.items.length == 2
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <!-- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
-
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_dc_creator.xml b/toolkit/components/feeds/test/xml/rss1/item_dc_creator.xml
deleted file mode 100644
index 71ecd6d77..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_dc_creator.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item dc:description
-Expect: var author = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).authors.queryElementAt(0, Components.interfaces.nsIFeedPerson); (author.name == "Simon St.Laurent" && author.email == "simonstl@simonstl.com")
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </dc:description>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>
- </item>
- <item>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.
- </dc:description>
- <title>XML: A Disruptive Technology</title>
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_dc_description.xml b/toolkit/components/feeds/test/xml/rss1/item_dc_description.xml
deleted file mode 100644
index 3d7880e8c..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_dc_description.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item dc:description
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('dc:description') == 'XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </dc:description>
- <!--
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.
- </dc:description>
- <title>XML: A Disruptive Technology</title>
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_dc_description_normalized.xml b/toolkit/components/feeds/test/xml/rss1/item_dc_description_normalized.xml
deleted file mode 100644
index d57477a99..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_dc_description_normalized.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item dc:description
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary.plainText() == 'XML is...'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <dc:description>XML is...</dc:description>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </description>
-
- <!--
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet 2.
- </dc:description>
- <title>XML: A Disruptive Technology</title>
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/item_description.xml b/toolkit/components/feeds/test/xml/rss1/item_description.xml
deleted file mode 100644
index db4a0137f..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_description.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item desc normalized
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary.plainText() == 'XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <description>
- XML is placing increasingly heavy loads on the existing technical infrastructure of the Internet.
- </description>
- <!-- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
-
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/item_id.xml b/toolkit/components/feeds/test/xml/rss1/item_id.xml
deleted file mode 100644
index 50048b0a3..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_id.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item rdf:about
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).id == 'http://example.com/hmm'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item rdf:about="http://example.com/hmm">
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <!-- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
-
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/item_link.xml b/toolkit/components/feeds/test/xml/rss1/item_link.xml
deleted file mode 100644
index 8ead15fb6..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_link.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item link
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('rss1:link') == 'http://c.moreover.com/click/here.pl?r123'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <!-- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
-
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_link_normalized.xml b/toolkit/components/feeds/test/xml/rss1/item_link_normalized.xml
deleted file mode 100644
index dbf9749ac..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_link_normalized.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item link
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == 'http://c.moreover.com/click/here.pl?r123'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <!-- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
-
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_title.xml b/toolkit/components/feeds/test/xml/rss1/item_title.xml
deleted file mode 100644
index b4d4b8e3e..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_title.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item title
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('rss1:title') == 'XML: A Disruptive Technology'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <!-- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
-
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss1/item_title_normalized.xml b/toolkit/components/feeds/test/xml/rss1/item_title_normalized.xml
deleted file mode 100644
index a9270982f..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_title_normalized.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item title normalized
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).title.text == 'XML: A Disruptive Technology'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <!-- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
-
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/item_updated_dcterms.xml b/toolkit/components/feeds/test/xml/rss1/item_updated_dcterms.xml
deleted file mode 100644
index d8f15ee32..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_updated_dcterms.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed updated
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'
- xmlns:dcterms='http://purl.org/dc/terms/'>
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- <dcterms:modified>Sat, 07 Sep 2002 00:00:01 GMT</dcterms:modified>
- </channel>
- <item rdf:about="http://example.com/hmm">
- <title>XML: A Disruptive Technology</title>
- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <dcterms:modified>Sat, 07 Sep 2002 00:00:01 GMT</dcterms:modified>
- </item>
-</rdf:RDF>
diff --git a/toolkit/components/feeds/test/xml/rss1/item_wiki_importance_extra_att.xml b/toolkit/components/feeds/test/xml/rss1/item_wiki_importance_extra_att.xml
deleted file mode 100644
index 49ba579dd..000000000
--- a/toolkit/components/feeds/test/xml/rss1/item_wiki_importance_extra_att.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: RSS1 feed w/ item wiki:importance with extra attribute
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).fields.getProperty('wiki:importance') == 'major'
-
--->
-<rdf:RDF
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns="http://purl.org/rss/1.0/"
- xmlns:dc='http://purl.org/dc/elements/1.1/'
- xmlns:w="http://purl.org/rss/1.0/modules/wiki/"
- xmlns:foo="http://example.org">
- <channel rdf:about="http://www.xml.com/xml/news.rss">
- <title>Test</title>
- <link>http://xml.com/pub</link>
- <dc:description>another description</dc:description>
- </channel>
- <item>
- <title>XML: A Disruptive Technology</title>
- <!-- <link>http://c.moreover.com/click/here.pl?r123</link>
- <dc:description>
- XML is placing increasingly heavy loads on the existing technical
- infrastructure of the Internet.
- </dc:description>
- <dc:publisher>The O'Reilly Network</dc:publisher>
- <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
- <dc:rights>Copyright &#169; 2000 O'Reilly &amp; Associates, Inc.</dc:rights>
- <dc:subject>XML</dc:subject>-->
- </item>
- <item>
- <w:importance foo:bar="baz">major</w:importance>
- </item>
-</rdf:RDF> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_category.xml b/toolkit/components/feeds/test/xml/rss2/feed_category.xml
deleted file mode 100644
index 553825995..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_category.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel category works
-Expect: feed.categories.queryElementAt(0, Components.interfaces.nsIPropertyBag).getProperty('term') == 'hmm'
-
--->
-<rss version="2.0" >
-<channel>
-<category>hmm</category>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_category_count.xml b/toolkit/components/feeds/test/xml/rss2/feed_category_count.xml
deleted file mode 100644
index 881c6e0d9..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_category_count.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel category works w/ domain
-Expect: feed.categories.length == 4
-
--->
-<rss version="2.0" >
-<channel>
-<category>hmm0</category>
-<category>hmm1</category>
-<category domain="http://example.org">hmm2</category>
-<category>hmm3</category>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_cloud.xml b/toolkit/components/feeds/test/xml/rss2/feed_cloud.xml
deleted file mode 100644
index caa033548..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_cloud.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel cloud works
-Expect: ((feed.cloud.getProperty('domain')=="rpc.sys.com") && (feed.cloud.getProperty('port')=="80") && (feed.cloud.getProperty('path')=="/RPC2") && (feed.cloud.getProperty('registerProcedure')=="pingMe") && (feed.cloud.getProperty('protocol')=="soap"))
-
--->
-<rss version="2.0" >
-<channel>
-<cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_copyright.xml b/toolkit/components/feeds/test/xml/rss2/feed_copyright.xml
deleted file mode 100644
index 2d00e7a14..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_copyright.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel copyright works
-Expect: feed.fields.getProperty('copyright') == 'copyright 2006'
-
--->
-<rss version="2.0" >
-<channel>
-<copyright>copyright 2006</copyright>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_copyright_linebreak.xml b/toolkit/components/feeds/test/xml/rss2/feed_copyright_linebreak.xml
deleted file mode 100644
index 4b9ca5e71..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_copyright_linebreak.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel copyright works
-Expect: feed.fields.getProperty('copyright') == 'copyright 2005'
-
--->
-<rss version="2.0" >
-<channel>
-<copyright>copyright 2005
-
-
-</copyright>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_data_outside_channel.xml b/toolkit/components/feeds/test/xml/rss2/feed_data_outside_channel.xml
deleted file mode 100644
index bf212760d..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_data_outside_channel.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel copyright works
-Expect: feed.fields.getProperty('copyright') == 'copyright 2006'
-
--->
-<rss version="2.0" >
-<dc:creator xmlns:dc="http://example.org">heynow</dc:creator>
-<channel>
-<copyright>copyright 2006</copyright>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_dc_contributor.xml b/toolkit/components/feeds/test/xml/rss2/feed_dc_contributor.xml
deleted file mode 100644
index cfb514ccd..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_dc_contributor.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel copyright works
-Expect: feed.contributors.queryElementAt(0, Components.interfaces.nsIFeedPerson).name == 'them';
-
--->
-<rss version="2.0" >
-<channel xmlns:dc="http://purl.org/dc/elements/1.1/">
-<copyright>copyright 2006</copyright>
-<dc:creator>me</dc:creator>
-<dc:contributor>them</dc:contributor>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_dc_creator.xml b/toolkit/components/feeds/test/xml/rss2/feed_dc_creator.xml
deleted file mode 100644
index 8ed1aff7f..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_dc_creator.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel copyright works
-Expect: feed.authors.queryElementAt(0, Components.interfaces.nsIFeedPerson).name == 'me'
-
--->
-<rss version="2.0" >
-<channel xmlns:dc="http://purl.org/dc/elements/1.1/">
-<copyright>copyright 2006</copyright>
-<dc:creator>me</dc:creator>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_description.xml b/toolkit/components/feeds/test/xml/rss2/feed_description.xml
deleted file mode 100644
index 11463dfe0..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_description.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel description works
-Expect: var desc = feed.fields.getProperty('description'); desc == 'test';
-
--->
-<rss version="2.0" >
-<channel>
-<description>test</description>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_description_html.xml b/toolkit/components/feeds/test/xml/rss2/feed_description_html.xml
deleted file mode 100644
index ecb544f6c..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_description_html.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel description works w/html
-Expect: feed.fields.getProperty('description') == '<b>test</b>'
-
--->
-<rss version="2.0" >
-<channel>
-<description>&lt;b>test&lt;/b></description>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_description_html_cdata.xml b/toolkit/components/feeds/test/xml/rss2/feed_description_html_cdata.xml
deleted file mode 100644
index 45ee9e92b..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_description_html_cdata.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel description works w/ html & CDATA
-Expect: feed.fields.getProperty('description') == '<b>test</b>'
-
--->
-<rss version="2.0" >
-<channel>
-<description><![CDATA[<b>test</b>]]></description>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_docs.xml b/toolkit/components/feeds/test/xml/rss2/feed_docs.xml
deleted file mode 100644
index 20323b22f..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_docs.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel docs works
-Expect: feed.fields.getProperty('docs') == 'http://example.org'
-
--->
-<rss version="2.0" >
-<channel>
-<docs>http://example.org</docs>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_generator.xml b/toolkit/components/feeds/test/xml/rss2/feed_generator.xml
deleted file mode 100644
index 91ba579b4..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_generator.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel generator works
-Expect: feed.generator.agent == 'a generator used to make feeds'
-
--->
-<rss version="2.0" >
-<channel>
-<generator>a generator used to make feeds</generator>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_image_desc.xml b/toolkit/components/feeds/test/xml/rss2/feed_image_desc.xml
deleted file mode 100644
index 7f665641b..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_image_desc.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel image description and required fields work
-Expect: ((feed.image.getProperty('title') == 'A picture') && (feed.image.getProperty('link') == 'http://example.org') && (feed.image.getProperty('url') == 'http://example.org/a.jpg') && (feed.image.getProperty('description') == 'Yo!'))
-
--->
-<rss version="2.0" >
-<channel>
-<image>
- <link>http://example.org</link>
- <title>A picture</title>
- <url>http://example.org/a.jpg</url>
- <description>Yo!</description>
-</image>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_image_desc_width_height.xml b/toolkit/components/feeds/test/xml/rss2/feed_image_desc_width_height.xml
deleted file mode 100644
index 2be53e86c..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_image_desc_width_height.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel image required fields work
-Expect: ((feed.image.getProperty('title') == 'A picture') && (feed.image.getProperty('link') == 'http://example.org') && (feed.image.getProperty('url') == 'http://example.org/a.jpg') && (feed.image.getProperty('description') == 'Yo!') && (feed.image.getProperty('width') == '42') && (feed.image.getProperty('height') == '43'))
-
--->
-<rss version="2.0" >
-<channel>
-<image>
- <link>http://example.org</link>
- <title>A picture</title>
- <url>http://example.org/a.jpg</url>
- <description>Yo!</description>
- <width>42</width>
- <height>43</height>
-</image>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_image_required.xml b/toolkit/components/feeds/test/xml/rss2/feed_image_required.xml
deleted file mode 100644
index 9035523a1..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_image_required.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel image required fields work
-Expect: ((feed.image.getProperty('title') == 'A picture') && (feed.image.getProperty('link') == 'http://example.org') && (feed.image.getProperty('url') == 'http://example.org/a.jpg'))
-
--->
-<rss version="2.0" >
-<channel>
-<image>
- <link>http://example.org</link>
- <title>A picture</title>
- <url>http://example.org/a.jpg</url>
-</image>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_language.xml b/toolkit/components/feeds/test/xml/rss2/feed_language.xml
deleted file mode 100644
index d4047a99f..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_language.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel language works
-Expect: feed.fields.getProperty('language') == 'en-us'
-
--->
-<rss version="2.0" >
-<channel>
-<language>en-us</language>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_lastBuildDate.xml b/toolkit/components/feeds/test/xml/rss2/feed_lastBuildDate.xml
deleted file mode 100644
index fee9ff582..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_lastBuildDate.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel lastBuildDate works
-Expect: feed.fields.getProperty('lastBuildDate') == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<lastBuildDate>Sat, 07 Sep 2002 00:00:01 GMT</lastBuildDate>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_linebreak_link.xml b/toolkit/components/feeds/test/xml/rss2/feed_linebreak_link.xml
deleted file mode 100644
index 1af6550f9..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_linebreak_link.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel link works w/ line break
-Expect: feed.link.spec == 'http://mozilla.org/'
-
--->
-<rss version="2.0" >
-<channel>
-<link>
-http://mozilla.org/
-</link>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_link.xml b/toolkit/components/feeds/test/xml/rss2/feed_link.xml
deleted file mode 100644
index a4874e9ca..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_link.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel link works
-Expect: feed.link.spec == 'http://mozilla.org/'
-
--->
-<rss version="2.0" >
-<channel>
-<link>http://mozilla.org/</link>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_link_cdata.xml b/toolkit/components/feeds/test/xml/rss2/feed_link_cdata.xml
deleted file mode 100644
index 5031ac1c3..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_link_cdata.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel link works w/ CDATA
-Expect: feed.link.spec == 'http://mozilla.org/'
-
--->
-<rss version="2.0" >
-<channel>
-<link>
- <![CDATA[http://mozilla.org/]]>
-</link>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_managingEditor.xml b/toolkit/components/feeds/test/xml/rss2/feed_managingEditor.xml
deleted file mode 100644
index 3f7060449..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_managingEditor.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel managingEditor works
-Expect: feed.authors.queryElementAt(0, Components.interfaces.nsIFeedPerson).email == 'example@example.com'
-
--->
-<rss version="2.0" >
-<channel>
-<managingEditor>example@example.com</managingEditor>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_managingEditor_extra_att.xml b/toolkit/components/feeds/test/xml/rss2/feed_managingEditor_extra_att.xml
deleted file mode 100644
index 017a4595f..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_managingEditor_extra_att.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel managingEditor works
-Expect: feed.authors.queryElementAt(0, Components.interfaces.nsIFeedPerson).email == 'example@example.com'
-
--->
-<rss version="2.0" >
-<channel>
-<managingEditor foo:bar="baz" xmlns:foo="http://example.org">example@example.com</managingEditor>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_multiple_categories.xml b/toolkit/components/feeds/test/xml/rss2/feed_multiple_categories.xml
deleted file mode 100644
index 538362b6a..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_multiple_categories.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel category works
-Expect: feed.categories.queryElementAt(2, Components.interfaces.nsIPropertyBag).getProperty('term') == 'hmm2'
-
--->
-<rss version="2.0" >
-<channel>
-<category>hmm0</category>
-<category>hmm1</category>
-<category>hmm2</category>
-<category>hmm3</category>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_pubDate.xml b/toolkit/components/feeds/test/xml/rss2/feed_pubDate.xml
deleted file mode 100644
index 42cea6832..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_pubDate.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel pubDate works
-Expect: feed.fields.getProperty('pubDate') == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Sat, 07 Sep 2002 00:00:01 GMT</pubDate>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_invalid.xml b/toolkit/components/feeds/test/xml/rss2/feed_pubDate_invalid.xml
deleted file mode 100644
index 48cce256a..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_invalid.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: non-RFC822 date should produce null feed.updated
-Expect: feed.updated == null
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Satmonkey, 07 Sepmonkey 2002 00:00:01 GMT</pubDate>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_1.xml b/toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_1.xml
deleted file mode 100644
index 846ef22a6..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_1.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: Test whether date parsing handles partly-abbreviated dates.
-Expect: feed.updated == 'Tue, 25 Apr 2006 08:00:00 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Tues, 25 Apri 2006 08:00:00 GMT</pubDate>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_2.xml b/toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_2.xml
deleted file mode 100644
index d1ee96f36..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_nonRFC822_2.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: Test whether date parsing handles unabbreviated dates.
-Expect: feed.updated == 'Sat, 25 Nov 2006 00:12:45 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Saturday 25 November 2006 10:12:45 +1000</pubDate>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_timezoneZ.xml b/toolkit/components/feeds/test/xml/rss2/feed_pubDate_timezoneZ.xml
deleted file mode 100644
index b31ed5c56..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_timezoneZ.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: Test whether date parsing handles "Z" as a timezone in RFC822.
-Expect: feed.updated == 'Tue, 25 Apr 2006 08:00:00 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Tue, 25 Apr 2006 08:00:00 Z</pubDate>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_utc.xml b/toolkit/components/feeds/test/xml/rss2/feed_pubDate_utc.xml
deleted file mode 100644
index 8eff56046..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_pubDate_utc.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: Test whether date parsing handles 'UTC' as a timezone.
-Expect: feed.updated == 'Mon, 16 Apr 2007 03:12:45 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Monday, 16 April 2007 03:12:45 UTC</pubDate>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_rating.xml b/toolkit/components/feeds/test/xml/rss2/feed_rating.xml
deleted file mode 100644
index dd5f8f9e5..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_rating.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel rating works
-Expect: feed.fields.getProperty('rating') == '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l by "webmaster@example.com" on "2006.01.29T10:09-0800" r (n 0 s 0 v 0 l 0))'
-
--->
-<rss version="2.0" >
-<channel>
-<rating>(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l by "webmaster@example.com" on "2006.01.29T10:09-0800" r (n 0 s 0 v 0 l 0))</rating>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_single_quote_stylesheet_pi.xml b/toolkit/components/feeds/test/xml/rss2/feed_single_quote_stylesheet_pi.xml
deleted file mode 100644
index 10141fe7e..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_single_quote_stylesheet_pi.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0"?>
-<!--
-
-Description: stylesheets with single quoted attributes work. Bug 352549.
-Base: http://www.penny-arcade.com/rss.xml
-Expect: result.stylesheet.spec == "http://www.penny-arcade.com/stylesheets/rss-display.xsl"
-
--->
-<?xml-stylesheet type='text/xsl' href='/stylesheets/rss-display.xsl' version='1.0'?>
-<rss version="2.0">
-<channel>
-<title>Penny-Arcade</title>
-<link>http://www.penny-arcade.com/</link>
-<language>en-us</language>
-
-<copyright>Copyright 1999 - 2006 Penny Arcade, Inc.</copyright>
-<image>
-<url>http://www.penny-arcade.com/images/rss-logo.png</url>
-<title>Penny-Arcade Logo</title>
-<link>http://www.penny-arcade.com/</link>
-<width>144</width>
-
-<height>82</height>
-</image>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_skipDays.xml b/toolkit/components/feeds/test/xml/rss2/feed_skipDays.xml
deleted file mode 100644
index 8c6ffa9e4..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_skipDays.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel skipDays works
-Expect: ((feed.skipDays.queryElementAt(0, Components.interfaces.nsISupportsString) == 'Sunday') && (feed.skipDays.queryElementAt(1, Components.interfaces.nsISupportsString) == 'Monday'))
-
--->
-<rss version="2.0" >
-<channel>
-<skipDays>
- <day>Sunday</day>
- <day>Monday</day>
-</skipDays>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_skipHours.xml b/toolkit/components/feeds/test/xml/rss2/feed_skipHours.xml
deleted file mode 100644
index a20372eda..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_skipHours.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel skipHours works
-Expect: ((feed.skipHours.queryElementAt(0, Components.interfaces.nsISupportsString) == '0') && (feed.skipHours.queryElementAt(4, Components.interfaces.nsISupportsString) == '23'))
-
--->
-<rss version="2.0" >
-<channel>
-<skipHours>
- <hour>0</hour>
- <hour>1</hour>
- <hour>2</hour>
- <hour>22</hour>
- <hour>23</hour>
-</skipHours>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_subtitle.xml b/toolkit/components/feeds/test/xml/rss2/feed_subtitle.xml
deleted file mode 100644
index a98a3c19e..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_subtitle.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel description works
-Expect: feed.subtitle.text == 'test'
-
--->
-<rss version="2.0" >
-<channel>
-<description>test</description>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_subtitle_html.xml b/toolkit/components/feeds/test/xml/rss2/feed_subtitle_html.xml
deleted file mode 100644
index fca819d36..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_subtitle_html.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel description works
-Expect: feed.subtitle.plainText() == '<i><b>test</b></i>'
-
--->
-<rss version="2.0" >
-<channel>
-<description><![CDATA[<i><b>test</b></i>]]></description>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_subtitle_markup_stripped.xml b/toolkit/components/feeds/test/xml/rss2/feed_subtitle_markup_stripped.xml
deleted file mode 100644
index 54f6a623c..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_subtitle_markup_stripped.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel description markup is not HTML
-Expect: feed.subtitle.plainText() == '<i><b>test</b></i>'
-
--->
-<rss version="2.0" >
-<channel>
-<description><![CDATA[<i><b>test</b></i>]]></description>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_textinput.xml b/toolkit/components/feeds/test/xml/rss2/feed_textinput.xml
deleted file mode 100644
index 4617d62bc..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_textinput.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel textInput works
-Expect: ((feed.textInput.getProperty('description') == 'Your aggregator supports the textInput element. What software are you using?') && (feed.textInput.getProperty('link') == 'http://www.cadenhead.org/textinput.php') && (feed.textInput.getProperty('name') == 'query') && (feed.textInput.getProperty('title') == 'TextInput Inquiry'))
-
--->
-<rss version="2.0" >
-<channel>
-<textInput>
- <description>Your aggregator supports the textInput element. What software are you using?</description>
- <link>http://www.cadenhead.org/textinput.php</link>
- <name>query</name>
- <title>TextInput Inquiry</title>
-</textInput>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_title.xml b/toolkit/components/feeds/test/xml/rss2/feed_title.xml
deleted file mode 100644
index 1f7d63ad2..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_title.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel title works
-Expect: feed.title.plainText() == 'test title'
-
--->
-<rss version="2.0" >
-<channel>
-<title>test title</title>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_title_cdata_mixed.xml b/toolkit/components/feeds/test/xml/rss2/feed_title_cdata_mixed.xml
deleted file mode 100644
index 19ef62915..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_title_cdata_mixed.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel title works w/ funky CDATA title
-Expect: feed.title.plainText() == 'test title'
-
--->
-<rss version="2.0" >
-<channel>
-<title>test t<![CDATA[it]]>le</title>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_title_nesting.xml b/toolkit/components/feeds/test/xml/rss2/feed_title_nesting.xml
deleted file mode 100644
index 82492cef7..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_title_nesting.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel title works w/ nested title
-Expect: feed.title.text == 'test title'
-
--->
-<rss version="2.0" >
-<channel>
-<title>test title</title>
-<bogus><title>bogus title</title></bogus>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_ttl.xml b/toolkit/components/feeds/test/xml/rss2/feed_ttl.xml
deleted file mode 100644
index 57158aff4..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_ttl.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel ttl works
-Expect: feed.fields.getProperty('ttl') == '60'
-
--->
-<rss version="2.0" >
-<channel>
-<ttl>60</ttl>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_updated.xml b/toolkit/components/feeds/test/xml/rss2/feed_updated.xml
deleted file mode 100644
index c9e75e360..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_updated.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel pubDate works
-Expect: feed.updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Sat, 07 Sep 2002 00:00:01 GMT</pubDate>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_updated_dcdate.xml b/toolkit/components/feeds/test/xml/rss2/feed_updated_dcdate.xml
deleted file mode 100644
index aa69e7800..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_updated_dcdate.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel pubDate works
-Expect: feed.updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
-<channel>
-<dc:date>Sat, 07 Sep 2002 00:00:01 GMT</dc:date>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate.xml b/toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate.xml
deleted file mode 100644
index 2fb24a7ec..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel lastBuildDate works
-Expect: feed.updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<lastBuildDate>Sat, 07 Sep 2002 00:00:01 GMT</lastBuildDate>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate_priority.xml b/toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate_priority.xml
deleted file mode 100644
index 24f024005..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_updated_lastBuildDate_priority.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel lastBuildDate trumps pubDate
-Expect: feed.updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" >
-<channel>
-<pubDate>Sun, 08 Sep 2002 00:00:01 GMT</pubDate>
-<lastBuildDate>Sat, 07 Sep 2002 00:00:01 GMT</lastBuildDate>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_webMaster.xml b/toolkit/components/feeds/test/xml/rss2/feed_webMaster.xml
deleted file mode 100644
index 887894983..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_webMaster.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel webMaster works
-Expect: feed.fields.getProperty('webMaster') == 'example@example.com'
-
--->
-<rss version="2.0" >
-<channel>
-<webMaster>example@example.com</webMaster>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_wfw_commentapi.xml b/toolkit/components/feeds/test/xml/rss2/feed_wfw_commentapi.xml
deleted file mode 100644
index af725064e..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_wfw_commentapi.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel copyright works
-Expect: feed.fields.getProperty('wfw:comment') == 'http://example.org'
-
--->
-<rss xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0" >
-<channel xmlns:dc="http://purl.org/dc/elements/1.1/">
-<wfw:comment>http://example.org</wfw:comment>
-<copyright>copyright 2006</copyright>
-<dc:creator>me</dc:creator>
-<dc:contributor>them</dc:contributor>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_wfw_commentrss.xml b/toolkit/components/feeds/test/xml/rss2/feed_wfw_commentrss.xml
deleted file mode 100644
index fb1d89609..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_wfw_commentrss.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel copyright works
-Expect: feed.fields.getProperty('wfw:commentRss') == 'http://example.org'
-
--->
-<rss xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0" >
-<channel xmlns:dc="http://purl.org/dc/elements/1.1/">
-<copyright>copyright 2006</copyright>
-<dc:creator>me</dc:creator>
-<wfw:commentRss>http://example.org</wfw:commentRss>
-<dc:contributor>them</dc:contributor>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_wiki.xml b/toolkit/components/feeds/test/xml/rss2/feed_wiki.xml
deleted file mode 100644
index b8cb783b0..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_wiki.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel unusual prefixed ext works
-Expect: feed.fields.getProperty('wiki:version') == '1'
-
--->
-<rss
-xmlns:w='http://purl.org/rss/1.0/modules/wiki/'
-xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0" >
-<channel xmlns:dc="http://purl.org/dc/elements/1.1/">
-<copyright>copyright 2006</copyright>
-<dc:creator>me</dc:creator>
-<w:version>1</w:version>
-<wfw:commentRss>http://example.org</wfw:commentRss>
-<dc:contributor>them</dc:contributor>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/feed_wiki_unusual_prefix.xml b/toolkit/components/feeds/test/xml/rss2/feed_wiki_unusual_prefix.xml
deleted file mode 100644
index b8cb783b0..000000000
--- a/toolkit/components/feeds/test/xml/rss2/feed_wiki_unusual_prefix.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel unusual prefixed ext works
-Expect: feed.fields.getProperty('wiki:version') == '1'
-
--->
-<rss
-xmlns:w='http://purl.org/rss/1.0/modules/wiki/'
-xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0" >
-<channel xmlns:dc="http://purl.org/dc/elements/1.1/">
-<copyright>copyright 2006</copyright>
-<dc:creator>me</dc:creator>
-<w:version>1</w:version>
-<wfw:commentRss>http://example.org</wfw:commentRss>
-<dc:contributor>them</dc:contributor>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/item_author.xml b/toolkit/components/feeds/test/xml/rss2/item_author.xml
deleted file mode 100644
index ad0c97e2a..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_author.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item author works
-Expect: var authors = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).authors; var author = authors.queryElementAt(0, Components.interfaces.nsIFeedPerson); ((author.name == 'Joe Bob Briggs'));
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_category.xml b/toolkit/components/feeds/test/xml/rss2/item_category.xml
deleted file mode 100644
index 4795e00bb..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_category.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item category works
-Expect: var cats = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('categories'); cats.QueryInterface(Components.interfaces.nsIArray); var cat = cats.queryElementAt(0, Components.interfaces.nsIPropertyBag); ((cat.getProperty('domain') == 'foo') && (cat.getProperty('term') == 'bar'));
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<category domain="foo">bar</category>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_comments.xml b/toolkit/components/feeds/test/xml/rss2/item_comments.xml
deleted file mode 100644
index da1cccc82..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_comments.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item comments works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('comments') == 'http://example.org'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<title>test</title>
-<!--<author>jbb@dallas.example.com (Joe Bob Briggs)</author>-->
-<comments>http://example.org</comments>
-
-<category domain="foo">bar</category>
-
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_content_encoded.xml b/toolkit/components/feeds/test/xml/rss2/item_content_encoded.xml
deleted file mode 100644
index 6611375b6..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_content_encoded.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item title works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).content.plainText() == 'foobar'
-
--->
-<rss version="2.0" >
-<channel>
-<item xmlns:c="http://purl.org/rss/1.0/modules/content/">
- <title>test</title>
- <c:encoded>foobar</c:encoded>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_count.xml b/toolkit/components/feeds/test/xml/rss2/item_count.xml
deleted file mode 100644
index a69cbc979..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_count.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: items length is correct
-Expect: feed.items.length == 1
-
--->
-<rss version="2.0"
- xmlns:dc="http://purl.org/dc/elements/1.1/">
-
-<channel>
-<title>Items Test</title>
-<link>http://mozilla.org/</link>
-<description></description>
-
-<dc:language>en-us</dc:language>
-<dc:creator>sayrer@gmail.com</dc:creator>
-<dc:date>2005-12-07T14:48:03-05:00</dc:date>
-
-<item>
-<title>Is the date right?</title>
-<link>http://example.org/dc_date.html</link>
-</item>
-
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/item_count2.xml b/toolkit/components/feeds/test/xml/rss2/item_count2.xml
deleted file mode 100644
index 27df0a932..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_count2.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: items length is correct
-Expect: feed.items.length == 2
-
--->
-<rss version="2.0"
- xmlns:dc="http://purl.org/dc/elements/1.1/">
-
-<channel>
-<title>Items Test</title>
-<link>http://mozilla.org/</link>
-<description></description>
-
-<dc:language>en-us</dc:language>
-<dc:creator>sayrer@gmail.com</dc:creator>
-<dc:date>2005-12-07T14:48:03-05:00</dc:date>
-
-<item>
-<title>Is the date right?</title>
-<link>http://example.org/dc_date.html</link>
-</item>
-<item>
-<title>Is the date right?</title>
-<link>http://example.org/dc_date.html</link>
-</item>
-
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/item_description.xml b/toolkit/components/feeds/test/xml/rss2/item_description.xml
deleted file mode 100644
index 7416d48e6..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_description.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item desc encoded works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary.text == 'I\'m headed for France. I wasn\'t gonna go this year, but then last week <a href="http://www.imdb.com/title/tt0086525/">Valley Girl</a> came out and I said to myself, Joe Bob, you gotta get out of the country for a while.'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<comments>http://example.org</comments>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_description_2.xml b/toolkit/components/feeds/test/xml/rss2/item_description_2.xml
deleted file mode 100644
index 427726868..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_description_2.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item desc encoded works
-Expect: feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).summary.text == 'I\'m headed for France. I wasn\'t gonna go this year, but then last week <a href="http://www.imdb.com/title/tt0086525/">Valley Girl</a> came out and I said to myself, Joe Bob, you gotta get out of the country for a while.'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
- <description>hmmm</description>
-</item>
-<item>
-<comments>http://example.org</comments>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_description_cdata.xml b/toolkit/components/feeds/test/xml/rss2/item_description_cdata.xml
deleted file mode 100644
index ef3926f87..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_description_cdata.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item desc CDATA works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary.text == 'I\'m headed for France. I wasn\'t gonna go this year, but then last week <a href="http://www.imdb.com/title/tt0086525/">Valley Girl</a> came out and I said to myself, Joe Bob, you gotta get out of the country for a while.'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-<description><![CDATA[I'm headed for France. I wasn't gonna go this year, but then last week <a href="http://www.imdb.com/title/tt0086525/">Valley Girl</a> came out and I said to myself, Joe Bob, you gotta get out of the country for a while.]]></description>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_description_decode_entities.xml b/toolkit/components/feeds/test/xml/rss2/item_description_decode_entities.xml
deleted file mode 100644
index e259354dc..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_description_decode_entities.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-
-Description: item desc encoded, double-escaped entity
-Expect: var summary = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary; summary.plainText() == "test D\u00e9sol\u00e9e";
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<comments>http://example.org</comments>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<category domain="foo">bar</category>
-
-<description>
- &lt;b>test D&amp;eacute;sol&amp;eacute;e&lt;/b>
-</description>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_description_normalized.xml b/toolkit/components/feeds/test/xml/rss2/item_description_normalized.xml
deleted file mode 100644
index 9819deb36..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_description_normalized.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item desc encoded, normalied works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary.text == 'I\'m headed for France. I wasn\'t gonna go this year, but then last week <a href="http://www.imdb.com/title/tt0086525/">Valley Girl</a> came out and I said to myself, Joe Bob, you gotta get out of the country for a while.'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<comments>http://example.org</comments>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_description_normalized_nohtml.xml b/toolkit/components/feeds/test/xml/rss2/item_description_normalized_nohtml.xml
deleted file mode 100644
index 0a34a008d..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_description_normalized_nohtml.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item desc encoded, normalized works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary.plainText() == 'I\'m headed for France. I wasn\'t gonna go this year, but then last week Valley Girl came out and I said to myself, Joe Bob, you gotta get out of the country for a while.'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<comments>http://example.org</comments>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_enclosure.xml b/toolkit/components/feeds/test/xml/rss2/item_enclosure.xml
deleted file mode 100644
index 2e38a370a..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_enclosure.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item enclosure works
-Expect: var enc = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('enclosure'); enc.QueryInterface(Components.interfaces.nsIPropertyBag); ((enc.getProperty('length') == '24986239') && (enc.getProperty('type') == 'audio/mpeg') && (enc.getProperty('url') == 'http://dallas.example.com/joebob_050689.mp3') && (feed.type == 1) && (feed.enclosureCount == 1));
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates.xml b/toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates.xml
deleted file mode 100644
index a9bcd2cc9..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: feed with duplicate enclosures on a single item
-Expect: ((feed.type == 4) && (feed.enclosureCount == 1));
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-
-<item>
-<enclosure length="24986239" type="video/mpeg" url="http://dallas.example.com/joebob_050689.mpeg" />
-<media:content fileSize="24986239" type="video/mpeg" url="http://dallas.example.com/joebob_050689.mpeg" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test audio</title>
-
-<category domain="foo">bar</category>
-
-<description>Listen to the words that are coming out of my mouth.</description>
-</item>
-
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates2.xml b/toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates2.xml
deleted file mode 100644
index 51f7caba9..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_enclosure_duplicates2.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: feed with duplicate enclosures on a single item with different data available
-Expect: var enc = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('enclosure'); enc.QueryInterface(Components.interfaces.nsIPropertyBag); ((enc.getProperty('length') == '24986239') && (enc.getProperty('type') == 'video/mpeg') && (feed.type == 4) && (feed.enclosureCount == 1) );
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-
-<item>
-<enclosure url="http://dallas.example.com/joebob_050689.mpeg" />
-<media:content fileSize="24986239" type="video/mpeg" url="http://dallas.example.com/joebob_050689.mpeg" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test audio</title>
-
-<category domain="foo">bar</category>
-
-<description>Listen to the words that are coming out of my mouth.</description>
-</item>
-
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed.xml b/toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed.xml
deleted file mode 100644
index 7b49e4d74..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: feed with different kinds of enclosures that should be TYPE_FEED (0)
-Expect: ((feed.type == 0) && (feed.enclosureCount == 2));
-
--->
-<rss version="2.0" >
-<channel>
-
-<item>
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test audio</title>
-
-<category domain="foo">bar</category>
-
-<description>Listen to the words that are coming out of my mouth.</description>
-</item>
-
-<item>
-<enclosure length="3000000" type="video/mpeg" url="http://dallas.example.com/joebob_pants.mpeg" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test video</title>
-
-<category domain="foo">bar</category>
-
-<description>Look into my eyes....</description>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed2.xml b/toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed2.xml
deleted file mode 100644
index a54a40559..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_enclosure_mixed2.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: feed that doesn't have at least one enclosure per entry should be TYPE_FEED (0)
-Expect: ((feed.type == 0) && (feed.enclosureCount == 1));
-
--->
-<rss version="2.0" >
-<channel>
-
-<item>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>no video this week!</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm on a trip to the moon this week for this year's Spaceshot Vlogger
-conference. No video this week!</description>
-</item>
-
-<item>
-<enclosure length="3000000" type="video/mpeg" url="http://dallas.example.com/joebob_pants.mpeg" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>orange keyboard</title>
-
-<category domain="foo">bar</category>
-
-<description>Crazy things happen when you paint your keyboard orange.</description>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid.xml b/toolkit/components/feeds/test/xml/rss2/item_guid.xml
deleted file mode 100644
index 2e7f551ef..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid works
-Expect: var guid = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('guid'); guid.QueryInterface(Components.interfaces.nsIPropertyBag2); guid.getProperty('guid') == 'asdf';
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-<guid>asdf</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_bogus_url.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_bogus_url.xml
deleted file mode 100644
index 2f1b67ced..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_bogus_url.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item copes with bogus guid
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link == null;
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-<guid isPermaLink="true">xorg</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink.xml
deleted file mode 100644
index c64341427..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid works
-Expect: var link = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link; link.spec == 'http://www.example.org/';
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<guid isPermaLink="true">http://www.example.org/</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_default.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_default.xml
deleted file mode 100644
index 7d6ae7958..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_default.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid works
-Expect: var link = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link; link.spec == 'http://www.example.org/';
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<guid>http://www.example.org/</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false.xml
deleted file mode 100644
index c2a1ad867..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid should not map to link when isPermaLink=false
-Expect: var link = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link; link == null;
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<guid isPermaLink="false">http://www.example.org/</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false_uppercase.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false_uppercase.xml
deleted file mode 100644
index 9ff2505c4..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_false_uppercase.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid should not map to link when isPermaLink=FaLsE
-Expect: var link = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link; link == null;
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<guid isPermaLink="FaLsE">http://www.example.org/</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_true_uppercase.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_true_uppercase.xml
deleted file mode 100644
index bc4fdc0e9..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_true_uppercase.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid should map to link when isPermaLink=TrUe
-Expect: var link = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link; link.spec == "http://www.example.org/";
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<guid isPermaLink="TrUe">http://www.example.org/</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_unknown_value.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_unknown_value.xml
deleted file mode 100644
index 4dce8c390..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_isPermaLink_unknown_value.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid should map to link when isPermaLink=meatcake or other unknown values
-Expect: var link = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link; link.spec == "http://www.example.org/";
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<title>test</title>
-<guid isPermaLink="meatcake">http://www.example.org/</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_normalized.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_normalized.xml
deleted file mode 100644
index e4ac97862..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_normalized.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item guid works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).id == 'asdf';
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-<guid>asdf</guid>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_guid_with_link.xml b/toolkit/components/feeds/test/xml/rss2/item_guid_with_link.xml
deleted file mode 100644
index d2d3daca5..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_guid_with_link.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item prefers link to guid
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == 'http://link.example.org/';
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-<guid isPermaLink="true">http://www.example.org</guid>
-<link>http://link.example.org/</link>
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_link.xml b/toolkit/components/feeds/test/xml/rss2/item_link.xml
deleted file mode 100644
index c89f71e77..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_link.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item comments works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('link') == 'http://dallas.example.com/1983/05/06/joebob.htm'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<title>test</title>
-<!--<author>jbb@dallas.example.com (Joe Bob Briggs)</author>-->
-<comments>http://example.org</comments>
-<link>http://dallas.example.com/1983/05/06/joebob.htm</link>
-<category domain="foo">bar</category>
-
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_link_normalized.xml b/toolkit/components/feeds/test/xml/rss2/item_link_normalized.xml
deleted file mode 100644
index 876d7613c..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_link_normalized.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item link normalized works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).link.spec == 'http://dallas.example.com/1983/05/06/joebob.htm'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-<title>test</title>
-<!--<author>jbb@dallas.example.com (Joe Bob Briggs)</author>-->
-<comments>http://example.org</comments>
-<link>http://dallas.example.com/1983/05/06/joebob.htm</link>
-<category domain="foo">bar</category>
-
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_plain_desc.xml b/toolkit/components/feeds/test/xml/rss2/item_plain_desc.xml
deleted file mode 100644
index ffb4226f1..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_plain_desc.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item desc plain text works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).summary.text == "I'm headed for France. I wasn't gonna go this year, but then last week \"Valley Girl\" came out and I said to myself, Joe Bob, you gotta get out of the country for a while."
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-<description>I'm headed for France. I wasn't gonna go this year, but then last week "Valley Girl" came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_populated_enclosures.xml b/toolkit/components/feeds/test/xml/rss2/item_populated_enclosures.xml
deleted file mode 100644
index 0a7d60df6..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_populated_enclosures.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item enclosure is added to enclosures array
-Expect: var encs = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).enclosures; encs.QueryInterface(Components.interfaces.nsIArray); var enc = encs.queryElementAt(0, Components.interfaces.nsIPropertyBag2); ((enc.getProperty('length') == '24986239') && (enc.getProperty('type') == 'audio/mpeg') && (enc.getProperty('url') == 'http://dallas.example.com/joebob_050689.mp3'));
-
--->
-<rss version="2.0" >
-<channel>
-<item>
-
-<enclosure length="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_pubDate.xml b/toolkit/components/feeds/test/xml/rss2/item_pubDate.xml
deleted file mode 100644
index acb4abdcc..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_pubDate.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: entry pubDate works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).published == 'Tue, 02 Sep 2003 00:00:01 GMT'
-
--->
-<rss version="2.0" xmlns:dcterms="http://purl.org/dc/terms/">
-<channel>
-<item>
-<pubDate>Tue, 02 Sep 2003 00:00:01 GMT</pubDate>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_published.xml b/toolkit/components/feeds/test/xml/rss2/item_published.xml
deleted file mode 100644
index 86bf55602..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_published.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: entry published works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).published == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" xmlns:dcterms="http://purl.org/dc/terms/">
-<channel>
-<item>
-<dcterms:issued>Sat, 07 Sep 2002 00:00:01 GMT</dcterms:issued>
-</item>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/item_title.xml b/toolkit/components/feeds/test/xml/rss2/item_title.xml
deleted file mode 100644
index 0126d7da0..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_title.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item title works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('title') == 'test'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
- <title>test</title>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_title_normalized.xml b/toolkit/components/feeds/test/xml/rss2/item_title_normalized.xml
deleted file mode 100644
index 51de0f7e2..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_title_normalized.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: item title works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).title.text == 'test'
-
--->
-<rss version="2.0" >
-<channel>
-<item>
- <title>test</title>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/item_updated_dcdate.xml b/toolkit/components/feeds/test/xml/rss2/item_updated_dcdate.xml
deleted file mode 100644
index dc20cdbc0..000000000
--- a/toolkit/components/feeds/test/xml/rss2/item_updated_dcdate.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: channel pubDate works
-Expect: feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).updated == 'Sat, 07 Sep 2002 00:00:01 GMT'
-
--->
-<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
-<channel>
-<item>
-<dc:date>Sat, 07 Sep 2002 00:00:01 GMT</dc:date>
-</item>
-</channel>
-</rss> \ No newline at end of file
diff --git a/toolkit/components/feeds/test/xml/rss2/items_2_titles.xml b/toolkit/components/feeds/test/xml/rss2/items_2_titles.xml
deleted file mode 100644
index 3a0d1eb67..000000000
--- a/toolkit/components/feeds/test/xml/rss2/items_2_titles.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: 2 items title works
-Expect: ((feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).title.text == 'test') && (feed.items.queryElementAt(1, Components.interfaces.nsIFeedEntry).title.text == 'test #2'))
-
--->
-<rss version="2.0" >
-<channel>
-<item>
- <title>test</title>
-</item>
-<item>
- <title>test #2</title>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/mrss_content.xml b/toolkit/components/feeds/test/xml/rss2/mrss_content.xml
deleted file mode 100644
index 62a47cdef..000000000
--- a/toolkit/components/feeds/test/xml/rss2/mrss_content.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: mrss content works
-Expect: var enc = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getPropertyAsInterface('mediacontent', Components.interfaces.nsIArray).queryElementAt(0, Components.interfaces.nsIPropertyBag); Assert.equal(enc.getProperty('fileSize'), '24986239', 'file size is correct'); Assert.equal(enc.getProperty('type'), 'video/mpeg', 'type is correct'); Assert.equal(enc.getProperty('url'), 'http://dallas.example.com/joebob_050689.mpeg', 'url is correct'); Assert.equal(feed.type, 4, 'Feed type is correct'); Assert.equal(feed.enclosureCount,1, 'Enclosure count is correct'); true;
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-<item>
-
-<media:content fileSize="24986239" type="video/mpeg" url="http://dallas.example.com/joebob_050689.mpeg" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/mrss_content2.xml b/toolkit/components/feeds/test/xml/rss2/mrss_content2.xml
deleted file mode 100644
index a0d740e69..000000000
--- a/toolkit/components/feeds/test/xml/rss2/mrss_content2.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: mrss content with a thumbnail
-Expect: var enc = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getPropertyAsInterface('mediacontent', Components.interfaces.nsIArray).queryElementAt(0, Components.interfaces.nsIPropertyBag); Assert.equal(enc.getProperty('fileSize'), '24986239', 'file size is correct'); Assert.equal(enc.getProperty('type'), 'video/mpeg', 'type is correct'); Assert.equal(enc.getProperty('url'), 'http://dallas.example.com/joebob_050689.mpeg', 'url is correct'); Assert.equal(feed.type, 0, 'Feed type is correct'); Assert.equal(feed.enclosureCount,2, 'Enclosure count is correct'); true;
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-<item>
-
-<media:content fileSize="24986239" type="video/mpeg" url="http://dallas.example.com/joebob_050689.mpeg" />
-<media:thumbnail url="http://dallas.example.com/joebob_050689.jpg" width="75" height="50"/>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/mrss_content_429049.xml b/toolkit/components/feeds/test/xml/rss2/mrss_content_429049.xml
deleted file mode 100644
index d13efc94c..000000000
--- a/toolkit/components/feeds/test/xml/rss2/mrss_content_429049.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: this tests bug 429049. the item with a valid url is added to the enclosures array and the item with an empty url does not.
-Expect: var encs = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).enclosures; encs.QueryInterface(Components.interfaces.nsIArray); (encs.length == 1);
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-
-<item>
-<media:content fileSize="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-<description>no description</description>
-</item>
-
-<item>
-<media:content url="" height="" width=""></media:content>
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test empty</title>
-
-<category domain="foo">bar</category>
-<description>no description</description>
-</item>
-
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/mrss_content_multiple.xml b/toolkit/components/feeds/test/xml/rss2/mrss_content_multiple.xml
deleted file mode 100644
index c391efdd2..000000000
--- a/toolkit/components/feeds/test/xml/rss2/mrss_content_multiple.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: mrss content with multiple media:content items works
-Expect: var mcs = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('mediacontent'); mcs.QueryInterface(Components.interfaces.nsIArray); var enc1 = mcs.queryElementAt(0, Components.interfaces.nsIPropertyBag); var enc2 = mcs.queryElementAt(1, Components.interfaces.nsIPropertyBag); ((enc1.getProperty('fileSize') == '24986239') && (enc1.getProperty('type') == 'video/mpeg') && (enc1.getProperty('url') == 'http://dallas.example.com/joebob_1.mpeg') && (enc2.getProperty('fileSize') == '30000000') && (enc2.getProperty('type') == 'video/mpeg') && (enc2.getProperty('url') == 'http://dallas.example.com/joebob_2.mpeg') && (feed.type == 4) && (feed.enclosureCount == 2));
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-<item>
-
-<media:content fileSize="24986239" type="video/mpeg" url="http://dallas.example.com/joebob_1.mpeg" />
-<media:content fileSize="30000000" type="video/mpeg" url="http://dallas.example.com/joebob_2.mpeg" />
-
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while. Two videos of that.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/mrss_content_populate_enclosure.xml b/toolkit/components/feeds/test/xml/rss2/mrss_content_populate_enclosure.xml
deleted file mode 100644
index f0718655f..000000000
--- a/toolkit/components/feeds/test/xml/rss2/mrss_content_populate_enclosure.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: mrss content added to enclosures array
-Expect: var encs = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).enclosures; encs.QueryInterface(Components.interfaces.nsIArray); var enc = encs.queryElementAt(0, Components.interfaces.nsIPropertyBag); ((enc.getProperty('length') == '24986239') && (enc.getProperty('type') == 'audio/mpeg') && (enc.getProperty('url') == 'http://dallas.example.com/joebob_050689.mp3') && (feed.type == 1) && (feed.enclosureCount == 1));
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-<item>
-
-<media:content fileSize="24986239" type="audio/mpeg" url="http://dallas.example.com/joebob_050689.mp3" />
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/mrss_group_content.xml b/toolkit/components/feeds/test/xml/rss2/mrss_group_content.xml
deleted file mode 100644
index da2ddb29c..000000000
--- a/toolkit/components/feeds/test/xml/rss2/mrss_group_content.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: mrss group content works
-Expect: var mg = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).fields.getProperty('mediagroup'); mg.QueryInterface(Components.interfaces.nsIPropertyBag); var mcs = mg.getProperty("mediacontent"); mcs.QueryInterface(Components.interfaces.nsIArray); var mc1 = mcs.queryElementAt(0, Components.interfaces.nsIPropertyBag); var mc2 = mcs.queryElementAt(1, Components.interfaces.nsIPropertyBag); ((mc1.getProperty('fileSize') == '400') && (mc1.getProperty('type') == 'audio/mpeg') && (mc1.getProperty('url') == 'http://dallas.example.com/joebob_050689_2.mp3') && (mc2.getProperty('fileSize') == '200') && (mc2.getProperty('type') == 'audio/mpeg') && (mc2.getProperty('url') == 'http://dallas.example.com/joebob_050689_1.mp3'));
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-<item>
-
-<media:group>
- <media:content fileSize="400" type="audio/mpeg" url="http://dallas.example.com/joebob_050689_2.mp3" />
- <media:content fileSize="200" type="audio/mpeg" url="http://dallas.example.com/joebob_050689_1.mp3" />
-</media:group>
-
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xml/rss2/mrss_group_content_populate_enclosure.xml b/toolkit/components/feeds/test/xml/rss2/mrss_group_content_populate_enclosure.xml
deleted file mode 100644
index f7b9ebabf..000000000
--- a/toolkit/components/feeds/test/xml/rss2/mrss_group_content_populate_enclosure.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!--
-
-Description: mrss group content works
-Expect: var encs = feed.items.queryElementAt(0, Components.interfaces.nsIFeedEntry).enclosures; encs.QueryInterface(Components.interfaces.nsIArray); var enc1 = encs.queryElementAt(0, Components.interfaces.nsIPropertyBag); var enc2 = encs.queryElementAt(1, Components.interfaces.nsIPropertyBag); ((enc1.getProperty('length') == '400') && (enc1.getProperty('type') == 'audio/mpeg') && (enc1.getProperty('url') == 'http://dallas.example.com/joebob_050689_2.mp3') && (enc2.getProperty('length') == '200') && (enc2.getProperty('type') == 'audio/mpeg') && (enc2.getProperty('url') == 'http://dallas.example.com/joebob_050689_1.mp3'));
-
-
--->
-<rss xmlns:media="http://search.yahoo.com/mrss" version="2.0" >
-<channel>
-<item>
-
-<media:group>
- <media:content fileSize="400" type="audio/mpeg" url="http://dallas.example.com/joebob_050689_2.mp3" />
- <media:content fileSize="200" type="audio/mpeg" url="http://dallas.example.com/joebob_050689_1.mp3" />
-</media:group>
-
-<author>jbb@dallas.example.com (Joe Bob Briggs)</author>
-<comments>http://example.org</comments>
-<title>test</title>
-
-<category domain="foo">bar</category>
-
-<description>I'm headed for France. I wasn't gonna go this year, but then last week &lt;a href="http://www.imdb.com/title/tt0086525/"&gt;Valley Girl&lt;/a&gt; came out and I said to myself, Joe Bob, you gotta get out of the country for a while.</description></item>
-</channel>
-</rss>
diff --git a/toolkit/components/feeds/test/xpcshell.ini b/toolkit/components/feeds/test/xpcshell.ini
deleted file mode 100644
index fbed5e559..000000000
--- a/toolkit/components/feeds/test/xpcshell.ini
+++ /dev/null
@@ -1,209 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-skip-if = toolkit == 'android'
-support-files =
- xml/rfc4287/author_namespaces.xml
- xml/rfc4287/entry_link_IANA.xml
- xml/rfc4287/feed_author_email_2.xml
- xml/rfc4287/feed_logo.xml
- xml/rfc4287/entry_author.xml
- xml/rfc4287/entry_link_otherURI_alt.xml
- xml/rfc4287/feed_author_email.xml
- xml/rfc4287/feed_random_attributes_on_feed_and_entry.xml
- xml/rfc4287/entry_content_encoded.xml
- xml/rfc4287/entry_link_payment_alt.xml
- xml/rfc4287/feed_author_name.xml
- xml/rfc4287/feed_rights_normalized.xml
- xml/rfc4287/entry_content_html.xml
- xml/rfc4287/entry_link_random.xml
- xml/rfc4287/feed_author_surrounded.xml
- xml/rfc4287/feed_rights_xhtml_nested_divs.xml
- xml/rfc4287/entry_content_xhtml_with_markup.xml
- xml/rfc4287/entry_published.xml
- xml/rfc4287/feed_author_uri.xml
- xml/rfc4287/feed_rights_xhtml.xml
- xml/rfc4287/entry_content_xhtml.xml
- xml/rfc4287/entry_rights_normalized.xml
- xml/rfc4287/feed_author.xml
- xml/rfc4287/feed_subtitle.xml
- xml/rfc4287/entry_content.xml
- xml/rfc4287/entry_summary.xml
- xml/rfc4287/feed_comment_rss_extra_att.xml
- xml/rfc4287/feed_tantek_title.xml
- xml/rfc4287/entry_contributor.xml
- xml/rfc4287/entry_title_normalized.xml
- xml/rfc4287/feed_contributor.xml
- xml/rfc4287/feed_title_full_feed.xml
- xml/rfc4287/entry_html_cdata.xml
- xml/rfc4287/entry_title.xml
- xml/rfc4287/feed_entry_count.xml
- xml/rfc4287/feed_title_xhtml_entities.xml
- xml/rfc4287/entry_id.xml
- xml/rfc4287/entry_updated.xml
- xml/rfc4287/feed_generator_uri.xml
- xml/rfc4287/feed_title_xhtml.xml
- xml/rfc4287/entry_link_2alts_allcore2.xml
- xml/rfc4287/entry_w_content_encoded.xml
- xml/rfc4287/feed_generator_uri_xmlbase.xml
- xml/rfc4287/feed_title.xml
- xml/rfc4287/entry_link_2alts_allcore.xml
- xml/rfc4287/entry_xhtml_baseURI_with_amp.xml
- xml/rfc4287/feed_generator_version.xml
- xml/rfc4287/feed_updated_invalid.xml
- xml/rfc4287/entry_link_2alts.xml
- xml/rfc4287/entry_xmlBase_on_link.xml
- xml/rfc4287/feed_generator.xml
- xml/rfc4287/feed_updated_normalized.xml
- xml/rfc4287/entry_link_alt_extension.xml
- xml/rfc4287/entry_xmlBase.xml
- xml/rfc4287/feed_icon.xml
- xml/rfc4287/feed_updated.xml
- xml/rfc4287/entry_link_enclosure_populate_enclosures.xml
- xml/rfc4287/feed_atom_rights_xhtml.xml
- xml/rfc4287/feed_id_extra_att.xml
- xml/rfc4287/feed_version.xml
- xml/rfc4287/entry_link_enclosure.xml
- xml/rfc4287/feed_author2.xml
- xml/rfc4287/feed_id.xml
- xml/rfc4287/feed_xmlBase.xml
- xml/rss09x/rss090.xml
- xml/rss09x/rss091_withNS.xml
- xml/rss09x/rss091.xml
- xml/rss09x/rss092.xml
- xml/rss09x/rss093.xml
- xml/rss09x/rss094.xml
- xml/rss09x/rssUnknown.xml
- xml/rss1/feed_bogus_title.xml
- xml/rss1/feed_description_normalized.xml
- xml/rss1/feed_description_with_dc_only.xml
- xml/rss1/feed_description_with_dc.xml
- xml/rss1/feed_description.xml
- xml/rss1/feed_generator.xml
- xml/rss1/feed_id.xml
- xml/rss1/feed_image.xml
- xml/rss1/feed_items_length_zero.xml
- xml/rss1/feed_link_normalized.xml
- xml/rss1/feed_link.xml
- xml/rss1/feed_textInput.xml
- xml/rss1/feed_title_extra_att.xml
- xml/rss1/feed_title_normalized.xml
- xml/rss1/feed_title.xml
- xml/rss1/feed_updated_dctermsmodified.xml
- xml/rss1/feed_updated.xml
- xml/rss1/feed_version.xml
- xml/rss1/full_feed_not_bozo.xml
- xml/rss1/full_feed_unknown_extension.xml
- xml/rss1/full_feed.xml
- xml/rss1/item_2_dc_description.xml
- xml/rss1/item_2_dc_publisher_extra_att_invalid_rdf.xml
- xml/rss1/item_2_dc_publisher.xml
- xml/rss1/item_count.xml
- xml/rss1/item_dc_creator.xml
- xml/rss1/item_dc_description_normalized.xml
- xml/rss1/item_dc_description.xml
- xml/rss1/item_description.xml
- xml/rss1/item_id.xml
- xml/rss1/item_link_normalized.xml
- xml/rss1/item_link.xml
- xml/rss1/item_title_normalized.xml
- xml/rss1/item_title.xml
- xml/rss1/item_updated_dcterms.xml
- xml/rss1/item_wiki_importance_extra_att.xml
- xml/rss2/feed_category_count.xml
- xml/rss2/feed_category.xml
- xml/rss2/feed_cloud.xml
- xml/rss2/feed_copyright_linebreak.xml
- xml/rss2/feed_copyright.xml
- xml/rss2/feed_data_outside_channel.xml
- xml/rss2/feed_dc_contributor.xml
- xml/rss2/feed_dc_creator.xml
- xml/rss2/feed_description_html_cdata.xml
- xml/rss2/feed_description_html.xml
- xml/rss2/feed_description.xml
- xml/rss2/feed_docs.xml
- xml/rss2/feed_generator.xml
- xml/rss2/feed_image_desc_width_height.xml
- xml/rss2/feed_image_desc.xml
- xml/rss2/feed_image_required.xml
- xml/rss2/feed_language.xml
- xml/rss2/feed_lastBuildDate.xml
- xml/rss2/feed_linebreak_link.xml
- xml/rss2/feed_link_cdata.xml
- xml/rss2/feed_link.xml
- xml/rss2/feed_managingEditor_extra_att.xml
- xml/rss2/feed_managingEditor.xml
- xml/rss2/feed_multiple_categories.xml
- xml/rss2/feed_pubDate_invalid.xml
- xml/rss2/feed_pubDate_nonRFC822_1.xml
- xml/rss2/feed_pubDate_nonRFC822_2.xml
- xml/rss2/feed_pubDate_timezoneZ.xml
- xml/rss2/feed_pubDate_utc.xml
- xml/rss2/feed_pubDate.xml
- xml/rss2/feed_rating.xml
- xml/rss2/feed_single_quote_stylesheet_pi.xml
- xml/rss2/feed_skipDays.xml
- xml/rss2/feed_skipHours.xml
- xml/rss2/feed_subtitle_html.xml
- xml/rss2/feed_subtitle_markup_stripped.xml
- xml/rss2/feed_subtitle.xml
- xml/rss2/feed_textinput.xml
- xml/rss2/feed_title_cdata_mixed.xml
- xml/rss2/feed_title_nesting.xml
- xml/rss2/feed_title.xml
- xml/rss2/feed_ttl.xml
- xml/rss2/feed_updated_dcdate.xml
- xml/rss2/feed_updated_lastBuildDate_priority.xml
- xml/rss2/feed_updated_lastBuildDate.xml
- xml/rss2/feed_updated.xml
- xml/rss2/feed_webMaster.xml
- xml/rss2/feed_wfw_commentapi.xml
- xml/rss2/feed_wfw_commentrss.xml
- xml/rss2/feed_wiki_unusual_prefix.xml
- xml/rss2/feed_wiki.xml
- xml/rss2/item_author.xml
- xml/rss2/item_category.xml
- xml/rss2/item_comments.xml
- xml/rss2/item_content_encoded.xml
- xml/rss2/item_count2.xml
- xml/rss2/item_count.xml
- xml/rss2/item_description_2.xml
- xml/rss2/item_description_cdata.xml
- xml/rss2/item_description_decode_entities.xml
- xml/rss2/item_description_normalized_nohtml.xml
- xml/rss2/item_description_normalized.xml
- xml/rss2/item_description.xml
- xml/rss2/item_enclosure_duplicates2.xml
- xml/rss2/item_enclosure_duplicates.xml
- xml/rss2/item_enclosure_mixed2.xml
- xml/rss2/item_enclosure_mixed.xml
- xml/rss2/item_enclosure.xml
- xml/rss2/item_guid_bogus_url.xml
- xml/rss2/item_guid_isPermaLink_default.xml
- xml/rss2/item_guid_isPermaLink_false_uppercase.xml
- xml/rss2/item_guid_isPermaLink_false.xml
- xml/rss2/item_guid_isPermaLink_true_uppercase.xml
- xml/rss2/item_guid_isPermaLink_unknown_value.xml
- xml/rss2/item_guid_isPermaLink.xml
- xml/rss2/item_guid_normalized.xml
- xml/rss2/item_guid_with_link.xml
- xml/rss2/item_guid.xml
- xml/rss2/item_link_normalized.xml
- xml/rss2/item_link.xml
- xml/rss2/item_plain_desc.xml
- xml/rss2/item_populated_enclosures.xml
- xml/rss2/item_pubDate.xml
- xml/rss2/item_published.xml
- xml/rss2/items_2_titles.xml
- xml/rss2/item_title_normalized.xml
- xml/rss2/item_title.xml
- xml/rss2/item_updated_dcdate.xml
- xml/rss2/mrss_content_429049.xml
- xml/rss2/mrss_content_multiple.xml
- xml/rss2/mrss_content_populate_enclosure.xml
- xml/rss2/mrss_content.xml
- xml/rss2/mrss_content2.xml
- xml/rss2/mrss_group_content_populate_enclosure.xml
- xml/rss2/mrss_group_content.xml
-
-[test_xml.js]
diff --git a/toolkit/components/filepicker/moz.build b/toolkit/components/filepicker/moz.build
index 0990cb00f..961912068 100644
--- a/toolkit/components/filepicker/moz.build
+++ b/toolkit/components/filepicker/moz.build
@@ -4,22 +4,16 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+XPIDL_SOURCES += ['nsIFileView.idl']
+
XPIDL_MODULE = 'filepicker'
-XPIDL_SOURCES += [
- 'nsIFileView.idl',
-]
-SOURCES += [
- 'nsFileView.cpp',
-]
-EXTRA_COMPONENTS += [
- 'nsFilePicker.js',
-]
-EXTRA_PP_COMPONENTS += [
- 'nsFilePicker.manifest',
-]
-XPCSHELL_TESTS_MANIFESTS += [
- 'test/unit/xpcshell.ini',
-]
+
+SOURCES += ['nsFileView.cpp']
+
+EXTRA_COMPONENTS += ['nsFilePicker.js']
+
+EXTRA_PP_COMPONENTS += ['nsFilePicker.manifest']
+
FINAL_LIBRARY = 'xul'
JAR_MANIFESTS += ['jar.mn']
diff --git a/toolkit/components/filepicker/test/unit/.eslintrc.js b/toolkit/components/filepicker/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/filepicker/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/filepicker/test/unit/test_filecomplete.js b/toolkit/components/filepicker/test/unit/test_filecomplete.js
deleted file mode 100644
index d1e18d533..000000000
--- a/toolkit/components/filepicker/test/unit/test_filecomplete.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/. */
-
-// Start by getting an empty directory.
-var dir = do_get_profile();
-dir.append("temp");
-dir.create(dir.DIRECTORY_TYPE, -1);
-var path = dir.path + "/";
-
-// Now create some sample entries.
-var file = dir.clone();
-file.append("test_file");
-file.create(file.NORMAL_FILE_TYPE, -1);
-file = dir.clone();
-file.append("other_file");
-file.create(file.NORMAL_FILE_TYPE, -1);
-dir.append("test_dir");
-dir.create(dir.DIRECTORY_TYPE, -1);
-
-var gListener = {
- onSearchResult: function(aSearch, aResult) {
- // Check that we got same search string back.
- do_check_eq(aResult.searchString, "test");
- // Check that the search succeeded.
- do_check_eq(aResult.searchResult, aResult.RESULT_SUCCESS);
- // Check that we got two results.
- do_check_eq(aResult.matchCount, 2);
- // Check that the first result is the directory we created.
- do_check_eq(aResult.getValueAt(0), "test_dir");
- // Check that the first result has directory style.
- do_check_eq(aResult.getStyleAt(0), "directory");
- // Check that the second result is the file we created.
- do_check_eq(aResult.getValueAt(1), "test_file");
- // Check that the second result has file style.
- do_check_eq(aResult.getStyleAt(1), "file");
- }
-};
-
-function run_test()
-{
- Components.classes["@mozilla.org/autocomplete/search;1?name=file"]
- .getService(Components.interfaces.nsIAutoCompleteSearch)
- .startSearch("test", path, null, gListener);
-}
diff --git a/toolkit/components/filepicker/test/unit/xpcshell.ini b/toolkit/components/filepicker/test/unit/xpcshell.ini
deleted file mode 100644
index 1a0a002dc..000000000
--- a/toolkit/components/filepicker/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[DEFAULT]
-head =
-tail =
-skip-if = toolkit == 'android'
-
-[test_filecomplete.js]
-skip-if = os != 'linux'
diff --git a/toolkit/components/filewatcher/moz.build b/toolkit/components/filewatcher/moz.build
index 5ce94b5d2..948a67bf9 100644
--- a/toolkit/components/filewatcher/moz.build
+++ b/toolkit/components/filewatcher/moz.build
@@ -4,20 +4,14 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
+XPIDL_MODULE = 'toolkit_filewatcher'
+
+XPIDL_SOURCES += ['nsINativeFileWatcher.idl']
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
EXPORTS += ['NativeFileWatcherWin.h']
- UNIFIED_SOURCES += [
- 'NativeFileWatcherWin.cpp',
- ]
+ UNIFIED_SOURCES += ['NativeFileWatcherWin.cpp']
else:
EXPORTS += ['NativeFileWatcherNotSupported.h']
-XPIDL_MODULE = 'toolkit_filewatcher'
-
-XPIDL_SOURCES += [
- 'nsINativeFileWatcher.idl',
-]
-
FINAL_LIBRARY = 'xul'
diff --git a/toolkit/components/filewatcher/tests/xpcshell/.eslintrc.js b/toolkit/components/filewatcher/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/filewatcher/tests/xpcshell/head.js b/toolkit/components/filewatcher/tests/xpcshell/head.js
deleted file mode 100644
index 73f8ac4f5..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/head.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";
-
-var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
-
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Promise.jsm", this);
-
-function makeWatcher() {
- let watcher =
- Cc['@mozilla.org/toolkit/filewatcher/native-file-watcher;1']
- .getService(Ci.nsINativeFileWatcherService);
- return watcher;
-}
-
-function promiseAddPath(watcher, resource, onChange=null, onError=null) {
- return new Promise(resolve =>
- watcher.addPath(resource, onChange, onError, resolve)
- );
-}
-
-function promiseRemovePath(watcher, resource, onChange=null, onError=null) {
- return new Promise(resolve =>
- watcher.removePath(resource, onChange, onError, resolve)
- );
-}
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_arguments.js b/toolkit/components/filewatcher/tests/xpcshell/test_arguments.js
deleted file mode 100644
index 7e62b1cb6..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_arguments.js
+++ /dev/null
@@ -1,79 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-
-/**
- * Test for addPath usage with null arguments.
- */
-add_task(function* test_null_args_addPath() {
-
- let watcher = makeWatcher();
- let testPath = 'someInvalidPath';
-
- // Define a dummy callback function. In this test no callback is
- // expected to be called.
- let dummyFunc = function(changed) {
- do_throw("Not expected in this test.");
- };
-
- // Check for error when passing a null first argument
- try {
- watcher.addPath(testPath, null, dummyFunc);
- } catch (ex) {
- if (ex.result != Cr.NS_ERROR_NULL_POINTER)
- throw ex;
- do_print("Initialisation thrown NS_ERROR_NULL_POINTER as expected.");
- }
-
- // Check for error when passing both null arguments
- try {
- watcher.addPath(testPath, null, null);
- } catch (ex) {
- if (ex.result != Cr.NS_ERROR_NULL_POINTER)
- throw ex;
- do_print("Initialisation thrown NS_ERROR_NULL_POINTER as expected.");
- }
-});
-
-/**
- * Test for removePath usage with null arguments.
- */
-add_task(function* test_null_args_removePath() {
-
- let watcher = makeWatcher();
- let testPath = 'someInvalidPath';
-
- // Define a dummy callback function. In this test no callback is
- // expected to be called.
- let dummyFunc = function(changed) {
- do_throw("Not expected in this test.");
- };
-
- // Check for error when passing a null first argument
- try {
- watcher.removePath(testPath, null, dummyFunc);
- } catch (ex) {
- if (ex.result != Cr.NS_ERROR_NULL_POINTER)
- throw ex;
- do_print("Initialisation thrown NS_ERROR_NULL_POINTER as expected.");
- }
-
- // Check for error when passing both null arguments
- try {
- watcher.removePath(testPath, null, null);
- } catch (ex) {
- if (ex.result != Cr.NS_ERROR_NULL_POINTER)
- throw ex;
- do_print("Initialisation thrown NS_ERROR_NULL_POINTER as expected.");
- }
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js b/toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js
deleted file mode 100644
index e5ceb33e5..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-
-/**
- * Test the component behaves correctly when no error callback is
- * provided and an error occurs.
- */
-add_task(function* test_error_with_no_error_callback() {
-
- let watcher = makeWatcher();
- let testPath = 'someInvalidPath';
-
- // Define a dummy callback function. In this test no callback is
- // expected to be called.
- let dummyFunc = function(changed) {
- do_throw("Not expected in this test.");
- };
-
- // We don't pass an error callback and try to watch an invalid
- // path.
- watcher.addPath(testPath, dummyFunc);
-});
-
-/**
- * Test the component behaves correctly when no error callback is
- * provided (no error should occur).
- */
-add_task(function* test_watch_single_path_file_creation_no_error_cb() {
-
- // Create and watch a sub-directory of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground");
- yield OS.File.makeDir(watchedDir);
-
- let tempFileName = "test_filecreation.tmp";
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Watch the profile directory but do not pass an error callback.
- yield promiseAddPath(watcher, watchedDir, deferred.resolve);
-
- // Create a file within the watched directory.
- let tmpFilePath = OS.Path.join(watchedDir, tempFileName);
- yield OS.File.writeAtomic(tmpFilePath, "some data");
-
- // Wait until the watcher informs us that the file was created.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpFilePath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' to unregister).
- watcher.removePath(watchedDir, deferred.resolve);
-
- // Remove the test directory and all of its content.
- yield OS.File.removeDir(watchedDir);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_remove_non_watched.js b/toolkit/components/filewatcher/tests/xpcshell/test_remove_non_watched.js
deleted file mode 100644
index 1375584a3..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_remove_non_watched.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";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-
-/**
- * Test removing non watched path
- */
-add_task(function* test_remove_not_watched() {
- let nonExistingDir =
- OS.Path.join(OS.Constants.Path.profileDir, "absolutelyNotExisting");
-
- // Instantiate the native watcher.
- let watcher = makeWatcher();
-
- // Try to un-watch a path which wasn't being watched.
- watcher.removePath(
- nonExistingDir,
- function(changed) {
- do_throw("No change is expected in this test.");
- },
- function(xpcomError, osError) {
- // When removing a resource which wasn't being watched, it should silently
- // ignore the request.
- do_throw("Unexpected exception: "
- + xpcomError + " (XPCOM) "
- + osError + " (OS Error)");
- }
- );
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_shared_callback.js b/toolkit/components/filewatcher/tests/xpcshell/test_shared_callback.js
deleted file mode 100644
index 482ba6b8b..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_shared_callback.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-
-/**
- * Test the watcher correctly handles two watches sharing the same
- * change callback.
- */
-add_task(function* test_watch_with_shared_callback() {
-
- // Create and watch two sub-directories of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDirs =
- [
- OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"),
- OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground2")
- ];
-
- yield OS.File.makeDir(watchedDirs[0]);
- yield OS.File.makeDir(watchedDirs[1]);
-
- let tempFileName = "test_filecreation.tmp";
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Watch both directories using the same callbacks.
- yield promiseAddPath(watcher, watchedDirs[0], deferred.resolve, deferred.reject);
- yield promiseAddPath(watcher, watchedDirs[1], deferred.resolve, deferred.reject);
-
- // Remove the watch for the first directory, but keep watching
- // for changes in the second: we need to make sure the callback
- // survives the removal of the first watch.
- watcher.removePath(watchedDirs[0], deferred.resolve, deferred.reject);
-
- // Create a file within the watched directory.
- let tmpFilePath = OS.Path.join(watchedDirs[1], tempFileName);
- yield OS.File.writeAtomic(tmpFilePath, "some data");
-
- // Wait until the watcher informs us that the file was created.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpFilePath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' and 'deferred.reject' to unregister).
- watcher.removePath(watchedDirs[1], deferred.resolve, deferred.reject);
-
- // Remove the test directories and all of their content.
- yield OS.File.removeDir(watchedDirs[0]);
- yield OS.File.removeDir(watchedDirs[1]);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_creation_single.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_creation_single.js
deleted file mode 100644
index a434ec751..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_creation_single.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";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files
- do_get_profile();
-
- // Start executing the tests
- run_next_test();
-}
-
-/**
- * Tests that the watcher correctly notifies of a directory creation when watching
- * a single path.
- */
-add_task(function* test_watch_single_path_directory_creation() {
-
- // Create and watch a sub-directory of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground");
- yield OS.File.makeDir(watchedDir);
-
- let tmpDirPath = OS.Path.join(watchedDir, "testdir");
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Add the profile directory to the watch list and wait for the file watcher
- // to start watching.
- yield promiseAddPath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Once ready, create a directory within the watched directory.
- yield OS.File.makeDir(tmpDirPath);
-
- // Wait until the watcher informs us that the file has changed.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpDirPath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' and 'deferred.reject' to unregister).
- yield promiseRemovePath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Clean up the test directory.
- yield OS.File.removeDir(watchedDir);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_deletion_single.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_deletion_single.js
deleted file mode 100644
index 2c74a9361..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_deletion_single.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";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-
-/**
- * Tests that the watcher correctly notifies of a directory deletion when watching
- * a single path.
- */
-add_task(function* test_watch_single_path_directory_deletion() {
-
- let watchedDir = OS.Constants.Path.profileDir;
- let tempDirName = "test";
- let tmpDirPath = OS.Path.join(watchedDir, tempDirName);
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Create a directory within the watched directory.
- yield OS.File.makeDir(tmpDirPath);
-
- // Add the profile directory to the watch list and wait for the file watcher
- // to start watching it.
- yield promiseAddPath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Remove the directory.
- OS.File.removeDir(tmpDirPath);
-
- // Wait until the watcher informs us that the file has changed.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpDirPath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' and 'deferred.reject' to unregister).
- yield promiseRemovePath(watcher, watchedDir, deferred.resolve, deferred.reject);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_creation_single.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_creation_single.js
deleted file mode 100644
index 9f87793f4..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_creation_single.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-
-/**
- * Test the watcher correctly notifies of a file creation when watching
- * a single path.
- */
-add_task(function* test_watch_single_path_file_creation() {
-
- // Create and watch a sub-directory of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground");
- yield OS.File.makeDir(watchedDir);
-
- let tempFileName = "test_filecreation.tmp";
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- let tmpFilePath = OS.Path.join(watchedDir, tempFileName);
-
- // Add the profile directory to the watch list and wait for the file watcher
- // to start watching.
- yield promiseAddPath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // create the file within the watched directory.
- yield OS.File.writeAtomic(tmpFilePath, "some data");
-
- // Wait until the watcher informs us that the file was created.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpFilePath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' and 'deferred.reject' to unregister).
- yield promiseRemovePath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Remove the test directory and all of its content.
- yield OS.File.removeDir(watchedDir);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js
deleted file mode 100644
index 97d2d61bc..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-/**
- * Test the watcher correctly notifies of a file deletion when watching
- * a single path.
- */
-add_task(function* test_watch_single_path_file_deletion() {
-
- // Create and watch a sub-directory of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground");
- yield OS.File.makeDir(watchedDir);
-
- let tempFileName = "test_filedeletion.tmp";
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Create a file within the directory to be watched. We do this
- // before watching the directory so we do not get the creation notification.
- let tmpFilePath = OS.Path.join(watchedDir, tempFileName);
- yield OS.File.writeAtomic(tmpFilePath, "some data");
-
- // Add the profile directory to the watch list and wait for the file watcher
- // to start watching it.
- yield promiseAddPath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Remove the file we created (should trigger a notification).
- do_print('Removing ' + tmpFilePath);
- yield OS.File.remove(tmpFilePath);
-
- // Wait until the watcher informs us that the file was deleted.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpFilePath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' and 'deferred.reject' to unregister).
- yield promiseRemovePath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Remove the test directory and all of its content.
- yield OS.File.removeDir(watchedDir);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_modification_single.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_modification_single.js
deleted file mode 100644
index ba25fdff6..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_modification_single.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files
- do_get_profile();
-
- // Start executing the tests
- run_next_test();
-}
-
-/**
- * Tests that the watcher correctly notifies of a file modification when watching
- * a single path.
- */
-add_task(function* test_watch_single_path_file_modification() {
-
- // Create and watch a sub-directory of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground");
- yield OS.File.makeDir(watchedDir);
-
- let tempFileName = "test_filemodification.tmp";
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Create a file within the directory to be watched. We do this
- // before watching the directory so we do not get the creation notification.
- let tmpFilePath = OS.Path.join(watchedDir, tempFileName);
- yield OS.File.writeAtomic(tmpFilePath, "some data");
-
- // Add the profile directory to the watch list and wait for the file watcher
- // to start watching it.
- yield promiseAddPath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Once ready, modify the file to trigger the notification.
- yield OS.File.writeAtomic(tmpFilePath, "some new data");
-
- // Wait until the watcher informs us that the file has changed.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpFilePath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' and 'deferred.reject' to unregister).
- yield promiseRemovePath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Remove the test directory and all of its content.
- yield OS.File.removeDir(watchedDir);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_many_changes.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_many_changes.js
deleted file mode 100644
index c236c6e1d..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_many_changes.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files
- do_get_profile();
-
- // Start executing the tests
- run_next_test();
-}
-
-/**
- * Test that we correctly handle watching directories when hundreds of files
- * change simultaneously.
- */
-add_task(function* test_fill_notification_buffer() {
-
- // Create and watch a sub-directory of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground");
- yield OS.File.makeDir(watchedDir);
-
- // The number of files to create.
- let numberOfFiles = 100;
- let fileNameBase = "testFile";
-
- // This will be used to keep track of the number of changes within the watched
- // directory.
- let detectedChanges = 0;
-
- // We expect at least the following notifications for each file:
- // - File creation
- // - File deletion
- let expectedChanges = numberOfFiles * 2;
-
- // Instantiate the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Initialise the change callback.
- let changeCallback = function(changed) {
- do_print(changed + " has changed.");
-
- detectedChanges += 1;
-
- // Resolve the promise if we get all the expected changes.
- if (detectedChanges >= expectedChanges) {
- deferred.resolve();
- }
- };
-
- // Add the profile directory to the watch list and wait for the file watcher
- // to start watching it.
- yield promiseAddPath(watcher, watchedDir, changeCallback, deferred.reject);
-
- // Create and then remove the files within the watched directory.
- for (let i = 0; i < numberOfFiles; i++) {
- let tmpFilePath = OS.Path.join(watchedDir, fileNameBase + i);
- yield OS.File.writeAtomic(tmpFilePath, "test content");
- yield OS.File.remove(tmpFilePath);
- }
-
- // Wait until the watcher informs us that all the files were
- // created, modified and removed.
- yield deferred.promise;
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'changeCallback' and 'errorCallback' to unregister).
- yield promiseRemovePath(watcher, watchedDir, changeCallback, deferred.reject);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_multi_paths.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_multi_paths.js
deleted file mode 100644
index c55b262f1..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_multi_paths.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files
- do_get_profile();
-
- // Start executing the tests
- run_next_test();
-}
-
-/**
- * Tests the watcher by watching several resources.
- * This test creates the specified number of directory inside the profile
- * directory, adds each one of them to the watched list the creates
- * a file in them in order to trigger the notification.
- * The test keeps track of the number of times the changes callback is
- * called in order to verify the success of the test.
- */
-add_task(function* test_watch_multi_paths() {
-
- // The number of resources to watch. We expect changes for
- // creating a file within each directory.
- let resourcesToWatch = 5;
- let watchedDir = OS.Constants.Path.profileDir;
-
- // The directories to be watched will be created with.
- let tempDirNameBase = "FileWatcher_Test_";
- let tempFileName = "test.tmp";
-
- // Instantiate the native watcher.
- let watcher = makeWatcher();
-
- // This will be used to keep track of the number of changes within the watched
- // resources.
- let detectedChanges = 0;
- let watchedResources = 0;
- let unwatchedResources = 0;
-
- let deferredChanges = Promise.defer();
- let deferredSuccesses = Promise.defer();
- let deferredShutdown = Promise.defer();
-
- // Define the change callback function.
- let changeCallback = function(changed) {
- do_print(changed + " has changed.");
-
- detectedChanges += 1;
-
- // Resolve the promise if we get all the expected changes.
- if (detectedChanges === resourcesToWatch) {
- deferredChanges.resolve();
- }
- };
-
- // Define the watch success callback function.
- let watchSuccessCallback = function(resourcePath) {
- do_print(resourcePath + " is being watched.");
-
- watchedResources += 1;
-
- // Resolve the promise when all the resources are being
- // watched.
- if (watchedResources === resourcesToWatch) {
- deferredSuccesses.resolve();
- }
- };
-
- // Define the watch success callback function.
- let unwatchSuccessCallback = function(resourcePath) {
- do_print(resourcePath + " is being un-watched.");
-
- unwatchedResources += 1;
-
- // Resolve the promise when all the resources are being
- // watched.
- if (unwatchedResources === resourcesToWatch) {
- deferredShutdown.resolve();
- }
- };
-
- // Create the directories and add them to the watched resources list.
- for (let i = 0; i < resourcesToWatch; i++) {
- let tmpSubDirPath = OS.Path.join(watchedDir, tempDirNameBase + i);
- do_print("Creating the " + tmpSubDirPath + " directory.");
- yield OS.File.makeDir(tmpSubDirPath);
- watcher.addPath(tmpSubDirPath, changeCallback, deferredChanges.reject, watchSuccessCallback);
- }
-
- // Wait until the watcher informs us that all the desired resources
- // are being watched.
- yield deferredSuccesses.promise;
-
- // Create a file within each watched directory.
- for (let i = 0; i < resourcesToWatch; i++) {
- let tmpFilePath = OS.Path.join(watchedDir, tempDirNameBase + i, tempFileName);
- yield OS.File.writeAtomic(tmpFilePath, "test content");
- }
-
- // Wait until the watcher informs us that all the files were created.
- yield deferredChanges.promise;
-
- // Remove the directories we have created.
- for (let i = 0; i < resourcesToWatch; i++) {
- let tmpSubDirPath = OS.Path.join(watchedDir, tempDirNameBase + i);
- watcher.removePath(tmpSubDirPath, changeCallback, deferredChanges.reject, unwatchSuccessCallback);
- }
-
- // Wait until the watcher un-watches the resources.
- yield deferredShutdown.promise;
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_recursively.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_recursively.js
deleted file mode 100644
index 13a3de8d3..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_recursively.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files.
- do_get_profile();
-
- // Start executing the tests.
- run_next_test();
-}
-
-/**
- * Test the watcher correctly notifies of a file creation in a subdirectory
- * of the watched sub-directory (recursion).
- */
-add_task(function* test_watch_recursively() {
-
- // Create and watch a sub-directory of the profile directory so we don't
- // catch notifications we're not interested in (i.e. "startupCache").
- let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground");
- yield OS.File.makeDir(watchedDir);
-
- // We need at least 2 levels of directories to test recursion.
- let subdirectory = OS.Path.join(watchedDir, "level1");
- yield OS.File.makeDir(subdirectory);
-
- let tempFileName = "test_filecreation.tmp";
-
- // Instantiate and initialize the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- let tmpFilePath = OS.Path.join(subdirectory, tempFileName);
-
- // Add the profile directory to the watch list and wait for the file watcher
- // to start watching it.
- yield promiseAddPath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Create a file within the subdirectory of the watched directory.
- yield OS.File.writeAtomic(tmpFilePath, "some data");
-
- // Wait until the watcher informs us that the file was created.
- let changed = yield deferred.promise;
- do_check_eq(changed, tmpFilePath);
-
- // Remove the watch and free the associated memory (we need to
- // reuse 'deferred.resolve' and 'deferred.reject' to unregister).
- yield promiseRemovePath(watcher, watchedDir, deferred.resolve, deferred.reject);
-
- // Remove the test directory and all of its content.
- yield OS.File.removeDir(watchedDir);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/test_watch_resource.js b/toolkit/components/filewatcher/tests/xpcshell/test_watch_resource.js
deleted file mode 100644
index fffdff24b..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_resource.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";
-
-function run_test() {
- // Set up profile. We will use profile path create some test files
- do_get_profile();
-
- // Start executing the tests
- run_next_test();
-}
-
-/**
- * Test watching non-existing path
- */
-add_task(function* test_watching_non_existing() {
- let notExistingDir =
- OS.Path.join(OS.Constants.Path.profileDir, "absolutelyNotExisting");
-
- // Instantiate the native watcher.
- let watcher = makeWatcher();
- let deferred = Promise.defer();
-
- // Try watch a path which doesn't exist.
- watcher.addPath(notExistingDir, deferred.reject, deferred.resolve);
-
- // Wait until the watcher informs us that there was an error.
- let error = yield deferred.promise;
- do_check_eq(error, Components.results.NS_ERROR_FILE_NOT_FOUND);
-});
diff --git a/toolkit/components/filewatcher/tests/xpcshell/xpcshell.ini b/toolkit/components/filewatcher/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index d6cc968eb..000000000
--- a/toolkit/components/filewatcher/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,18 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-skip-if = os != "win"
-
-[test_arguments.js]
-[test_no_error_callback.js]
-[test_remove_non_watched.js]
-[test_shared_callback.js]
-[test_watch_file_creation_single.js]
-[test_watch_file_deletion_single.js]
-[test_watch_file_modification_single.js]
-[test_watch_directory_creation_single.js]
-[test_watch_directory_deletion_single.js]
-[test_watch_many_changes.js]
-[test_watch_multi_paths.js]
-[test_watch_recursively.js]
-[test_watch_resource.js]
diff --git a/toolkit/components/formautofill/moz.build b/toolkit/components/formautofill/moz.build
index 2c2179f81..3dfc58281 100644
--- a/toolkit/components/formautofill/moz.build
+++ b/toolkit/components/formautofill/moz.build
@@ -4,22 +4,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-if CONFIG['NIGHTLY_BUILD']:
- BROWSER_CHROME_MANIFESTS += [
- 'test/browser/browser.ini',
- ]
-
- MOCHITEST_CHROME_MANIFESTS += [
- 'test/chrome/chrome.ini',
- ]
-
-XPCSHELL_TESTS_MANIFESTS += [
- 'test/xpcshell/xpcshell.ini',
-]
-
-XPIDL_SOURCES += [
- 'nsIFormAutofillContentService.idl',
-]
+XPIDL_SOURCES += ['nsIFormAutofillContentService.idl']
XPIDL_MODULE = 'toolkit_formautofill'
@@ -28,9 +13,7 @@ EXTRA_COMPONENTS += [
'FormAutofillStartup.js',
]
-EXTRA_PP_COMPONENTS += [
- 'formautofill.manifest',
-]
+EXTRA_PP_COMPONENTS += ['formautofill.manifest']
EXTRA_JS_MODULES += [
'content/RequestAutocompleteUI.jsm',
@@ -38,9 +21,4 @@ EXTRA_JS_MODULES += [
'FormAutofillIntegration.jsm',
]
-JAR_MANIFESTS += [
- 'jar.mn',
-]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Form Manager')
+JAR_MANIFESTS += ['jar.mn']
diff --git a/toolkit/components/formautofill/test/browser/.eslintrc.js b/toolkit/components/formautofill/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/formautofill/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/formautofill/test/browser/browser.ini b/toolkit/components/formautofill/test/browser/browser.ini
deleted file mode 100644
index dff9c3381..000000000
--- a/toolkit/components/formautofill/test/browser/browser.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-# The following files starting with ".." are installed in the current folder.
-support-files =
- ../head_common.js
- ../loader_common.js
- head.js
- loader.js
-
-[browser_infrastructure.js]
-[browser_ui_requestAutocomplete.js]
diff --git a/toolkit/components/formautofill/test/browser/browser_infrastructure.js b/toolkit/components/formautofill/test/browser/browser_infrastructure.js
deleted file mode 100644
index af27cfdb5..000000000
--- a/toolkit/components/formautofill/test/browser/browser_infrastructure.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests the local testing infrastructure.
- */
-
-"use strict";
-
-/**
- * Tests the truth assertion function.
- */
-add_task(function* test_assert_truth() {
- Assert.ok(1 != 2);
-});
-
-/**
- * Tests the equality assertion function.
- */
-add_task(function* test_assert_equality() {
- Assert.equal(1 + 1, 2);
-});
-
-/**
- * Uses some of the utility functions provided by the framework.
- */
-add_task(function* test_utility_functions() {
- // The "print" function is useful to log information that is not known before.
- let randomString = "R" + Math.floor(Math.random() * 10);
- Output.print("The random contents will be '" + randomString + "'.");
-
- // Create the text file with the random contents.
- let path = yield TestUtils.getTempFile("test-infrastructure.txt");
- yield OS.File.writeAtomic(path, new TextEncoder().encode(randomString));
-
- // Test a few utility functions.
- yield TestUtils.waitForTick();
- yield TestUtils.waitMs(50);
-
- let promiseMyNotification = TestUtils.waitForNotification("my-topic");
- Services.obs.notifyObservers(null, "my-topic", "");
- yield promiseMyNotification;
-
- // Check the file size. The file will be deleted automatically later.
- Assert.equal((yield OS.File.stat(path)).size, randomString.length);
-});
-
-add_task(terminationTaskFn);
diff --git a/toolkit/components/formautofill/test/browser/browser_ui_requestAutocomplete.js b/toolkit/components/formautofill/test/browser/browser_ui_requestAutocomplete.js
deleted file mode 100644
index 2a7b58f12..000000000
--- a/toolkit/components/formautofill/test/browser/browser_ui_requestAutocomplete.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests the requestAutocomplete user interface.
- */
-
-"use strict";
-
-/**
- * Open the requestAutocomplete UI and test that selecting a profile results in
- * the correct data being sent back to the opener.
- */
-add_task(function* test_select_profile() {
- // Request an e-mail address.
- let { uiWindow, promiseResult } = yield FormAutofillTest.showUI(
- TestData.requestEmailOnly);
-
- // Accept the dialog.
- let acceptButton = uiWindow.document.getElementById("accept");
- EventUtils.synthesizeMouseAtCenter(acceptButton, {}, uiWindow);
-
- let result = yield promiseResult;
- Assert.equal(result.fields.length, 1);
- Assert.equal(result.fields[0].section, "");
- Assert.equal(result.fields[0].addressType, "");
- Assert.equal(result.fields[0].contactType, "");
- Assert.equal(result.fields[0].fieldName, "email");
- Assert.equal(result.fields[0].value, "email@example.org");
-});
-
-/**
- * Open the requestAutocomplete UI and cancel the dialog.
- */
-add_task(function* test_cancel() {
- // Request an e-mail address.
- let { uiWindow, promiseResult } = yield FormAutofillTest.showUI(
- TestData.requestEmailOnly);
-
- // Cancel the dialog.
- let acceptButton = uiWindow.document.getElementById("cancel");
- EventUtils.synthesizeMouseAtCenter(acceptButton, {}, uiWindow);
-
- let result = yield promiseResult;
- Assert.ok(result.canceled);
-});
-
-add_task(terminationTaskFn);
diff --git a/toolkit/components/formautofill/test/browser/head.js b/toolkit/components/formautofill/test/browser/head.js
deleted file mode 100644
index 882f3fd5e..000000000
--- a/toolkit/components/formautofill/test/browser/head.js
+++ /dev/null
@@ -1,18 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Initialization specific to Form Autofill mochitest-browser tests.
- */
-
-"use strict";
-
-// We cannot start initialization from "loader.js" like we do in the xpcshell
-// and mochitest-chrome frameworks, thus we load the script here.
-Services.scriptloader.loadSubScript(getRootDirectory(gTestPath) + "loader.js",
- this);
-
-// The testing framework is fully initialized at this point, you can add
-// mochitest-browser specific test initialization here. If you need shared
-// functions or initialization that are not specific to mochitest-browser,
-// consider adding them to "head_common.js" in the parent folder instead.
diff --git a/toolkit/components/formautofill/test/browser/loader.js b/toolkit/components/formautofill/test/browser/loader.js
deleted file mode 100644
index bfd5b9ee0..000000000
--- a/toolkit/components/formautofill/test/browser/loader.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Infrastructure for the mochitest-browser tests located in this folder.
- *
- * See "loader_common.js" in the parent folder for a general overview.
- *
- * Unless you are adding new features to the framework, you shouldn't have to
- * modify this file. Use "head_common.js" or "head.js" for shared code.
- */
-
-"use strict";
-
-Services.scriptloader.loadSubScript(getRootDirectory(gTestPath) +
- "loader_common.js", this);
-
-// Define output functions so they look the same across all frameworks.
-var Output = {
- print: info,
-};
-
-// Define assertion functions so they look the same across all frameworks.
-var Assert = {
- ok: _mochitestAssert.ok,
- equal: _mochitestAssert.equal,
-};
-
-// Define task registration functions, see description in "loader_common.js".
-var add_task_in_parent_process = add_task;
-var add_task_in_child_process = function () {};
-var add_task_in_both_processes = add_task;
-
-Services.scriptloader.loadSubScript(getRootDirectory(gTestPath) +
- "head_common.js", this);
-
-// Reminder: unless you are adding new features to the framework, you shouldn't
-// have to modify this file. Use "head_common.js" or "head.js" for shared code.
diff --git a/toolkit/components/formautofill/test/chrome/.eslintrc.js b/toolkit/components/formautofill/test/chrome/.eslintrc.js
deleted file mode 100644
index 8c0f4f574..000000000
--- a/toolkit/components/formautofill/test/chrome/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/formautofill/test/chrome/chrome.ini b/toolkit/components/formautofill/test/chrome/chrome.ini
deleted file mode 100644
index 67b7869af..000000000
--- a/toolkit/components/formautofill/test/chrome/chrome.ini
+++ /dev/null
@@ -1,17 +0,0 @@
-[DEFAULT]
-# The following files starting with ".." are installed in the current folder.
-support-files =
- ../head_common.js
- ../loader_common.js
- head.js
- test_infrastructure.js
- test_requestAutocomplete_cancel.js
- loader_parent.js
- loader.js
-
-# For each test defined below, the associated JavaScript file must be declared
-# in the list above. This is required because a "support-files" declaration on
-# the individual test would override the global list instead of adding entries.
-
-[test_infrastructure.html]
-[test_requestAutocomplete_cancel.html]
diff --git a/toolkit/components/formautofill/test/chrome/head.js b/toolkit/components/formautofill/test/chrome/head.js
deleted file mode 100644
index 4110d5e7c..000000000
--- a/toolkit/components/formautofill/test/chrome/head.js
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Initialization specific to Form Autofill mochitest-chrome tests.
- *
- * This file is loaded by "loader.js".
- */
-
-"use strict";
-
-// The testing framework is fully initialized at this point, you can add
-// mochitest-chrome specific test initialization here. If you need shared
-// functions or initialization that are not specific to mochitest-chrome,
-// consider adding them to "head_common.js" in the parent folder instead.
diff --git a/toolkit/components/formautofill/test/chrome/loader.js b/toolkit/components/formautofill/test/chrome/loader.js
deleted file mode 100644
index 25b0e6ea3..000000000
--- a/toolkit/components/formautofill/test/chrome/loader.js
+++ /dev/null
@@ -1,116 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Infrastructure for the mochitest-chrome tests located in this folder.
- *
- * See "loader_common.js" in the parent folder for a general overview.
- *
- * Unless you are adding new features to the framework, you shouldn't have to
- * modify this file. Use "head_common.js" or "head.js" for shared code.
- */
-
-"use strict";
-
-var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-Services.scriptloader.loadSubScript(
- "chrome://mochikit/content/tests/SimpleTest/SimpleTest.js", this);
-
-var sharedUrl = SimpleTest.getTestFileURL("loader_common.js");
-Services.scriptloader.loadSubScript(sharedUrl, this);
-
-var parentScript = SpecialPowers.loadChromeScript(
- SimpleTest.getTestFileURL("loader_parent.js"));
-
-// Replace the extension of the loaded HTML file with ".js"
-var testUrl = location.href.replace(/\.\w+$/, ".js");
-
-// Start loading the test script in the parent process.
-var promiseParentInitFinished = new Promise(function (resolve) {
- parentScript.addMessageListener("finish_load_in_parent", resolve);
-});
-parentScript.sendAsyncMessage("start_load_in_parent", { testUrl: testUrl });
-
-// Define output functions so they look the same across all frameworks.
-var Output = {
- print: info,
-};
-
-// Define assertion functions so they look the same across all frameworks.
-var Assert = {
- ok: _mochitestAssert.ok,
- equal: _mochitestAssert.equal,
-};
-
-var executeSoon = SimpleTest.executeSoon;
-
-var gTestTasks = [];
-
-// Define task registration functions, see description in "loader_common.js".
-function add_task(taskFn) {
- gTestTasks.push([taskFn, "content", taskFn.name]);
-}
-function add_task_in_parent_process(taskFn, taskIdOverride) {
- let taskId = taskIdOverride || getTaskId(Components.stack.caller);
- gTestTasks.push([taskFn, "parent", taskId]);
-}
-function add_task_in_both_processes(taskFn) {
- // We need to define a task ID based on our direct caller.
- add_task_in_parent_process(taskFn, getTaskId(Components.stack.caller));
- add_task(taskFn);
-}
-var add_task_in_child_process = add_task;
-
-window.addEventListener("load", function onLoad() {
- window.removeEventListener("load", onLoad);
-
- Task.spawn(function* () {
- try {
- for (let [taskFn, taskType, taskId] of gTestTasks) {
- if (taskType == "content") {
- // This is a normal task executed in the current process.
- info("Running " + taskFn.name);
- yield Task.spawn(taskFn);
- } else {
- // This is a task executed in the parent process.
- info("Running task in parent process: " + taskFn.name);
- let promiseFinished = new Promise(function (resolve) {
- parentScript.addMessageListener("finish_task_" + taskId, resolve);
- });
- parentScript.sendAsyncMessage("start_task_" + taskId);
- yield promiseFinished;
- info("Finished task in parent process: " + taskFn.name);
- }
- }
- } catch (ex) {
- ok(false, ex);
- }
-
- SimpleTest.finish();
- });
-});
-
-// Wait for the test script to be loaded in the parent process. This means that
-// test tasks are registered and ready, but have not been executed yet.
-add_task(function* wait_loading_in_parent_process() {
- yield promiseParentInitFinished;
-});
-
-var headUrl = SimpleTest.getTestFileURL("head_common.js");
-Services.scriptloader.loadSubScript(headUrl, this);
-
-Output.print("Loading test file: " + testUrl);
-Services.scriptloader.loadSubScript(testUrl, this);
-
-// Register the execution of termination tasks after all other tasks.
-add_task(terminationTaskFn);
-add_task_in_parent_process(terminationTaskFn, terminationTaskFn.name);
-
-SimpleTest.waitForExplicitFinish();
-
-// Reminder: unless you are adding new features to the framework, you shouldn't
-// have to modify this file. Use "head_common.js" or "head.js" for shared code.
diff --git a/toolkit/components/formautofill/test/chrome/loader_parent.js b/toolkit/components/formautofill/test/chrome/loader_parent.js
deleted file mode 100644
index bf823218e..000000000
--- a/toolkit/components/formautofill/test/chrome/loader_parent.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Infrastructure for the mochitest-chrome tests located in this folder, always
- * executed in the parent process.
- *
- * See "loader_common.js" in the parent folder for a general overview.
- *
- * Unless you are adding new features to the framework, you shouldn't have to
- * modify this file. Use "head_common.js" or "head.js" for shared code.
- */
-
-"use strict";
-
-var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-var sharedUrl = "chrome://mochitests/content/chrome/" +
- "toolkit/components/formautofill/test/chrome/loader_common.js";
-Services.scriptloader.loadSubScript(sharedUrl, this);
-
-// Define output functions so they look the same across all frameworks. Since
-// we don't have an output function available here, we report as TEST-PASS.
-var Output = {
- print: message => assert.ok(true, message),
-};
-
-// Define assertion functions so they look the same across all frameworks.
-var Assert = {
- ok: assert.ok,
- equal: assert.equal,
-};
-
-// Define task registration functions, see description in "loader_common.js".
-function add_task_in_parent_process(taskFn, taskIdOverride) {
- let taskId = taskIdOverride || getTaskId(Components.stack.caller);
- Output.print("Registering in the parent process: " + taskId);
- addMessageListener("start_task_" + taskId, function () {
- Task.spawn(function* () {
- try {
- Output.print("Running in the parent process " + taskId);
- yield Task.spawn(taskFn);
- } catch (ex) {
- assert.ok(false, ex);
- }
-
- sendAsyncMessage("finish_task_" + taskId, {});
- });
- });
-}
-var add_task = function () {};
-var add_task_in_child_process = function () {};
-var add_task_in_both_processes = add_task_in_parent_process;
-
-// We need to wait for the child process to send us the path of the test file
-// to load before we can actually start loading it.
-var context = this;
-addMessageListener("start_load_in_parent", function (message) {
- Output.print("Starting loading infrastructure in parent process.");
- let headUrl = "chrome://mochitests/content/chrome/" +
- "toolkit/components/formautofill/test/chrome/head_common.js";
- Services.scriptloader.loadSubScript(headUrl, context);
-
- Services.scriptloader.loadSubScript(message.testUrl, context);
-
- // Register the execution of termination tasks after all other tasks.
- add_task_in_parent_process(terminationTaskFn, terminationTaskFn.name);
-
- Output.print("Finished loading infrastructure in parent process.");
- sendAsyncMessage("finish_load_in_parent", {});
-});
-
-// Reminder: unless you are adding new features to the framework, you shouldn't
-// have to modify this file. Use "head_common.js" or "head.js" for shared code.
diff --git a/toolkit/components/formautofill/test/chrome/test_infrastructure.html b/toolkit/components/formautofill/test/chrome/test_infrastructure.html
deleted file mode 100644
index 54f417f77..000000000
--- a/toolkit/components/formautofill/test/chrome/test_infrastructure.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<script type="application/javascript;version=1.7" src="loader.js"></script>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<p id="paragraph">Paragraph contents.</p>
-
-</body></html>
diff --git a/toolkit/components/formautofill/test/chrome/test_infrastructure.js b/toolkit/components/formautofill/test/chrome/test_infrastructure.js
deleted file mode 100644
index c3b0b43ff..000000000
--- a/toolkit/components/formautofill/test/chrome/test_infrastructure.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests the local testing infrastructure.
- */
-
-"use strict";
-
-/**
- * Tests the truth assertion function.
- */
-add_task(function* test_assert_truth() {
- Assert.ok(1 != 2);
-});
-
-/**
- * Tests the equality assertion function.
- */
-add_task(function* test_assert_equality() {
- Assert.equal(1 + 1, 2);
-});
-
-/**
- * Uses some of the utility functions provided by the framework.
- */
-add_task(function* test_utility_functions() {
- // The "print" function is useful to log information that is not known before.
- let randomString = "R" + Math.floor(Math.random() * 10);
- Output.print("The random contents will be '" + randomString + "'.");
-
- // Create the text file with the random contents.
- let path = yield TestUtils.getTempFile("test-infrastructure.txt");
- yield OS.File.writeAtomic(path, new TextEncoder().encode(randomString));
-
- // Test a few utility functions.
- yield TestUtils.waitForTick();
- yield TestUtils.waitMs(50);
-
- let promiseMyNotification = TestUtils.waitForNotification("my-topic");
- Services.obs.notifyObservers(null, "my-topic", "");
- yield promiseMyNotification;
-
- // Check the file size. The file will be deleted automatically later.
- Assert.equal((yield OS.File.stat(path)).size, randomString.length);
-});
-
-/**
- * This type of test has access to the content declared above.
- */
-add_task(function* test_content() {
- Assert.equal($("paragraph").innerHTML, "Paragraph contents.");
-
- let promiseMyEvent = TestUtils.waitForEvent($("paragraph"), "MyEvent");
-
- let event = document.createEvent("CustomEvent");
- event.initCustomEvent("MyEvent", true, false, {});
- $("paragraph").dispatchEvent(event);
-
- yield promiseMyEvent;
-});
diff --git a/toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.html b/toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.html
deleted file mode 100644
index 8ae7ffd4b..000000000
--- a/toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<script type="application/javascript;version=1.7" src="loader.js"></script>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<form id="form">
-</form>
-
-</body></html>
diff --git a/toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.js b/toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.js
deleted file mode 100644
index 1ee12bd9a..000000000
--- a/toolkit/components/formautofill/test/chrome/test_requestAutocomplete_cancel.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests the response sent when requestAutocomplete is canceled by the user.
- */
-
-"use strict";
-
-/**
- * The requestAutocomplete UI will not be displayed during these tests.
- */
-add_task_in_parent_process(function* test_cancel_init() {
- FormAutofillTest.requestAutocompleteResponse = { canceled: true };
-});
-
-/**
- * Tests the case where the feature is canceled.
- */
-add_task(function* test_cancel() {
- let promise = TestUtils.waitForEvent($("form"), "autocompleteerror");
- $("form").requestAutocomplete();
- let errorEvent = yield promise;
-
- Assert.equal(errorEvent.reason, "cancel");
-});
diff --git a/toolkit/components/formautofill/test/head_common.js b/toolkit/components/formautofill/test/head_common.js
deleted file mode 100644
index 82b87e4a6..000000000
--- a/toolkit/components/formautofill/test/head_common.js
+++ /dev/null
@@ -1,245 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Initialization of Form Autofill tests shared between all frameworks.
- *
- * A copy of this file is installed in each of the framework subfolders, this
- * means it becomes a sibling of the test files in the final layout. This is
- * determined by how manifest "support-files" installation works.
- */
-
-"use strict";
-
-// The requestAutocomplete framework is available at this point, you can add
-// mochitest-chrome specific test initialization here. If you need shared
-// functions or initialization that are not specific to mochitest-chrome,
-// consider adding them to "head_common.js" in the parent folder instead.
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths",
- "resource://gre/modules/DownloadPaths.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FormAutofill",
- "resource://gre/modules/FormAutofill.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-
-/* --- Global helpers --- */
-
-// Some of these functions are already implemented in other parts of the source
-// tree, see bug 946708 about sharing more code.
-
-var TestUtils = {
- /**
- * Waits for at least one tick of the event loop. This means that all pending
- * events at the time of this call will have been processed. Other events may
- * be processed before the returned promise is resolved.
- *
- * @return {Promise}
- * @resolves When pending events have been processed.
- * @rejects Never.
- */
- waitForTick: function () {
- return new Promise(resolve => executeSoon(resolve));
- },
-
- /**
- * Waits for the specified timeout.
- *
- * @param aTimeMs
- * Minimum time to wait from the moment of this call, in milliseconds.
- * The actual wait may be longer, due to system timer resolution and
- * pending events being processed before the promise is resolved.
- *
- * @return {Promise}
- * @resolves When the specified time has passed.
- * @rejects Never.
- */
- waitMs: function (aTimeMs) {
- return new Promise(resolve => setTimeout(resolve, aTimeMs));
- },
-
- /**
- * Allows waiting for an observer notification once.
- *
- * @param aTopic
- * Notification topic to observe.
- *
- * @return {Promise}
- * @resolves The array [aSubject, aData] from the observed notification.
- * @rejects Never.
- */
- waitForNotification: function (aTopic) {
- Output.print("Waiting for notification: '" + aTopic + "'.");
-
- return new Promise(resolve => Services.obs.addObserver(
- function observe(aSubject, aTopic, aData) {
- Services.obs.removeObserver(observe, aTopic);
- resolve([aSubject, aData]);
- }, aTopic, false));
- },
-
- /**
- * Waits for a DOM event on the specified target.
- *
- * @param aTarget
- * The DOM EventTarget on which addEventListener should be called.
- * @param aEventName
- * String with the name of the event.
- * @param aUseCapture
- * This parameter is passed to the addEventListener call.
- *
- * @return {Promise}
- * @resolves The arguments from the observed event.
- * @rejects Never.
- */
- waitForEvent: function (aTarget, aEventName, aUseCapture = false) {
- Output.print("Waiting for event: '" + aEventName + "' on " + aTarget + ".");
-
- return new Promise(resolve => aTarget.addEventListener(aEventName,
- function onEvent(...aArgs) {
- aTarget.removeEventListener(aEventName, onEvent, aUseCapture);
- resolve(...aArgs);
- }, aUseCapture));
- },
-
- // While the previous test file should have deleted all the temporary files it
- // used, on Windows these might still be pending deletion on the physical file
- // system. Thus, start from a new base number every time, to make a collision
- // with a file that is still pending deletion highly unlikely.
- _fileCounter: Math.floor(Math.random() * 1000000),
-
- /**
- * Returns a reference to a temporary file, that is guaranteed not to exist,
- * and to have never been created before.
- *
- * @param aLeafName
- * Suggested leaf name for the file to be created.
- *
- * @return {Promise}
- * @resolves Path of a non-existent file in a temporary directory.
- *
- * @note It is not enough to delete the file if it exists, or to delete the
- * file after calling nsIFile.createUnique, because on Windows the
- * delete operation in the file system may still be pending, preventing
- * a new file with the same name to be created.
- */
- getTempFile: Task.async(function* (aLeafName) {
- // Prepend a serial number to the extension in the suggested leaf name.
- let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
- let leafName = base + "-" + this._fileCounter + ext;
- this._fileCounter++;
-
- // Get a file reference under the temporary directory for this test file.
- let path = OS.Path.join(OS.Constants.Path.tmpDir, leafName);
- Assert.ok(!(yield OS.File.exists(path)));
-
- // Ensure the file is deleted whe the test terminates.
- add_termination_task(function* () {
- if (yield OS.File.exists(path)) {
- yield OS.File.remove(path);
- }
- });
-
- return path;
- }),
-};
-
-/* --- Local helpers --- */
-
-var FormAutofillTest = {
- /**
- * Stores the response that the next call to the mock requestAutocomplete UI
- * will return to the requester, or null to enable displaying the default UI.
- */
- requestAutocompleteResponse: null,
-
- /**
- * Displays the requestAutocomplete user interface using the specified data.
- *
- * @param aFormAutofillData
- * Serializable object containing the set of requested fields.
- *
- * @return {Promise}
- * @resolves An object with the following properties:
- * {
- * uiWindow: Reference to the initialized window.
- * promiseResult: Promise resolved by the UI when it closes.
- * }
- */
- showUI: Task.async(function* (aFormAutofillData) {
- Output.print("Opening UI with data: " + JSON.stringify(aFormAutofillData));
-
- // Wait for the initialization event before opening the window.
- let promiseUIWindow =
- TestUtils.waitForNotification("formautofill-window-initialized");
- let ui = yield FormAutofill.integration.createRequestAutocompleteUI(
- aFormAutofillData);
- let promiseResult = ui.show();
-
- // The window is the subject of the observer notification.
- return {
- uiWindow: (yield promiseUIWindow)[0],
- promiseResult: promiseResult,
- };
- }),
-};
-
-var TestData = {
- /**
- * Autofill UI request for the e-mail field only.
- */
- get requestEmailOnly() {
- return {
- sections: [{
- name: "",
- addressSections: [{
- addressType: "",
- fields: [{
- fieldName: "email",
- contactType: "",
- }],
- }],
- }],
- };
- },
-};
-
-/* --- Initialization and termination functions common to all tests --- */
-
-add_task_in_parent_process(function* () {
- // If required, we return a mock response instead of displaying the UI.
- let mockIntegrationFn = base => ({
- createRequestAutocompleteUI: Task.async(function* () {
- // Call the base method to display the UI if override is not requested.
- if (FormAutofillTest.requestAutocompleteResponse === null) {
- return yield base.createRequestAutocompleteUI.apply(this, arguments);
- }
-
- // Return a mock RequestAutocompleteUI object.
- return {
- show: Task.async(function* () {
- let response = FormAutofillTest.requestAutocompleteResponse;
- Output.print("Mock UI response: " + JSON.stringify(response));
- return response;
- }),
- };
- }),
- });
-
- FormAutofill.registerIntegration(mockIntegrationFn);
- add_termination_task(function* () {
- FormAutofill.unregisterIntegration(mockIntegrationFn);
- });
-});
-
-add_task_in_both_processes(function* () {
- // We must manually enable the feature while testing.
- Services.prefs.setBoolPref("dom.forms.requestAutocomplete", true);
- add_termination_task(function* () {
- Services.prefs.clearUserPref("dom.forms.requestAutocomplete");
- });
-});
diff --git a/toolkit/components/formautofill/test/loader_common.js b/toolkit/components/formautofill/test/loader_common.js
deleted file mode 100644
index 340586b65..000000000
--- a/toolkit/components/formautofill/test/loader_common.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Infrastructure common to the test frameworks located in subfolders.
- *
- * A copy of this file is installed in each of the framework subfolders, this
- * means it becomes a sibling of the test files in the final layout. This is
- * determined by how manifest "support-files" installation works.
- *
- * Unless you are adding new features to the framework, you shouldn't have to
- * modify this file. Use "head_common.js" or the "head.js" file of each
- * framework for shared code.
- */
-
-"use strict";
-
-/*
- * --------------------
- * FRAMEWORK OVERVIEW
- * --------------------
- *
- * This framework is designed in such a way that test can be written in similar
- * ways in the xpcshell, mochitest-chrome, and mochitest-browser frameworks,
- * both when tests are running in the parent process or in a content process.
- *
- * There are some basic self-documenting assertion and output functions:
- *
- * Assert.ok(actualValue);
- * Assert.is(actualValue, expectedValue);
- * Output.print(string);
- *
- * Test cases and initialization functions are declared in shared head files
- * ("head_common.js" and "head.js") as well as individual test files. When
- * tests run in an Elecrolysis (e10s) environment, they are executed in both
- * processes at first. Normally, at this point only the registration of test
- * cases happen. When everything has finished loading, tests are started and
- * appropriately synchronized between processes.
- *
- * Tests can be declared using the add_task syntax:
- *
- * add_task(function* test_something () { ... });
- * This adds a test either in the parent process or child process:
- * - Parent: xpcshell, mochitest-chrome --disable-e10s, mochitest-browser
- * - Child: mochitest-chrome with e10s
- * In the future, these might run in the child process for "xpcshell".
- *
- * add_task_in_parent_process(function* test_something () { ... });
- * This test runs in the parent process, but the child process will wait for
- * its completion before continuing with the next task. This wait currently
- * happens only in mochitest-chrome with e10s, in other frameworks that run
- * only in the parent process this is the same as a normal add_task.
- *
- * add_task_in_child_process(function* test_something () { ... });
- * This test runs only in the child process. This means that the test is not
- * run unless this is an e10s test, currently mochitest-chrome with e10s.
- *
- * add_task_in_both_processes(function* test_something () { ... });
- * Useful for initialization that must be done both in the parent and the
- * child, like setting preferences.
- *
- * add_termination_task(function* () { ... });
- * Registers a new asynchronous termination task. This is executed after all
- * test cases in the file finished, and always in the same process where the
- * termination task is registered.
- */
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-
-var gTerminationTasks = [];
-
-/**
- * None of the testing frameworks support asynchronous termination functions, so
- * this task must be registered later, after the other "add_task" calls.
- *
- * Even xpcshell doesn't support calling "add_task" in the "tail.js" file,
- * because it registers the task but does not wait for its termination,
- * potentially leading to intermittent failures in subsequent tests.
- */
-function* terminationTaskFn() {
- for (let taskFn of gTerminationTasks) {
- try {
- yield Task.spawn(taskFn);
- } catch (ex) {
- Output.print(ex);
- Assert.ok(false);
- }
- }
-}
-
-function add_termination_task(taskFn) {
- gTerminationTasks.push(taskFn);
-}
-
-/**
- * Returns a unique identifier used for synchronizing the given test task
- * between the parent and child processes.
- */
-function getTaskId(stackFrame) {
- return stackFrame.filename + ":" + stackFrame.lineNumber;
-}
-
-// This is a shared helper for mochitest-chrome and mochitest-browser.
-var _mochitestAssert = {
- ok: function (actual) {
- let stack = Components.stack.caller;
- ok(actual, "[" + stack.name + " : " + stack.lineNumber + "] " + actual +
- " == true");
- },
- equal: function (actual, expected) {
- let stack = Components.stack.caller;
- is(actual, expected, "[" + stack.name + " : " + stack.lineNumber + "] " +
- actual + " == " + expected);
- },
-};
-
-// Reminder: unless you are adding new features to the framework, you shouldn't
-// have to modify this file. Use "head_common.js" or "head.js" for shared code.
diff --git a/toolkit/components/formautofill/test/xpcshell/.eslintrc.js b/toolkit/components/formautofill/test/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/formautofill/test/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/formautofill/test/xpcshell/head.js b/toolkit/components/formautofill/test/xpcshell/head.js
deleted file mode 100644
index 1cee023f2..000000000
--- a/toolkit/components/formautofill/test/xpcshell/head.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Initialization specific to Form Autofill xpcshell tests.
- *
- * This file is loaded by "loader.js".
- */
-
-"use strict";
-
-// The testing framework is fully initialized at this point, you can add
-// xpcshell specific test initialization here. If you need shared functions or
-// initialization that are not specific to xpcshell, consider adding them to
-// "head_common.js" in the parent folder instead.
-
-add_task_in_parent_process(function* test_xpcshell_initialize_profile() {
- // We need to send the profile-after-change notification manually to the
- // startup component to ensure it has been initialized.
- Cc["@mozilla.org/formautofill/startup;1"]
- .getService(Ci.nsIObserver)
- .observe(null, "profile-after-change", "");
-});
diff --git a/toolkit/components/formautofill/test/xpcshell/loader.js b/toolkit/components/formautofill/test/xpcshell/loader.js
deleted file mode 100644
index 449989c8a..000000000
--- a/toolkit/components/formautofill/test/xpcshell/loader.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Infrastructure for the xpcshell tests located in this folder.
- *
- * See "loader_common.js" in the parent folder for a general overview.
- *
- * Unless you are adding new features to the framework, you shouldn't have to
- * modify this file. Use "head_common.js" or "head.js" for shared code.
- */
-
-"use strict";
-
-var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-Services.scriptloader.loadSubScript(
- Services.io.newFileURI(do_get_file("loader_common.js")).spec, this);
-
-// Define output functions so they look the same across all frameworks.
-var Output = {
- print: do_print,
-};
-
-var executeSoon = do_execute_soon;
-var setTimeout = (fn, delay) => do_timeout(delay, fn);
-
-// Define task registration functions, see description in "loader_common.js".
-var add_task_in_parent_process = add_task;
-var add_task_in_child_process = function () {};
-var add_task_in_both_processes = add_task;
-
-Services.scriptloader.loadSubScript(
- Services.io.newFileURI(do_get_file("head_common.js")).spec, this);
-
-// Tests are always run asynchronously and with the profile loaded.
-function run_test() {
- do_get_profile();
- run_next_test();
-}
-
-// Reminder: unless you are adding new features to the framework, you shouldn't
-// have to modify this file. Use "head_common.js" or "head.js" for shared code.
diff --git a/toolkit/components/formautofill/test/xpcshell/test_infrastructure.js b/toolkit/components/formautofill/test/xpcshell/test_infrastructure.js
deleted file mode 100644
index af27cfdb5..000000000
--- a/toolkit/components/formautofill/test/xpcshell/test_infrastructure.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests the local testing infrastructure.
- */
-
-"use strict";
-
-/**
- * Tests the truth assertion function.
- */
-add_task(function* test_assert_truth() {
- Assert.ok(1 != 2);
-});
-
-/**
- * Tests the equality assertion function.
- */
-add_task(function* test_assert_equality() {
- Assert.equal(1 + 1, 2);
-});
-
-/**
- * Uses some of the utility functions provided by the framework.
- */
-add_task(function* test_utility_functions() {
- // The "print" function is useful to log information that is not known before.
- let randomString = "R" + Math.floor(Math.random() * 10);
- Output.print("The random contents will be '" + randomString + "'.");
-
- // Create the text file with the random contents.
- let path = yield TestUtils.getTempFile("test-infrastructure.txt");
- yield OS.File.writeAtomic(path, new TextEncoder().encode(randomString));
-
- // Test a few utility functions.
- yield TestUtils.waitForTick();
- yield TestUtils.waitMs(50);
-
- let promiseMyNotification = TestUtils.waitForNotification("my-topic");
- Services.obs.notifyObservers(null, "my-topic", "");
- yield promiseMyNotification;
-
- // Check the file size. The file will be deleted automatically later.
- Assert.equal((yield OS.File.stat(path)).size, randomString.length);
-});
-
-add_task(terminationTaskFn);
diff --git a/toolkit/components/formautofill/test/xpcshell/test_integration.js b/toolkit/components/formautofill/test/xpcshell/test_integration.js
deleted file mode 100644
index 7707f3880..000000000
--- a/toolkit/components/formautofill/test/xpcshell/test_integration.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests overriding the FormAutofillIntegration module functions.
- */
-
-"use strict";
-
-/**
- * The requestAutocomplete UI will not be displayed during these tests.
- */
-add_task_in_parent_process(function* test_initialize() {
- FormAutofillTest.requestAutocompleteResponse = { canceled: true };
-});
-
-/**
- * Registers and unregisters an integration override function.
- */
-add_task(function* test_integration_override() {
- let overrideCalled = false;
-
- let newIntegrationFn = base => ({
- createRequestAutocompleteUI: Task.async(function* () {
- overrideCalled = true;
- return yield base.createRequestAutocompleteUI.apply(this, arguments);
- }),
- });
-
- FormAutofill.registerIntegration(newIntegrationFn);
- try {
- let ui = yield FormAutofill.integration.createRequestAutocompleteUI({});
- let result = yield ui.show();
- Assert.ok(result.canceled);
- } finally {
- FormAutofill.unregisterIntegration(newIntegrationFn);
- }
-
- Assert.ok(overrideCalled);
-});
-
-/**
- * Registers an integration override function that throws an exception, and
- * ensures that this does not block other functions from being registered.
- */
-add_task(function* test_integration_override_error() {
- let overrideCalled = false;
-
- let errorIntegrationFn = base => { throw "Expected error." };
-
- let newIntegrationFn = base => ({
- createRequestAutocompleteUI: Task.async(function* () {
- overrideCalled = true;
- return yield base.createRequestAutocompleteUI.apply(this, arguments);
- }),
- });
-
- FormAutofill.registerIntegration(errorIntegrationFn);
- FormAutofill.registerIntegration(newIntegrationFn);
- try {
- let ui = yield FormAutofill.integration.createRequestAutocompleteUI({});
- let result = yield ui.show();
- Assert.ok(result.canceled);
- } finally {
- FormAutofill.unregisterIntegration(errorIntegrationFn);
- FormAutofill.unregisterIntegration(newIntegrationFn);
- }
-
- Assert.ok(overrideCalled);
-});
-
-add_task(terminationTaskFn);
diff --git a/toolkit/components/formautofill/test/xpcshell/xpcshell.ini b/toolkit/components/formautofill/test/xpcshell/xpcshell.ini
deleted file mode 100644
index 711c03399..000000000
--- a/toolkit/components/formautofill/test/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-head = loader.js head.js
-tail =
-skip-if = toolkit == 'android'
-# The following files starting with ".." are installed in the current folder.
-# However, they cannot be referenced directly in the "head" directive above.
-support-files =
- ../head_common.js
- ../loader_common.js
-
-[test_infrastructure.js]
-[test_integration.js]
diff --git a/toolkit/components/jsdownloads/moz.build b/toolkit/components/jsdownloads/moz.build
index 62f08b160..56566bc97 100644
--- a/toolkit/components/jsdownloads/moz.build
+++ b/toolkit/components/jsdownloads/moz.build
@@ -4,15 +4,4 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-with Files('*'):
- BUG_COMPONENT = ('Toolkit', 'Download Manager')
-
DIRS += ['public', 'src']
-
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-BROWSER_CHROME_MANIFESTS += ['test/browser/browser.ini']
-
-TEST_HARNESS_FILES.xpcshell.toolkit.components.jsdownloads.test.data += [
- 'test/data/empty.txt',
- 'test/data/source.txt',
-]
diff --git a/toolkit/components/jsdownloads/test/browser/.eslintrc.js b/toolkit/components/jsdownloads/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/jsdownloads/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/jsdownloads/test/browser/browser.ini b/toolkit/components/jsdownloads/test/browser/browser.ini
deleted file mode 100644
index 131fc4ec8..000000000
--- a/toolkit/components/jsdownloads/test/browser/browser.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- testFile.html
-
-[browser_DownloadPDFSaver.js]
-skip-if = os != "win"
diff --git a/toolkit/components/jsdownloads/test/browser/browser_DownloadPDFSaver.js b/toolkit/components/jsdownloads/test/browser/browser_DownloadPDFSaver.js
deleted file mode 100644
index 80ed9665a..000000000
--- a/toolkit/components/jsdownloads/test/browser/browser_DownloadPDFSaver.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the PDF download saver, and tests using a window as a
- * source for the copy download saver.
- */
-
-"use strict";
-
-/**
- * Helper function to make sure a window reference exists on the download source.
- */
-function* test_download_windowRef(aTab, aDownload) {
- ok(aDownload.source.windowRef, "Download source had a window reference");
- ok(aDownload.source.windowRef instanceof Ci.xpcIJSWeakReference, "Download window reference is a weak ref");
- is(aDownload.source.windowRef.get(), aTab.linkedBrowser.contentWindow, "Download window exists during test");
-}
-
-/**
- * Helper function to check the state of a completed download.
- */
-function* test_download_state_complete(aTab, aDownload, aPrivate, aCanceled) {
- ok(aDownload.source, "Download has a source");
- is(aDownload.source.url, aTab.linkedBrowser.contentWindow.location, "Download source has correct url");
- is(aDownload.source.isPrivate, aPrivate, "Download source has correct private state");
- ok(aDownload.stopped, "Download is stopped");
- is(aCanceled, aDownload.canceled, "Download has correct canceled state");
- is(!aCanceled, aDownload.succeeded, "Download has correct succeeded state");
- is(aDownload.error, null, "Download error is not defined");
-}
-
-function* test_createDownload_common(aPrivate, aType) {
- let win = yield BrowserTestUtils.openNewBrowserWindow({ private : aPrivate});
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, getRootDirectory(gTestPath) + "testFile.html");
- let download = yield Downloads.createDownload({
- source: tab.linkedBrowser.contentWindow,
- target: { path: getTempFile(TEST_TARGET_FILE_NAME_PDF).path },
- saver: { type: aType }
- });
-
- yield test_download_windowRef(tab, download);
- yield download.start();
-
- yield test_download_state_complete(tab, download, aPrivate, false);
- if (aType == "pdf") {
- let signature = yield OS.File.read(download.target.path,
- { bytes: 4, encoding: "us-ascii" });
- is(signature, "%PDF", "File exists and signature matches");
- } else {
- ok((yield OS.File.exists(download.target.path)), "File exists");
- }
-
- win.gBrowser.removeTab(tab);
- win.close()
-}
-
-add_task(function* test_createDownload_pdf_private() {
- yield test_createDownload_common(true, "pdf");
-});
-add_task(function* test_createDownload_pdf_not_private() {
- yield test_createDownload_common(false, "pdf");
-});
-
-// Even for the copy saver, using a window should produce valid results
-add_task(function* test_createDownload_copy_private() {
- yield test_createDownload_common(true, "copy");
-});
-add_task(function* test_createDownload_copy_not_private() {
- yield test_createDownload_common(false, "copy");
-});
-
-add_task(function* test_cancel_pdf_download() {
- let tab = gBrowser.addTab(getRootDirectory(gTestPath) + "testFile.html");
- yield promiseBrowserLoaded(tab.linkedBrowser);
-
- let download = yield Downloads.createDownload({
- source: tab.linkedBrowser.contentWindow,
- target: { path: getTempFile(TEST_TARGET_FILE_NAME_PDF).path },
- saver: "pdf",
- });
-
- yield test_download_windowRef(tab, download);
- download.start().catch(() => {});
-
- // Immediately cancel the download to test that it is erased correctly.
- yield download.cancel();
- yield test_download_state_complete(tab, download, false, true);
-
- let exists = yield OS.File.exists(download.target.path)
- ok(!exists, "Target file does not exist");
-
- gBrowser.removeTab(tab);
-});
diff --git a/toolkit/components/jsdownloads/test/browser/head.js b/toolkit/components/jsdownloads/test/browser/head.js
deleted file mode 100644
index 769aaacb3..000000000
--- a/toolkit/components/jsdownloads/test/browser/head.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Provides infrastructure for automated download components tests.
- */
-
-"use strict";
-
-// Globals
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths",
- "resource://gre/modules/DownloadPaths.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
- "resource://gre/modules/Downloads.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Services",
- "resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "HttpServer",
- "resource://testing-common/httpd.js");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-
-const TEST_TARGET_FILE_NAME_PDF = "test-download.pdf";
-
-// Support functions
-
-// While the previous test file should have deleted all the temporary files it
-// used, on Windows these might still be pending deletion on the physical file
-// system. Thus, start from a new base number every time, to make a collision
-// with a file that is still pending deletion highly unlikely.
-var gFileCounter = Math.floor(Math.random() * 1000000);
-
-/**
- * Returns a reference to a temporary file, that is guaranteed not to exist, and
- * to have never been created before.
- *
- * @param aLeafName
- * Suggested leaf name for the file to be created.
- *
- * @return nsIFile pointing to a non-existent file in a temporary directory.
- *
- * @note It is not enough to delete the file if it exists, or to delete the file
- * after calling nsIFile.createUnique, because on Windows the delete
- * operation in the file system may still be pending, preventing a new
- * file with the same name to be created.
- */
-function getTempFile(aLeafName)
-{
- // Prepend a serial number to the extension in the suggested leaf name.
- let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
- let leafName = base + "-" + gFileCounter + ext;
- gFileCounter++;
-
- // Get a file reference under the temporary directory for this test file.
- let file = FileUtils.getFile("TmpD", [leafName]);
- ok(!file.exists(), "Temp file does not exist");
-
- registerCleanupFunction(function () {
- if (file.exists()) {
- file.remove(false);
- }
- });
-
- return file;
-}
-
-function promiseBrowserLoaded(browser) {
- return new Promise(resolve => {
- browser.addEventListener("load", function onLoad(event) {
- if (event.target == browser.contentDocument) {
- browser.removeEventListener("load", onLoad, true);
- resolve();
- }
- }, true);
- });
-}
diff --git a/toolkit/components/jsdownloads/test/browser/testFile.html b/toolkit/components/jsdownloads/test/browser/testFile.html
deleted file mode 100644
index ee413514b..000000000
--- a/toolkit/components/jsdownloads/test/browser/testFile.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <title>Test Save as PDF</title>
- </head>
- <body>
- <p>Save me as a PDF!</p>
- </body>
-</html>
diff --git a/toolkit/components/jsdownloads/test/data/.eslintrc.js b/toolkit/components/jsdownloads/test/data/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/jsdownloads/test/data/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/jsdownloads/test/data/empty.txt b/toolkit/components/jsdownloads/test/data/empty.txt
deleted file mode 100644
index e69de29bb..000000000
--- a/toolkit/components/jsdownloads/test/data/empty.txt
+++ /dev/null
diff --git a/toolkit/components/jsdownloads/test/data/source.txt b/toolkit/components/jsdownloads/test/data/source.txt
deleted file mode 100644
index 2156cb8c0..000000000
--- a/toolkit/components/jsdownloads/test/data/source.txt
+++ /dev/null
@@ -1 +0,0 @@
-This test string is downloaded. \ No newline at end of file
diff --git a/toolkit/components/jsdownloads/test/unit/.eslintrc.js b/toolkit/components/jsdownloads/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/jsdownloads/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/jsdownloads/test/unit/common_test_Download.js b/toolkit/components/jsdownloads/test/unit/common_test_Download.js
deleted file mode 100644
index 42d4c5682..000000000
--- a/toolkit/components/jsdownloads/test/unit/common_test_Download.js
+++ /dev/null
@@ -1,2432 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This script is loaded by "test_DownloadCore.js" and "test_DownloadLegacy.js"
- * with different values of the gUseLegacySaver variable, to apply tests to both
- * the "copy" and "legacy" saver implementations.
- */
-
-"use strict";
-
-// Globals
-
-const kDeleteTempFileOnExit = "browser.helperApps.deleteTempFileOnExit";
-
-/**
- * Creates and starts a new download, using either DownloadCopySaver or
- * DownloadLegacySaver based on the current test run.
- *
- * @return {Promise}
- * @resolves The newly created Download object. The download may be in progress
- * or already finished. The promiseDownloadStopped function can be
- * used to wait for completion.
- * @rejects JavaScript exception.
- */
-function promiseStartDownload(aSourceUrl) {
- if (gUseLegacySaver) {
- return promiseStartLegacyDownload(aSourceUrl);
- }
-
- return promiseNewDownload(aSourceUrl).then(download => {
- download.start().catch(() => {});
- return download;
- });
-}
-
-/**
- * Creates and starts a new download, configured to keep partial data, and
- * returns only when the first part of "interruptible_resumable.txt" has been
- * saved to disk. You must call "continueResponses" to allow the interruptible
- * request to continue.
- *
- * This function uses either DownloadCopySaver or DownloadLegacySaver based on
- * the current test run.
- *
- * @return {Promise}
- * @resolves The newly created Download object, still in progress.
- * @rejects JavaScript exception.
- */
-function promiseStartDownload_tryToKeepPartialData() {
- return Task.spawn(function* () {
- mustInterruptResponses();
-
- // Start a new download and configure it to keep partially downloaded data.
- let download;
- if (!gUseLegacySaver) {
- let targetFilePath = getTempFile(TEST_TARGET_FILE_NAME).path;
- download = yield Downloads.createDownload({
- source: httpUrl("interruptible_resumable.txt"),
- target: { path: targetFilePath,
- partFilePath: targetFilePath + ".part" },
- });
- download.tryToKeepPartialData = true;
- download.start().catch(() => {});
- } else {
- // Start a download using nsIExternalHelperAppService, that is configured
- // to keep partially downloaded data by default.
- download = yield promiseStartExternalHelperAppServiceDownload();
- }
-
- yield promiseDownloadMidway(download);
- yield promisePartFileReady(download);
-
- return download;
- });
-}
-
-/**
- * This function should be called after the progress notification for a download
- * is received, and waits for the worker thread of BackgroundFileSaver to
- * receive the data to be written to the ".part" file on disk.
- *
- * @return {Promise}
- * @resolves When the ".part" file has been written to disk.
- * @rejects JavaScript exception.
- */
-function promisePartFileReady(aDownload) {
- return Task.spawn(function* () {
- // We don't have control over the file output code in BackgroundFileSaver.
- // After we receive the download progress notification, we may only check
- // that the ".part" file has been created, while its size cannot be
- // determined because the file is currently open.
- try {
- do {
- yield promiseTimeout(50);
- } while (!(yield OS.File.exists(aDownload.target.partFilePath)));
- } catch (ex) {
- if (!(ex instanceof OS.File.Error)) {
- throw ex;
- }
- // This indicates that the file has been created and cannot be accessed.
- // The specific error might vary with the platform.
- do_print("Expected exception while checking existence: " + ex.toString());
- // Wait some more time to allow the write to complete.
- yield promiseTimeout(100);
- }
- });
-}
-
-/**
- * Checks that the actual data written to disk matches the expected data as well
- * as the properties of the given DownloadTarget object.
- *
- * @param downloadTarget
- * The DownloadTarget object whose details have to be verified.
- * @param expectedContents
- * String containing the octets that are expected in the file.
- *
- * @return {Promise}
- * @resolves When the properties have been verified.
- * @rejects JavaScript exception.
- */
-var promiseVerifyTarget = Task.async(function* (downloadTarget,
- expectedContents) {
- yield promiseVerifyContents(downloadTarget.path, expectedContents);
- do_check_true(downloadTarget.exists);
- do_check_eq(downloadTarget.size, expectedContents.length);
-});
-
-/**
- * Waits for an attempt to launch a file, and returns the nsIMIMEInfo used for
- * the launch, or null if the file was launched with the default handler.
- */
-function waitForFileLaunched() {
- return new Promise(resolve => {
- let waitFn = base => ({
- launchFile(file, mimeInfo) {
- Integration.downloads.unregister(waitFn);
- if (!mimeInfo ||
- mimeInfo.preferredAction == Ci.nsIMIMEInfo.useSystemDefault) {
- resolve(null);
- } else {
- resolve(mimeInfo);
- }
- return Promise.resolve();
- },
- });
- Integration.downloads.register(waitFn);
- });
-}
-
-/**
- * Waits for an attempt to show the directory where a file is located, and
- * returns the path of the file.
- */
-function waitForDirectoryShown() {
- return new Promise(resolve => {
- let waitFn = base => ({
- showContainingDirectory(path) {
- Integration.downloads.unregister(waitFn);
- resolve(path);
- return Promise.resolve();
- },
- });
- Integration.downloads.register(waitFn);
- });
-}
-
-// Tests
-
-/**
- * Executes a download and checks its basic properties after construction.
- * The download is started by constructing the simplest Download object with
- * the "copy" saver, or using the legacy nsITransfer interface.
- */
-add_task(function* test_basic()
-{
- let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
-
- let download;
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we have control over the download, thus
- // we can check its basic properties before it starts.
- download = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt") },
- target: { path: targetFile.path },
- saver: { type: "copy" },
- });
-
- do_check_eq(download.source.url, httpUrl("source.txt"));
- do_check_eq(download.target.path, targetFile.path);
-
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, the download is already started when it
- // is created, thus we must check its basic properties while in progress.
- download = yield promiseStartLegacyDownload(null,
- { targetFile: targetFile });
-
- do_check_eq(download.source.url, httpUrl("source.txt"));
- do_check_eq(download.target.path, targetFile.path);
-
- yield promiseDownloadStopped(download);
- }
-
- // Check additional properties on the finished download.
- do_check_true(download.source.referrer === null);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
-});
-
-/**
- * Executes a download with the tryToKeepPartialData property set, and ensures
- * that the file is saved correctly. When testing DownloadLegacySaver, the
- * download is executed using the nsIExternalHelperAppService component.
- */
-add_task(function* test_basic_tryToKeepPartialData()
-{
- let download = yield promiseStartDownload_tryToKeepPartialData();
- continueResponses();
- yield promiseDownloadStopped(download);
-
- // The target file should now have been created, and the ".part" file deleted.
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
- do_check_eq(32, download.saver.getSha256Hash().length);
-});
-
-/**
- * Tests the permissions of the final target file once the download finished.
- */
-add_task(function* test_unix_permissions()
-{
- // This test is only executed on some Desktop systems.
- if (Services.appinfo.OS != "Darwin" && Services.appinfo.OS != "Linux" &&
- Services.appinfo.OS != "WINNT") {
- do_print("Skipping test.");
- return;
- }
-
- let launcherPath = getTempFile("app-launcher").path;
-
- for (let autoDelete of [false, true]) {
- for (let isPrivate of [false, true]) {
- for (let launchWhenSucceeded of [false, true]) {
- do_print("Checking " + JSON.stringify({ autoDelete,
- isPrivate,
- launchWhenSucceeded }));
-
- Services.prefs.setBoolPref(kDeleteTempFileOnExit, autoDelete);
-
- let download;
- if (!gUseLegacySaver) {
- download = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt"), isPrivate },
- target: getTempFile(TEST_TARGET_FILE_NAME).path,
- launchWhenSucceeded,
- launcherPath,
- });
- yield download.start();
- } else {
- download = yield promiseStartLegacyDownload(httpUrl("source.txt"), {
- isPrivate,
- launchWhenSucceeded,
- launcherPath: launchWhenSucceeded && launcherPath,
- });
- yield promiseDownloadStopped(download);
- }
-
- let isTemporary = launchWhenSucceeded && (autoDelete || isPrivate);
- let stat = yield OS.File.stat(download.target.path);
- if (Services.appinfo.OS == "WINNT") {
- // On Windows
- // Temporary downloads should be read-only
- do_check_eq(stat.winAttributes.readOnly, isTemporary ? true : false);
- } else {
- // On Linux, Mac
- // Temporary downloads should be read-only and not accessible to other
- // users, while permanently downloaded files should be readable and
- // writable as specified by the system umask.
- do_check_eq(stat.unixMode,
- isTemporary ? 0o400 : (0o666 & ~OS.Constants.Sys.umask));
- }
- }
- }
- }
-
- // Clean up the changes to the preference.
- Services.prefs.clearUserPref(kDeleteTempFileOnExit);
-});
-
-/**
- * Checks the referrer for downloads.
- */
-add_task(function* test_referrer()
-{
- let sourcePath = "/test_referrer.txt";
- let sourceUrl = httpUrl("test_referrer.txt");
- let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
-
- function cleanup() {
- gHttpServer.registerPathHandler(sourcePath, null);
- }
- do_register_cleanup(cleanup);
-
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
-
- do_check_true(aRequest.hasHeader("Referer"));
- do_check_eq(aRequest.getHeader("Referer"), TEST_REFERRER_URL);
- });
- let download = yield Downloads.createDownload({
- source: { url: sourceUrl, referrer: TEST_REFERRER_URL },
- target: targetPath,
- });
- do_check_eq(download.source.referrer, TEST_REFERRER_URL);
- yield download.start();
-
- download = yield Downloads.createDownload({
- source: { url: sourceUrl, referrer: TEST_REFERRER_URL,
- isPrivate: true },
- target: targetPath,
- });
- do_check_eq(download.source.referrer, TEST_REFERRER_URL);
- yield download.start();
-
- // Test the download still works for non-HTTP channel with referrer.
- sourceUrl = "data:text/html,<html><body></body></html>";
- download = yield Downloads.createDownload({
- source: { url: sourceUrl, referrer: TEST_REFERRER_URL },
- target: targetPath,
- });
- do_check_eq(download.source.referrer, TEST_REFERRER_URL);
- yield download.start();
-
- cleanup();
-});
-
-/**
- * Checks the adjustChannel callback for downloads.
- */
-add_task(function* test_adjustChannel()
-{
- const sourcePath = "/test_post.txt";
- const sourceUrl = httpUrl("test_post.txt");
- const targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
- const customHeader = { name: "X-Answer", value: "42" };
- const postData = "Don't Panic";
-
- function cleanup() {
- gHttpServer.registerPathHandler(sourcePath, null);
- }
- do_register_cleanup(cleanup);
-
- gHttpServer.registerPathHandler(sourcePath, aRequest => {
- do_check_eq(aRequest.method, "POST");
-
- do_check_true(aRequest.hasHeader(customHeader.name));
- do_check_eq(aRequest.getHeader(customHeader.name), customHeader.value);
-
- const stream = aRequest.bodyInputStream;
- const body = NetUtil.readInputStreamToString(stream, stream.available());
- do_check_eq(body, postData);
- });
-
- function adjustChannel(channel) {
- channel.QueryInterface(Ci.nsIHttpChannel);
- channel.setRequestHeader(customHeader.name, customHeader.value, false);
-
- const stream = Cc["@mozilla.org/io/string-input-stream;1"]
- .createInstance(Ci.nsIStringInputStream);
- stream.setData(postData, postData.length);
-
- channel.QueryInterface(Ci.nsIUploadChannel2);
- channel.explicitSetUploadStream(stream, null, -1, "POST", false);
-
- return Promise.resolve();
- }
-
- const download = yield Downloads.createDownload({
- source: { url: sourceUrl, adjustChannel },
- target: targetPath,
- });
- do_check_eq(download.source.adjustChannel, adjustChannel);
- do_check_eq(download.toSerializable(), null);
- yield download.start();
-
- cleanup();
-});
-
-/**
- * Checks initial and final state and progress for a successful download.
- */
-add_task(function* test_initial_final_state()
-{
- let download;
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we have control over the download, thus
- // we can check its state before it starts.
- download = yield promiseNewDownload();
-
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
- do_check_eq(download.progress, 0);
- do_check_true(download.startTime === null);
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, the download is already started when it
- // is created, thus we cannot check its initial state.
- download = yield promiseStartLegacyDownload();
- yield promiseDownloadStopped(download);
- }
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
- do_check_eq(download.progress, 100);
- do_check_true(isValidDate(download.startTime));
- do_check_true(download.target.exists);
- do_check_eq(download.target.size, TEST_DATA_SHORT.length);
-});
-
-/**
- * Checks the notification of the final download state.
- */
-add_task(function* test_final_state_notified()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
-
- let onchangeNotified = false;
- let lastNotifiedStopped;
- let lastNotifiedProgress;
- download.onchange = function () {
- onchangeNotified = true;
- lastNotifiedStopped = download.stopped;
- lastNotifiedProgress = download.progress;
- };
-
- // Allow the download to complete.
- let promiseAttempt = download.start();
- continueResponses();
- yield promiseAttempt;
-
- // The view should have been notified before the download completes.
- do_check_true(onchangeNotified);
- do_check_true(lastNotifiedStopped);
- do_check_eq(lastNotifiedProgress, 100);
-});
-
-/**
- * Checks intermediate progress for a successful download.
- */
-add_task(function* test_intermediate_progress()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
-
- yield promiseDownloadMidway(download);
-
- do_check_true(download.hasProgress);
- do_check_eq(download.currentBytes, TEST_DATA_SHORT.length);
- do_check_eq(download.totalBytes, TEST_DATA_SHORT.length * 2);
-
- // The final file size should not be computed for in-progress downloads.
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- // Continue after the first chunk of data is fully received.
- continueResponses();
- yield promiseDownloadStopped(download);
-
- do_check_true(download.stopped);
- do_check_eq(download.progress, 100);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
-});
-
-/**
- * Downloads a file with a "Content-Length" of 0 and checks the progress.
- */
-add_task(function* test_empty_progress()
-{
- let download = yield promiseStartDownload(httpUrl("empty.txt"));
- yield promiseDownloadStopped(download);
-
- do_check_true(download.stopped);
- do_check_true(download.hasProgress);
- do_check_eq(download.progress, 100);
- do_check_eq(download.currentBytes, 0);
- do_check_eq(download.totalBytes, 0);
-
- // We should have received the content type even for an empty file.
- do_check_eq(download.contentType, "text/plain");
-
- do_check_eq((yield OS.File.stat(download.target.path)).size, 0);
- do_check_true(download.target.exists);
- do_check_eq(download.target.size, 0);
-});
-
-/**
- * Downloads a file with a "Content-Length" of 0 with the tryToKeepPartialData
- * property set, and ensures that the file is saved correctly.
- */
-add_task(function* test_empty_progress_tryToKeepPartialData()
-{
- // Start a new download and configure it to keep partially downloaded data.
- let download;
- if (!gUseLegacySaver) {
- let targetFilePath = getTempFile(TEST_TARGET_FILE_NAME).path;
- download = yield Downloads.createDownload({
- source: httpUrl("empty.txt"),
- target: { path: targetFilePath,
- partFilePath: targetFilePath + ".part" },
- });
- download.tryToKeepPartialData = true;
- download.start().catch(() => {});
- } else {
- // Start a download using nsIExternalHelperAppService, that is configured
- // to keep partially downloaded data by default.
- download = yield promiseStartExternalHelperAppServiceDownload(
- httpUrl("empty.txt"));
- }
- yield promiseDownloadStopped(download);
-
- // The target file should now have been created, and the ".part" file deleted.
- do_check_eq((yield OS.File.stat(download.target.path)).size, 0);
- do_check_true(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- do_check_false(yield OS.File.exists(download.target.partFilePath));
- do_check_eq(32, download.saver.getSha256Hash().length);
-});
-
-/**
- * Downloads an empty file with no "Content-Length" and checks the progress.
- */
-add_task(function* test_empty_noprogress()
-{
- let sourcePath = "/test_empty_noprogress.txt";
- let sourceUrl = httpUrl("test_empty_noprogress.txt");
- let deferRequestReceived = Promise.defer();
-
- // Register an interruptible handler that notifies us when the request occurs.
- function cleanup() {
- gHttpServer.registerPathHandler(sourcePath, null);
- }
- do_register_cleanup(cleanup);
-
- registerInterruptibleHandler(sourcePath,
- function firstPart(aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
- deferRequestReceived.resolve();
- }, function secondPart(aRequest, aResponse) { });
-
- // Start the download, without allowing the request to finish.
- mustInterruptResponses();
- let download;
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we have control over the download, thus
- // we can hook its onchange callback that will be notified when the
- // download starts.
- download = yield promiseNewDownload(sourceUrl);
-
- download.onchange = function () {
- if (!download.stopped) {
- do_check_false(download.hasProgress);
- do_check_eq(download.currentBytes, 0);
- do_check_eq(download.totalBytes, 0);
- }
- };
-
- download.start().catch(() => {});
- } else {
- // When testing DownloadLegacySaver, the download is already started when it
- // is created, and it may have already made all needed property change
- // notifications, thus there is no point in checking the onchange callback.
- download = yield promiseStartLegacyDownload(sourceUrl);
- }
-
- // Wait for the request to be received by the HTTP server, but don't allow the
- // request to finish yet. Before checking the download state, wait for the
- // events to be processed by the client.
- yield deferRequestReceived.promise;
- yield promiseExecuteSoon();
-
- // Check that this download has no progress report.
- do_check_false(download.stopped);
- do_check_false(download.hasProgress);
- do_check_eq(download.currentBytes, 0);
- do_check_eq(download.totalBytes, 0);
-
- // Now allow the response to finish.
- continueResponses();
- yield promiseDownloadStopped(download);
-
- // We should have received the content type even if no progress is reported.
- do_check_eq(download.contentType, "text/plain");
-
- // Verify the state of the completed download.
- do_check_true(download.stopped);
- do_check_false(download.hasProgress);
- do_check_eq(download.progress, 100);
- do_check_eq(download.currentBytes, 0);
- do_check_eq(download.totalBytes, 0);
- do_check_true(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- do_check_eq((yield OS.File.stat(download.target.path)).size, 0);
-});
-
-/**
- * Calls the "start" method two times before the download is finished.
- */
-add_task(function* test_start_twice()
-{
- mustInterruptResponses();
-
- let download;
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we have control over the download, thus
- // we can start the download later during the test.
- download = yield promiseNewDownload(httpUrl("interruptible.txt"));
- } else {
- // When testing DownloadLegacySaver, the download is already started when it
- // is created. Effectively, we are starting the download three times.
- download = yield promiseStartLegacyDownload(httpUrl("interruptible.txt"));
- }
-
- // Call the start method two times.
- let promiseAttempt1 = download.start();
- let promiseAttempt2 = download.start();
-
- // Allow the download to finish.
- continueResponses();
-
- // Both promises should now be resolved.
- yield promiseAttempt1;
- yield promiseAttempt2;
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
-});
-
-/**
- * Cancels a download and verifies that its state is reported correctly.
- */
-add_task(function* test_cancel_midway()
-{
- mustInterruptResponses();
-
- // In this test case, we execute different checks that are only possible with
- // DownloadCopySaver or DownloadLegacySaver respectively.
- let download;
- let options = {};
- if (!gUseLegacySaver) {
- download = yield promiseNewDownload(httpUrl("interruptible.txt"));
- } else {
- download = yield promiseStartLegacyDownload(httpUrl("interruptible.txt"),
- options);
- }
-
- // Cancel the download after receiving the first part of the response.
- let deferCancel = Promise.defer();
- let onchange = function () {
- if (!download.stopped && !download.canceled && download.progress == 50) {
- // Cancel the download immediately during the notification.
- deferCancel.resolve(download.cancel());
-
- // The state change happens immediately after calling "cancel", but
- // temporary files or part files may still exist at this point.
- do_check_true(download.canceled);
- }
- };
-
- // Register for the notification, but also call the function directly in
- // case the download already reached the expected progress. This may happen
- // when using DownloadLegacySaver.
- download.onchange = onchange;
- onchange();
-
- let promiseAttempt;
- if (!gUseLegacySaver) {
- promiseAttempt = download.start();
- }
-
- // Wait on the promise returned by the "cancel" method to ensure that the
- // cancellation process finished and temporary files were removed.
- yield deferCancel.promise;
-
- if (gUseLegacySaver) {
- // The nsIWebBrowserPersist instance should have been canceled now.
- do_check_eq(options.outPersist.result, Cr.NS_ERROR_ABORT);
- }
-
- do_check_true(download.stopped);
- do_check_true(download.canceled);
- do_check_true(download.error === null);
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- do_check_false(yield OS.File.exists(download.target.path));
-
- // Progress properties are not reset by canceling.
- do_check_eq(download.progress, 50);
- do_check_eq(download.totalBytes, TEST_DATA_SHORT.length * 2);
- do_check_eq(download.currentBytes, TEST_DATA_SHORT.length);
-
- if (!gUseLegacySaver) {
- // The promise returned by "start" should have been rejected meanwhile.
- try {
- yield promiseAttempt;
- do_throw("The download should have been canceled.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error)) {
- throw ex;
- }
- do_check_false(ex.becauseSourceFailed);
- do_check_false(ex.becauseTargetFailed);
- }
- }
-});
-
-/**
- * Cancels a download while keeping partially downloaded data, and verifies that
- * both the target file and the ".part" file are deleted.
- */
-add_task(function* test_cancel_midway_tryToKeepPartialData()
-{
- let download = yield promiseStartDownload_tryToKeepPartialData();
-
- do_check_true(yield OS.File.exists(download.target.path));
- do_check_true(yield OS.File.exists(download.target.partFilePath));
-
- yield download.cancel();
- yield download.removePartialData();
-
- do_check_true(download.stopped);
- do_check_true(download.canceled);
- do_check_true(download.error === null);
-
- do_check_false(yield OS.File.exists(download.target.path));
- do_check_false(yield OS.File.exists(download.target.partFilePath));
-});
-
-/**
- * Cancels a download right after starting it.
- */
-add_task(function* test_cancel_immediately()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
-
- let promiseAttempt = download.start();
- do_check_false(download.stopped);
-
- let promiseCancel = download.cancel();
- do_check_true(download.canceled);
-
- // At this point, we don't know whether the download has already stopped or
- // is still waiting for cancellation. We can wait on the promise returned
- // by the "start" method to know for sure.
- try {
- yield promiseAttempt;
- do_throw("The download should have been canceled.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error)) {
- throw ex;
- }
- do_check_false(ex.becauseSourceFailed);
- do_check_false(ex.becauseTargetFailed);
- }
-
- do_check_true(download.stopped);
- do_check_true(download.canceled);
- do_check_true(download.error === null);
-
- do_check_false(yield OS.File.exists(download.target.path));
-
- // Check that the promise returned by the "cancel" method has been resolved.
- yield promiseCancel;
-});
-
-/**
- * Cancels and restarts a download sequentially.
- */
-add_task(function* test_cancel_midway_restart()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
-
- // The first time, cancel the download midway.
- yield promiseDownloadMidway(download);
- yield download.cancel();
-
- do_check_true(download.stopped);
-
- // The second time, we'll provide the entire interruptible response.
- continueResponses();
- download.onchange = null;
- let promiseAttempt = download.start();
-
- // Download state should have already been reset.
- do_check_false(download.stopped);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- // For the following test, we rely on the network layer reporting its progress
- // asynchronously. Otherwise, there is nothing stopping the restarted
- // download from reaching the same progress as the first request already.
- do_check_eq(download.progress, 0);
- do_check_eq(download.totalBytes, 0);
- do_check_eq(download.currentBytes, 0);
-
- yield promiseAttempt;
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
-});
-
-/**
- * Cancels a download and restarts it from where it stopped.
- */
-add_task(function* test_cancel_midway_restart_tryToKeepPartialData()
-{
- let download = yield promiseStartDownload_tryToKeepPartialData();
- yield download.cancel();
-
- do_check_true(download.stopped);
- do_check_true(download.hasPartialData);
-
- // The target file should not exist, but we should have kept the partial data.
- do_check_false(yield OS.File.exists(download.target.path));
- yield promiseVerifyContents(download.target.partFilePath, TEST_DATA_SHORT);
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- // Verify that the server sent the response from the start.
- do_check_eq(gMostRecentFirstBytePos, 0);
-
- // The second time, we'll request and obtain the second part of the response,
- // but we still stop when half of the remaining progress is reached.
- let deferMidway = Promise.defer();
- download.onchange = function () {
- if (!download.stopped && !download.canceled &&
- download.currentBytes == Math.floor(TEST_DATA_SHORT.length * 3 / 2)) {
- download.onchange = null;
- deferMidway.resolve();
- }
- };
-
- mustInterruptResponses();
- let promiseAttempt = download.start();
-
- // Continue when the number of bytes we received is correct, then check that
- // progress is at about 75 percent. The exact figure may vary because of
- // rounding issues, since the total number of bytes in the response might not
- // be a multiple of four.
- yield deferMidway.promise;
- do_check_true(download.progress > 72 && download.progress < 78);
-
- // Now we allow the download to finish.
- continueResponses();
- yield promiseAttempt;
-
- // Check that the server now sent the second part only.
- do_check_eq(gMostRecentFirstBytePos, TEST_DATA_SHORT.length);
-
- // The target file should now have been created, and the ".part" file deleted.
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
-});
-
-/**
- * Cancels a download while keeping partially downloaded data, then removes the
- * data and restarts the download from the beginning.
- */
-add_task(function* test_cancel_midway_restart_removePartialData()
-{
- let download = yield promiseStartDownload_tryToKeepPartialData();
- yield download.cancel();
-
- do_check_true(download.hasPartialData);
- yield promiseVerifyContents(download.target.partFilePath, TEST_DATA_SHORT);
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- yield download.removePartialData();
-
- do_check_false(download.hasPartialData);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- // The second time, we'll request and obtain the entire response again.
- continueResponses();
- yield download.start();
-
- // Verify that the server sent the response from the start.
- do_check_eq(gMostRecentFirstBytePos, 0);
-
- // The target file should now have been created, and the ".part" file deleted.
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
-});
-
-/**
- * Cancels a download while keeping partially downloaded data, then removes the
- * data and restarts the download from the beginning without keeping the partial
- * data anymore.
- */
-add_task(function* test_cancel_midway_restart_tryToKeepPartialData_false()
-{
- let download = yield promiseStartDownload_tryToKeepPartialData();
- yield download.cancel();
-
- download.tryToKeepPartialData = false;
-
- // The above property change does not affect existing partial data.
- do_check_true(download.hasPartialData);
- yield promiseVerifyContents(download.target.partFilePath, TEST_DATA_SHORT);
-
- yield download.removePartialData();
- do_check_false(yield OS.File.exists(download.target.partFilePath));
-
- // Restart the download from the beginning.
- mustInterruptResponses();
- download.start().catch(() => {});
-
- yield promiseDownloadMidway(download);
- yield promisePartFileReady(download);
-
- // While the download is in progress, we should still have a ".part" file.
- do_check_false(download.hasPartialData);
- do_check_true(yield OS.File.exists(download.target.partFilePath));
-
- // On Unix, verify that the file with the partially downloaded data is not
- // accessible by other users on the system.
- if (Services.appinfo.OS == "Darwin" || Services.appinfo.OS == "Linux") {
- do_check_eq((yield OS.File.stat(download.target.partFilePath)).unixMode,
- 0o600);
- }
-
- yield download.cancel();
-
- // The ".part" file should be deleted now that the download is canceled.
- do_check_false(download.hasPartialData);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
-
- // The third time, we'll request and obtain the entire response again.
- continueResponses();
- yield download.start();
-
- // Verify that the server sent the response from the start.
- do_check_eq(gMostRecentFirstBytePos, 0);
-
- // The target file should now have been created, and the ".part" file deleted.
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
-});
-
-/**
- * Cancels a download right after starting it, then restarts it immediately.
- */
-add_task(function* test_cancel_immediately_restart_immediately()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
- let promiseAttempt = download.start();
-
- do_check_false(download.stopped);
-
- download.cancel();
- do_check_true(download.canceled);
-
- let promiseRestarted = download.start();
- do_check_false(download.stopped);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- // For the following test, we rely on the network layer reporting its progress
- // asynchronously. Otherwise, there is nothing stopping the restarted
- // download from reaching the same progress as the first request already.
- do_check_eq(download.hasProgress, false);
- do_check_eq(download.progress, 0);
- do_check_eq(download.totalBytes, 0);
- do_check_eq(download.currentBytes, 0);
-
- // Ensure the next request is now allowed to complete, regardless of whether
- // the canceled request was received by the server or not.
- continueResponses();
- try {
- yield promiseAttempt;
- // If we get here, it means that the first attempt actually succeeded. In
- // fact, this could be a valid outcome, because the cancellation request may
- // not have been processed in time before the download finished.
- do_print("The download should have been canceled.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error)) {
- throw ex;
- }
- do_check_false(ex.becauseSourceFailed);
- do_check_false(ex.becauseTargetFailed);
- }
-
- yield promiseRestarted;
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
-});
-
-/**
- * Cancels a download midway, then restarts it immediately.
- */
-add_task(function* test_cancel_midway_restart_immediately()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
- let promiseAttempt = download.start();
-
- // The first time, cancel the download midway.
- yield promiseDownloadMidway(download);
- download.cancel();
- do_check_true(download.canceled);
-
- let promiseRestarted = download.start();
- do_check_false(download.stopped);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- // For the following test, we rely on the network layer reporting its progress
- // asynchronously. Otherwise, there is nothing stopping the restarted
- // download from reaching the same progress as the first request already.
- do_check_eq(download.hasProgress, false);
- do_check_eq(download.progress, 0);
- do_check_eq(download.totalBytes, 0);
- do_check_eq(download.currentBytes, 0);
-
- // The second request is allowed to complete.
- continueResponses();
- try {
- yield promiseAttempt;
- do_throw("The download should have been canceled.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error)) {
- throw ex;
- }
- do_check_false(ex.becauseSourceFailed);
- do_check_false(ex.becauseTargetFailed);
- }
-
- yield promiseRestarted;
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
-});
-
-/**
- * Calls the "cancel" method on a successful download.
- */
-add_task(function* test_cancel_successful()
-{
- let download = yield promiseStartDownload();
- yield promiseDownloadStopped(download);
-
- // The cancel method should succeed with no effect.
- yield download.cancel();
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
-});
-
-/**
- * Calls the "cancel" method two times in a row.
- */
-add_task(function* test_cancel_twice()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
-
- let promiseAttempt = download.start();
- do_check_false(download.stopped);
-
- let promiseCancel1 = download.cancel();
- do_check_true(download.canceled);
- let promiseCancel2 = download.cancel();
-
- try {
- yield promiseAttempt;
- do_throw("The download should have been canceled.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error)) {
- throw ex;
- }
- do_check_false(ex.becauseSourceFailed);
- do_check_false(ex.becauseTargetFailed);
- }
-
- // Both promises should now be resolved.
- yield promiseCancel1;
- yield promiseCancel2;
-
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_true(download.canceled);
- do_check_true(download.error === null);
-
- do_check_false(yield OS.File.exists(download.target.path));
-});
-
-/**
- * Checks the "refresh" method for succeeded downloads.
- */
-add_task(function* test_refresh_succeeded()
-{
- let download = yield promiseStartDownload();
- yield promiseDownloadStopped(download);
-
- // The DownloadTarget properties should be the same after calling "refresh".
- yield download.refresh();
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
-
- // If the file is removed, only the "exists" property should change, and the
- // "size" property should keep its previous value.
- yield OS.File.move(download.target.path, download.target.path + ".old");
- yield download.refresh();
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, TEST_DATA_SHORT.length);
-
- // The DownloadTarget properties should be restored when the file is put back.
- yield OS.File.move(download.target.path + ".old", download.target.path);
- yield download.refresh();
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
-});
-
-/**
- * Checks that a download cannot be restarted after the "finalize" method.
- */
-add_task(function* test_finalize()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
-
- let promiseFinalized = download.finalize();
-
- try {
- yield download.start();
- do_throw("It should not be possible to restart after finalization.");
- } catch (ex) { }
-
- yield promiseFinalized;
-
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_true(download.canceled);
- do_check_true(download.error === null);
-
- do_check_false(yield OS.File.exists(download.target.path));
-});
-
-/**
- * Checks that the "finalize" method can remove partially downloaded data.
- */
-add_task(function* test_finalize_tryToKeepPartialData()
-{
- // Check finalization without removing partial data.
- let download = yield promiseStartDownload_tryToKeepPartialData();
- yield download.finalize();
-
- do_check_true(download.hasPartialData);
- do_check_true(yield OS.File.exists(download.target.partFilePath));
-
- // Clean up.
- yield download.removePartialData();
-
- // Check finalization while removing partial data.
- download = yield promiseStartDownload_tryToKeepPartialData();
- yield download.finalize(true);
-
- do_check_false(download.hasPartialData);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
-});
-
-/**
- * Checks that whenSucceeded returns a promise that is resolved after a restart.
- */
-add_task(function* test_whenSucceeded_after_restart()
-{
- mustInterruptResponses();
-
- let promiseSucceeded;
-
- let download;
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we have control over the download, thus
- // we can verify getting a reference before the first download attempt.
- download = yield promiseNewDownload(httpUrl("interruptible.txt"));
- promiseSucceeded = download.whenSucceeded();
- download.start().catch(() => {});
- } else {
- // When testing DownloadLegacySaver, the download is already started when it
- // is created, thus we cannot get the reference before the first attempt.
- download = yield promiseStartLegacyDownload(httpUrl("interruptible.txt"));
- promiseSucceeded = download.whenSucceeded();
- }
-
- // Cancel the first download attempt.
- yield download.cancel();
-
- // The second request is allowed to complete.
- continueResponses();
- download.start().catch(() => {});
-
- // Wait for the download to finish by waiting on the whenSucceeded promise.
- yield promiseSucceeded;
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
-});
-
-/**
- * Ensures download error details are reported on network failures.
- */
-add_task(function* test_error_source()
-{
- let serverSocket = startFakeServer();
- try {
- let sourceUrl = "http://localhost:" + serverSocket.port + "/source.txt";
-
- let download;
- try {
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we want to check that the promise
- // returned by the "start" method is rejected.
- download = yield promiseNewDownload(sourceUrl);
-
- do_check_true(download.error === null);
-
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, we cannot be sure whether we are
- // testing the promise returned by the "start" method or we are testing
- // the "error" property checked by promiseDownloadStopped. This happens
- // because we don't have control over when the download is started.
- download = yield promiseStartLegacyDownload(sourceUrl);
- yield promiseDownloadStopped(download);
- }
- do_throw("The download should have failed.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseSourceFailed) {
- throw ex;
- }
- // A specific error object is thrown when reading from the source fails.
- }
-
- // Check the properties now that the download stopped.
- do_check_true(download.stopped);
- do_check_false(download.canceled);
- do_check_true(download.error !== null);
- do_check_true(download.error.becauseSourceFailed);
- do_check_false(download.error.becauseTargetFailed);
-
- do_check_false(yield OS.File.exists(download.target.path));
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
- } finally {
- serverSocket.close();
- }
-});
-
-/**
- * Ensures a download error is reported when receiving less bytes than what was
- * specified in the Content-Length header.
- */
-add_task(function* test_error_source_partial()
-{
- let sourceUrl = httpUrl("shorter-than-content-length-http-1-1.txt");
-
- let enforcePref = Services.prefs.getBoolPref("network.http.enforce-framing.http1");
- Services.prefs.setBoolPref("network.http.enforce-framing.http1", true);
-
- function cleanup() {
- Services.prefs.setBoolPref("network.http.enforce-framing.http1", enforcePref);
- }
- do_register_cleanup(cleanup);
-
- let download;
- try {
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we want to check that the promise
- // returned by the "start" method is rejected.
- download = yield promiseNewDownload(sourceUrl);
-
- do_check_true(download.error === null);
-
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, we cannot be sure whether we are
- // testing the promise returned by the "start" method or we are testing
- // the "error" property checked by promiseDownloadStopped. This happens
- // because we don't have control over when the download is started.
- download = yield promiseStartLegacyDownload(sourceUrl);
- yield promiseDownloadStopped(download);
- }
- do_throw("The download should have failed.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseSourceFailed) {
- throw ex;
- }
- // A specific error object is thrown when reading from the source fails.
- }
-
- // Check the properties now that the download stopped.
- do_check_true(download.stopped);
- do_check_false(download.canceled);
- do_check_true(download.error !== null);
- do_check_true(download.error.becauseSourceFailed);
- do_check_false(download.error.becauseTargetFailed);
- do_check_eq(download.error.result, Cr.NS_ERROR_NET_PARTIAL_TRANSFER);
-
- do_check_false(yield OS.File.exists(download.target.path));
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-});
-
-/**
- * Ensures download error details are reported on local writing failures.
- */
-add_task(function* test_error_target()
-{
- // Create a file without write access permissions before downloading.
- let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
- targetFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0);
- try {
- let download;
- try {
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we want to check that the promise
- // returned by the "start" method is rejected.
- download = yield Downloads.createDownload({
- source: httpUrl("source.txt"),
- target: targetFile,
- });
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, we cannot be sure whether we are
- // testing the promise returned by the "start" method or we are testing
- // the "error" property checked by promiseDownloadStopped. This happens
- // because we don't have control over when the download is started.
- download = yield promiseStartLegacyDownload(null,
- { targetFile: targetFile });
- yield promiseDownloadStopped(download);
- }
- do_throw("The download should have failed.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseTargetFailed) {
- throw ex;
- }
- // A specific error object is thrown when writing to the target fails.
- }
-
- // Check the properties now that the download stopped.
- do_check_true(download.stopped);
- do_check_false(download.canceled);
- do_check_true(download.error !== null);
- do_check_true(download.error.becauseTargetFailed);
- do_check_false(download.error.becauseSourceFailed);
- } finally {
- // Restore the default permissions to allow deleting the file on Windows.
- if (targetFile.exists()) {
- targetFile.permissions = FileUtils.PERMS_FILE;
- targetFile.remove(false);
- }
- }
-});
-
-/**
- * Restarts a failed download.
- */
-add_task(function* test_error_restart()
-{
- let download;
-
- // Create a file without write access permissions before downloading.
- let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
- targetFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0);
- try {
- // Use DownloadCopySaver or DownloadLegacySaver based on the test run,
- // specifying the target file we created.
- if (!gUseLegacySaver) {
- download = yield Downloads.createDownload({
- source: httpUrl("source.txt"),
- target: targetFile,
- });
- download.start().catch(() => {});
- } else {
- download = yield promiseStartLegacyDownload(null,
- { targetFile: targetFile });
- }
- yield promiseDownloadStopped(download);
- do_throw("The download should have failed.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseTargetFailed) {
- throw ex;
- }
- // A specific error object is thrown when writing to the target fails.
- } finally {
- // Restore the default permissions to allow deleting the file on Windows.
- if (targetFile.exists()) {
- targetFile.permissions = FileUtils.PERMS_FILE;
-
- // Also for Windows, rename the file before deleting. This makes the
- // current file name available immediately for a new file, while deleting
- // in place prevents creation of a file with the same name for some time.
- targetFile.moveTo(null, targetFile.leafName + ".delete.tmp");
- targetFile.remove(false);
- }
- }
-
- // Restart the download and wait for completion.
- yield download.start();
-
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.canceled);
- do_check_true(download.error === null);
- do_check_eq(download.progress, 100);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
-});
-
-/**
- * Executes download in both public and private modes.
- */
-add_task(function* test_public_and_private()
-{
- let sourcePath = "/test_public_and_private.txt";
- let sourceUrl = httpUrl("test_public_and_private.txt");
- let testCount = 0;
-
- // Apply pref to allow all cookies.
- Services.prefs.setIntPref("network.cookie.cookieBehavior", 0);
-
- function cleanup() {
- Services.prefs.clearUserPref("network.cookie.cookieBehavior");
- Services.cookies.removeAll();
- gHttpServer.registerPathHandler(sourcePath, null);
- }
- do_register_cleanup(cleanup);
-
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
-
- if (testCount == 0) {
- // No cookies should exist for first public download.
- do_check_false(aRequest.hasHeader("Cookie"));
- aResponse.setHeader("Set-Cookie", "foobar=1", false);
- testCount++;
- } else if (testCount == 1) {
- // The cookie should exists for second public download.
- do_check_true(aRequest.hasHeader("Cookie"));
- do_check_eq(aRequest.getHeader("Cookie"), "foobar=1");
- testCount++;
- } else if (testCount == 2) {
- // No cookies should exist for first private download.
- do_check_false(aRequest.hasHeader("Cookie"));
- }
- });
-
- let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
- yield Downloads.fetch(sourceUrl, targetFile);
- yield Downloads.fetch(sourceUrl, targetFile);
-
- if (!gUseLegacySaver) {
- let download = yield Downloads.createDownload({
- source: { url: sourceUrl, isPrivate: true },
- target: targetFile,
- });
- yield download.start();
- } else {
- let download = yield promiseStartLegacyDownload(sourceUrl,
- { isPrivate: true });
- yield promiseDownloadStopped(download);
- }
-
- cleanup();
-});
-
-/**
- * Checks the startTime gets updated even after a restart.
- */
-add_task(function* test_cancel_immediately_restart_and_check_startTime()
-{
- let download = yield promiseStartDownload();
-
- let startTime = download.startTime;
- do_check_true(isValidDate(download.startTime));
-
- yield download.cancel();
- do_check_eq(download.startTime.getTime(), startTime.getTime());
-
- // Wait for a timeout.
- yield promiseTimeout(10);
-
- yield download.start();
- do_check_true(download.startTime.getTime() > startTime.getTime());
-});
-
-/**
- * Executes download with content-encoding.
- */
-add_task(function* test_with_content_encoding()
-{
- let sourcePath = "/test_with_content_encoding.txt";
- let sourceUrl = httpUrl("test_with_content_encoding.txt");
-
- function cleanup() {
- gHttpServer.registerPathHandler(sourcePath, null);
- }
- do_register_cleanup(cleanup);
-
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
- aResponse.setHeader("Content-Encoding", "gzip", false);
- aResponse.setHeader("Content-Length",
- "" + TEST_DATA_SHORT_GZIP_ENCODED.length, false);
-
- let bos = new BinaryOutputStream(aResponse.bodyOutputStream);
- bos.writeByteArray(TEST_DATA_SHORT_GZIP_ENCODED,
- TEST_DATA_SHORT_GZIP_ENCODED.length);
- });
-
- let download = yield promiseStartDownload(sourceUrl);
- yield promiseDownloadStopped(download);
-
- do_check_eq(download.progress, 100);
- do_check_eq(download.totalBytes, TEST_DATA_SHORT_GZIP_ENCODED.length);
-
- // Ensure the content matches the decoded test data.
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
-
- cleanup();
-});
-
-/**
- * Checks that the file is not decoded if the extension matches the encoding.
- */
-add_task(function* test_with_content_encoding_ignore_extension()
-{
- let sourcePath = "/test_with_content_encoding_ignore_extension.gz";
- let sourceUrl = httpUrl("test_with_content_encoding_ignore_extension.gz");
-
- function cleanup() {
- gHttpServer.registerPathHandler(sourcePath, null);
- }
- do_register_cleanup(cleanup);
-
- gHttpServer.registerPathHandler(sourcePath, function (aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
- aResponse.setHeader("Content-Encoding", "gzip", false);
- aResponse.setHeader("Content-Length",
- "" + TEST_DATA_SHORT_GZIP_ENCODED.length, false);
-
- let bos = new BinaryOutputStream(aResponse.bodyOutputStream);
- bos.writeByteArray(TEST_DATA_SHORT_GZIP_ENCODED,
- TEST_DATA_SHORT_GZIP_ENCODED.length);
- });
-
- let download = yield promiseStartDownload(sourceUrl);
- yield promiseDownloadStopped(download);
-
- do_check_eq(download.progress, 100);
- do_check_eq(download.totalBytes, TEST_DATA_SHORT_GZIP_ENCODED.length);
- do_check_eq(download.target.size, TEST_DATA_SHORT_GZIP_ENCODED.length);
-
- // Ensure the content matches the encoded test data. We convert the data to a
- // string before executing the content check.
- yield promiseVerifyTarget(download.target,
- String.fromCharCode.apply(String, TEST_DATA_SHORT_GZIP_ENCODED));
-
- cleanup();
-});
-
-/**
- * Cancels and restarts a download sequentially with content-encoding.
- */
-add_task(function* test_cancel_midway_restart_with_content_encoding()
-{
- mustInterruptResponses();
-
- let download = yield promiseStartDownload(httpUrl("interruptible_gzip.txt"));
-
- // The first time, cancel the download midway.
- let deferCancel = Promise.defer();
- let onchange = function () {
- if (!download.stopped && !download.canceled &&
- download.currentBytes == TEST_DATA_SHORT_GZIP_ENCODED_FIRST.length) {
- deferCancel.resolve(download.cancel());
- }
- };
-
- // Register for the notification, but also call the function directly in
- // case the download already reached the expected progress.
- download.onchange = onchange;
- onchange();
-
- yield deferCancel.promise;
-
- do_check_true(download.stopped);
-
- // The second time, we'll provide the entire interruptible response.
- continueResponses();
- download.onchange = null;
- yield download.start();
-
- do_check_eq(download.progress, 100);
- do_check_eq(download.totalBytes, TEST_DATA_SHORT_GZIP_ENCODED.length);
-
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT);
-});
-
-/**
- * Download with parental controls enabled.
- */
-add_task(function* test_blocked_parental_controls()
-{
- let blockFn = base => ({
- shouldBlockForParentalControls: () => Promise.resolve(true),
- });
-
- Integration.downloads.register(blockFn);
- function cleanup() {
- Integration.downloads.unregister(blockFn);
- }
- do_register_cleanup(cleanup);
-
- let download;
- try {
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we want to check that the promise
- // returned by the "start" method is rejected.
- download = yield promiseNewDownload();
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, we cannot be sure whether we are
- // testing the promise returned by the "start" method or we are testing
- // the "error" property checked by promiseDownloadStopped. This happens
- // because we don't have control over when the download is started.
- download = yield promiseStartLegacyDownload();
- yield promiseDownloadStopped(download);
- }
- do_throw("The download should have blocked.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseBlocked) {
- throw ex;
- }
- do_check_true(ex.becauseBlockedByParentalControls);
- do_check_true(download.error.becauseBlockedByParentalControls);
- }
-
- // Now that the download stopped, the target file should not exist.
- do_check_false(yield OS.File.exists(download.target.path));
-
- cleanup();
-});
-
-/**
- * Test a download that will be blocked by Windows parental controls by
- * resulting in an HTTP status code of 450.
- */
-add_task(function* test_blocked_parental_controls_httpstatus450()
-{
- let download;
- try {
- if (!gUseLegacySaver) {
- download = yield promiseNewDownload(httpUrl("parentalblocked.zip"));
- yield download.start();
- }
- else {
- download = yield promiseStartLegacyDownload(httpUrl("parentalblocked.zip"));
- yield promiseDownloadStopped(download);
- }
- do_throw("The download should have blocked.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseBlocked) {
- throw ex;
- }
- do_check_true(ex.becauseBlockedByParentalControls);
- do_check_true(download.error.becauseBlockedByParentalControls);
- do_check_true(download.stopped);
- }
-
- do_check_false(yield OS.File.exists(download.target.path));
-});
-
-/**
- * Download with runtime permissions
- */
-add_task(function* test_blocked_runtime_permissions()
-{
- let blockFn = base => ({
- shouldBlockForRuntimePermissions: () => Promise.resolve(true),
- });
-
- Integration.downloads.register(blockFn);
- function cleanup() {
- Integration.downloads.unregister(blockFn);
- }
- do_register_cleanup(cleanup);
-
- let download;
- try {
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we want to check that the promise
- // returned by the "start" method is rejected.
- download = yield promiseNewDownload();
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, we cannot be sure whether we are
- // testing the promise returned by the "start" method or we are testing
- // the "error" property checked by promiseDownloadStopped. This happens
- // because we don't have control over when the download is started.
- download = yield promiseStartLegacyDownload();
- yield promiseDownloadStopped(download);
- }
- do_throw("The download should have blocked.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseBlocked) {
- throw ex;
- }
- do_check_true(ex.becauseBlockedByRuntimePermissions);
- do_check_true(download.error.becauseBlockedByRuntimePermissions);
- }
-
- // Now that the download stopped, the target file should not exist.
- do_check_false(yield OS.File.exists(download.target.path));
-
- cleanup();
-});
-
-/**
- * Check that DownloadCopySaver can always retrieve the hash.
- * DownloadLegacySaver can only retrieve the hash when
- * nsIExternalHelperAppService is invoked.
- */
-add_task(function* test_getSha256Hash()
-{
- if (!gUseLegacySaver) {
- let download = yield promiseStartDownload(httpUrl("source.txt"));
- yield promiseDownloadStopped(download);
- do_check_true(download.stopped);
- do_check_eq(32, download.saver.getSha256Hash().length);
- }
-});
-
-/**
- * Create a download which will be reputation blocked.
- *
- * @param options
- * {
- * keepPartialData: bool,
- * keepBlockedData: bool,
- * }
- * @return {Promise}
- * @resolves The reputation blocked download.
- * @rejects JavaScript exception.
- */
-var promiseBlockedDownload = Task.async(function* (options) {
- let blockFn = base => ({
- shouldBlockForReputationCheck: () => Promise.resolve({
- shouldBlock: true,
- verdict: Downloads.Error.BLOCK_VERDICT_UNCOMMON,
- }),
- shouldKeepBlockedData: () => Promise.resolve(options.keepBlockedData),
- });
-
- Integration.downloads.register(blockFn);
- function cleanup() {
- Integration.downloads.unregister(blockFn);
- }
- do_register_cleanup(cleanup);
-
- let download;
-
- try {
- if (options.keepPartialData) {
- download = yield promiseStartDownload_tryToKeepPartialData();
- continueResponses();
- } else if (gUseLegacySaver) {
- download = yield promiseStartLegacyDownload();
- } else {
- download = yield promiseNewDownload();
- yield download.start();
- do_throw("The download should have blocked.");
- }
-
- yield promiseDownloadStopped(download);
- do_throw("The download should have blocked.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseBlocked) {
- throw ex;
- }
- do_check_true(ex.becauseBlockedByReputationCheck);
- do_check_eq(ex.reputationCheckVerdict,
- Downloads.Error.BLOCK_VERDICT_UNCOMMON);
- do_check_true(download.error.becauseBlockedByReputationCheck);
- do_check_eq(download.error.reputationCheckVerdict,
- Downloads.Error.BLOCK_VERDICT_UNCOMMON);
- }
-
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_false(yield OS.File.exists(download.target.path));
-
- cleanup();
- return download;
-});
-
-/**
- * Checks that application reputation blocks the download and the target file
- * does not exist.
- */
-add_task(function* test_blocked_applicationReputation()
-{
- let download = yield promiseBlockedDownload({
- keepPartialData: false,
- keepBlockedData: false,
- });
-
- // Now that the download is blocked, the target file should not exist.
- do_check_false(yield OS.File.exists(download.target.path));
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-
- // There should also be no blocked data in this case
- do_check_false(download.hasBlockedData);
-});
-
-/**
- * Checks that if a download restarts while processing an application reputation
- * request, the status is handled correctly.
- */
-add_task(function* test_blocked_applicationReputation_race()
-{
- let isFirstShouldBlockCall = true;
-
- let blockFn = base => ({
- shouldBlockForReputationCheck(download) {
- if (isFirstShouldBlockCall) {
- isFirstShouldBlockCall = false;
-
- // 2. Cancel and restart the download before the first attempt has a
- // chance to finish.
- download.cancel();
- download.removePartialData();
- download.start();
-
- // 3. Allow the first attempt to finish with a blocked response.
- return Promise.resolve({
- shouldBlock: true,
- verdict: Downloads.Error.BLOCK_VERDICT_UNCOMMON,
- });
- }
-
- // 4/5. Don't block the download the second time. The race condition would
- // occur with the first attempt regardless of whether the second one
- // is blocked, but not blocking here makes the test simpler.
- return Promise.resolve({
- shouldBlock: false,
- verdict: "",
- });
- },
- shouldKeepBlockedData: () => Promise.resolve(true),
- });
-
- Integration.downloads.register(blockFn);
- function cleanup() {
- Integration.downloads.unregister(blockFn);
- }
- do_register_cleanup(cleanup);
-
- let download;
-
- try {
- // 1. Start the download and get a reference to the promise asociated with
- // the first attempt, before allowing the response to continue.
- download = yield promiseStartDownload_tryToKeepPartialData();
- let firstAttempt = promiseDownloadStopped(download);
- continueResponses();
-
- // 4/5. Wait for the first attempt to be completed. The result of this
- // should appear as a cancellation.
- yield firstAttempt;
-
- do_throw("The first attempt should have been canceled.");
- } catch (ex) {
- // The "becauseBlocked" property should be false.
- if (!(ex instanceof Downloads.Error) || ex.becauseBlocked) {
- throw ex;
- }
- }
-
- // 6. Wait for the second attempt to be completed.
- yield promiseDownloadStopped(download);
-
- // 7. At this point, "hasBlockedData" should be false.
- do_check_false(download.hasBlockedData);
-
- cleanup();
-});
-
-/**
- * Checks that application reputation blocks the download but maintains the
- * blocked data, which will be deleted when the block is confirmed.
- */
-add_task(function* test_blocked_applicationReputation_confirmBlock()
-{
- let download = yield promiseBlockedDownload({
- keepPartialData: true,
- keepBlockedData: true,
- });
-
- do_check_true(download.hasBlockedData);
- do_check_true(yield OS.File.exists(download.target.partFilePath));
-
- yield download.confirmBlock();
-
- // After confirming the block the download should be in a failed state and
- // have no downloaded data left on disk.
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_false(download.hasBlockedData);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
- do_check_false(yield OS.File.exists(download.target.path));
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-});
-
-/**
- * Checks that application reputation blocks the download but maintains the
- * blocked data, which will be used to complete the download when unblocking.
- */
-add_task(function* test_blocked_applicationReputation_unblock()
-{
- let download = yield promiseBlockedDownload({
- keepPartialData: true,
- keepBlockedData: true,
- });
-
- do_check_true(download.hasBlockedData);
- do_check_true(yield OS.File.exists(download.target.partFilePath));
-
- yield download.unblock();
-
- // After unblocking the download should have succeeded and be
- // present at the final path.
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.hasBlockedData);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
- yield promiseVerifyTarget(download.target, TEST_DATA_SHORT + TEST_DATA_SHORT);
-
- // The only indication the download was previously blocked is the
- // existence of the error, so we make sure it's still set.
- do_check_true(download.error instanceof Downloads.Error);
- do_check_true(download.error.becauseBlocked);
- do_check_true(download.error.becauseBlockedByReputationCheck);
-});
-
-/**
- * Check that calling cancel on a blocked download will not cause errors
- */
-add_task(function* test_blocked_applicationReputation_cancel()
-{
- let download = yield promiseBlockedDownload({
- keepPartialData: true,
- keepBlockedData: true,
- });
-
- // This call should succeed on a blocked download.
- yield download.cancel();
-
- // Calling cancel should not have changed the current state, the download
- // should still be blocked.
- do_check_true(download.error.becauseBlockedByReputationCheck);
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_true(download.hasBlockedData);
-});
-
-/**
- * Checks that unblock and confirmBlock cannot race on a blocked download
- */
-add_task(function* test_blocked_applicationReputation_decisionRace()
-{
- let download = yield promiseBlockedDownload({
- keepPartialData: true,
- keepBlockedData: true,
- });
-
- let unblockPromise = download.unblock();
- let confirmBlockPromise = download.confirmBlock();
-
- yield confirmBlockPromise.then(() => {
- do_throw("confirmBlock should have failed.");
- }, () => {});
-
- yield unblockPromise;
-
- // After unblocking the download should have succeeded and be
- // present at the final path.
- do_check_true(download.stopped);
- do_check_true(download.succeeded);
- do_check_false(download.hasBlockedData);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
- do_check_true(yield OS.File.exists(download.target.path));
-
- download = yield promiseBlockedDownload({
- keepPartialData: true,
- keepBlockedData: true,
- });
-
- confirmBlockPromise = download.confirmBlock();
- unblockPromise = download.unblock();
-
- yield unblockPromise.then(() => {
- do_throw("unblock should have failed.");
- }, () => {});
-
- yield confirmBlockPromise;
-
- // After confirming the block the download should be in a failed state and
- // have no downloaded data left on disk.
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_false(download.hasBlockedData);
- do_check_false(yield OS.File.exists(download.target.partFilePath));
- do_check_false(yield OS.File.exists(download.target.path));
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-});
-
-/**
- * Checks that unblocking a blocked download fails if the blocked data has been
- * removed.
- */
-add_task(function* test_blocked_applicationReputation_unblock()
-{
- let download = yield promiseBlockedDownload({
- keepPartialData: true,
- keepBlockedData: true,
- });
-
- do_check_true(download.hasBlockedData);
- do_check_true(yield OS.File.exists(download.target.partFilePath));
-
- // Remove the blocked data without telling the download.
- yield OS.File.remove(download.target.partFilePath);
-
- let unblockPromise = download.unblock();
- yield unblockPromise.then(() => {
- do_throw("unblock should have failed.");
- }, () => {});
-
- // Even though unblocking failed the download state should have been updated
- // to reflect the lack of blocked data.
- do_check_false(download.hasBlockedData);
- do_check_true(download.stopped);
- do_check_false(download.succeeded);
- do_check_false(download.target.exists);
- do_check_eq(download.target.size, 0);
-});
-
-/**
- * download.showContainingDirectory() action
- */
-add_task(function* test_showContainingDirectory() {
- let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
-
- let download = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt") },
- target: ""
- });
-
- let promiseDirectoryShown = waitForDirectoryShown();
- yield download.showContainingDirectory();
- let path = yield promiseDirectoryShown;
- try {
- new FileUtils.File(path);
- do_throw("Should have failed because of an invalid path.");
- } catch (ex) {
- if (!(ex instanceof Components.Exception)) {
- throw ex;
- }
- // Invalid paths on Windows are reported with NS_ERROR_FAILURE,
- // but with NS_ERROR_FILE_UNRECOGNIZED_PATH on Mac/Linux
- let validResult = ex.result == Cr.NS_ERROR_FILE_UNRECOGNIZED_PATH ||
- ex.result == Cr.NS_ERROR_FAILURE;
- do_check_true(validResult);
- }
-
- download = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt") },
- target: targetPath
- });
-
- promiseDirectoryShown = waitForDirectoryShown();
- download.showContainingDirectory();
- yield promiseDirectoryShown;
-});
-
-/**
- * download.launch() action
- */
-add_task(function* test_launch() {
- let customLauncher = getTempFile("app-launcher");
-
- // Test both with and without setting a custom application.
- for (let launcherPath of [null, customLauncher.path]) {
- let download;
- if (!gUseLegacySaver) {
- // When testing DownloadCopySaver, we have control over the download, thus
- // we can test that file is not launched if download.succeeded is not set.
- download = yield Downloads.createDownload({
- source: httpUrl("source.txt"),
- target: getTempFile(TEST_TARGET_FILE_NAME).path,
- launcherPath: launcherPath,
- launchWhenSucceeded: true
- });
-
- try {
- yield download.launch();
- do_throw("Can't launch download file as it has not completed yet");
- } catch (ex) {
- do_check_eq(ex.message,
- "launch can only be called if the download succeeded");
- }
-
- yield download.start();
- } else {
- // When testing DownloadLegacySaver, the download is already started when
- // it is created, thus we don't test calling "launch" before starting.
- download = yield promiseStartLegacyDownload(
- httpUrl("source.txt"),
- { launcherPath: launcherPath,
- launchWhenSucceeded: true });
- yield promiseDownloadStopped(download);
- }
-
- do_check_true(download.launchWhenSucceeded);
-
- let promiseFileLaunched = waitForFileLaunched();
- download.launch();
- let result = yield promiseFileLaunched;
-
- // Verify that the results match the test case.
- if (!launcherPath) {
- // This indicates that the default handler has been chosen.
- do_check_true(result === null);
- } else {
- // Check the nsIMIMEInfo instance that would have been used for launching.
- do_check_eq(result.preferredAction, Ci.nsIMIMEInfo.useHelperApp);
- do_check_true(result.preferredApplicationHandler
- .QueryInterface(Ci.nsILocalHandlerApp)
- .executable.equals(customLauncher));
- }
- }
-});
-
-/**
- * Test passing an invalid path as the launcherPath property.
- */
-add_task(function* test_launcherPath_invalid() {
- let download = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt") },
- target: { path: getTempFile(TEST_TARGET_FILE_NAME).path },
- launcherPath: " "
- });
-
- let promiseDownloadLaunched = new Promise(resolve => {
- let waitFn = base => ({
- __proto__: base,
- launchDownload() {
- Integration.downloads.unregister(waitFn);
- let superPromise = super.launchDownload(...arguments);
- resolve(superPromise);
- return superPromise;
- },
- });
- Integration.downloads.register(waitFn);
- });
-
- yield download.start();
- try {
- download.launch();
- yield promiseDownloadLaunched;
- do_throw("Can't launch file with invalid custom launcher")
- } catch (ex) {
- if (!(ex instanceof Components.Exception)) {
- throw ex;
- }
- // Invalid paths on Windows are reported with NS_ERROR_FAILURE,
- // but with NS_ERROR_FILE_UNRECOGNIZED_PATH on Mac/Linux
- let validResult = ex.result == Cr.NS_ERROR_FILE_UNRECOGNIZED_PATH ||
- ex.result == Cr.NS_ERROR_FAILURE;
- do_check_true(validResult);
- }
-});
-
-/**
- * Tests that download.launch() is automatically called after
- * the download finishes if download.launchWhenSucceeded = true
- */
-add_task(function* test_launchWhenSucceeded() {
- let customLauncher = getTempFile("app-launcher");
-
- // Test both with and without setting a custom application.
- for (let launcherPath of [null, customLauncher.path]) {
- let promiseFileLaunched = waitForFileLaunched();
-
- if (!gUseLegacySaver) {
- let download = yield Downloads.createDownload({
- source: httpUrl("source.txt"),
- target: getTempFile(TEST_TARGET_FILE_NAME).path,
- launchWhenSucceeded: true,
- launcherPath: launcherPath,
- });
- yield download.start();
- } else {
- let download = yield promiseStartLegacyDownload(
- httpUrl("source.txt"),
- { launcherPath: launcherPath,
- launchWhenSucceeded: true });
- yield promiseDownloadStopped(download);
- }
-
- let result = yield promiseFileLaunched;
-
- // Verify that the results match the test case.
- if (!launcherPath) {
- // This indicates that the default handler has been chosen.
- do_check_true(result === null);
- } else {
- // Check the nsIMIMEInfo instance that would have been used for launching.
- do_check_eq(result.preferredAction, Ci.nsIMIMEInfo.useHelperApp);
- do_check_true(result.preferredApplicationHandler
- .QueryInterface(Ci.nsILocalHandlerApp)
- .executable.equals(customLauncher));
- }
- }
-});
-
-/**
- * Tests that the proper content type is set for a normal download.
- */
-add_task(function* test_contentType() {
- let download = yield promiseStartDownload(httpUrl("source.txt"));
- yield promiseDownloadStopped(download);
-
- do_check_eq("text/plain", download.contentType);
-});
-
-/**
- * Tests that the serialization/deserialization of the startTime Date
- * object works correctly.
- */
-add_task(function* test_toSerializable_startTime()
-{
- let download1 = yield promiseStartDownload(httpUrl("source.txt"));
- yield promiseDownloadStopped(download1);
-
- let serializable = download1.toSerializable();
- let reserialized = JSON.parse(JSON.stringify(serializable));
-
- let download2 = yield Downloads.createDownload(reserialized);
-
- do_check_eq(download1.startTime.constructor.name, "Date");
- do_check_eq(download2.startTime.constructor.name, "Date");
- do_check_eq(download1.startTime.toJSON(), download2.startTime.toJSON());
-});
-
-/**
- * Checks that downloads are added to browsing history when they start.
- */
-add_task(function* test_history()
-{
- mustInterruptResponses();
-
- // We will wait for the visit to be notified during the download.
- yield PlacesTestUtils.clearHistory();
- let promiseVisit = promiseWaitForVisit(httpUrl("interruptible.txt"));
-
- // Start a download that is not allowed to finish yet.
- let download = yield promiseStartDownload(httpUrl("interruptible.txt"));
-
- // The history notifications should be received before the download completes.
- let [time, transitionType] = yield promiseVisit;
- do_check_eq(time, download.startTime.getTime() * 1000);
- do_check_eq(transitionType, Ci.nsINavHistoryService.TRANSITION_DOWNLOAD);
-
- // Restart and complete the download after clearing history.
- yield PlacesTestUtils.clearHistory();
- download.cancel();
- continueResponses();
- yield download.start();
-
- // The restart should not have added a new history visit.
- do_check_false(yield promiseIsURIVisited(httpUrl("interruptible.txt")));
-});
-
-/**
- * Checks that downloads started by nsIHelperAppService are added to the
- * browsing history when they start.
- */
-add_task(function* test_history_tryToKeepPartialData()
-{
- // We will wait for the visit to be notified during the download.
- yield PlacesTestUtils.clearHistory();
- let promiseVisit =
- promiseWaitForVisit(httpUrl("interruptible_resumable.txt"));
-
- // Start a download that is not allowed to finish yet.
- let beforeStartTimeMs = Date.now();
- let download = yield promiseStartDownload_tryToKeepPartialData();
-
- // The history notifications should be received before the download completes.
- let [time, transitionType] = yield promiseVisit;
- do_check_eq(transitionType, Ci.nsINavHistoryService.TRANSITION_DOWNLOAD);
-
- // The time set by nsIHelperAppService may be different than the start time in
- // the download object, thus we only check that it is a meaningful time. Note
- // that we subtract one second from the earliest time to account for rounding.
- do_check_true(time >= beforeStartTimeMs * 1000 - 1000000);
-
- // Complete the download before finishing the test.
- continueResponses();
- yield promiseDownloadStopped(download);
-});
-
-/**
- * Tests that the temp download files are removed on exit and exiting private
- * mode after they have been launched.
- */
-add_task(function* test_launchWhenSucceeded_deleteTempFileOnExit() {
- let customLauncherPath = getTempFile("app-launcher").path;
- let autoDeleteTargetPathOne = getTempFile(TEST_TARGET_FILE_NAME).path;
- let autoDeleteTargetPathTwo = getTempFile(TEST_TARGET_FILE_NAME).path;
- let noAutoDeleteTargetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
-
- let autoDeleteDownloadOne = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt"), isPrivate: true },
- target: autoDeleteTargetPathOne,
- launchWhenSucceeded: true,
- launcherPath: customLauncherPath,
- });
- yield autoDeleteDownloadOne.start();
-
- Services.prefs.setBoolPref(kDeleteTempFileOnExit, true);
- let autoDeleteDownloadTwo = yield Downloads.createDownload({
- source: httpUrl("source.txt"),
- target: autoDeleteTargetPathTwo,
- launchWhenSucceeded: true,
- launcherPath: customLauncherPath,
- });
- yield autoDeleteDownloadTwo.start();
-
- Services.prefs.setBoolPref(kDeleteTempFileOnExit, false);
- let noAutoDeleteDownload = yield Downloads.createDownload({
- source: httpUrl("source.txt"),
- target: noAutoDeleteTargetPath,
- launchWhenSucceeded: true,
- launcherPath: customLauncherPath,
- });
- yield noAutoDeleteDownload.start();
-
- Services.prefs.clearUserPref(kDeleteTempFileOnExit);
-
- do_check_true(yield OS.File.exists(autoDeleteTargetPathOne));
- do_check_true(yield OS.File.exists(autoDeleteTargetPathTwo));
- do_check_true(yield OS.File.exists(noAutoDeleteTargetPath));
-
- // Simulate leaving private browsing mode
- Services.obs.notifyObservers(null, "last-pb-context-exited", null);
- do_check_false(yield OS.File.exists(autoDeleteTargetPathOne));
-
- // Simulate browser shutdown
- let expire = Cc["@mozilla.org/uriloader/external-helper-app-service;1"]
- .getService(Ci.nsIObserver);
- expire.observe(null, "profile-before-change", null);
- do_check_false(yield OS.File.exists(autoDeleteTargetPathTwo));
- do_check_true(yield OS.File.exists(noAutoDeleteTargetPath));
-});
diff --git a/toolkit/components/jsdownloads/test/unit/head.js b/toolkit/components/jsdownloads/test/unit/head.js
deleted file mode 100644
index f322244c4..000000000
--- a/toolkit/components/jsdownloads/test/unit/head.js
+++ /dev/null
@@ -1,843 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Provides infrastructure for automated download components tests.
- */
-
-"use strict";
-
-// Globals
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource://gre/modules/Integration.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths",
- "resource://gre/modules/DownloadPaths.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
- "resource://gre/modules/Downloads.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "HttpServer",
- "resource://testing-common/httpd.js");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Services",
- "resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "MockRegistrar",
- "resource://testing-common/MockRegistrar.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gExternalHelperAppService",
- "@mozilla.org/uriloader/external-helper-app-service;1",
- Ci.nsIExternalHelperAppService);
-
-Integration.downloads.defineModuleGetter(this, "DownloadIntegration",
- "resource://gre/modules/DownloadIntegration.jsm");
-
-const ServerSocket = Components.Constructor(
- "@mozilla.org/network/server-socket;1",
- "nsIServerSocket",
- "init");
-const BinaryOutputStream = Components.Constructor(
- "@mozilla.org/binaryoutputstream;1",
- "nsIBinaryOutputStream",
- "setOutputStream")
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMIMEService",
- "@mozilla.org/mime;1",
- "nsIMIMEService");
-
-const TEST_TARGET_FILE_NAME = "test-download.txt";
-const TEST_STORE_FILE_NAME = "test-downloads.json";
-
-const TEST_REFERRER_URL = "http://www.example.com/referrer.html";
-
-const TEST_DATA_SHORT = "This test string is downloaded.";
-// Generate using gzipCompressString in TelemetryController.jsm.
-const TEST_DATA_SHORT_GZIP_ENCODED_FIRST = [
- 31, 139, 8, 0, 0, 0, 0, 0, 0, 3, 11, 201, 200, 44, 86, 40, 73, 45, 46, 81, 40, 46, 41, 202, 204
-];
-const TEST_DATA_SHORT_GZIP_ENCODED_SECOND = [
- 75, 87, 0, 114, 83, 242, 203, 243, 114, 242, 19, 83, 82, 83, 244, 0, 151, 222, 109, 43, 31, 0, 0, 0
-];
-const TEST_DATA_SHORT_GZIP_ENCODED =
- TEST_DATA_SHORT_GZIP_ENCODED_FIRST.concat(TEST_DATA_SHORT_GZIP_ENCODED_SECOND);
-
-/**
- * All the tests are implemented with add_task, this starts them automatically.
- */
-function run_test()
-{
- do_get_profile();
- run_next_test();
-}
-
-// Support functions
-
-/**
- * HttpServer object initialized before tests start.
- */
-var gHttpServer;
-
-/**
- * Given a file name, returns a string containing an URI that points to the file
- * on the currently running instance of the test HTTP server.
- */
-function httpUrl(aFileName) {
- return "http://localhost:" + gHttpServer.identity.primaryPort + "/" +
- aFileName;
-}
-
-// While the previous test file should have deleted all the temporary files it
-// used, on Windows these might still be pending deletion on the physical file
-// system. Thus, start from a new base number every time, to make a collision
-// with a file that is still pending deletion highly unlikely.
-var gFileCounter = Math.floor(Math.random() * 1000000);
-
-/**
- * Returns a reference to a temporary file, that is guaranteed not to exist, and
- * to have never been created before.
- *
- * @param aLeafName
- * Suggested leaf name for the file to be created.
- *
- * @return nsIFile pointing to a non-existent file in a temporary directory.
- *
- * @note It is not enough to delete the file if it exists, or to delete the file
- * after calling nsIFile.createUnique, because on Windows the delete
- * operation in the file system may still be pending, preventing a new
- * file with the same name to be created.
- */
-function getTempFile(aLeafName)
-{
- // Prepend a serial number to the extension in the suggested leaf name.
- let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
- let leafName = base + "-" + gFileCounter + ext;
- gFileCounter++;
-
- // Get a file reference under the temporary directory for this test file.
- let file = FileUtils.getFile("TmpD", [leafName]);
- do_check_false(file.exists());
-
- do_register_cleanup(function () {
- try {
- file.remove(false)
- } catch (e) {
- if (!(e instanceof Components.Exception &&
- (e.result == Cr.NS_ERROR_FILE_ACCESS_DENIED ||
- e.result == Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST ||
- e.result == Cr.NS_ERROR_FILE_NOT_FOUND))) {
- throw e;
- }
- // On Windows, we may get an access denied error if the file existed before,
- // and was recently deleted.
- // Don't bother checking file.exists() as that may also cause an access
- // denied error.
- }
- });
-
- return file;
-}
-
-/**
- * Waits for pending events to be processed.
- *
- * @return {Promise}
- * @resolves When pending events have been processed.
- * @rejects Never.
- */
-function promiseExecuteSoon()
-{
- let deferred = Promise.defer();
- do_execute_soon(deferred.resolve);
- return deferred.promise;
-}
-
-/**
- * Waits for a pending events to be processed after a timeout.
- *
- * @return {Promise}
- * @resolves When pending events have been processed.
- * @rejects Never.
- */
-function promiseTimeout(aTime)
-{
- let deferred = Promise.defer();
- do_timeout(aTime, deferred.resolve);
- return deferred.promise;
-}
-
-/**
- * Waits for a new history visit to be notified for the specified URI.
- *
- * @param aUrl
- * String containing the URI that will be visited.
- *
- * @return {Promise}
- * @resolves Array [aTime, aTransitionType] from nsINavHistoryObserver.onVisit.
- * @rejects Never.
- */
-function promiseWaitForVisit(aUrl)
-{
- let deferred = Promise.defer();
-
- let uri = NetUtil.newURI(aUrl);
-
- PlacesUtils.history.addObserver({
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver]),
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType, aGUID, aHidden) {
- if (aURI.equals(uri)) {
- PlacesUtils.history.removeObserver(this);
- deferred.resolve([aTime, aTransitionType]);
- }
- },
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
- }, false);
-
- return deferred.promise;
-}
-
-/**
- * Check browsing history to see whether the given URI has been visited.
- *
- * @param aUrl
- * String containing the URI that will be visited.
- *
- * @return {Promise}
- * @resolves Boolean indicating whether the URI has been visited.
- * @rejects JavaScript exception.
- */
-function promiseIsURIVisited(aUrl) {
- let deferred = Promise.defer();
-
- PlacesUtils.asyncHistory.isURIVisited(NetUtil.newURI(aUrl),
- function (aURI, aIsVisited) {
- deferred.resolve(aIsVisited);
- });
-
- return deferred.promise;
-}
-
-/**
- * Creates a new Download object, setting a temporary file as the target.
- *
- * @param aSourceUrl
- * String containing the URI for the download source, or null to use
- * httpUrl("source.txt").
- *
- * @return {Promise}
- * @resolves The newly created Download object.
- * @rejects JavaScript exception.
- */
-function promiseNewDownload(aSourceUrl) {
- return Downloads.createDownload({
- source: aSourceUrl || httpUrl("source.txt"),
- target: getTempFile(TEST_TARGET_FILE_NAME),
- });
-}
-
-/**
- * Starts a new download using the nsIWebBrowserPersist interface, and controls
- * it using the legacy nsITransfer interface.
- *
- * @param aSourceUrl
- * String containing the URI for the download source, or null to use
- * httpUrl("source.txt").
- * @param aOptions
- * An optional object used to control the behavior of this function.
- * You may pass an object with a subset of the following fields:
- * {
- * isPrivate: Boolean indicating whether the download originated from a
- * private window.
- * targetFile: nsIFile for the target, or null to use a temporary file.
- * outPersist: Receives a reference to the created nsIWebBrowserPersist
- * instance.
- * launchWhenSucceeded: Boolean indicating whether the target should
- * be launched when it has completed successfully.
- * launcherPath: String containing the path of the custom executable to
- * use to launch the target of the download.
- * }
- *
- * @return {Promise}
- * @resolves The Download object created as a consequence of controlling the
- * download through the legacy nsITransfer interface.
- * @rejects Never. The current test fails in case of exceptions.
- */
-function promiseStartLegacyDownload(aSourceUrl, aOptions) {
- let sourceURI = NetUtil.newURI(aSourceUrl || httpUrl("source.txt"));
- let targetFile = (aOptions && aOptions.targetFile)
- || getTempFile(TEST_TARGET_FILE_NAME);
-
- let persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
- .createInstance(Ci.nsIWebBrowserPersist);
- if (aOptions) {
- aOptions.outPersist = persist;
- }
-
- let fileExtension = null, mimeInfo = null;
- let match = sourceURI.path.match(/\.([^.\/]+)$/);
- if (match) {
- fileExtension = match[1];
- }
-
- if (fileExtension) {
- try {
- mimeInfo = gMIMEService.getFromTypeAndExtension(null, fileExtension);
- mimeInfo.preferredAction = Ci.nsIMIMEInfo.saveToDisk;
- } catch (ex) { }
- }
-
- if (aOptions && aOptions.launcherPath) {
- do_check_true(mimeInfo != null);
-
- let localHandlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"]
- .createInstance(Ci.nsILocalHandlerApp);
- localHandlerApp.executable = new FileUtils.File(aOptions.launcherPath);
-
- mimeInfo.preferredApplicationHandler = localHandlerApp;
- mimeInfo.preferredAction = Ci.nsIMIMEInfo.useHelperApp;
- }
-
- if (aOptions && aOptions.launchWhenSucceeded) {
- do_check_true(mimeInfo != null);
-
- mimeInfo.preferredAction = Ci.nsIMIMEInfo.useHelperApp;
- }
-
- // Apply decoding if required by the "Content-Encoding" header.
- persist.persistFlags &= ~Ci.nsIWebBrowserPersist.PERSIST_FLAGS_NO_CONVERSION;
- persist.persistFlags |=
- Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
-
- let transfer = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer);
-
- let deferred = Promise.defer();
-
- Downloads.getList(Downloads.ALL).then(function (aList) {
- // Temporarily register a view that will get notified when the download we
- // are controlling becomes visible in the list of downloads.
- aList.addView({
- onDownloadAdded: function (aDownload) {
- aList.removeView(this).then(null, do_report_unexpected_exception);
-
- // Remove the download to keep the list empty for the next test. This
- // also allows the caller to register the "onchange" event directly.
- let promise = aList.remove(aDownload);
-
- // When the download object is ready, make it available to the caller.
- promise.then(() => deferred.resolve(aDownload),
- do_report_unexpected_exception);
- },
- }).then(null, do_report_unexpected_exception);
-
- let isPrivate = aOptions && aOptions.isPrivate;
-
- // Initialize the components so they reference each other. This will cause
- // the Download object to be created and added to the public downloads.
- transfer.init(sourceURI, NetUtil.newURI(targetFile), null, mimeInfo, null,
- null, persist, isPrivate);
- persist.progressListener = transfer;
-
- // Start the actual download process.
- persist.savePrivacyAwareURI(sourceURI, null, null, 0, null, null, targetFile,
- isPrivate);
- }.bind(this)).then(null, do_report_unexpected_exception);
-
- return deferred.promise;
-}
-
-/**
- * Starts a new download using the nsIHelperAppService interface, and controls
- * it using the legacy nsITransfer interface. The source of the download will
- * be "interruptible_resumable.txt" and partially downloaded data will be kept.
- *
- * @param aSourceUrl
- * String containing the URI for the download source, or null to use
- * httpUrl("interruptible_resumable.txt").
- *
- * @return {Promise}
- * @resolves The Download object created as a consequence of controlling the
- * download through the legacy nsITransfer interface.
- * @rejects Never. The current test fails in case of exceptions.
- */
-function promiseStartExternalHelperAppServiceDownload(aSourceUrl) {
- let sourceURI = NetUtil.newURI(aSourceUrl ||
- httpUrl("interruptible_resumable.txt"));
-
- let deferred = Promise.defer();
-
- Downloads.getList(Downloads.PUBLIC).then(function (aList) {
- // Temporarily register a view that will get notified when the download we
- // are controlling becomes visible in the list of downloads.
- aList.addView({
- onDownloadAdded: function (aDownload) {
- aList.removeView(this).then(null, do_report_unexpected_exception);
-
- // Remove the download to keep the list empty for the next test. This
- // also allows the caller to register the "onchange" event directly.
- let promise = aList.remove(aDownload);
-
- // When the download object is ready, make it available to the caller.
- promise.then(() => deferred.resolve(aDownload),
- do_report_unexpected_exception);
- },
- }).then(null, do_report_unexpected_exception);
-
- let channel = NetUtil.newChannel({
- uri: sourceURI,
- loadUsingSystemPrincipal: true
- });
-
- // Start the actual download process.
- channel.asyncOpen2({
- contentListener: null,
-
- onStartRequest: function (aRequest, aContext)
- {
- let requestChannel = aRequest.QueryInterface(Ci.nsIChannel);
- this.contentListener = gExternalHelperAppService.doContent(
- requestChannel.contentType, aRequest, null, true);
- this.contentListener.onStartRequest(aRequest, aContext);
- },
-
- onStopRequest: function (aRequest, aContext, aStatusCode)
- {
- this.contentListener.onStopRequest(aRequest, aContext, aStatusCode);
- },
-
- onDataAvailable: function (aRequest, aContext, aInputStream, aOffset,
- aCount)
- {
- this.contentListener.onDataAvailable(aRequest, aContext, aInputStream,
- aOffset, aCount);
- },
- });
- }.bind(this)).then(null, do_report_unexpected_exception);
-
- return deferred.promise;
-}
-
-/**
- * Waits for a download to reach half of its progress, in case it has not
- * reached the expected progress already.
- *
- * @param aDownload
- * The Download object to wait upon.
- *
- * @return {Promise}
- * @resolves When the download has reached half of its progress.
- * @rejects Never.
- */
-function promiseDownloadMidway(aDownload) {
- let deferred = Promise.defer();
-
- // Wait for the download to reach half of its progress.
- let onchange = function () {
- if (!aDownload.stopped && !aDownload.canceled && aDownload.progress == 50) {
- aDownload.onchange = null;
- deferred.resolve();
- }
- };
-
- // Register for the notification, but also call the function directly in
- // case the download already reached the expected progress.
- aDownload.onchange = onchange;
- onchange();
-
- return deferred.promise;
-}
-
-/**
- * Waits for a download to finish, in case it has not finished already.
- *
- * @param aDownload
- * The Download object to wait upon.
- *
- * @return {Promise}
- * @resolves When the download has finished successfully.
- * @rejects JavaScript exception if the download failed.
- */
-function promiseDownloadStopped(aDownload) {
- if (!aDownload.stopped) {
- // The download is in progress, wait for the current attempt to finish and
- // report any errors that may occur.
- return aDownload.start();
- }
-
- if (aDownload.succeeded) {
- return Promise.resolve();
- }
-
- // The download failed or was canceled.
- return Promise.reject(aDownload.error || new Error("Download canceled."));
-}
-
-/**
- * Returns a new public or private DownloadList object.
- *
- * @param aIsPrivate
- * True for the private list, false or undefined for the public list.
- *
- * @return {Promise}
- * @resolves The newly created DownloadList object.
- * @rejects JavaScript exception.
- */
-function promiseNewList(aIsPrivate)
-{
- // We need to clear all the internal state for the list and summary objects,
- // since all the objects are interdependent internally.
- Downloads._promiseListsInitialized = null;
- Downloads._lists = {};
- Downloads._summaries = {};
-
- return Downloads.getList(aIsPrivate ? Downloads.PRIVATE : Downloads.PUBLIC);
-}
-
-/**
- * Ensures that the given file contents are equal to the given string.
- *
- * @param aPath
- * String containing the path of the file whose contents should be
- * verified.
- * @param aExpectedContents
- * String containing the octets that are expected in the file.
- *
- * @return {Promise}
- * @resolves When the operation completes.
- * @rejects Never.
- */
-function promiseVerifyContents(aPath, aExpectedContents)
-{
- return Task.spawn(function* () {
- let file = new FileUtils.File(aPath);
-
- if (!(yield OS.File.exists(aPath))) {
- do_throw("File does not exist: " + aPath);
- }
-
- if ((yield OS.File.stat(aPath)).size == 0) {
- do_throw("File is empty: " + aPath);
- }
-
- let deferred = Promise.defer();
- NetUtil.asyncFetch(
- { uri: NetUtil.newURI(file), loadUsingSystemPrincipal: true },
- function(aInputStream, aStatus) {
- do_check_true(Components.isSuccessCode(aStatus));
- let contents = NetUtil.readInputStreamToString(aInputStream,
- aInputStream.available());
- if (contents.length > TEST_DATA_SHORT.length * 2 ||
- /[^\x20-\x7E]/.test(contents)) {
- // Do not print the entire content string to the test log.
- do_check_eq(contents.length, aExpectedContents.length);
- do_check_true(contents == aExpectedContents);
- } else {
- // Print the string if it is short and made of printable characters.
- do_check_eq(contents, aExpectedContents);
- }
- deferred.resolve();
- });
-
- yield deferred.promise;
- });
-}
-
-/**
- * Starts a socket listener that closes each incoming connection.
- *
- * @returns nsIServerSocket that listens for connections. Call its "close"
- * method to stop listening and free the server port.
- */
-function startFakeServer()
-{
- let serverSocket = new ServerSocket(-1, true, -1);
- serverSocket.asyncListen({
- onSocketAccepted: function (aServ, aTransport) {
- aTransport.close(Cr.NS_BINDING_ABORTED);
- },
- onStopListening: function () { },
- });
- return serverSocket;
-}
-
-/**
- * This is an internal reference that should not be used directly by tests.
- */
-var _gDeferResponses = Promise.defer();
-
-/**
- * Ensures that all the interruptible requests started after this function is
- * called won't complete until the continueResponses function is called.
- *
- * Normally, the internal HTTP server returns all the available data as soon as
- * a request is received. In order for some requests to be served one part at a
- * time, special interruptible handlers are registered on the HTTP server. This
- * allows testing events or actions that need to happen in the middle of a
- * download.
- *
- * For example, the handler accessible at the httpUri("interruptible.txt")
- * address returns the TEST_DATA_SHORT text, then it may block until the
- * continueResponses method is called. At this point, the handler sends the
- * TEST_DATA_SHORT text again to complete the response.
- *
- * If an interruptible request is started before the function is called, it may
- * or may not be blocked depending on the actual sequence of events.
- */
-function mustInterruptResponses()
-{
- // If there are pending blocked requests, allow them to complete. This is
- // done to prevent requests from being blocked forever, but should not affect
- // the test logic, since previously started requests should not be monitored
- // on the client side anymore.
- _gDeferResponses.resolve();
-
- do_print("Interruptible responses will be blocked midway.");
- _gDeferResponses = Promise.defer();
-}
-
-/**
- * Allows all the current and future interruptible requests to complete.
- */
-function continueResponses()
-{
- do_print("Interruptible responses are now allowed to continue.");
- _gDeferResponses.resolve();
-}
-
-/**
- * Registers an interruptible response handler.
- *
- * @param aPath
- * Path passed to nsIHttpServer.registerPathHandler.
- * @param aFirstPartFn
- * This function is called when the response is received, with the
- * aRequest and aResponse arguments of the server.
- * @param aSecondPartFn
- * This function is called with the aRequest and aResponse arguments of
- * the server, when the continueResponses function is called.
- */
-function registerInterruptibleHandler(aPath, aFirstPartFn, aSecondPartFn)
-{
- gHttpServer.registerPathHandler(aPath, function (aRequest, aResponse) {
- do_print("Interruptible request started.");
-
- // Process the first part of the response.
- aResponse.processAsync();
- aFirstPartFn(aRequest, aResponse);
-
- // Wait on the current deferred object, then finish the request.
- _gDeferResponses.promise.then(function RIH_onSuccess() {
- aSecondPartFn(aRequest, aResponse);
- aResponse.finish();
- do_print("Interruptible request finished.");
- }).then(null, Cu.reportError);
- });
-}
-
-/**
- * Ensure the given date object is valid.
- *
- * @param aDate
- * The date object to be checked. This value can be null.
- */
-function isValidDate(aDate) {
- return aDate && aDate.getTime && !isNaN(aDate.getTime());
-}
-
-/**
- * Position of the first byte served by the "interruptible_resumable.txt"
- * handler during the most recent response.
- */
-var gMostRecentFirstBytePos;
-
-// Initialization functions common to all tests
-
-add_task(function test_common_initialize()
-{
- // Start the HTTP server.
- gHttpServer = new HttpServer();
- gHttpServer.registerDirectory("/", do_get_file("../data"));
- gHttpServer.start(-1);
- do_register_cleanup(() => {
- return new Promise(resolve => {
- // Ensure all the pending HTTP requests have a chance to finish.
- continueResponses();
- // Stop the HTTP server, calling resolve when it's done.
- gHttpServer.stop(resolve);
- });
- });
-
- // Cache locks might prevent concurrent requests to the same resource, and
- // this may block tests that use the interruptible handlers.
- Services.prefs.setBoolPref("browser.cache.disk.enable", false);
- Services.prefs.setBoolPref("browser.cache.memory.enable", false);
- do_register_cleanup(function () {
- Services.prefs.clearUserPref("browser.cache.disk.enable");
- Services.prefs.clearUserPref("browser.cache.memory.enable");
- });
-
- registerInterruptibleHandler("/interruptible.txt",
- function firstPart(aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
- aResponse.setHeader("Content-Length", "" + (TEST_DATA_SHORT.length * 2),
- false);
- aResponse.write(TEST_DATA_SHORT);
- }, function secondPart(aRequest, aResponse) {
- aResponse.write(TEST_DATA_SHORT);
- });
-
- registerInterruptibleHandler("/interruptible_resumable.txt",
- function firstPart(aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
-
- // Determine if only part of the data should be sent.
- let data = TEST_DATA_SHORT + TEST_DATA_SHORT;
- if (aRequest.hasHeader("Range")) {
- var matches = aRequest.getHeader("Range")
- .match(/^\s*bytes=(\d+)?-(\d+)?\s*$/);
- var firstBytePos = (matches[1] === undefined) ? 0 : matches[1];
- var lastBytePos = (matches[2] === undefined) ? data.length - 1
- : matches[2];
- if (firstBytePos >= data.length) {
- aResponse.setStatusLine(aRequest.httpVersion, 416,
- "Requested Range Not Satisfiable");
- aResponse.setHeader("Content-Range", "*/" + data.length, false);
- aResponse.finish();
- return;
- }
-
- aResponse.setStatusLine(aRequest.httpVersion, 206, "Partial Content");
- aResponse.setHeader("Content-Range", firstBytePos + "-" +
- lastBytePos + "/" +
- data.length, false);
-
- data = data.substring(firstBytePos, lastBytePos + 1);
-
- gMostRecentFirstBytePos = firstBytePos;
- } else {
- gMostRecentFirstBytePos = 0;
- }
-
- aResponse.setHeader("Content-Length", "" + data.length, false);
-
- aResponse.write(data.substring(0, data.length / 2));
-
- // Store the second part of the data on the response object, so that it
- // can be used by the secondPart function.
- aResponse.secondPartData = data.substring(data.length / 2);
- }, function secondPart(aRequest, aResponse) {
- aResponse.write(aResponse.secondPartData);
- });
-
- registerInterruptibleHandler("/interruptible_gzip.txt",
- function firstPart(aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/plain", false);
- aResponse.setHeader("Content-Encoding", "gzip", false);
- aResponse.setHeader("Content-Length", "" + TEST_DATA_SHORT_GZIP_ENCODED.length);
-
- let bos = new BinaryOutputStream(aResponse.bodyOutputStream);
- bos.writeByteArray(TEST_DATA_SHORT_GZIP_ENCODED_FIRST,
- TEST_DATA_SHORT_GZIP_ENCODED_FIRST.length);
- }, function secondPart(aRequest, aResponse) {
- let bos = new BinaryOutputStream(aResponse.bodyOutputStream);
- bos.writeByteArray(TEST_DATA_SHORT_GZIP_ENCODED_SECOND,
- TEST_DATA_SHORT_GZIP_ENCODED_SECOND.length);
- });
-
- gHttpServer.registerPathHandler("/shorter-than-content-length-http-1-1.txt",
- function (aRequest, aResponse) {
- aResponse.processAsync();
- aResponse.setStatusLine("1.1", 200, "OK");
- aResponse.setHeader("Content-Type", "text/plain", false);
- aResponse.setHeader("Content-Length", "" + (TEST_DATA_SHORT.length * 2),
- false);
- aResponse.write(TEST_DATA_SHORT);
- aResponse.finish();
- });
-
- // This URL will emulate being blocked by Windows Parental controls
- gHttpServer.registerPathHandler("/parentalblocked.zip",
- function (aRequest, aResponse) {
- aResponse.setStatusLine(aRequest.httpVersion, 450,
- "Blocked by Windows Parental Controls");
- });
-
- // During unit tests, most of the functions that require profile access or
- // operating system features will be disabled. Individual tests may override
- // them again to check for specific behaviors.
- Integration.downloads.register(base => ({
- __proto__: base,
- loadPublicDownloadListFromStore: () => Promise.resolve(),
- shouldKeepBlockedData: () => Promise.resolve(false),
- shouldBlockForParentalControls: () => Promise.resolve(false),
- shouldBlockForRuntimePermissions: () => Promise.resolve(false),
- shouldBlockForReputationCheck: () => Promise.resolve({
- shouldBlock: false,
- verdict: "",
- }),
- confirmLaunchExecutable: () => Promise.resolve(),
- launchFile: () => Promise.resolve(),
- showContainingDirectory: () => Promise.resolve(),
- // This flag allows re-enabling the default observers during their tests.
- allowObservers: false,
- addListObservers() {
- return this.allowObservers ? super.addListObservers(...arguments)
- : Promise.resolve();
- },
- // This flag allows re-enabling the download directory logic for its tests.
- _allowDirectories: false,
- set allowDirectories(value) {
- this._allowDirectories = value;
- // We have to invalidate the previously computed directory path.
- this._downloadsDirectory = null;
- },
- _getDirectory(name) {
- return super._getDirectory(this._allowDirectories ? name : "TmpD");
- },
- }));
-
- // Make sure that downloads started using nsIExternalHelperAppService are
- // saved to disk without asking for a destination interactively.
- let mock = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIHelperAppLauncherDialog]),
- promptForSaveToFileAsync(aLauncher,
- aWindowContext,
- aDefaultFileName,
- aSuggestedFileExtension,
- aForcePrompt) {
- // The dialog should create the empty placeholder file.
- let file = getTempFile(TEST_TARGET_FILE_NAME);
- file.create(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
- aLauncher.saveDestinationAvailable(file);
- },
- };
-
- let cid = MockRegistrar.register("@mozilla.org/helperapplauncherdialog;1", mock);
- do_register_cleanup(() => {
- MockRegistrar.unregister(cid);
- });
-});
diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadCore.js b/toolkit/components/jsdownloads/test/unit/test_DownloadCore.js
deleted file mode 100644
index 6e32c63d3..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadCore.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the main download interfaces using DownloadCopySaver.
- */
-
-"use strict";
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadError",
- "resource://gre/modules/DownloadCore.jsm");
-
-// Execution of common tests
-
-var gUseLegacySaver = false;
-
-var scriptFile = do_get_file("common_test_Download.js");
-Services.scriptloader.loadSubScript(NetUtil.newURI(scriptFile).spec);
-
-// Tests
-
-/**
- * Tests the DownloadError object.
- */
-add_task(function test_DownloadError()
-{
- let error = new DownloadError({ result: Cr.NS_ERROR_NOT_RESUMABLE,
- message: "Not resumable."});
- do_check_eq(error.result, Cr.NS_ERROR_NOT_RESUMABLE);
- do_check_eq(error.message, "Not resumable.");
- do_check_false(error.becauseSourceFailed);
- do_check_false(error.becauseTargetFailed);
- do_check_false(error.becauseBlocked);
- do_check_false(error.becauseBlockedByParentalControls);
-
- error = new DownloadError({ message: "Unknown error."});
- do_check_eq(error.result, Cr.NS_ERROR_FAILURE);
- do_check_eq(error.message, "Unknown error.");
-
- error = new DownloadError({ result: Cr.NS_ERROR_NOT_RESUMABLE });
- do_check_eq(error.result, Cr.NS_ERROR_NOT_RESUMABLE);
- do_check_true(error.message.indexOf("Exception") > 0);
-
- // becauseSourceFailed will be set, but not the unknown property.
- error = new DownloadError({ message: "Unknown error.",
- becauseSourceFailed: true,
- becauseUnknown: true });
- do_check_true(error.becauseSourceFailed);
- do_check_false("becauseUnknown" in error);
-
- error = new DownloadError({ result: Cr.NS_ERROR_MALFORMED_URI,
- inferCause: true });
- do_check_eq(error.result, Cr.NS_ERROR_MALFORMED_URI);
- do_check_true(error.becauseSourceFailed);
- do_check_false(error.becauseTargetFailed);
- do_check_false(error.becauseBlocked);
- do_check_false(error.becauseBlockedByParentalControls);
-
- // This test does not set inferCause, so becauseSourceFailed will not be set.
- error = new DownloadError({ result: Cr.NS_ERROR_MALFORMED_URI });
- do_check_eq(error.result, Cr.NS_ERROR_MALFORMED_URI);
- do_check_false(error.becauseSourceFailed);
-
- error = new DownloadError({ result: Cr.NS_ERROR_FILE_INVALID_PATH,
- inferCause: true });
- do_check_eq(error.result, Cr.NS_ERROR_FILE_INVALID_PATH);
- do_check_false(error.becauseSourceFailed);
- do_check_true(error.becauseTargetFailed);
- do_check_false(error.becauseBlocked);
- do_check_false(error.becauseBlockedByParentalControls);
-
- error = new DownloadError({ becauseBlocked: true });
- do_check_eq(error.message, "Download blocked.");
- do_check_false(error.becauseSourceFailed);
- do_check_false(error.becauseTargetFailed);
- do_check_true(error.becauseBlocked);
- do_check_false(error.becauseBlockedByParentalControls);
-
- error = new DownloadError({ becauseBlockedByParentalControls: true });
- do_check_eq(error.message, "Download blocked.");
- do_check_false(error.becauseSourceFailed);
- do_check_false(error.becauseTargetFailed);
- do_check_true(error.becauseBlocked);
- do_check_true(error.becauseBlockedByParentalControls);
-});
diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js b/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js
deleted file mode 100644
index 388870f00..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadImport.js
+++ /dev/null
@@ -1,701 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the DownloadImport object.
- */
-
-"use strict";
-
-// Globals
-
-XPCOMUtils.defineLazyModuleGetter(this, "Sqlite",
- "resource://gre/modules/Sqlite.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadImport",
- "resource://gre/modules/DownloadImport.jsm");
-
-// Importable states
-const DOWNLOAD_NOTSTARTED = -1;
-const DOWNLOAD_DOWNLOADING = 0;
-const DOWNLOAD_PAUSED = 4;
-const DOWNLOAD_QUEUED = 5;
-
-// Non importable states
-const DOWNLOAD_FAILED = 2;
-const DOWNLOAD_CANCELED = 3;
-const DOWNLOAD_BLOCKED_PARENTAL = 6;
-const DOWNLOAD_SCANNING = 7;
-const DOWNLOAD_DIRTY = 8;
-const DOWNLOAD_BLOCKED_POLICY = 9;
-
-// The TEST_DATA_TAINTED const is a version of TEST_DATA_SHORT in which the
-// beginning of the data was changed (with the TEST_DATA_REPLACEMENT value).
-// We use this to test that the entityID is properly imported and the download
-// can be resumed from where it was paused.
-// For simplification purposes, the test requires that TEST_DATA_SHORT and
-// TEST_DATA_TAINTED have the same length.
-const TEST_DATA_REPLACEMENT = "-changed- ";
-const TEST_DATA_TAINTED = TEST_DATA_REPLACEMENT +
- TEST_DATA_SHORT.substr(TEST_DATA_REPLACEMENT.length);
-const TEST_DATA_LENGTH = TEST_DATA_SHORT.length;
-
-// The length of the partial file that we'll write to disk as an existing
-// ongoing download.
-const TEST_DATA_PARTIAL_LENGTH = TEST_DATA_REPLACEMENT.length;
-
-// The value of the "maxBytes" column stored in the DB about the downloads.
-// It's intentionally different than TEST_DATA_LENGTH to test that each value
-// is seen when expected.
-const MAXBYTES_IN_DB = TEST_DATA_LENGTH - 10;
-
-var gDownloadsRowToImport;
-var gDownloadsRowNonImportable;
-
-/**
- * Creates a database with an empty moz_downloads table and leaves an
- * open connection to it.
- *
- * @param aPath
- * String containing the path of the database file to be created.
- * @param aSchemaVersion
- * Number with the version of the database schema to set.
- *
- * @return {Promise}
- * @resolves The open connection to the database.
- * @rejects If an error occurred during the database creation.
- */
-function promiseEmptyDatabaseConnection({aPath, aSchemaVersion}) {
- return Task.spawn(function* () {
- let connection = yield Sqlite.openConnection({ path: aPath });
-
- yield connection.execute("CREATE TABLE moz_downloads ("
- + "id INTEGER PRIMARY KEY,"
- + "name TEXT,"
- + "source TEXT,"
- + "target TEXT,"
- + "tempPath TEXT,"
- + "startTime INTEGER,"
- + "endTime INTEGER,"
- + "state INTEGER,"
- + "referrer TEXT,"
- + "entityID TEXT,"
- + "currBytes INTEGER NOT NULL DEFAULT 0,"
- + "maxBytes INTEGER NOT NULL DEFAULT -1,"
- + "mimeType TEXT,"
- + "preferredApplication TEXT,"
- + "preferredAction INTEGER NOT NULL DEFAULT 0,"
- + "autoResume INTEGER NOT NULL DEFAULT 0,"
- + "guid TEXT)");
-
- yield connection.setSchemaVersion(aSchemaVersion);
-
- return connection;
- });
-}
-
-/**
- * Inserts a new entry in the database with the given columns' values.
- *
- * @param aConnection
- * The database connection.
- * @param aDownloadRow
- * An object representing the values for each column of the row
- * being inserted.
- *
- * @return {Promise}
- * @resolves When the operation completes.
- * @rejects If there's an error inserting the row.
- */
-function promiseInsertRow(aConnection, aDownloadRow) {
- // We can't use the aDownloadRow obj directly in the execute statement
- // because the obj bind code in Sqlite.jsm doesn't allow objects
- // with extra properties beyond those being binded. So we might as well
- // use an array as it is simpler.
- let values = [
- aDownloadRow.source, aDownloadRow.target, aDownloadRow.tempPath,
- aDownloadRow.startTime.getTime() * 1000, aDownloadRow.state,
- aDownloadRow.referrer, aDownloadRow.entityID, aDownloadRow.maxBytes,
- aDownloadRow.mimeType, aDownloadRow.preferredApplication,
- aDownloadRow.preferredAction, aDownloadRow.autoResume
- ];
-
- return aConnection.execute("INSERT INTO moz_downloads ("
- + "name, source, target, tempPath, startTime,"
- + "endTime, state, referrer, entityID, currBytes,"
- + "maxBytes, mimeType, preferredApplication,"
- + "preferredAction, autoResume, guid)"
- + "VALUES ("
- + "'', ?, ?, ?, ?, " // name,
- + "0, ?, ?, ?, 0, " // endTime, currBytes
- + " ?, ?, ?, " //
- + " ?, ?, '')", // and guid are not imported
- values);
-}
-
-/**
- * Retrieves the number of rows in the moz_downloads table of the
- * database.
- *
- * @param aConnection
- * The database connection.
- *
- * @return {Promise}
- * @resolves With the number of rows.
- * @rejects Never.
- */
-function promiseTableCount(aConnection) {
- return aConnection.execute("SELECT COUNT(*) FROM moz_downloads")
- .then(res => res[0].getResultByName("COUNT(*)"))
- .then(null, Cu.reportError);
-}
-
-/**
- * Briefly opens a network channel to a given URL to retrieve
- * the entityID of this url, as generated by the network code.
- *
- * @param aUrl
- * The URL to retrieve the entityID.
- *
- * @return {Promise}
- * @resolves The EntityID of the given URL.
- * @rejects When there's a problem accessing the URL.
- */
-function promiseEntityID(aUrl) {
- let deferred = Promise.defer();
- let entityID = "";
- let channel = NetUtil.newChannel({
- uri: NetUtil.newURI(aUrl),
- loadUsingSystemPrincipal: true
- });
-
- channel.asyncOpen2({
- onStartRequest: function (aRequest) {
- if (aRequest instanceof Ci.nsIResumableChannel) {
- entityID = aRequest.entityID;
- }
- aRequest.cancel(Cr.NS_BINDING_ABORTED);
- },
-
- onStopRequest: function (aRequest, aContext, aStatusCode) {
- if (aStatusCode == Cr.NS_BINDING_ABORTED) {
- deferred.resolve(entityID);
- } else {
- deferred.reject("Unexpected status code received");
- }
- },
-
- onDataAvailable: function () {}
- });
-
- return deferred.promise;
-}
-
-/**
- * Gets a file path to a temporary writeable download target, in the
- * correct format as expected to be stored in the downloads database,
- * which is file:///absolute/path/to/file
- *
- * @param aLeafName
- * A hint leaf name for the file.
- *
- * @return String The path to the download target.
- */
-function getDownloadTarget(aLeafName) {
- return NetUtil.newURI(getTempFile(aLeafName)).spec;
-}
-
-/**
- * Generates a temporary partial file to use as an in-progress
- * download. The file is written to disk with a part of the total expected
- * download content pre-written.
- *
- * @param aLeafName
- * A hint leaf name for the file.
- * @param aTainted
- * A boolean value. When true, the partial content of the file
- * will be different from the expected content of the original source
- * file. See the declaration of TEST_DATA_TAINTED for more information.
- *
- * @return {Promise}
- * @resolves When the operation completes, and returns a string with the path
- * to the generated file.
- * @rejects If there's an error writing the file.
- */
-function getPartialFile(aLeafName, aTainted = false) {
- let tempDownload = getTempFile(aLeafName);
- let partialContent = aTainted
- ? TEST_DATA_TAINTED.substr(0, TEST_DATA_PARTIAL_LENGTH)
- : TEST_DATA_SHORT.substr(0, TEST_DATA_PARTIAL_LENGTH);
-
- return OS.File.writeAtomic(tempDownload.path, partialContent,
- { tmpPath: tempDownload.path + ".tmp",
- flush: true })
- .then(() => tempDownload.path);
-}
-
-/**
- * Generates a Date object to be used as the startTime for the download rows
- * in the DB. A date that is obviously different from the current time is
- * generated to make sure this stored data and a `new Date()` can't collide.
- *
- * @param aOffset
- * A offset from the base generated date is used to differentiate each
- * row in the database.
- *
- * @return A Date object.
- */
-function getStartTime(aOffset) {
- return new Date(1000000 + (aOffset * 10000));
-}
-
-/**
- * Performs various checks on an imported Download object to make sure
- * all properties are properly set as expected from the import procedure.
- *
- * @param aDownload
- * The Download object to be checked.
- * @param aDownloadRow
- * An object that represents a row from the original database table,
- * with extra properties describing expected values that are not
- * explictly part of the database.
- *
- * @return {Promise}
- * @resolves When the operation completes
- * @rejects Never
- */
-function checkDownload(aDownload, aDownloadRow) {
- return Task.spawn(function*() {
- do_check_eq(aDownload.source.url, aDownloadRow.source);
- do_check_eq(aDownload.source.referrer, aDownloadRow.referrer);
-
- do_check_eq(aDownload.target.path,
- NetUtil.newURI(aDownloadRow.target)
- .QueryInterface(Ci.nsIFileURL).file.path);
-
- do_check_eq(aDownload.target.partFilePath, aDownloadRow.tempPath);
-
- if (aDownloadRow.expectedResume) {
- do_check_true(!aDownload.stopped || aDownload.succeeded);
- yield promiseDownloadStopped(aDownload);
-
- do_check_true(aDownload.succeeded);
- do_check_eq(aDownload.progress, 100);
- // If the download has resumed, a new startTime will be set.
- // By calling toJSON we're also testing that startTime is a Date object.
- do_check_neq(aDownload.startTime.toJSON(),
- aDownloadRow.startTime.toJSON());
- } else {
- do_check_false(aDownload.succeeded);
- do_check_eq(aDownload.startTime.toJSON(),
- aDownloadRow.startTime.toJSON());
- }
-
- do_check_eq(aDownload.stopped, true);
-
- let serializedSaver = aDownload.saver.toSerializable();
- if (typeof(serializedSaver) == "object") {
- do_check_eq(serializedSaver.type, "copy");
- } else {
- do_check_eq(serializedSaver, "copy");
- }
-
- if (aDownloadRow.entityID) {
- do_check_eq(aDownload.saver.entityID, aDownloadRow.entityID);
- }
-
- do_check_eq(aDownload.currentBytes, aDownloadRow.expectedCurrentBytes);
- do_check_eq(aDownload.totalBytes, aDownloadRow.expectedTotalBytes);
-
- if (aDownloadRow.expectedContent) {
- let fileToCheck = aDownloadRow.expectedResume
- ? aDownload.target.path
- : aDownload.target.partFilePath;
- yield promiseVerifyContents(fileToCheck, aDownloadRow.expectedContent);
- }
-
- do_check_eq(aDownload.contentType, aDownloadRow.expectedContentType);
- do_check_eq(aDownload.launcherPath, aDownloadRow.preferredApplication);
-
- do_check_eq(aDownload.launchWhenSucceeded,
- aDownloadRow.preferredAction != Ci.nsIMIMEInfo.saveToDisk);
- });
-}
-
-// Preparation tasks
-
-/**
- * Prepares the list of downloads to be added to the database that should
- * be imported by the import procedure.
- */
-add_task(function* prepareDownloadsToImport() {
-
- let sourceUrl = httpUrl("source.txt");
- let sourceEntityId = yield promiseEntityID(sourceUrl);
-
- gDownloadsRowToImport = [
- // Paused download with autoResume and a partial file. By
- // setting the correct entityID the download can resume from
- // where it stopped, and to test that this works properly we
- // intentionally set different data in the beginning of the
- // partial file to make sure it was not replaced.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress1.txt"),
- tempPath: yield getPartialFile("inprogress1.txt.part", true),
- startTime: getStartTime(1),
- state: DOWNLOAD_PAUSED,
- referrer: httpUrl("referrer1"),
- entityID: sourceEntityId,
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType1",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication1",
- autoResume: 1,
-
- // Even though the information stored in the DB said
- // maxBytes was MAXBYTES_IN_DB, the download turned out to be
- // a different length. Here we make sure the totalBytes property
- // was correctly set with the actual value. The same consideration
- // applies to the contentType.
- expectedCurrentBytes: TEST_DATA_LENGTH,
- expectedTotalBytes: TEST_DATA_LENGTH,
- expectedResume: true,
- expectedContentType: "text/plain",
- expectedContent: TEST_DATA_TAINTED,
- },
-
- // Paused download with autoResume and a partial file,
- // but missing entityID. This means that the download will
- // start from beginning, and the entire original content of the
- // source file should replace the different data that was stored
- // in the partial file.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress2.txt"),
- tempPath: yield getPartialFile("inprogress2.txt.part", true),
- startTime: getStartTime(2),
- state: DOWNLOAD_PAUSED,
- referrer: httpUrl("referrer2"),
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType2",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication2",
- autoResume: 1,
-
- expectedCurrentBytes: TEST_DATA_LENGTH,
- expectedTotalBytes: TEST_DATA_LENGTH,
- expectedResume: true,
- expectedContentType: "text/plain",
- expectedContent: TEST_DATA_SHORT
- },
-
- // Paused download with no autoResume and a partial file.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress3.txt"),
- tempPath: yield getPartialFile("inprogress3.txt.part"),
- startTime: getStartTime(3),
- state: DOWNLOAD_PAUSED,
- referrer: httpUrl("referrer3"),
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType3",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication3",
- autoResume: 0,
-
- // Since this download has not been resumed, the actual data
- // about its total size and content type is not known.
- // Therefore, we're going by the information imported from the DB.
- expectedCurrentBytes: TEST_DATA_PARTIAL_LENGTH,
- expectedTotalBytes: MAXBYTES_IN_DB,
- expectedResume: false,
- expectedContentType: "mimeType3",
- expectedContent: TEST_DATA_SHORT.substr(0, TEST_DATA_PARTIAL_LENGTH),
- },
-
- // Paused download with autoResume and no partial file.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress4.txt"),
- tempPath: "",
- startTime: getStartTime(4),
- state: DOWNLOAD_PAUSED,
- referrer: httpUrl("referrer4"),
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "text/plain",
- preferredAction: Ci.nsIMIMEInfo.useHelperApp,
- preferredApplication: "prerredApplication4",
- autoResume: 1,
-
- expectedCurrentBytes: TEST_DATA_LENGTH,
- expectedTotalBytes: TEST_DATA_LENGTH,
- expectedResume: true,
- expectedContentType: "text/plain",
- expectedContent: TEST_DATA_SHORT
- },
-
- // Paused download with no autoResume and no partial file.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress5.txt"),
- tempPath: "",
- startTime: getStartTime(5),
- state: DOWNLOAD_PAUSED,
- referrer: httpUrl("referrer4"),
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "text/plain",
- preferredAction: Ci.nsIMIMEInfo.useSystemDefault,
- preferredApplication: "prerredApplication5",
- autoResume: 0,
-
- expectedCurrentBytes: 0,
- expectedTotalBytes: MAXBYTES_IN_DB,
- expectedResume: false,
- expectedContentType: "text/plain",
- },
-
- // Queued download with no autoResume and no partial file.
- // Even though autoResume=0, queued downloads always autoResume.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress6.txt"),
- tempPath: "",
- startTime: getStartTime(6),
- state: DOWNLOAD_QUEUED,
- referrer: httpUrl("referrer6"),
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "text/plain",
- preferredAction: Ci.nsIMIMEInfo.useHelperApp,
- preferredApplication: "prerredApplication6",
- autoResume: 0,
-
- expectedCurrentBytes: TEST_DATA_LENGTH,
- expectedTotalBytes: TEST_DATA_LENGTH,
- expectedResume: true,
- expectedContentType: "text/plain",
- expectedContent: TEST_DATA_SHORT
- },
-
- // Notstarted download with no autoResume and no partial file.
- // Even though autoResume=0, notstarted downloads always autoResume.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress7.txt"),
- tempPath: "",
- startTime: getStartTime(7),
- state: DOWNLOAD_NOTSTARTED,
- referrer: httpUrl("referrer7"),
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "text/plain",
- preferredAction: Ci.nsIMIMEInfo.useHelperApp,
- preferredApplication: "prerredApplication7",
- autoResume: 0,
-
- expectedCurrentBytes: TEST_DATA_LENGTH,
- expectedTotalBytes: TEST_DATA_LENGTH,
- expectedResume: true,
- expectedContentType: "text/plain",
- expectedContent: TEST_DATA_SHORT
- },
-
- // Downloading download with no autoResume and a partial file.
- // Even though autoResume=0, downloading downloads always autoResume.
- {
- source: sourceUrl,
- target: getDownloadTarget("inprogress8.txt"),
- tempPath: yield getPartialFile("inprogress8.txt.part", true),
- startTime: getStartTime(8),
- state: DOWNLOAD_DOWNLOADING,
- referrer: httpUrl("referrer8"),
- entityID: sourceEntityId,
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "text/plain",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication8",
- autoResume: 0,
-
- expectedCurrentBytes: TEST_DATA_LENGTH,
- expectedTotalBytes: TEST_DATA_LENGTH,
- expectedResume: true,
- expectedContentType: "text/plain",
- expectedContent: TEST_DATA_TAINTED
- },
- ];
-});
-
-/**
- * Prepares the list of downloads to be added to the database that should
- * *not* be imported by the import procedure.
- */
-add_task(function* prepareNonImportableDownloads()
-{
- gDownloadsRowNonImportable = [
- // Download with no source (should never happen in normal circumstances).
- {
- source: "",
- target: "nonimportable1.txt",
- tempPath: "",
- startTime: getStartTime(1),
- state: DOWNLOAD_PAUSED,
- referrer: "",
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType1",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication1",
- autoResume: 1
- },
-
- // state = DOWNLOAD_FAILED
- {
- source: httpUrl("source.txt"),
- target: "nonimportable2.txt",
- tempPath: "",
- startTime: getStartTime(2),
- state: DOWNLOAD_FAILED,
- referrer: "",
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType2",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication2",
- autoResume: 1
- },
-
- // state = DOWNLOAD_CANCELED
- {
- source: httpUrl("source.txt"),
- target: "nonimportable3.txt",
- tempPath: "",
- startTime: getStartTime(3),
- state: DOWNLOAD_CANCELED,
- referrer: "",
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType3",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication3",
- autoResume: 1
- },
-
- // state = DOWNLOAD_BLOCKED_PARENTAL
- {
- source: httpUrl("source.txt"),
- target: "nonimportable4.txt",
- tempPath: "",
- startTime: getStartTime(4),
- state: DOWNLOAD_BLOCKED_PARENTAL,
- referrer: "",
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType4",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication4",
- autoResume: 1
- },
-
- // state = DOWNLOAD_SCANNING
- {
- source: httpUrl("source.txt"),
- target: "nonimportable5.txt",
- tempPath: "",
- startTime: getStartTime(5),
- state: DOWNLOAD_SCANNING,
- referrer: "",
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType5",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication5",
- autoResume: 1
- },
-
- // state = DOWNLOAD_DIRTY
- {
- source: httpUrl("source.txt"),
- target: "nonimportable6.txt",
- tempPath: "",
- startTime: getStartTime(6),
- state: DOWNLOAD_DIRTY,
- referrer: "",
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType6",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication6",
- autoResume: 1
- },
-
- // state = DOWNLOAD_BLOCKED_POLICY
- {
- source: httpUrl("source.txt"),
- target: "nonimportable7.txt",
- tempPath: "",
- startTime: getStartTime(7),
- state: DOWNLOAD_BLOCKED_POLICY,
- referrer: "",
- entityID: "",
- maxBytes: MAXBYTES_IN_DB,
- mimeType: "mimeType7",
- preferredAction: Ci.nsIMIMEInfo.saveToDisk,
- preferredApplication: "prerredApplication7",
- autoResume: 1
- },
- ];
-});
-
-// Test
-
-/**
- * Creates a temporary Sqlite database with download data and perform an
- * import of that data to the new Downloads API to verify that the import
- * worked correctly.
- */
-add_task(function* test_downloadImport()
-{
- let connection = null;
- let downloadsSqlite = getTempFile("downloads.sqlite").path;
-
- try {
- // Set up the database.
- connection = yield promiseEmptyDatabaseConnection({
- aPath: downloadsSqlite,
- aSchemaVersion: 9
- });
-
- // Insert both the importable and non-importable
- // downloads together.
- for (let downloadRow of gDownloadsRowToImport) {
- yield promiseInsertRow(connection, downloadRow);
- }
-
- for (let downloadRow of gDownloadsRowNonImportable) {
- yield promiseInsertRow(connection, downloadRow);
- }
-
- // Check that every item was inserted.
- do_check_eq((yield promiseTableCount(connection)),
- gDownloadsRowToImport.length +
- gDownloadsRowNonImportable.length);
- } finally {
- // Close the connection so that DownloadImport can open it.
- yield connection.close();
- }
-
- // Import items.
- let list = yield promiseNewList(false);
- yield new DownloadImport(list, downloadsSqlite).import();
- let items = yield list.getAll();
-
- do_check_eq(items.length, gDownloadsRowToImport.length);
-
- for (let i = 0; i < gDownloadsRowToImport.length; i++) {
- yield checkDownload(items[i], gDownloadsRowToImport[i]);
- }
-})
diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadIntegration.js b/toolkit/components/jsdownloads/test/unit/test_DownloadIntegration.js
deleted file mode 100644
index 31dd7c7a4..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadIntegration.js
+++ /dev/null
@@ -1,432 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the DownloadIntegration object.
- */
-
-"use strict";
-
-// Globals
-
-/**
- * Notifies the prompt observers and verify the expected downloads count.
- *
- * @param aIsPrivate
- * Flag to know is test private observers.
- * @param aExpectedCount
- * the expected downloads count for quit and offline observers.
- * @param aExpectedPBCount
- * the expected downloads count for private browsing observer.
- */
-function notifyPromptObservers(aIsPrivate, aExpectedCount, aExpectedPBCount) {
- let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].
- createInstance(Ci.nsISupportsPRBool);
-
- // Notify quit application requested observer.
- DownloadIntegration._testPromptDownloads = -1;
- Services.obs.notifyObservers(cancelQuit, "quit-application-requested", null);
- do_check_eq(DownloadIntegration._testPromptDownloads, aExpectedCount);
-
- // Notify offline requested observer.
- DownloadIntegration._testPromptDownloads = -1;
- Services.obs.notifyObservers(cancelQuit, "offline-requested", null);
- do_check_eq(DownloadIntegration._testPromptDownloads, aExpectedCount);
-
- if (aIsPrivate) {
- // Notify last private browsing requested observer.
- DownloadIntegration._testPromptDownloads = -1;
- Services.obs.notifyObservers(cancelQuit, "last-pb-context-exiting", null);
- do_check_eq(DownloadIntegration._testPromptDownloads, aExpectedPBCount);
- }
-
- delete DownloadIntegration._testPromptDownloads;
-}
-
-// Tests
-
-/**
- * Allows re-enabling the real download directory logic during one test.
- */
-function allowDirectoriesInTest() {
- DownloadIntegration.allowDirectories = true;
- function cleanup() {
- DownloadIntegration.allowDirectories = false;
- }
- do_register_cleanup(cleanup);
- return cleanup;
-}
-
-XPCOMUtils.defineLazyGetter(this, "gStringBundle", function() {
- return Services.strings.
- createBundle("chrome://mozapps/locale/downloads/downloads.properties");
-});
-
-/**
- * Tests that getSystemDownloadsDirectory returns an existing directory or
- * creates a new directory depending on the platform. Instead of the real
- * directory, this test is executed in the temporary directory so we can safely
- * delete the created folder to check whether it is created again.
- */
-add_task(function* test_getSystemDownloadsDirectory_exists_or_creates()
-{
- let tempDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
- let downloadDir;
-
- // OSX / Linux / Windows but not XP/2k
- if (Services.appinfo.OS == "Darwin" ||
- Services.appinfo.OS == "Linux" ||
- (Services.appinfo.OS == "WINNT" &&
- parseFloat(Services.sysinfo.getProperty("version")) >= 6)) {
- downloadDir = yield DownloadIntegration.getSystemDownloadsDirectory();
- do_check_eq(downloadDir, tempDir.path);
- do_check_true(yield OS.File.exists(downloadDir));
-
- let info = yield OS.File.stat(downloadDir);
- do_check_true(info.isDir);
- } else {
- let targetPath = OS.Path.join(tempDir.path,
- gStringBundle.GetStringFromName("downloadsFolder"));
- try {
- yield OS.File.removeEmptyDir(targetPath);
- } catch (e) {}
- downloadDir = yield DownloadIntegration.getSystemDownloadsDirectory();
- do_check_eq(downloadDir, targetPath);
- do_check_true(yield OS.File.exists(downloadDir));
-
- let info = yield OS.File.stat(downloadDir);
- do_check_true(info.isDir);
- yield OS.File.removeEmptyDir(targetPath);
- }
-});
-
-/**
- * Tests that the real directory returned by getSystemDownloadsDirectory is not
- * the one that is used during unit tests. Since this is the actual downloads
- * directory of the operating system, we don't try to delete it afterwards.
- */
-add_task(function* test_getSystemDownloadsDirectory_real()
-{
- let fakeDownloadDir = yield DownloadIntegration.getSystemDownloadsDirectory();
-
- let cleanup = allowDirectoriesInTest();
- let realDownloadDir = yield DownloadIntegration.getSystemDownloadsDirectory();
- cleanup();
-
- do_check_neq(fakeDownloadDir, realDownloadDir);
-});
-
-/**
- * Tests that the getPreferredDownloadsDirectory returns a valid download
- * directory string path.
- */
-add_task(function* test_getPreferredDownloadsDirectory()
-{
- let cleanupDirectories = allowDirectoriesInTest();
-
- let folderListPrefName = "browser.download.folderList";
- let dirPrefName = "browser.download.dir";
- function cleanupPrefs() {
- Services.prefs.clearUserPref(folderListPrefName);
- Services.prefs.clearUserPref(dirPrefName);
- }
- do_register_cleanup(cleanupPrefs);
-
- // Should return the system downloads directory.
- Services.prefs.setIntPref(folderListPrefName, 1);
- let systemDir = yield DownloadIntegration.getSystemDownloadsDirectory();
- let downloadDir = yield DownloadIntegration.getPreferredDownloadsDirectory();
- do_check_neq(downloadDir, "");
- do_check_eq(downloadDir, systemDir);
-
- // Should return the desktop directory.
- Services.prefs.setIntPref(folderListPrefName, 0);
- downloadDir = yield DownloadIntegration.getPreferredDownloadsDirectory();
- do_check_neq(downloadDir, "");
- do_check_eq(downloadDir, Services.dirsvc.get("Desk", Ci.nsIFile).path);
-
- // Should return the system downloads directory because the dir preference
- // is not set.
- Services.prefs.setIntPref(folderListPrefName, 2);
- downloadDir = yield DownloadIntegration.getPreferredDownloadsDirectory();
- do_check_neq(downloadDir, "");
- do_check_eq(downloadDir, systemDir);
-
- // Should return the directory which is listed in the dir preference.
- let time = (new Date()).getTime();
- let tempDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
- tempDir.append(time);
- Services.prefs.setComplexValue("browser.download.dir", Ci.nsIFile, tempDir);
- downloadDir = yield DownloadIntegration.getPreferredDownloadsDirectory();
- do_check_neq(downloadDir, "");
- do_check_eq(downloadDir, tempDir.path);
- do_check_true(yield OS.File.exists(downloadDir));
- yield OS.File.removeEmptyDir(tempDir.path);
-
- // Should return the system downloads directory beacause the path is invalid
- // in the dir preference.
- tempDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
- tempDir.append("dir_not_exist");
- tempDir.append(time);
- Services.prefs.setComplexValue("browser.download.dir", Ci.nsIFile, tempDir);
- downloadDir = yield DownloadIntegration.getPreferredDownloadsDirectory();
- do_check_eq(downloadDir, systemDir);
-
- // Should return the system downloads directory because the folderList
- // preference is invalid
- Services.prefs.setIntPref(folderListPrefName, 999);
- downloadDir = yield DownloadIntegration.getPreferredDownloadsDirectory();
- do_check_eq(downloadDir, systemDir);
-
- cleanupPrefs();
- cleanupDirectories();
-});
-
-/**
- * Tests that the getTemporaryDownloadsDirectory returns a valid download
- * directory string path.
- */
-add_task(function* test_getTemporaryDownloadsDirectory()
-{
- let cleanup = allowDirectoriesInTest();
-
- let downloadDir = yield DownloadIntegration.getTemporaryDownloadsDirectory();
- do_check_neq(downloadDir, "");
-
- if ("nsILocalFileMac" in Ci) {
- let preferredDownloadDir = yield DownloadIntegration.getPreferredDownloadsDirectory();
- do_check_eq(downloadDir, preferredDownloadDir);
- } else {
- let tempDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
- do_check_eq(downloadDir, tempDir.path);
- }
-
- cleanup();
-});
-
-// Tests DownloadObserver
-
-/**
- * Re-enables the default observers for the following tests.
- *
- * This takes effect the first time a DownloadList object is created, and lasts
- * until this test file has completed.
- */
-add_task(function* test_observers_setup()
-{
- DownloadIntegration.allowObservers = true;
- do_register_cleanup(function () {
- DownloadIntegration.allowObservers = false;
- });
-});
-
-/**
- * Tests notifications prompts when observers are notified if there are public
- * and private active downloads.
- */
-add_task(function* test_notifications()
-{
- for (let isPrivate of [false, true]) {
- mustInterruptResponses();
-
- let list = yield promiseNewList(isPrivate);
- let download1 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- let download2 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- let download3 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- let promiseAttempt1 = download1.start();
- let promiseAttempt2 = download2.start();
- download3.start().catch(() => {});
-
- // Add downloads to list.
- yield list.add(download1);
- yield list.add(download2);
- yield list.add(download3);
- // Cancel third download
- yield download3.cancel();
-
- notifyPromptObservers(isPrivate, 2, 2);
-
- // Allow the downloads to complete.
- continueResponses();
- yield promiseAttempt1;
- yield promiseAttempt2;
-
- // Clean up.
- yield list.remove(download1);
- yield list.remove(download2);
- yield list.remove(download3);
- }
-});
-
-/**
- * Tests that notifications prompts observers are not notified if there are no
- * public or private active downloads.
- */
-add_task(function* test_no_notifications()
-{
- for (let isPrivate of [false, true]) {
- let list = yield promiseNewList(isPrivate);
- let download1 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- let download2 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- download1.start().catch(() => {});
- download2.start().catch(() => {});
-
- // Add downloads to list.
- yield list.add(download1);
- yield list.add(download2);
-
- yield download1.cancel();
- yield download2.cancel();
-
- notifyPromptObservers(isPrivate, 0, 0);
-
- // Clean up.
- yield list.remove(download1);
- yield list.remove(download2);
- }
-});
-
-/**
- * Tests notifications prompts when observers are notified if there are public
- * and private active downloads at the same time.
- */
-add_task(function* test_mix_notifications()
-{
- mustInterruptResponses();
-
- let publicList = yield promiseNewList();
- let privateList = yield Downloads.getList(Downloads.PRIVATE);
- let download1 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- let download2 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- let promiseAttempt1 = download1.start();
- let promiseAttempt2 = download2.start();
-
- // Add downloads to lists.
- yield publicList.add(download1);
- yield privateList.add(download2);
-
- notifyPromptObservers(true, 2, 1);
-
- // Allow the downloads to complete.
- continueResponses();
- yield promiseAttempt1;
- yield promiseAttempt2;
-
- // Clean up.
- yield publicList.remove(download1);
- yield privateList.remove(download2);
-});
-
-/**
- * Tests suspending and resuming as well as going offline and then online again.
- * The downloads should stop when suspending and start again when resuming.
- */
-add_task(function* test_suspend_resume()
-{
- // The default wake delay is 10 seconds, so set the wake delay to be much
- // faster for these tests.
- Services.prefs.setIntPref("browser.download.manager.resumeOnWakeDelay", 5);
-
- let addDownload = function(list)
- {
- return Task.spawn(function* () {
- let download = yield promiseNewDownload(httpUrl("interruptible.txt"));
- download.start().catch(() => {});
- list.add(download);
- return download;
- });
- }
-
- let publicList = yield promiseNewList();
- let privateList = yield promiseNewList(true);
-
- let download1 = yield addDownload(publicList);
- let download2 = yield addDownload(publicList);
- let download3 = yield addDownload(privateList);
- let download4 = yield addDownload(privateList);
- let download5 = yield addDownload(publicList);
-
- // First, check that the downloads are all canceled when going to sleep.
- Services.obs.notifyObservers(null, "sleep_notification", null);
- do_check_true(download1.canceled);
- do_check_true(download2.canceled);
- do_check_true(download3.canceled);
- do_check_true(download4.canceled);
- do_check_true(download5.canceled);
-
- // Remove a download. It should not be started again.
- publicList.remove(download5);
- do_check_true(download5.canceled);
-
- // When waking up again, the downloads start again after the wake delay. To be
- // more robust, don't check after a delay but instead just wait for the
- // downloads to finish.
- Services.obs.notifyObservers(null, "wake_notification", null);
- yield download1.whenSucceeded();
- yield download2.whenSucceeded();
- yield download3.whenSucceeded();
- yield download4.whenSucceeded();
-
- // Downloads should no longer be canceled. However, as download5 was removed
- // from the public list, it will not be restarted.
- do_check_false(download1.canceled);
- do_check_true(download5.canceled);
-
- // Create four new downloads and check for going offline and then online again.
-
- download1 = yield addDownload(publicList);
- download2 = yield addDownload(publicList);
- download3 = yield addDownload(privateList);
- download4 = yield addDownload(privateList);
-
- // Going offline should cancel the downloads.
- Services.obs.notifyObservers(null, "network:offline-about-to-go-offline", null);
- do_check_true(download1.canceled);
- do_check_true(download2.canceled);
- do_check_true(download3.canceled);
- do_check_true(download4.canceled);
-
- // Going back online should start the downloads again.
- Services.obs.notifyObservers(null, "network:offline-status-changed", "online");
- yield download1.whenSucceeded();
- yield download2.whenSucceeded();
- yield download3.whenSucceeded();
- yield download4.whenSucceeded();
-
- Services.prefs.clearUserPref("browser.download.manager.resumeOnWakeDelay");
-});
-
-/**
- * Tests both the downloads list and the in-progress downloads are clear when
- * private browsing observer is notified.
- */
-add_task(function* test_exit_private_browsing()
-{
- mustInterruptResponses();
-
- let privateList = yield promiseNewList(true);
- let download1 = yield promiseNewDownload(httpUrl("source.txt"));
- let download2 = yield promiseNewDownload(httpUrl("interruptible.txt"));
- let promiseAttempt1 = download1.start();
- download2.start();
-
- // Add downloads to list.
- yield privateList.add(download1);
- yield privateList.add(download2);
-
- // Complete the download.
- yield promiseAttempt1;
-
- do_check_eq((yield privateList.getAll()).length, 2);
-
- // Simulate exiting the private browsing.
- yield new Promise(resolve => {
- DownloadIntegration._testResolveClearPrivateList = resolve;
- Services.obs.notifyObservers(null, "last-pb-context-exited", null);
- });
- delete DownloadIntegration._testResolveClearPrivateList;
-
- do_check_eq((yield privateList.getAll()).length, 0);
-
- continueResponses();
-});
diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadLegacy.js b/toolkit/components/jsdownloads/test/unit/test_DownloadLegacy.js
deleted file mode 100644
index dc6c18623..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadLegacy.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the integration with legacy interfaces for downloads.
- */
-
-"use strict";
-
-// Execution of common tests
-
-var gUseLegacySaver = true;
-
-var scriptFile = do_get_file("common_test_Download.js");
-Services.scriptloader.loadSubScript(NetUtil.newURI(scriptFile).spec);
diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js b/toolkit/components/jsdownloads/test/unit/test_DownloadList.js
deleted file mode 100644
index 71e880741..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadList.js
+++ /dev/null
@@ -1,564 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the DownloadList object.
- */
-
-"use strict";
-
-// Globals
-
-/**
- * Returns a PRTime in the past usable to add expirable visits.
- *
- * @note Expiration ignores any visit added in the last 7 days, but it's
- * better be safe against DST issues, by going back one day more.
- */
-function getExpirablePRTime()
-{
- let dateObj = new Date();
- // Normalize to midnight
- dateObj.setHours(0);
- dateObj.setMinutes(0);
- dateObj.setSeconds(0);
- dateObj.setMilliseconds(0);
- dateObj = new Date(dateObj.getTime() - 8 * 86400000);
- return dateObj.getTime() * 1000;
-}
-
-/**
- * Adds an expirable history visit for a download.
- *
- * @param aSourceUrl
- * String containing the URI for the download source, or null to use
- * httpUrl("source.txt").
- *
- * @return {Promise}
- * @rejects JavaScript exception.
- */
-function promiseExpirableDownloadVisit(aSourceUrl)
-{
- let deferred = Promise.defer();
- PlacesUtils.asyncHistory.updatePlaces(
- {
- uri: NetUtil.newURI(aSourceUrl || httpUrl("source.txt")),
- visits: [{
- transitionType: Ci.nsINavHistoryService.TRANSITION_DOWNLOAD,
- visitDate: getExpirablePRTime(),
- }]
- },
- {
- handleError: function handleError(aResultCode, aPlaceInfo) {
- let ex = new Components.Exception("Unexpected error in adding visits.",
- aResultCode);
- deferred.reject(ex);
- },
- handleResult: function () {},
- handleCompletion: function handleCompletion() {
- deferred.resolve();
- }
- });
- return deferred.promise;
-}
-
-// Tests
-
-/**
- * Checks the testing mechanism used to build different download lists.
- */
-add_task(function* test_construction()
-{
- let downloadListOne = yield promiseNewList();
- let downloadListTwo = yield promiseNewList();
- let privateDownloadListOne = yield promiseNewList(true);
- let privateDownloadListTwo = yield promiseNewList(true);
-
- do_check_neq(downloadListOne, downloadListTwo);
- do_check_neq(privateDownloadListOne, privateDownloadListTwo);
- do_check_neq(downloadListOne, privateDownloadListOne);
-});
-
-/**
- * Checks the methods to add and retrieve items from the list.
- */
-add_task(function* test_add_getAll()
-{
- let list = yield promiseNewList();
-
- let downloadOne = yield promiseNewDownload();
- yield list.add(downloadOne);
-
- let itemsOne = yield list.getAll();
- do_check_eq(itemsOne.length, 1);
- do_check_eq(itemsOne[0], downloadOne);
-
- let downloadTwo = yield promiseNewDownload();
- yield list.add(downloadTwo);
-
- let itemsTwo = yield list.getAll();
- do_check_eq(itemsTwo.length, 2);
- do_check_eq(itemsTwo[0], downloadOne);
- do_check_eq(itemsTwo[1], downloadTwo);
-
- // The first snapshot should not have been modified.
- do_check_eq(itemsOne.length, 1);
-});
-
-/**
- * Checks the method to remove items from the list.
- */
-add_task(function* test_remove()
-{
- let list = yield promiseNewList();
-
- yield list.add(yield promiseNewDownload());
- yield list.add(yield promiseNewDownload());
-
- let items = yield list.getAll();
- yield list.remove(items[0]);
-
- // Removing an item that was never added should not raise an error.
- yield list.remove(yield promiseNewDownload());
-
- items = yield list.getAll();
- do_check_eq(items.length, 1);
-});
-
-/**
- * Tests that the "add", "remove", and "getAll" methods on the global
- * DownloadCombinedList object combine the contents of the global DownloadList
- * objects for public and private downloads.
- */
-add_task(function* test_DownloadCombinedList_add_remove_getAll()
-{
- let publicList = yield promiseNewList();
- let privateList = yield Downloads.getList(Downloads.PRIVATE);
- let combinedList = yield Downloads.getList(Downloads.ALL);
-
- let publicDownload = yield promiseNewDownload();
- let privateDownload = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt"), isPrivate: true },
- target: getTempFile(TEST_TARGET_FILE_NAME).path,
- });
-
- yield publicList.add(publicDownload);
- yield privateList.add(privateDownload);
-
- do_check_eq((yield combinedList.getAll()).length, 2);
-
- yield combinedList.remove(publicDownload);
- yield combinedList.remove(privateDownload);
-
- do_check_eq((yield combinedList.getAll()).length, 0);
-
- yield combinedList.add(publicDownload);
- yield combinedList.add(privateDownload);
-
- do_check_eq((yield publicList.getAll()).length, 1);
- do_check_eq((yield privateList.getAll()).length, 1);
- do_check_eq((yield combinedList.getAll()).length, 2);
-
- yield publicList.remove(publicDownload);
- yield privateList.remove(privateDownload);
-
- do_check_eq((yield combinedList.getAll()).length, 0);
-});
-
-/**
- * Checks that views receive the download add and remove notifications, and that
- * adding and removing views works as expected, both for a normal and a combined
- * list.
- */
-add_task(function* test_notifications_add_remove()
-{
- for (let isCombined of [false, true]) {
- // Force creating a new list for both the public and combined cases.
- let list = yield promiseNewList();
- if (isCombined) {
- list = yield Downloads.getList(Downloads.ALL);
- }
-
- let downloadOne = yield promiseNewDownload();
- let downloadTwo = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt"), isPrivate: true },
- target: getTempFile(TEST_TARGET_FILE_NAME).path,
- });
- yield list.add(downloadOne);
- yield list.add(downloadTwo);
-
- // Check that we receive add notifications for existing elements.
- let addNotifications = 0;
- let viewOne = {
- onDownloadAdded: function (aDownload) {
- // The first download to be notified should be the first that was added.
- if (addNotifications == 0) {
- do_check_eq(aDownload, downloadOne);
- } else if (addNotifications == 1) {
- do_check_eq(aDownload, downloadTwo);
- }
- addNotifications++;
- },
- };
- yield list.addView(viewOne);
- do_check_eq(addNotifications, 2);
-
- // Check that we receive add notifications for new elements.
- yield list.add(yield promiseNewDownload());
- do_check_eq(addNotifications, 3);
-
- // Check that we receive remove notifications.
- let removeNotifications = 0;
- let viewTwo = {
- onDownloadRemoved: function (aDownload) {
- do_check_eq(aDownload, downloadOne);
- removeNotifications++;
- },
- };
- yield list.addView(viewTwo);
- yield list.remove(downloadOne);
- do_check_eq(removeNotifications, 1);
-
- // We should not receive remove notifications after the view is removed.
- yield list.removeView(viewTwo);
- yield list.remove(downloadTwo);
- do_check_eq(removeNotifications, 1);
-
- // We should not receive add notifications after the view is removed.
- yield list.removeView(viewOne);
- yield list.add(yield promiseNewDownload());
- do_check_eq(addNotifications, 3);
- }
-});
-
-/**
- * Checks that views receive the download change notifications, both for a
- * normal and a combined list.
- */
-add_task(function* test_notifications_change()
-{
- for (let isCombined of [false, true]) {
- // Force creating a new list for both the public and combined cases.
- let list = yield promiseNewList();
- if (isCombined) {
- list = yield Downloads.getList(Downloads.ALL);
- }
-
- let downloadOne = yield promiseNewDownload();
- let downloadTwo = yield Downloads.createDownload({
- source: { url: httpUrl("source.txt"), isPrivate: true },
- target: getTempFile(TEST_TARGET_FILE_NAME).path,
- });
- yield list.add(downloadOne);
- yield list.add(downloadTwo);
-
- // Check that we receive change notifications.
- let receivedOnDownloadChanged = false;
- yield list.addView({
- onDownloadChanged: function (aDownload) {
- do_check_eq(aDownload, downloadOne);
- receivedOnDownloadChanged = true;
- },
- });
- yield downloadOne.start();
- do_check_true(receivedOnDownloadChanged);
-
- // We should not receive change notifications after a download is removed.
- receivedOnDownloadChanged = false;
- yield list.remove(downloadTwo);
- yield downloadTwo.start();
- do_check_false(receivedOnDownloadChanged);
- }
-});
-
-/**
- * Checks that the reference to "this" is correct in the view callbacks.
- */
-add_task(function* test_notifications_this()
-{
- let list = yield promiseNewList();
-
- // Check that we receive change notifications.
- let receivedOnDownloadAdded = false;
- let receivedOnDownloadChanged = false;
- let receivedOnDownloadRemoved = false;
- let view = {
- onDownloadAdded: function () {
- do_check_eq(this, view);
- receivedOnDownloadAdded = true;
- },
- onDownloadChanged: function () {
- // Only do this check once.
- if (!receivedOnDownloadChanged) {
- do_check_eq(this, view);
- receivedOnDownloadChanged = true;
- }
- },
- onDownloadRemoved: function () {
- do_check_eq(this, view);
- receivedOnDownloadRemoved = true;
- },
- };
- yield list.addView(view);
-
- let download = yield promiseNewDownload();
- yield list.add(download);
- yield download.start();
- yield list.remove(download);
-
- // Verify that we executed the checks.
- do_check_true(receivedOnDownloadAdded);
- do_check_true(receivedOnDownloadChanged);
- do_check_true(receivedOnDownloadRemoved);
-});
-
-/**
- * Checks that download is removed on history expiration.
- */
-add_task(function* test_history_expiration()
-{
- mustInterruptResponses();
-
- function cleanup() {
- Services.prefs.clearUserPref("places.history.expiration.max_pages");
- }
- do_register_cleanup(cleanup);
-
- // Set max pages to 0 to make the download expire.
- Services.prefs.setIntPref("places.history.expiration.max_pages", 0);
-
- let list = yield promiseNewList();
- let downloadOne = yield promiseNewDownload();
- let downloadTwo = yield promiseNewDownload(httpUrl("interruptible.txt"));
-
- let deferred = Promise.defer();
- let removeNotifications = 0;
- let downloadView = {
- onDownloadRemoved: function (aDownload) {
- if (++removeNotifications == 2) {
- deferred.resolve();
- }
- },
- };
- yield list.addView(downloadView);
-
- // Work with one finished download and one canceled download.
- yield downloadOne.start();
- downloadTwo.start().catch(() => {});
- yield downloadTwo.cancel();
-
- // We must replace the visits added while executing the downloads with visits
- // that are older than 7 days, otherwise they will not be expired.
- yield PlacesTestUtils.clearHistory();
- yield promiseExpirableDownloadVisit();
- yield promiseExpirableDownloadVisit(httpUrl("interruptible.txt"));
-
- // After clearing history, we can add the downloads to be removed to the list.
- yield list.add(downloadOne);
- yield list.add(downloadTwo);
-
- // Force a history expiration.
- Cc["@mozilla.org/places/expiration;1"]
- .getService(Ci.nsIObserver).observe(null, "places-debug-start-expiration", -1);
-
- // Wait for both downloads to be removed.
- yield deferred.promise;
-
- cleanup();
-});
-
-/**
- * Checks all downloads are removed after clearing history.
- */
-add_task(function* test_history_clear()
-{
- let list = yield promiseNewList();
- let downloadOne = yield promiseNewDownload();
- let downloadTwo = yield promiseNewDownload();
- yield list.add(downloadOne);
- yield list.add(downloadTwo);
-
- let deferred = Promise.defer();
- let removeNotifications = 0;
- let downloadView = {
- onDownloadRemoved: function (aDownload) {
- if (++removeNotifications == 2) {
- deferred.resolve();
- }
- },
- };
- yield list.addView(downloadView);
-
- yield downloadOne.start();
- yield downloadTwo.start();
-
- yield PlacesTestUtils.clearHistory();
-
- // Wait for the removal notifications that may still be pending.
- yield deferred.promise;
-});
-
-/**
- * Tests the removeFinished method to ensure that it only removes
- * finished downloads.
- */
-add_task(function* test_removeFinished()
-{
- let list = yield promiseNewList();
- let downloadOne = yield promiseNewDownload();
- let downloadTwo = yield promiseNewDownload();
- let downloadThree = yield promiseNewDownload();
- let downloadFour = yield promiseNewDownload();
- yield list.add(downloadOne);
- yield list.add(downloadTwo);
- yield list.add(downloadThree);
- yield list.add(downloadFour);
-
- let deferred = Promise.defer();
- let removeNotifications = 0;
- let downloadView = {
- onDownloadRemoved: function (aDownload) {
- do_check_true(aDownload == downloadOne ||
- aDownload == downloadTwo ||
- aDownload == downloadThree);
- do_check_true(removeNotifications < 3);
- if (++removeNotifications == 3) {
- deferred.resolve();
- }
- },
- };
- yield list.addView(downloadView);
-
- // Start three of the downloads, but don't start downloadTwo, then set
- // downloadFour to have partial data. All downloads except downloadFour
- // should be removed.
- yield downloadOne.start();
- yield downloadThree.start();
- yield downloadFour.start();
- downloadFour.hasPartialData = true;
-
- list.removeFinished();
- yield deferred.promise;
-
- let downloads = yield list.getAll()
- do_check_eq(downloads.length, 1);
-});
-
-/**
- * Tests the global DownloadSummary objects for the public, private, and
- * combined download lists.
- */
-add_task(function* test_DownloadSummary()
-{
- mustInterruptResponses();
-
- let publicList = yield promiseNewList();
- let privateList = yield Downloads.getList(Downloads.PRIVATE);
-
- let publicSummary = yield Downloads.getSummary(Downloads.PUBLIC);
- let privateSummary = yield Downloads.getSummary(Downloads.PRIVATE);
- let combinedSummary = yield Downloads.getSummary(Downloads.ALL);
-
- // Add a public download that has succeeded.
- let succeededPublicDownload = yield promiseNewDownload();
- yield succeededPublicDownload.start();
- yield publicList.add(succeededPublicDownload);
-
- // Add a public download that has been canceled midway.
- let canceledPublicDownload =
- yield promiseNewDownload(httpUrl("interruptible.txt"));
- canceledPublicDownload.start().catch(() => {});
- yield promiseDownloadMidway(canceledPublicDownload);
- yield canceledPublicDownload.cancel();
- yield publicList.add(canceledPublicDownload);
-
- // Add a public download that is in progress.
- let inProgressPublicDownload =
- yield promiseNewDownload(httpUrl("interruptible.txt"));
- inProgressPublicDownload.start().catch(() => {});
- yield promiseDownloadMidway(inProgressPublicDownload);
- yield publicList.add(inProgressPublicDownload);
-
- // Add a private download that is in progress.
- let inProgressPrivateDownload = yield Downloads.createDownload({
- source: { url: httpUrl("interruptible.txt"), isPrivate: true },
- target: getTempFile(TEST_TARGET_FILE_NAME).path,
- });
- inProgressPrivateDownload.start().catch(() => {});
- yield promiseDownloadMidway(inProgressPrivateDownload);
- yield privateList.add(inProgressPrivateDownload);
-
- // Verify that the summary includes the total number of bytes and the
- // currently transferred bytes only for the downloads that are not stopped.
- // For simplicity, we assume that after a download is added to the list, its
- // current state is immediately propagated to the summary object, which is
- // true in the current implementation, though it is not guaranteed as all the
- // download operations may happen asynchronously.
- do_check_false(publicSummary.allHaveStopped);
- do_check_eq(publicSummary.progressTotalBytes, TEST_DATA_SHORT.length * 2);
- do_check_eq(publicSummary.progressCurrentBytes, TEST_DATA_SHORT.length);
-
- do_check_false(privateSummary.allHaveStopped);
- do_check_eq(privateSummary.progressTotalBytes, TEST_DATA_SHORT.length * 2);
- do_check_eq(privateSummary.progressCurrentBytes, TEST_DATA_SHORT.length);
-
- do_check_false(combinedSummary.allHaveStopped);
- do_check_eq(combinedSummary.progressTotalBytes, TEST_DATA_SHORT.length * 4);
- do_check_eq(combinedSummary.progressCurrentBytes, TEST_DATA_SHORT.length * 2);
-
- yield inProgressPublicDownload.cancel();
-
- // Stopping the download should have excluded it from the summary.
- do_check_true(publicSummary.allHaveStopped);
- do_check_eq(publicSummary.progressTotalBytes, 0);
- do_check_eq(publicSummary.progressCurrentBytes, 0);
-
- do_check_false(privateSummary.allHaveStopped);
- do_check_eq(privateSummary.progressTotalBytes, TEST_DATA_SHORT.length * 2);
- do_check_eq(privateSummary.progressCurrentBytes, TEST_DATA_SHORT.length);
-
- do_check_false(combinedSummary.allHaveStopped);
- do_check_eq(combinedSummary.progressTotalBytes, TEST_DATA_SHORT.length * 2);
- do_check_eq(combinedSummary.progressCurrentBytes, TEST_DATA_SHORT.length);
-
- yield inProgressPrivateDownload.cancel();
-
- // All the downloads should be stopped now.
- do_check_true(publicSummary.allHaveStopped);
- do_check_eq(publicSummary.progressTotalBytes, 0);
- do_check_eq(publicSummary.progressCurrentBytes, 0);
-
- do_check_true(privateSummary.allHaveStopped);
- do_check_eq(privateSummary.progressTotalBytes, 0);
- do_check_eq(privateSummary.progressCurrentBytes, 0);
-
- do_check_true(combinedSummary.allHaveStopped);
- do_check_eq(combinedSummary.progressTotalBytes, 0);
- do_check_eq(combinedSummary.progressCurrentBytes, 0);
-});
-
-/**
- * Checks that views receive the summary change notification. This is tested on
- * the combined summary when adding a public download, as we assume that if we
- * pass the test in this case we will also pass it in the others.
- */
-add_task(function* test_DownloadSummary_notifications()
-{
- let list = yield promiseNewList();
- let summary = yield Downloads.getSummary(Downloads.ALL);
-
- let download = yield promiseNewDownload();
- yield list.add(download);
-
- // Check that we receive change notifications.
- let receivedOnSummaryChanged = false;
- yield summary.addView({
- onSummaryChanged: function () {
- receivedOnSummaryChanged = true;
- },
- });
- yield download.start();
- do_check_true(receivedOnSummaryChanged);
-});
diff --git a/toolkit/components/jsdownloads/test/unit/test_DownloadStore.js b/toolkit/components/jsdownloads/test/unit/test_DownloadStore.js
deleted file mode 100644
index 3a23dfbe3..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_DownloadStore.js
+++ /dev/null
@@ -1,315 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the DownloadStore object.
- */
-
-"use strict";
-
-// Globals
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadStore",
- "resource://gre/modules/DownloadStore.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm")
-
-/**
- * Returns a new DownloadList object with an associated DownloadStore.
- *
- * @param aStorePath
- * String pointing to the file to be associated with the DownloadStore,
- * or undefined to use a non-existing temporary file. In this case, the
- * temporary file is deleted when the test file execution finishes.
- *
- * @return {Promise}
- * @resolves Array [ Newly created DownloadList , associated DownloadStore ].
- * @rejects JavaScript exception.
- */
-function promiseNewListAndStore(aStorePath)
-{
- return promiseNewList().then(function (aList) {
- let path = aStorePath || getTempFile(TEST_STORE_FILE_NAME).path;
- let store = new DownloadStore(aList, path);
- return [aList, store];
- });
-}
-
-// Tests
-
-/**
- * Saves downloads to a file, then reloads them.
- */
-add_task(function* test_save_reload()
-{
- let [listForSave, storeForSave] = yield promiseNewListAndStore();
- let [listForLoad, storeForLoad] = yield promiseNewListAndStore(
- storeForSave.path);
-
- listForSave.add(yield promiseNewDownload(httpUrl("source.txt")));
- listForSave.add(yield Downloads.createDownload({
- source: { url: httpUrl("empty.txt"),
- referrer: TEST_REFERRER_URL },
- target: getTempFile(TEST_TARGET_FILE_NAME),
- }));
-
- // This PDF download should not be serialized because it never succeeds.
- let pdfDownload = yield Downloads.createDownload({
- source: { url: httpUrl("empty.txt"),
- referrer: TEST_REFERRER_URL },
- target: getTempFile(TEST_TARGET_FILE_NAME),
- saver: "pdf",
- });
- listForSave.add(pdfDownload);
-
- // If we used a callback to adjust the channel, the download should
- // not be serialized because we can't recreate it across sessions.
- let adjustedDownload = yield Downloads.createDownload({
- source: { url: httpUrl("empty.txt"),
- adjustChannel: () => Promise.resolve() },
- target: getTempFile(TEST_TARGET_FILE_NAME),
- });
- listForSave.add(adjustedDownload);
-
- let legacyDownload = yield promiseStartLegacyDownload();
- yield legacyDownload.cancel();
- listForSave.add(legacyDownload);
-
- yield storeForSave.save();
- yield storeForLoad.load();
-
- // Remove the PDF and adjusted downloads because they should not appear here.
- listForSave.remove(adjustedDownload);
- listForSave.remove(pdfDownload);
-
- let itemsForSave = yield listForSave.getAll();
- let itemsForLoad = yield listForLoad.getAll();
-
- do_check_eq(itemsForSave.length, itemsForLoad.length);
-
- // Downloads should be reloaded in the same order.
- for (let i = 0; i < itemsForSave.length; i++) {
- // The reloaded downloads are different objects.
- do_check_neq(itemsForSave[i], itemsForLoad[i]);
-
- // The reloaded downloads have the same properties.
- do_check_eq(itemsForSave[i].source.url,
- itemsForLoad[i].source.url);
- do_check_eq(itemsForSave[i].source.referrer,
- itemsForLoad[i].source.referrer);
- do_check_eq(itemsForSave[i].target.path,
- itemsForLoad[i].target.path);
- do_check_eq(itemsForSave[i].saver.toSerializable(),
- itemsForLoad[i].saver.toSerializable());
- }
-});
-
-/**
- * Checks that saving an empty list deletes any existing file.
- */
-add_task(function* test_save_empty()
-{
- let [, store] = yield promiseNewListAndStore();
-
- let createdFile = yield OS.File.open(store.path, { create: true });
- yield createdFile.close();
-
- yield store.save();
-
- do_check_false(yield OS.File.exists(store.path));
-
- // If the file does not exist, saving should not generate exceptions.
- yield store.save();
-});
-
-/**
- * Checks that loading from a missing file results in an empty list.
- */
-add_task(function* test_load_empty()
-{
- let [list, store] = yield promiseNewListAndStore();
-
- do_check_false(yield OS.File.exists(store.path));
-
- yield store.load();
-
- let items = yield list.getAll();
- do_check_eq(items.length, 0);
-});
-
-/**
- * Loads downloads from a string in a predefined format. The purpose of this
- * test is to verify that the JSON format used in previous versions can be
- * loaded, assuming the file is reloaded on the same platform.
- */
-add_task(function* test_load_string_predefined()
-{
- let [list, store] = yield promiseNewListAndStore();
-
- // The platform-dependent file name should be generated dynamically.
- let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
- let filePathLiteral = JSON.stringify(targetPath);
- let sourceUriLiteral = JSON.stringify(httpUrl("source.txt"));
- let emptyUriLiteral = JSON.stringify(httpUrl("empty.txt"));
- let referrerUriLiteral = JSON.stringify(TEST_REFERRER_URL);
-
- let string = "{\"list\":[{\"source\":" + sourceUriLiteral + "," +
- "\"target\":" + filePathLiteral + "}," +
- "{\"source\":{\"url\":" + emptyUriLiteral + "," +
- "\"referrer\":" + referrerUriLiteral + "}," +
- "\"target\":" + filePathLiteral + "}]}";
-
- yield OS.File.writeAtomic(store.path,
- new TextEncoder().encode(string),
- { tmpPath: store.path + ".tmp" });
-
- yield store.load();
-
- let items = yield list.getAll();
-
- do_check_eq(items.length, 2);
-
- do_check_eq(items[0].source.url, httpUrl("source.txt"));
- do_check_eq(items[0].target.path, targetPath);
-
- do_check_eq(items[1].source.url, httpUrl("empty.txt"));
- do_check_eq(items[1].source.referrer, TEST_REFERRER_URL);
- do_check_eq(items[1].target.path, targetPath);
-});
-
-/**
- * Loads downloads from a well-formed JSON string containing unrecognized data.
- */
-add_task(function* test_load_string_unrecognized()
-{
- let [list, store] = yield promiseNewListAndStore();
-
- // The platform-dependent file name should be generated dynamically.
- let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
- let filePathLiteral = JSON.stringify(targetPath);
- let sourceUriLiteral = JSON.stringify(httpUrl("source.txt"));
-
- let string = "{\"list\":[{\"source\":null," +
- "\"target\":null}," +
- "{\"source\":{\"url\":" + sourceUriLiteral + "}," +
- "\"target\":{\"path\":" + filePathLiteral + "}," +
- "\"saver\":{\"type\":\"copy\"}}]}";
-
- yield OS.File.writeAtomic(store.path,
- new TextEncoder().encode(string),
- { tmpPath: store.path + ".tmp" });
-
- yield store.load();
-
- let items = yield list.getAll();
-
- do_check_eq(items.length, 1);
-
- do_check_eq(items[0].source.url, httpUrl("source.txt"));
- do_check_eq(items[0].target.path, targetPath);
-});
-
-/**
- * Loads downloads from a malformed JSON string.
- */
-add_task(function* test_load_string_malformed()
-{
- let [list, store] = yield promiseNewListAndStore();
-
- let string = "{\"list\":[{\"source\":null,\"target\":null}," +
- "{\"source\":{\"url\":\"about:blank\"}}}";
-
- yield OS.File.writeAtomic(store.path, new TextEncoder().encode(string),
- { tmpPath: store.path + ".tmp" });
-
- try {
- yield store.load();
- do_throw("Exception expected when JSON data is malformed.");
- } catch (ex) {
- if (ex.name != "SyntaxError") {
- throw ex;
- }
- do_print("The expected SyntaxError exception was thrown.");
- }
-
- let items = yield list.getAll();
-
- do_check_eq(items.length, 0);
-});
-
-/**
- * Saves downloads with unknown properties to a file and then reloads
- * them to ensure that these properties are preserved.
- */
-add_task(function* test_save_reload_unknownProperties()
-{
- let [listForSave, storeForSave] = yield promiseNewListAndStore();
- let [listForLoad, storeForLoad] = yield promiseNewListAndStore(
- storeForSave.path);
-
- let download1 = yield promiseNewDownload(httpUrl("source.txt"));
- // startTime should be ignored as it is a known property, and error
- // is ignored by serialization
- download1._unknownProperties = { peanut: "butter",
- orange: "marmalade",
- startTime: 77,
- error: { message: "Passed" } };
- listForSave.add(download1);
-
- let download2 = yield promiseStartLegacyDownload();
- yield download2.cancel();
- download2._unknownProperties = { number: 5, object: { test: "string" } };
- listForSave.add(download2);
-
- let download3 = yield Downloads.createDownload({
- source: { url: httpUrl("empty.txt"),
- referrer: TEST_REFERRER_URL,
- source1: "download3source1",
- source2: "download3source2" },
- target: { path: getTempFile(TEST_TARGET_FILE_NAME).path,
- target1: "download3target1",
- target2: "download3target2" },
- saver : { type: "copy",
- saver1: "download3saver1",
- saver2: "download3saver2" },
- });
- listForSave.add(download3);
-
- yield storeForSave.save();
- yield storeForLoad.load();
-
- let itemsForSave = yield listForSave.getAll();
- let itemsForLoad = yield listForLoad.getAll();
-
- do_check_eq(itemsForSave.length, itemsForLoad.length);
-
- do_check_eq(Object.keys(itemsForLoad[0]._unknownProperties).length, 2);
- do_check_eq(itemsForLoad[0]._unknownProperties.peanut, "butter");
- do_check_eq(itemsForLoad[0]._unknownProperties.orange, "marmalade");
- do_check_false("startTime" in itemsForLoad[0]._unknownProperties);
- do_check_false("error" in itemsForLoad[0]._unknownProperties);
-
- do_check_eq(Object.keys(itemsForLoad[1]._unknownProperties).length, 2);
- do_check_eq(itemsForLoad[1]._unknownProperties.number, 5);
- do_check_eq(itemsForLoad[1]._unknownProperties.object.test, "string");
-
- do_check_eq(Object.keys(itemsForLoad[2].source._unknownProperties).length, 2);
- do_check_eq(itemsForLoad[2].source._unknownProperties.source1,
- "download3source1");
- do_check_eq(itemsForLoad[2].source._unknownProperties.source2,
- "download3source2");
-
- do_check_eq(Object.keys(itemsForLoad[2].target._unknownProperties).length, 2);
- do_check_eq(itemsForLoad[2].target._unknownProperties.target1,
- "download3target1");
- do_check_eq(itemsForLoad[2].target._unknownProperties.target2,
- "download3target2");
-
- do_check_eq(Object.keys(itemsForLoad[2].saver._unknownProperties).length, 2);
- do_check_eq(itemsForLoad[2].saver._unknownProperties.saver1,
- "download3saver1");
- do_check_eq(itemsForLoad[2].saver._unknownProperties.saver2,
- "download3saver2");
-});
diff --git a/toolkit/components/jsdownloads/test/unit/test_Downloads.js b/toolkit/components/jsdownloads/test/unit/test_Downloads.js
deleted file mode 100644
index 2027beee1..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_Downloads.js
+++ /dev/null
@@ -1,194 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the functions located directly in the "Downloads" object.
- */
-
-"use strict";
-
-// Tests
-
-/**
- * Tests that the createDownload function exists and can be called. More
- * detailed tests are implemented separately for the DownloadCore module.
- */
-add_task(function* test_createDownload()
-{
- // Creates a simple Download object without starting the download.
- yield Downloads.createDownload({
- source: { url: "about:blank" },
- target: { path: getTempFile(TEST_TARGET_FILE_NAME).path },
- saver: { type: "copy" },
- });
-});
-
-/**
- * Tests createDownload for private download.
- */
-add_task(function* test_createDownload_private()
-{
- let download = yield Downloads.createDownload({
- source: { url: "about:blank", isPrivate: true },
- target: { path: getTempFile(TEST_TARGET_FILE_NAME).path },
- saver: { type: "copy" }
- });
- do_check_true(download.source.isPrivate);
-});
-
-/**
- * Tests createDownload for normal (public) download.
- */
-add_task(function* test_createDownload_public()
-{
- let tempPath = getTempFile(TEST_TARGET_FILE_NAME).path;
- let download = yield Downloads.createDownload({
- source: { url: "about:blank", isPrivate: false },
- target: { path: tempPath },
- saver: { type: "copy" }
- });
- do_check_false(download.source.isPrivate);
-
- download = yield Downloads.createDownload({
- source: { url: "about:blank" },
- target: { path: tempPath },
- saver: { type: "copy" }
- });
- do_check_false(download.source.isPrivate);
-});
-
-/**
- * Tests createDownload for a pdf saver throws if only given a url.
- */
-add_task(function* test_createDownload_pdf()
-{
- let download = yield Downloads.createDownload({
- source: { url: "about:blank" },
- target: { path: getTempFile(TEST_TARGET_FILE_NAME).path },
- saver: { type: "pdf" },
- });
-
- try {
- yield download.start();
- do_throw("The download should have failed.");
- } catch (ex) {
- if (!(ex instanceof Downloads.Error) || !ex.becauseSourceFailed) {
- throw ex;
- }
- }
-
- do_check_false(download.succeeded);
- do_check_true(download.stopped);
- do_check_false(download.canceled);
- do_check_true(download.error !== null);
- do_check_true(download.error.becauseSourceFailed);
- do_check_false(download.error.becauseTargetFailed);
- do_check_false(yield OS.File.exists(download.target.path));
-});
-
-/**
- * Tests "fetch" with nsIURI and nsIFile as arguments.
- */
-add_task(function* test_fetch_uri_file_arguments()
-{
- let targetFile = getTempFile(TEST_TARGET_FILE_NAME);
- yield Downloads.fetch(NetUtil.newURI(httpUrl("source.txt")), targetFile);
- yield promiseVerifyContents(targetFile.path, TEST_DATA_SHORT);
-});
-
-/**
- * Tests "fetch" with DownloadSource and DownloadTarget as arguments.
- */
-add_task(function* test_fetch_object_arguments()
-{
- let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
- yield Downloads.fetch({ url: httpUrl("source.txt") }, { path: targetPath });
- yield promiseVerifyContents(targetPath, TEST_DATA_SHORT);
-});
-
-/**
- * Tests "fetch" with string arguments.
- */
-add_task(function* test_fetch_string_arguments()
-{
- let targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
- yield Downloads.fetch(httpUrl("source.txt"), targetPath);
- yield promiseVerifyContents(targetPath, TEST_DATA_SHORT);
-
- targetPath = getTempFile(TEST_TARGET_FILE_NAME).path;
- yield Downloads.fetch(new String(httpUrl("source.txt")),
- new String(targetPath));
- yield promiseVerifyContents(targetPath, TEST_DATA_SHORT);
-});
-
-/**
- * Tests that the getList function returns the same list when called multiple
- * times with the same argument, but returns different lists when called with
- * different arguments. More detailed tests are implemented separately for the
- * DownloadList module.
- */
-add_task(function* test_getList()
-{
- let publicListOne = yield Downloads.getList(Downloads.PUBLIC);
- let privateListOne = yield Downloads.getList(Downloads.PRIVATE);
-
- let publicListTwo = yield Downloads.getList(Downloads.PUBLIC);
- let privateListTwo = yield Downloads.getList(Downloads.PRIVATE);
-
- do_check_eq(publicListOne, publicListTwo);
- do_check_eq(privateListOne, privateListTwo);
-
- do_check_neq(publicListOne, privateListOne);
-});
-
-/**
- * Tests that the getSummary function returns the same summary when called
- * multiple times with the same argument, but returns different summaries when
- * called with different arguments. More detailed tests are implemented
- * separately for the DownloadSummary object in the DownloadList module.
- */
-add_task(function* test_getSummary()
-{
- let publicSummaryOne = yield Downloads.getSummary(Downloads.PUBLIC);
- let privateSummaryOne = yield Downloads.getSummary(Downloads.PRIVATE);
-
- let publicSummaryTwo = yield Downloads.getSummary(Downloads.PUBLIC);
- let privateSummaryTwo = yield Downloads.getSummary(Downloads.PRIVATE);
-
- do_check_eq(publicSummaryOne, publicSummaryTwo);
- do_check_eq(privateSummaryOne, privateSummaryTwo);
-
- do_check_neq(publicSummaryOne, privateSummaryOne);
-});
-
-/**
- * Tests that the getSystemDownloadsDirectory returns a non-empty download
- * directory string.
- */
-add_task(function* test_getSystemDownloadsDirectory()
-{
- let downloadDir = yield Downloads.getSystemDownloadsDirectory();
- do_check_neq(downloadDir, "");
-});
-
-/**
- * Tests that the getPreferredDownloadsDirectory returns a non-empty download
- * directory string.
- */
-add_task(function* test_getPreferredDownloadsDirectory()
-{
- let downloadDir = yield Downloads.getPreferredDownloadsDirectory();
- do_check_neq(downloadDir, "");
-});
-
-/**
- * Tests that the getTemporaryDownloadsDirectory returns a non-empty download
- * directory string.
- */
-add_task(function* test_getTemporaryDownloadsDirectory()
-{
- let downloadDir = yield Downloads.getTemporaryDownloadsDirectory();
- do_check_neq(downloadDir, "");
-});
diff --git a/toolkit/components/jsdownloads/test/unit/test_PrivateTemp.js b/toolkit/components/jsdownloads/test/unit/test_PrivateTemp.js
deleted file mode 100644
index 1308e9782..000000000
--- a/toolkit/components/jsdownloads/test/unit/test_PrivateTemp.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/*
- * The temporary directory downloads saves to, should be only readable
- * for the current user.
- */
-add_task(function* test_private_temp() {
-
- let download = yield promiseStartExternalHelperAppServiceDownload(
- httpUrl("empty.txt"));
-
- yield promiseDownloadStopped(download);
-
- var targetFile = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
- targetFile.initWithPath(download.target.path);
-
- // 488 is the decimal value of 0o700.
- equal(targetFile.parent.permissions, 448);
-});
diff --git a/toolkit/components/jsdownloads/test/unit/xpcshell.ini b/toolkit/components/jsdownloads/test/unit/xpcshell.ini
deleted file mode 100644
index 8de554540..000000000
--- a/toolkit/components/jsdownloads/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-skip-if = toolkit == 'android'
-
-# Note: The "tail.js" file is not defined in the "tail" key because it calls
-# the "add_test_task" function, that does not work properly in tail files.
-support-files =
- common_test_Download.js
-
-[test_DownloadCore.js]
-[test_DownloadImport.js]
-[test_DownloadIntegration.js]
-[test_DownloadLegacy.js]
-[test_DownloadList.js]
-[test_Downloads.js]
-[test_DownloadStore.js]
-[test_PrivateTemp.js]
-skip-if = os != 'linux'
diff --git a/toolkit/components/lz4/moz.build b/toolkit/components/lz4/moz.build
index a70185930..b94e937de 100644
--- a/toolkit/components/lz4/moz.build
+++ b/toolkit/components/lz4/moz.build
@@ -4,15 +4,11 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
EXTRA_JS_MODULES += [
'lz4.js',
'lz4_internal.js',
]
-SOURCES += [
- 'lz4.cpp',
-]
+SOURCES += ['lz4.cpp']
FINAL_LIBRARY = 'xul'
diff --git a/toolkit/components/lz4/tests/xpcshell/.eslintrc.js b/toolkit/components/lz4/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/lz4/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/lz4/tests/xpcshell/data/chrome.manifest b/toolkit/components/lz4/tests/xpcshell/data/chrome.manifest
deleted file mode 100644
index e2f9a9d8e..000000000
--- a/toolkit/components/lz4/tests/xpcshell/data/chrome.manifest
+++ /dev/null
@@ -1 +0,0 @@
-content test_lz4 ./
diff --git a/toolkit/components/lz4/tests/xpcshell/data/compression.lz b/toolkit/components/lz4/tests/xpcshell/data/compression.lz
deleted file mode 100644
index a354edc03..000000000
--- a/toolkit/components/lz4/tests/xpcshell/data/compression.lz
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/lz4/tests/xpcshell/data/worker_lz4.js b/toolkit/components/lz4/tests/xpcshell/data/worker_lz4.js
deleted file mode 100644
index 47e3ea369..000000000
--- a/toolkit/components/lz4/tests/xpcshell/data/worker_lz4.js
+++ /dev/null
@@ -1,146 +0,0 @@
-importScripts("resource://gre/modules/workers/require.js");
-importScripts("resource://gre/modules/osfile.jsm");
-
-
-function do_print(x) {
- // self.postMessage({kind: "do_print", args: [x]});
- dump("TEST-INFO: " + x + "\n");
-}
-
-function do_check_true(x) {
- self.postMessage({kind: "do_check_true", args: [!!x]});
- if (x) {
- dump("TEST-PASS: " + x + "\n");
- } else {
- throw new Error("do_check_true failed");
- }
-}
-
-function do_check_eq(a, b) {
- let result = a == b;
- self.postMessage({kind: "do_check_true", args: [result]});
- if (!result) {
- throw new Error("do_check_eq failed " + a + " != " + b);
- }
-}
-
-function do_test_complete() {
- self.postMessage({kind: "do_test_complete", args:[]});
-}
-
-self.onmessage = function() {
- try {
- run_test();
- } catch (ex) {
- let {message, moduleStack, moduleName, lineNumber} = ex;
- let error = new Error(message, moduleName, lineNumber);
- error.stack = moduleStack;
- dump("Uncaught error: " + error + "\n");
- dump("Full stack: " + moduleStack + "\n");
- throw error;
- }
-};
-
-var Lz4;
-var Internals;
-function test_import() {
- Lz4 = require("resource://gre/modules/lz4.js");
- Internals = require("resource://gre/modules/lz4_internal.js");
-}
-
-function test_bound() {
- for (let k of ["compress", "decompress", "maxCompressedSize"]) {
- try {
- do_print("Checking the existence of " + k + "\n");
- do_check_true(!!Internals[k]);
- do_print(k + " exists");
- } catch (ex) {
- // Ignore errors
- do_print(k + " doesn't exist!");
- }
- }
-}
-
-function test_reference_file() {
- do_print("Decompress reference file");
- let path = OS.Path.join("data", "compression.lz");
- let data = OS.File.read(path);
- let decompressed = Lz4.decompressFileContent(data);
- let text = (new TextDecoder()).decode(decompressed);
- do_check_eq(text, "Hello, lz4");
-}
-
-function compare_arrays(a, b) {
- return Array.prototype.join.call(a) == Array.prototype.join.call(a);
-}
-
-function run_rawcompression(name, array) {
- do_print("Raw compression test " + name);
- let length = array.byteLength;
- let compressedArray = new Uint8Array(Internals.maxCompressedSize(length));
- let compressedBytes = Internals.compress(array, length, compressedArray);
- compressedArray = new Uint8Array(compressedArray.buffer, 0, compressedBytes);
- do_print("Raw compressed: " + length + " into " + compressedBytes);
-
- let decompressedArray = new Uint8Array(length);
- let decompressedBytes = new ctypes.size_t();
- let success = Internals.decompress(compressedArray, compressedBytes,
- decompressedArray, length,
- decompressedBytes.address());
- do_print("Raw decompression success? " + success);
- do_print("Raw decompression size: " + decompressedBytes.value);
- do_check_true(compare_arrays(array, decompressedArray));
-}
-
-function run_filecompression(name, array) {
- do_print("File compression test " + name);
- let compressed = Lz4.compressFileContent(array);
- do_print("Compressed " + array.byteLength + " bytes into " + compressed.byteLength);
-
- let decompressed = Lz4.decompressFileContent(compressed);
- do_print("Decompressed " + compressed.byteLength + " bytes into " + decompressed.byteLength);
- do_check_true(compare_arrays(array, decompressed));
-}
-
-function run_faileddecompression(name, array) {
- do_print("invalid decompression test " + name);
-
- // Ensure that raw decompression doesn't segfault
- let length = 1 << 14;
- let decompressedArray = new Uint8Array(length);
- let decompressedBytes = new ctypes.size_t();
- Internals.decompress(array, array.byteLength,
- decompressedArray, length,
- decompressedBytes.address());
-
- // File decompression should fail with an acceptable exception
- let exn = null;
- try {
- Lz4.decompressFileContent(array);
- } catch (ex) {
- exn = ex;
- }
- do_check_true(exn);
- if (array.byteLength < 10) {
- do_check_true(exn.becauseLZNoHeader);
- } else {
- do_check_true(exn.becauseLZWrongMagicNumber);
- }
-}
-
-function run_test() {
- test_import();
- test_bound();
- test_reference_file();
- for (let length of [0, 1, 1024]) {
- let array = new Uint8Array(length);
- for (let i = 0; i < length; ++i) {
- array[i] = i % 256;
- }
- let name = length + " bytes";
- run_rawcompression(name, array);
- run_filecompression(name, array);
- run_faileddecompression(name, array);
- }
- do_test_complete();
-}
diff --git a/toolkit/components/lz4/tests/xpcshell/test_lz4.js b/toolkit/components/lz4/tests/xpcshell/test_lz4.js
deleted file mode 100644
index 8a8fc0b21..000000000
--- a/toolkit/components/lz4/tests/xpcshell/test_lz4.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/Promise.jsm");
-
-var WORKER_SOURCE_URI = "chrome://test_lz4/content/worker_lz4.js";
-do_load_manifest("data/chrome.manifest");
-
-function run_test() {
- run_next_test();
-}
-
-
-add_task(function() {
- let worker = new ChromeWorker(WORKER_SOURCE_URI);
- let deferred = Promise.defer();
- worker.onmessage = function(event) {
- let data = event.data;
- switch (data.kind) {
- case "do_check_true":
- try {
- do_check_true(data.args[0]);
- } catch (ex) {
- // Ignore errors
- }
- return;
- case "do_test_complete":
- deferred.resolve();
- worker.terminate();
- break;
- case "do_print":
- do_print(data.args[0]);
- }
- };
- worker.onerror = function(event) {
- let error = new Error(event.message, event.filename, event.lineno);
- worker.terminate();
- deferred.reject(error);
- };
- worker.postMessage("START");
- return deferred.promise;
-});
-
diff --git a/toolkit/components/lz4/tests/xpcshell/test_lz4_sync.js b/toolkit/components/lz4/tests/xpcshell/test_lz4_sync.js
deleted file mode 100644
index 61605373b..000000000
--- a/toolkit/components/lz4/tests/xpcshell/test_lz4_sync.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const Cu = Components.utils;
-Cu.import("resource://gre/modules/lz4.js");
-Cu.import("resource://gre/modules/osfile.jsm");
-
-function run_test() {
- run_next_test();
-}
-
-function compare_arrays(a, b) {
- return Array.prototype.join.call(a) == Array.prototype.join.call(a);
-}
-
-add_task(function*() {
- let path = OS.Path.join("data", "compression.lz");
- let data = yield OS.File.read(path);
- let decompressed = Lz4.decompressFileContent(data);
- let text = (new TextDecoder()).decode(decompressed);
- do_check_eq(text, "Hello, lz4");
-});
-
-add_task(function*() {
- for (let length of [0, 1, 1024]) {
- let array = new Uint8Array(length);
- for (let i = 0; i < length; ++i) {
- array[i] = i % 256;
- }
-
- let compressed = Lz4.compressFileContent(array);
- do_print("Compressed " + array.byteLength + " bytes into " +
- compressed.byteLength);
-
- let decompressed = Lz4.decompressFileContent(compressed);
- do_print("Decompressed " + compressed.byteLength + " bytes into " +
- decompressed.byteLength);
-
- do_check_true(compare_arrays(array, decompressed));
- }
-});
diff --git a/toolkit/components/lz4/tests/xpcshell/xpcshell.ini b/toolkit/components/lz4/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index e457f29b2..000000000
--- a/toolkit/components/lz4/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[DEFAULT]
-head =
-tail =
-skip-if = toolkit == 'android'
-support-files =
- data/worker_lz4.js
- data/chrome.manifest
- data/compression.lz
-
-[test_lz4.js]
-[test_lz4_sync.js]
diff --git a/toolkit/components/mediasniffer/moz.build b/toolkit/components/mediasniffer/moz.build
index d4f935f56..21be451dd 100644
--- a/toolkit/components/mediasniffer/moz.build
+++ b/toolkit/components/mediasniffer/moz.build
@@ -4,11 +4,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-
-EXPORTS += [
- 'nsMediaSniffer.h',
-]
+EXPORTS += ['nsMediaSniffer.h']
UNIFIED_SOURCES += [
'mp3sniff.c',
@@ -17,6 +13,3 @@ UNIFIED_SOURCES += [
]
FINAL_LIBRARY = 'xul'
-
-with Files('**'):
- BUG_COMPONENT = ('Core', 'Video/Audio')
diff --git a/toolkit/components/mediasniffer/test/unit/.eslintrc.js b/toolkit/components/mediasniffer/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/mediasniffer/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/mediasniffer/test/unit/data/bug1079747.mp4 b/toolkit/components/mediasniffer/test/unit/data/bug1079747.mp4
deleted file mode 100644
index f00731d7e..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/bug1079747.mp4
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/detodos.mp3 b/toolkit/components/mediasniffer/test/unit/data/detodos.mp3
deleted file mode 100644
index 12e3f89c2..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/detodos.mp3
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/ff-inst.exe b/toolkit/components/mediasniffer/test/unit/data/ff-inst.exe
deleted file mode 100644
index 0f02f36e1..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/ff-inst.exe
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/file.mkv b/toolkit/components/mediasniffer/test/unit/data/file.mkv
deleted file mode 100644
index 4618cda03..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/file.mkv
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/file.webm b/toolkit/components/mediasniffer/test/unit/data/file.webm
deleted file mode 100644
index 7bc738b8b..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/file.webm
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/fl10.mp2 b/toolkit/components/mediasniffer/test/unit/data/fl10.mp2
deleted file mode 100644
index bf84d7367..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/fl10.mp2
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/he_free.mp3 b/toolkit/components/mediasniffer/test/unit/data/he_free.mp3
deleted file mode 100644
index e3da8e6a7..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/he_free.mp3
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/id3tags.mp3 b/toolkit/components/mediasniffer/test/unit/data/id3tags.mp3
deleted file mode 100644
index 23091e666..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/id3tags.mp3
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/notags-bad.mp3 b/toolkit/components/mediasniffer/test/unit/data/notags-bad.mp3
deleted file mode 100644
index 5ad89786f..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/notags-bad.mp3
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/notags-scan.mp3 b/toolkit/components/mediasniffer/test/unit/data/notags-scan.mp3
deleted file mode 100644
index 949b7c468..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/notags-scan.mp3
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/data/notags.mp3 b/toolkit/components/mediasniffer/test/unit/data/notags.mp3
deleted file mode 100644
index c7db94361..000000000
--- a/toolkit/components/mediasniffer/test/unit/data/notags.mp3
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js
deleted file mode 100644
index b26d554a8..000000000
--- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-
-Cu.import("resource://testing-common/httpd.js");
-Cu.import("resource://gre/modules/NetUtil.jsm");
-
-const PATH = "/file.meh";
-var httpserver = new HttpServer();
-
-// Each time, the data consist in a string that should be sniffed as Ogg.
-const data = "OggS\0meeeh.";
-var testRan = 0;
-
-// If the content-type is not present, or if it's application/octet-stream, it
-// should be sniffed to application/ogg by the media sniffer. Otherwise, it
-// should not be changed.
-const tests = [
- // Those three first case are the case of a media loaded in a media element.
- // All three should be sniffed.
- { contentType: "",
- expectedContentType: "application/ogg",
- flags: Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS | Ci.nsIChannel.LOAD_MEDIA_SNIFFER_OVERRIDES_CONTENT_TYPE },
- { contentType: "application/octet-stream",
- expectedContentType: "application/ogg",
- flags: Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS | Ci.nsIChannel.LOAD_MEDIA_SNIFFER_OVERRIDES_CONTENT_TYPE },
- { contentType: "application/something",
- expectedContentType: "application/ogg",
- flags: Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS | Ci.nsIChannel.LOAD_MEDIA_SNIFFER_OVERRIDES_CONTENT_TYPE },
- // This last cases test the case of a channel opened while allowing content
- // sniffers to override the content-type, like in the docshell.
- { contentType: "application/octet-stream",
- expectedContentType: "application/ogg",
- flags: Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS },
- { contentType: "",
- expectedContentType: "application/ogg",
- flags: Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS },
- { contentType: "application/something",
- expectedContentType: "application/something",
- flags: Ci.nsIChannel.LOAD_CALL_CONTENT_SNIFFERS },
-];
-
-// A basic listener that reads checks the if we sniffed properly.
-var listener = {
- onStartRequest: function(request, context) {
- do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType,
- tests[testRan].expectedContentType);
- },
-
- onDataAvailable: function(request, context, stream, offset, count) {
- try {
- var bis = Components.classes["@mozilla.org/binaryinputstream;1"]
- .createInstance(Components.interfaces.nsIBinaryInputStream);
- bis.setInputStream(stream);
- bis.readByteArray(bis.available());
- } catch (ex) {
- do_throw("Error in onDataAvailable: " + ex);
- }
- },
-
- onStopRequest: function(request, context, status) {
- testRan++;
- runNext();
- }
-};
-
-function setupChannel(url, flags)
-{
- let uri = "http://localhost:" +
- httpserver.identity.primaryPort + url;
- var chan = NetUtil.newChannel({
- uri: uri,
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_MEDIA
- });
- chan.loadFlags |= flags;
- var httpChan = chan.QueryInterface(Components.interfaces.nsIHttpChannel);
- return httpChan;
-}
-
-function runNext() {
- if (testRan == tests.length) {
- do_test_finished();
- return;
- }
- var channel = setupChannel(PATH, tests[testRan].flags);
- httpserver.registerPathHandler(PATH, function(request, response) {
- response.setHeader("Content-Type", tests[testRan].contentType, false);
- response.bodyOutputStream.write(data, data.length);
- });
- channel.asyncOpen2(listener);
-}
-
-function run_test() {
- httpserver.start(-1);
- do_test_pending();
- try {
- runNext();
- } catch (e) {
- print("ERROR - " + e + "\n");
- }
-}
diff --git a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js b/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js
deleted file mode 100644
index ce30a5c1b..000000000
--- a/toolkit/components/mediasniffer/test/unit/test_mediasniffer_ext.js
+++ /dev/null
@@ -1,122 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cc = Components.classes;
-var CC = Components.Constructor;
-
-var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1",
- "nsIBinaryOutputStream",
- "setOutputStream");
-
-Cu.import("resource://testing-common/httpd.js");
-Cu.import("resource://gre/modules/NetUtil.jsm");
-
-var httpserver = new HttpServer();
-
-var testRan = 0;
-
-// The tests files we want to test, and the type we should have after sniffing.
-const tests = [
- // Real webm and mkv files truncated to 512 bytes.
- { path: "data/file.webm", expected: "video/webm" },
- { path: "data/file.mkv", expected: "application/octet-stream" },
- // MP3 files with and without id3 headers truncated to 512 bytes.
- // NB these have 208/209 byte frames, but mp3 can require up to
- // 1445 bytes to detect with our method.
- { path: "data/id3tags.mp3", expected: "audio/mpeg" },
- { path: "data/notags.mp3", expected: "audio/mpeg" },
- // MPEG-2 mp3 files.
- { path: "data/detodos.mp3", expected: "audio/mpeg" },
- // Padding bit flipped in the first header: sniffing should fail.
- { path: "data/notags-bad.mp3", expected: "application/octet-stream" },
- // Garbage before header: sniffing should fail.
- { path: "data/notags-scan.mp3", expected: "application/octet-stream" },
- // VBR from the layer III test patterns. We can't sniff this.
- { path: "data/he_free.mp3", expected: "application/octet-stream" },
- // Make sure we reject mp2, which has a similar header.
- { path: "data/fl10.mp2", expected: "application/octet-stream" },
- // Truncated ff installer regression test for bug 875769.
- { path: "data/ff-inst.exe", expected: "application/octet-stream" },
- // MP4 with invalid box size (0) for "ftyp".
- { path: "data/bug1079747.mp4", expected: "application/octet-stream" },
-];
-
-// A basic listener that reads checks the if we sniffed properly.
-var listener = {
- onStartRequest: function(request, context) {
- do_print("Sniffing " + tests[testRan].path);
- do_check_eq(request.QueryInterface(Ci.nsIChannel).contentType, tests[testRan].expected);
- },
-
- onDataAvailable: function(request, context, stream, offset, count) {
- try {
- var bis = Components.classes["@mozilla.org/binaryinputstream;1"]
- .createInstance(Components.interfaces.nsIBinaryInputStream);
- bis.setInputStream(stream);
- bis.readByteArray(bis.available());
- } catch (ex) {
- do_throw("Error in onDataAvailable: " + ex);
- }
- },
-
- onStopRequest: function(request, context, status) {
- testRan++;
- runNext();
- }
-};
-
-function setupChannel(url) {
- var chan = NetUtil.newChannel({
- uri: "http://localhost:" + httpserver.identity.primaryPort + url,
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_MEDIA
- });
- var httpChan = chan.QueryInterface(Components.interfaces.nsIHttpChannel);
- return httpChan;
-}
-
-function runNext() {
- if (testRan == tests.length) {
- do_test_finished();
- return;
- }
- var channel = setupChannel("/");
- channel.asyncOpen2(listener);
-}
-
-function getFileContents(aFile) {
- var fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- fileStream.init(aFile, 1, -1, null);
- var bis = Components.classes["@mozilla.org/binaryinputstream;1"]
- .createInstance(Components.interfaces.nsIBinaryInputStream);
- bis.setInputStream(fileStream);
-
- var data = bis.readByteArray(bis.available());
-
- return data;
-}
-
-function handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, "OK");
- // Send an empty Content-Type, so we are guaranteed to sniff.
- response.setHeader("Content-Type", "", false);
- var body = getFileContents(do_get_file(tests[testRan].path));
- var bos = new BinaryOutputStream(response.bodyOutputStream);
- bos.writeByteArray(body, body.length);
-}
-
-function run_test() {
- // We use a custom handler so we can change the header to force sniffing.
- httpserver.registerPathHandler("/", handler);
- httpserver.start(-1);
- do_test_pending();
- try {
- runNext();
- } catch (e) {
- print("ERROR - " + e + "\n");
- }
-}
diff --git a/toolkit/components/mediasniffer/test/unit/xpcshell.ini b/toolkit/components/mediasniffer/test/unit/xpcshell.ini
deleted file mode 100644
index 5ab4763f9..000000000
--- a/toolkit/components/mediasniffer/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[DEFAULT]
-head =
-tail =
-skip-if = toolkit == 'android'
-support-files =
- data/bug1079747.mp4
- data/detodos.mp3
- data/ff-inst.exe
- data/file.mkv
- data/file.webm
- data/fl10.mp2
- data/he_free.mp3
- data/id3tags.mp3
- data/notags-bad.mp3
- data/notags-scan.mp3
- data/notags.mp3
-
-[test_mediasniffer.js]
-[test_mediasniffer_ext.js]
diff --git a/toolkit/components/microformats/manifest.ini b/toolkit/components/microformats/manifest.ini
deleted file mode 100644
index 24dbcb1ca..000000000
--- a/toolkit/components/microformats/manifest.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[DEFAULT]
-run-if = buildapp == 'browser'
-
-[test/marionette/test_standards.py]
-[test/marionette/test_modules.py]
-[test/marionette/test_interface.py]
-
diff --git a/toolkit/components/microformats/moz.build b/toolkit/components/microformats/moz.build
index 39cefe4c8..ca91e2c46 100644
--- a/toolkit/components/microformats/moz.build
+++ b/toolkit/components/microformats/moz.build
@@ -4,9 +4,4 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-EXTRA_JS_MODULES += [
- 'microformat-shiv.js'
-]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Microformats')
+EXTRA_JS_MODULES += ['microformat-shiv.js']
diff --git a/toolkit/components/microformats/test/interface-tests/count-test.js b/toolkit/components/microformats/test/interface-tests/count-test.js
deleted file mode 100644
index baac56c2b..000000000
--- a/toolkit/components/microformats/test/interface-tests/count-test.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
-Unit test for count
-*/
-
-assert = chai.assert;
-
-
-describe('Microformat.count', function() {
-
- it('count', function(){
-
- var doc,
- node,
- result;
-
- var html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a><a class="h-card" href="http://janedoe.net"><span class="p-name">Jane</span></a><a class="h-event" href="http://janedoe.net"><span class="p-name">Event</span><span class="dt-start">2015-07-01</span></a>';
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = html;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- };
-
- result = Microformats.count(options);
- assert.deepEqual( result, {'h-event': 1,'h-card': 2} );
-
- });
-
-
- it('count rels', function(){
-
- var doc,
- node,
- result;
-
- var html = '<link href="http://glennjones.net/notes/atom" rel="notes alternate" title="Notes" type="application/atom+xml" /><a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a><a class="h-card" href="http://janedoe.net"><span class="p-name">Jane</span></a><a class="h-event" href="http://janedoe.net"><span class="p-name">Event</span><span class="dt-start">2015-07-01</span></a>';
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = html;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- };
-
- result = Microformats.count(options);
- assert.deepEqual( result, {'h-event': 1,'h-card': 2, 'rels': 1} );
-
- });
-
-
- it('count - no results', function(){
-
- var doc,
- node,
- result;
-
- var html = '<span class="p-name">Jane</span>';
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = html;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- };
-
- result = Microformats.count(options);
- assert.deepEqual( result, {} );
-
- });
-
-
-
- it('count - no options', function(){
-
- var result;
-
- result = Microformats.count({});
- assert.deepEqual( result, {} );
-
- });
-
-
- it('count - options.html', function(){
-
- var options = {},
- result;
-
- options.html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a><a class="h-card" href="http://janedoe.net"><span class="p-name">Jane</span></a><a class="h-event" href="http://janedoe.net"><span class="p-name">Event</span><span class="dt-start">2015-07-01</span></a>';
-
- result = Microformats.count(options);
- assert.deepEqual( result, {'h-event': 1,'h-card': 2} );
-
- });
-
-
-
- });
diff --git a/toolkit/components/microformats/test/interface-tests/experimental-test.js b/toolkit/components/microformats/test/interface-tests/experimental-test.js
deleted file mode 100644
index 4d32b83c0..000000000
--- a/toolkit/components/microformats/test/interface-tests/experimental-test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
-Unit test for get
-*/
-
-assert = chai.assert;
-
-
-describe('experimental', function() {
-
- it('h-geo - geo data writen as lat;lon', function(){
-
- var expected = {
- 'items': [{
- 'type': ['h-geo'],
- 'properties': {
- 'name': ['30.267991;-97.739568'],
- 'latitude': [30.267991],
- 'longitude': [-97.739568]
- }
- }],
- 'rels': {},
- 'rel-urls': {}
- },
- options = {
- 'html': '<div class="h-geo">30.267991;-97.739568</div>',
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5',
- 'parseLatLonGeo': true
- };
-
- var result = Microformats.get(options);
- assert.deepEqual( result, expected );
-
- });
-
-
-});
diff --git a/toolkit/components/microformats/test/interface-tests/get-test.js b/toolkit/components/microformats/test/interface-tests/get-test.js
deleted file mode 100644
index 098ff4e3d..000000000
--- a/toolkit/components/microformats/test/interface-tests/get-test.js
+++ /dev/null
@@ -1,605 +0,0 @@
-/*
-Unit test for get
-*/
-
-assert = chai.assert;
-
-
-describe('Microformat.get', function() {
-
-
- var expected = {
- 'items': [{
- 'type': ['h-card'],
- 'properties': {
- 'name': ['Glenn Jones'],
- 'url': ['http://glennjones.net']
- }
- }],
- 'rels': {
- 'bookmark': ['http://glennjones.net'],
- 'alternate': ['http://example.com/fr'],
- 'home': ['http://example.com/fr']
- },
- 'rel-urls': {
- 'http://glennjones.net': {
- 'text': 'Glenn Jones',
- 'rels': ['bookmark']
- },
- 'http://example.com/fr': {
- 'media': 'handheld',
- 'hreflang': 'fr',
- 'text': 'French mobile homepage',
- 'rels': ['alternate', 'home']
- }
- }
- },
- html = '<div class="h-card"><a class="p-name u-url" rel="bookmark" href="http://glennjones.net">Glenn Jones</a></div><a rel="alternate home" href="http://example.com/fr" media="handheld" hreflang="fr">French mobile homepage</a>';
-
-
-
-
-
- it('get - no options.node parse this document', function(){
- var result;
-
- result = Microformats.get({});
- assert.deepEqual( result.items, [] );
- });
-
-
- it('get - standard', function(){
-
- var doc,
- node,
- options,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = html;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, expected );
-
- });
-
-
- it('get - doc pass to node', function(){
-
- var doc,
- node,
- options,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = html;
- doc.body.appendChild(node);
-
- options ={
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, expected );
-
- });
-
-
- it('get - pass base tag', function(){
-
- var doc,
- node,
- options,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = html + '<base href="http://example.com">';
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, expected );
-
- });
-
-
- it('get - pass no document', function(){
-
- var doc,
- node,
- options,
- parser,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = html + '<base href="http://example.com">';
- doc.body.appendChild(node);
-
- options ={
- 'node': doc,
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, expected );
-
- });
-
-
- it('get - textFormat: normalised', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<a class="h-card" href="http://glennjones.net">\n';
- altHTML += ' <span class="p-given-name">Glenn</span>\n';
- altHTML += ' <span class="p-family-name">Jones</span>\n';
- altHTML += '</a>\n';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'textFormat': 'normalised',
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.equal( result.items[0].properties.name[0], 'Glenn Jones' );
-
- });
-
-
- it('get - textFormat: whitespace', function(){
-
- var doc,
- node,
- options,
- parser,
- result;
-
- var altHTML = '<a class="h-card" href="http://glennjones.net">\n';
- altHTML += ' <span class="p-given-name">Glenn</span>\n';
- altHTML += ' <span class="p-family-name">Jones</span>\n';
- altHTML += '</a>\n';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'textFormat': 'whitespace',
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.equal( result.items[0].properties.name[0], '\n Glenn\n Jones\n' );
-
- });
-
-
-
- it('get - textFormat: whitespacetrimmed', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<a class="h-card" href="http://glennjones.net">\n';
- altHTML += ' <span class="p-given-name">Glenn</span>\n';
- altHTML += ' <span class="p-family-name">Jones</span>\n';
- altHTML += '</a>\n';
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'textFormat': 'whitespacetrimmed',
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.equal( result.items[0].properties.name[0], 'Glenn\n Jones' );
-
- });
-
-
- it('get - dateFormat: auto', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'dateFormat': 'auto'
- };
-
- result = Microformats.get(options);
- assert.equal( result.items[0].properties.start[0], '2015-07-01t17:30z' );
-
- });
-
-
- it('get - dateFormat: w3c', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'dateFormat': 'w3c'
- };
-
- result = Microformats.get(options);
- assert.equal( result.items[0].properties.start[0], '2015-07-01T17:30Z' );
-
- });
-
-
- it('get - dateFormat: html5', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.equal( result.items[0].properties.start[0], '2015-07-01 17:30Z' );
-
- });
-
-
-
- it('get - dateFormat: rfc3339', function(){
-
- var doc,
- node,
- options,
-
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'dateFormat': 'rfc3339'
- };
-
- result = Microformats.get(options);
- assert.equal( result.items[0].properties.start[0], '20150701T1730Z' );
-
- });
-
-
-
- it('get - filters h-card', function(){
-
- var doc,
- node,
- options,
- parser,
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div><a class="h-card" href="http://glennjones.net">Glenn Jones</a>';
- var altExpected = {
- 'items': [{
- 'type': ['h-card'],
- 'properties': {
- 'name': ['Glenn Jones'],
- 'url': ['http://glennjones.net']
- }
- }],
- 'rels': {},
- 'rel-urls': {}
- }
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- // filter as an array
- options ={
- 'node': node,
- 'filters': ['h-card'],
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, altExpected );
-
- // filter as an string
- options ={
- 'node': node,
- 'filters': 'h-card',
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, altExpected );
- });
-
-
- it('get - filters h-event', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div><a class="h-card" href="http://glennjones.net">Glenn Jones</a>';
- var altExpected = {
- 'items': [{
- 'type': ['h-event'],
- 'properties': {
- 'name': ['Pub'],
- 'start': ['2015-07-01 17:30Z']
- }
- }],
- 'rels': {},
- 'rel-urls': {}
- }
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'filters': ['h-event'],
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, altExpected );
-
- });
-
-
- it('get - filters h-card and h-event', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div><a class="h-card" href="http://glennjones.net">Glenn Jones</a>';
- var altExpected = {
- 'items': [{
- 'type': ['h-event'],
- 'properties': {
- 'name': ['Pub'],
- 'start': ['2015-07-01 17:30Z']
- }
- },
- {
- 'type': ['h-card'],
- 'properties': {
- 'name': ['Glenn Jones'],
- 'url': ['http://glennjones.net']
- }
- }],
- 'rels': {},
- 'rel-urls': {}
- }
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'filter': ['h-event'],
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, altExpected );
-
- });
-
-
- it('get - filters h-card no result', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div>';
- var altExpected = {
- 'items': [],
- 'rels': {},
- 'rel-urls': {}
- }
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'filters': ['h-card'],
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, altExpected );
-
- });
-
-
- it('get - filters h-card match v1 format', function(){
-
- var doc,
- node,
- options,
- parser,
- result;
-
- var altHTML = '<a class="vcard" href="http://glennjones.net"><span class="fn">Glenn Jones</span></a>';
- var altExpected = {
- 'items': [{
- 'type': ['h-card'],
- 'properties': {
- 'name': ['Glenn Jones']
- }
- }],
- 'rels': {},
- 'rel-urls': {}
- }
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'filter': ['h-card'],
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, altExpected );
-
- });
-
-
- it('get - add new v1 format through options', function(){
-
- var doc,
- node,
- options,
- result;
-
- var altHTML = '<div class="hpayment">£<span class="amount">36.78</span></div>';
- var altExpected = {
- 'items': [{
- 'type': ['h-payment'],
- 'properties': {
- 'amount': ['36.78']
- }
- }],
- 'rels': {},
- 'rel-urls': {}
- };
- var v1Definition = {
- root: 'hpayment',
- name: 'h-payment',
- properties: {
- 'amount': {}
- }
- };
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
-
- options ={
- 'node': node,
- 'maps': v1Definition,
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, altExpected );
-
- });
-
-
- it('get - options.html', function(){
-
- var options,
- result;
-
- options ={
- 'html': html,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
-
- result = Microformats.get(options);
- assert.deepEqual( result, expected );
-
- });
-
-
-
-
-
-});
diff --git a/toolkit/components/microformats/test/interface-tests/getParent-test.js b/toolkit/components/microformats/test/interface-tests/getParent-test.js
deleted file mode 100644
index 56ccbb2ba..000000000
--- a/toolkit/components/microformats/test/interface-tests/getParent-test.js
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
-Unit test for getParent
-*/
-
-assert = chai.assert;
-
-
-describe('Microformat.getParent', function() {
-
- var HTML = '<div class="h-event"><span class="p-name">Pub</span><span class="dt-start">2015-07-01t17:30z</span></div>';
- var emptyExpected = {
- "items": [],
- "rels": {},
- "rel-urls": {}
- };
- var expected = {
- "items": [
- {
- "type": [
- "h-event"
- ],
- "properties": {
- "name": [
- "Pub"
- ],
- "start": [
- "2015-07-01 17:30Z"
- ]
- }
- }
- ],
- "rels": {},
- "rel-urls": {}
- };
- var options = {'dateFormat': 'html5'};
-
-
-
-
- it('getParent with parent', function(){
-
- var doc,
- node,
- span,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = HTML;
- doc.body.appendChild(node);
- span = doc.querySelector('.dt-start');
-
- result = Microformats.getParent(span,options);
- assert.deepEqual( result, expected );
-
- });
-
-
-
- it('getParent without parent', function(){
-
- var doc,
- node,
- parser,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = HTML;
- doc.body.appendChild(node);
-
- result = Microformats.getParent(node,options);
- assert.deepEqual( result, emptyExpected );
-
- });
-
-
- it('getParent found with option.filters', function(){
-
- var doc,
- node,
- span,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = HTML;
- doc.body.appendChild(node);
- span = doc.querySelector('.dt-start');
-
- result = Microformats.getParent( span, {'filters': ['h-event'], 'dateFormat': 'html5'} );
- assert.deepEqual( result, expected );
-
- });
-
-
- it('getParent not found with option.filters', function(){
-
- var doc,
- node,
- span,
- result;
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = HTML;
- doc.body.appendChild(node);
- span = doc.querySelector('.dt-start');
-
- result = Microformats.getParent( span, {'filters': ['h-card'], 'dateFormat': 'html5'} );
- assert.deepEqual( result, emptyExpected );
-
- });
-
-
- it('getParent use option.filters to up through h-*', function(){
-
- var doc,
- node,
- span,
- result;
-
- var altHTML = '<div class="h-entry"><h1 class="p-name">test</h1><div class="e-content">this</div><a class="p-author h-card" href="http://glennjones.net"><span class="p-name">Glenn Jones</span></a><span class="dt-publish">2015-07-01t17:30z</span></div>';
- var altExpected = {
- "items": [
- {
- "type": [
- "h-entry"
- ],
- "properties": {
- "name": [
- "test"
- ],
- "content": [
- {
- "value": "this",
- "html": "this"
- }
- ],
- "author": [
- {
- "value": "Glenn Jones",
- "type": [
- "h-card"
- ],
- "properties": {
- "name": [
- "Glenn Jones"
- ],
- "url": [
- "http://glennjones.net"
- ]
- }
- }
- ],
- "publish": [
- "2015-07-01 17:30Z"
- ]
- }
- }
- ],
- "rels": {},
- "rel-urls": {}
- };
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
- span = doc.querySelector('.h-card .p-name');
-
- result = Microformats.getParent( span, {'filters': ['h-entry'], 'dateFormat': 'html5'} );
- assert.deepEqual( result, altExpected );
-
- });
-
-
- it('getParent stop at first h-* parent', function(){
-
- var doc,
- node,
- span,
- result;
-
- var altHTML = '<div class="h-entry"><h1 class="p-name">test</h1><div class="e-content">this</div><a class="p-author h-card" href="http://glennjones.net"><span class="p-name">Glenn Jones</span></a><span class="dt-publish">2015-07-01t17:30z</span></div>';
- var altExpected = {
- "items": [
- {
- "type": [
- "h-card"
- ],
- "properties": {
- "name": [
- "Glenn Jones"
- ],
- "url": [
- "http://glennjones.net"
- ]
- }
- }
- ],
- "rels": {},
- "rel-urls": {}
- };
-
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- node.innerHTML = altHTML;
- doc.body.appendChild(node);
- span = doc.querySelector('.h-card .p-name');
-
- result = Microformats.getParent( span, options );
- assert.deepEqual( result, altExpected );
-
- });
-
-
-});
diff --git a/toolkit/components/microformats/test/interface-tests/hasMicroformats-test.js b/toolkit/components/microformats/test/interface-tests/hasMicroformats-test.js
deleted file mode 100644
index 98c79a855..000000000
--- a/toolkit/components/microformats/test/interface-tests/hasMicroformats-test.js
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
-Unit test for hasMicroformat
-*/
-
-assert = chai.assert;
-
-
-describe('Microformat.hasMicroformats', function() {
-
- it('true - v2 on node', function(){
-
- var doc,
- node;
-
- var html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.hasMicroformats( node ) );
-
- });
-
-
- it('true - v1 on node', function(){
-
- var doc,
- node;
-
- var html = '<a class="vcard" href="http://glennjones.net"><span class="fn">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.hasMicroformats( node ) );
-
- });
-
-
- it('true - v2 filter on node', function(){
-
- var doc,
- node;
-
- var html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.hasMicroformats( node, {'filters': ['h-card']} ) );
-
- });
-
-
- it('true - v1 filter on node', function(){
-
- var doc,
- node;
-
- var html = '<a class="vcard" href="http://glennjones.net"><span class="fn">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.hasMicroformats( node, {'filters': ['h-card']} ) );
-
- });
-
-
- it('false - v2 filter on node', function(){
-
- var doc,
- node;
-
- var html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isFalse( Microformats.hasMicroformats( node, {'filters': ['h-entry']} ) );
-
- });
-
-
-
- it('false - property', function(){
-
- var doc,
- node,
- parser;
-
- var html = '<span class="p-name">Glenn</span>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'span' );
-
- assert.isFalse( Microformats.hasMicroformats( node ) );
-
- });
-
-
- it('false - no class', function(){
-
- var doc,
- node,
- parser;
-
- var html = '<span>Glenn</span>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'span' );
-
- assert.isFalse( Microformats.hasMicroformats( node ) );
-
- });
-
-
- it('false - no node', function(){
- assert.isFalse( Microformats.hasMicroformats( ) );
- });
-
-
- it('false - undefined node', function(){
- assert.isFalse( Microformats.hasMicroformats( undefined ) );
- });
-
-
- it('true - child', function(){
-
- var doc,
- node;
-
- var html = '<section><div><a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a></div></section>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
-
- assert.isTrue( Microformats.hasMicroformats( node ) );
-
- });
-
-
-
- it('true - document', function(){
-
- var doc,
- node;
-
- var html = '<html><head></head><body><section><div><a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a></div></section></body></html>';
-
- var dom = new DOMParser();
- doc = dom.parseFromString( html, 'text/html' );
-
- assert.isTrue( Microformats.hasMicroformats( doc ) );
-
- });
-
-
-
-
-
- });
diff --git a/toolkit/components/microformats/test/interface-tests/index.html b/toolkit/components/microformats/test/interface-tests/index.html
deleted file mode 100644
index 61759790e..000000000
--- a/toolkit/components/microformats/test/interface-tests/index.html
+++ /dev/null
@@ -1,69 +0,0 @@
-<html><head><title>Mocha</title>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<link rel="stylesheet" href="../static/css/mocha.css" />
-<script src="../static/javascript/chai.js"></script>
-<script src="../static/javascript/mocha.js"></script>
-<link rel="stylesheet" href="../static/css/mocha-custom.css" />
-<link rel="icon" type="image/png" id="favicon" href="chrome://branding/content/icon32.png"/>
-
-<script src="../static/javascript/DOMParser.js"></script>
-
-<script data-cover src="../../microformat-shiv.js"></script>
-
-<script>
-var uncaughtError;
-
-window.addEventListener("error", function(error) {
-uncaughtError = error;
-});
-
-var consoleWarn = console.warn;
-var caughtWarnings = [];
-
-console.warn = function() {
-var args = Array.slice(arguments);
-caughtWarnings.push(args);
-consoleWarn.apply(console, args);
-};
-</script>
-
-<script>
-chai.config.includeStack = true;
-mocha.setup({ui: 'bdd', timeout: 10000});
-</script>
-
-
-<script src="../interface-tests/get-test.js"></script>
-<script src="../interface-tests/getParent-test.js"></script>
-<script src="../interface-tests/count-test.js"></script>
-<script src="../interface-tests/isMicroformat-test.js"></script>
-<script src="../interface-tests/hasMicroformats-test.js"></script>
-
-<script src="../interface-tests/experimental-test.js"></script>
-
-</head><body>
-<h3 class="capitalize">Microformats-shiv: interface tests</h3>
-<div id="mocha"></div>
-</body>
-<script>
-describe("Uncaught Error Check", function() {
-it("should load the tests without errors", function() {
-chai.expect(uncaughtError && uncaughtError.message).to.be.undefined;
-});
-});
-
-describe("Unexpected Warnings Check", function() {
-it("should long only the warnings we expect", function() {
-chai.expect(caughtWarnings.length).to.eql(0);
-});
-});
-
-mocha.run(function () {
-var completeNode = document.createElement("p");
-completeNode.setAttribute("id", "complete");
-completeNode.appendChild(document.createTextNode("Complete"));
-document.getElementById("mocha").appendChild(completeNode);
-});
-
-</script>
-</body></html>
diff --git a/toolkit/components/microformats/test/interface-tests/isMicroformat-test.js b/toolkit/components/microformats/test/interface-tests/isMicroformat-test.js
deleted file mode 100644
index 7081b2880..000000000
--- a/toolkit/components/microformats/test/interface-tests/isMicroformat-test.js
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
-Unit test for isMicroformat
-*/
-
-assert = chai.assert;
-
-
-describe('Microformat.isMicroformat', function() {
-
- it('true - v2', function(){
-
- var doc,
- node;
-
- var html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.isMicroformat( node ) );
-
- });
-
-
- it('true - v1', function(){
-
- var doc,
- node;
-
- var html = '<a class="vcard" href="http://glennjones.net"><span class="fn">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.isMicroformat( node ) );
-
- });
-
-
- it('true - v2 filter', function(){
-
- var doc,
- node;
-
- var html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.isMicroformat( node, {'filters': ['h-card']} ) );
-
- });
-
-
- it('true - v1 filter', function(){
-
- var doc,
- node;
-
- var html = '<a class="vcard" href="http://glennjones.net"><span class="fn">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isTrue( Microformats.isMicroformat( node, {'filters': ['h-card']} ) );
-
- });
-
-
- it('false - v2 filter', function(){
-
- var doc,
- node;
-
- var html = '<a class="h-card" href="http://glennjones.net"><span class="p-name">Glenn</span></a>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'a' );
-
- assert.isFalse( Microformats.isMicroformat( node, {'filters': ['h-entry']} ) );
-
- });
-
-
-
- it('false - property', function(){
-
- var doc,
- node;
-
- var html = '<span class="p-name">Glenn</span>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'span' );
-
- assert.isFalse( Microformats.isMicroformat( node ) );
-
- });
-
-
- it('false - no class', function(){
-
- var doc,
- node;
-
- var html = '<span>Glenn</span>';
-
- doc = document.implementation.createHTMLDocument('New Document');
- node = document.createElement('div');
- doc.body.appendChild( node );
- node.innerHTML = html;
- node = doc.querySelector( 'span' );
-
- assert.isFalse( Microformats.isMicroformat( node ) );
-
- });
-
-
- it('false - no node', function(){
- assert.isFalse( Microformats.isMicroformat( ) );
- });
-
-
- it('false - undefined node', function(){
- assert.isFalse( Microformats.isMicroformat( undefined ) );
- });
-
- });
diff --git a/toolkit/components/microformats/test/lib/dates.js b/toolkit/components/microformats/test/lib/dates.js
deleted file mode 100644
index 6d6129b08..000000000
--- a/toolkit/components/microformats/test/lib/dates.js
+++ /dev/null
@@ -1,268 +0,0 @@
-/*!
- dates
- These functions are based on microformats implied rules for parsing date fragments from text.
- They are not generalist date utilities and should only be used with the isodate.js module of this library.
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- Dependencies utilities.js, isodate.js
-*/
-
-
-var Modules = (function (modules) {
-
- modules.dates = {
-
-
- /**
- * does text contain am
- *
- * @param {String} text
- * @return {Boolean}
- */
- hasAM: function( text ) {
- text = text.toLowerCase();
- return(text.indexOf('am') > -1 || text.indexOf('a.m.') > -1);
- },
-
-
- /**
- * does text contain pm
- *
- * @param {String} text
- * @return {Boolean}
- */
- hasPM: function( text ) {
- text = text.toLowerCase();
- return(text.indexOf('pm') > -1 || text.indexOf('p.m.') > -1);
- },
-
-
- /**
- * remove am and pm from text and return it
- *
- * @param {String} text
- * @return {String}
- */
- removeAMPM: function( text ) {
- return text.replace('pm', '').replace('p.m.', '').replace('am', '').replace('a.m.', '');
- },
-
-
- /**
- * simple test of whether ISO date string is a duration i.e. PY17M or PW12
- *
- * @param {String} text
- * @return {Boolean}
- */
- isDuration: function( text ) {
- if(modules.utils.isString( text )){
- text = text.toLowerCase();
- if(modules.utils.startWith(text, 'p') ){
- return true;
- }
- }
- return false;
- },
-
-
- /**
- * is text a time or timezone
- * i.e. HH-MM-SS or z+-HH-MM-SS 08:43 | 15:23:00:0567 | 10:34pm | 10:34 p.m. | +01:00:00 | -02:00 | z15:00 | 0843
- *
- * @param {String} text
- * @return {Boolean}
- */
- isTime: function( text ) {
- if(modules.utils.isString(text)){
- text = text.toLowerCase();
- text = modules.utils.trim( text );
- // start with timezone char
- if( text.match(':') && ( modules.utils.startWith(text, 'z') || modules.utils.startWith(text, '-') || modules.utils.startWith(text, '+') )) {
- return true;
- }
- // has ante meridiem or post meridiem
- if( text.match(/^[0-9]/) &&
- ( this.hasAM(text) || this.hasPM(text) )) {
- return true;
- }
- // contains time delimiter but not datetime delimiter
- if( text.match(':') && !text.match(/t|\s/) ) {
- return true;
- }
-
- // if it's a number of 2, 4 or 6 chars
- if(modules.utils.isNumber(text)){
- if(text.length === 2 || text.length === 4 || text.length === 6){
- return true;
- }
- }
- }
- return false;
- },
-
-
- /**
- * parses a time from text and returns 24hr time string
- * i.e. 5:34am = 05:34:00 and 1:52:04p.m. = 13:52:04
- *
- * @param {String} text
- * @return {String}
- */
- parseAmPmTime: function( text ) {
- var out = text,
- times = [];
-
- // if the string has a text : or am or pm
- if(modules.utils.isString(out)) {
- //text = text.toLowerCase();
- text = text.replace(/[ ]+/g, '');
-
- if(text.match(':') || this.hasAM(text) || this.hasPM(text)) {
-
- if(text.match(':')) {
- times = text.split(':');
- } else {
- // single number text i.e. 5pm
- times[0] = text;
- times[0] = this.removeAMPM(times[0]);
- }
-
- // change pm hours to 24hr number
- if(this.hasPM(text)) {
- if(times[0] < 12) {
- times[0] = parseInt(times[0], 10) + 12;
- }
- }
-
- // add leading zero's where needed
- if(times[0] && times[0].length === 1) {
- times[0] = '0' + times[0];
- }
-
- // rejoin text elements together
- if(times[0]) {
- text = times.join(':');
- }
- }
- }
-
- // remove am/pm strings
- return this.removeAMPM(text);
- },
-
-
- /**
- * overlays a time on a date to return the union of the two
- *
- * @param {String} date
- * @param {String} time
- * @param {String} format ( Modules.ISODate profile format )
- * @return {Object} Modules.ISODate
- */
- dateTimeUnion: function(date, time, format) {
- var isodate = new modules.ISODate(date, format),
- isotime = new modules.ISODate();
-
- isotime.parseTime(this.parseAmPmTime(time), format);
- if(isodate.hasFullDate() && isotime.hasTime()) {
- isodate.tH = isotime.tH;
- isodate.tM = isotime.tM;
- isodate.tS = isotime.tS;
- isodate.tD = isotime.tD;
- return isodate;
- } else {
- if(isodate.hasFullDate()){
- return isodate;
- }
- return new modules.ISODate();
- }
- },
-
-
- /**
- * concatenate an array of date and time text fragments to create an ISODate object
- * used for microformat value and value-title rules
- *
- * @param {Array} arr ( Array of Strings )
- * @param {String} format ( Modules.ISODate profile format )
- * @return {Object} Modules.ISODate
- */
- concatFragments: function (arr, format) {
- var out = new modules.ISODate(),
- i = 0,
- value = '';
-
- // if the fragment already contains a full date just return it once
- if(arr[0].toUpperCase().match('T')) {
- return new modules.ISODate(arr[0], format);
- }else{
- for(i = 0; i < arr.length; i++) {
- value = arr[i];
-
- // date pattern
- if( value.charAt(4) === '-' && out.hasFullDate() === false ){
- out.parseDate(value);
- }
-
- // time pattern
- if( (value.indexOf(':') > -1 || modules.utils.isNumber( this.parseAmPmTime(value) )) && out.hasTime() === false ) {
- // split time and timezone
- var items = this.splitTimeAndZone(value);
- value = items[0];
-
- // parse any use of am/pm
- value = this.parseAmPmTime(value);
- out.parseTime(value);
-
- // parse any timezone
- if(items.length > 1){
- out.parseTimeZone(items[1], format);
- }
- }
-
- // timezone pattern
- if(value.charAt(0) === '-' || value.charAt(0) === '+' || value.toUpperCase() === 'Z') {
- if( out.hasTimeZone() === false ){
- out.parseTimeZone(value);
- }
- }
-
- }
- return out;
-
- }
- },
-
-
- /**
- * parses text by splitting it into an array of time and timezone strings
- *
- * @param {String} text
- * @return {Array} Modules.ISODate
- */
- splitTimeAndZone: function ( text ){
- var out = [text],
- chars = ['-','+','z','Z'],
- i = chars.length;
-
- while (i--) {
- if(text.indexOf(chars[i]) > -1){
- out[0] = text.slice( 0, text.indexOf(chars[i]) );
- out.push( text.slice( text.indexOf(chars[i]) ) );
- break;
- }
- }
- return out;
- }
-
- };
-
-
- return modules;
-
-} (Modules || {}));
-
-
-
-
diff --git a/toolkit/components/microformats/test/lib/domparser.js b/toolkit/components/microformats/test/lib/domparser.js
deleted file mode 100644
index bc342634a..000000000
--- a/toolkit/components/microformats/test/lib/domparser.js
+++ /dev/null
@@ -1,103 +0,0 @@
-
-// Based on https://gist.github.com/1129031 By Eli Grey, http://eligrey.com - Public domain.
-
-// DO NOT use https://developer.mozilla.org/en-US/docs/Web/API/DOMParser example polyfill
-// as it does not work with earlier versions of Chrome
-
-
-(function(DOMParser) {
- 'use strict';
-
- var DOMParser_proto;
- var real_parseFromString;
- var textHTML; // Flag for text/html support
- var textXML; // Flag for text/xml support
- var htmlElInnerHTML; // Flag for support for setting html element's innerHTML
-
- // Stop here if DOMParser not defined
- if (!DOMParser) {
- return;
- }
-
- // Firefox, Opera and IE throw errors on unsupported types
- try {
- // WebKit returns null on unsupported types
- textHTML = !!(new DOMParser()).parseFromString('', 'text/html');
-
- } catch (er) {
- textHTML = false;
- }
-
- // If text/html supported, don't need to do anything.
- if (textHTML) {
- return;
- }
-
- // Next try setting innerHTML of a created document
- // IE 9 and lower will throw an error (can't set innerHTML of its HTML element)
- try {
- var doc = document.implementation.createHTMLDocument('');
- doc.documentElement.innerHTML = '<title></title><div></div>';
- htmlElInnerHTML = true;
-
- } catch (er) {
- htmlElInnerHTML = false;
- }
-
- // If if that failed, try text/xml
- if (!htmlElInnerHTML) {
-
- try {
- textXML = !!(new DOMParser()).parseFromString('', 'text/xml');
-
- } catch (er) {
- textHTML = false;
- }
- }
-
- // Mess with DOMParser.prototype (less than optimal...) if one of the above worked
- // Assume can write to the prototype, if not, make this a stand alone function
- if (DOMParser.prototype && (htmlElInnerHTML || textXML)) {
- DOMParser_proto = DOMParser.prototype;
- real_parseFromString = DOMParser_proto.parseFromString;
-
- DOMParser_proto.parseFromString = function (markup, type) {
-
- // Only do this if type is text/html
- if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
- var doc, doc_el, first_el;
-
- // Use innerHTML if supported
- if (htmlElInnerHTML) {
- doc = document.implementation.createHTMLDocument('');
- doc_el = doc.documentElement;
- doc_el.innerHTML = markup;
- first_el = doc_el.firstElementChild;
-
- // Otherwise use XML method
- } else if (textXML) {
-
- // Make sure markup is wrapped in HTML tags
- // Should probably allow for a DOCTYPE
- if (!(/^<html.*html>$/i.test(markup))) {
- markup = '<html>' + markup + '<\/html>';
- }
- doc = (new DOMParser()).parseFromString(markup, 'text/xml');
- doc_el = doc.documentElement;
- first_el = doc_el.firstElementChild;
- }
-
- // Is this an entire document or a fragment?
- if (doc_el.childElementCount === 1 && first_el.localName.toLowerCase() === 'html') {
- doc.replaceChild(first_el, doc_el);
- }
-
- return doc;
-
- // If not text/html, send as-is to host method
- } else {
- return real_parseFromString.apply(this, arguments);
- }
- };
- }
-}(DOMParser));
diff --git a/toolkit/components/microformats/test/lib/domutils.js b/toolkit/components/microformats/test/lib/domutils.js
deleted file mode 100644
index 57269de97..000000000
--- a/toolkit/components/microformats/test/lib/domutils.js
+++ /dev/null
@@ -1,611 +0,0 @@
-/*
- dom utilities
- The purpose of this module is to abstract DOM functions away from the main parsing modules of the library.
- It was created so the file can be replaced in node.js environment to make use of different types of light weight node.js DOM's
- such as 'cherrio.js'. It also contains a number of DOM utilities which are used throughout the parser such as: 'getDescendant'
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- Dependencies utilities.js
-
-*/
-
-
-var Modules = (function (modules) {
-
- modules.domUtils = {
-
- // blank objects for DOM
- document: null,
- rootNode: null,
-
-
- /**
- * gets DOMParser object
- *
- * @return {Object || undefined}
- */
- getDOMParser: function () {
- if (typeof DOMParser === undefined) {
- try {
- return Components.classes["@mozilla.org/xmlextras/domparser;1"]
- .createInstance(Components.interfaces.nsIDOMParser);
- } catch (e) {
- return undefined;
- }
- } else {
- return new DOMParser();
- }
- },
-
-
- /**
- * configures what are the base DOM objects for parsing
- *
- * @param {Object} options
- * @return {DOM Node} node
- */
- getDOMContext: function( options ){
-
- // if a node is passed
- if(options.node){
- this.rootNode = options.node;
- }
-
-
- // if a html string is passed
- if(options.html){
- //var domParser = new DOMParser();
- var domParser = this.getDOMParser();
- this.rootNode = domParser.parseFromString( options.html, 'text/html' );
- }
-
-
- // find top level document from rootnode
- if(this.rootNode !== null){
- if(this.rootNode.nodeType === 9){
- this.document = this.rootNode;
- this.rootNode = modules.domUtils.querySelector(this.rootNode, 'html');
- }else{
- // if it's DOM node get parent DOM Document
- this.document = modules.domUtils.ownerDocument(this.rootNode);
- }
- }
-
-
- // use global document object
- if(!this.rootNode && document){
- this.rootNode = modules.domUtils.querySelector(document, 'html');
- this.document = document;
- }
-
-
- if(this.rootNode && this.document){
- return {document: this.document, rootNode: this.rootNode};
- }
-
- return {document: null, rootNode: null};
- },
-
-
-
- /**
- * gets the first DOM node
- *
- * @param {Dom Document}
- * @return {DOM Node} node
- */
- getTopMostNode: function( node ){
- //var doc = this.ownerDocument(node);
- //if(doc && doc.nodeType && doc.nodeType === 9 && doc.documentElement){
- // return doc.documentElement;
- //}
- return node;
- },
-
-
-
- /**
- * abstracts DOM ownerDocument
- *
- * @param {DOM Node} node
- * @return {Dom Document}
- */
- ownerDocument: function(node){
- return node.ownerDocument;
- },
-
-
- /**
- * abstracts DOM textContent
- *
- * @param {DOM Node} node
- * @return {String}
- */
- textContent: function(node){
- if(node.textContent){
- return node.textContent;
- }else if(node.innerText){
- return node.innerText;
- }
- return '';
- },
-
-
- /**
- * abstracts DOM innerHTML
- *
- * @param {DOM Node} node
- * @return {String}
- */
- innerHTML: function(node){
- return node.innerHTML;
- },
-
-
- /**
- * abstracts DOM hasAttribute
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- * @return {Boolean}
- */
- hasAttribute: function(node, attributeName) {
- return node.hasAttribute(attributeName);
- },
-
-
- /**
- * does an attribute contain a value
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- * @param {String} value
- * @return {Boolean}
- */
- hasAttributeValue: function(node, attributeName, value) {
- return (this.getAttributeList(node, attributeName).indexOf(value) > -1);
- },
-
-
- /**
- * abstracts DOM getAttribute
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- * @return {String || null}
- */
- getAttribute: function(node, attributeName) {
- return node.getAttribute(attributeName);
- },
-
-
- /**
- * abstracts DOM setAttribute
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- * @param {String} attributeValue
- */
- setAttribute: function(node, attributeName, attributeValue){
- node.setAttribute(attributeName, attributeValue);
- },
-
-
- /**
- * abstracts DOM removeAttribute
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- */
- removeAttribute: function(node, attributeName) {
- node.removeAttribute(attributeName);
- },
-
-
- /**
- * abstracts DOM getElementById
- *
- * @param {DOM Node || DOM Document} node
- * @param {String} id
- * @return {DOM Node}
- */
- getElementById: function(docNode, id) {
- return docNode.querySelector( '#' + id );
- },
-
-
- /**
- * abstracts DOM querySelector
- *
- * @param {DOM Node || DOM Document} node
- * @param {String} selector
- * @return {DOM Node}
- */
- querySelector: function(docNode, selector) {
- return docNode.querySelector( selector );
- },
-
-
- /**
- * get value of a Node attribute as an array
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- * @return {Array}
- */
- getAttributeList: function(node, attributeName) {
- var out = [],
- attList;
-
- attList = node.getAttribute(attributeName);
- if(attList && attList !== '') {
- if(attList.indexOf(' ') > -1) {
- out = attList.split(' ');
- } else {
- out.push(attList);
- }
- }
- return out;
- },
-
-
- /**
- * gets all child nodes with a given attribute
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- * @return {NodeList}
- */
- getNodesByAttribute: function(node, attributeName) {
- var selector = '[' + attributeName + ']';
- return node.querySelectorAll(selector);
- },
-
-
- /**
- * gets all child nodes with a given attribute containing a given value
- *
- * @param {DOM Node} node
- * @param {String} attributeName
- * @return {DOM NodeList}
- */
- getNodesByAttributeValue: function(rootNode, name, value) {
- var arr = [],
- x = 0,
- i,
- out = [];
-
- arr = this.getNodesByAttribute(rootNode, name);
- if(arr) {
- i = arr.length;
- while(x < i) {
- if(this.hasAttributeValue(arr[x], name, value)) {
- out.push(arr[x]);
- }
- x++;
- }
- }
- return out;
- },
-
-
- /**
- * gets attribute value from controlled list of tags
- *
- * @param {Array} tagNames
- * @param {String} attributeName
- * @return {String || null}
- */
- getAttrValFromTagList: function(node, tagNames, attributeName) {
- var i = tagNames.length;
-
- while(i--) {
- if(node.tagName.toLowerCase() === tagNames[i]) {
- var attrValue = this.getAttribute(node, attributeName);
- if(attrValue && attrValue !== '') {
- return attrValue;
- }
- }
- }
- return null;
- },
-
-
- /**
- * get node if it has no siblings. CSS equivalent is :only-child
- *
- * @param {DOM Node} rootNode
- * @param {Array} tagNames
- * @return {DOM Node || null}
- */
- getSingleDescendant: function(node){
- return this.getDescendant( node, null, false );
- },
-
-
- /**
- * get node if it has no siblings of the same type. CSS equivalent is :only-of-type
- *
- * @param {DOM Node} rootNode
- * @param {Array} tagNames
- * @return {DOM Node || null}
- */
- getSingleDescendantOfType: function(node, tagNames){
- return this.getDescendant( node, tagNames, true );
- },
-
-
- /**
- * get child node limited by presence of siblings - either CSS :only-of-type or :only-child
- *
- * @param {DOM Node} rootNode
- * @param {Array} tagNames
- * @return {DOM Node || null}
- */
- getDescendant: function( node, tagNames, onlyOfType ){
- var i = node.children.length,
- countAll = 0,
- countOfType = 0,
- child,
- out = null;
-
- while(i--) {
- child = node.children[i];
- if(child.nodeType === 1) {
- if(tagNames){
- // count just only-of-type
- if(this.hasTagName(child, tagNames)){
- out = child;
- countOfType++;
- }
- }else{
- // count all elements
- out = child;
- countAll++;
- }
- }
- }
- if(onlyOfType === true){
- return (countOfType === 1)? out : null;
- }else{
- return (countAll === 1)? out : null;
- }
- },
-
-
- /**
- * is a node one of a list of tags
- *
- * @param {DOM Node} rootNode
- * @param {Array} tagNames
- * @return {Boolean}
- */
- hasTagName: function(node, tagNames){
- var i = tagNames.length;
- while(i--) {
- if(node.tagName.toLowerCase() === tagNames[i]) {
- return true;
- }
- }
- return false;
- },
-
-
- /**
- * abstracts DOM appendChild
- *
- * @param {DOM Node} node
- * @param {DOM Node} childNode
- * @return {DOM Node}
- */
- appendChild: function(node, childNode){
- return node.appendChild(childNode);
- },
-
-
- /**
- * abstracts DOM removeChild
- *
- * @param {DOM Node} childNode
- * @return {DOM Node || null}
- */
- removeChild: function(childNode){
- if (childNode.parentNode) {
- return childNode.parentNode.removeChild(childNode);
- }else{
- return null;
- }
- },
-
-
- /**
- * abstracts DOM cloneNode
- *
- * @param {DOM Node} node
- * @return {DOM Node}
- */
- clone: function(node) {
- var newNode = node.cloneNode(true);
- newNode.removeAttribute('id');
- return newNode;
- },
-
-
- /**
- * gets the text of a node
- *
- * @param {DOM Node} node
- * @return {String}
- */
- getElementText: function( node ){
- if(node && node.data){
- return node.data;
- }else{
- return '';
- }
- },
-
-
- /**
- * gets the attributes of a node - ordered by sequence in html
- *
- * @param {DOM Node} node
- * @return {Array}
- */
- getOrderedAttributes: function( node ){
- var nodeStr = node.outerHTML,
- attrs = [];
-
- for (var i = 0; i < node.attributes.length; i++) {
- var attr = node.attributes[i];
- attr.indexNum = nodeStr.indexOf(attr.name);
-
- attrs.push( attr );
- }
- return attrs.sort( modules.utils.sortObjects( 'indexNum' ) );
- },
-
-
- /**
- * decodes html entities in given text
- *
- * @param {DOM Document} doc
- * @param String} text
- * @return {String}
- */
- decodeEntities: function( doc, text ){
- //return text;
- return doc.createTextNode( text ).nodeValue;
- },
-
-
- /**
- * clones a DOM document
- *
- * @param {DOM Document} document
- * @return {DOM Document}
- */
- cloneDocument: function( document ){
- var newNode,
- newDocument = null;
-
- if( this.canCloneDocument( document )){
- newDocument = document.implementation.createHTMLDocument('');
- newNode = newDocument.importNode( document.documentElement, true );
- newDocument.replaceChild(newNode, newDocument.querySelector('html'));
- }
- return (newNode && newNode.nodeType && newNode.nodeType === 1)? newDocument : document;
- },
-
-
- /**
- * can environment clone a DOM document
- *
- * @param {DOM Document} document
- * @return {Boolean}
- */
- canCloneDocument: function( document ){
- return (document && document.importNode && document.implementation && document.implementation.createHTMLDocument);
- },
-
-
- /**
- * get the child index of a node. Used to create a node path
- *
- * @param {DOM Node} node
- * @return {Int}
- */
- getChildIndex: function (node) {
- var parent = node.parentNode,
- i = -1,
- child;
- while (parent && (child = parent.childNodes[++i])){
- if (child === node){
- return i;
- }
- }
- return -1;
- },
-
-
- /**
- * get a node's path
- *
- * @param {DOM Node} node
- * @return {Array}
- */
- getNodePath: function (node) {
- var parent = node.parentNode,
- path = [],
- index = this.getChildIndex(node);
-
- if(parent && (path = this.getNodePath(parent))){
- if(index > -1){
- path.push(index);
- }
- }
- return path;
- },
-
-
- /**
- * get a node from a path.
- *
- * @param {DOM document} document
- * @param {Array} path
- * @return {DOM Node}
- */
- getNodeByPath: function (document, path) {
- var node = document.documentElement,
- i = 0,
- index;
- while ((index = path[++i]) > -1){
- node = node.childNodes[index];
- }
- return node;
- },
-
-
- /**
- * get an array/nodeList of child nodes
- *
- * @param {DOM node} node
- * @return {Array}
- */
- getChildren: function( node ){
- return node.children;
- },
-
-
- /**
- * create a node
- *
- * @param {String} tagName
- * @return {DOM node}
- */
- createNode: function( tagName ){
- return this.document.createElement(tagName);
- },
-
-
- /**
- * create a node with text content
- *
- * @param {String} tagName
- * @param {String} text
- * @return {DOM node}
- */
- createNodeWithText: function( tagName, text ){
- var node = this.document.createElement(tagName);
- node.innerHTML = text;
- return node;
- }
-
-
-
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/html.js b/toolkit/components/microformats/test/lib/html.js
deleted file mode 100644
index ab150d91e..000000000
--- a/toolkit/components/microformats/test/lib/html.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- html
- Extracts a HTML string from DOM nodes. Was created to get around the issue of not being able to exclude the content
- of nodes with the 'data-include' attribute. DO NOT replace with functions such as innerHTML as it will break a
- number of microformat include patterns.
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-node/master/license.txt
- Dependencies utilities.js, domutils.js
-*/
-
-
-var Modules = (function (modules) {
-
- modules.html = {
-
- // elements which are self-closing
- selfClosingElt: ['area', 'base', 'br', 'col', 'hr', 'img', 'input', 'link', 'meta', 'param', 'command', 'keygen', 'source'],
-
-
- /**
- * parse the html string from DOM Node
- *
- * @param {DOM Node} node
- * @return {String}
- */
- parse: function( node ){
- var out = '',
- j = 0;
-
- // we do not want the outer container
- if(node.childNodes && node.childNodes.length > 0){
- for (j = 0; j < node.childNodes.length; j++) {
- var text = this.walkTreeForHtml( node.childNodes[j] );
- if(text !== undefined){
- out += text;
- }
- }
- }
-
- return out;
- },
-
-
- /**
- * walks the DOM tree parsing the html string from the nodes
- *
- * @param {DOM Document} doc
- * @param {DOM Node} node
- * @return {String}
- */
- walkTreeForHtml: function( node ) {
- var out = '',
- j = 0;
-
- // if node is a text node get its text
- if(node.nodeType && node.nodeType === 3){
- out += modules.domUtils.getElementText( node );
- }
-
-
- // exclude text which has been added with include pattern -
- if(node.nodeType && node.nodeType === 1 && modules.domUtils.hasAttribute(node, 'data-include') === false){
-
- // begin tag
- out += '<' + node.tagName.toLowerCase();
-
- // add attributes
- var attrs = modules.domUtils.getOrderedAttributes(node);
- for (j = 0; j < attrs.length; j++) {
- out += ' ' + attrs[j].name + '=' + '"' + attrs[j].value + '"';
- }
-
- if(this.selfClosingElt.indexOf(node.tagName.toLowerCase()) === -1){
- out += '>';
- }
-
- // get the text of the child nodes
- if(node.childNodes && node.childNodes.length > 0){
-
- for (j = 0; j < node.childNodes.length; j++) {
- var text = this.walkTreeForHtml( node.childNodes[j] );
- if(text !== undefined){
- out += text;
- }
- }
- }
-
- // end tag
- if(this.selfClosingElt.indexOf(node.tagName.toLowerCase()) > -1){
- out += ' />';
- }else{
- out += '</' + node.tagName.toLowerCase() + '>';
- }
- }
-
- return (out === '')? undefined : out;
- }
-
-
- };
-
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/isodate.js b/toolkit/components/microformats/test/lib/isodate.js
deleted file mode 100644
index 30f35f35d..000000000
--- a/toolkit/components/microformats/test/lib/isodate.js
+++ /dev/null
@@ -1,481 +0,0 @@
-/*!
- iso date
- This module was built for the exact needs of parsing ISO dates to the microformats standard.
-
- * Parses and builds ISO dates to the W3C note, HTML5 or RFC3339 profiles.
- * Also allows for profile detection using 'auto'
- * Outputs to the same level of specificity of date and time that was input
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- */
-
-
-
-var Modules = (function (modules) {
-
-
- /**
- * constructor
- * parses text to find just the date element of an ISO date/time string i.e. 2008-05-01
- *
- * @param {String} dateString
- * @param {String} format
- * @return {String}
- */
- modules.ISODate = function ( dateString, format ) {
- this.clear();
-
- this.format = (format)? format : 'auto'; // auto or W3C or RFC3339 or HTML5
- this.setFormatSep();
-
- // optional should be full iso date/time string
- if(arguments[0]) {
- this.parse(dateString, format);
- }
- };
-
-
- modules.ISODate.prototype = {
-
-
- /**
- * clear all states
- *
- */
- clear: function(){
- this.clearDate();
- this.clearTime();
- this.clearTimeZone();
- this.setAutoProfileState();
- },
-
-
- /**
- * clear date states
- *
- */
- clearDate: function(){
- this.dY = -1;
- this.dM = -1;
- this.dD = -1;
- this.dDDD = -1;
- },
-
-
- /**
- * clear time states
- *
- */
- clearTime: function(){
- this.tH = -1;
- this.tM = -1;
- this.tS = -1;
- this.tD = -1;
- },
-
-
- /**
- * clear timezone states
- *
- */
- clearTimeZone: function(){
- this.tzH = -1;
- this.tzM = -1;
- this.tzPN = '+';
- this.z = false;
- },
-
-
- /**
- * resets the auto profile state
- *
- */
- setAutoProfileState: function(){
- this.autoProfile = {
- sep: 'T',
- dsep: '-',
- tsep: ':',
- tzsep: ':',
- tzZulu: 'Z'
- };
- },
-
-
- /**
- * parses text to find ISO date/time string i.e. 2008-05-01T15:45:19Z
- *
- * @param {String} dateString
- * @param {String} format
- * @return {String}
- */
- parse: function( dateString, format ) {
- this.clear();
-
- var parts = [],
- tzArray = [],
- position = 0,
- datePart = '',
- timePart = '',
- timeZonePart = '';
-
- if(format){
- this.format = format;
- }
-
-
-
- // discover date time separtor for auto profile
- // Set to 'T' by default
- if(dateString.indexOf('t') > -1) {
- this.autoProfile.sep = 't';
- }
- if(dateString.indexOf('z') > -1) {
- this.autoProfile.tzZulu = 'z';
- }
- if(dateString.indexOf('Z') > -1) {
- this.autoProfile.tzZulu = 'Z';
- }
- if(dateString.toUpperCase().indexOf('T') === -1) {
- this.autoProfile.sep = ' ';
- }
-
-
- dateString = dateString.toUpperCase().replace(' ','T');
-
- // break on 'T' divider or space
- if(dateString.indexOf('T') > -1) {
- parts = dateString.split('T');
- datePart = parts[0];
- timePart = parts[1];
-
- // zulu UTC
- if(timePart.indexOf( 'Z' ) > -1) {
- this.z = true;
- }
-
- // timezone
- if(timePart.indexOf( '+' ) > -1 || timePart.indexOf( '-' ) > -1) {
- tzArray = timePart.split( 'Z' ); // incase of incorrect use of Z
- timePart = tzArray[0];
- timeZonePart = tzArray[1];
-
- // timezone
- if(timePart.indexOf( '+' ) > -1 || timePart.indexOf( '-' ) > -1) {
- position = 0;
-
- if(timePart.indexOf( '+' ) > -1) {
- position = timePart.indexOf( '+' );
- } else {
- position = timePart.indexOf( '-' );
- }
-
- timeZonePart = timePart.substring( position, timePart.length );
- timePart = timePart.substring( 0, position );
- }
- }
-
- } else {
- datePart = dateString;
- }
-
- if(datePart !== '') {
- this.parseDate( datePart );
- if(timePart !== '') {
- this.parseTime( timePart );
- if(timeZonePart !== '') {
- this.parseTimeZone( timeZonePart );
- }
- }
- }
- return this.toString( format );
- },
-
-
- /**
- * parses text to find just the date element of an ISO date/time string i.e. 2008-05-01
- *
- * @param {String} dateString
- * @param {String} format
- * @return {String}
- */
- parseDate: function( dateString, format ) {
- this.clearDate();
-
- var parts = [];
-
- // discover timezone separtor for auto profile // default is ':'
- if(dateString.indexOf('-') === -1) {
- this.autoProfile.tsep = '';
- }
-
- // YYYY-DDD
- parts = dateString.match( /(\d\d\d\d)-(\d\d\d)/ );
- if(parts) {
- if(parts[1]) {
- this.dY = parts[1];
- }
- if(parts[2]) {
- this.dDDD = parts[2];
- }
- }
-
- if(this.dDDD === -1) {
- // YYYY-MM-DD ie 2008-05-01 and YYYYMMDD ie 20080501
- parts = dateString.match( /(\d\d\d\d)?-?(\d\d)?-?(\d\d)?/ );
- if(parts[1]) {
- this.dY = parts[1];
- }
- if(parts[2]) {
- this.dM = parts[2];
- }
- if(parts[3]) {
- this.dD = parts[3];
- }
- }
- return this.toString(format);
- },
-
-
- /**
- * parses text to find just the time element of an ISO date/time string i.e. 13:30:45
- *
- * @param {String} timeString
- * @param {String} format
- * @return {String}
- */
- parseTime: function( timeString, format ) {
- this.clearTime();
- var parts = [];
-
- // discover date separtor for auto profile // default is ':'
- if(timeString.indexOf(':') === -1) {
- this.autoProfile.tsep = '';
- }
-
- // finds timezone HH:MM:SS and HHMMSS ie 13:30:45, 133045 and 13:30:45.0135
- parts = timeString.match( /(\d\d)?:?(\d\d)?:?(\d\d)?.?([0-9]+)?/ );
- if(parts[1]) {
- this.tH = parts[1];
- }
- if(parts[2]) {
- this.tM = parts[2];
- }
- if(parts[3]) {
- this.tS = parts[3];
- }
- if(parts[4]) {
- this.tD = parts[4];
- }
- return this.toTimeString(format);
- },
-
-
- /**
- * parses text to find just the time element of an ISO date/time string i.e. +08:00
- *
- * @param {String} timeString
- * @param {String} format
- * @return {String}
- */
- parseTimeZone: function( timeString, format ) {
- this.clearTimeZone();
- var parts = [];
-
- if(timeString.toLowerCase() === 'z'){
- this.z = true;
- // set case for z
- this.autoProfile.tzZulu = (timeString === 'z')? 'z' : 'Z';
- }else{
-
- // discover timezone separtor for auto profile // default is ':'
- if(timeString.indexOf(':') === -1) {
- this.autoProfile.tzsep = '';
- }
-
- // finds timezone +HH:MM and +HHMM ie +13:30 and +1330
- parts = timeString.match( /([\-\+]{1})?(\d\d)?:?(\d\d)?/ );
- if(parts[1]) {
- this.tzPN = parts[1];
- }
- if(parts[2]) {
- this.tzH = parts[2];
- }
- if(parts[3]) {
- this.tzM = parts[3];
- }
-
-
- }
- this.tzZulu = 'z';
- return this.toTimeString( format );
- },
-
-
- /**
- * returns ISO date/time string in W3C Note, RFC 3339, HTML5, or auto profile
- *
- * @param {String} format
- * @return {String}
- */
- toString: function( format ) {
- var output = '';
-
- if(format){
- this.format = format;
- }
- this.setFormatSep();
-
- if(this.dY > -1) {
- output = this.dY;
- if(this.dM > 0 && this.dM < 13) {
- output += this.dsep + this.dM;
- if(this.dD > 0 && this.dD < 32) {
- output += this.dsep + this.dD;
- if(this.tH > -1 && this.tH < 25) {
- output += this.sep + this.toTimeString( format );
- }
- }
- }
- if(this.dDDD > -1) {
- output += this.dsep + this.dDDD;
- }
- } else if(this.tH > -1) {
- output += this.toTimeString( format );
- }
-
- return output;
- },
-
-
- /**
- * returns just the time string element of an ISO date/time
- * in W3C Note, RFC 3339, HTML5, or auto profile
- *
- * @param {String} format
- * @return {String}
- */
- toTimeString: function( format ) {
- var out = '';
-
- if(format){
- this.format = format;
- }
- this.setFormatSep();
-
- // time can only be created with a full date
- if(this.tH) {
- if(this.tH > -1 && this.tH < 25) {
- out += this.tH;
- if(this.tM > -1 && this.tM < 61){
- out += this.tsep + this.tM;
- if(this.tS > -1 && this.tS < 61){
- out += this.tsep + this.tS;
- if(this.tD > -1){
- out += '.' + this.tD;
- }
- }
- }
-
-
-
- // time zone offset
- if(this.z) {
- out += this.tzZulu;
- } else {
- if(this.tzH && this.tzH > -1 && this.tzH < 25) {
- out += this.tzPN + this.tzH;
- if(this.tzM > -1 && this.tzM < 61){
- out += this.tzsep + this.tzM;
- }
- }
- }
- }
- }
- return out;
- },
-
-
- /**
- * set the current profile to W3C Note, RFC 3339, HTML5, or auto profile
- *
- */
- setFormatSep: function() {
- switch( this.format.toLowerCase() ) {
- case 'rfc3339':
- this.sep = 'T';
- this.dsep = '';
- this.tsep = '';
- this.tzsep = '';
- this.tzZulu = 'Z';
- break;
- case 'w3c':
- this.sep = 'T';
- this.dsep = '-';
- this.tsep = ':';
- this.tzsep = ':';
- this.tzZulu = 'Z';
- break;
- case 'html5':
- this.sep = ' ';
- this.dsep = '-';
- this.tsep = ':';
- this.tzsep = ':';
- this.tzZulu = 'Z';
- break;
- default:
- // auto - defined by format of input string
- this.sep = this.autoProfile.sep;
- this.dsep = this.autoProfile.dsep;
- this.tsep = this.autoProfile.tsep;
- this.tzsep = this.autoProfile.tzsep;
- this.tzZulu = this.autoProfile.tzZulu;
- }
- },
-
-
- /**
- * does current data contain a full date i.e. 2015-03-23
- *
- * @return {Boolean}
- */
- hasFullDate: function() {
- return(this.dY !== -1 && this.dM !== -1 && this.dD !== -1);
- },
-
-
- /**
- * does current data contain a minimum date which is just a year number i.e. 2015
- *
- * @return {Boolean}
- */
- hasDate: function() {
- return(this.dY !== -1);
- },
-
-
- /**
- * does current data contain a minimum time which is just a hour number i.e. 13
- *
- * @return {Boolean}
- */
- hasTime: function() {
- return(this.tH !== -1);
- },
-
- /**
- * does current data contain a minimum timezone i.e. -1 || +1 || z
- *
- * @return {Boolean}
- */
- hasTimeZone: function() {
- return(this.tzH !== -1);
- }
-
- };
-
- modules.ISODate.prototype.constructor = modules.ISODate;
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/living-standard.js b/toolkit/components/microformats/test/lib/living-standard.js
deleted file mode 100644
index e2b063573..000000000
--- a/toolkit/components/microformats/test/lib/living-standard.js
+++ /dev/null
@@ -1 +0,0 @@
- modules.livingStandard = '2015-09-25T12:26:04Z';
diff --git a/toolkit/components/microformats/test/lib/maps/h-adr.js b/toolkit/components/microformats/test/lib/maps/h-adr.js
deleted file mode 100644
index aa3a695c5..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-adr.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-adr'] = {
- root: 'adr',
- name: 'h-adr',
- properties: {
- 'post-office-box': {},
- 'street-address': {},
- 'extended-address': {},
- 'locality': {},
- 'region': {},
- 'postal-code': {},
- 'country-name': {}
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
-
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-card.js b/toolkit/components/microformats/test/lib/maps/h-card.js
deleted file mode 100644
index 124750a37..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-card.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-card'] = {
- root: 'vcard',
- name: 'h-card',
- properties: {
- 'fn': {
- 'map': 'p-name'
- },
- 'adr': {
- 'map': 'p-adr',
- 'uf': ['h-adr']
- },
- 'agent': {
- 'uf': ['h-card']
- },
- 'bday': {
- 'map': 'dt-bday'
- },
- 'class': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- 'email': {
- 'map': 'u-email'
- },
- 'geo': {
- 'map': 'p-geo',
- 'uf': ['h-geo']
- },
- 'key': {
- 'map': 'u-key'
- },
- 'label': {},
- 'logo': {
- 'map': 'u-logo'
- },
- 'mailer': {},
- 'honorific-prefix': {},
- 'given-name': {},
- 'additional-name': {},
- 'family-name': {},
- 'honorific-suffix': {},
- 'nickname': {},
- 'note': {}, // could be html i.e. e-note
- 'org': {},
- 'p-organization-name': {},
- 'p-organization-unit': {},
- 'photo': {
- 'map': 'u-photo'
- },
- 'rev': {
- 'map': 'dt-rev'
- },
- 'role': {},
- 'sequence': {},
- 'sort-string': {},
- 'sound': {
- 'map': 'u-sound'
- },
- 'title': {
- 'map': 'p-job-title'
- },
- 'tel': {},
- 'tz': {},
- 'uid': {
- 'map': 'u-uid'
- },
- 'url': {
- 'map': 'u-url'
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-entry.js b/toolkit/components/microformats/test/lib/maps/h-entry.js
deleted file mode 100644
index b82c4c2d9..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-entry.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-entry'] = {
- root: 'hentry',
- name: 'h-entry',
- properties: {
- 'entry-title': {
- 'map': 'p-name'
- },
- 'entry-summary': {
- 'map': 'p-summary'
- },
- 'entry-content': {
- 'map': 'e-content'
- },
- 'published': {
- 'map': 'dt-published'
- },
- 'updated': {
- 'map': 'dt-updated'
- },
- 'author': {
- 'uf': ['h-card']
- },
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- 'geo': {
- 'map': 'p-geo',
- 'uf': ['h-geo']
- },
- 'latitude': {},
- 'longitude': {},
- 'url': {
- 'map': 'u-url',
- 'relAlt': ['bookmark']
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-event.js b/toolkit/components/microformats/test/lib/maps/h-event.js
deleted file mode 100644
index 6599d4549..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-event.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-event'] = {
- root: 'vevent',
- name: 'h-event',
- properties: {
- 'summary': {
- 'map': 'p-name'
- },
- 'dtstart': {
- 'map': 'dt-start'
- },
- 'dtend': {
- 'map': 'dt-end'
- },
- 'description': {},
- 'url': {
- 'map': 'u-url'
- },
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- 'location': {
- 'uf': ['h-card']
- },
- 'geo': {
- 'uf': ['h-geo']
- },
- 'latitude': {},
- 'longitude': {},
- 'duration': {
- 'map': 'dt-duration'
- },
- 'contact': {
- 'uf': ['h-card']
- },
- 'organizer': {
- 'uf': ['h-card']},
- 'attendee': {
- 'uf': ['h-card']},
- 'uid': {
- 'map': 'u-uid'
- },
- 'attach': {
- 'map': 'u-attach'
- },
- 'status': {},
- 'rdate': {},
- 'rrule': {}
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-feed.js b/toolkit/components/microformats/test/lib/maps/h-feed.js
deleted file mode 100644
index f68022856..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-feed.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-feed'] = {
- root: 'hfeed',
- name: 'h-feed',
- properties: {
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- 'summary': {
- 'map': 'p-summary'
- },
- 'author': {
- 'uf': ['h-card']
- },
- 'url': {
- 'map': 'u-url'
- },
- 'photo': {
- 'map': 'u-photo'
- },
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-geo.js b/toolkit/components/microformats/test/lib/maps/h-geo.js
deleted file mode 100644
index fabb86f07..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-geo.js
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-geo'] = {
- root: 'geo',
- name: 'h-geo',
- properties: {
- 'latitude': {},
- 'longitude': {}
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-item.js b/toolkit/components/microformats/test/lib/maps/h-item.js
deleted file mode 100644
index 471a8454e..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-item.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-item'] = {
- root: 'item',
- name: 'h-item',
- subTree: false,
- properties: {
- 'fn': {
- 'map': 'p-name'
- },
- 'url': {
- 'map': 'u-url'
- },
- 'photo': {
- 'map': 'u-photo'
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-listing.js b/toolkit/components/microformats/test/lib/maps/h-listing.js
deleted file mode 100644
index 94783d9ee..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-listing.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-listing'] = {
- root: 'hlisting',
- name: 'h-listing',
- properties: {
- 'version': {},
- 'lister': {
- 'uf': ['h-card']
- },
- 'dtlisted': {
- 'map': 'dt-listed'
- },
- 'dtexpired': {
- 'map': 'dt-expired'
- },
- 'location': {},
- 'price': {},
- 'item': {
- 'uf': ['h-card','a-adr','h-geo']
- },
- 'summary': {
- 'map': 'p-name'
- },
- 'description': {
- 'map': 'e-description'
- },
- 'listing': {}
- }
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/maps/h-news.js b/toolkit/components/microformats/test/lib/maps/h-news.js
deleted file mode 100644
index 362a5a570..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-news.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-news'] = {
- root: 'hnews',
- name: 'h-news',
- properties: {
- 'entry': {
- 'uf': ['h-entry']
- },
- 'geo': {
- 'uf': ['h-geo']
- },
- 'latitude': {},
- 'longitude': {},
- 'source-org': {
- 'uf': ['h-card']
- },
- 'dateline': {
- 'uf': ['h-card']
- },
- 'item-license': {
- 'map': 'u-item-license'
- },
- 'principles': {
- 'map': 'u-principles',
- 'relAlt': ['principles']
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-org.js b/toolkit/components/microformats/test/lib/maps/h-org.js
deleted file mode 100644
index d1b4e8245..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-org.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-org'] = {
- root: 'h-x-org', // drop this from v1 as it causes issue with fn org hcard pattern
- name: 'h-org',
- childStructure: true,
- properties: {
- 'organization-name': {},
- 'organization-unit': {}
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-product.js b/toolkit/components/microformats/test/lib/maps/h-product.js
deleted file mode 100644
index 18f8eb51a..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-product.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-product'] = {
- root: 'hproduct',
- name: 'h-product',
- properties: {
- 'brand': {
- 'uf': ['h-card']
- },
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- 'price': {},
- 'description': {
- 'map': 'e-description'
- },
- 'fn': {
- 'map': 'p-name'
- },
- 'photo': {
- 'map': 'u-photo'
- },
- 'url': {
- 'map': 'u-url'
- },
- 'review': {
- 'uf': ['h-review', 'h-review-aggregate']
- },
- 'listing': {
- 'uf': ['h-listing']
- },
- 'identifier': {
- 'map': 'u-identifier'
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-recipe.js b/toolkit/components/microformats/test/lib/maps/h-recipe.js
deleted file mode 100644
index e3901ea3e..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-recipe.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-recipe'] = {
- root: 'hrecipe',
- name: 'h-recipe',
- properties: {
- 'fn': {
- 'map': 'p-name'
- },
- 'ingredient': {
- 'map': 'e-ingredient'
- },
- 'yield': {},
- 'instructions': {
- 'map': 'e-instructions'
- },
- 'duration': {
- 'map': 'dt-duration'
- },
- 'photo': {
- 'map': 'u-photo'
- },
- 'summary': {},
- 'author': {
- 'uf': ['h-card']
- },
- 'published': {
- 'map': 'dt-published'
- },
- 'nutrition': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- }
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/maps/h-resume.js b/toolkit/components/microformats/test/lib/maps/h-resume.js
deleted file mode 100644
index d6a46cc88..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-resume.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-resume'] = {
- root: 'hresume',
- name: 'h-resume',
- properties: {
- 'summary': {},
- 'contact': {
- 'uf': ['h-card']
- },
- 'education': {
- 'uf': ['h-card', 'h-event']
- },
- 'experience': {
- 'uf': ['h-card', 'h-event']
- },
- 'skill': {},
- 'affiliation': {
- 'uf': ['h-card']
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
-
diff --git a/toolkit/components/microformats/test/lib/maps/h-review-aggregate.js b/toolkit/components/microformats/test/lib/maps/h-review-aggregate.js
deleted file mode 100644
index 4b6027cbf..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-review-aggregate.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-review-aggregate'] = {
- root: 'hreview-aggregate',
- name: 'h-review-aggregate',
- properties: {
- 'summary': {
- 'map': 'p-name'
- },
- 'item': {
- 'map': 'p-item',
- 'uf': ['h-item', 'h-geo', 'h-adr', 'h-card', 'h-event', 'h-product']
- },
- 'rating': {},
- 'average': {},
- 'best': {},
- 'worst': {},
- 'count': {},
- 'votes': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- 'url': {
- 'map': 'u-url',
- 'relAlt': ['self', 'bookmark']
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/maps/h-review.js b/toolkit/components/microformats/test/lib/maps/h-review.js
deleted file mode 100644
index 83f4c24bc..000000000
--- a/toolkit/components/microformats/test/lib/maps/h-review.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.maps = (modules.maps)? modules.maps : {};
-
- modules.maps['h-review'] = {
- root: 'hreview',
- name: 'h-review',
- properties: {
- 'summary': {
- 'map': 'p-name'
- },
- 'description': {
- 'map': 'e-description'
- },
- 'item': {
- 'map': 'p-item',
- 'uf': ['h-item', 'h-geo', 'h-adr', 'h-card', 'h-event', 'h-product']
- },
- 'reviewer': {
- 'uf': ['h-card']
- },
- 'dtreviewer': {
- 'map': 'dt-reviewer'
- },
- 'rating': {},
- 'best': {},
- 'worst': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
- },
- 'url': {
- 'map': 'u-url',
- 'relAlt': ['self', 'bookmark']
- }
- }
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/maps/rel.js b/toolkit/components/microformats/test/lib/maps/rel.js
deleted file mode 100644
index 8accf8009..000000000
--- a/toolkit/components/microformats/test/lib/maps/rel.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.rels = {
- // xfn
- 'friend': [ 'yes','external'],
- 'acquaintance': [ 'yes','external'],
- 'contact': [ 'yes','external'],
- 'met': [ 'yes','external'],
- 'co-worker': [ 'yes','external'],
- 'colleague': [ 'yes','external'],
- 'co-resident': [ 'yes','external'],
- 'neighbor': [ 'yes','external'],
- 'child': [ 'yes','external'],
- 'parent': [ 'yes','external'],
- 'sibling': [ 'yes','external'],
- 'spouse': [ 'yes','external'],
- 'kin': [ 'yes','external'],
- 'muse': [ 'yes','external'],
- 'crush': [ 'yes','external'],
- 'date': [ 'yes','external'],
- 'sweetheart': [ 'yes','external'],
- 'me': [ 'yes','external'],
-
- // other rel=*
- 'license': [ 'yes','yes'],
- 'nofollow': [ 'no','external'],
- 'tag': [ 'no','yes'],
- 'self': [ 'no','external'],
- 'bookmark': [ 'no','external'],
- 'author': [ 'no','external'],
- 'home': [ 'no','external'],
- 'directory': [ 'no','external'],
- 'enclosure': [ 'no','external'],
- 'pronunciation': [ 'no','external'],
- 'payment': [ 'no','external'],
- 'principles': [ 'no','external']
-
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/parser-implied.js b/toolkit/components/microformats/test/lib/parser-implied.js
deleted file mode 100644
index 7f67a2ca1..000000000
--- a/toolkit/components/microformats/test/lib/parser-implied.js
+++ /dev/null
@@ -1,439 +0,0 @@
-/*!
- Parser implied
- All the functions that deal with microformats implied rules
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- Dependencies dates.js, domutils.js, html.js, isodate,js, text.js, utilities.js, url.js
-*/
-
-var Modules = (function (modules) {
-
- // check parser module is loaded
- if(modules.Parser){
-
- /**
- * applies "implied rules" microformat output structure i.e. feed-title, name, photo, url and date
- *
- * @param {DOM Node} node
- * @param {Object} uf (microformat output structure)
- * @param {Object} parentClasses (classes structure)
- * @param {Boolean} impliedPropertiesByVersion
- * @return {Object}
- */
- modules.Parser.prototype.impliedRules = function(node, uf, parentClasses) {
- var typeVersion = (uf.typeVersion)? uf.typeVersion: 'v2';
-
- // TEMP: override to allow v1 implied properties while spec changes
- if(this.options.impliedPropertiesByVersion === false){
- typeVersion = 'v2';
- }
-
- if(node && uf && uf.properties) {
- uf = this.impliedBackwardComp( node, uf, parentClasses );
- if(typeVersion === 'v2'){
- uf = this.impliedhFeedTitle( uf );
- uf = this.impliedName( node, uf );
- uf = this.impliedPhoto( node, uf );
- uf = this.impliedUrl( node, uf );
- }
- uf = this.impliedValue( node, uf, parentClasses );
- uf = this.impliedDate( uf );
-
- // TEMP: flagged while spec changes are put forward
- if(this.options.parseLatLonGeo === true){
- uf = this.impliedGeo( uf );
- }
- }
-
- return uf;
- };
-
-
- /**
- * apply implied name rule
- *
- * @param {DOM Node} node
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedName = function(node, uf) {
- // implied name rule
- /*
- img.h-x[alt] <img class="h-card" src="glenn.htm" alt="Glenn Jones"></a>
- area.h-x[alt] <area class="h-card" href="glenn.htm" alt="Glenn Jones"></area>
- abbr.h-x[title] <abbr class="h-card" title="Glenn Jones"GJ</abbr>
-
- .h-x>img:only-child[alt]:not[.h-*] <div class="h-card"><a src="glenn.htm" alt="Glenn Jones"></a></div>
- .h-x>area:only-child[alt]:not[.h-*] <div class="h-card"><area href="glenn.htm" alt="Glenn Jones"></area></div>
- .h-x>abbr:only-child[title] <div class="h-card"><abbr title="Glenn Jones">GJ</abbr></div>
-
- .h-x>:only-child>img:only-child[alt]:not[.h-*] <div class="h-card"><span><img src="jane.html" alt="Jane Doe"/></span></div>
- .h-x>:only-child>area:only-child[alt]:not[.h-*] <div class="h-card"><span><area href="jane.html" alt="Jane Doe"></area></span></div>
- .h-x>:only-child>abbr:only-child[title] <div class="h-card"><span><abbr title="Jane Doe">JD</abbr></span></div>
- */
- var name,
- value;
-
- if(!uf.properties.name) {
- value = this.getImpliedProperty(node, ['img', 'area', 'abbr'], this.getNameAttr);
- var textFormat = this.options.textFormat;
- // if no value for tags/properties use text
- if(!value) {
- name = [modules.text.parse(this.document, node, textFormat)];
- }else{
- name = [modules.text.parseText(this.document, value, textFormat)];
- }
- if(name && name[0] !== ''){
- uf.properties.name = name;
- }
- }
-
- return uf;
- };
-
-
- /**
- * apply implied photo rule
- *
- * @param {DOM Node} node
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedPhoto = function(node, uf) {
- // implied photo rule
- /*
- img.h-x[src] <img class="h-card" alt="Jane Doe" src="jane.jpeg"/>
- object.h-x[data] <object class="h-card" data="jane.jpeg"/>Jane Doe</object>
- .h-x>img[src]:only-of-type:not[.h-*] <div class="h-card"><img alt="Jane Doe" src="jane.jpeg"/></div>
- .h-x>object[data]:only-of-type:not[.h-*] <div class="h-card"><object data="jane.jpeg"/>Jane Doe</object></div>
- .h-x>:only-child>img[src]:only-of-type:not[.h-*] <div class="h-card"><span><img alt="Jane Doe" src="jane.jpeg"/></span></div>
- .h-x>:only-child>object[data]:only-of-type:not[.h-*] <div class="h-card"><span><object data="jane.jpeg"/>Jane Doe</object></span></div>
- */
- var value;
- if(!uf.properties.photo) {
- value = this.getImpliedProperty(node, ['img', 'object'], this.getPhotoAttr);
- if(value) {
- // relative to absolute URL
- if(value && value !== '' && this.options.baseUrl !== '' && value.indexOf('://') === -1) {
- value = modules.url.resolve(value, this.options.baseUrl);
- }
- uf.properties.photo = [modules.utils.trim(value)];
- }
- }
- return uf;
- };
-
-
- /**
- * apply implied URL rule
- *
- * @param {DOM Node} node
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedUrl = function(node, uf) {
- // implied URL rule
- /*
- a.h-x[href] <a class="h-card" href="glenn.html">Glenn</a>
- area.h-x[href] <area class="h-card" href="glenn.html">Glenn</area>
- .h-x>a[href]:only-of-type:not[.h-*] <div class="h-card" ><a href="glenn.html">Glenn</a><p>...</p></div>
- .h-x>area[href]:only-of-type:not[.h-*] <div class="h-card" ><area href="glenn.html">Glenn</area><p>...</p></div>
- */
- var value;
- if(!uf.properties.url) {
- value = this.getImpliedProperty(node, ['a', 'area'], this.getURLAttr);
- if(value) {
- // relative to absolute URL
- if(value && value !== '' && this.options.baseUrl !== '' && value.indexOf('://') === -1) {
- value = modules.url.resolve(value, this.options.baseUrl);
- }
- uf.properties.url = [modules.utils.trim(value)];
- }
- }
- return uf;
- };
-
-
- /**
- * apply implied date rule - if there is a time only property try to concat it with any date property
- *
- * @param {DOM Node} node
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedDate = function(uf) {
- // implied date rule
- // http://microformats.org/wiki/value-class-pattern#microformats2_parsers
- // http://microformats.org/wiki/microformats2-parsing-issues#implied_date_for_dt_properties_both_mf2_and_backcompat
- var newDate;
- if(uf.times.length > 0 && uf.dates.length > 0) {
- newDate = modules.dates.dateTimeUnion(uf.dates[0][1], uf.times[0][1], this.options.dateFormat);
- uf.properties[this.removePropPrefix(uf.times[0][0])][0] = newDate.toString(this.options.dateFormat);
- }
- // clean-up object
- delete uf.times;
- delete uf.dates;
- return uf;
- };
-
-
- /**
- * get an implied property value from pre-defined tag/attriubte combinations
- *
- * @param {DOM Node} node
- * @param {String} tagList (Array of tags from which an implied value can be pulled)
- * @param {String} getAttrFunction (Function which can extract implied value)
- * @return {String || null}
- */
- modules.Parser.prototype.getImpliedProperty = function(node, tagList, getAttrFunction) {
- // i.e. img.h-card
- var value = getAttrFunction(node),
- descendant,
- child;
-
- if(!value) {
- // i.e. .h-card>img:only-of-type:not(.h-card)
- descendant = modules.domUtils.getSingleDescendantOfType( node, tagList);
- if(descendant && this.hasHClass(descendant) === false){
- value = getAttrFunction(descendant);
- }
- if(node.children.length > 0 ){
- // i.e. .h-card>:only-child>img:only-of-type:not(.h-card)
- child = modules.domUtils.getSingleDescendant(node);
- if(child && this.hasHClass(child) === false){
- descendant = modules.domUtils.getSingleDescendantOfType(child, tagList);
- if(descendant && this.hasHClass(descendant) === false){
- value = getAttrFunction(descendant);
- }
- }
- }
- }
-
- return value;
- };
-
-
- /**
- * get an implied name value from a node
- *
- * @param {DOM Node} node
- * @return {String || null}
- */
- modules.Parser.prototype.getNameAttr = function(node) {
- var value = modules.domUtils.getAttrValFromTagList(node, ['img','area'], 'alt');
- if(!value) {
- value = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
- }
- return value;
- };
-
-
- /**
- * get an implied photo value from a node
- *
- * @param {DOM Node} node
- * @return {String || null}
- */
- modules.Parser.prototype.getPhotoAttr = function(node) {
- var value = modules.domUtils.getAttrValFromTagList(node, ['img'], 'src');
- if(!value && modules.domUtils.hasAttributeValue(node, 'class', 'include') === false) {
- value = modules.domUtils.getAttrValFromTagList(node, ['object'], 'data');
- }
- return value;
- };
-
-
- /**
- * get an implied photo value from a node
- *
- * @param {DOM Node} node
- * @return {String || null}
- */
- modules.Parser.prototype.getURLAttr = function(node) {
- var value = null;
- if(modules.domUtils.hasAttributeValue(node, 'class', 'include') === false){
-
- value = modules.domUtils.getAttrValFromTagList(node, ['a'], 'href');
- if(!value) {
- value = modules.domUtils.getAttrValFromTagList(node, ['area'], 'href');
- }
-
- }
- return value;
- };
-
-
- /**
- *
- *
- * @param {DOM Node} node
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedValue = function(node, uf, parentClasses){
-
- // intersection of implied name and implied value rules
- if(uf.properties.name) {
- if(uf.value && parentClasses.root.length > 0 && parentClasses.properties.length === 1){
- uf = this.getAltValue(uf, parentClasses.properties[0][0], 'p-name', uf.properties.name[0]);
- }
- }
-
- // intersection of implied URL and implied value rules
- if(uf.properties.url) {
- if(parentClasses && parentClasses.root.length === 1 && parentClasses.properties.length === 1){
- uf = this.getAltValue(uf, parentClasses.properties[0][0], 'u-url', uf.properties.url[0]);
- }
- }
-
- // apply alt value
- if(uf.altValue !== null){
- uf.value = uf.altValue.value;
- }
- delete uf.altValue;
-
-
- return uf;
- };
-
-
- /**
- * get alt value based on rules about parent property prefix
- *
- * @param {Object} uf
- * @param {String} parentPropertyName
- * @param {String} propertyName
- * @param {String} value
- * @return {Object}
- */
- modules.Parser.prototype.getAltValue = function(uf, parentPropertyName, propertyName, value){
- if(uf.value && !uf.altValue){
- // first p-name of the h-* child
- if(modules.utils.startWith(parentPropertyName,'p-') && propertyName === 'p-name'){
- uf.altValue = {name: propertyName, value: value};
- }
- // if it's an e-* property element
- if(modules.utils.startWith(parentPropertyName,'e-') && modules.utils.startWith(propertyName,'e-')){
- uf.altValue = {name: propertyName, value: value};
- }
- // if it's an u-* property element
- if(modules.utils.startWith(parentPropertyName,'u-') && propertyName === 'u-url'){
- uf.altValue = {name: propertyName, value: value};
- }
- }
- return uf;
- };
-
-
- /**
- * if a h-feed does not have a title use the title tag of a page
- *
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedhFeedTitle = function( uf ){
- if(uf.type && uf.type.indexOf('h-feed') > -1){
- // has no name property
- if(uf.properties.name === undefined || uf.properties.name[0] === '' ){
- // use the text from the title tag
- var title = modules.domUtils.querySelector(this.document, 'title');
- if(title){
- uf.properties.name = [modules.domUtils.textContent(title)];
- }
- }
- }
- return uf;
- };
-
-
-
- /**
- * implied Geo from pattern <abbr class="p-geo" title="37.386013;-122.082932">
- *
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedGeo = function( uf ){
- var geoPair,
- parts,
- longitude,
- latitude,
- valid = true;
-
- if(uf.type && uf.type.indexOf('h-geo') > -1){
-
- // has no latitude or longitude property
- if(uf.properties.latitude === undefined || uf.properties.longitude === undefined ){
-
- geoPair = (uf.properties.name)? uf.properties.name[0] : null;
- geoPair = (!geoPair && uf.properties.value)? uf.properties.value : geoPair;
-
- if(geoPair){
- // allow for the use of a ';' as in microformats and also ',' as in Geo URL
- geoPair = geoPair.replace(';',',');
-
- // has sep char
- if(geoPair.indexOf(',') > -1 ){
- parts = geoPair.split(',');
-
- // only correct if we have two or more parts
- if(parts.length > 1){
-
- // latitude no value outside the range -90 or 90
- latitude = parseFloat( parts[0] );
- if(modules.utils.isNumber(latitude) && latitude > 90 || latitude < -90){
- valid = false;
- }
-
- // longitude no value outside the range -180 to 180
- longitude = parseFloat( parts[1] );
- if(modules.utils.isNumber(longitude) && longitude > 180 || longitude < -180){
- valid = false;
- }
-
- if(valid){
- uf.properties.latitude = [latitude];
- uf.properties.longitude = [longitude];
- }
- }
-
- }
- }
- }
- }
- return uf;
- };
-
-
- /**
- * if a backwards compat built structure has no properties add name through this.impliedName
- *
- * @param {Object} uf
- * @return {Object}
- */
- modules.Parser.prototype.impliedBackwardComp = function(node, uf, parentClasses){
-
- // look for pattern in parent classes like "p-geo h-geo"
- // these are structures built from backwards compat parsing of geo
- if(parentClasses.root.length === 1 && parentClasses.properties.length === 1) {
- if(parentClasses.root[0].replace('h-','') === this.removePropPrefix(parentClasses.properties[0][0])) {
-
- // if microformat has no properties apply the impliedName rule to get value from containing node
- // this will get value from html such as <abbr class="geo" title="30.267991;-97.739568">Brighton</abbr>
- if( modules.utils.hasProperties(uf.properties) === false ){
- uf = this.impliedName( node, uf );
- }
- }
- }
-
- return uf;
- };
-
-
-
- }
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/parser-includes.js b/toolkit/components/microformats/test/lib/parser-includes.js
deleted file mode 100644
index f0967710d..000000000
--- a/toolkit/components/microformats/test/lib/parser-includes.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/*!
- Parser includes
- All the functions that deal with microformats v1 include rules
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- Dependencies dates.js, domutils.js, html.js, isodate,js, text.js, utilities.js
-*/
-
-
-var Modules = (function (modules) {
-
- // check parser module is loaded
- if(modules.Parser){
-
-
- /**
- * appends clones of include Nodes into the DOM structure
- *
- * @param {DOM node} rootNode
- */
- modules.Parser.prototype.addIncludes = function(rootNode) {
- this.addAttributeIncludes(rootNode, 'itemref');
- this.addAttributeIncludes(rootNode, 'headers');
- this.addClassIncludes(rootNode);
- };
-
-
- /**
- * appends clones of include Nodes into the DOM structure for attribute based includes
- *
- * @param {DOM node} rootNode
- * @param {String} attributeName
- */
- modules.Parser.prototype.addAttributeIncludes = function(rootNode, attributeName) {
- var arr,
- idList,
- i,
- x,
- z,
- y;
-
- arr = modules.domUtils.getNodesByAttribute(rootNode, attributeName);
- x = 0;
- i = arr.length;
- while(x < i) {
- idList = modules.domUtils.getAttributeList(arr[x], attributeName);
- if(idList) {
- z = 0;
- y = idList.length;
- while(z < y) {
- this.apppendInclude(arr[x], idList[z]);
- z++;
- }
- }
- x++;
- }
- };
-
-
- /**
- * appends clones of include Nodes into the DOM structure for class based includes
- *
- * @param {DOM node} rootNode
- */
- modules.Parser.prototype.addClassIncludes = function(rootNode) {
- var id,
- arr,
- x = 0,
- i;
-
- arr = modules.domUtils.getNodesByAttributeValue(rootNode, 'class', 'include');
- i = arr.length;
- while(x < i) {
- id = modules.domUtils.getAttrValFromTagList(arr[x], ['a'], 'href');
- if(!id) {
- id = modules.domUtils.getAttrValFromTagList(arr[x], ['object'], 'data');
- }
- this.apppendInclude(arr[x], id);
- x++;
- }
- };
-
-
- /**
- * appends a clone of an include into another Node using Id
- *
- * @param {DOM node} rootNode
- * @param {Stringe} id
- */
- modules.Parser.prototype.apppendInclude = function(node, id){
- var include,
- clone;
-
- id = modules.utils.trim(id.replace('#', ''));
- include = modules.domUtils.getElementById(this.document, id);
- if(include) {
- clone = modules.domUtils.clone(include);
- this.markIncludeChildren(clone);
- modules.domUtils.appendChild(node, clone);
- }
- };
-
-
- /**
- * adds an attribute marker to all the child microformat roots
- *
- * @param {DOM node} rootNode
- */
- modules.Parser.prototype.markIncludeChildren = function(rootNode) {
- var arr,
- x,
- i;
-
- // loop the array and add the attribute
- arr = this.findRootNodes(rootNode);
- x = 0;
- i = arr.length;
- modules.domUtils.setAttribute(rootNode, 'data-include', 'true');
- modules.domUtils.setAttribute(rootNode, 'style', 'display:none');
- while(x < i) {
- modules.domUtils.setAttribute(arr[x], 'data-include', 'true');
- x++;
- }
- };
-
-
- /**
- * removes all appended include clones from DOM
- *
- * @param {DOM node} rootNode
- */
- modules.Parser.prototype.removeIncludes = function(rootNode){
- var arr,
- i;
-
- // remove all the items that were added as includes
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'data-include');
- i = arr.length;
- while(i--) {
- modules.domUtils.removeChild(rootNode,arr[i]);
- }
- };
-
-
- }
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/parser-rels.js b/toolkit/components/microformats/test/lib/parser-rels.js
deleted file mode 100644
index 63ef67446..000000000
--- a/toolkit/components/microformats/test/lib/parser-rels.js
+++ /dev/null
@@ -1,200 +0,0 @@
-/*!
- Parser rels
- All the functions that deal with microformats v2 rel structures
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- Dependencies dates.js, domutils.js, html.js, isodate,js, text.js, utilities.js, url.js
-*/
-
-
-var Modules = (function (modules) {
-
- // check parser module is loaded
- if(modules.Parser){
-
- /**
- * finds rel=* structures
- *
- * @param {DOM node} rootNode
- * @return {Object}
- */
- modules.Parser.prototype.findRels = function(rootNode) {
- var out = {
- 'items': [],
- 'rels': {},
- 'rel-urls': {}
- },
- x,
- i,
- y,
- z,
- relList,
- items,
- item,
- value,
- arr;
-
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'rel');
- x = 0;
- i = arr.length;
- while(x < i) {
- relList = modules.domUtils.getAttribute(arr[x], 'rel');
-
- if(relList) {
- items = relList.split(' ');
-
-
- // add rels
- z = 0;
- y = items.length;
- while(z < y) {
- item = modules.utils.trim(items[z]);
-
- // get rel value
- value = modules.domUtils.getAttrValFromTagList(arr[x], ['a', 'area'], 'href');
- if(!value) {
- value = modules.domUtils.getAttrValFromTagList(arr[x], ['link'], 'href');
- }
-
- // create the key
- if(!out.rels[item]) {
- out.rels[item] = [];
- }
-
- if(typeof this.options.baseUrl === 'string' && typeof value === 'string') {
-
- var resolved = modules.url.resolve(value, this.options.baseUrl);
- // do not add duplicate rels - based on resolved URLs
- if(out.rels[item].indexOf(resolved) === -1){
- out.rels[item].push( resolved );
- }
- }
- z++;
- }
-
-
- var url = null;
- if(modules.domUtils.hasAttribute(arr[x], 'href')){
- url = modules.domUtils.getAttribute(arr[x], 'href');
- if(url){
- url = modules.url.resolve(url, this.options.baseUrl );
- }
- }
-
-
- // add to rel-urls
- var relUrl = this.getRelProperties(arr[x]);
- relUrl.rels = items;
- // // do not add duplicate rel-urls - based on resolved URLs
- if(url && out['rel-urls'][url] === undefined){
- out['rel-urls'][url] = relUrl;
- }
-
-
- }
- x++;
- }
- return out;
- };
-
-
- /**
- * gets the properties of a rel=*
- *
- * @param {DOM node} node
- * @return {Object}
- */
- modules.Parser.prototype.getRelProperties = function(node){
- var obj = {};
-
- if(modules.domUtils.hasAttribute(node, 'media')){
- obj.media = modules.domUtils.getAttribute(node, 'media');
- }
- if(modules.domUtils.hasAttribute(node, 'type')){
- obj.type = modules.domUtils.getAttribute(node, 'type');
- }
- if(modules.domUtils.hasAttribute(node, 'hreflang')){
- obj.hreflang = modules.domUtils.getAttribute(node, 'hreflang');
- }
- if(modules.domUtils.hasAttribute(node, 'title')){
- obj.title = modules.domUtils.getAttribute(node, 'title');
- }
- if(modules.utils.trim(this.getPValue(node, false)) !== ''){
- obj.text = this.getPValue(node, false);
- }
-
- return obj;
- };
-
-
- /**
- * finds any alt rel=* mappings for a given node/microformat
- *
- * @param {DOM node} node
- * @param {String} ufName
- * @return {String || undefined}
- */
- modules.Parser.prototype.findRelImpied = function(node, ufName) {
- var out,
- map,
- i;
-
- map = this.getMapping(ufName);
- if(map) {
- for(var key in map.properties) {
- if (map.properties.hasOwnProperty(key)) {
- var prop = map.properties[key],
- propName = (prop.map) ? prop.map : 'p-' + key,
- relCount = 0;
-
- // is property an alt rel=* mapping
- if(prop.relAlt && modules.domUtils.hasAttribute(node, 'rel')) {
- i = prop.relAlt.length;
- while(i--) {
- if(modules.domUtils.hasAttributeValue(node, 'rel', prop.relAlt[i])) {
- relCount++;
- }
- }
- if(relCount === prop.relAlt.length) {
- out = propName;
- }
- }
- }
- }
- }
- return out;
- };
-
-
- /**
- * returns whether a node or its children has rel=* microformat
- *
- * @param {DOM node} node
- * @return {Boolean}
- */
- modules.Parser.prototype.hasRel = function(node) {
- return (this.countRels(node) > 0);
- };
-
-
- /**
- * returns the number of rel=* microformats
- *
- * @param {DOM node} node
- * @return {Int}
- */
- modules.Parser.prototype.countRels = function(node) {
- if(node){
- return modules.domUtils.getNodesByAttribute(node, 'rel').length;
- }
- return 0;
- };
-
-
-
- }
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/parser.js b/toolkit/components/microformats/test/lib/parser.js
deleted file mode 100644
index 062ec9f0e..000000000
--- a/toolkit/components/microformats/test/lib/parser.js
+++ /dev/null
@@ -1,1453 +0,0 @@
-/*!
- Parser
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- Dependencies dates.js, domutils.js, html.js, isodate,js, text.js, utilities.js, url.js
-*/
-
-
-var Modules = (function (modules) {
-
-
- /**
- * constructor
- *
- */
- modules.Parser = function () {
- this.rootPrefix = 'h-';
- this.propertyPrefixes = ['p-', 'dt-', 'u-', 'e-'];
- this.excludeTags = ['br', 'hr'];
- };
-
-
- // create objects incase the v1 map modules don't load
- modules.maps = (modules.maps)? modules.maps : {};
- modules.rels = (modules.rels)? modules.rels : {};
-
-
- modules.Parser.prototype = {
-
- init: function(){
- this.rootNode = null;
- this.document = null;
- this.options = {
- 'baseUrl': '',
- 'filters': [],
- 'textFormat': 'whitespacetrimmed',
- 'dateFormat': 'auto', // html5 for testing
- 'overlappingVersions': false,
- 'impliedPropertiesByVersion': true,
- 'parseLatLonGeo': false
- };
- this.rootID = 0;
- this.errors = [];
- this.noContentErr = 'No options.node or options.html was provided and no document object could be found.';
- },
-
-
- /**
- * internal parse function
- *
- * @param {Object} options
- * @return {Object}
- */
- get: function(options) {
- var out = this.formatEmpty(),
- data = [],
- rels;
-
- this.init();
- options = (options)? options : {};
- this.mergeOptions(options);
- this.getDOMContext( options );
-
- // if we do not have any context create error
- if(!this.rootNode || !this.document){
- this.errors.push(this.noContentErr);
- }else{
-
- // only parse h-* microformats if we need to
- // this is added to speed up parsing
- if(this.hasMicroformats(this.rootNode, options)){
- this.prepareDOM( options );
-
- if(this.options.filters.length > 0){
- // parse flat list of items
- var newRootNode = this.findFilterNodes(this.rootNode, this.options.filters);
- data = this.walkRoot(newRootNode);
- }else{
- // parse whole document from root
- data = this.walkRoot(this.rootNode);
- }
-
- out.items = data;
- // don't clear-up DOM if it was cloned
- if(modules.domUtils.canCloneDocument(this.document) === false){
- this.clearUpDom(this.rootNode);
- }
- }
-
- // find any rels
- if(this.findRels){
- rels = this.findRels(this.rootNode);
- out.rels = rels.rels;
- out['rel-urls'] = rels['rel-urls'];
- }
-
- }
-
- if(this.errors.length > 0){
- return this.formatError();
- }
- return out;
- },
-
-
- /**
- * parse to get parent microformat of passed node
- *
- * @param {DOM Node} node
- * @param {Object} options
- * @return {Object}
- */
- getParent: function(node, options) {
- this.init();
- options = (options)? options : {};
-
- if(node){
- return this.getParentTreeWalk(node, options);
- }else{
- this.errors.push(this.noContentErr);
- return this.formatError();
- }
- },
-
-
- /**
- * get the count of microformats
- *
- * @param {DOM Node} rootNode
- * @return {Int}
- */
- count: function( options ) {
- var out = {},
- items,
- classItems,
- x,
- i;
-
- this.init();
- options = (options)? options : {};
- this.getDOMContext( options );
-
- // if we do not have any context create error
- if(!this.rootNode || !this.document){
- return {'errors': [this.noContentErr]};
- }else{
-
- items = this.findRootNodes( this.rootNode, true );
- i = items.length;
- while(i--) {
- classItems = modules.domUtils.getAttributeList(items[i], 'class');
- x = classItems.length;
- while(x--) {
- // find v2 names
- if(modules.utils.startWith( classItems[x], 'h-' )){
- this.appendCount(classItems[x], 1, out);
- }
- // find v1 names
- for(var key in modules.maps) {
- // dont double count if v1 and v2 roots are present
- if(modules.maps[key].root === classItems[x] && classItems.indexOf(key) === -1) {
- this.appendCount(key, 1, out);
- }
- }
- }
- }
- var relCount = this.countRels( this.rootNode );
- if(relCount > 0){
- out.rels = relCount;
- }
-
- return out;
- }
- },
-
-
- /**
- * does a node have a class that marks it as a microformats root
- *
- * @param {DOM Node} node
- * @param {Objecte} options
- * @return {Boolean}
- */
- isMicroformat: function( node, options ) {
- var classes,
- i;
-
- if(!node){
- return false;
- }
-
- // if documemt gets topmost node
- node = modules.domUtils.getTopMostNode( node );
-
- // look for h-* microformats
- classes = this.getUfClassNames(node);
- if(options && options.filters && modules.utils.isArray(options.filters)){
- i = options.filters.length;
- while(i--) {
- if(classes.root.indexOf(options.filters[i]) > -1){
- return true;
- }
- }
- return false;
- }else{
- return (classes.root.length > 0);
- }
- },
-
-
- /**
- * does a node or its children have microformats
- *
- * @param {DOM Node} node
- * @param {Objecte} options
- * @return {Boolean}
- */
- hasMicroformats: function( node, options ) {
- var items,
- i;
-
- if(!node){
- return false;
- }
-
- // if browser based documemt get topmost node
- node = modules.domUtils.getTopMostNode( node );
-
- // returns all microformat roots
- items = this.findRootNodes( node, true );
- if(options && options.filters && modules.utils.isArray(options.filters)){
- i = items.length;
- while(i--) {
- if( this.isMicroformat( items[i], options ) ){
- return true;
- }
- }
- return false;
- }else{
- return (items.length > 0);
- }
- },
-
-
- /**
- * add a new v1 mapping object to parser
- *
- * @param {Array} maps
- */
- add: function( maps ){
- maps.forEach(function(map){
- if(map && map.root && map.name && map.properties){
- modules.maps[map.name] = JSON.parse(JSON.stringify(map));
- }
- });
- },
-
-
- /**
- * internal parse to get parent microformats by walking up the tree
- *
- * @param {DOM Node} node
- * @param {Object} options
- * @param {Int} recursive
- * @return {Object}
- */
- getParentTreeWalk: function (node, options, recursive) {
- options = (options)? options : {};
-
- // recursive calls
- if (recursive === undefined) {
- if (node.parentNode && node.nodeName !== 'HTML'){
- return this.getParentTreeWalk(node.parentNode, options, true);
- }else{
- return this.formatEmpty();
- }
- }
- if (node !== null && node !== undefined && node.parentNode) {
- if (this.isMicroformat( node, options )) {
- // if we have a match return microformat
- options.node = node;
- return this.get( options );
- }else{
- return this.getParentTreeWalk(node.parentNode, options, true);
- }
- }else{
- return this.formatEmpty();
- }
- },
-
-
-
- /**
- * configures what are the base DOM objects for parsing
- *
- * @param {Object} options
- */
- getDOMContext: function( options ){
- var nodes = modules.domUtils.getDOMContext( options );
- this.rootNode = nodes.rootNode;
- this.document = nodes.document;
- },
-
-
- /**
- * prepares DOM before the parse begins
- *
- * @param {Object} options
- * @return {Boolean}
- */
- prepareDOM: function( options ){
- var baseTag,
- href;
-
- // use current document to define baseUrl, try/catch needed for IE10+ error
- try {
- if (!options.baseUrl && this.document && this.document.location) {
- this.options.baseUrl = this.document.location.href;
- }
- } catch (e) {
- // there is no alt action
- }
-
-
- // find base tag to set baseUrl
- baseTag = modules.domUtils.querySelector(this.document,'base');
- if(baseTag) {
- href = modules.domUtils.getAttribute(baseTag, 'href');
- if(href){
- this.options.baseUrl = href;
- }
- }
-
- // get path to rootNode
- // then clone document
- // then reset the rootNode to its cloned version in a new document
- var path,
- newDocument,
- newRootNode;
-
- path = modules.domUtils.getNodePath(this.rootNode);
- newDocument = modules.domUtils.cloneDocument(this.document);
- newRootNode = modules.domUtils.getNodeByPath(newDocument, path);
-
- // check results as early IE fails
- if(newDocument && newRootNode){
- this.document = newDocument;
- this.rootNode = newRootNode;
- }
-
- // add includes
- if(this.addIncludes){
- this.addIncludes( this.document );
- }
-
- return (this.rootNode && this.document);
- },
-
-
- /**
- * returns an empty structure with errors
- *
- * @return {Object}
- */
- formatError: function(){
- var out = this.formatEmpty();
- out.errors = this.errors;
- return out;
- },
-
-
- /**
- * returns an empty structure
- *
- * @return {Object}
- */
- formatEmpty: function(){
- return {
- 'items': [],
- 'rels': {},
- 'rel-urls': {}
- };
- },
-
-
- // find microformats of a given type and return node structures
- findFilterNodes: function(rootNode, filters) {
- var newRootNode = modules.domUtils.createNode('div'),
- items = this.findRootNodes(rootNode, true),
- i = 0,
- x = 0,
- y = 0;
-
- if(items){
- i = items.length;
- while(x < i) {
- // add v1 names
- y = filters.length;
- while (y--) {
- if(this.getMapping(filters[y])){
- var v1Name = this.getMapping(filters[y]).root;
- filters.push(v1Name);
- }
- }
- // append matching nodes into newRootNode
- y = filters.length;
- while (y--) {
- if(modules.domUtils.hasAttributeValue(items[x], 'class', filters[y])){
- var clone = modules.domUtils.clone(items[x]);
- modules.domUtils.appendChild(newRootNode, clone);
- break;
- }
- }
- x++;
- }
- }
-
- return newRootNode;
- },
-
-
- /**
- * appends data to output object for count
- *
- * @param {string} name
- * @param {Int} count
- * @param {Object}
- */
- appendCount: function(name, count, out){
- if(out[name]){
- out[name] = out[name] + count;
- }else{
- out[name] = count;
- }
- },
-
-
- /**
- * is the microformats type in the filter list
- *
- * @param {Object} uf
- * @param {Array} filters
- * @return {Boolean}
- */
- shouldInclude: function(uf, filters) {
- var i;
-
- if(modules.utils.isArray(filters) && filters.length > 0) {
- i = filters.length;
- while(i--) {
- if(uf.type[0] === filters[i]) {
- return true;
- }
- }
- return false;
- } else {
- return true;
- }
- },
-
-
- /**
- * finds all microformat roots in a rootNode
- *
- * @param {DOM Node} rootNode
- * @param {Boolean} includeRoot
- * @return {Array}
- */
- findRootNodes: function(rootNode, includeRoot) {
- var arr = null,
- out = [],
- classList = [],
- items,
- x,
- i,
- y,
- key;
-
-
- // build an array of v1 root names
- for(key in modules.maps) {
- if (modules.maps.hasOwnProperty(key)) {
- classList.push(modules.maps[key].root);
- }
- }
-
- // get all elements that have a class attribute
- includeRoot = (includeRoot) ? includeRoot : false;
- if(includeRoot && rootNode.parentNode) {
- arr = modules.domUtils.getNodesByAttribute(rootNode.parentNode, 'class');
- } else {
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'class');
- }
-
- // loop elements that have a class attribute
- x = 0;
- i = arr.length;
- while(x < i) {
-
- items = modules.domUtils.getAttributeList(arr[x], 'class');
-
- // loop classes on an element
- y = items.length;
- while(y--) {
- // match v1 root names
- if(classList.indexOf(items[y]) > -1) {
- out.push(arr[x]);
- break;
- }
-
- // match v2 root name prefix
- if(modules.utils.startWith(items[y], 'h-')) {
- out.push(arr[x]);
- break;
- }
- }
-
- x++;
- }
- return out;
- },
-
-
- /**
- * starts the tree walk to find microformats
- *
- * @param {DOM Node} node
- * @return {Array}
- */
- walkRoot: function(node){
- var context = this,
- children = [],
- child,
- classes,
- items = [],
- out = [];
-
- classes = this.getUfClassNames(node);
- // if it is a root microformat node
- if(classes && classes.root.length > 0){
- items = this.walkTree(node);
-
- if(items.length > 0){
- out = out.concat(items);
- }
- }else{
- // check if there are children and one of the children has a root microformat
- children = modules.domUtils.getChildren( node );
- if(children && children.length > 0 && this.findRootNodes(node, true).length > -1){
- for (var i = 0; i < children.length; i++) {
- child = children[i];
- items = context.walkRoot(child);
- if(items.length > 0){
- out = out.concat(items);
- }
- }
- }
- }
- return out;
- },
-
-
- /**
- * starts the tree walking for a single microformat
- *
- * @param {DOM Node} node
- * @return {Array}
- */
- walkTree: function(node) {
- var classes,
- out = [],
- obj,
- itemRootID;
-
- // loop roots found on one element
- classes = this.getUfClassNames(node);
- if(classes && classes.root.length && classes.root.length > 0){
-
- this.rootID++;
- itemRootID = this.rootID;
- obj = this.createUfObject(classes.root, classes.typeVersion);
-
- this.walkChildren(node, obj, classes.root, itemRootID, classes);
- if(this.impliedRules){
- this.impliedRules(node, obj, classes);
- }
- out.push( this.cleanUfObject(obj) );
-
-
- }
- return out;
- },
-
-
- /**
- * finds child properties of microformat
- *
- * @param {DOM Node} node
- * @param {Object} out
- * @param {String} ufName
- * @param {Int} rootID
- * @param {Object} parentClasses
- */
- walkChildren: function(node, out, ufName, rootID, parentClasses) {
- var context = this,
- children = [],
- rootItem,
- itemRootID,
- value,
- propertyName,
- propertyVersion,
- i,
- x,
- y,
- z,
- child;
-
- children = modules.domUtils.getChildren( node );
-
- y = 0;
- z = children.length;
- while(y < z) {
- child = children[y];
-
- // get microformat classes for this single element
- var classes = context.getUfClassNames(child, ufName);
-
- // a property which is a microformat
- if(classes.root.length > 0 && classes.properties.length > 0 && !child.addedAsRoot) {
- // create object with type, property and value
- rootItem = context.createUfObject(
- classes.root,
- classes.typeVersion,
- modules.text.parse(this.document, child, context.options.textFormat)
- );
-
- // add the microformat as an array of properties
- propertyName = context.removePropPrefix(classes.properties[0][0]);
-
- // modifies value with "implied value rule"
- if(parentClasses && parentClasses.root.length === 1 && parentClasses.properties.length === 1){
- if(context.impliedValueRule){
- out = context.impliedValueRule(out, parentClasses.properties[0][0], classes.properties[0][0], value);
- }
- }
-
- if(out.properties[propertyName]) {
- out.properties[propertyName].push(rootItem);
- } else {
- out.properties[propertyName] = [rootItem];
- }
-
- context.rootID++;
- // used to stop duplication in heavily nested structures
- child.addedAsRoot = true;
-
-
- x = 0;
- i = rootItem.type.length;
- itemRootID = context.rootID;
- while(x < i) {
- context.walkChildren(child, rootItem, rootItem.type, itemRootID, classes);
- x++;
- }
- if(this.impliedRules){
- context.impliedRules(child, rootItem, classes);
- }
- this.cleanUfObject(rootItem);
-
- }
-
- // a property which is NOT a microformat and has not been used for a given root element
- if(classes.root.length === 0 && classes.properties.length > 0) {
-
- x = 0;
- i = classes.properties.length;
- while(x < i) {
-
- value = context.getValue(child, classes.properties[x][0], out);
- propertyName = context.removePropPrefix(classes.properties[x][0]);
- propertyVersion = classes.properties[x][1];
-
- // modifies value with "implied value rule"
- if(parentClasses && parentClasses.root.length === 1 && parentClasses.properties.length === 1){
- if(context.impliedValueRule){
- out = context.impliedValueRule(out, parentClasses.properties[0][0], classes.properties[x][0], value);
- }
- }
-
- // if we have not added this value into a property with the same name already
- if(!context.hasRootID(child, rootID, propertyName)) {
- // check the root and property is the same version or if overlapping versions are allowed
- if( context.isAllowedPropertyVersion( out.typeVersion, propertyVersion ) ){
- // add the property as an array of properties
- if(out.properties[propertyName]) {
- out.properties[propertyName].push(value);
- } else {
- out.properties[propertyName] = [value];
- }
- // add rootid to node so we can track its use
- context.appendRootID(child, rootID, propertyName);
- }
- }
-
- x++;
- }
-
- context.walkChildren(child, out, ufName, rootID, classes);
- }
-
- // if the node has no microformat classes, see if its children have
- if(classes.root.length === 0 && classes.properties.length === 0) {
- context.walkChildren(child, out, ufName, rootID, classes);
- }
-
- // if the node is a child root add it to the children tree
- if(classes.root.length > 0 && classes.properties.length === 0) {
-
- // create object with type, property and value
- rootItem = context.createUfObject(
- classes.root,
- classes.typeVersion,
- modules.text.parse(this.document, child, context.options.textFormat)
- );
-
- // add the microformat as an array of properties
- if(!out.children){
- out.children = [];
- }
-
- if(!context.hasRootID(child, rootID, 'child-root')) {
- out.children.push( rootItem );
- context.appendRootID(child, rootID, 'child-root');
- context.rootID++;
- }
-
- x = 0;
- i = rootItem.type.length;
- itemRootID = context.rootID;
- while(x < i) {
- context.walkChildren(child, rootItem, rootItem.type, itemRootID, classes);
- x++;
- }
- if(this.impliedRules){
- context.impliedRules(child, rootItem, classes);
- }
- context.cleanUfObject( rootItem );
-
- }
-
-
-
- y++;
- }
-
- },
-
-
-
-
- /**
- * gets the value of a property from a node
- *
- * @param {DOM Node} node
- * @param {String} className
- * @param {Object} uf
- * @return {String || Object}
- */
- getValue: function(node, className, uf) {
- var value = '';
-
- if(modules.utils.startWith(className, 'p-')) {
- value = this.getPValue(node, true);
- }
-
- if(modules.utils.startWith(className, 'e-')) {
- value = this.getEValue(node);
- }
-
- if(modules.utils.startWith(className, 'u-')) {
- value = this.getUValue(node, true);
- }
-
- if(modules.utils.startWith(className, 'dt-')) {
- value = this.getDTValue(node, className, uf, true);
- }
- return value;
- },
-
-
- /**
- * gets the value of a node which contains a 'p-' property
- *
- * @param {DOM Node} node
- * @param {Boolean} valueParse
- * @return {String}
- */
- getPValue: function(node, valueParse) {
- var out = '';
- if(valueParse) {
- out = this.getValueClass(node, 'p');
- }
-
- if(!out && valueParse) {
- out = this.getValueTitle(node);
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['data','input'], 'value');
- }
-
- if(node.name === 'br' || node.name === 'hr') {
- out = '';
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['img', 'area'], 'alt');
- }
-
- if(!out) {
- out = modules.text.parse(this.document, node, this.options.textFormat);
- }
-
- return(out) ? out : '';
- },
-
-
- /**
- * gets the value of a node which contains the 'e-' property
- *
- * @param {DOM Node} node
- * @return {Object}
- */
- getEValue: function(node) {
-
- var out = {value: '', html: ''};
-
- this.expandURLs(node, 'src', this.options.baseUrl);
- this.expandURLs(node, 'href', this.options.baseUrl);
-
- out.value = modules.text.parse(this.document, node, this.options.textFormat);
- out.html = modules.html.parse(node);
-
- return out;
- },
-
-
- /**
- * gets the value of a node which contains the 'u-' property
- *
- * @param {DOM Node} node
- * @param {Boolean} valueParse
- * @return {String}
- */
- getUValue: function(node, valueParse) {
- var out = '';
- if(valueParse) {
- out = this.getValueClass(node, 'u');
- }
-
- if(!out && valueParse) {
- out = this.getValueTitle(node);
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['a', 'area'], 'href');
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['img','audio','video','source'], 'src');
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['object'], 'data');
- }
-
- // if we have no protocol separator, turn relative url to absolute url
- if(out && out !== '' && out.indexOf('://') === -1) {
- out = modules.url.resolve(out, this.options.baseUrl);
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['data','input'], 'value');
- }
-
- if(!out) {
- out = modules.text.parse(this.document, node, this.options.textFormat);
- }
-
- return(out) ? out : '';
- },
-
-
- /**
- * gets the value of a node which contains the 'dt-' property
- *
- * @param {DOM Node} node
- * @param {String} className
- * @param {Object} uf
- * @param {Boolean} valueParse
- * @return {String}
- */
- getDTValue: function(node, className, uf, valueParse) {
- var out = '';
-
- if(valueParse) {
- out = this.getValueClass(node, 'dt');
- }
-
- if(!out && valueParse) {
- out = this.getValueTitle(node);
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['time', 'ins', 'del'], 'datetime');
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
- }
-
- if(!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['data', 'input'], 'value');
- }
-
- if(!out) {
- out = modules.text.parse(this.document, node, this.options.textFormat);
- }
-
- if(out) {
- if(modules.dates.isDuration(out)) {
- // just duration
- return out;
- } else if(modules.dates.isTime(out)) {
- // just time or time+timezone
- if(uf) {
- uf.times.push([className, modules.dates.parseAmPmTime(out, this.options.dateFormat)]);
- }
- return modules.dates.parseAmPmTime(out, this.options.dateFormat);
- } else {
- // returns a date - microformat profile
- if(uf) {
- uf.dates.push([className, new modules.ISODate(out).toString( this.options.dateFormat )]);
- }
- return new modules.ISODate(out).toString( this.options.dateFormat );
- }
- } else {
- return '';
- }
- },
-
-
- /**
- * appends a new rootid to a given node
- *
- * @param {DOM Node} node
- * @param {String} id
- * @param {String} propertyName
- */
- appendRootID: function(node, id, propertyName) {
- if(this.hasRootID(node, id, propertyName) === false){
- var rootids = [];
- if(modules.domUtils.hasAttribute(node,'rootids')){
- rootids = modules.domUtils.getAttributeList(node,'rootids');
- }
- rootids.push('id' + id + '-' + propertyName);
- modules.domUtils.setAttribute(node, 'rootids', rootids.join(' '));
- }
- },
-
-
- /**
- * does a given node already have a rootid
- *
- * @param {DOM Node} node
- * @param {String} id
- * @param {String} propertyName
- * @return {Boolean}
- */
- hasRootID: function(node, id, propertyName) {
- var rootids = [];
- if(!modules.domUtils.hasAttribute(node,'rootids')){
- return false;
- } else {
- rootids = modules.domUtils.getAttributeList(node, 'rootids');
- return (rootids.indexOf('id' + id + '-' + propertyName) > -1);
- }
- },
-
-
-
- /**
- * gets the text of any child nodes with a class value
- *
- * @param {DOM Node} node
- * @param {String} propertyName
- * @return {String || null}
- */
- getValueClass: function(node, propertyType) {
- var context = this,
- children = [],
- out = [],
- child,
- x,
- i;
-
- children = modules.domUtils.getChildren( node );
-
- x = 0;
- i = children.length;
- while(x < i) {
- child = children[x];
- var value = null;
- if(modules.domUtils.hasAttributeValue(child, 'class', 'value')) {
- switch(propertyType) {
- case 'p':
- value = context.getPValue(child, false);
- break;
- case 'u':
- value = context.getUValue(child, false);
- break;
- case 'dt':
- value = context.getDTValue(child, '', null, false);
- break;
- }
- if(value) {
- out.push(modules.utils.trim(value));
- }
- }
- x++;
- }
- if(out.length > 0) {
- if(propertyType === 'p') {
- return modules.text.parseText( this.document, out.join(' '), this.options.textFormat);
- }
- if(propertyType === 'u') {
- return out.join('');
- }
- if(propertyType === 'dt') {
- return modules.dates.concatFragments(out,this.options.dateFormat).toString(this.options.dateFormat);
- }
- } else {
- return null;
- }
- },
-
-
- /**
- * returns a single string of the 'title' attr from all
- * the child nodes with the class 'value-title'
- *
- * @param {DOM Node} node
- * @return {String}
- */
- getValueTitle: function(node) {
- var out = [],
- items,
- i,
- x;
-
- items = modules.domUtils.getNodesByAttributeValue(node, 'class', 'value-title');
- x = 0;
- i = items.length;
- while(x < i) {
- if(modules.domUtils.hasAttribute(items[x], 'title')) {
- out.push(modules.domUtils.getAttribute(items[x], 'title'));
- }
- x++;
- }
- return out.join('');
- },
-
-
- /**
- * finds out whether a node has h-* class v1 and v2
- *
- * @param {DOM Node} node
- * @return {Boolean}
- */
- hasHClass: function(node){
- var classes = this.getUfClassNames(node);
- if(classes.root && classes.root.length > 0){
- return true;
- }else{
- return false;
- }
- },
-
-
- /**
- * get both the root and property class names from a node
- *
- * @param {DOM Node} node
- * @param {Array} ufNameArr
- * @return {Object}
- */
- getUfClassNames: function(node, ufNameArr) {
- var context = this,
- out = {
- 'root': [],
- 'properties': []
- },
- classNames,
- key,
- items,
- item,
- i,
- x,
- z,
- y,
- map,
- prop,
- propName,
- v2Name,
- impiedRel,
- ufName;
-
- // don't get classes from excluded list of tags
- if(modules.domUtils.hasTagName(node, this.excludeTags) === false){
-
- // find classes for node
- classNames = modules.domUtils.getAttribute(node, 'class');
- if(classNames) {
- items = classNames.split(' ');
- x = 0;
- i = items.length;
- while(x < i) {
-
- item = modules.utils.trim(items[x]);
-
- // test for root prefix - v2
- if(modules.utils.startWith(item, context.rootPrefix)) {
- if(out.root.indexOf(item) === -1){
- out.root.push(item);
- }
- out.typeVersion = 'v2';
- }
-
- // test for property prefix - v2
- z = context.propertyPrefixes.length;
- while(z--) {
- if(modules.utils.startWith(item, context.propertyPrefixes[z])) {
- out.properties.push([item,'v2']);
- }
- }
-
- // test for mapped root classnames v1
- for(key in modules.maps) {
- if(modules.maps.hasOwnProperty(key)) {
- // only add a root once
- if(modules.maps[key].root === item && out.root.indexOf(key) === -1) {
- // if root map has subTree set to true
- // test to see if we should create a property or root
- if(modules.maps[key].subTree) {
- out.properties.push(['p-' + modules.maps[key].root, 'v1']);
- } else {
- out.root.push(key);
- if(!out.typeVersion){
- out.typeVersion = 'v1';
- }
- }
- }
- }
- }
-
-
- // test for mapped property classnames v1
- if(ufNameArr){
- for (var a = 0; a < ufNameArr.length; a++) {
- ufName = ufNameArr[a];
- // get mapped property v1 microformat
- map = context.getMapping(ufName);
- if(map) {
- for(key in map.properties) {
- if (map.properties.hasOwnProperty(key)) {
-
- prop = map.properties[key];
- propName = (prop.map) ? prop.map : 'p-' + key;
-
- if(key === item) {
- if(prop.uf) {
- // loop all the classList make sure
- // 1. this property is a root
- // 2. that there is not already an equivalent v2 property i.e. url and u-url on the same element
- y = 0;
- while(y < i) {
- v2Name = context.getV2RootName(items[y]);
- // add new root
- if(prop.uf.indexOf(v2Name) > -1 && out.root.indexOf(v2Name) === -1) {
- out.root.push(v2Name);
- out.typeVersion = 'v1';
- }
- y++;
- }
- //only add property once
- if(out.properties.indexOf(propName) === -1) {
- out.properties.push([propName,'v1']);
- }
- } else {
- if(out.properties.indexOf(propName) === -1) {
- out.properties.push([propName,'v1']);
- }
- }
- }
- }
-
- }
- }
- }
-
- }
-
- x++;
-
- }
- }
- }
-
-
- // finds any alt rel=* mappings for a given node/microformat
- if(ufNameArr && this.findRelImpied){
- for (var b = 0; b < ufNameArr.length; b++) {
- ufName = ufNameArr[b];
- impiedRel = this.findRelImpied(node, ufName);
- if(impiedRel && out.properties.indexOf(impiedRel) === -1) {
- out.properties.push([impiedRel, 'v1']);
- }
- }
- }
-
-
- //if(out.root.length === 1 && out.properties.length === 1) {
- // if(out.root[0].replace('h-','') === this.removePropPrefix(out.properties[0][0])) {
- // out.typeVersion = 'v2';
- // }
- //}
-
- return out;
- },
-
-
- /**
- * given a v1 or v2 root name, return mapping object
- *
- * @param {String} name
- * @return {Object || null}
- */
- getMapping: function(name) {
- var key;
- for(key in modules.maps) {
- if(modules.maps[key].root === name || key === name) {
- return modules.maps[key];
- }
- }
- return null;
- },
-
-
- /**
- * given a v1 root name returns a v2 root name i.e. vcard >>> h-card
- *
- * @param {String} name
- * @return {String || null}
- */
- getV2RootName: function(name) {
- var key;
- for(key in modules.maps) {
- if(modules.maps[key].root === name) {
- return key;
- }
- }
- return null;
- },
-
-
- /**
- * whether a property is the right microformats version for its root type
- *
- * @param {String} typeVersion
- * @param {String} propertyVersion
- * @return {Boolean}
- */
- isAllowedPropertyVersion: function(typeVersion, propertyVersion){
- if(this.options.overlappingVersions === true){
- return true;
- }else{
- return (typeVersion === propertyVersion);
- }
- },
-
-
- /**
- * creates a blank microformats object
- *
- * @param {String} name
- * @param {String} value
- * @return {Object}
- */
- createUfObject: function(names, typeVersion, value) {
- var out = {};
-
- // is more than just whitespace
- if(value && modules.utils.isOnlyWhiteSpace(value) === false) {
- out.value = value;
- }
- // add type i.e. ["h-card", "h-org"]
- if(modules.utils.isArray(names)) {
- out.type = names;
- } else {
- out.type = [names];
- }
- out.properties = {};
- // metadata properties for parsing
- out.typeVersion = typeVersion;
- out.times = [];
- out.dates = [];
- out.altValue = null;
-
- return out;
- },
-
-
- /**
- * removes unwanted microformats property before output
- *
- * @param {Object} microformat
- */
- cleanUfObject: function( microformat ) {
- delete microformat.times;
- delete microformat.dates;
- delete microformat.typeVersion;
- delete microformat.altValue;
- return microformat;
- },
-
-
-
- /**
- * removes microformat property prefixes from text
- *
- * @param {String} text
- * @return {String}
- */
- removePropPrefix: function(text) {
- var i;
-
- i = this.propertyPrefixes.length;
- while(i--) {
- var prefix = this.propertyPrefixes[i];
- if(modules.utils.startWith(text, prefix)) {
- text = text.substr(prefix.length);
- }
- }
- return text;
- },
-
-
- /**
- * expands all relative URLs to absolute ones where it can
- *
- * @param {DOM Node} node
- * @param {String} attrName
- * @param {String} baseUrl
- */
- expandURLs: function(node, attrName, baseUrl){
- var i,
- nodes,
- attr;
-
- nodes = modules.domUtils.getNodesByAttribute(node, attrName);
- i = nodes.length;
- while (i--) {
- try{
- // the url parser can blow up if the format is not right
- attr = modules.domUtils.getAttribute(nodes[i], attrName);
- if(attr && attr !== '' && baseUrl !== '' && attr.indexOf('://') === -1) {
- //attr = urlParser.resolve(baseUrl, attr);
- attr = modules.url.resolve(attr, baseUrl);
- modules.domUtils.setAttribute(nodes[i], attrName, attr);
- }
- }catch(err){
- // do nothing - convert only the urls we can, leave the rest as they are
- }
- }
- },
-
-
-
- /**
- * merges passed and default options -single level clone of properties
- *
- * @param {Object} options
- */
- mergeOptions: function(options) {
- var key;
- for(key in options) {
- if(options.hasOwnProperty(key)) {
- this.options[key] = options[key];
- }
- }
- },
-
-
- /**
- * removes all rootid attributes
- *
- * @param {DOM Node} rootNode
- */
- removeRootIds: function(rootNode){
- var arr,
- i;
-
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'rootids');
- i = arr.length;
- while(i--) {
- modules.domUtils.removeAttribute(arr[i],'rootids');
- }
- },
-
-
- /**
- * removes all changes made to the DOM
- *
- * @param {DOM Node} rootNode
- */
- clearUpDom: function(rootNode){
- if(this.removeIncludes){
- this.removeIncludes(rootNode);
- }
- this.removeRootIds(rootNode);
- }
-
-
- };
-
-
- modules.Parser.prototype.constructor = modules.Parser;
-
- return modules;
-
-} (Modules || {}));
-
-
-
diff --git a/toolkit/components/microformats/test/lib/text.js b/toolkit/components/microformats/test/lib/text.js
deleted file mode 100644
index fe94dae0a..000000000
--- a/toolkit/components/microformats/test/lib/text.js
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- text
- Extracts text string from DOM nodes. Was created to extract text in a whitespace-normalized form.
- It works like a none-CSS aware version of IE's innerText function. DO NOT replace this module
- with functions such as textContent as it will reduce the quality of data provided to the API user.
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
- Dependencies utilities.js, domutils.js
-*/
-
-
-var Modules = (function (modules) {
-
-
- modules.text = {
-
- // normalised or whitespace or whitespacetrimmed
- textFormat: 'whitespacetrimmed',
-
- // block level tags, used to add line returns
- blockLevelTags: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'hr', 'pre', 'table',
- 'address', 'article', 'aside', 'blockquote', 'caption', 'col', 'colgroup', 'dd', 'div',
- 'dt', 'dir', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'header', 'hgroup', 'hr',
- 'li', 'map', 'menu', 'nav', 'optgroup', 'option', 'section', 'tbody', 'testarea',
- 'tfoot', 'th', 'thead', 'tr', 'td', 'ul', 'ol', 'dl', 'details'],
-
- // tags to exclude
- excludeTags: ['noframe', 'noscript', 'template', 'script', 'style', 'frames', 'frameset'],
-
-
- /**
- * parses the text from the DOM Node
- *
- * @param {DOM Node} node
- * @param {String} textFormat
- * @return {String}
- */
- parse: function(doc, node, textFormat){
- var out;
- this.textFormat = (textFormat)? textFormat : this.textFormat;
- if(this.textFormat === 'normalised'){
- out = this.walkTreeForText( node );
- if(out !== undefined){
- return this.normalise( doc, out );
- }else{
- return '';
- }
- }else{
- return this.formatText( doc, modules.domUtils.textContent(node), this.textFormat );
- }
- },
-
-
- /**
- * parses the text from a html string
- *
- * @param {DOM Document} doc
- * @param {String} text
- * @param {String} textFormat
- * @return {String}
- */
- parseText: function( doc, text, textFormat ){
- var node = modules.domUtils.createNodeWithText( 'div', text );
- return this.parse( doc, node, textFormat );
- },
-
-
- /**
- * parses the text from a html string - only for whitespace or whitespacetrimmed formats
- *
- * @param {String} text
- * @param {String} textFormat
- * @return {String}
- */
- formatText: function( doc, text, textFormat ){
- this.textFormat = (textFormat)? textFormat : this.textFormat;
- if(text){
- var out = '',
- regex = /(<([^>]+)>)/ig;
-
- out = text.replace(regex, '');
- if(this.textFormat === 'whitespacetrimmed') {
- out = modules.utils.trimWhitespace( out );
- }
-
- //return entities.decode( out, 2 );
- return modules.domUtils.decodeEntities( doc, out );
- }else{
- return '';
- }
- },
-
-
- /**
- * normalises whitespace in given text
- *
- * @param {String} text
- * @return {String}
- */
- normalise: function( doc, text ){
- text = text.replace( /&nbsp;/g, ' ') ; // exchanges html entity for space into space char
- text = modules.utils.collapseWhiteSpace( text ); // removes linefeeds, tabs and addtional spaces
- text = modules.domUtils.decodeEntities( doc, text ); // decode HTML entities
- text = text.replace( '–', '-' ); // correct dash decoding
- return modules.utils.trim( text );
- },
-
-
- /**
- * walks DOM tree parsing the text from DOM Nodes
- *
- * @param {DOM Node} node
- * @return {String}
- */
- walkTreeForText: function( node ) {
- var out = '',
- j = 0;
-
- if(node.tagName && this.excludeTags.indexOf( node.tagName.toLowerCase() ) > -1){
- return out;
- }
-
- // if node is a text node get its text
- if(node.nodeType && node.nodeType === 3){
- out += modules.domUtils.getElementText( node );
- }
-
- // get the text of the child nodes
- if(node.childNodes && node.childNodes.length > 0){
- for (j = 0; j < node.childNodes.length; j++) {
- var text = this.walkTreeForText( node.childNodes[j] );
- if(text !== undefined){
- out += text;
- }
- }
- }
-
- // if it's a block level tag add an additional space at the end
- if(node.tagName && this.blockLevelTags.indexOf( node.tagName.toLowerCase() ) !== -1){
- out += ' ';
- }
-
- return (out === '')? undefined : out ;
- }
-
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/url.js b/toolkit/components/microformats/test/lib/url.js
deleted file mode 100644
index 81ed9f29e..000000000
--- a/toolkit/components/microformats/test/lib/url.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- url
- Where possible use the modern window.URL API if its not available use the DOMParser method.
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
-
- modules.url = {
-
-
- /**
- * creates DOM objects needed to resolve URLs
- */
- init: function(){
- //this._domParser = new DOMParser();
- this._domParser = modules.domUtils.getDOMParser();
- // do not use a head tag it does not work with IE9
- this._html = '<base id="base" href=""></base><a id="link" href=""></a>';
- this._nodes = this._domParser.parseFromString( this._html, 'text/html' );
- this._baseNode = modules.domUtils.getElementById(this._nodes,'base');
- this._linkNode = modules.domUtils.getElementById(this._nodes,'link');
- },
-
-
- /**
- * resolves url to absolute version using baseUrl
- *
- * @param {String} url
- * @param {String} baseUrl
- * @return {String}
- */
- resolve: function(url, baseUrl) {
- // use modern URL web API where we can
- if(modules.utils.isString(url) && modules.utils.isString(baseUrl) && url.indexOf('://') === -1){
- // this try catch is required as IE has an URL object but no constuctor support
- // http://glennjones.net/articles/the-problem-with-window-url
- try {
- var resolved = new URL(url, baseUrl).toString();
- // deal with early Webkit not throwing an error - for Safari
- if(resolved === '[object URL]'){
- resolved = URI.resolve(baseUrl, url);
- }
- return resolved;
- }catch(e){
- // otherwise fallback to DOM
- if(this._domParser === undefined){
- this.init();
- }
-
- // do not use setAttribute it does not work with IE9
- this._baseNode.href = baseUrl;
- this._linkNode.href = url;
-
- // dont use getAttribute as it returns orginal value not resolved
- return this._linkNode.href;
- }
- }else{
- if(modules.utils.isString(url)){
- return url;
- }
- return '';
- }
- },
-
- };
-
- return modules;
-
-} (Modules || {}));
diff --git a/toolkit/components/microformats/test/lib/utilities.js b/toolkit/components/microformats/test/lib/utilities.js
deleted file mode 100644
index c54714811..000000000
--- a/toolkit/components/microformats/test/lib/utilities.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- Utilities
-
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var Modules = (function (modules) {
-
- modules.utils = {
-
- /**
- * is the object a string
- *
- * @param {Object} obj
- * @return {Boolean}
- */
- isString: function( obj ) {
- return typeof( obj ) === 'string';
- },
-
- /**
- * is the object a number
- *
- * @param {Object} obj
- * @return {Boolean}
- */
- isNumber: function( obj ) {
- return !isNaN(parseFloat( obj )) && isFinite( obj );
- },
-
-
- /**
- * is the object an array
- *
- * @param {Object} obj
- * @return {Boolean}
- */
- isArray: function( obj ) {
- return obj && !( obj.propertyIsEnumerable( 'length' ) ) && typeof obj === 'object' && typeof obj.length === 'number';
- },
-
-
- /**
- * is the object a function
- *
- * @param {Object} obj
- * @return {Boolean}
- */
- isFunction: function(obj) {
- return !!(obj && obj.constructor && obj.call && obj.apply);
- },
-
-
- /**
- * does the text start with a test string
- *
- * @param {String} text
- * @param {String} test
- * @return {Boolean}
- */
- startWith: function( text, test ) {
- return(text.indexOf(test) === 0);
- },
-
-
- /**
- * removes spaces at front and back of text
- *
- * @param {String} text
- * @return {String}
- */
- trim: function( text ) {
- if(text && this.isString(text)){
- return (text.trim())? text.trim() : text.replace(/^\s+|\s+$/g, '');
- }else{
- return '';
- }
- },
-
-
- /**
- * replaces a character in text
- *
- * @param {String} text
- * @param {Int} index
- * @param {String} character
- * @return {String}
- */
- replaceCharAt: function( text, index, character ) {
- if(text && text.length > index){
- return text.substr(0, index) + character + text.substr(index+character.length);
- }else{
- return text;
- }
- },
-
-
- /**
- * removes whitespace, tabs and returns from start and end of text
- *
- * @param {String} text
- * @return {String}
- */
- trimWhitespace: function( text ){
- if(text && text.length){
- var i = text.length,
- x = 0;
-
- // turn all whitespace chars at end into spaces
- while (i--) {
- if(this.isOnlyWhiteSpace(text[i])){
- text = this.replaceCharAt( text, i, ' ' );
- }else{
- break;
- }
- }
-
- // turn all whitespace chars at start into spaces
- i = text.length;
- while (x < i) {
- if(this.isOnlyWhiteSpace(text[x])){
- text = this.replaceCharAt( text, i, ' ' );
- }else{
- break;
- }
- x++;
- }
- }
- return this.trim(text);
- },
-
-
- /**
- * does text only contain whitespace characters
- *
- * @param {String} text
- * @return {Boolean}
- */
- isOnlyWhiteSpace: function( text ){
- return !(/[^\t\n\r ]/.test( text ));
- },
-
-
- /**
- * removes whitespace from text (leaves a single space)
- *
- * @param {String} text
- * @return {Sring}
- */
- collapseWhiteSpace: function( text ){
- return text.replace(/[\t\n\r ]+/g, ' ');
- },
-
-
- /**
- * does an object have any of its own properties
- *
- * @param {Object} obj
- * @return {Boolean}
- */
- hasProperties: function( obj ) {
- var key;
- for(key in obj) {
- if( obj.hasOwnProperty( key ) ) {
- return true;
- }
- }
- return false;
- },
-
-
- /**
- * a sort function - to sort objects in an array by a given property
- *
- * @param {String} property
- * @param {Boolean} reverse
- * @return {Int}
- */
- sortObjects: function(property, reverse) {
- reverse = (reverse) ? -1 : 1;
- return function (a, b) {
- a = a[property];
- b = b[property];
- if (a < b) {
- return reverse * -1;
- }
- if (a > b) {
- return reverse * 1;
- }
- return 0;
- };
- }
-
- };
-
- return modules;
-
-} (Modules || {}));
-
-
-
-
-
-
-
diff --git a/toolkit/components/microformats/test/lib/version.js b/toolkit/components/microformats/test/lib/version.js
deleted file mode 100644
index 371272cff..000000000
--- a/toolkit/components/microformats/test/lib/version.js
+++ /dev/null
@@ -1 +0,0 @@
- modules.version = '1.4.0';
diff --git a/toolkit/components/microformats/test/marionette/microformats_tester.py b/toolkit/components/microformats/test/marionette/microformats_tester.py
deleted file mode 100644
index 69fcb60ba..000000000
--- a/toolkit/components/microformats/test/marionette/microformats_tester.py
+++ /dev/null
@@ -1,170 +0,0 @@
-import threading
-import SimpleHTTPServer
-import SocketServer
-import BaseHTTPServer
-import urllib
-import urlparse
-import os
-import posixpath
-
-from marionette_driver.errors import NoSuchElementException
-from marionette_harness import MarionetteTestCase
-
-DEBUG = True
-
-# Example taken from mozilla-central/browser/components/loop/
-
-# XXX Once we're on a branch with bug 993478 landed, we may want to get
-# rid of this HTTP server and just use the built-in one from Marionette,
-# since there will less code to maintain, and it will be faster. We'll
-# need to consider whether this code wants to be shared with WebDriver tests
-# for other browsers, though.
-
-class ThreadingSimpleServer(SocketServer.ThreadingMixIn,
- BaseHTTPServer.HTTPServer):
- pass
-
-
-class HttpRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler, object):
- def __init__(self, *args):
- # set root to toolkit/components/microformats/
- self.root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.normpath(__file__))))
- super(HttpRequestHandler, self).__init__(*args)
-
- def log_message(self, format, *args, **kwargs):
- if DEBUG:
- super(HttpRequestHandler, self).log_message(format, *args, **kwargs)
-
- def translate_path(self, path):
- """Translate a /-separated PATH to the local filename syntax.
-
- Components that mean special things to the local file system
- (e.g. drive or directory names) are ignored. (XXX They should
- probably be diagnosed.)
-
- """
- # abandon query parameters
- path = path.split('?',1)[0]
- path = path.split('#',1)[0]
- # Don't forget explicit trailing slash when normalizing. Issue17324
- trailing_slash = path.rstrip().endswith('/')
- path = posixpath.normpath(urllib.unquote(path))
- words = path.split('/')
- words = filter(None, words)
- path = self.root
- for word in words:
- drive, word = os.path.splitdrive(word)
- head, word = os.path.split(word)
- if word in (os.curdir, os.pardir): continue
- path = os.path.join(path, word)
- if trailing_slash:
- path += '/'
- return path
-
-class BaseTestFrontendUnits(MarionetteTestCase):
-
- @classmethod
- def setUpClass(cls):
- super(BaseTestFrontendUnits, cls).setUpClass()
-
- # Port 0 means to select an arbitrary unused port
- cls.server = ThreadingSimpleServer(('', 0), HttpRequestHandler)
- cls.ip, cls.port = cls.server.server_address
-
- cls.server_thread = threading.Thread(target=cls.server.serve_forever)
- cls.server_thread.daemon = False
- cls.server_thread.start()
-
- @classmethod
- def tearDownClass(cls):
- cls.server.shutdown()
- cls.server_thread.join()
-
- # make sure everything gets GCed so it doesn't interfere with the next
- # test class. Even though this is class-static, each subclass gets
- # its own instance of this stuff.
- cls.server_thread = None
- cls.server = None
-
- def setUp(self):
- super(BaseTestFrontendUnits, self).setUp()
-
- # Unfortunately, enforcing preferences currently comes with the side
- # effect of launching and restarting the browser before running the
- # real functional tests. Bug 1048554 has been filed to track this.
- #
- # Note: when e10s is enabled by default, this pref can go away. The automatic
- # restart will also go away if this is still the only pref set here.
- self.marionette.enforce_gecko_prefs({
- "browser.tabs.remote.autostart": True
- })
-
- # This extends the timeout for find_element. We need this as the tests
- # take an amount of time to run after loading, which we have to wait for.
- self.marionette.timeout.implicit = 120
-
- self.marionette.timeout.page_load = 120
-
- # srcdir_path should be the directory relative to this file.
- def set_server_prefix(self, srcdir_path):
- self.server_prefix = urlparse.urljoin("http://localhost:" + str(self.port),
- srcdir_path)
-
- def check_page(self, page):
-
- self.marionette.navigate(urlparse.urljoin(self.server_prefix, page))
- try:
- self.marionette.find_element("id", 'complete')
- except NoSuchElementException:
- fullPageUrl = urlparse.urljoin(self.relPath, page)
-
- details = "%s: 1 failure encountered\n%s" % \
- (fullPageUrl,
- self.get_failure_summary(
- fullPageUrl, "Waiting for Completion",
- "Could not find the test complete indicator"))
-
- raise AssertionError(details)
-
- fail_node = self.marionette.find_element("css selector",
- '.failures > em')
- if fail_node.text == "0":
- return
-
- # This may want to be in a more general place triggerable by an env
- # var some day if it ends up being something we need often:
- #
- # If you have browser-based unit tests which work when loaded manually
- # but not from marionette, uncomment the two lines below to break
- # on failing tests, so that the browsers won't be torn down, and you
- # can use the browser debugging facilities to see what's going on.
- #from ipdb import set_trace
- #set_trace()
-
- raise AssertionError(self.get_failure_details(page))
-
- def get_failure_summary(self, fullPageUrl, testName, testError):
- return "TEST-UNEXPECTED-FAIL | %s | %s - %s" % (fullPageUrl, testName, testError)
-
- def get_failure_details(self, page):
- fail_nodes = self.marionette.find_elements("css selector",
- '.test.fail')
- fullPageUrl = urlparse.urljoin(self.relPath, page)
-
- details = ["%s: %d failure(s) encountered:" % (fullPageUrl, len(fail_nodes))]
-
- for node in fail_nodes:
- errorText = node.find_element("css selector", '.error').text
-
- # We have to work our own failure message here, as we could be reporting multiple failures.
- # XXX Ideally we'd also give the full test tree for <test name> - that requires walking
- # up the DOM tree.
-
- # Format: TEST-UNEXPECTED-FAIL | <filename> | <test name> - <test error>
- details.append(
- self.get_failure_summary(page,
- node.find_element("tag name", 'h2').text.split("\n")[0],
- errorText.split("\n")[0]))
- details.append(
- errorText)
- return "\n".join(details)
diff --git a/toolkit/components/microformats/test/marionette/test_interface.py b/toolkit/components/microformats/test/marionette/test_interface.py
deleted file mode 100644
index aa34ef1c2..000000000
--- a/toolkit/components/microformats/test/marionette/test_interface.py
+++ /dev/null
@@ -1,17 +0,0 @@
-# Code example copied from mozilla-central/browser/components/loop/
-# need to get this dir in the path so that we make the import work
-import os
-import sys
-sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'marionette'))
-
-from microformats_tester import BaseTestFrontendUnits
-
-
-class TestInterfaceUnits(BaseTestFrontendUnits):
-
- def setUp(self):
- super(TestInterfaceUnits, self).setUp()
- self.set_server_prefix("/test/interface-tests/")
-
- def test_units(self):
- self.check_page("index.html")
diff --git a/toolkit/components/microformats/test/marionette/test_modules.py b/toolkit/components/microformats/test/marionette/test_modules.py
deleted file mode 100644
index f2291259c..000000000
--- a/toolkit/components/microformats/test/marionette/test_modules.py
+++ /dev/null
@@ -1,17 +0,0 @@
-# Code example copied from mozilla-central/browser/components/loop/
-# need to get this dir in the path so that we make the import work
-import os
-import sys
-sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'marionette'))
-
-from microformats_tester import BaseTestFrontendUnits
-
-
-class TestModulesUnits(BaseTestFrontendUnits):
-
- def setUp(self):
- super(TestModulesUnits, self).setUp()
- self.set_server_prefix("/test/module-tests/")
-
- def test_units(self):
- self.check_page("index.html")
diff --git a/toolkit/components/microformats/test/marionette/test_standards.py b/toolkit/components/microformats/test/marionette/test_standards.py
deleted file mode 100644
index ec688fe78..000000000
--- a/toolkit/components/microformats/test/marionette/test_standards.py
+++ /dev/null
@@ -1,17 +0,0 @@
-# Code example copied from mozilla-central/browser/components/loop/
-# need to get this dir in the path so that we make the import work
-import os
-import sys
-sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'marionette')))
-
-from microformats_tester import BaseTestFrontendUnits
-
-
-class TestStandardsUnits(BaseTestFrontendUnits):
-
- def setUp(self):
- super(TestStandardsUnits, self).setUp()
- self.set_server_prefix("/test/standards-tests/")
-
- def test_units(self):
- self.check_page("index.html")
diff --git a/toolkit/components/microformats/test/module-tests/dates-test.js b/toolkit/components/microformats/test/module-tests/dates-test.js
deleted file mode 100644
index e5e034190..000000000
--- a/toolkit/components/microformats/test/module-tests/dates-test.js
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
-Unit test for dates
-*/
-
-assert = chai.assert;
-
-// Tests the private Modules.dates object
-// Modules.dates is unit tested as it has an interface access by other modules
-
-
-describe('Modules.dates', function() {
-
-
- it('hasAM', function(){
- assert.isTrue( Modules.dates.hasAM( '5am' ) );
- assert.isTrue( Modules.dates.hasAM( '5AM' ) );
- assert.isTrue( Modules.dates.hasAM( '5 am' ) );
- assert.isTrue( Modules.dates.hasAM( '5a.m.' ) );
- assert.isTrue( Modules.dates.hasAM( '5:20 a.m.' ) );
- assert.isFalse( Modules.dates.hasAM( '5pm' ) );
- });
-
-
- it('hasPM', function(){
- assert.isTrue( Modules.dates.hasPM( '5pm' ) );
- assert.isTrue( Modules.dates.hasPM( '5PM' ) );
- assert.isTrue( Modules.dates.hasPM( '5 pm' ) );
- assert.isTrue( Modules.dates.hasPM( '5p.m.' ) );
- assert.isTrue( Modules.dates.hasPM( '5:20 p.m.' ) );
- assert.isFalse( Modules.dates.hasPM( '5am' ) );
- });
-
-
- it('removeAMPM', function(){
- assert.equal( Modules.dates.removeAMPM( '5pm' ), '5' );
- assert.equal( Modules.dates.removeAMPM( '5 pm' ), '5 ' );
- assert.equal( Modules.dates.removeAMPM( '5p.m.' ), '5' );
- assert.equal( Modules.dates.removeAMPM( '5am' ), '5' );
- assert.equal( Modules.dates.removeAMPM( '5a.m.' ), '5' );
- assert.equal( Modules.dates.removeAMPM( '5' ), '5' );
- });
-
-
- it('isDuration', function(){
- assert.isTrue( Modules.dates.isDuration( 'PY17M' ) );
- assert.isTrue( Modules.dates.isDuration( 'PW12' ) );
- assert.isTrue( Modules.dates.isDuration( 'P0.5Y' ) );
- assert.isTrue( Modules.dates.isDuration( 'P3Y6M4DT12H30M5S' ) );
- assert.isFalse( Modules.dates.isDuration( '2015-01-23T13:45' ) );
- assert.isFalse( Modules.dates.isDuration( '2015-01-23 13:45' ) );
- assert.isFalse( Modules.dates.isDuration( '20150123T1345' ) );
- });
-
-
- it('isTime', function(){
- assert.isTrue( Modules.dates.isTime( '8:43' ) );
- assert.isTrue( Modules.dates.isTime( '08:43' ) );
- assert.isTrue( Modules.dates.isTime( '15:23:00:0567' ) );
- assert.isTrue( Modules.dates.isTime( '10:34pm' ) );
- assert.isTrue( Modules.dates.isTime( '10:34 p.m.' ) );
- assert.isTrue( Modules.dates.isTime( '+01:00:00' ) );
- assert.isTrue( Modules.dates.isTime( '-02:00' ) );
- assert.isTrue( Modules.dates.isTime( 'z15:00' ) );
- assert.isTrue( Modules.dates.isTime( '0843' ) );
- assert.isFalse( Modules.dates.isTime( 'P3Y6M4DT12H30M5S' ) );
- assert.isFalse( Modules.dates.isTime( '2015-01-23T13:45' ) );
- assert.isFalse( Modules.dates.isTime( '2015-01-23 13:45' ) );
- assert.isFalse( Modules.dates.isTime( '20150123T1345' ) );
- assert.isFalse( Modules.dates.isTime( 'abc' ) );
- assert.isFalse( Modules.dates.isTime( '12345' ) );
- });
-
-
- it('parseAmPmTime', function(){
- assert.equal( Modules.dates.parseAmPmTime( '5am' ), '05' );
- assert.equal( Modules.dates.parseAmPmTime( '12pm' ), '12' );
- assert.equal( Modules.dates.parseAmPmTime( '5a.m.' ), '05' );
- assert.equal( Modules.dates.parseAmPmTime( '5pm' ), '17' );
- assert.equal( Modules.dates.parseAmPmTime( '5:34pm' ), '17:34' );
- assert.equal( Modules.dates.parseAmPmTime( '5:04pm' ), '17:04' );
- assert.equal( Modules.dates.parseAmPmTime( '05:34:00' ), '05:34:00' );
- assert.equal( Modules.dates.parseAmPmTime( '05:34:00' ), '05:34:00' );
- assert.equal( Modules.dates.parseAmPmTime( '1:52:04pm' ), '13:52:04' );
- });
-
-
- it('dateTimeUnion', function(){
- assert.equal( Modules.dates.dateTimeUnion( '2015-01-23', '05:34:00', 'HTML5' ).toString('HTML5'), '2015-01-23 05:34:00' );
- assert.equal( Modules.dates.dateTimeUnion( '2015-01-23', '05:34', 'HTML5' ).toString('HTML5'), '2015-01-23 05:34' );
- assert.equal( Modules.dates.dateTimeUnion( '2015-01-23', '05', 'HTML5' ).toString('HTML5'), '2015-01-23 05' );
- assert.equal( Modules.dates.dateTimeUnion( '2009-06-26T19:00', '2200', 'HTML5' ).toString('HTML5'), '2009-06-26 22:00' );
-
- assert.equal( Modules.dates.dateTimeUnion( '2015-01-23', '', 'HTML5' ).toString('HTML5'), '2015-01-23' );
- assert.equal( Modules.dates.dateTimeUnion( '', '', 'HTML5' ).toString('HTML5'), '' );
- });
-
-
- it('concatFragments', function(){
- assert.equal( Modules.dates.concatFragments( ['2015-01-23', '05:34:00'], 'HTML5' ).toString('HTML5'), '2015-01-23 05:34:00' );
- assert.equal( Modules.dates.concatFragments( ['05:34:00', '2015-01-23'], 'HTML5' ).toString('HTML5'), '2015-01-23 05:34:00' );
- assert.equal( Modules.dates.concatFragments( ['2015-01-23T05:34:00'], 'HTML5' ).toString('HTML5'), '2015-01-23 05:34:00' );
- assert.equal( Modules.dates.concatFragments( ['2015-01-23', '05:34:00', 'z'], 'HTML5' ).toString('HTML5'), '2015-01-23 05:34:00Z' );
- assert.equal( Modules.dates.concatFragments( ['2015-01-23', '05:34', '-01'], 'HTML5' ).toString('HTML5'), '2015-01-23 05:34-01' );
- assert.equal( Modules.dates.concatFragments( ['2015-01-23', '05:34', '-01:00'], 'HTML5' ).toString('HTML5'), '2015-01-23 05:34-01:00' );
- assert.equal( Modules.dates.concatFragments( ['2015-01-23', '05:34-01:00'], 'HTML5' ).toString('HTML5'), '2015-01-23 05:34-01:00' );
-
- });
-
-
-
-
-
-});
diff --git a/toolkit/components/microformats/test/module-tests/domutils-test.js b/toolkit/components/microformats/test/module-tests/domutils-test.js
deleted file mode 100644
index 5d3f036a9..000000000
--- a/toolkit/components/microformats/test/module-tests/domutils-test.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
-Unit test for domutils
-*/
-
-assert = chai.assert;
-
-
-// Tests the private Modules.domUtils object
-// Modules.domUtils is unit tested as it has an interface access by other modules
-
-
-describe('Modules.domutils', function() {
-
-
- it('ownerDocument', function(){
- var node = document.createElement('div');
- assert.equal( Modules.domUtils.ownerDocument( node ).nodeType, 9);
- });
-
-
- it('innerHTML', function(){
- var html = '<a href="http://glennjones.net">Glenn Jones</a>',
- node = document.createElement('div');
-
- node.innerHTML = html;
- assert.equal( Modules.domUtils.innerHTML( node ), html );
- });
-
-
- it('hasAttribute', function(){
- var node = document.createElement('a');
-
- node.href = 'http://glennjones.net';
- assert.isTrue( Modules.domUtils.hasAttribute( node, 'href' ) );
- assert.isFalse( Modules.domUtils.hasAttribute( node, 'class' ) );
- });
-
-
- it('hasAttributeValue', function(){
- var node = document.createElement('a');
-
- node.href = 'http://glennjones.net';
- assert.isTrue( Modules.domUtils.hasAttributeValue( node, 'href', 'http://glennjones.net' ) );
- assert.isFalse( Modules.domUtils.hasAttributeValue( node, 'href', 'http://example.net' ) );
- assert.isFalse( Modules.domUtils.hasAttributeValue( node, 'class', 'test' ) );
- });
-
-
- it('getAttribute', function(){
- var node = document.createElement('a');
-
- node.href = 'http://glennjones.net';
- assert.equal( Modules.domUtils.getAttribute( node, 'href' ), 'http://glennjones.net' );
- });
-
-
- it('setAttribute', function(){
- var node = document.createElement('a');
-
- Modules.domUtils.setAttribute(node, 'href', 'http://glennjones.net')
- assert.equal( Modules.domUtils.getAttribute( node, 'href' ), 'http://glennjones.net' );
- });
-
-
- it('removeAttribute', function(){
- var node = document.createElement('a');
-
- node.href = 'http://glennjones.net';
- Modules.domUtils.removeAttribute(node, 'href')
- assert.isFalse( Modules.domUtils.hasAttribute( node, 'href' ) );
- });
-
-
- it('getAttributeList', function(){
- var node = document.createElement('a');
-
- node.rel = 'next';
- assert.deepEqual( Modules.domUtils.getAttributeList( node, 'rel'), ['next'] );
- node.rel = 'next bookmark';
- assert.deepEqual( Modules.domUtils.getAttributeList( node, 'rel'), ['next','bookmark'] );
- });
-
-
- it('hasAttributeValue', function(){
- var node = document.createElement('a');
-
- node.href = 'http://glennjones.net';
- node.rel = 'next bookmark';
- assert.isTrue( Modules.domUtils.hasAttributeValue( node, 'href', 'http://glennjones.net' ) );
- assert.isFalse( Modules.domUtils.hasAttributeValue( node, 'href', 'http://codebits.glennjones.net' ) );
- assert.isFalse( Modules.domUtils.hasAttributeValue( node, 'class', 'p-name' ) );
- assert.isTrue( Modules.domUtils.hasAttributeValue( node, 'rel', 'bookmark' ) );
- assert.isFalse( Modules.domUtils.hasAttributeValue( node, 'rel', 'previous' ) );
- });
-
-
- it('getNodesByAttribute', function(){
- var node = document.createElement('ul');
- node.innerHTML = '<li class="h-card">one</li><li>two</li><li class="h-card">three</li>';
-
- assert.equal( Modules.domUtils.getNodesByAttribute( node, 'class' ).length, 2 );
- assert.equal( Modules.domUtils.getNodesByAttribute( node, 'href' ).length, 0 );
- });
-
-
- it('getNodesByAttributeValue', function(){
- var node = document.createElement('ul');
- node.innerHTML = '<li class="h-card">one</li><li>two</li><li class="h-card">three</li><li class="p-name">four</li>';
-
- assert.equal( Modules.domUtils.getNodesByAttributeValue( node, 'class', 'h-card' ).length, 2 );
- assert.equal( Modules.domUtils.getNodesByAttributeValue( node, 'class', 'p-name' ).length, 1 );
- assert.equal( Modules.domUtils.getNodesByAttributeValue( node, 'class', 'u-url' ).length, 0 );
- });
-
-
- it('getAttrValFromTagList', function(){
- var node = document.createElement('a');
-
- node.href = 'http://glennjones.net';
-
- assert.equal( Modules.domUtils.getAttrValFromTagList( node, ['a','area'], 'href' ), 'http://glennjones.net' );
- assert.equal( Modules.domUtils.getAttrValFromTagList( node, ['a','area'], 'class' ), null );
- assert.equal( Modules.domUtils.getAttrValFromTagList( node, ['p'], 'href' ), null );
- });
-
-
- it('getSingleDescendant', function(){
- var html = '<a class="u-url" href="http://glennjones.net">Glenn Jones</a>',
- node = document.createElement('div');
-
- node.innerHTML = html,
-
- // one instance of a element
- assert.equal( Modules.domUtils.getSingleDescendant( node ).outerHTML, html );
-
- // two instances of a element
- node.appendChild(document.createElement('a'));
- assert.equal( Modules.domUtils.getSingleDescendant( node ), null );
-
- });
-
-
- it('getSingleDescendantOfType', function(){
- var html = '<a class="u-url" href="http://glennjones.net">Glenn Jones</a>',
- node = document.createElement('div');
-
- node.innerHTML = html,
-
- // one instance of a element
- assert.equal( Modules.domUtils.getSingleDescendantOfType( node, ['a', 'link']).outerHTML, html );
- assert.equal( Modules.domUtils.getSingleDescendantOfType( node, ['img','area']), null );
-
- node.appendChild(document.createElement('p'));
- assert.equal( Modules.domUtils.getSingleDescendantOfType( node, ['a', 'link']).outerHTML, html );
-
- // two instances of a element
- node.appendChild(document.createElement('a'));
- assert.equal( Modules.domUtils.getSingleDescendantOfType( node, ['a', 'link']), null );
-
- });
-
-
- it('appendChild', function(){
- var node = document.createElement('div'),
- child = document.createElement('a');
-
- Modules.domUtils.appendChild( node, child );
- assert.equal( node.innerHTML, '<a></a>' );
- });
-
-
- it('removeChild', function(){
- var node = document.createElement('div'),
- child = document.createElement('a');
-
- node.appendChild(child)
-
- assert.equal( node.innerHTML, '<a></a>' );
- Modules.domUtils.removeChild( child );
- assert.equal( node.innerHTML, '' );
- });
-
-
- it('clone', function(){
- var node = document.createElement('div');
-
- node.innerHTML = 'text content';
- assert.equal( Modules.domUtils.clone( node ).outerHTML, '<div>text content</div>' );
- });
-
-
- it('getElementText', function(){
- assert.equal( Modules.domUtils.getElementText( {} ), '' );
- });
-
-
- it('getNodePath', function(){
- var node = document.createElement('ul');
- node.innerHTML = '<div><ul><li class="h-card">one</li><li>two</li><li class="h-card">three</li><li class="p-name">four</li></ul></div>';
- var child = node.querySelector('.p-name');
-
- assert.deepEqual( Modules.domUtils.getNodePath( child ), [0,0,3] );
- });
-
-
-});
diff --git a/toolkit/components/microformats/test/module-tests/html-test.js b/toolkit/components/microformats/test/module-tests/html-test.js
deleted file mode 100644
index cd06c7b7f..000000000
--- a/toolkit/components/microformats/test/module-tests/html-test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
-Unit test for html
-*/
-
-assert = chai.assert;
-
-// Tests the private Modules.html object
-// Modules.html is unit tested as it has an interface access by other modules
-
-describe('Modules.html', function() {
-
-
- it('parse', function(){
- var html = '<a href="http://glennjones.net">Glenn Jones</a>',
- bloghtml = '<section id="content" class="body"><ol id="posts-list" class="h-feed"><li><article class="h-entry"><header><h2 class="p-namee"><a href="#" rel="bookmark" title="Permalink to this POST TITLE">This be the title</a></h2></header><footer class="post-info"><abbr class="dt-published" title="2005-10-10T14:07:00-07:00">10th October 2005</abbr><address class="h-card p-author">By <a class="u-url p-name" href="#">Enrique Ramírez</a></address></footer><div class="e-content"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque venenatis nunc vitae libero iaculis elementum. Nullam et justo <a href="#">non sapien</a> dapibus blandit nec et leo. Ut ut malesuada tellus.</p></div></article></li></ol></section>',
- node = document.createElement('div');
-
- node.innerHTML = html;
- assert.equal(Modules.html.parse( node ), html );
-
- // make sure excludes 'data-include' marked items
- var child = document.createElement('p');
- child.setAttribute('data-include', 'true');
- node.appendChild(child);
- assert.equal( Modules.html.parse( node ), html );
-
- node = document.createElement('div');
- node.innerHTML = bloghtml;
- assert.equal( Modules.html.parse( node ), bloghtml );
-
- node = document.createElement('div');
- assert.equal( Modules.html.parse( node ), '' );
-
- child = document.createElement('br');
- node.appendChild(child);
- assert.equal( Modules.html.parse( node ), '<br />' );
-
- node = document.createComment('test comment');
- assert.equal( Modules.html.parse( node ), '' );
-
- });
-
-
-
-
-
-
-
-
-});
diff --git a/toolkit/components/microformats/test/module-tests/index.html b/toolkit/components/microformats/test/module-tests/index.html
deleted file mode 100644
index 0eb3c2040..000000000
--- a/toolkit/components/microformats/test/module-tests/index.html
+++ /dev/null
@@ -1,76 +0,0 @@
-<html><head><title>Mocha</title>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<link rel="stylesheet" href="../static/css/mocha.css" />
-<script src="../static/javascript/chai.js"></script>
-<script src="../static/javascript/mocha.js"></script>
-<link rel="stylesheet" href="../static/css/mocha-custom.css" />
-<link rel="icon" type="image/png" id="favicon" href="chrome://branding/content/icon32.png"/>
-<script src="../static/javascript/DOMParser.js"></script>
-
-<script data-cover src="../lib/utilities.js"></script>
-<script data-cover src="../lib/domutils.js"></script>
-<script data-cover src="../lib/url.js"></script>
-<script data-cover src="../lib/html.js"></script>
-<script data-cover src="../lib/text.js"></script>
-<script data-cover src="../lib/dates.js"></script>
-<script data-cover src="../lib/isodate.js"></script>
-
-<script>
-var uncaughtError;
-
-window.addEventListener("error", function(error) {
-uncaughtError = error;
-});
-
-var consoleWarn = console.warn;
-var caughtWarnings = [];
-
-console.warn = function() {
-var args = Array.slice(arguments);
-caughtWarnings.push(args);
-consoleWarn.apply(console, args);
-};
-</script>
-
-<script>
-chai.config.includeStack = true;
-mocha.setup({ui: 'bdd', timeout: 10000});
-</script>
-
-
-<script src="../module-tests/dates-test.js"></script>
-<script src="../module-tests/domUtils-test.js"></script>
-<script src="../module-tests/html-test.js"></script>
-<script src="../module-tests/isodate-test.js"></script>
-<script src="../module-tests/text-test.js"></script>
-
-<script src="../module-tests/url-test.js"></script>
-
-<script src="../module-tests/utilities-test.js"></script>
-
-</head><body>
-<h3 class="capitalize">Microformats-shiv: module tests</h3>
-<div id="mocha"></div>
-</body>
-<script>
-describe("Uncaught Error Check", function() {
-it("should load the tests without errors", function() {
-chai.expect(uncaughtError && uncaughtError.message).to.be.undefined;
-});
-});
-
-describe("Unexpected Warnings Check", function() {
-it("should long only the warnings we expect", function() {
-chai.expect(caughtWarnings.length).to.eql(0);
-});
-});
-
-mocha.run(function () {
-var completeNode = document.createElement("p");
-completeNode.setAttribute("id", "complete");
-completeNode.appendChild(document.createTextNode("Complete"));
-document.getElementById("mocha").appendChild(completeNode);
-});
-
-</script>
-</body></html>
diff --git a/toolkit/components/microformats/test/module-tests/isodate-test.js b/toolkit/components/microformats/test/module-tests/isodate-test.js
deleted file mode 100644
index 5f081f81c..000000000
--- a/toolkit/components/microformats/test/module-tests/isodate-test.js
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
-Unit test for dates
-*/
-
-assert = chai.assert;
-
-
-// Tests private Modules.ISODate object
-// Modules.ISODate is unit tested as it has an interface access by other modules
-
-
-describe('Modules.ISODates', function() {
-
-
-
- it('constructor', function(){
- assert.equal( new Modules.ISODate().toString('auto'), '' );
- assert.equal( new Modules.ISODate('2015-01-23T05:34:00', 'html5').toString('html5'), '2015-01-23 05:34:00' );
- assert.equal( new Modules.ISODate('2015-01-23T05:34:00', 'w3c').toString('w3c'), '2015-01-23T05:34:00' );
- assert.equal( new Modules.ISODate('2015-01-23T05:34:00', 'html5').toString('rfc3339'), '20150123T053400' );
- assert.equal( new Modules.ISODate('2015-01-23T05:34:00', 'auto').toString('auto'), '2015-01-23T05:34:00' );
- });
-
-
- it('parse', function(){
- assert.equal( new Modules.ISODate().parse('2015-01-23T05:34:00', 'html5').toString('html5'), '2015-01-23 05:34:00' );
- assert.equal( new Modules.ISODate().parse('2015-01-23T05:34:00', 'auto').toString('auto'), '2015-01-23T05:34:00' );
- assert.equal( new Modules.ISODate().parse('2015-01-23t05:34:00', 'auto').toString('auto'), '2015-01-23t05:34:00' );
-
- assert.equal( new Modules.ISODate().parse('2015-01-23t05:34:00Z', 'auto').toString('auto'), '2015-01-23t05:34:00Z' );
- assert.equal( new Modules.ISODate().parse('2015-01-23t05:34:00z', 'auto').toString('auto'), '2015-01-23t05:34:00z' );
- assert.equal( new Modules.ISODate().parse('2015-01-23 05:34:00Z', 'auto').toString('auto'), '2015-01-23 05:34:00Z' );
- assert.equal( new Modules.ISODate().parse('2015-01-23 05:34', 'auto').toString('auto'), '2015-01-23 05:34' );
- assert.equal( new Modules.ISODate().parse('2015-01-23 05', 'auto').toString('auto'), '2015-01-23 05' );
-
- assert.equal( new Modules.ISODate().parse('2015-01-23 05:34+01:00', 'auto').toString('auto'), '2015-01-23 05:34+01:00' );
- assert.equal( new Modules.ISODate().parse('2015-01-23 05:34-01:00', 'auto').toString('auto'), '2015-01-23 05:34-01:00' );
- assert.equal( new Modules.ISODate().parse('2015-01-23 05:34-01', 'auto').toString('auto'), '2015-01-23 05:34-01' );
-
-
- assert.equal( new Modules.ISODate().parse('2015-01-23', 'auto').toString('auto'), '2015-01-23' );
- // TODO support for importing rfc3339 profile dates
- // assert.equal( new Modules.ISODate().parse('20150123t0534', 'auto').toString('auto'), '2015-01-23 05:34' );
- });
-
-
- it('parseDate', function(){
- assert.equal( new Modules.ISODate().parseDate('2015-01-23T05:34:00', 'html5'), '2015-01-23' );
- assert.equal( new Modules.ISODate().parseDate('2015-01-23', 'auto'), '2015-01-23' );
- assert.equal( new Modules.ISODate().parseDate('2015-01', 'auto'), '2015-01' );
- assert.equal( new Modules.ISODate().parseDate('2015', 'auto'), '2015' );
- assert.equal( new Modules.ISODate().parseDate('2015-134', 'auto'), '2015-134' );
- });
-
-
- it('parseTime', function(){
- assert.equal( new Modules.ISODate().parseTime('05:34:00.1267', 'html5'), '05:34:00.1267' );
- assert.equal( new Modules.ISODate().parseTime('05:34:00', 'html5'), '05:34:00' );
- assert.equal( new Modules.ISODate().parseTime('05:34', 'html5'), '05:34' );
- assert.equal( new Modules.ISODate().parseTime('05', 'html5'), '05' );
- });
-
- it('parseTimeZone', function(){
- var date = new Modules.ISODate();
- date.parseTime('14:00');
- assert.equal( date.parseTimeZone('-01:00', 'auto'), '14:00-01:00' );
-
- date.clear();
- date.parseTime('14:00');
- assert.equal( date.parseTimeZone('-01', 'auto'), '14:00-01' );
-
- date.clear();
- date.parseTime('14:00');
- assert.equal( date.parseTimeZone('+01:00', 'auto').toString('auto'), '14:00+01:00' );
-
- date.clear();
- date.parseTime('15:00');
- assert.equal( date.parseTimeZone('Z', 'auto').toString('auto'), '15:00Z' );
-
- date.clear();
- date.parseTime('16:00');
- assert.equal( date.parseTimeZone('z', 'auto'), '16:00z' );
-
- });
-
-
-
- it('toString', function(){
- var date = new Modules.ISODate();
- date.parseTime('05:34:00.1267');
-
- assert.equal( date.toString('html5'), '05:34:00.1267' );
- });
-
-
- it('toTimeString', function(){
- var date = new Modules.ISODate();
- date.parseTime('05:34:00.1267');
-
- assert.equal( date.toTimeString('html5'), '05:34:00.1267' );
- });
-
-
- it('hasFullDate', function(){
- var dateEmpty = new Modules.ISODate(),
- date = new Modules.ISODate('2015-01-23T05:34:00');
-
- assert.isFalse( dateEmpty.hasFullDate() );
- assert.isTrue( date.hasFullDate() );
- });
-
-
- it('hasDate', function(){
- var dateEmpty = new Modules.ISODate(),
- date = new Modules.ISODate('2015-01-23');
-
- assert.isFalse( dateEmpty.hasDate() );
- assert.isTrue( date.hasDate() );
- });
-
-
- it('hasTime', function(){
- var dateEmpty = new Modules.ISODate(),
- date = new Modules.ISODate();
-
- date.parseTime('12:34');
-
- assert.isFalse( dateEmpty.hasTime() );
- assert.isTrue( date.hasTime() );
- });
-
-
- it('hasTimeZone', function(){
- var dateEmpty = new Modules.ISODate(),
- date = new Modules.ISODate();
-
- date.parseTime('12:34'),
- date.parseTimeZone('-01:00');
-
- assert.isFalse( dateEmpty.hasTimeZone() );
- assert.isTrue( date.hasTimeZone() );
- });
-
-
-});
diff --git a/toolkit/components/microformats/test/module-tests/text-test.js b/toolkit/components/microformats/test/module-tests/text-test.js
deleted file mode 100644
index f1f2e775c..000000000
--- a/toolkit/components/microformats/test/module-tests/text-test.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-Unit test for text
-*/
-
-assert = chai.assert;
-
-// Tests the private Modules.text object
-// Modules.text is unit tested as it has an interface access by other modules
-
-
-describe('Modules.text', function() {
-
-
- it('parse', function(){
- var html = '\n <a href="http://glennjones.net">Glenn\n Jones \n</a> \n',
- node = document.createElement('div');
-
- node.innerHTML = html;
- assert.equal( Modules.text.parse( document, node, 'whitespacetrimmed' ), 'Glenn\n Jones' );
- assert.equal( Modules.text.parse( document, node, 'whitespace' ), '\n Glenn\n Jones \n \n' );
- assert.equal( Modules.text.parse( document, node, 'normalised' ), 'Glenn Jones' );
-
- // exclude tags
- node.innerHTML = '<script>test</script>text';
- assert.equal( Modules.text.parse( document, node, 'normalised' ), 'text' );
-
- // block level
- node.innerHTML = '<p>test</p>text';
- //assert.equal( Modules.text.parse( document, node, 'normalised' ), 'test text' );
-
- // node with no text data
- node = document.createComment('test comment');
- assert.equal( Modules.text.parse( document, node, 'normalised' ), '' );
-
- });
-
-
- it('parseText', function(){
- var text = '\n <a href="http://glennjones.net">Glenn\n Jones \n</a> \n';
-
- // create DOM context first
- Modules.domUtils.getDOMContext( {} );
-
- assert.equal( Modules.text.parseText( document, text, 'whitespacetrimmed' ), 'Glenn\n Jones' );
- assert.equal( Modules.text.parseText( document, text, 'whitespace' ), '\n Glenn\n Jones \n \n' );
- assert.equal( Modules.text.parseText( document, text, 'normalised' ), 'Glenn Jones' );
- });
-
-
- it('formatText', function(){
- assert.equal( Modules.text.formatText( document, null, 'whitespacetrimmed' ), '' );
- });
-
-
-
-});
diff --git a/toolkit/components/microformats/test/module-tests/url-test.js b/toolkit/components/microformats/test/module-tests/url-test.js
deleted file mode 100644
index 788e8fdb5..000000000
--- a/toolkit/components/microformats/test/module-tests/url-test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
-Unit test for url
-*/
-
-assert = chai.assert;
-
-
-// Tests the private Modules.url object
-// Modules.url is unit tested as it has an interface access by other modules
-
-
-describe('Modules.url', function() {
-
- it('resolve', function(){
- assert.equal( Modules.url.resolve( 'docs/index.html', 'http://example.org' ), 'http://example.org/docs/index.html' );
- assert.equal( Modules.url.resolve( '../index.html', 'http://example.org/docs/' ), 'http://example.org/index.html' );
- assert.equal( Modules.url.resolve( '/', 'http://example.org/' ), 'http://example.org/' );
- assert.equal( Modules.url.resolve( 'http://glennjones.net/', 'http://example.org/' ), 'http://glennjones.net/' );
-
- assert.equal( Modules.url.resolve( undefined, 'http://example.org/' ), '' );
- assert.equal( Modules.url.resolve( undefined, undefined ), '' );
- assert.equal( Modules.url.resolve( 'http://glennjones.net/', undefined ), 'http://glennjones.net/' );
- });
-
-});
diff --git a/toolkit/components/microformats/test/module-tests/utilities-test.js b/toolkit/components/microformats/test/module-tests/utilities-test.js
deleted file mode 100644
index b37236a6b..000000000
--- a/toolkit/components/microformats/test/module-tests/utilities-test.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
-Unit test for utilities
-*/
-
-assert = chai.assert;
-
-// Tests the private Modules.utils object
-// Modules.utils is unit tested as it has an interface access by other modules
-
-
-describe('Modules.utilities', function() {
-
-
- it('isString', function(){
- assert.isTrue( Modules.utils.isString( 'abc' ) );
- assert.isFalse( Modules.utils.isString( 123 ) );
- assert.isFalse( Modules.utils.isString( 1.23 ) );
- assert.isFalse( Modules.utils.isString( {'abc': 'abc'} ) );
- assert.isFalse( Modules.utils.isString( ['abc'] ) );
- assert.isFalse( Modules.utils.isString( true ) );
- });
-
-
- it('isArray', function(){
- assert.isTrue( Modules.utils.isArray( ['abc'] ) );
- assert.isFalse( Modules.utils.isArray( 123 ) );
- assert.isFalse( Modules.utils.isArray( 1.23 ) );
- assert.isFalse( Modules.utils.isArray( 'abc' ) );
- assert.isFalse( Modules.utils.isArray( {'abc': 'abc'} ) );
- assert.isFalse( Modules.utils.isArray( true ) );
- });
-
-
- it('isNumber', function(){
- assert.isTrue( Modules.utils.isNumber( 123 ) );
- assert.isTrue( Modules.utils.isNumber( 1.23 ) );
- assert.isFalse( Modules.utils.isNumber( 'abc' ) );
- assert.isFalse( Modules.utils.isNumber( {'abc': 'abc'} ) );
- assert.isFalse( Modules.utils.isNumber( ['abc'] ) );
- assert.isFalse( Modules.utils.isNumber( true ) );
- });
-
-
- it('startWith', function(){
- assert.isTrue( Modules.utils.startWith( 'p-name', 'p-' ) );
- assert.isFalse( Modules.utils.startWith( 'p-name', 'name' ) );
- assert.isFalse( Modules.utils.startWith( 'p-name', 'u-' ) );
- });
-
-
- it('trim', function(){
- assert.equal( Modules.utils.trim( ' Glenn Jones ' ), 'Glenn Jones' );
- assert.equal( Modules.utils.trim( 'Glenn Jones' ), 'Glenn Jones' );
- assert.equal( Modules.utils.trim( undefined ), '' );
- });
-
-
- it('replaceCharAt', function(){
- assert.equal( Modules.utils.replaceCharAt( 'Glenn Jones', 5, '-' ), 'Glenn-Jones' );
- assert.equal( Modules.utils.replaceCharAt( 'Glenn Jones', 50, '-' ), 'Glenn Jones' );
- });
-
-
- it('isOnlyWhiteSpace', function(){
- assert.isTrue( Modules.utils.isOnlyWhiteSpace( ' ') );
- assert.isTrue( Modules.utils.isOnlyWhiteSpace( ' \n\r') );
- assert.isFalse( Modules.utils.isOnlyWhiteSpace( ' text\n\r') );
- });
-
-
- it('collapseWhiteSpace', function(){
- assert.equal( Modules.utils.collapseWhiteSpace( ' '), ' ' );
- assert.equal( Modules.utils.collapseWhiteSpace( ' \n\r'), ' ' );
- assert.equal( Modules.utils.collapseWhiteSpace( ' text\n\r'), ' text ' );
- });
-
-
- it('hasProperties', function(){
- assert.isTrue( Modules.utils.hasProperties( {name: 'glennjones'} ) );
- assert.isFalse( Modules.utils.hasProperties( {} ) );
- });
-
-
- it('sortObjects', function(){
- var arr = [{'name': 'one'},{'name': 'two'},{'name': 'three'},{'name': 'three'}];
-
- assert.deepEqual( arr.sort( Modules.utils.sortObjects( 'name', true ) ), [{"name":"two"},{"name":"three"},{'name': 'three'},{"name":"one"}] );
- assert.deepEqual( arr.sort( Modules.utils.sortObjects( 'name', false ) ), [{"name":"one"},{"name":"three"},{'name': 'three'},{"name":"two"}] );
- });
-
-
-
-});
diff --git a/toolkit/components/microformats/test/standards-tests/index.html b/toolkit/components/microformats/test/standards-tests/index.html
deleted file mode 100644
index 47f89f988..000000000
--- a/toolkit/components/microformats/test/standards-tests/index.html
+++ /dev/null
@@ -1,179 +0,0 @@
-<html><head><title>Mocha</title>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<link rel="stylesheet" href="../static/css/mocha.css" />
-<script src="../static/javascript/chai.js"></script>
-<script src="../static/javascript/mocha.js"></script>
-<link rel="stylesheet" href="../static/css/mocha-custom.css" />
-<link rel="icon" type="image/png" id="favicon" href="chrome://branding/content/icon32.png"/>
-
-<script src="../static/javascript/DOMParser.js"></script>
-
-<script data-cover src="../../microformat-shiv.js"></script>
-
-<script>
-var uncaughtError;
-
-window.addEventListener("error", function(error) {
-uncaughtError = error;
-});
-
-var consoleWarn = console.warn;
-var caughtWarnings = [];
-
-console.warn = function() {
-var args = Array.slice(arguments);
-caughtWarnings.push(args);
-consoleWarn.apply(console, args);
-};
-</script>
-
-<script>
-chai.config.includeStack = true;
-mocha.setup({ui: 'bdd', timeout: 10000});
-</script>
-
-<script src="../standards-tests/mf-mixed-h-card-mixedpropertries.js"></script>
-<script src="../standards-tests/mf-mixed-h-card-tworoots.js"></script>
-<script src="../standards-tests/mf-mixed-h-entry-mixedroots.js"></script>
-<script src="../standards-tests/mf-mixed-h-resume-mixedroots.js"></script>
-<script src="../standards-tests/mf-v1-adr-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v1-geo-abbrpattern.js"></script>
-<script src="../standards-tests/mf-v1-geo-hidden.js"></script>
-<script src="../standards-tests/mf-v1-geo-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v1-geo-valuetitleclass.js"></script>
-<script src="../standards-tests/mf-v1-hcalendar-ampm.js"></script>
-<script src="../standards-tests/mf-v1-hcalendar-attendees.js"></script>
-<script src="../standards-tests/mf-v1-hcalendar-combining.js"></script>
-<script src="../standards-tests/mf-v1-hcalendar-concatenate.js"></script>
-<script src="../standards-tests/mf-v1-hcalendar-time.js"></script>
-<script src="../standards-tests/mf-v1-hcard-email.js"></script>
-<script src="../standards-tests/mf-v1-hcard-format.js"></script>
-<script src="../standards-tests/mf-v1-hcard-hyperlinkedphoto.js"></script>
-<script src="../standards-tests/mf-v1-hcard-justahyperlink.js"></script>
-<script src="../standards-tests/mf-v1-hcard-justaname.js"></script>
-<script src="../standards-tests/mf-v1-hcard-multiple.js"></script>
-<script src="../standards-tests/mf-v1-hcard-name.js"></script>
-<script src="../standards-tests/mf-v1-hcard-single.js"></script>
-<script src="../standards-tests/mf-v1-hentry-summarycontent.js"></script>
-<script src="../standards-tests/mf-v1-hfeed-simple.js"></script>
-<script src="../standards-tests/mf-v1-hnews-all.js"></script>
-<script src="../standards-tests/mf-v1-hnews-minimum.js"></script>
-<script src="../standards-tests/mf-v1-hproduct-aggregate.js"></script>
-<script src="../standards-tests/mf-v1-hproduct-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v1-hresume-affiliation.js"></script>
-<script src="../standards-tests/mf-v1-hresume-contact.js"></script>
-<script src="../standards-tests/mf-v1-hresume-education.js"></script>
-<script src="../standards-tests/mf-v1-hresume-skill.js"></script>
-<script src="../standards-tests/mf-v1-hresume-work.js"></script>
-<script src="../standards-tests/mf-v1-hreview-item.js"></script>
-<script src="../standards-tests/mf-v1-hreview-vcard.js"></script>
-<script src="../standards-tests/mf-v1-hreview-aggregate-hcard.js"></script>
-<script src="../standards-tests/mf-v1-hreview-aggregate-justahyperlink.js"></script>
-<script src="../standards-tests/mf-v1-hreview-aggregate-vevent.js"></script>
-<script src="../standards-tests/mf-v1-includes-hcarditemref.js"></script>
-<script src="../standards-tests/mf-v1-includes-heventitemref.js"></script>
-<script src="../standards-tests/mf-v1-includes-hyperlink.js"></script>
-<script src="../standards-tests/mf-v1-includes-object.js"></script>
-<script src="../standards-tests/mf-v1-includes-table.js"></script>
-<script src="../standards-tests/mf-v2-h-adr-geo.js"></script>
-<script src="../standards-tests/mf-v2-h-adr-geourl.js"></script>
-<script src="../standards-tests/mf-v2-h-adr-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-adr-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v2-h-as-note-note.js"></script>
-<script src="../standards-tests/mf-v2-h-card-baseurl.js"></script>
-<script src="../standards-tests/mf-v2-h-card-childimplied.js"></script>
-<script src="../standards-tests/mf-v2-h-card-extendeddescription.js"></script>
-<script src="../standards-tests/mf-v2-h-card-hcard.js"></script>
-<script src="../standards-tests/mf-v2-h-card-horghcard.js"></script>
-<script src="../standards-tests/mf-v2-h-card-hyperlinkedphoto.js"></script>
-<script src="../standards-tests/mf-v2-h-card-impliedname.js"></script>
-<script src="../standards-tests/mf-v2-h-card-impliedphoto.js"></script>
-<script src="../standards-tests/mf-v2-h-card-impliedurl.js"></script>
-<script src="../standards-tests/mf-v2-h-card-justahyperlink.js"></script>
-<script src="../standards-tests/mf-v2-h-card-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-card-nested.js"></script>
-<script src="../standards-tests/mf-v2-h-card-p-property.js"></script>
-<script src="../standards-tests/mf-v2-h-card-relativeurls.js"></script>
-<script src="../standards-tests/mf-v2-h-entry-impliedvalue-nested.js"></script>
-<script src="../standards-tests/mf-v2-h-entry-justahyperlink.js"></script>
-<script src="../standards-tests/mf-v2-h-entry-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-entry-summarycontent.js"></script>
-<script src="../standards-tests/mf-v2-h-entry-u-property.js"></script>
-<script src="../standards-tests/mf-v2-h-entry-urlincontent.js"></script>
-<script src="../standards-tests/mf-v2-h-event-ampm.js"></script>
-<script src="../standards-tests/mf-v2-h-event-attendees.js"></script>
-<script src="../standards-tests/mf-v2-h-event-combining.js"></script>
-<script src="../standards-tests/mf-v2-h-event-concatenate.js"></script>
-<script src="../standards-tests/mf-v2-h-event-dates.js"></script>
-<script src="../standards-tests/mf-v2-h-event-dt-property.js"></script>
-<script src="../standards-tests/mf-v2-h-event-justahyperlink.js"></script>
-<script src="../standards-tests/mf-v2-h-event-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-event-time.js"></script>
-<script src="../standards-tests/mf-v2-h-feed-implied-title.js"></script>
-<script src="../standards-tests/mf-v2-h-feed-simple.js"></script>
-<script src="../standards-tests/mf-v2-h-geo-abbrpattern.js"></script>
-<script src="../standards-tests/mf-v2-h-geo-altitude.js"></script>
-<script src="../standards-tests/mf-v2-h-geo-hidden.js"></script>
-<script src="../standards-tests/mf-v2-h-geo-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-geo-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v2-h-geo-valuetitleclass.js"></script>
-<script src="../standards-tests/mf-v2-h-news-all.js"></script>
-<script src="../standards-tests/mf-v2-h-news-minimum.js"></script>
-<script src="../standards-tests/mf-v2-h-org-hyperlink.js"></script>
-<script src="../standards-tests/mf-v2-h-org-simple.js"></script>
-<script src="../standards-tests/mf-v2-h-org-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v2-h-product-aggregate.js"></script>
-<script src="../standards-tests/mf-v2-h-product-justahyperlink.js"></script>
-<script src="../standards-tests/mf-v2-h-product-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-product-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v2-h-recipe-all.js"></script>
-<script src="../standards-tests/mf-v2-h-recipe-minimum.js"></script>
-<script src="../standards-tests/mf-v2-h-resume-affiliation.js"></script>
-<script src="../standards-tests/mf-v2-h-resume-contact.js"></script>
-<script src="../standards-tests/mf-v2-h-resume-education.js"></script>
-<script src="../standards-tests/mf-v2-h-resume-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-resume-skill.js"></script>
-<script src="../standards-tests/mf-v2-h-resume-work.js"></script>
-<script src="../standards-tests/mf-v2-h-review-hyperlink.js"></script>
-<script src="../standards-tests/mf-v2-h-review-implieditem.js"></script>
-<script src="../standards-tests/mf-v2-h-review-item.js"></script>
-<script src="../standards-tests/mf-v2-h-review-justaname.js"></script>
-<script src="../standards-tests/mf-v2-h-review-photo.js"></script>
-<script src="../standards-tests/mf-v2-h-review-vcard.js"></script>
-<script src="../standards-tests/mf-v2-h-review-aggregate-hevent.js"></script>
-<script src="../standards-tests/mf-v2-h-review-aggregate-justahyperlink.js"></script>
-<script src="../standards-tests/mf-v2-h-review-aggregate-simpleproperties.js"></script>
-<script src="../standards-tests/mf-v2-rel-duplicate-rels.js"></script>
-<script src="../standards-tests/mf-v2-rel-license.js"></script>
-<script src="../standards-tests/mf-v2-rel-nofollow.js"></script>
-<script src="../standards-tests/mf-v2-rel-rel-urls.js"></script>
-<script src="../standards-tests/mf-v2-rel-varying-text-duplicate-rels.js"></script>
-<script src="../standards-tests/mf-v2-rel-xfn-all.js"></script>
-<script src="../standards-tests/mf-v2-rel-xfn-elsewhere.js"></script>
-</head><body>
-<h3 class="capitalize">Microformats-shiv: standards tests</h3>
-<p>Standards tests built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST). Downloaded from github repo: microformats/tests version v0.1.24</p>
-<div id="mocha"></div>
-</body>
-<script>
-describe("Uncaught Error Check", function() {
-it("should load the tests without errors", function() {
-chai.expect(uncaughtError && uncaughtError.message).to.be.undefined;
-});
-});
-
-describe("Unexpected Warnings Check", function() {
-it("should long only the warnings we expect", function() {
-chai.expect(caughtWarnings.length).to.eql(0);
-});
-});
-
-mocha.run(function () {
-var completeNode = document.createElement("p");
-completeNode.setAttribute("id", "complete");
-completeNode.appendChild(document.createTextNode("Complete"));
-document.getElementById("mocha").appendChild(completeNode);
-});
-
-</script>
-</body></html>
diff --git a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-mixedpropertries.js b/toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-mixedpropertries.js
deleted file mode 100644
index db99dc92a..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-mixedpropertries.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-mixed/h-card/mixedpropertries
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<div class=\"h-card\">\n <p>\n <a class=\"p-name p-org u-url\" href=\"http://mozilla.org/\">Mozilla Foundation</a>\n <img class=\"logo\" src=\"../logo.jpg\"/>\n </p>\n <p class=\"adr\">\n <span class=\"street-address\">665 3rd St.</span> \n <span class=\"extended-address\">Suite 207</span> \n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n <span class=\"postal-code\">94107</span> \n <span class=\"p-country-name\">U.S.A.</span> \n </p>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Mozilla Foundation"],"org":["Mozilla Foundation"],"url":["http://mozilla.org/"],"adr":[{"value":"665 3rd St. \n Suite 207 \n San Francisco, \n CA \n 94107 \n U.S.A.","type":["h-adr"],"properties":{"street-address":["665 3rd St."],"extended-address":["Suite 207"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94107"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('mixedpropertries', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-tworoots.js b/toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-tworoots.js
deleted file mode 100644
index be43abcd8..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-card-tworoots.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-mixed/h-card/tworoots
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<p class=\"h-card vcard\">Frances Berriman</p>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Frances Berriman"]}}],"rels":{},"rel-urls":{}};
-
- it('tworoots', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-entry-mixedroots.js b/toolkit/components/microformats/test/standards-tests/mf-mixed-h-entry-mixedroots.js
deleted file mode 100644
index 705ffeebf..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-entry-mixedroots.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-mixed/h-entry/mixedroots
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-entry', function() {
- var htmlFragment = "<!-- simplified version of http://aaronparecki.com/notes/2013/10/18/2/realtimeconf-mapattack -->\n<base href=\"http://aaronparecki.com/\" />\n\n<div class=\"h-entry\">\n <div class=\"h-card vcard author p-author\">\n <img class=\"photo logo u-photo u-logo\" src=\"https://aaronparecki.com/images/aaronpk.png\" alt=\"Aaron Parecki\"/>\n <a href=\"https://aaronparecki.com/\" rel=\"author\" class=\"u-url u-uid url\">aaronparecki.com</a>\n <a class=\"p-name fn value\" href=\"https://aaronparecki.com/\">Aaron Parecki</a>\n <a href=\"https://plus.google.com/117847912875913905493\" rel=\"author\" class=\"google-profile\">Aaron Parecki</a>\n </div>\n <div class=\"entry-content e-content p-name\">Did you play\n <a href=\"http://twitter.com/playmapattack\">@playmapattack</a>at\n <a href=\"/tag/realtimeconf\">#<span class=\"p-category\">realtimeconf</span></a>? Here is some more info about how we built it!\n <a href=\"http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/\"><span class=\"protocol\">http://</span>pdx.esri.com/blog/2013/10/17/introducting-mapattack/</a>\n </div>\n</div>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"author":[{"value":"aaronparecki.com\n Aaron Parecki\n Aaron Parecki","type":["h-card"],"properties":{"photo":["https://aaronparecki.com/images/aaronpk.png"],"logo":["https://aaronparecki.com/images/aaronpk.png"],"url":["https://aaronparecki.com/"],"uid":["https://aaronparecki.com/"],"name":["Aaron Parecki"]}}],"content":[{"value":"Did you play\n @playmapattackat\n #realtimeconf? Here is some more info about how we built it!\n http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/","html":"Did you play\n <a href=\"http://twitter.com/playmapattack\">@playmapattack</a>at\n <a href=\"http://aaronparecki.com/tag/realtimeconf\">#<span class=\"p-category\">realtimeconf</span></a>? Here is some more info about how we built it!\n <a href=\"http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/\"><span class=\"protocol\">http://</span>pdx.esri.com/blog/2013/10/17/introducting-mapattack/</a>\n "}],"name":["Did you play\n @playmapattackat\n #realtimeconf? Here is some more info about how we built it!\n http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/"],"category":["realtimeconf"]}}],"rels":{"author":["https://aaronparecki.com/","https://plus.google.com/117847912875913905493"]},"rel-urls":{"https://aaronparecki.com/":{"text":"aaronparecki.com","rels":["author"]},"https://plus.google.com/117847912875913905493":{"text":"Aaron Parecki","rels":["author"]}}};
-
- it('mixedroots', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-resume-mixedroots.js b/toolkit/components/microformats/test/standards-tests/mf-mixed-h-resume-mixedroots.js
deleted file mode 100644
index 5147866c6..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-mixed-h-resume-mixedroots.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-mixed/h-resume/mixedroots
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-resume', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"h-resume\">\n <div class=\"p-contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <div class=\"p-experience vevent vcard\">\n <p class=\"title\">Director</p>\n <p><a class=\"fn org summary url\" href=\"http://www.webfoundation.org/\">World Wide Web Foundation</a></p>\n <p>\n <time class=\"dtstart\" datetime=\"2009-01-18\">Jan 2009</time> – Present\n <time class=\"duration\" datetime=\"P2Y11M\">(2 years 11 month)</time>\n </p>\n </div>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"contact":[{"value":"Tim Berners-Lee","type":["h-card"],"properties":{"name":["Tim Berners-Lee"],"job-title":["Director of the World Wide Web Foundation"]}}],"summary":["Invented the World Wide Web."],"experience":[{"value":"World Wide Web Foundation","type":["h-event","h-card"],"properties":{"job-title":["Director"],"name":["World Wide Web Foundation"],"org":["World Wide Web Foundation"],"url":["http://www.webfoundation.org/"],"start":["2009-01-18"],"duration":["P2Y11M"]}}],"name":["Tim Berners-Lee\n Director of the World Wide Web Foundation\n \n Invented the World Wide Web.\n \n Director\n World Wide Web Foundation\n \n Jan 2009 – Present\n (2 years 11 month)"]}}],"rels":{},"rel-urls":{}};
-
- it('mixedroots', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-adr-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v1-adr-simpleproperties.js
deleted file mode 100644
index 09a346e0c..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-adr-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/adr/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('adr', function() {
- var htmlFragment = "<p class=\"adr\">\n <span class=\"street-address\">665 3rd St.</span> \n <span class=\"extended-address\">Suite 207</span> \n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n <span class=\"postal-code\">94107</span> \n <span class=\"country-name\">U.S.A.</span> \n</p>";
- var expected = {"items":[{"type":["h-adr"],"properties":{"street-address":["665 3rd St."],"extended-address":["Suite 207"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94107"],"country-name":["U.S.A."]}}],"rels":{},"rel-urls":{}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-abbrpattern.js b/toolkit/components/microformats/test/standards-tests/mf-v1-geo-abbrpattern.js
deleted file mode 100644
index 090e98bb9..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-abbrpattern.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/geo/abbrpattern
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('geo', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<p class=\"geo\">\n <abbr class=\"latitude\" title=\"37.408183\">N 37° 24.491</abbr>, \n <abbr class=\"longitude\" title=\"-122.13855\">W 122° 08.313</abbr>\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["37.408183"],"longitude":["-122.13855"]}}],"rels":{},"rel-urls":{}};
-
- it('abbrpattern', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-hidden.js b/toolkit/components/microformats/test/standards-tests/mf-v1-geo-hidden.js
deleted file mode 100644
index d67a03b4f..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-hidden.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/geo/hidden
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('geo', function() {
- var htmlFragment = "<p>\n <span class=\"geo\">The Bricklayer's Arms\n <span class=\"latitude\">\n <span class=\"value-title\" title=\"51.513458\"> </span> \n </span>\n <span class=\"longitude\">\n <span class=\"value-title\" title=\"-0.14812\"> </span>\n </span>\n </span>\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["51.513458"],"longitude":["-0.14812"]}}],"rels":{},"rel-urls":{}};
-
- it('hidden', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v1-geo-simpleproperties.js
deleted file mode 100644
index 82cd7d3d9..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/geo/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('geo', function() {
- var htmlFragment = "We are meeting at \n<span class=\"geo\"> \n <span>The Bricklayer's Arms</span>\n (Geo: <span class=\"latitude\">51.513458</span>:\n <span class=\"longitude\">-0.14812</span>)\n</span>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["51.513458"],"longitude":["-0.14812"]}}],"rels":{},"rel-urls":{}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-valuetitleclass.js b/toolkit/components/microformats/test/standards-tests/mf-v1-geo-valuetitleclass.js
deleted file mode 100644
index 196e07f7d..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-geo-valuetitleclass.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/geo/valuetitleclass
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('geo', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<p>\n <span class=\"geo\">\n <span class=\"latitude\">\n <span class=\"value-title\" title=\"51.513458\">N 51° 51.345</span>, \n </span>\n <span class=\"longitude\">\n <span class=\"value-title\" title=\"-0.14812\">W -0° 14.812</span>\n </span>\n </span>\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["51.513458"],"longitude":["-0.14812"]}}],"rels":{},"rel-urls":{}};
-
- it('valuetitleclass', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-ampm.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-ampm.js
deleted file mode 100644
index 5da5fd7df..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-ampm.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcalendar/ampm
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcalendar', function() {
- var htmlFragment = "<div class=\"vevent\">\n <span class=\"summary\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00am \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00p.m. \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00PM \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00am \n </span></li>\n </ul>\n</div>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The 4th Microformat party"],"start":["2009-06-26 19:00:00","2009-06-26 07:00:00","2009-06-26 19:00","2009-06-26 19","2009-06-26 19","2009-06-26 19:00","2009-06-26 19:00","2009-06-26 19:00","2009-06-26 07:00"]}}],"rels":{},"rel-urls":{}};
-
- it('ampm', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-attendees.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-attendees.js
deleted file mode 100644
index ca28ad431..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-attendees.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcalendar/attendees
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcalendar', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"vevent\">\n <span class=\"summary\">CPJ Online Press Freedom Summit</span>\n (<time class=\"dtstart\" datetime=\"2012-10-10\">10 Nov 2012</time>) in\n <span class=\"location\">San Francisco</span>.\n Attendees:\n <ul>\n <li class=\"attendee vcard\"><span class=\"fn\">Brian Warner</span></li>\n <li class=\"attendee vcard\"><span class=\"fn\">Kyle Machulis</span></li>\n <li class=\"attendee vcard\"><span class=\"fn\">Tantek Çelik</span></li>\n <li class=\"attendee vcard\"><span class=\"fn\">Sid Sutter</span></li>\n </ul>\n</div>\n";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["CPJ Online Press Freedom Summit"],"start":["2012-10-10"],"location":["San Francisco"],"attendee":[{"value":"Brian Warner","type":["h-card"],"properties":{"name":["Brian Warner"]}},{"value":"Kyle Machulis","type":["h-card"],"properties":{"name":["Kyle Machulis"]}},{"value":"Tantek Çelik","type":["h-card"],"properties":{"name":["Tantek Çelik"]}},{"value":"Sid Sutter","type":["h-card"],"properties":{"name":["Sid Sutter"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('attendees', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-combining.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-combining.js
deleted file mode 100644
index 7e5a361b1..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-combining.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcalendar/combining
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcalendar', function() {
- var htmlFragment = "<div class=\"vevent\">\n <a class=\"summary url\" href=\"http://indiewebcamp.com/2012\">\n IndieWebCamp 2012\n </a>\n from <time class=\"dtstart\">2012-06-30</time> \n to <time class=\"dtend\">2012-07-01</time> at \n <span class=\"location vcard\">\n <a class=\"fn org url\" href=\"http://geoloqi.com/\">Geoloqi</a>, \n <span class=\"adr\">\n <span class=\"street-address\">920 SW 3rd Ave. Suite 400</span>, \n <span class=\"locality\">Portland</span>, \n <abbr class=\"region\" title=\"Oregon\">OR</abbr>\n </span>\n </span>\n</div>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["IndieWebCamp 2012"],"url":["http://indiewebcamp.com/2012"],"start":["2012-06-30"],"end":["2012-07-01"],"location":[{"value":"Geoloqi","type":["h-card"],"properties":{"name":["Geoloqi"],"org":["Geoloqi"],"url":["http://geoloqi.com/"],"adr":[{"value":"920 SW 3rd Ave. Suite 400, \n Portland, \n OR","type":["h-adr"],"properties":{"street-address":["920 SW 3rd Ave. Suite 400"],"locality":["Portland"],"region":["Oregon"]}}]}}]}}],"rels":{},"rel-urls":{}};
-
- it('combining', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-concatenate.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-concatenate.js
deleted file mode 100644
index d17914e1c..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-concatenate.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcalendar/concatenate
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcalendar', function() {
- var htmlFragment = "<div class=\"vevent\">\n <span class=\"summary\">The 4th Microformat party</span> will be on \n <span class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time></span> to \n <span class=\"dtend\"><time class=\"value\">22:00</time></span>.\n</div>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The 4th Microformat party"],"start":["2009-06-26 19:00"],"end":["2009-06-26 22:00"]}}],"rels":{},"rel-urls":{}};
-
- it('concatenate', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-time.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-time.js
deleted file mode 100644
index edb26d6ad..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcalendar-time.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcalendar/time
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcalendar', function() {
- var htmlFragment = "<div class=\"vevent\">\n <span class=\"summary\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-08:00</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-0800</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00+0800</time> \n </li> \n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00Z</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00-08:00</time> \n </li> \n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00+08:00</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00z</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time> \n </li> \n <li>\n <time class=\"dtend\" datetime=\"2013-034\">3 February 2013</time>\n </li> \n </ul>\n</div>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The 4th Microformat party"],"start":["2009-06-26 19:00:00-08:00","2009-06-26 19:00:00-08:00","2009-06-26 19:00:00+08:00","2009-06-26 19:00:00Z","2009-06-26 19:00:00","2009-06-26 19:00-08:00","2009-06-26 19:00+08:00","2009-06-26 19:00Z","2009-06-26 19:00"],"end":["2013-034"]}}],"rels":{},"rel-urls":{}};
-
- it('time', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-email.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-email.js
deleted file mode 100644
index 48660ffb1..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-email.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/email
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<div class=\"vcard\">\n <span class=\"fn\">John Doe</span> \n <ul>\n <li><a class=\"email\" href=\"mailto:john@example.com\">notthis@example.com</a></li>\n <li>\n <span class=\"email\">\n <span class=\"type\">internet</span> \n <a class=\"value\" href=\"mailto:john@example.com\">notthis@example.com</a>\n </span>\n </li> \n <li><a class=\"email\" href=\"mailto:john@example.com?subject=parser-test\">notthis@example.com</a></li>\n <li class=\"email\">john@example.com</li>\n </ul>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["John Doe"],"email":["mailto:john@example.com","mailto:john@example.com","mailto:john@example.com?subject=parser-test","john@example.com"]}}],"rels":{},"rel-urls":{}};
-
- it('email', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-format.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-format.js
deleted file mode 100644
index eb539fd87..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-format.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/format
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<p class=\"vcard\">\n <span class=\"profile-name fn n\">\n <span class=\" given-name \">John</span> \n <span class=\"FAMILY-NAME\">Doe</span> \n </span>\n</p>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["John \n Doe"],"given-name":["John"]}}],"rels":{},"rel-urls":{}};
-
- it('format', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-hyperlinkedphoto.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-hyperlinkedphoto.js
deleted file mode 100644
index 7f348b4a8..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-hyperlinkedphoto.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/hyperlinkedphoto
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<a class=\"vcard\" href=\"http://rohit.khare.org/\">\n <img alt=\"Rohit Khare\" src=\"images/photo.gif\" />\n</a>";
- var expected = {"items":[{"type":["h-card"],"properties":{}}],"rels":{},"rel-urls":{}};
-
- it('hyperlinkedphoto', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justahyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justahyperlink.js
deleted file mode 100644
index e320f0f8a..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justahyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/justahyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<a class=\"vcard\" href=\"http://benward.me/\">Ben Ward</a>";
- var expected = {"items":[{"type":["h-card"],"properties":{}}],"rels":{},"rel-urls":{}};
-
- it('justahyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justaname.js
deleted file mode 100644
index ba2a6d47d..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<p class=\"vcard\">Frances Berriman</p>";
- var expected = {"items":[{"type":["h-card"],"properties":{}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-multiple.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-multiple.js
deleted file mode 100644
index 058e5e2ae..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-multiple.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/multiple
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<base href=\"http://example.com\">\n <div class=\"vcard\">\n \n <div class=\"fn n\"><span class=\"given-name\">John</span> <span class=\"family-name\">Doe</span></div>\n <a class=\"sound\" href=\"http://www.madgex.com/johndoe.mpeg\">Pronunciation of my name</a>\n <div><img class=\"photo\" src=\"images/photo.gif\" alt=\"Photo of John Doe\" /></div>\n\n <p>Nicknames:</p>\n <ul>\n <li class=\"nickname\">Man with no name</li>\n <li class=\"nickname\">Lost boy</li>\n </ul>\n\n <p>About:</p>\n <p class=\"note\">John Doe is one of those names you always have issues with.</p>\n <p class=\"note\">It can be a real problem booking a hotel room with the name John Doe.</p>\n\n <p>Companies:</p>\n <div>\n <img class=\"logo\" src=\"images/logo.gif\" alt=\"Madgex company logo\" />\n <img class=\"logo\" src=\"images/logo.gif\" alt=\"Web Feet Media company logo\" />\n </div>\n <ul>\n <li><a class=\"url org\" href=\"http://www.madgex.com/\">Madgex</a> <span class=\"title\">Creative Director</span></li>\n <li><a class=\"url org\" href=\"http://www.webfeetmedia.com/\">Web Feet Media Ltd</a> <span class=\"title\">Owner</span></li>\n </ul>\n \n <p>Tags: \n <a rel=\"tag\" class=\"category\" href=\"http://en.wikipedia.org/wiki/design\">design</a>, \n <a rel=\"tag\" class=\"category\" href=\"http://en.wikipedia.org/wiki/development\">development</a> and\n <a rel=\"tag\" class=\"category\" href=\"http://en.wikipedia.org/wiki/web\">web</a>\n </p>\n \n <p>Phone numbers:</p>\n <ul>\n <li class=\"tel\">\n <span class=\"type\">Work</span> (<span class=\"type\">pref</span>erred):\n <span class=\"value\">+1 415 555 100</span>\n </li>\n <li class=\"tel\"><span class=\"type\">Home</span>: <span class=\"value\">+1 415 555 200</span></li>\n <li class=\"tel\"><span class=\"type\">Postal</span>: <span class=\"value\">+1 415 555 300</span></li>\n </ul>\n \n <p>Emails:</p>\n <ul>\n <li><a class=\"email\" href=\"mailto:john.doe@madgex.com\">John Doe at Madgex</a></li>\n <li><a class=\"email\" href=\"mailto:john.doe@webfeetmedia.com\">John Doe at Web Feet Media</a></li>\n </ul>\n <p>John Doe uses <span class=\"mailer\">PigeonMail 2.1</span> or <span class=\"mailer\">Outlook 2007</span> for email.</p>\n\n <p>Addresses:</p>\n <ul>\n <li class=\"label\">\n <span class=\"adr\">\n <span class=\"type\">Work</span>: \n <span class=\"street-address\">North Street</span>, \n <span class=\"locality\">Brighton</span>, \n <span class=\"country-name\">United Kingdom</span>\n </span>\n \n </li>\n <li class=\"label\">\n <span class=\"adr\">\n <span class=\"type\">Home</span>: \n <span class=\"street-address\">West Street</span>, \n <span class=\"locality\">Brighton</span>, \n <span class=\"country-name\">United Kingdom</span>\n </span>\n </li>\n </ul>\n \n <p>In emergency contact: <span class=\"agent\">Jane Doe</span> or <span class=\"agent vcard\"><span class=\"fn\">Dave Doe</span></span>.</p>\n <p>Key: <span class=\"key\">hd02$Gfu*d%dh87KTa2=23934532479</span></p>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["John Doe"],"given-name":["John"],"family-name":["Doe"],"sound":["http://www.madgex.com/johndoe.mpeg"],"photo":["http://example.com/images/photo.gif"],"nickname":["Man with no name","Lost boy"],"note":["John Doe is one of those names you always have issues with.","It can be a real problem booking a hotel room with the name John Doe."],"logo":["http://example.com/images/logo.gif","http://example.com/images/logo.gif"],"url":["http://www.madgex.com/","http://www.webfeetmedia.com/"],"org":["Madgex","Web Feet Media Ltd"],"job-title":["Creative Director","Owner"],"category":["design","development","web"],"tel":["+1 415 555 100","+1 415 555 200","+1 415 555 300"],"email":["mailto:john.doe@madgex.com","mailto:john.doe@webfeetmedia.com"],"mailer":["PigeonMail 2.1","Outlook 2007"],"label":["Work: \n North Street, \n Brighton, \n United Kingdom","Home: \n West Street, \n Brighton, \n United Kingdom"],"adr":[{"value":"Work: \n North Street, \n Brighton, \n United Kingdom","type":["h-adr"],"properties":{"street-address":["North Street"],"locality":["Brighton"],"country-name":["United Kingdom"]}},{"value":"Home: \n West Street, \n Brighton, \n United Kingdom","type":["h-adr"],"properties":{"street-address":["West Street"],"locality":["Brighton"],"country-name":["United Kingdom"]}}],"agent":["Jane Doe",{"value":"Dave Doe","type":["h-card"],"properties":{"name":["Dave Doe"]}}],"key":["hd02$Gfu*d%dh87KTa2=23934532479"]}}],"rels":{"tag":["http://en.wikipedia.org/wiki/design","http://en.wikipedia.org/wiki/development","http://en.wikipedia.org/wiki/web"]},"rel-urls":{"http://en.wikipedia.org/wiki/design":{"text":"design","rels":["tag"]},"http://en.wikipedia.org/wiki/development":{"text":"development","rels":["tag"]},"http://en.wikipedia.org/wiki/web":{"text":"web","rels":["tag"]}}};
-
- it('multiple', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-name.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-name.js
deleted file mode 100644
index ef75899cf..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-name.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/name
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<base href=\"http://example.com\">\n<div class=\"vcard\">\n <div class=\"name\">\n <span class=\"honorific-prefix\">Dr</span> \n <span class=\"given-name\">John</span> \n <abbr class=\"additional-name\" title=\"Peter\">P</abbr> \n <span class=\"family-name\">Doe</span> \n <data class=\"honorific-suffix\" value=\"MSc\"></data>\n <img class=\"photo honorific-suffix\" src=\"images/logo.gif\" alt=\"PHD\" />\n </div>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"honorific-prefix":["Dr"],"given-name":["John"],"additional-name":["Peter"],"family-name":["Doe"],"honorific-suffix":["MSc","PHD"],"photo":["http://example.com/images/logo.gif"]}}],"rels":{},"rel-urls":{}};
-
- it('name', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-single.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-single.js
deleted file mode 100644
index a7ef7628b..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hcard-single.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hcard/single
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hcard', function() {
- var htmlFragment = "<div class=\"vcard\">\n \n <div class=\"fn n\"><span class=\"given-name sort-string\">John</span> Doe</div>\n <div>Birthday: <abbr class=\"bday\" title=\"2000-01-01T00:00:00-08:00\">January 1st, 2000</abbr></div>\n <div>Role: <span class=\"role\">Designer</span></div>\n <div>Location: <abbr class=\"geo\" title=\"30.267991;-97.739568\">Brighton</abbr></div>\n <div>Time zone: <abbr class=\"tz\" title=\"-05:00\">Eastern Standard Time</abbr></div>\n \n <div>Profile details:\n <div>Profile id: <span class=\"uid\">http://example.com/profiles/johndoe</span></div>\n <div>Details are: <span class=\"class\">Public</span></div>\n <div>Last updated: <abbr class=\"rev\" title=\"2008-01-01T13:45:00\">January 1st, 2008 - 13:45</abbr></div>\n </div>\n </div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["John Doe"],"given-name":["John"],"sort-string":["John"],"bday":["2000-01-01 00:00:00-08:00"],"role":["Designer"],"geo":[{"value":"30.267991;-97.739568","type":["h-geo"],"properties":{"name":["30.267991;-97.739568"]}}],"tz":["-05:00"],"uid":["http://example.com/profiles/johndoe"],"class":["Public"],"rev":["2008-01-01 13:45:00"]}}],"rels":{},"rel-urls":{}};
-
- it('single', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hentry-summarycontent.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hentry-summarycontent.js
deleted file mode 100644
index 5280efb04..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hentry-summarycontent.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hentry/summarycontent
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hentry', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"hentry\">\n <h1><a class=\"entry-title\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"entry-content\">\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"name":["microformats.org at 7"],"content":[{"value":"Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service","html":"\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n "}],"summary":["Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities."],"updated":["2012-06-25 17:08:26"],"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('summarycontent', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hfeed-simple.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hfeed-simple.js
deleted file mode 100644
index 4c8294d49..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hfeed-simple.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hfeed/simple
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hfeed', function() {
- var htmlFragment = "<section class=\"hfeed\">\n\t<h1 class=\"name\">Microformats blog</h1>\n\t<span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n\t<a class=\"url\" href=\"http://microformats.org/blog\">permlink</a>\n\t<img class=\"photo\" src=\"photo.jpeg\"/>\n\t<p>\n\t\tTags: <a rel=\"tag\" href=\"tags/microformats\">microformats</a>, \n\t\t<a rel=\"tag\" href=\"tags/html\">html</a>\n\t</p>\n\t\n\t<div class=\"hentry\">\n\t <h1><a class=\"entry-title\" rel=\"bookmark\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n\t <div class=\"entry-content\">\n\t <p class=\"entry-summary\">Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.</p>\n\t\n\t <p>The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service </p>\n\t </div> \n\t <p>Updated \n\t <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time>\n\t </p>\n\t</div>\n\t\n</section>";
- var expected = {"items":[{"type":["h-feed"],"properties":{"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}],"url":["http://microformats.org/blog"],"photo":["http://example.com/photo.jpeg"],"category":["microformats","html"]},"children":[{"value":"microformats.org at 7\n\t \n\t Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.\n\t\n\t The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t principles, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service \n\t \n\t Updated \n\t June 25th, 2012","type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"content":[{"value":"Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.\n\t\n\t The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t principles, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service","html":"\n\t <p class=\"entry-summary\">Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.</p>\n\t\n\t <p>The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service </p>\n\t "}],"summary":["Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities."],"updated":["2012-06-25 17:08:26"]}}]}],"rels":{"tag":["http://example.com/tags/microformats","http://example.com/tags/html"],"bookmark":["http://microformats.org/2012/06/25/microformats-org-at-7"]},"rel-urls":{"http://example.com/tags/microformats":{"text":"microformats","rels":["tag"]},"http://example.com/tags/html":{"text":"html","rels":["tag"]},"http://microformats.org/2012/06/25/microformats-org-at-7":{"text":"microformats.org at 7","rels":["bookmark"]}}};
-
- it('simple', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hnews-all.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hnews-all.js
deleted file mode 100644
index 82eb37b95..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hnews-all.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hnews/all
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hnews', function() {
- var htmlFragment = "<div class=\"hnews\">\n <div class=\"entry hentry\">\n <h1><a class=\"entry-title\" rel=\"bookmark\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"entry-content\">\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n </p>\n </div>\n\n <p>\n <span class=\"dateline vcard\">\n <span class=\"adr\">\n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n </span>\n </span>\n (Geo: <span class=\"geo\">37.774921;-122.445202</span>) \n <span class=\"source-org vcard\">\n <a class=\"fn org url\" href=\"http://microformats.org/\">microformats.org</a>\n </span>\n </p>\n <p>\n <a rel=\"principles\" href=\"http://microformats.org/wiki/Category:public_domain_license\">Publishing policy</a>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-news"],"properties":{"entry":[{"value":"microformats.org at 7","type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"content":[{"value":"Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service","html":"\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n "}],"summary":["Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities."],"updated":["2012-06-25 17:08:26"],"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}]}}],"dateline":[{"value":"San Francisco, \n CA","type":["h-card"],"properties":{"adr":[{"value":"San Francisco, \n CA","type":["h-adr"],"properties":{"locality":["San Francisco"],"region":["CA"]}}]}}],"geo":[{"value":"37.774921;-122.445202","type":["h-geo"],"properties":{"name":["37.774921;-122.445202"]}}],"source-org":[{"value":"microformats.org","type":["h-card"],"properties":{"name":["microformats.org"],"org":["microformats.org"],"url":["http://microformats.org/"]}}],"principles":["http://microformats.org/wiki/Category:public_domain_license"]}}],"rels":{"bookmark":["http://microformats.org/2012/06/25/microformats-org-at-7"],"principles":["http://microformats.org/wiki/Category:public_domain_license"]},"rel-urls":{"http://microformats.org/2012/06/25/microformats-org-at-7":{"text":"microformats.org at 7","rels":["bookmark"]},"http://microformats.org/wiki/Category:public_domain_license":{"text":"Publishing policy","rels":["principles"]}}};
-
- it('all', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hnews-minimum.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hnews-minimum.js
deleted file mode 100644
index 5faf13d7b..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hnews-minimum.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hnews/minimum
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hnews', function() {
- var htmlFragment = "<div class=\"hnews\">\n <div class=\"entry hentry\">\n <h1><a class=\"entry-title\" rel=\"bookmark\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"entry-content\">\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n </p>\n </div>\n\n <p class=\"source-org vcard\">\n <a class=\"fn org url\" href=\"http://microformats.org/\">microformats.org</a> \n </p>\n</div>";
- var expected = {"items":[{"type":["h-news"],"properties":{"entry":[{"value":"microformats.org at 7","type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"content":[{"value":"Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service","html":"\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n "}],"summary":["Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities."],"updated":["2012-06-25 17:08:26"],"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}]}}],"source-org":[{"value":"microformats.org","type":["h-card"],"properties":{"name":["microformats.org"],"org":["microformats.org"],"url":["http://microformats.org/"]}}]}}],"rels":{"bookmark":["http://microformats.org/2012/06/25/microformats-org-at-7"]},"rel-urls":{"http://microformats.org/2012/06/25/microformats-org-at-7":{"text":"microformats.org at 7","rels":["bookmark"]}}};
-
- it('minimum', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-aggregate.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-aggregate.js
deleted file mode 100644
index 7171bc726..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-aggregate.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hproduct/aggregate
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hproduct', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"hproduct\">\n <h2 class=\"fn\">Raspberry Pi</h2>\n <img class=\"photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"price\">£29.95</p>\n <p class=\"review hreview-aggregate\">\n <span class=\"rating\">\n <span class=\"average value\">9.2</span> out of \n <span class=\"best\">10</span> \n based on <span class=\"count\">178</span> reviews\n </span>\n </p>\n <p>Categories: \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/computer\" class=\"category\">Computer</a>, \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/education\" class=\"category\">Education</a>\n </p>\n <p class=\"brand vcard\">From: \n <span class=\"fn org\">The Raspberry Pi Foundation</span> - \n <span class=\"adr\">\n <span class=\"locality\">Cambridge</span> \n <span class=\"country-name\">UK</span>\n </span>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-product"],"properties":{"name":["Raspberry Pi"],"photo":["http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg"],"description":[{"value":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.","html":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming."}],"url":["http://www.raspberrypi.org/"],"price":["£29.95"],"review":[{"value":"9.2 out of \n 10 \n based on 178 reviews","type":["h-review-aggregate"],"properties":{"rating":["9.2"],"average":["9.2"],"best":["10"],"count":["178"]}}],"category":["Computer","Education"],"brand":[{"value":"The Raspberry Pi Foundation","type":["h-card"],"properties":{"name":["The Raspberry Pi Foundation"],"org":["The Raspberry Pi Foundation"],"adr":[{"value":"Cambridge \n UK","type":["h-adr"],"properties":{"locality":["Cambridge"],"country-name":["UK"]}}]}}]}}],"rels":{"tag":["http://en.wikipedia.org/wiki/computer","http://en.wikipedia.org/wiki/education"]},"rel-urls":{"http://en.wikipedia.org/wiki/computer":{"text":"Computer","rels":["tag"]},"http://en.wikipedia.org/wiki/education":{"text":"Education","rels":["tag"]}}};
-
- it('aggregate', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-simpleproperties.js
deleted file mode 100644
index 7ec61f27b..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hproduct-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hproduct/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hproduct', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"hproduct\">\n <h2 class=\"fn\">Raspberry Pi</h2>\n <img class=\"photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"price\">£29.95</p>\n <p class=\"review hreview\"><span class=\"rating\">4.5</span> out of 5</p>\n <p>Categories: \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/computer\" class=\"category\">Computer</a>, \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/education\" class=\"category\">Education</a>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-product"],"properties":{"name":["Raspberry Pi"],"photo":["http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg"],"description":[{"value":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.","html":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming."}],"url":["http://www.raspberrypi.org/"],"price":["£29.95"],"category":["Computer","Education"],"review":[{"value":"4.5 out of 5","type":["h-review"],"properties":{"rating":["4.5"]}}]}}],"rels":{"tag":["http://en.wikipedia.org/wiki/computer","http://en.wikipedia.org/wiki/education"]},"rel-urls":{"http://en.wikipedia.org/wiki/computer":{"text":"Computer","rels":["tag"]},"http://en.wikipedia.org/wiki/education":{"text":"Education","rels":["tag"]}}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-affiliation.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-affiliation.js
deleted file mode 100644
index d580d68db..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-affiliation.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hresume/affiliation
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hresume', function() {
- var htmlFragment = "<div class=\"hresume\">\n <p>\n <span class=\"contact vcard\"><span class=\"fn\">Tim Berners-Lee</span></span>, \n <span class=\"summary\">invented the World Wide Web</span>.\n </p>\n Belongs to following groups:\n <p> \n <a class=\"affiliation vcard\" href=\"http://www.w3.org/\">\n <img class=\"fn photo\" alt=\"W3C\" src=\"http://www.w3.org/Icons/WWW/w3c_home_nb.png\" />\n </a>\n </p> \n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"contact":[{"value":"Tim Berners-Lee","type":["h-card"],"properties":{"name":["Tim Berners-Lee"]}}],"summary":["invented the World Wide Web"],"affiliation":[{"type":["h-card"],"properties":{"name":["W3C"],"photo":["http://www.w3.org/Icons/WWW/w3c_home_nb.png"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('affiliation', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-contact.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-contact.js
deleted file mode 100644
index 595087af4..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-contact.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hresume/contact
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hresume', function() {
- var htmlFragment = "<div class=\"hresume\">\n <div class=\"contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"org\">MIT</p>\n <p class=\"adr\">\n <span class=\"street-address\">32 Vassar Street</span>, \n <span class=\"extended-address\">Room 32-G524</span>, \n <span class=\"locality\">Cambridge</span>, \n <span class=\"region\">MA</span> \n <span class=\"postal-code\">02139</span>, \n <span class=\"country-name\">USA</span>. \n (<span class=\"type\">Work</span>)\n </p>\n <p>Tel:<span class=\"tel\">+1 (617) 253 5702</span></p>\n <p>Email:<a class=\"email\" href=\"mailto:timbl@w3.org\">timbl@w3.org</a></p>\n </div>\n <p class=\"summary\">Invented the World Wide Web.</p>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"contact":[{"value":"Tim Berners-Lee","type":["h-card"],"properties":{"name":["Tim Berners-Lee"],"org":["MIT"],"adr":[{"value":"32 Vassar Street, \n Room 32-G524, \n Cambridge, \n MA \n 02139, \n USA. \n (Work)","type":["h-adr"],"properties":{"street-address":["32 Vassar Street"],"extended-address":["Room 32-G524"],"locality":["Cambridge"],"region":["MA"],"postal-code":["02139"],"country-name":["USA"]}}],"tel":["+1 (617) 253 5702"],"email":["mailto:timbl@w3.org"]}}],"summary":["Invented the World Wide Web."]}}],"rels":{},"rel-urls":{}};
-
- it('contact', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-education.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-education.js
deleted file mode 100644
index 7a0114f53..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-education.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hresume/education
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hresume', function() {
- var htmlFragment = "<div class=\"hresume\">\n <div class=\"contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"summary\">Invented the World Wide Web.</p><hr />\n <p class=\"education vevent vcard\">\n <span class=\"fn summary org\">The Queen's College, Oxford University</span>, \n <span class=\"description\">BA Hons (I) Physics</span> \n <time class=\"dtstart\" datetime=\"1973-09\">1973</time> –\n <time class=\"dtend\" datetime=\"1976-06\">1976</time>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"contact":[{"value":"Tim Berners-Lee","type":["h-card"],"properties":{"name":["Tim Berners-Lee"],"job-title":["Director of the World Wide Web Foundation"]}}],"summary":["Invented the World Wide Web."],"education":[{"value":"The Queen's College, Oxford University","type":["h-event","h-card"],"properties":{"name":["The Queen's College, Oxford University"],"org":["The Queen's College, Oxford University"],"description":["BA Hons (I) Physics"],"start":["1973-09"],"end":["1976-06"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('education', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-skill.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-skill.js
deleted file mode 100644
index b08256700..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-skill.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hresume/skill
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hresume', function() {
- var htmlFragment = "<div class=\"hresume\"> \n <p>\n <span class=\"contact vcard\"><span class=\"fn\">Tim Berners-Lee</span></span>, \n <span class=\"summary\">invented the World Wide Web</span>.\n </p>\n Skills: \n <ul>\n <li><a class=\"skill\" rel=\"tag\" href=\"http://example.com/skills/informationsystems\">information systems</a></li>\n <li><a class=\"skill\" rel=\"tag\" href=\"http://example.com/skills/advocacy\">advocacy</a></li>\n <li><a class=\"skill\" rel=\"tag\" href=\"http://example.com/skills/leadership\">leadership</a></li>\n </ul>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"contact":[{"value":"Tim Berners-Lee","type":["h-card"],"properties":{"name":["Tim Berners-Lee"]}}],"summary":["invented the World Wide Web"],"skill":["information systems","advocacy","leadership"]}}],"rels":{"tag":["http://example.com/skills/informationsystems","http://example.com/skills/advocacy","http://example.com/skills/leadership"]},"rel-urls":{"http://example.com/skills/informationsystems":{"text":"information systems","rels":["tag"]},"http://example.com/skills/advocacy":{"text":"advocacy","rels":["tag"]},"http://example.com/skills/leadership":{"text":"leadership","rels":["tag"]}}};
-
- it('skill', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-work.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-work.js
deleted file mode 100644
index 4ece3a389..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hresume-work.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hresume/work
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hresume', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"hresume\">\n <div class=\"contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"summary\">Invented the World Wide Web.</p><hr />\n <div class=\"experience vevent vcard\">\n <p class=\"title\">Director</p>\n <p><a class=\"fn summary org url\" href=\"http://www.webfoundation.org/\">World Wide Web Foundation</a></p>\n <p>\n <time class=\"dtstart\" datetime=\"2009-01-18\">Jan 2009</time> – Present\n <time class=\"duration\" datetime=\"P2Y11M\">(2 years 11 month)</time>\n </p>\n </div>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"contact":[{"value":"Tim Berners-Lee","type":["h-card"],"properties":{"name":["Tim Berners-Lee"],"job-title":["Director of the World Wide Web Foundation"]}}],"summary":["Invented the World Wide Web."],"experience":[{"value":"World Wide Web Foundation","type":["h-event","h-card"],"properties":{"job-title":["Director"],"name":["World Wide Web Foundation"],"org":["World Wide Web Foundation"],"url":["http://www.webfoundation.org/"],"start":["2009-01-18"],"duration":["P2Y11M"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('work', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-hcard.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-hcard.js
deleted file mode 100644
index 6cdf65484..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-hcard.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hreview-aggregate/hcard
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hreview-aggregate', function() {
- var htmlFragment = "<div class=\"hreview-aggregate\">\n <div class=\"item vcard\">\n <h3 class=\"fn org\">Mediterranean Wraps</h3> \n <p>\n <span class=\"adr\">\n <span class=\"street-address\">433 S California Ave</span>, \n <span class=\"locality\">Palo Alto</span>, \n <span class=\"region\">CA</span></span> - \n \n <span class=\"tel\">(650) 321-8189</span>\n </p>\n </div> \n <p class=\"rating\">\n <span class=\"average value\">9.2</span> out of \n <span class=\"best\">10</span> \n based on <span class=\"count\">17</span> reviews\n </p>\n</div>";
- var expected = {"items":[{"type":["h-review-aggregate"],"properties":{"item":[{"value":"Mediterranean Wraps","type":["h-item","h-card"],"properties":{"name":["Mediterranean Wraps"],"org":["Mediterranean Wraps"],"adr":[{"value":"433 S California Ave, \n Palo Alto, \n CA","type":["h-adr"],"properties":{"street-address":["433 S California Ave"],"locality":["Palo Alto"],"region":["CA"]}}],"tel":["(650) 321-8189"]}}],"rating":["9.2"],"average":["9.2"],"best":["10"],"count":["17"]}}],"rels":{},"rel-urls":{}};
-
- it('hcard', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-justahyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-justahyperlink.js
deleted file mode 100644
index 56d106fdb..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-justahyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hreview-aggregate/justahyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hreview-aggregate', function() {
- var htmlFragment = "<p class=\"hreview-aggregate\">\n <span class=\"item\">\n <a class=\"fn url\" href=\"http://example.com/mediterraneanwraps\">Mediterranean Wraps</a>\n </span> - Rated: \n <span class=\"rating\">4.5</span> out of 5 (<span class=\"count\">6</span> reviews)\n</p>";
- var expected = {"items":[{"type":["h-review-aggregate"],"properties":{"item":[{"value":"Mediterranean Wraps","type":["h-item"],"properties":{"name":["Mediterranean Wraps"],"url":["http://example.com/mediterraneanwraps"]}}],"rating":["4.5"],"count":["6"]}}],"rels":{},"rel-urls":{}};
-
- it('justahyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-vevent.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-vevent.js
deleted file mode 100644
index 896bbdc1d..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-aggregate-vevent.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hreview-aggregate/vevent
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hreview-aggregate', function() {
- var htmlFragment = "<div class=\"hreview-aggregate\">\n <div class=\"item vevent\">\n <h3 class=\"summary\">Fullfrontal</h3>\n <p class=\"description\">A one day JavaScript Conference held in Brighton</p>\n <p><time class=\"dtstart\" datetime=\"2012-11-09\">9th November 2012</time></p> \n </div> \n \n <p class=\"rating\">\n <span class=\"average value\">9.9</span> out of \n <span class=\"best\">10</span> \n based on <span class=\"count\">62</span> reviews\n </p>\n</div>";
- var expected = {"items":[{"type":["h-review-aggregate"],"properties":{"item":[{"value":"Fullfrontal","type":["h-item","h-event"],"properties":{"name":["Fullfrontal"],"description":["A one day JavaScript Conference held in Brighton"],"start":["2012-11-09"]}}],"rating":["9.9"],"average":["9.9"],"best":["10"],"count":["62"]}}],"rels":{},"rel-urls":{}};
-
- it('vevent', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-item.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-item.js
deleted file mode 100644
index 4a00ac46a..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-item.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hreview/item
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hreview', function() {
- var htmlFragment = "<base href=\"http://example.com\">\n<div class=\"hreview\">\n <p class=\"item\">\n <img class=\"photo\" src=\"images/photo.gif\" />\n <a class=\"fn url\" href=\"http://example.com/crepeoncole\">Crepes on Cole</a>\n </p>\n <p><span class=\"rating\">5</span> out of 5 stars</p>\n</div>";
- var expected = {"items":[{"type":["h-review"],"properties":{"item":[{"value":"Crepes on Cole","type":["h-item"],"properties":{"photo":["http://example.com/images/photo.gif"],"name":["Crepes on Cole"],"url":["http://example.com/crepeoncole"]}}],"rating":["5"]}}],"rels":{},"rel-urls":{}};
-
- it('item', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-vcard.js b/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-vcard.js
deleted file mode 100644
index d59decb7f..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-hreview-vcard.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/hreview/vcard
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('hreview', function() {
- var htmlFragment = "<div class=\"hreview\">\n <span><span class=\"rating\">5</span> out of 5 stars</span>\n <h4 class=\"summary\">Crepes on Cole is awesome</h4>\n <span class=\"reviewer vcard\">\n Reviewer: <span class=\"fn\">Tantek</span> - \n </span>\n <time class=\"reviewed\" datetime=\"2005-04-18\">April 18, 2005</time>\n <div class=\"description\">\n <p class=\"item vcard\">\n <span class=\"fn org\">Crepes on Cole</span> is one of the best little \n creperies in <span class=\"adr\"><span class=\"locality\">San Francisco</span></span>.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.\n </p>\n </div>\n <p>Visit date: <span>April 2005</span></p>\n <p>Food eaten: <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/crepe\">crepe</a></p>\n <p>Permanent link for review: <a rel=\"self bookmark\" href=\"http://example.com/crepe\">http://example.com/crepe</a></p>\n <p><a rel=\"license\" href=\"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a></p>\n</div>";
- var expected = {"items":[{"type":["h-review"],"properties":{"rating":["5"],"name":["Crepes on Cole is awesome"],"reviewer":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"]}}],"description":[{"value":"Crepes on Cole is one of the best little \n creperies in San Francisco.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.","html":"\n <p class=\"item vcard\">\n <span class=\"fn org\">Crepes on Cole</span> is one of the best little \n creperies in <span class=\"adr\"><span class=\"locality\">San Francisco</span></span>.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.\n </p>\n "}],"item":[{"value":"Crepes on Cole","type":["h-item","h-card"],"properties":{"name":["Crepes on Cole"],"org":["Crepes on Cole"],"adr":[{"value":"San Francisco","type":["h-adr"],"properties":{"locality":["San Francisco"]}}]}}],"category":["crepe"],"url":["http://example.com/crepe"]}}],"rels":{"tag":["http://en.wikipedia.org/wiki/crepe"],"self":["http://example.com/crepe"],"bookmark":["http://example.com/crepe"],"license":["http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"]},"rel-urls":{"http://en.wikipedia.org/wiki/crepe":{"text":"crepe","rels":["tag"]},"http://example.com/crepe":{"text":"http://example.com/crepe","rels":["self","bookmark"]},"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License":{"text":"Creative Commons Attribution-ShareAlike License","rels":["license"]}}};
-
- it('vcard', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-hcarditemref.js b/toolkit/components/microformats/test/standards-tests/mf-v1-includes-hcarditemref.js
deleted file mode 100644
index 5ffa373d7..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-hcarditemref.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/includes/hcarditemref
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('includes', function() {
- var htmlFragment = "<div class=\"vcard\" itemref=\"mozilla-org mozilla-adr\">\n <span class=\"name\">Brendan Eich</span>\n</div>\n<div class=\"vcard\" itemref=\"mozilla-org mozilla-adr\">\n <span class=\"name\">Mitchell Baker</span>\n</div>\n\n<p id=\"mozilla-org\" class=\"org\">Mozilla</p>\n<p id=\"mozilla-adr\" class=\"adr\">\n <span class=\"street-address\">665 3rd St.</span> \n <span class=\"extended-address\">Suite 207</span> \n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n <span class=\"postal-code\">94107</span> \n <span class=\"country-name\">U.S.A.</span> \n</p>";
- var expected = {"items":[{"type":["h-card"],"properties":{"org":["Mozilla"],"adr":[{"value":"665 3rd St. \n Suite 207 \n San Francisco, \n CA \n 94107 \n U.S.A.","type":["h-adr"],"properties":{"street-address":["665 3rd St."],"extended-address":["Suite 207"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94107"],"country-name":["U.S.A."]}}]}},{"type":["h-card"],"properties":{"org":["Mozilla"],"adr":[{"value":"665 3rd St. \n Suite 207 \n San Francisco, \n CA \n 94107 \n U.S.A.","type":["h-adr"],"properties":{"street-address":["665 3rd St."],"extended-address":["Suite 207"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94107"],"country-name":["U.S.A."]}}]}},{"type":["h-adr"],"properties":{"street-address":["665 3rd St."],"extended-address":["Suite 207"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94107"],"country-name":["U.S.A."]}}],"rels":{},"rel-urls":{}};
-
- it('hcarditemref', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-heventitemref.js b/toolkit/components/microformats/test/standards-tests/mf-v1-includes-heventitemref.js
deleted file mode 100644
index b3a16025b..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-heventitemref.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/includes/heventitemref
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('includes', function() {
- var htmlFragment = "<div class=\"vevent\" itemref=\"io-session07\">\n <span class=\"name\">Monetizing Android Apps</span> - spaekers: \n <span class=\"speaker\">Chrix Finne</span>, \n <span class=\"speaker\">Kenneth Lui</span> - \n <span itemref=\"io-location\" class=\"location adr\">\n <span class=\"extended-address\">Room 10</span>\n </span> \n</div>\n<div class=\"vevent\" itemref=\"io-session07\">\n <span class=\"name\">New Low-Level Media APIs in Android</span> - spaekers: \n <span class=\"speaker\">Dave Burke</span> -\n <span itemref=\"io-location\" class=\"location adr\">\n <span class=\"extended-address\">Room 11</span>\n </span> \n</div>\n\n<p id=\"io-session07\">\n Session 01 is between: \n <time class=\"dtstart\" datetime=\"2012-06-27T15:45:00-0800\">3:45PM</time> to \n <time class=\"dtend\" datetime=\"2012-06-27T16:45:00-0800\">4:45PM</time> \n</p> \n<p id=\"io-location\">\n <span class=\"extended-address\">Moscone Center</span>, \n <span class=\"locality\">San Francisco</span> \n</p>";
- var expected = {"items":[{"type":["h-event"],"properties":{"location":[{"value":"Room 10\n \n Moscone Center, \n San Francisco","type":["h-adr"],"properties":{"extended-address":["Room 10","Moscone Center"],"locality":["San Francisco"]}}],"start":["2012-06-27 15:45:00-08:00"],"end":["2012-06-27 16:45:00-08:00"]}},{"type":["h-event"],"properties":{"location":[{"value":"Room 11\n \n Moscone Center, \n San Francisco","type":["h-adr"],"properties":{"extended-address":["Room 11","Moscone Center"],"locality":["San Francisco"]}}],"start":["2012-06-27 15:45:00-08:00"],"end":["2012-06-27 16:45:00-08:00"]}}],"rels":{},"rel-urls":{}};
-
- it('heventitemref', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-hyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v1-includes-hyperlink.js
deleted file mode 100644
index 3a789bb1b..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-hyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/includes/hyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('includes', function() {
- var htmlFragment = "<div class=\"vcard\">\n <span class=\"name\">Ben Ward</span>\n <a class=\"include\" href=\"#twitter\">Twitter</a>\n</div>\n<div class=\"vcard\">\n <span class=\"name\">Dan Webb</span>\n <a class=\"include\" href=\"#twitter\">Twitter</a>\n</div>\n\n<div id=\"twitter\">\n <p class=\"org\">Twitter</p>\n <p class=\"adr\">\n <span class=\"street-address\">1355 Market St</span>,\n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span>\n <span class=\"postal-code\">94103</span>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"org":["Twitter"],"adr":[{"value":"1355 Market St,\n San Francisco, \n CA\n 94103","type":["h-adr"],"properties":{"street-address":["1355 Market St"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94103"]}}]}},{"type":["h-card"],"properties":{"org":["Twitter"],"adr":[{"value":"1355 Market St,\n San Francisco, \n CA\n 94103","type":["h-adr"],"properties":{"street-address":["1355 Market St"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94103"]}}]}},{"type":["h-adr"],"properties":{"street-address":["1355 Market St"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94103"]}}],"rels":{},"rel-urls":{}};
-
- it('hyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-object.js b/toolkit/components/microformats/test/standards-tests/mf-v1-includes-object.js
deleted file mode 100644
index 3bc15bd45..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-object.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/includes/object
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('includes', function() {
- var htmlFragment = "<div class=\"vevent\">\n <span class=\"name\">HTML5 & CSS3 latest features in action!</span> - \n <span class=\"speaker\">David Rousset</span> -\n <time class=\"dtstart\" datetime=\"2012-10-30T11:45:00-08:00\">Tue 11:45am</time>\n <object data=\"#buildconf\" class=\"include\" type=\"text/html\" height=\"0\" width=\"0\"></object>\n</div>\n<div class=\"vevent\">\n <span class=\"name\">Building High-Performing JavaScript for Modern Engines</span> -\n <span class=\"speaker\">John-David Dalton</span> and \n <span class=\"speaker\">Amanda Silver</span> -\n <time class=\"dtstart\" datetime=\"2012-10-31T11:15:00-08:00\">Wed 11:15am</time>\n <object data=\"#buildconf\" class=\"include\" type=\"text/html\" height=\"0\" width=\"0\"></object>\n</div>\n\n\n<div id=\"buildconf\">\n <p class=\"summary\">Build Conference</p>\n <p class=\"location adr\">\n <span class=\"locality\">Redmond</span>, \n <span class=\"region\">Washington</span>, \n <span class=\"country-name\">USA</span>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-event"],"properties":{"start":["2012-10-30 11:45:00-08:00"],"name":["Build Conference"],"location":[{"value":"Redmond, \n Washington, \n USA","type":["h-adr"],"properties":{"locality":["Redmond"],"region":["Washington"],"country-name":["USA"]}}]}},{"type":["h-event"],"properties":{"start":["2012-10-31 11:15:00-08:00"],"name":["Build Conference"],"location":[{"value":"Redmond, \n Washington, \n USA","type":["h-adr"],"properties":{"locality":["Redmond"],"region":["Washington"],"country-name":["USA"]}}]}},{"type":["h-adr"],"properties":{"locality":["Redmond"],"region":["Washington"],"country-name":["USA"]}}],"rels":{},"rel-urls":{}};
-
- it('object', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-table.js b/toolkit/components/microformats/test/standards-tests/mf-v1-includes-table.js
deleted file mode 100644
index a0d3ef55c..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v1-includes-table.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v1/includes/table
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('includes', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<table>\n <tr>\n <th id=\"org\"><a class=\"url org\" href=\"http://dev.opera.com/\">Opera</a></th>\n </tr>\n <tr>\n <td class=\"vcard\" headers=\"org\"><span class=\"fn\">Chris Mills</span></td>\n </tr>\n <tr>\n <td class=\"vcard\" headers=\"org\"><span class=\"fn\">Erik Möller</span></td>\n </tr>\n </table>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Chris Mills"],"url":["http://dev.opera.com/"],"org":["Opera"]}},{"type":["h-card"],"properties":{"name":["Erik Möller"],"url":["http://dev.opera.com/"],"org":["Opera"]}}],"rels":{},"rel-urls":{}};
-
- it('table', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geo.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geo.js
deleted file mode 100644
index 8ed7d747d..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geo.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-adr/geo
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-adr', function() {
- var htmlFragment = "<p class=\"h-adr\">\n <span class=\"p-name\">Bricklayer's Arms</span>\n <span class=\"p-label\"> \n <span class=\"p-street-address\">3 Charlotte Road</span>, \n <span class=\"p-locality\">City of London</span>, \n <span class=\"p-postal-code\">EC2A 3PE</span>, \n <span class=\"p-country-name\">UK</span> \n </span> – \n Geo:(<span class=\"p-geo\">51.526421;-0.081067</span>) \n</p>";
- var expected = {"items":[{"type":["h-adr"],"properties":{"name":["Bricklayer's Arms"],"label":["3 Charlotte Road, \n City of London, \n EC2A 3PE, \n UK"],"street-address":["3 Charlotte Road"],"locality":["City of London"],"postal-code":["EC2A 3PE"],"country-name":["UK"],"geo":["51.526421;-0.081067"]}}],"rels":{},"rel-urls":{}};
-
- it('geo', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geourl.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geourl.js
deleted file mode 100644
index b97e76f60..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-geourl.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-adr/geourl
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-adr', function() {
- var htmlFragment = "<p class=\"h-adr\">\n <a class=\"p-name u-geo\" href=\"geo:51.526421;-0.081067;crs=wgs84;u=40\">Bricklayer's Arms</a>, \n <span class=\"p-locality\">London</span> \n</p>";
- var expected = {"items":[{"type":["h-adr"],"properties":{"name":["Bricklayer's Arms"],"geo":["geo:51.526421;-0.081067;crs=wgs84;u=40"],"locality":["London"],"url":["geo:51.526421;-0.081067;crs=wgs84;u=40"]}}],"rels":{},"rel-urls":{}};
-
- it('geourl', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-justaname.js
deleted file mode 100644
index c943fbafc..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-adr/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-adr', function() {
- var htmlFragment = "<p class=\"h-adr\">665 3rd St. Suite 207 San Francisco, CA 94107 U.S.A.</p>";
- var expected = {"items":[{"type":["h-adr"],"properties":{"name":["665 3rd St. Suite 207 San Francisco, CA 94107 U.S.A."]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-simpleproperties.js
deleted file mode 100644
index 084dac440..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-adr-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-adr/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-adr', function() {
- var htmlFragment = "<p class=\"h-adr\">\n <span class=\"p-street-address\">665 3rd St.</span> \n <span class=\"p-extended-address\">Suite 207</span> \n <span class=\"p-locality\">San Francisco</span>, \n <span class=\"p-region\">CA</span> \n <span class=\"p-postal-code\">94107</span> \n <span class=\"p-country-name\">U.S.A.</span> \n</p>";
- var expected = {"items":[{"type":["h-adr"],"properties":{"street-address":["665 3rd St."],"extended-address":["Suite 207"],"locality":["San Francisco"],"region":["CA"],"postal-code":["94107"],"country-name":["U.S.A."],"name":["665 3rd St. \n Suite 207 \n San Francisco, \n CA \n 94107 \n U.S.A."]}}],"rels":{},"rel-urls":{}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-as-note-note.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-as-note-note.js
deleted file mode 100644
index 7e0ac260c..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-as-note-note.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-as-note/note
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-as-note', function() {
- var htmlFragment = "<!-- http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy -->\n<base href=\"http://tantek.com/\" />\n\n<li class=\"h-entry hentry h-as-note\">\n <div>\n <ul>\n <li>\n <a href=\"152/t1/congrats-fellow-elected-w3cab-members\" id=\"previtem\" title=\"View the previous (older) item in the stream.\"\n rel=\"prev\"><abbr title=\"Previous\">←</abbr></a>\n </li>\n <li>\n <a href=\"152/t3/going-indiewebcamp-2015-portland\" id=\"nextitem\" title=\"View the next (newer) item in the stream\" rel=\"next\"><abbr title=\"Next\">→</abbr></a>\n </li>\n </ul>\n </div>\n <div>In reply to:\n <p>\n <a class=\"u-in-reply-to h-cite\" rel=\"in-reply-to\" href=\"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\">http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far</a>\n </p>\n <p>\n <a class=\"u-in-reply-to h-cite\" rel=\"in-reply-to\" href=\"https://twitter.com/benwerd/status/604733231284383744\">https://twitter.com/benwerd/status/604733231284383744</a>\n </p>\n <hr>\n </div>\n <a href=\"../\" class=\"p-author h-card\" rel=\"author\" title=\"Tantek Çelik\"><img src=\"/images/photo.gif\" alt=\"Tantek Çelik\"></a>\n <p class=\"p-name entry-title e-content entry-content article\">\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/benwerd\">@benwerd</a>\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/erinjo\">@erinjo</a>also proud of you &amp;\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/withknown\">@withknown</a>— so much #indieweb &amp; especially user empathy. Keep up the great work!</p>\n <span>\n <span class=\"dt-published published dt-updated updated\">\n <time class=\"value\" datetime=\"22:20-0700\">22:20</time>on\n <time class=\"value\">2015-06-01</time>\n </span>\n <span class=\"lt\">(ttk.me t4bT2)</span>using\n <span class=\"using\">BBEdit</span>\n </span>\n <div>\n <form action=\"http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy\">\n <div>\n <label>\n <span class=\"lt\">URL:</span>\n <input class=\"u-url url u-uid uid bookmark\" type=\"url\" size=\"70\" style=\"max-width:100%\" value=\"http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy\">\n </label>\n </div>\n </form>\n </div>\n <div>\n <a class=\"u-syndication\" rel=\"syndication\" style=\"float:right;\" href=\"https://twitter.com/t/status/605604965566906369\">\n <img src=\"/images/photo.gif\" style=\"vertical-align:-30%\" alt=\"\"> \n View \n Conversation\n on Twitter\n</a>\n </div>\n</li>";
- var expected = {"items":[{"type":["h-entry","h-as-note"],"properties":{"in-reply-to":[{"value":"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far","type":["h-cite"],"properties":{"name":["http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far"],"url":["http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far"]}},{"value":"https://twitter.com/benwerd/status/604733231284383744","type":["h-cite"],"properties":{"name":["https://twitter.com/benwerd/status/604733231284383744"],"url":["https://twitter.com/benwerd/status/604733231284383744"]}}],"author":[{"type":["h-card"],"properties":{"name":["Tantek Çelik"],"photo":["http://tantek.com/images/photo.gif"],"url":["http://tantek.com/"]}}],"name":["@benwerd\n @erinjoalso proud of you &\n @withknown— so much #indieweb & especially user empathy. Keep up the great work!"],"content":[{"value":"@benwerd\n @erinjoalso proud of you &\n @withknown— so much #indieweb & especially user empathy. Keep up the great work!","html":"\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/benwerd\">@benwerd</a>\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/erinjo\">@erinjo</a>also proud of you &\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/withknown\">@withknown</a>— so much #indieweb & especially user empathy. Keep up the great work!"}],"published":["2015-06-01 22:20-07:00"],"updated":["2015-06-01 22:20-07:00"],"url":["http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy"],"uid":["http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy"],"syndication":["https://twitter.com/t/status/605604965566906369"]},"children":[{"value":"@benwerd","type":["h-x-username"],"properties":{"name":["@benwerd"],"url":["https://twitter.com/benwerd"]}},{"value":"@erinjo","type":["h-x-username"],"properties":{"name":["@erinjo"],"url":["https://twitter.com/erinjo"]}},{"value":"@withknown","type":["h-x-username"],"properties":{"name":["@withknown"],"url":["https://twitter.com/withknown"]}}]}],"rels":{"prev":["http://tantek.com/152/t1/congrats-fellow-elected-w3cab-members"],"next":["http://tantek.com/152/t3/going-indiewebcamp-2015-portland"],"in-reply-to":["http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far","https://twitter.com/benwerd/status/604733231284383744"],"author":["http://tantek.com/"],"syndication":["https://twitter.com/t/status/605604965566906369"]},"rel-urls":{"http://tantek.com/152/t1/congrats-fellow-elected-w3cab-members":{"title":"View the previous (older) item in the stream.","text":"←","rels":["prev"]},"http://tantek.com/152/t3/going-indiewebcamp-2015-portland":{"title":"View the next (newer) item in the stream","text":"→","rels":["next"]},"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far":{"text":"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far","rels":["in-reply-to"]},"https://twitter.com/benwerd/status/604733231284383744":{"text":"https://twitter.com/benwerd/status/604733231284383744","rels":["in-reply-to"]},"http://tantek.com/":{"title":"Tantek Çelik","rels":["author"]},"https://twitter.com/t/status/605604965566906369":{"text":"View \n Conversation\n on Twitter","rels":["syndication"]}}};
-
- it('note', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-baseurl.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-baseurl.js
deleted file mode 100644
index d098db392..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-baseurl.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/baseurl
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<base href=\"http://example.org\"/>\n<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card\" href=\"bios/mitchell-baker/\">Mozilla Foundation</a>)\n <img class=\"u-photo\" src=\"images/photo.gif\"/>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Mitchell Baker"],"url":["http://blog.lizardwrangler.com/"],"org":[{"value":"Mozilla Foundation","type":["h-card"],"properties":{"name":["Mozilla Foundation"],"url":["http://example.org/bios/mitchell-baker/"]}}],"photo":["http://example.org/images/photo.gif"]}}],"rels":{},"rel-urls":{}};
-
- it('baseurl', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-childimplied.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-childimplied.js
deleted file mode 100644
index 3ab1fa8ca..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-childimplied.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/childimplied
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<a class=\"h-card\" href=\"http://people.opera.com/howcome/\" title=\"Håkon Wium Lie, CTO Opera\">\n <article>\n <h2 class=\"p-name\">Håkon Wium Lie</h2>\n <img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/H%C3%A5kon-Wium-Lie-2009-03.jpg/215px-H%C3%A5kon-Wium-Lie-2009-03.jpg\" />\n </article>\n</a>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Håkon Wium Lie"],"photo":["http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/H%C3%A5kon-Wium-Lie-2009-03.jpg/215px-H%C3%A5kon-Wium-Lie-2009-03.jpg"],"url":["http://people.opera.com/howcome/"]}}],"rels":{},"rel-urls":{}};
-
- it('childimplied', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-extendeddescription.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-extendeddescription.js
deleted file mode 100644
index 8ee35b022..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-extendeddescription.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/extendeddescription
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<div class=\"h-card\">\n <img class=\"u-photo\" alt=\"photo of Mitchell\" src=\"http://blog.mozilla.org/press/files/2012/04/mitchell-baker.jpg\" />\n <p>\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a>\n (<a class=\"u-url\" href=\"https://twitter.com/MitchellBaker\">@MitchellBaker</a>)\n <span class=\"p-org\">Mozilla Foundation</span>\n </p>\n <p class=\"p-note\">Mitchell is responsible for setting the direction and scope of the Mozilla Foundation and its activities.</p>\n <p><span class=\"p-category\">Strategy</span> and <span class=\"p-category\">Leadership</span></p>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"photo":["http://blog.mozilla.org/press/files/2012/04/mitchell-baker.jpg"],"url":["http://blog.lizardwrangler.com/","https://twitter.com/MitchellBaker"],"name":["Mitchell Baker"],"org":["Mozilla Foundation"],"note":["Mitchell is responsible for setting the direction and scope of the Mozilla Foundation and its activities."],"category":["Strategy","Leadership"]}}],"rels":{},"rel-urls":{}};
-
- it('extendeddescription', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hcard.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hcard.js
deleted file mode 100644
index 961381610..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hcard.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/hcard
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card\" href=\"http://mozilla.org/\">Mozilla Foundation</a>)\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"url":["http://blog.lizardwrangler.com/"],"name":["Mitchell Baker"],"org":[{"value":"Mozilla Foundation","type":["h-card"],"properties":{"name":["Mozilla Foundation"],"url":["http://mozilla.org/"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('hcard', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-horghcard.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-horghcard.js
deleted file mode 100644
index bc6329ae6..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-horghcard.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/horghcard
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card h-org\" href=\"http://mozilla.org/\">Mozilla Foundation</a>)\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Mitchell Baker"],"url":["http://blog.lizardwrangler.com/"],"org":[{"value":"Mozilla Foundation","type":["h-card","h-org"],"properties":{"name":["Mozilla Foundation"],"url":["http://mozilla.org/"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('horghcard', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hyperlinkedphoto.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hyperlinkedphoto.js
deleted file mode 100644
index 70febcb84..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-hyperlinkedphoto.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/hyperlinkedphoto
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<a class=\"h-card\" href=\"http://rohit.khare.org/\">\n <img alt=\"Rohit Khare\" src=\"images/photo.gif\" />\n </a>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Rohit Khare"],"photo":["http://example.com/images/photo.gif"],"url":["http://rohit.khare.org/"]}}],"rels":{},"rel-urls":{}};
-
- it('hyperlinkedphoto', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedname.js
deleted file mode 100644
index bcf45aecb..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/impliedname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "\n<img class=\"h-card\" src=\"jane.html\" alt=\"Jane Doe\"/>\n<area class=\"h-card\" href=\"jane.html\" alt=\"Jane Doe\"></area>\n<abbr class=\"h-card\" title=\"Jane Doe\">JD</abbr>\n\n<div class=\"h-card\"><img src=\"jane.html\" alt=\"Jane Doe\"/></div>\n<div class=\"h-card\"><area href=\"jane.html\" alt=\"Jane Doe\"></area></div>\n<div class=\"h-card\"><abbr title=\"Jane Doe\">JD</abbr></div>\n\n<div class=\"h-card\"><span><img src=\"jane.html\" alt=\"Jane Doe\"/></span></div>\n<div class=\"h-card\"><span><area href=\"jane.html\" alt=\"Jane Doe\"></area></span></div>\n<div class=\"h-card\"><span><abbr title=\"Jane Doe\">JD</abbr></span></div>\n\n<div class=\"h-card\"><img class=\"h-card\" src=\"john.html\" alt=\"John Doe\"/>Name</div>\n<div class=\"h-card\"><span class=\"h-card\"><img src=\"john.html\" alt=\"John Doe\"/>Name</span></div>\n";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"]}},{"type":["h-card"],"properties":{"name":["Name"]},"children":[{"type":["h-card"],"properties":{"name":["John Doe"],"photo":["http://example.com/john.html"]}}]},{"type":["h-card"],"properties":{"name":["Name"]},"children":[{"value":"Name","type":["h-card"],"properties":{"name":["John Doe"],"photo":["http://example.com/john.html"]}}]}],"rels":{},"rel-urls":{}};
-
- it('impliedname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedphoto.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedphoto.js
deleted file mode 100644
index 3248a1d0f..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedphoto.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/impliedphoto
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<img class=\"h-card\" alt=\"Jane Doe\" src=\"jane.jpeg\"/>\n<object class=\"h-card\" data=\"jane.jpeg\"/>Jane Doe</object>\n\n<div class=\"h-card\"><img alt=\"Jane Doe\" src=\"jane.jpeg\"/></div> \n<div class=\"h-card\"><object data=\"jane.jpeg\"/>Jane Doe</object></div> \n\n<div class=\"h-card\"><span><img alt=\"Jane Doe\" src=\"jane.jpeg\"/></span></div> \n<div class=\"h-card\"><span><object data=\"jane.jpeg\"/>Jane Doe</object></span></div> \n\n<div class=\"h-card\"><img class=\"h-card\" alt=\"Jane Doe\" src=\"jane.jpeg\"/>Jane Doe</div> \n<div class=\"h-card\"><span class=\"h-card\"><object data=\"jane.jpeg\"/>Jane Doe</object></span></div> ";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"]},"children":[{"type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}}]},{"type":["h-card"],"properties":{"name":["Jane Doe"]},"children":[{"value":"Jane Doe","type":["h-card"],"properties":{"name":["Jane Doe"],"photo":["http://example.com/jane.jpeg"]}}]}],"rels":{},"rel-urls":{}};
-
- it('impliedphoto', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedurl.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedurl.js
deleted file mode 100644
index 4034194ce..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-impliedurl.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/impliedurl
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<a class=\"h-card\" href=\"jane.html\">Jane Doe</a>\n<area class=\"h-card\" href=\"jane.html\" alt=\"Jane Doe\"/ >\n<div class=\"h-card\" ><a href=\"jane.html\">Jane Doe</a><p></p></div> \n<div class=\"h-card\" ><area href=\"jane.html\">Jane Doe</area><p></p></div>\n<div class=\"h-card\" ><a class=\"h-card\" href=\"jane.html\">Jane Doe</a><p></p></div> ";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}},{"type":["h-card"],"properties":{"name":["Jane Doe"]},"children":[{"value":"Jane Doe","type":["h-card"],"properties":{"name":["Jane Doe"],"url":["http://example.com/jane.html"]}}]}],"rels":{},"rel-urls":{}};
-
- it('impliedurl', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justahyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justahyperlink.js
deleted file mode 100644
index 5911cc00f..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justahyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/justahyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<a class=\"h-card\" href=\"http://benward.me/\">Ben Ward</a>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Ben Ward"],"url":["http://benward.me/"]}}],"rels":{},"rel-urls":{}};
-
- it('justahyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justaname.js
deleted file mode 100644
index 4f239fab5..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<p class=\"h-card\">Frances Berriman</p>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Frances Berriman"]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-nested.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-nested.js
deleted file mode 100644
index da2336e29..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-nested.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/nested
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"h-org h-card\" href=\"http://mozilla.org/\">Mozilla Foundation</a>)\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Mitchell Baker"],"url":["http://blog.lizardwrangler.com/"]},"children":[{"value":"Mozilla Foundation","type":["h-org","h-card"],"properties":{"name":["Mozilla Foundation"],"url":["http://mozilla.org/"]}}]}],"rels":{},"rel-urls":{}};
-
- it('nested', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-p-property.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-p-property.js
deleted file mode 100644
index 0a365e34b..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-p-property.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/p-property
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<div class=\"h-card\">\n \n <span class=\"p-name\">\n <span class=\"p-given-name value\">John</span> \n <abbr class=\"p-additional-name\" title=\"Peter\">P</abbr> \n <span class=\"p-family-name value \">Doe</span> \n </span>\n <data class=\"p-honorific-suffix\" value=\"MSc\"></data>\n \n \n <br class=\"p-honorific-suffix\" />BSc<br />\n <hr class=\"p-honorific-suffix\" />BA\n \n \n <img class=\"p-honorific-suffix\" src=\"images/logo.gif\" alt=\"PHD\" />\n <img src=\"images/logo.gif\" alt=\"company logos\" usemap=\"#logomap\" />\n <map name=\"logomap\">\n <area class=\"p-org\" shape=\"rect\" coords=\"0,0,82,126\" href=\"madgex.htm\" alt=\"Madgex\" />\n <area class=\"p-org\" shape=\"circle\" coords=\"90,58,3\" href=\"mozilla.htm\" alt=\"Mozilla\" />\n </map>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["John Doe"],"given-name":["John"],"additional-name":["Peter"],"family-name":["Doe"],"honorific-suffix":["MSc","PHD"],"org":["Madgex","Mozilla"]}}],"rels":{},"rel-urls":{}};
-
- it('p-property', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-relativeurls.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-relativeurls.js
deleted file mode 100644
index 712a8cf72..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-card-relativeurls.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-card/relativeurls
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-card', function() {
- var htmlFragment = "<base href=\"http://example.com\" >\n<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card\" href=\"bios/mitchell-baker/\">Mozilla Foundation</a>)\n <img class=\"u-photo\" src=\"bios/mitchell-baker/picture.jpeg\"/>\n</div>";
- var expected = {"items":[{"type":["h-card"],"properties":{"name":["Mitchell Baker"],"url":["http://blog.lizardwrangler.com/"],"org":[{"value":"Mozilla Foundation","type":["h-card"],"properties":{"name":["Mozilla Foundation"],"url":["http://example.com/bios/mitchell-baker/"]}}],"photo":["http://example.com/bios/mitchell-baker/picture.jpeg"]}}],"rels":{},"rel-urls":{}};
-
- it('relativeurls', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-impliedvalue-nested.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-impliedvalue-nested.js
deleted file mode 100644
index e729b48b0..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-impliedvalue-nested.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-entry/impliedvalue-nested
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-entry', function() {
- var htmlFragment = "<div class=\"h-entry\">\n <div class=\"u-in-reply-to h-cite\">\n <span class=\"p-author h-card\">\n <span class=\"p-name\">Example Author</span>\n <a class=\"u-url\" href=\"http://example.com\">Home</a>\n </span>\n <a class=\"p-name u-url\" href=\"http://example.com/post\">Example Post</a>\n </div>\n</div>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"in-reply-to":[{"type":["h-cite"],"properties":{"name":["Example Post"],"url":["http://example.com/post"],"author":[{"type":["h-card"],"properties":{"url":["http://example.com"],"name":["Example Author"]},"value":"Example Author"}]},"value":"http://example.com/post"}],"name":["Example Author\n Home\n \n Example Post"]}}],"rels":{},"rel-urls":{}};
-
- it('impliedvalue-nested', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justahyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justahyperlink.js
deleted file mode 100644
index 1e793e727..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justahyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-entry/justahyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-entry', function() {
- var htmlFragment = "<a class=\"h-entry\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"]}}],"rels":{},"rel-urls":{}};
-
- it('justahyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justaname.js
deleted file mode 100644
index f4d31bf87..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-entry/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-entry', function() {
- var htmlFragment = "<p class=\"h-entry\">microformats.org at 7</p>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"name":["microformats.org at 7"]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-summarycontent.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-summarycontent.js
deleted file mode 100644
index b697f6c7c..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-summarycontent.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-entry/summarycontent
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-entry', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"h-entry\">\n <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"e-content\">\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"name":["microformats.org at 7"],"content":[{"value":"Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service","html":"\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n "}],"summary":["Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities."],"updated":["2012-06-25 17:08:26"],"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('summarycontent', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-u-property.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-u-property.js
deleted file mode 100644
index 510f0aa90..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-u-property.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-entry/u-property
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-entry', function() {
- var htmlFragment = "<base href=\"http://example.com\">\n<div class=\"h-entry\">\n <p class=\"p-name\">microformats.org at 7</p>\n\n \n <p class=\"u-url\">\n <span class=\"value-title\" title=\"http://microformats.org/\"> </span>\n Article permalink\n </p>\n <p class=\"u-url\">\n <span class=\"value\">http://microformats.org/</span> - \n <span class=\"value\">2012/06/25/microformats-org-at-7</span> \n </p> \n\n <p><a class=\"u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">Article permalink</a></p>\n\n <img src=\"images/logo.gif\" alt=\"company logos\" usemap=\"#logomap\" />\n <map name=\"logomap\">\n <area class=\"u-url\" shape=\"rect\" coords=\"0,0,82,126\" href=\"http://microformats.org/\" alt=\"microformats.org\" />\n </map>\n\n <img class=\"u-photo\" src=\"images/logo.gif\" alt=\"company logos\" />\n\n <object class=\"u-url\" data=\"http://microformats.org/wiki/microformats2-parsing\"></object>\n\n <abbr class=\"u-url\" title=\"http://microformats.org/wiki/value-class-pattern\">value-class-pattern</abbr> \n <data class=\"u-url\" value=\"http://microformats.org/wiki/\"></data>\n <p class=\"u-url\">http://microformats.org/discuss</p>\n</div>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/","http://microformats.org/2012/06/25/microformats-org-at-7","http://microformats.org/2012/06/25/microformats-org-at-7","http://microformats.org/","http://microformats.org/wiki/microformats2-parsing","http://microformats.org/wiki/value-class-pattern","http://microformats.org/wiki/","http://microformats.org/discuss"],"photo":["http://example.com/images/logo.gif"]}}],"rels":{},"rel-urls":{}};
-
- it('u-property', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-urlincontent.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-urlincontent.js
deleted file mode 100644
index 295ac9925..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-entry-urlincontent.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-entry/urlincontent
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-entry', function() {
- var htmlFragment = "<div class=\"h-entry\">\n <h1><a class=\"p-name\">Expanding URLs within HTML content</a></h1>\n <div class=\"e-content\">\n <ul>\n <li><a href=\"http://www.w3.org/\">Should not change: http://www.w3.org/</a></li>\n <li><a href=\"http://example.com/\">Should not change: http://example.com/</a></li>\n <li><a href=\"test.html\">File relative: test.html = http://example.com/test.html</a></li>\n <li><a href=\"/test/test.html\">Directory relative: /test/test.html = http://example.com/test/test.html</a></li>\n <li><a href=\"/test.html\">Relative to root: /test.html = http://example.com/test.html</a></li>\n </ul>\n <img src=\"images/photo.gif\" />\n </div> \n</div>";
- var expected = {"items":[{"type":["h-entry"],"properties":{"name":["Expanding URLs within HTML content"],"content":[{"value":"Should not change: http://www.w3.org/\n Should not change: http://example.com/\n File relative: test.html = http://example.com/test.html\n Directory relative: /test/test.html = http://example.com/test/test.html\n Relative to root: /test.html = http://example.com/test.html","html":"\n <ul>\n <li><a href=\"http://www.w3.org/\">Should not change: http://www.w3.org/</a></li>\n <li><a href=\"http://example.com/\">Should not change: http://example.com/</a></li>\n <li><a href=\"http://example.com/test.html\">File relative: test.html = http://example.com/test.html</a></li>\n <li><a href=\"http://example.com/test/test.html\">Directory relative: /test/test.html = http://example.com/test/test.html</a></li>\n <li><a href=\"http://example.com/test.html\">Relative to root: /test.html = http://example.com/test.html</a></li>\n </ul>\n <img src=\"http://example.com/images/photo.gif\" />\n "}]}}],"rels":{},"rel-urls":{}};
-
- it('urlincontent', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-ampm.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-ampm.js
deleted file mode 100644
index 814c3c42e..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-ampm.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/ampm
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<span class=\"h-event\">\n <span class=\"p-name\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00am \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00p.m. \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00PM \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00am \n </span></li>\n </ul>\n</span>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The 4th Microformat party"],"start":["2009-06-26 19:00:00","2009-06-26 07:00:00","2009-06-26 19:00","2009-06-26 19","2009-06-26 19","2009-06-26 19:00","2009-06-26 19:00","2009-06-26 19:00","2009-06-26 07:00"]}}],"rels":{},"rel-urls":{}};
-
- it('ampm', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-attendees.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-attendees.js
deleted file mode 100644
index 2315dbe91..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-attendees.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/attendees
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"h-event\">\n <span class=\"p-name\">CPJ Online Press Freedom Summit</span>\n (<time class=\"dt-start\" datetime=\"2012-10-10\">10 Nov 2012</time>) in\n <span class=\"p-location\">San Francisco</span>.\n Attendees:\n <ul>\n <li class=\"p-attendee h-card\">Brian Warner</li>\n <li class=\"p-attendee h-card\">Kyle Machulis</li>\n <li class=\"p-attendee h-card\">Tantek Çelik</li>\n <li class=\"p-attendee h-card\">Sid Sutter</li>\n </ul>\n</div>\n";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["CPJ Online Press Freedom Summit"],"start":["2012-10-10"],"location":["San Francisco"],"attendee":[{"value":"Brian Warner","type":["h-card"],"properties":{"name":["Brian Warner"]}},{"value":"Kyle Machulis","type":["h-card"],"properties":{"name":["Kyle Machulis"]}},{"value":"Tantek Çelik","type":["h-card"],"properties":{"name":["Tantek Çelik"]}},{"value":"Sid Sutter","type":["h-card"],"properties":{"name":["Sid Sutter"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('attendees', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-combining.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-combining.js
deleted file mode 100644
index e91b381ba..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-combining.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/combining
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<div class=\"h-event\">\n <a class=\"p-name u-url\" href=\"http://indiewebcamp.com/2012\">\n IndieWebCamp 2012\n </a>\n from <time class=\"dt-start\">2012-06-30</time> \n to <time class=\"dt-end\">2012-07-01</time> at \n <span class=\"p-location h-card\">\n <a class=\"p-name p-org u-url\" href=\"http://geoloqi.com/\">Geoloqi</a>, \n <span class=\"p-street-address\">920 SW 3rd Ave. Suite 400</span>, \n <span class=\"p-locality\">Portland</span>, \n <abbr class=\"p-region\" title=\"Oregon\">OR</abbr>\n </span>\n</div>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["IndieWebCamp 2012"],"url":["http://indiewebcamp.com/2012"],"start":["2012-06-30"],"end":["2012-07-01"],"location":[{"value":"Geoloqi","type":["h-card"],"properties":{"name":["Geoloqi"],"org":["Geoloqi"],"url":["http://geoloqi.com/"],"street-address":["920 SW 3rd Ave. Suite 400"],"locality":["Portland"],"region":["Oregon"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('combining', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-concatenate.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-concatenate.js
deleted file mode 100644
index 897210674..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-concatenate.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/concatenate
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<span class=\"h-event\">\n <span class=\"p-name\">The 4th Microformat party</span> will be on \n <span class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time></span> to \n <span class=\"dt-end\"><time class=\"value\">22:00</time></span>.\n</span>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The 4th Microformat party"],"start":["2009-06-26 19:00"],"end":["2009-06-26 22:00"]}}],"rels":{},"rel-urls":{}};
-
- it('concatenate', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dates.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dates.js
deleted file mode 100644
index c26b5bccc..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dates.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/dates
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<section class=\"h-event\">\n\t<p><span class=\"p-name\">The 4th Microformat party</span> will be on:</p>\n\t<ul>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00-08:00\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00-08\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00-0800\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00+0800\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00+08:00\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00Z\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26t19:00-08:00\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26 19:00:00-08:00\">26 July</time></li>\n\t</ul>\n</section>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The 4th Microformat party"],"start":["2009-06-26 19:00-08:00","2009-06-26 19:00-08","2009-06-26 19:00-08:00","2009-06-26 19:00+08:00","2009-06-26 19:00+08:00","2009-06-26 19:00Z","2009-06-26 19:00-08:00","2009-06-26 19:00:00-08:00"]}}],"rels":{},"rel-urls":{}};
-
- it('dates', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dt-property.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dt-property.js
deleted file mode 100644
index eb97beccb..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-dt-property.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/dt-property
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<span class=\"h-event\">\n <span class=\"p-name\">The party</span> will be on \n \n <p class=\"dt-start\">\n <span class=\"value-title\" title=\"2013-03-14\"> </span>\n March 14th 2013\n </p>\n <p class=\"dt-start\">\n <time class=\"value\" datetime=\"2013-06-25\">25 July</time>, from\n <span class=\"value\">07:00:00am \n </span></p> \n \n <p>\n <time class=\"dt-start\" datetime=\"2013-06-26\">26 June</time>\n \n <ins class=\"dt-start\" datetime=\"2013-06-27\">Just added</ins>, \n <del class=\"dt-start\" datetime=\"2013-06-28\">Removed</del>\n </p>\n <abbr class=\"dt-start\" title=\"2013-06-29\">June 29</abbr> \n <data class=\"dt-start\" value=\"2013-07-01\"></data>\n <p class=\"dt-start\">2013-07-02</p>\n \n</span>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The party"],"start":["2013-03-14","2013-06-25 07:00:00","2013-06-26","2013-06-27","2013-06-28","2013-06-29","2013-07-01","2013-07-02"]}}],"rels":{},"rel-urls":{}};
-
- it('dt-property', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justahyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justahyperlink.js
deleted file mode 100644
index 26c835863..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justahyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/justahyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<a class=\"h-event\" href=\"http://indiewebcamp.com/2012\">IndieWebCamp 2012</a>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["IndieWebCamp 2012"],"url":["http://indiewebcamp.com/2012"]}}],"rels":{},"rel-urls":{}};
-
- it('justahyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justaname.js
deleted file mode 100644
index be3a5335d..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<p class=\"h-event\">IndieWebCamp 2012</p>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["IndieWebCamp 2012"]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-time.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-time.js
deleted file mode 100644
index 243b518bf..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-event-time.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-event/time
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-event', function() {
- var htmlFragment = "<span class=\"h-event\">\n <span class=\"p-name\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-08:00</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-0800</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00+0800</time> \n </li> \n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00Z</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00-08:00</time> \n </li> \n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00+08:00</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00Z</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time> \n </li> \n <li>\n <time class=\"dt-end\" datetime=\"2013-034\">3 February 2013</time>\n </li>\n <li>\n <time class=\"dt-end\" datetime=\"2013-06-27 15:34\">26 July 2013</time>\n </li> \n </ul>\n</span>";
- var expected = {"items":[{"type":["h-event"],"properties":{"name":["The 4th Microformat party"],"start":["2009-06-26 19:00:00-08:00","2009-06-26 19:00:00-08:00","2009-06-26 19:00:00+08:00","2009-06-26 19:00:00Z","2009-06-26 19:00:00","2009-06-26 19:00-08:00","2009-06-26 19:00+08:00","2009-06-26 19:00Z","2009-06-26 19:00"],"end":["2013-034","2013-06-27 15:34"]}}],"rels":{},"rel-urls":{}};
-
- it('time', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-implied-title.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-implied-title.js
deleted file mode 100644
index 30bbf52df..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-implied-title.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-feed/implied-title
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-feed', function() {
- var htmlFragment = "\n<html>\n\t<head>\n\t\t<title>microformats blog</title>\n\t</head>\n\t<body>\n\t<section class=\"h-feed\">\n\t\t\n\t\t<div class=\"h-entry\">\n\t\t <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n\t\t <div class=\"e-content\">\n\t\t <p class=\"p-summary\">Last week the microformats.org community \n\t\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t\t San Francisco and recognized accomplishments, challenges, and \n\t\t opportunities.</p>\n\t\t\n\t\t <p>The microformats tagline “humans first, machines second” \n\t\t forms the basis of many of our \n\t\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t\t in that regard, we’d like to recognize a few people and \n\t\t thank them for their years of volunteer service </p>\n\t\t </div> \n\t\t <p>Updated \n\t\t <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time>\n\t\t </p>\n\t\t</div>\n\t\t\n\t</section>\n\t</body>\n</html>";
- var expected = {"items":[{"type":["h-feed"],"properties":{"name":["microformats blog"]},"children":[{"value":"microformats.org at 7\n\t\t \n\t\t Last week the microformats.org community \n\t\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t\t San Francisco and recognized accomplishments, challenges, and \n\t\t opportunities.\n\t\t\n\t\t The microformats tagline “humans first, machines second” \n\t\t forms the basis of many of our \n\t\t principles, and \n\t\t in that regard, we’d like to recognize a few people and \n\t\t thank them for their years of volunteer service \n\t\t \n\t\t Updated \n\t\t June 25th, 2012","type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"content":[{"value":"Last week the microformats.org community \n\t\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t\t San Francisco and recognized accomplishments, challenges, and \n\t\t opportunities.\n\t\t\n\t\t The microformats tagline “humans first, machines second” \n\t\t forms the basis of many of our \n\t\t principles, and \n\t\t in that regard, we’d like to recognize a few people and \n\t\t thank them for their years of volunteer service","html":"\n\t\t <p class=\"p-summary\">Last week the microformats.org community \n\t\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t\t San Francisco and recognized accomplishments, challenges, and \n\t\t opportunities.</p>\n\t\t\n\t\t <p>The microformats tagline “humans first, machines second” \n\t\t forms the basis of many of our \n\t\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t\t in that regard, we’d like to recognize a few people and \n\t\t thank them for their years of volunteer service </p>\n\t\t "}],"summary":["Last week the microformats.org community \n\t\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t\t San Francisco and recognized accomplishments, challenges, and \n\t\t opportunities."],"updated":["2012-06-25 17:08:26"]}}]}],"rels":{},"rel-urls":{}};
-
- it('implied-title', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-simple.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-simple.js
deleted file mode 100644
index c72b24140..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-feed-simple.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-feed/simple
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-feed', function() {
- var htmlFragment = "<section class=\"h-feed\">\n\t<h1 class=\"p-name\">Microformats blog</h1>\n\t<a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n\t<a class=\"u-url\" href=\"http://microformats.org/blog\">permlink</a>\n\t<img class=\"u-photo\" src=\"photo.jpeg\"/>\n\t\n\t<div class=\"h-entry\">\n\t <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n\t <div class=\"e-content\">\n\t <p class=\"p-summary\">Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.</p>\n\t\n\t <p>The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service </p>\n\t </div> \n\t <p>Updated \n\t <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time>\n\t </p>\n\t</div>\n\t\n</section>";
- var expected = {"items":[{"type":["h-feed"],"properties":{"name":["Microformats blog"],"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}],"url":["http://microformats.org/blog"],"photo":["http://example.com/photo.jpeg"]},"children":[{"value":"microformats.org at 7\n\t \n\t Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.\n\t\n\t The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t principles, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service \n\t \n\t Updated \n\t June 25th, 2012","type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"content":[{"value":"Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.\n\t\n\t The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t principles, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service","html":"\n\t <p class=\"p-summary\">Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.</p>\n\t\n\t <p>The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service </p>\n\t "}],"summary":["Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities."],"updated":["2012-06-25 17:08:26"]}}]}],"rels":{},"rel-urls":{}};
-
- it('simple', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-abbrpattern.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-abbrpattern.js
deleted file mode 100644
index d26e9ed0d..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-abbrpattern.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-geo/abbrpattern
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-geo', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<p class=\"h-geo\">\n <abbr class=\"p-latitude\" title=\"37.408183\">N 37° 24.491</abbr>, \n <abbr class=\"p-longitude\" title=\"-122.13855\">W 122° 08.313</abbr>\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["37.408183"],"longitude":["-122.13855"],"name":["N 37° 24.491, \n W 122° 08.313"]}}],"rels":{},"rel-urls":{}};
-
- it('abbrpattern', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-altitude.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-altitude.js
deleted file mode 100644
index 45da683ff..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-altitude.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-geo/altitude
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-geo', function() {
- var htmlFragment = "<p>My favourite hill in the lakes is \n <span class=\"h-geo\">\n <span class=\"p-name\">Pen-y-ghent</span> \n (Geo: <span class=\"p-latitude\">54.155278</span>,\n <span class=\"p-longitude\">-2.249722</span>). It\n raises to <span class=\"p-altitude\">694</span>m.\n </span>\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"name":["Pen-y-ghent"],"latitude":["54.155278"],"longitude":["-2.249722"],"altitude":["694"]}}],"rels":{},"rel-urls":{}};
-
- it('altitude', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-hidden.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-hidden.js
deleted file mode 100644
index 968ed1285..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-hidden.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-geo/hidden
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-geo', function() {
- var htmlFragment = "<p>\n <span class=\"h-geo\">The Bricklayer's Arms\n <span class=\"p-latitude\">\n <span class=\"value-title\" title=\"51.513458\"> </span> \n </span>\n <span class=\"p-longitude\">\n <span class=\"value-title\" title=\"-0.14812\"> </span>\n </span>\n </span>\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["51.513458"],"longitude":["-0.14812"],"name":["The Bricklayer's Arms"]}}],"rels":{},"rel-urls":{}};
-
- it('hidden', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-justaname.js
deleted file mode 100644
index 23c142462..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-geo/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-geo', function() {
- var htmlFragment = "<p>On my way to The Bricklayer's Arms\n (Geo: <span class=\"h-geo\">51.513458;-0.14812</span>)\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"name":["51.513458;-0.14812"]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-simpleproperties.js
deleted file mode 100644
index e9700a3e2..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-geo/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-geo', function() {
- var htmlFragment = "<p class=\"h-geo\">We are meeting at \n <span class=\"p-name\">The Bricklayer's Arms</span>\n (Geo: <span class=\"p-latitude\">51.513458</span>:\n <span class=\"p-longitude\">-0.14812</span>)\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"name":["The Bricklayer's Arms"],"latitude":["51.513458"],"longitude":["-0.14812"]}}],"rels":{},"rel-urls":{}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-valuetitleclass.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-valuetitleclass.js
deleted file mode 100644
index 813d21592..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-geo-valuetitleclass.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-geo/valuetitleclass
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-geo', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<p>\n <span class=\"h-geo\">\n <span class=\"p-latitude\">\n <span class=\"value-title\" title=\"51.513458\">N 51° 51.345</span>, \n </span>\n <span class=\"p-longitude\">\n <span class=\"value-title\" title=\"-0.14812\">W -0° 14.812</span>\n </span>\n </span>\n</p>";
- var expected = {"items":[{"type":["h-geo"],"properties":{"latitude":["51.513458"],"longitude":["-0.14812"],"name":["N 51° 51.345, \n \n \n W -0° 14.812"]}}],"rels":{},"rel-urls":{}};
-
- it('valuetitleclass', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-news-all.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-news-all.js
deleted file mode 100644
index a7deb3f2f..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-news-all.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-news/all
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-news', function() {
- var htmlFragment = "<div class=\"h-news\">\n <div class=\"p-entry h-entry\">\n <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"e-content\">\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n </p>\n </div>\n\n <p>\n <span class=\"p-dateline h-adr\">\n <span class=\"p-locality\">San Francisco</span>, \n <span class=\"p-region\">CA</span> \n </span>\n (Geo: <span class=\"p-geo\">37.774921;-122.445202</span>) \n <span class=\"p-source-org h-card\">\n <a class=\"p-name u-url\" href=\"http://microformats.org/\">microformats.org</a>\n </span>\n </p>\n <p>\n <a class=\"u-principles\" href=\"http://microformats.org/wiki/Category:public_domain_license\">Publishing policy</a>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-news"],"properties":{"entry":[{"value":"microformats.org at 7","type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"content":[{"value":"Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service","html":"\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n "}],"summary":["Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities."],"updated":["2012-06-25 17:08:26"],"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}]}}],"dateline":[{"value":"San Francisco, \n CA","type":["h-adr"],"properties":{"locality":["San Francisco"],"region":["CA"],"name":["San Francisco, \n CA"]}}],"geo":["37.774921;-122.445202"],"source-org":[{"value":"microformats.org","type":["h-card"],"properties":{"name":["microformats.org"],"url":["http://microformats.org/"]}}],"principles":["http://microformats.org/wiki/Category:public_domain_license"],"name":["microformats.org at 7\n \n Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service \n \n Updated \n June 25th, 2012 by\n Tantek\n \n \n\n \n \n San Francisco, \n CA \n \n (Geo: 37.774921;-122.445202) \n \n microformats.org\n \n \n \n Publishing policy"]}}],"rels":{},"rel-urls":{}};
-
- it('all', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-news-minimum.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-news-minimum.js
deleted file mode 100644
index 4494cb8ab..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-news-minimum.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-news/minimum
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-news', function() {
- var htmlFragment = "<div class=\"h-news\">\n <div class=\"p-entry h-entry\">\n <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"e-content\">\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n </p>\n </div>\n <p>\n <a class=\"p-source-org h-card\" href=\"http://microformats.org/\">microformats.org</a> \n </p>\n</div>";
- var expected = {"items":[{"type":["h-news"],"properties":{"entry":[{"value":"microformats.org at 7","type":["h-entry"],"properties":{"name":["microformats.org at 7"],"url":["http://microformats.org/2012/06/25/microformats-org-at-7"],"content":[{"value":"Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service","html":"\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n "}],"summary":["Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities."],"updated":["2012-06-25 17:08:26"],"author":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"],"url":["http://tantek.com/"]}}]}}],"source-org":[{"value":"microformats.org","type":["h-card"],"properties":{"name":["microformats.org"],"url":["http://microformats.org/"]}}],"name":["microformats.org at 7\n \n Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.\n\n The microformats tagline “humans first, machines second” \n forms the basis of many of our \n principles, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service \n \n Updated \n June 25th, 2012 by\n Tantek\n \n \n \n microformats.org"]}}],"rels":{},"rel-urls":{}};
-
- it('minimum', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-hyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-hyperlink.js
deleted file mode 100644
index b7150aae4..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-hyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-org/hyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-org', function() {
- var htmlFragment = "<a class=\"h-org\" href=\"http://mozilla.org/\">Mozilla Foundation</a>";
- var expected = {"items":[{"type":["h-org"],"properties":{"name":["Mozilla Foundation"],"url":["http://mozilla.org/"]}}],"rels":{},"rel-urls":{}};
-
- it('hyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simple.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simple.js
deleted file mode 100644
index 4f5a75e88..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simple.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-org/simple
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-org', function() {
- var htmlFragment = "<span class=\"h-org\">Mozilla Foundation</span>";
- var expected = {"items":[{"type":["h-org"],"properties":{"name":["Mozilla Foundation"]}}],"rels":{},"rel-urls":{}};
-
- it('simple', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simpleproperties.js
deleted file mode 100644
index 5c7e939e6..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-org-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-org/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-org', function() {
- var htmlFragment = "<p class=\"h-org\">\n <span class=\"p-organization-name\">W3C</span> - \n <span class=\"p-organization-unit\">CSS Working Group</span>\n</p>";
- var expected = {"items":[{"type":["h-org"],"properties":{"organization-name":["W3C"],"organization-unit":["CSS Working Group"],"name":["W3C - \n CSS Working Group"]}}],"rels":{},"rel-urls":{}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-aggregate.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-aggregate.js
deleted file mode 100644
index b07d3f547..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-aggregate.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-product/aggregate
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-product', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"h-product\">\n <h2 class=\"p-name\">Raspberry Pi</h2>\n <img class=\"u-photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"e-description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"u-url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"p-price\">£29.95</p>\n <p class=\"p-review h-review-aggregate\">\n <span class=\"p-rating h-rating\">\n <span class=\"p-average\">9.2</span> out of \n <span class=\"p-best\">10</span> \n based on <span class=\"p-count\">178</span> reviews\n </span>\n </p>\n <p>Categories: <span class=\"p-category\">Computer</span>, <span class=\"p-category\">Education</span></p>\n <p class=\"p-brand h-card\">From: \n <span class=\"p-name p-org\">The Raspberry Pi Foundation</span> - \n <span class=\"p-locality\">Cambridge</span> \n <span class=\"p-country-name\">UK</span>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-product"],"properties":{"name":["Raspberry Pi"],"photo":["http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg"],"description":[{"value":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.","html":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming."}],"url":["http://www.raspberrypi.org/"],"price":["£29.95"],"review":[{"value":"9.2 out of \n 10 \n based on 178 reviews","type":["h-review-aggregate"],"properties":{"rating":[{"value":"9.2 out of \n 10 \n based on 178 reviews","type":["h-rating"],"properties":{"average":["9.2"],"best":["10"],"count":["178"],"name":["9.2 out of \n 10 \n based on 178 reviews"]}}],"name":["9.2 out of \n 10 \n based on 178 reviews"]}}],"category":["Computer","Education"],"brand":[{"value":"The Raspberry Pi Foundation","type":["h-card"],"properties":{"name":["The Raspberry Pi Foundation"],"org":["The Raspberry Pi Foundation"],"locality":["Cambridge"],"country-name":["UK"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('aggregate', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justahyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justahyperlink.js
deleted file mode 100644
index cf2638e31..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justahyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-product/justahyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-product', function() {
- var htmlFragment = "<a class=\"h-product\" href=\"http://www.raspberrypi.org/\">Raspberry Pi</a>";
- var expected = {"items":[{"type":["h-product"],"properties":{"name":["Raspberry Pi"],"url":["http://www.raspberrypi.org/"]}}],"rels":{},"rel-urls":{}};
-
- it('justahyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justaname.js
deleted file mode 100644
index f946a10e0..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-product/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-product', function() {
- var htmlFragment = "<p class=\"h-product\">Raspberry Pi</p>";
- var expected = {"items":[{"type":["h-product"],"properties":{"name":["Raspberry Pi"]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-simpleproperties.js
deleted file mode 100644
index 1c5467d51..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-product-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-product/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-product', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"h-product\">\n <h2 class=\"p-name\">Raspberry Pi</h2>\n <img class=\"u-photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"e-description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"u-url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"p-price\">£29.95</p>\n <p class=\"p-review h-review\"><span class=\"p-rating\">4.5</span> out of 5</p>\n <p>Categories: <span class=\"p-category\">Computer</span>, <span class=\"p-category\">Education</span></p>\n</div>";
- var expected = {"items":[{"type":["h-product"],"properties":{"name":["Raspberry Pi"],"photo":["http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg"],"description":[{"value":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.","html":"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming."}],"url":["http://www.raspberrypi.org/"],"price":["£29.95"],"category":["Computer","Education"],"review":[{"value":"4.5 out of 5","type":["h-review"],"properties":{"rating":["4.5"],"name":["4.5 out of 5"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-all.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-all.js
deleted file mode 100644
index fa0e4cb37..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-all.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-recipe/all
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-recipe', function() {
- var htmlFragment = "<section class=\"h-recipe\">\n <h1 class=\"p-name\">Yorkshire Puddings</h1> \n <p class=\"p-summary\">Makes <span class=\"p-yield\">6 good sized Yorkshire puddings</span>, the way my mum taught me</p>\n\n\n <p><img class=\"u-photo\" src=\"http://codebits.glennjones.net/semantic/yorkshire-puddings.jpg\" /></p>\n\n <span class=\"p-review h-review-aggregate\">\n <span class=\"p-rating\">\n <span class=\"p-average\">4.5</span> stars out 5 based on </span>\n <span class=\"p-count\">35</span> reviews</span>\n \n \n\n <div id=\"ingredients-container\">\n <h3>Ingredients</h3>\n <ul>\n <li class=\"e-ingredient\">1 egg</li>\n <li class=\"e-ingredient\">75g plain flour</li>\n <li class=\"e-ingredient\">70ml milk</li>\n <li class=\"e-ingredient\">60ml water</li>\n <li class=\"e-ingredient\">Pinch of salt</li>\n </ul>\n </div>\n\n <h3>Time</h3>\n <ul>\n <li class=\"prepTime\">Preparation <span class=\"value-title\" title=\"PT0H10M\">10 mins</span></li>\n <li class=\"cookTime\">Cook <span class=\"value-title\" title=\"PT0H25M\">25 mins</span></li>\n </ul> \n\n\n <h3>Instructions</h3>\n <div class=\"e-instructions\">\n <ol>\n <li>Pre-heat oven to 230C or gas mark 8. Pour the vegetable oil evenly into 2 x 4-hole \n Yorkshire pudding tins and place in the oven to heat through.</li> \n \n <li>To make the batter, add all the flour into a bowl and beat in the eggs until smooth. \n Gradually add the milk and water while beating the mixture. It should be smooth and \n without lumps. Finally add a pinch of salt.</li>\n \n <li>Make sure the oil is piping hot before pouring the batter evenly into the tins. \n Place in the oven for 20-25 minutes until pudding have risen and look golden brown</li>\n </ol>\n </div>\n\n <h3>Nutrition</h3>\n <ul id=\"nutrition-list\">\n <li class=\"p-nutrition\">Calories: <span class=\"calories\">125</span></li>\n <li class=\"p-nutrition\">Fat: <span class=\"fat\">3.2g</span></li>\n <li class=\"p-nutrition\">Cholesterol: <span class=\"cholesterol\">77mg</span></li>\n </ul>\n <p>(Amount per pudding)</p>\n\n <p>\n Published on <time class=\"dt-published\" datetime=\"2011-10-27\">27 Oct 2011</time> by \n <span class=\"p-author h-card\">\n <a class=\"p-name u-url\" href=\"http://glennjones.net\">Glenn Jones</a>\n </span>\n </p>\n <a href=\"http://www.flickr.com/photos/dithie/4106528495/\">Photo by dithie</a>\n </section>";
- var expected = {"items":[{"type":["h-recipe"],"properties":{"name":["Yorkshire Puddings"],"summary":["Makes 6 good sized Yorkshire puddings, the way my mum taught me"],"yield":["6 good sized Yorkshire puddings"],"photo":["http://codebits.glennjones.net/semantic/yorkshire-puddings.jpg"],"review":[{"value":"4.5 stars out 5 based on \n 35 reviews","type":["h-review-aggregate"],"properties":{"rating":["4.5 stars out 5 based on"],"average":["4.5"],"count":["35"],"name":["4.5 stars out 5 based on \n 35 reviews"]}}],"ingredient":[{"value":"1 egg","html":"1 egg"},{"value":"75g plain flour","html":"75g plain flour"},{"value":"70ml milk","html":"70ml milk"},{"value":"60ml water","html":"60ml water"},{"value":"Pinch of salt","html":"Pinch of salt"}],"instructions":[{"value":"Pre-heat oven to 230C or gas mark 8. Pour the vegetable oil evenly into 2 x 4-hole \n Yorkshire pudding tins and place in the oven to heat through. \n \n To make the batter, add all the flour into a bowl and beat in the eggs until smooth. \n Gradually add the milk and water while beating the mixture. It should be smooth and \n without lumps. Finally add a pinch of salt.\n \n Make sure the oil is piping hot before pouring the batter evenly into the tins. \n Place in the oven for 20-25 minutes until pudding have risen and look golden brown","html":"\n <ol>\n <li>Pre-heat oven to 230C or gas mark 8. Pour the vegetable oil evenly into 2 x 4-hole \n Yorkshire pudding tins and place in the oven to heat through.</li> \n \n <li>To make the batter, add all the flour into a bowl and beat in the eggs until smooth. \n Gradually add the milk and water while beating the mixture. It should be smooth and \n without lumps. Finally add a pinch of salt.</li>\n \n <li>Make sure the oil is piping hot before pouring the batter evenly into the tins. \n Place in the oven for 20-25 minutes until pudding have risen and look golden brown</li>\n </ol>\n "}],"nutrition":["Calories: 125","Fat: 3.2g","Cholesterol: 77mg"],"published":["2011-10-27"],"author":[{"value":"Glenn Jones","type":["h-card"],"properties":{"name":["Glenn Jones"],"url":["http://glennjones.net"]}}],"url":["http://www.flickr.com/photos/dithie/4106528495/"]}}],"rels":{},"rel-urls":{}};
-
- it('all', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-minimum.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-minimum.js
deleted file mode 100644
index ac3d91dc7..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-recipe-minimum.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-recipe/minimum
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-recipe', function() {
- var htmlFragment = "<div class=\"h-recipe\"> \n <p class=\"p-name\">Toast</p>\n <ul>\n <li class=\"e-ingredient\">Slice of bread</li>\n <li class=\"e-ingredient\">Butter</li>\n </ul>\n</div>";
- var expected = {"items":[{"type":["h-recipe"],"properties":{"name":["Toast"],"ingredient":[{"value":"Slice of bread","html":"Slice of bread"},{"value":"Butter","html":"Butter"}]}}],"rels":{},"rel-urls":{}};
-
- it('minimum', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-affiliation.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-affiliation.js
deleted file mode 100644
index 73329d46c..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-affiliation.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-resume/affiliation
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-resume', function() {
- var htmlFragment = "<div class=\"h-resume\">\n <p>\n <span class=\"p-name\">Tim Berners-Lee</span>, \n <span class=\"p-summary\">invented the World Wide Web</span>. \n </p> \n Belongs to following groups:\n <p> \n <a class=\"p-affiliation h-card\" href=\"http://www.w3.org/\">\n <img class=\"p-name u-photo\" alt=\"W3C\" src=\"http://www.w3.org/Icons/WWW/w3c_home_nb.png\" />\n </a>\n </p> \n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"name":["Tim Berners-Lee"],"summary":["invented the World Wide Web"],"affiliation":[{"type":["h-card"],"properties":{"name":["W3C"],"photo":["http://www.w3.org/Icons/WWW/w3c_home_nb.png"],"url":["http://www.w3.org/"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('affiliation', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-contact.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-contact.js
deleted file mode 100644
index f2a1f76f7..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-contact.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-resume/contact
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-resume', function() {
- var htmlFragment = "<div class=\"h-resume\">\n <p class=\"p-name\">Tim Berners-Lee</p>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <div class=\"p-contact h-card\">\n <p class=\"p-name\">MIT</p>\n <p>\n <span class=\"p-street-address\">32 Vassar Street</span>, \n <span class=\"p-extended-address\">Room 32-G524</span>, \n <span class=\"p-locality\">Cambridge</span>, \n <span class=\"p-region\">MA</span> \n <span class=\"p-postal-code\">02139</span>, \n <span class=\"p-country-name\">USA</span>.\n </p>\n <p>Tel:<span class=\"p-tel\">+1 (617) 253 5702</span></p>\n <p>Email:<a class=\"u-email\" href=\"mailto:timbl@w3.org\">timbl@w3.org</a></p>\n </div>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"name":["Tim Berners-Lee"],"summary":["Invented the World Wide Web."],"contact":[{"value":"MIT","type":["h-card"],"properties":{"name":["MIT"],"street-address":["32 Vassar Street"],"extended-address":["Room 32-G524"],"locality":["Cambridge"],"region":["MA"],"postal-code":["02139"],"country-name":["USA"],"tel":["+1 (617) 253 5702"],"email":["mailto:timbl@w3.org"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('contact', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-education.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-education.js
deleted file mode 100644
index 5e3838434..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-education.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-resume/education
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-resume', function() {
- var htmlFragment = "<div class=\"h-resume\">\n <p class=\"p-name\">Tim Berners-Lee</p>\n <div class=\"p-contact h-card\">\n <p class=\"p-title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <p class=\"p-education h-event h-card\">\n <span class=\"p-name p-org\">The Queen's College, Oxford University</span>, \n <span class=\"p-description\">BA Hons (I) Physics</span> \n <time class=\"dt-start\" datetime=\"1973-09\">1973</time> –\n <time class=\"dt-end\" datetime=\"1976-06\">1976</time>\n </p>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"name":["Tim Berners-Lee"],"contact":[{"value":"Director of the World Wide Web Foundation","type":["h-card"],"properties":{"title":["Director of the World Wide Web Foundation"],"name":["Director of the World Wide Web Foundation"]}}],"summary":["Invented the World Wide Web."],"education":[{"value":"The Queen's College, Oxford University","type":["h-event","h-card"],"properties":{"name":["The Queen's College, Oxford University"],"org":["The Queen's College, Oxford University"],"description":["BA Hons (I) Physics"],"start":["1973-09"],"end":["1976-06"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('education', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-justaname.js
deleted file mode 100644
index 2357bf1a2..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-resume/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-resume', function() {
- var htmlFragment = "<p class=\"h-resume\">Tim Berners-Lee, invented the World Wide Web.</p>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"name":["Tim Berners-Lee, invented the World Wide Web."]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-skill.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-skill.js
deleted file mode 100644
index 60a983e04..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-skill.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-resume/skill
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-resume', function() {
- var htmlFragment = "<div class=\"h-resume\">\n <p>\n <span class=\"p-name\">Tim Berners-Lee</span>, \n <span class=\"p-summary\">invented the World Wide Web</span>.\n </p>\n Skills: \n <ul>\n <li class=\"p-skill\">information systems</li>\n <li class=\"p-skill\">advocacy</li>\n <li class=\"p-skill\">leadership</li>\n <ul> \n</ul></ul></div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"name":["Tim Berners-Lee"],"summary":["invented the World Wide Web"],"skill":["information systems","advocacy","leadership"]}}],"rels":{},"rel-urls":{}};
-
- it('skill', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-work.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-work.js
deleted file mode 100644
index d61ea3de5..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-resume-work.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-resume/work
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-resume', function() {
- var htmlFragment = "<meta charset=\"utf-8\">\n<div class=\"h-resume\">\n <p class=\"p-name\">Tim Berners-Lee</p>\n <div class=\"p-contact h-card\">\n <p class=\"p-title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <div class=\"p-experience h-event h-card\">\n <p class=\"p-title\">Director</p>\n <p><a class=\"p-name p-org u-url\" href=\"http://www.webfoundation.org/\">World Wide Web Foundation</a></p>\n <p>\n <time class=\"dt-start\" datetime=\"2009-01-18\">Jan 2009</time> – Present\n <time class=\"dt-duration\" datetime=\"P2Y11M\">(2 years 11 month)</time>\n </p>\n </div>\n</div>";
- var expected = {"items":[{"type":["h-resume"],"properties":{"name":["Tim Berners-Lee"],"contact":[{"value":"Director of the World Wide Web Foundation","type":["h-card"],"properties":{"title":["Director of the World Wide Web Foundation"],"name":["Director of the World Wide Web Foundation"]}}],"summary":["Invented the World Wide Web."],"experience":[{"value":"World Wide Web Foundation","type":["h-event","h-card"],"properties":{"title":["Director"],"name":["World Wide Web Foundation"],"org":["World Wide Web Foundation"],"url":["http://www.webfoundation.org/"],"start":["2009-01-18"],"duration":["P2Y11M"]}}]}}],"rels":{},"rel-urls":{}};
-
- it('work', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-hevent.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-hevent.js
deleted file mode 100644
index e698ee37a..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-hevent.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review-aggregate/hevent
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review-aggregate', function() {
- var htmlFragment = "<div class=\"h-review-aggregate\">\n <div class=\"p-item h-event\">\n <h3 class=\"p-name\">Fullfrontal</h3>\n <p class=\"p-description\">A one day JavaScript Conference held in Brighton</p>\n <p><time class=\"dt-start\" datetime=\"2012-11-09\">9th November 2012</time></p> \n </div> \n \n <p class=\"p-rating\">\n <span class=\"p-average value\">9.9</span> out of \n <span class=\"p-best\">10</span> \n based on <span class=\"p-count\">62</span> reviews\n </p>\n</div>";
- var expected = {"items":[{"type":["h-review-aggregate"],"properties":{"item":[{"value":"Fullfrontal","type":["h-event"],"properties":{"name":["Fullfrontal"],"description":["A one day JavaScript Conference held in Brighton"],"start":["2012-11-09"]}}],"rating":["9.9"],"average":["9.9"],"best":["10"],"count":["62"],"name":["Fullfrontal\n A one day JavaScript Conference held in Brighton\n 9th November 2012 \n \n \n \n 9.9 out of \n 10 \n based on 62 reviews"]}}],"rels":{},"rel-urls":{}};
-
- it('hevent', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-justahyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-justahyperlink.js
deleted file mode 100644
index 729fdfb2d..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-justahyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review-aggregate/justahyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review-aggregate', function() {
- var htmlFragment = "<div class=\"h-review-aggregate\">\n <h3 class=\"p-item h-item\">Mediterranean Wraps</h3>\n <span class=\"p-summary\">\n Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff.\n </span>\n <span class=\"p-rating\">4.5</span> out of 5 \n</div>";
- var expected = {"items":[{"type":["h-review-aggregate"],"properties":{"item":[{"value":"Mediterranean Wraps","type":["h-item"],"properties":{"name":["Mediterranean Wraps"]}}],"summary":["Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff."],"rating":["4.5"],"name":["Mediterranean Wraps\n \n Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff.\n \n 4.5 out of 5"]}}],"rels":{},"rel-urls":{}};
-
- it('justahyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-simpleproperties.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-simpleproperties.js
deleted file mode 100644
index d49cabb5f..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-aggregate-simpleproperties.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review-aggregate/simpleproperties
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review-aggregate', function() {
- var htmlFragment = "<div class=\"h-review-aggregate\">\n <div class=\"p-item h-card\">\n <h3 class=\"p-name\">Mediterranean Wraps</h3>\n <p>\n <span class=\"p-street-address\">433 S California Ave</span>, \n <span class=\"p-locality\">Palo Alto</span>, \n <span class=\"p-region\">CA</span> - \n <span class=\"p-tel\">(650) 321-8189</span>\n </p>\n </div> \n <span class=\"p-summary\">Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff.</span>\n <span class=\"p-rating\">\n <span class=\"p-average value\">9.2</span> out of \n <span class=\"p-best\">10</span> \n based on <span class=\"p-count\">17</span> reviews\n </span>\n</div>";
- var expected = {"items":[{"type":["h-review-aggregate"],"properties":{"item":[{"value":"Mediterranean Wraps","type":["h-card"],"properties":{"name":["Mediterranean Wraps"],"street-address":["433 S California Ave"],"locality":["Palo Alto"],"region":["CA"],"tel":["(650) 321-8189"]}}],"summary":["Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff."],"rating":["9.2"],"average":["9.2"],"best":["10"],"count":["17"],"name":["Mediterranean Wraps\n \n 433 S California Ave, \n Palo Alto, \n CA - \n (650) 321-8189\n \n \n Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff.\n \n 9.2 out of \n 10 \n based on 17 reviews"]}}],"rels":{},"rel-urls":{}};
-
- it('simpleproperties', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-hyperlink.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-hyperlink.js
deleted file mode 100644
index 3f547d7a9..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-hyperlink.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review/hyperlink
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review', function() {
- var htmlFragment = "<a class=\"h-review\" href=\"https://plus.google.com/116941523817079328322/about\">Crepes on Cole</a>";
- var expected = {"items":[{"type":["h-review"],"properties":{"name":["Crepes on Cole"],"url":["https://plus.google.com/116941523817079328322/about"]}}],"rels":{},"rel-urls":{}};
-
- it('hyperlink', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-implieditem.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-implieditem.js
deleted file mode 100644
index ecde19277..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-implieditem.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review/implieditem
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review', function() {
- var htmlFragment = "<div class=\"h-review\">\n <a class=\"p-item h-item\" href=\"http://example.com/crepeoncole\">Crepes on Cole</a>\n <p><span class=\"p-rating\">4.7</span> out of 5 stars</p>\n</div>";
- var expected = {"items":[{"type":["h-review"],"properties":{"item":[{"value":"Crepes on Cole","type":["h-item"],"properties":{"name":["Crepes on Cole"],"url":["http://example.com/crepeoncole"]}}],"rating":["4.7"],"name":["Crepes on Cole\n 4.7 out of 5 stars"]}}],"rels":{},"rel-urls":{}};
-
- it('implieditem', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-item.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-item.js
deleted file mode 100644
index d8aef51c8..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-item.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review/item
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review', function() {
- var htmlFragment = "<base href=\"http://example.com\" >\n<div class=\"h-review\">\n <p class=\"p-item h-item\">\n <img class=\"u-photo\" src=\"images/photo.gif\" />\n <a class=\"p-name u-url\" href=\"http://example.com/crepeoncole\">Crepes on Cole</a>\n </p>\n <p><span class=\"p-rating\">5</span> out of 5 stars</p>\n</div>";
- var expected = {"items":[{"type":["h-review"],"properties":{"item":[{"value":"Crepes on Cole","type":["h-item"],"properties":{"photo":["http://example.com/images/photo.gif"],"name":["Crepes on Cole"],"url":["http://example.com/crepeoncole"]}}],"rating":["5"],"name":["Crepes on Cole\n \n 5 out of 5 stars"]}}],"rels":{},"rel-urls":{}};
-
- it('item', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-justaname.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-justaname.js
deleted file mode 100644
index 89523e909..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-justaname.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review/justaname
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review', function() {
- var htmlFragment = "<p class=\"h-review\">Crepes on Cole</p>";
- var expected = {"items":[{"type":["h-review"],"properties":{"name":["Crepes on Cole"]}}],"rels":{},"rel-urls":{}};
-
- it('justaname', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-photo.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-photo.js
deleted file mode 100644
index ee0c41fe6..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-photo.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review/photo
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review', function() {
- var htmlFragment = "<base href=\"http://example.com\" ><img class=\"h-review\" src=\"images/photo.gif\" alt=\"Crepes on Cole\" />";
- var expected = {"items":[{"type":["h-review"],"properties":{"name":["Crepes on Cole"],"photo":["http://example.com/images/photo.gif"]}}],"rels":{},"rel-urls":{}};
-
- it('photo', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-vcard.js b/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-vcard.js
deleted file mode 100644
index 8411c4d2a..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-h-review-vcard.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/h-review/vcard
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('h-review', function() {
- var htmlFragment = "<div class=\"h-review\">\n <span><span class=\"p-rating\">5</span> out of 5 stars</span>\n <h4 class=\"p-name\">Crepes on Cole is awesome</h4>\n <span class=\"p-reviewer h-card\">\n Reviewer: <span class=\"p-name\">Tantek</span> - \n </span>\n <time class=\"dt-reviewed\" datetime=\"2005-04-18\">April 18, 2005</time>\n <div class=\"e-description\">\n <p class=\"p-item h-card\">\n <span class=\"p-name p-org\">Crepes on Cole</span> is one of the best little \n creperies in <span class=\"p-adr h-adr\"><span class=\"p-locality\">San Francisco</span></span>.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.\n </p>\n </div>\n <p>Visit date: <span>April 2005</span></p>\n <p>Food eaten: <a class=\"p-category\" href=\"http://en.wikipedia.org/wiki/crepe\">crepe</a></p>\n <p>Permanent link for review: <a class=\"u-url\" href=\"http://example.com/crepe\">http://example.com/crepe</a></p>\n <p><a rel=\"license\" href=\"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a></p>\n</div>";
- var expected = {"items":[{"type":["h-review"],"properties":{"rating":["5"],"name":["Crepes on Cole is awesome"],"reviewer":[{"value":"Tantek","type":["h-card"],"properties":{"name":["Tantek"]}}],"reviewed":["2005-04-18"],"description":[{"value":"Crepes on Cole is one of the best little \n creperies in San Francisco.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.","html":"\n <p class=\"p-item h-card\">\n <span class=\"p-name p-org\">Crepes on Cole</span> is one of the best little \n creperies in <span class=\"p-adr h-adr\"><span class=\"p-locality\">San Francisco</span></span>.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.\n </p>\n "}],"item":[{"value":"Crepes on Cole","type":["h-card"],"properties":{"name":["Crepes on Cole"],"org":["Crepes on Cole"],"adr":[{"value":"San Francisco","type":["h-adr"],"properties":{"locality":["San Francisco"],"name":["San Francisco"]}}]}}],"category":["crepe"],"url":["http://example.com/crepe"]}}],"rels":{"license":["http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"]},"rel-urls":{"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License":{"text":"Creative Commons Attribution-ShareAlike License","rels":["license"]}}};
-
- it('vcard', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-duplicate-rels.js b/toolkit/components/microformats/test/standards-tests/mf-v2-rel-duplicate-rels.js
deleted file mode 100644
index d65dfdf8b..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-duplicate-rels.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/rel/duplicate-rels
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('rel', function() {
- var htmlFragment = "<a href=\"http://ma.tt/2015/05/beethoven-mozart-bach/\" \n title=\"Permalink to Beethoven, Mozart, Bach\" rel=\"bookmark\">\n<time class=\"entry-date\" datetime=\"2015-05-31T22:42:00+00:00\">May 31, 2015</time></a></span>\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">Asides</a>\n<span class=\"author vcard\">\n<a class=\"url fn n\" href=\"http://ma.tt/author/saxmatt/\" \n title=\"View all posts by Matt\" rel=\"author\">Matt</a></span>\n<span class=\"date\"><a href=\"http://ma.tt/2015/06/jefferson-on-idleness/\" title=\"Permalink to Jefferson on Idleness\" rel=\"bookmark\"><time class=\"entry-date\" datetime=\"2015-06-02T21:26:00+00:00\">June 2, 2015</time></a></span>\n<span class=\"categories-links\"><a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">Asides</a></span>\n<span class=\"author vcard\"><a class=\"url fn n\" href=\"http://ma.tt/author/saxmatt/\" title=\"View all posts by Matt\" rel=\"author\">Matt</a></span>\n";
- var expected = {"rels":{"bookmark":["http://ma.tt/2015/05/beethoven-mozart-bach/","http://ma.tt/2015/06/jefferson-on-idleness/"],"category":["http://ma.tt/category/asides/"],"tag":["http://ma.tt/category/asides/"],"author":["http://ma.tt/author/saxmatt/"]},"items":[{"type":["h-card"],"properties":{"url":["http://ma.tt/author/saxmatt/"],"name":["Matt"]}},{"type":["h-card"],"properties":{"url":["http://ma.tt/author/saxmatt/"],"name":["Matt"]}}],"rel-urls":{"http://ma.tt/category/asides/":{"rels":["category","tag"],"text":"Asides"},"http://ma.tt/author/saxmatt/":{"rels":["author"],"text":"Matt","title":"View all posts by Matt"},"http://ma.tt/2015/05/beethoven-mozart-bach/":{"rels":["bookmark"],"text":"May 31, 2015","title":"Permalink to Beethoven, Mozart, Bach"},"http://ma.tt/2015/06/jefferson-on-idleness/":{"rels":["bookmark"],"text":"June 2, 2015","title":"Permalink to Jefferson on Idleness"}}};
-
- it('duplicate-rels', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-license.js b/toolkit/components/microformats/test/standards-tests/mf-v2-rel-license.js
deleted file mode 100644
index d5606f5a3..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-license.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/rel/license
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('rel', function() {
- var htmlFragment = "<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/2.5/\">cc by 2.5</a>";
- var expected = {"items":[],"rels":{"license":["http://creativecommons.org/licenses/by/2.5/"]},"rel-urls":{"http://creativecommons.org/licenses/by/2.5/":{"text":"cc by 2.5","rels":["license"]}}};
-
- it('license', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-nofollow.js b/toolkit/components/microformats/test/standards-tests/mf-v2-rel-nofollow.js
deleted file mode 100644
index 4332d3572..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-nofollow.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/rel/nofollow
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('rel', function() {
- var htmlFragment = "<a rel=\"nofollow\" href=\"http://microformats.org/wiki/microformats:copyrights\">Copyrights</a>";
- var expected = {"items":[],"rels":{"nofollow":["http://microformats.org/wiki/microformats:copyrights"]},"rel-urls":{"http://microformats.org/wiki/microformats:copyrights":{"text":"Copyrights","rels":["nofollow"]}}};
-
- it('nofollow', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-rel-urls.js b/toolkit/components/microformats/test/standards-tests/mf-v2-rel-rel-urls.js
deleted file mode 100644
index 685532f44..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-rel-urls.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/rel/rel-urls
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('rel', function() {
- var htmlFragment = "<a rel=\"author\" href=\"http://example.com/a\">author a</a>\n<a rel=\"author\" href=\"http://example.com/b\">author b</a>\n<a rel=\"in-reply-to\" href=\"http://example.com/1\">post 1</a>\n<a rel=\"in-reply-to\" href=\"http://example.com/2\">post 2</a>\n<a rel=\"alternate home\"\n href=\"http://example.com/fr\"\n media=\"handheld\"\n hreflang=\"fr\">French mobile homepage</a>";
- var expected = {"items":[],"rels":{"author":["http://example.com/a","http://example.com/b"],"in-reply-to":["http://example.com/1","http://example.com/2"],"home":["http://example.com/fr"],"alternate":["http://example.com/fr"]},"rel-urls":{"http://example.com/a":{"rels":["author"],"text":"author a"},"http://example.com/b":{"rels":["author"],"text":"author b"},"http://example.com/1":{"rels":["in-reply-to"],"text":"post 1"},"http://example.com/2":{"rels":["in-reply-to"],"text":"post 2"},"http://example.com/fr":{"rels":["alternate","home"],"media":"handheld","hreflang":"fr","text":"French mobile homepage"}}};
-
- it('rel-urls', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-varying-text-duplicate-rels.js b/toolkit/components/microformats/test/standards-tests/mf-v2-rel-varying-text-duplicate-rels.js
deleted file mode 100644
index 3b1b72f44..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-varying-text-duplicate-rels.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/rel/varying-text-duplicate-rels
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('rel', function() {
- var htmlFragment = "This is a contrived example - not found links like this in the wild:\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">Asides</a>\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">B-sides</a>\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">seasides</a>";
- var expected = {"rels":{"category":["http://ma.tt/category/asides/"],"tag":["http://ma.tt/category/asides/"]},"items":[],"rel-urls":{"http://ma.tt/category/asides/":{"rels":["category","tag"],"text":"Asides"}}};
-
- it('varying-text-duplicate-rels', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-all.js b/toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-all.js
deleted file mode 100644
index 3850ad564..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-all.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/rel/xfn-all
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('rel', function() {
- var htmlFragment = "<ul>\n <li><a rel=\"friend\" href=\"http://example.com/profile/jane\">jane</a></li>\n <li><a rel=\"acquaintance\" href=\"http://example.com/profile/jeo\">jeo</a></li>\n <li><a rel=\"contact\" href=\"http://example.com/profile/lily\">lily</a></li>\n <li><a rel=\"met\" href=\"http://example.com/profile/oliver\">oliver</a></li>\n <li><a rel=\"co-worker\" href=\"http://example.com/profile/emily\">emily</a></li>\n <li><a rel=\"colleague\" href=\"http://example.com/profile/jack\">jack</a></li>\n <li><a rel=\"neighbor\" href=\"http://example.com/profile/isabella\">isabella</a></li>\n <li><a rel=\"child\" href=\"http://example.com/profile/harry\">harry</a></li>\n <li><a rel=\"parent\" href=\"http://example.com/profile/sophia\">sophia</a></li>\n <li><a rel=\"sibling\" href=\"http://example.com/profile/charlie\">charlie</a></li>\n <li><a rel=\"spouse\" href=\"http://example.com/profile/olivia\">olivia</a></li>\n <li><a rel=\"kin\" href=\"http://example.com/profile/james\">james</a></li>\n <li><a rel=\"muse\" href=\"http://example.com/profile/ava\">ava</a></li>\n <li><a rel=\"crush\" href=\"http://example.com/profile/joshua\">joshua</a></li>\n <li><a rel=\"date\" href=\"http://example.com/profile/chloe\">chloe</a></li>\n <li><a rel=\"sweetheart\" href=\"http://example.com/profile/alfie\">alfie</a></li>\n <li><a rel=\"me\" href=\"http://example.com/profile/isla\">isla</a></li>\n</ul>";
- var expected = {"items":[],"rels":{"friend":["http://example.com/profile/jane"],"acquaintance":["http://example.com/profile/jeo"],"contact":["http://example.com/profile/lily"],"met":["http://example.com/profile/oliver"],"co-worker":["http://example.com/profile/emily"],"colleague":["http://example.com/profile/jack"],"neighbor":["http://example.com/profile/isabella"],"child":["http://example.com/profile/harry"],"parent":["http://example.com/profile/sophia"],"sibling":["http://example.com/profile/charlie"],"spouse":["http://example.com/profile/olivia"],"kin":["http://example.com/profile/james"],"muse":["http://example.com/profile/ava"],"crush":["http://example.com/profile/joshua"],"date":["http://example.com/profile/chloe"],"sweetheart":["http://example.com/profile/alfie"],"me":["http://example.com/profile/isla"]},"rel-urls":{"http://example.com/profile/jane":{"text":"jane","rels":["friend"]},"http://example.com/profile/jeo":{"text":"jeo","rels":["acquaintance"]},"http://example.com/profile/lily":{"text":"lily","rels":["contact"]},"http://example.com/profile/oliver":{"text":"oliver","rels":["met"]},"http://example.com/profile/emily":{"text":"emily","rels":["co-worker"]},"http://example.com/profile/jack":{"text":"jack","rels":["colleague"]},"http://example.com/profile/isabella":{"text":"isabella","rels":["neighbor"]},"http://example.com/profile/harry":{"text":"harry","rels":["child"]},"http://example.com/profile/sophia":{"text":"sophia","rels":["parent"]},"http://example.com/profile/charlie":{"text":"charlie","rels":["sibling"]},"http://example.com/profile/olivia":{"text":"olivia","rels":["spouse"]},"http://example.com/profile/james":{"text":"james","rels":["kin"]},"http://example.com/profile/ava":{"text":"ava","rels":["muse"]},"http://example.com/profile/joshua":{"text":"joshua","rels":["crush"]},"http://example.com/profile/chloe":{"text":"chloe","rels":["date"]},"http://example.com/profile/alfie":{"text":"alfie","rels":["sweetheart"]},"http://example.com/profile/isla":{"text":"isla","rels":["me"]}}};
-
- it('xfn-all', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-elsewhere.js b/toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-elsewhere.js
deleted file mode 100644
index d982af5cc..000000000
--- a/toolkit/components/microformats/test/standards-tests/mf-v2-rel-xfn-elsewhere.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.24
-Mocha integration test from: microformats-v2/rel/xfn-elsewhere
-The test was built on Fri Sep 25 2015 13:26:26 GMT+0100 (BST)
-*/
-
-assert = chai.assert;
-
-
-describe('rel', function() {
- var htmlFragment = "<ul>\n <li><a rel=\"me\" href=\"http://twitter.com/glennjones\">twitter</a></li>\n <li><a rel=\"me\" href=\"http://delicious.com/glennjonesnet/\">delicious</a></li>\n <li><a rel=\"me\" href=\"https://plus.google.com/u/0/105161464208920272734/about\">google+</a></li>\n <li><a rel=\"me\" href=\"http://lanyrd.com/people/glennjones/\">lanyrd</a></li>\n <li><a rel=\"me\" href=\"http://github.com/glennjones\">github</a></li>\n <li><a rel=\"me\" href=\"http://www.flickr.com/photos/glennjonesnet/\">flickr</a></li>\n <li><a rel=\"me\" href=\"http://www.linkedin.com/in/glennjones\">linkedin</a></li>\n <li><a rel=\"me\" href=\"http://www.slideshare.net/glennjones/presentations\">slideshare</a></li>\n</ul>";
- var expected = {"items":[],"rels":{"me":["http://twitter.com/glennjones","http://delicious.com/glennjonesnet/","https://plus.google.com/u/0/105161464208920272734/about","http://lanyrd.com/people/glennjones/","http://github.com/glennjones","http://www.flickr.com/photos/glennjonesnet/","http://www.linkedin.com/in/glennjones","http://www.slideshare.net/glennjones/presentations"]},"rel-urls":{"http://twitter.com/glennjones":{"text":"twitter","rels":["me"]},"http://delicious.com/glennjonesnet/":{"text":"delicious","rels":["me"]},"https://plus.google.com/u/0/105161464208920272734/about":{"text":"google+","rels":["me"]},"http://lanyrd.com/people/glennjones/":{"text":"lanyrd","rels":["me"]},"http://github.com/glennjones":{"text":"github","rels":["me"]},"http://www.flickr.com/photos/glennjonesnet/":{"text":"flickr","rels":["me"]},"http://www.linkedin.com/in/glennjones":{"text":"linkedin","rels":["me"]},"http://www.slideshare.net/glennjones/presentations":{"text":"slideshare","rels":["me"]}}};
-
- it('xfn-elsewhere', function(){
- var doc, dom, node, options, parser, found;
- dom = new DOMParser();
- doc = dom.parseFromString( htmlFragment, 'text/html' );
- options ={
- 'document': doc,
- 'node': doc,
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5'
- };
- found = Microformats.get( options );
- assert.deepEqual(found, expected);
- });
-});
diff --git a/toolkit/components/microformats/test/static/count.html b/toolkit/components/microformats/test/static/count.html
deleted file mode 100644
index c367b29ea..000000000
--- a/toolkit/components/microformats/test/static/count.html
+++ /dev/null
@@ -1,84 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
-
- <meta charset="UTF-8">
- <title>Count Microformats</title>
- <meta name="description" content="microformat-shiv - A light-weight cross browser javascript microformats 2 parser" />
-
- <link rel="stylesheet" href="css/testrunner.css">
- <link rel="stylesheet" href="css/prettify.css">
-
-
- <!-- loads Modules to help with debugging ie windows.Modules -->
- <script src="../../lib/utilities.js"></script>
- <script src="../../lib/domutils.js"></script>
- <script src="../../lib/url.js"></script>
- <script src="../../lib/html.js"></script>
- <script src="../../lib/text.js"></script>
- <script src="../../lib/dates.js"></script>
- <script src="../../lib/isodate.js"></script>
- <script src="../../lib/parser.js"></script>
- <script src="../../lib/parser-implied.js"></script>
- <script src="../../lib/parser-includes.js"></script>
- <script src="../../lib/parser-rels.js"></script>
-
- <script src="../../lib/maps/h-adr.js"></script>
- <script src="../../lib/maps/h-card.js"></script>
- <script src="../../lib/maps/h-entry.js"></script>
- <script src="../../lib/maps/h-event.js"></script>
- <script src="../../lib/maps/h-feed.js"></script>
- <script src="../../lib/maps/h-geo.js"></script>
- <script src="../../lib/maps/h-item.js"></script>
- <script src="../../lib/maps/h-listing.js"></script>
- <script src="../../lib/maps/h-news.js"></script>
- <script src="../../lib/maps/h-org.js"></script>
- <script src="../../lib/maps/h-product.js"></script>
- <script src="../../lib/maps/h-recipe.js"></script>
- <script src="../../lib/maps/h-resume.js"></script>
- <script src="../../lib/maps/h-review-aggregate.js"></script>
- <script src="../../lib/maps/h-review.js"></script>
- <script src="../../lib/maps/rel.js"></script>
-
-
- <script src="javascript/beautify.js"></script>
- <script src="javascript/prettify.js"></script>
-
- <script src="javascript/count.js"></script>
-
- </head>
-
- <body>
-
- <p>microformat-shiv</p>
- <h1>Count Microformats</h1>
- <p>Type or copy and paste the HTML you want to parse into the box below.</p>
-
- <form id="mf-form" class="tool-interface" method="get" action="">
- <p>
- <label for="html">HTML</label>
-<textarea id="html" name="html">&lt;a class="h-card" href="http://glennjones.net"&gt;
- &lt;span class="p-given-name"&gt;Glenn&lt;/span&gt;
- &lt;span class="p-family-name"&gt;Jones&lt;/span&gt;
-&lt;/a&gt;
-&lt;a class="h-card" href="http://janedoe.net"&gt;
- &lt;span class="p-given-name"&gt;Jane&lt;/span&gt;
- &lt;span class="p-family-name"&gt;Doe&lt;/span&gt;
-&lt;/a&gt;
-&lt;a class="h-event" href="http://janedoe.net"&gt;
- &lt;span class="p-name"&gt;Event&lt;/span&gt;
- &lt;span class="dt-start"&gt;2015-07-01&lt;/span&gt;
-&lt;/a&gt;
-</textarea>
- </p>
-
- <input class="button" value="Count" type="submit">
- </form>
-
- <h1>Parser JSON</h1>
- <div id="parser-json"><pre class="prettyprint"><code class="language-json"></code></pre></div>
-
-
-
- </body>
-</html> \ No newline at end of file
diff --git a/toolkit/components/microformats/test/static/css/mocha-custom.css b/toolkit/components/microformats/test/static/css/mocha-custom.css
deleted file mode 100644
index 30f07756b..000000000
--- a/toolkit/components/microformats/test/static/css/mocha-custom.css
+++ /dev/null
@@ -1,9 +0,0 @@
-
-body {
- font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
- padding: 60px 50px;
-}
-
-h3.capitalize {
- text-transform: capitalize;
-} \ No newline at end of file
diff --git a/toolkit/components/microformats/test/static/css/mocha.css b/toolkit/components/microformats/test/static/css/mocha.css
deleted file mode 100644
index 42b9798fa..000000000
--- a/toolkit/components/microformats/test/static/css/mocha.css
+++ /dev/null
@@ -1,270 +0,0 @@
-@charset "utf-8";
-
-body {
- margin:0;
-}
-
-#mocha {
- font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
- margin: 60px 50px;
-}
-
-#mocha ul,
-#mocha li {
- margin: 0;
- padding: 0;
-}
-
-#mocha ul {
- list-style: none;
-}
-
-#mocha h1,
-#mocha h2 {
- margin: 0;
-}
-
-#mocha h1 {
- margin-top: 15px;
- font-size: 1em;
- font-weight: 200;
-}
-
-#mocha h1 a {
- text-decoration: none;
- color: inherit;
-}
-
-#mocha h1 a:hover {
- text-decoration: underline;
-}
-
-#mocha .suite .suite h1 {
- margin-top: 0;
- font-size: .8em;
-}
-
-#mocha .hidden {
- display: none;
-}
-
-#mocha h2 {
- font-size: 12px;
- font-weight: normal;
- cursor: pointer;
-}
-
-#mocha .suite {
- margin-left: 15px;
-}
-
-#mocha .test {
- margin-left: 15px;
- overflow: hidden;
-}
-
-#mocha .test.pending:hover h2::after {
- content: '(pending)';
- font-family: arial, sans-serif;
-}
-
-#mocha .test.pass.medium .duration {
- background: #c09853;
-}
-
-#mocha .test.pass.slow .duration {
- background: #b94a48;
-}
-
-#mocha .test.pass::before {
- content: '✓';
- font-size: 12px;
- display: block;
- float: left;
- margin-right: 5px;
- color: #00d6b2;
-}
-
-#mocha .test.pass .duration {
- font-size: 9px;
- margin-left: 5px;
- padding: 2px 5px;
- color: #fff;
- -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
- -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
- box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
- -webkit-border-radius: 5px;
- -moz-border-radius: 5px;
- -ms-border-radius: 5px;
- -o-border-radius: 5px;
- border-radius: 5px;
-}
-
-#mocha .test.pass.fast .duration {
- display: none;
-}
-
-#mocha .test.pending {
- color: #0b97c4;
-}
-
-#mocha .test.pending::before {
- content: '◦';
- color: #0b97c4;
-}
-
-#mocha .test.fail {
- color: #c00;
-}
-
-#mocha .test.fail pre {
- color: black;
-}
-
-#mocha .test.fail::before {
- content: '✖';
- font-size: 12px;
- display: block;
- float: left;
- margin-right: 5px;
- color: #c00;
-}
-
-#mocha .test pre.error {
- color: #c00;
- max-height: 300px;
- overflow: auto;
-}
-
-/**
- * (1): approximate for browsers not supporting calc
- * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border)
- * ^^ seriously
- */
-#mocha .test pre {
- display: block;
- float: left;
- clear: left;
- font: 12px/1.5 monaco, monospace;
- margin: 5px;
- padding: 15px;
- border: 1px solid #eee;
- max-width: 85%; /*(1)*/
- max-width: calc(100% - 42px); /*(2)*/
- word-wrap: break-word;
- border-bottom-color: #ddd;
- -webkit-border-radius: 3px;
- -webkit-box-shadow: 0 1px 3px #eee;
- -moz-border-radius: 3px;
- -moz-box-shadow: 0 1px 3px #eee;
- border-radius: 3px;
-}
-
-#mocha .test h2 {
- position: relative;
-}
-
-#mocha .test a.replay {
- position: absolute;
- top: 3px;
- right: 0;
- text-decoration: none;
- vertical-align: middle;
- display: block;
- width: 15px;
- height: 15px;
- line-height: 15px;
- text-align: center;
- background: #eee;
- font-size: 15px;
- -moz-border-radius: 15px;
- border-radius: 15px;
- -webkit-transition: opacity 200ms;
- -moz-transition: opacity 200ms;
- transition: opacity 200ms;
- opacity: 0.3;
- color: #888;
-}
-
-#mocha .test:hover a.replay {
- opacity: 1;
-}
-
-#mocha-report.pass .test.fail {
- display: none;
-}
-
-#mocha-report.fail .test.pass {
- display: none;
-}
-
-#mocha-report.pending .test.pass,
-#mocha-report.pending .test.fail {
- display: none;
-}
-#mocha-report.pending .test.pass.pending {
- display: block;
-}
-
-#mocha-error {
- color: #c00;
- font-size: 1.5em;
- font-weight: 100;
- letter-spacing: 1px;
-}
-
-#mocha-stats {
- position: fixed;
- top: 15px;
- right: 10px;
- font-size: 12px;
- margin: 0;
- color: #888;
- z-index: 1;
-}
-
-#mocha-stats .progress {
- float: right;
- padding-top: 0;
-}
-
-#mocha-stats em {
- color: black;
-}
-
-#mocha-stats a {
- text-decoration: none;
- color: inherit;
-}
-
-#mocha-stats a:hover {
- border-bottom: 1px solid #eee;
-}
-
-#mocha-stats li {
- display: inline-block;
- margin: 0 5px;
- list-style: none;
- padding-top: 11px;
-}
-
-#mocha-stats canvas {
- width: 40px;
- height: 40px;
-}
-
-#mocha code .comment { color: #ddd; }
-#mocha code .init { color: #2f6fad; }
-#mocha code .string { color: #5890ad; }
-#mocha code .keyword { color: #8a6343; }
-#mocha code .number { color: #2f6fad; }
-
-@media screen and (max-device-width: 480px) {
- #mocha {
- margin: 60px 0px;
- }
-
- #mocha #stats {
- position: absolute;
- }
-}
diff --git a/toolkit/components/microformats/test/static/css/prettify.css b/toolkit/components/microformats/test/static/css/prettify.css
deleted file mode 100644
index 843e903e7..000000000
--- a/toolkit/components/microformats/test/static/css/prettify.css
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Pretty printing styles. Used with prettify.js. */
-
-.str { color: #85C5DC; }
-.kwd { color: #EDF0D1; }
-.com { color: #878989; }
-.typ { color: #F5896F; }
-.lit { color: #FFB17A; }
-.pun { color: #FFFFFF; }
-.pln { color: #FFFFFF; }
-.tag { color: #F5896F; }
-.atn { color: #F5896F; }
-.atv { color: #85C5DC; }
-.dec { color: #878989; }
-
-pre.prettyprint {
- background-color:#302F2D;
- border: none;
- line-height: normal;
- font-size: 100%;
- border-radius: 6px 6px 6px 6px;
- font-family: consolas,​'andale mono',​'courier new',​monospace;
- padding-top: 12px;
- overflow: hidden;
-}
-
-code{
- font-size: 13px;
- line-height: normal;
-}
-
-/* Specify class=linenums on a pre to get line numbering */
-ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */
-li.L0,
-li.L1,
-li.L2,
-li.L3,
-li.L5,
-li.L6,
-li.L7,
-li.L8 { list-style-type: none }
-/* Alternate shading for lines */
-li.L1,
-li.L3,
-li.L5,
-li.L7,
-li.L9 { background: #eee }
-
-@media print {
- .str { color: #060; }
- .kwd { color: #006; font-weight: bold; }
- .com { color: #600; font-style: italic; }
- .typ { color: #404; font-weight: bold; }
- .lit { color: #044; }
- .pun { color: #440; }
- .pln { color: #000; }
- .tag { color: #006; font-weight: bold; }
- .atn { color: #404; }
- .atv { color: #060; }
-}
-
-
-/* correct additional line return at top of html diaplay*/
-code>:first-child{
- display: none;
-} \ No newline at end of file
diff --git a/toolkit/components/microformats/test/static/css/testrunner.css b/toolkit/components/microformats/test/static/css/testrunner.css
deleted file mode 100644
index 0064b139c..000000000
--- a/toolkit/components/microformats/test/static/css/testrunner.css
+++ /dev/null
@@ -1,367 +0,0 @@
-/*
-All content and code is released into the public domain
-http://en.wikipedia.org/wiki/public_domain
-
-Contributors
-Glenn Jones - http://glennjones.net/
-*/
-
-
-
-
-@import url(https://fonts.googleapis.com/css?family=Lato:300italic,700italic,300,700);
-
-body {
- padding:50px;
- font:1em "Helvetica Neue", Helvetica, Arial, sans-serif;
- color:#333;
- font-weight:300;
- border-top: 5px solid #302F2D;
- margin: 0;
-}
-
-h1, h2, h3, h4, h5, h6 {
- color:#222;
- font-weight: normal;
-}
-
-p, ul, ol, table, pre, dl {
- margin:0 0 20px;
-}
-
-h1, h2, h3 {
- margin-top: 50px;
- margin-bottom: 10px;
- font-family: Lato, "Helvetica Neue", Helvetica, Arial, sans-serif;
-}
-
-h1 {
- font-size: 2em;
-}
-
-h2, h3 {
- font-size: 1.5em;
-}
-
-/* the first h1 in a page */
-h1:first-of-type{
- margin-top: 0;
- font-weight: bold;
-}
-
-a {
- color: #39c;
- font-weight: 300;
- text-decoration: none;
-}
-
-a:hover {
- text-decoration: underline;
-}
-
-a[name]{
- color: #333;
-}
-
-a[name]:hover {
- text-decoration: none;
-}
-
-blockquote {
- border-left: 1px solid #e5e5e5;
- margin: 0;
- padding: 0 0 0 20px;
- font-style: italic;
-}
-
-code, pre {
- font-family: Monaco, Bitstream Vera Sans Mono, Lucida Console, Terminal;
- font-size: 12px;
- margin: 0;
-}
-
-pre {
- padding: 8px 15px;
- border-radius: 5px;
- border: 1px solid #e5e5e5;
- overflow-x: auto;
- color: #fff;
- margin: 0;
-}
-
-table {
- border-collapse: collapse;
-}
-
-th, td {
- text-align: left;
- padding: 2px 10px;
- border-bottom: 1px solid #e5e5e5;
- font-weight: 300;
-}
-
-th{
- background-color: #333;
- color:#fff;
-}
-
-td a{
- font-weight: 300;
-}
-
-dt {
- color:#444;
- font-weight:700;
-}
-
-img {
- max-width:100%;
-}
-
-li{
- padding: 0.25em 0 0.25em 0;
-}
-
-
-button, input[type="submit"], input[type="button"], .button {
- display: inline-block;
- padding-top: 0.4em;
- padding-right: 1em;
- padding-left: 1em;
- padding-bottom: 0.5em;
- margin-bottom: 0;
- font-weight: 200;
- font-size: 1rem;
- text-align: center;
- white-space: nowrap;
- cursor: pointer;
- background-image: none;
- border: 1px solid transparent;
- border-radius: 3px;
- background-color: #33a0e8;
- color: #fff;
- -webkit-user-select: none;
- -moz-user-select: none;
- -ms-user-select: none;
- -o-user-select: none;
- user-select: none;
-}
-
-select {
- height: 34px;
- padding: 6px 12px;
- font-size: 14px;
- line-height: 1.42857143;
- color: #555;
- background-color: #fff;
- background-image: none;
- border: 1px solid #ccc;
- border-radius: 4px;
- -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
- box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
- -webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;
- -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
- transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
-}
-
-option {
- padding: 2em;
-}
-
-footer{
- margin-top: 8em;
- text-align: center;
-}
-
-
-/* The Magnificent Clearfix: Updated to prevent margin-collapsing on child elements.
- j.mp/bestclearfix */
-.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
-.clearfix:after { clear: both; }
-/* Fix clearfix: blueprintcss.lighthouseapp.com/projects/15318/tickets/5-extra-margin-padding-bottom-of-page */
-.clearfix { zoom: 1; }
-
-.test-counts{
- font-weight: 700;
- margin-bottom: 4em;
-}
-
-.test-detail{
- display:none;
-}
-
-.all-test-list, .test-result-list{
- list-style: none;
- margin: 0;
- padding: 0;
- display: block;
- float: left;
-}
-
-.all-test-list li .test-result-list li{
- padding: 0.2em 0 0.2em 0;
- white-space: nowrap;
- cursor: pointer;
-}
-
-.all-test-list li::hover, .test-result-list li::hover{
- text-decoration: underline;
-}
-
-.all-test-list li.test-error a, .test-result-list li.test-error a{
- color: red;
- text-decoration: underline;
-}
-
-.flexbox-container {
- display: -ms-flex;
- display: -webkit-flex;
- display: flex;
-}
-
-.flexbox-container > section {
- margin-bottom: 3em;
-}
-
-.flexbox-container > section:first-child {
- width: 20%;
- margin-right: 20px;
-}
-
-.flexbox-container > section:nth-child(2) {
- padding-left: 1em;
- width: 80%;
-}
-
-
-@media (max-width: 1400px) {
- .flexbox-container > section:first-child {
- width: 25%;
- }
-
- .flexbox-container > section:nth-child(2) {
- width: 75%;
- }
-}
-
-@media (max-width: 1200px) {
- .flexbox-container > section:first-child {
- width: 30%;
- }
-
- .flexbox-container > section:nth-child(2) {
- width: 70%;
- }
-}
-
-
-@media (max-width: 1000px) {
- .flexbox-container > section:first-child {
- width: 35%;
- }
-
- .flexbox-container > section:nth-child(2) {
- width: 65%;
- }
-}
-
-
-
-
-
-
-#test-status {
- margin-top: 0;
-}
-
-.test-passed{
- border-left: 10px solid green;
-}
-
-.test-failed{
- border-left: 10px solid red;
-}
-
-.differences-description{
- margin-top: 2em;
-}
-
-.differences-description li{
- padding: 0;
-}
-
-.failed{
- color: red;
-}
-
-#test-list-by-version section{
- width: 30%;
- margin-right: 20px;
-}
-
-.test-container{
- padding-left: 1em;
-}
-
-
-#textcontent-test textarea{
- font-size: 1em;
- min-height: 6em;
- min-width: 40em;
- padding: 0.5em;
-}
-
-#textcontent-test input{
- font-size: 1em;
-}
-
-
-/* Tool interface */
-
-.tool-interface input[type="text"], input[type="url"] {
- width: 20em;
- padding: 0.4em;
- border: 1px solid #999;
- border-radius: 0.4em;
- color: #333;
- font-size: 1em
-}
-
-.tool-interface label {
- display: inline-block;
- width: 5em;
-}
-
-.tool-interface select {
- padding: 0.2em;
- font-family: open_sansregular, calibri, arial, helvetica, 'lucida grande', 'lucida sans unicode', verdana, sans-serif;
-}
-
-.tool-interface option{
- padding: 0.2em;
-}
-
-.tool-interface textarea{
- width: 100%;
- height: 16em;
- border: 1px solid #999;
- border-radius: 0.4em;
- font-size: 1em;
- font-family: open_sansregular, calibri, arial, helvetica, 'lucida grande', 'lucida sans unicode', verdana, sans-serif;
-}
-
-.tool-interface .button{
- margin-left: 5.2em;
-}
-
-.tool-interface label.checkbox-label{
- width: auto;
-}
-
-.tool-interface .checkbox{
- margin-left: 5.2em;
-}
-
-select.indent {
- margin-left: 5em;
-}
diff --git a/toolkit/components/microformats/test/static/images/logo.gif b/toolkit/components/microformats/test/static/images/logo.gif
deleted file mode 100644
index 96c965e70..000000000
--- a/toolkit/components/microformats/test/static/images/logo.gif
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/microformats/test/static/images/photo.gif b/toolkit/components/microformats/test/static/images/photo.gif
deleted file mode 100644
index 96c965e70..000000000
--- a/toolkit/components/microformats/test/static/images/photo.gif
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/microformats/test/static/javascript/DOMParser.js b/toolkit/components/microformats/test/static/javascript/DOMParser.js
deleted file mode 100644
index fa26bcdfd..000000000
--- a/toolkit/components/microformats/test/static/javascript/DOMParser.js
+++ /dev/null
@@ -1,99 +0,0 @@
-
-// Based on https://gist.github.com/1129031 By Eli Grey, http://eligrey.com - Public domain.
-
-// DO NOT use https://developer.mozilla.org/en-US/docs/Web/API/DOMParser example polyfill
-// as it does not work with earliar version of chrome
-
-
-(function(DOMParser) {
- "use strict";
-
- var DOMParser_proto;
- var real_parseFromString;
- var textHTML; // Flag for text/html support
- var textXML; // Flag for text/xml support
- var htmlElInnerHTML; // Flag for support for setting html element's innerHTML
-
- // Stop here if DOMParser not defined
- if (!DOMParser) return;
-
- // Firefox, Opera and IE throw errors on unsupported types
- try {
- // WebKit returns null on unsupported types
- textHTML = !!(new DOMParser).parseFromString('', 'text/html');
-
- } catch (er) {
- textHTML = false;
- }
-
- // If text/html supported, don't need to do anything.
- if (textHTML) return;
-
- // Next try setting innerHTML of a created document
- // IE 9 and lower will throw an error (can't set innerHTML of its HTML element)
- try {
- var doc = document.implementation.createHTMLDocument('');
- doc.documentElement.innerHTML = '<title></title><div></div>';
- htmlElInnerHTML = true;
-
- } catch (er) {
- htmlElInnerHTML = false;
- }
-
- // If if that failed, try text/xml
- if (!htmlElInnerHTML) {
-
- try {
- textXML = !!(new DOMParser).parseFromString('', 'text/xml');
-
- } catch (er) {
- textHTML = false;
- }
- }
-
- // Mess with DOMParser.prototype (less than optimal...) if one of the above worked
- // Assume can write to the prototype, if not, make this a stand alone function
- if (DOMParser.prototype && (htmlElInnerHTML || textXML)) {
- DOMParser_proto = DOMParser.prototype;
- real_parseFromString = DOMParser_proto.parseFromString;
-
- DOMParser_proto.parseFromString = function (markup, type) {
-
- // Only do this if type is text/html
- if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
- var doc, doc_el, first_el;
-
- // Use innerHTML if supported
- if (htmlElInnerHTML) {
- doc = document.implementation.createHTMLDocument("");
- doc_el = doc.documentElement;
- doc_el.innerHTML = markup;
- first_el = doc_el.firstElementChild;
-
- // Otherwise use XML method
- } else if (textXML) {
-
- // Make sure markup is wrapped in HTML tags
- // Should probably allow for a DOCTYPE
- if (!(/^<html.*html>$/i.test(markup))) {
- markup = '<html>' + markup + '<\/html>';
- }
- doc = (new DOMParser).parseFromString(markup, 'text/xml');
- doc_el = doc.documentElement;
- first_el = doc_el.firstElementChild;
- }
-
- // Is this an entire document or a fragment?
- if (doc_el.childElementCount == 1 && first_el.localName.toLowerCase() == 'html') {
- doc.replaceChild(first_el, doc_el);
- }
-
- return doc;
-
- // If not text/html, send as-is to host method
- } else {
- return real_parseFromString.apply(this, arguments);
- }
- };
- }
-}(DOMParser));
diff --git a/toolkit/components/microformats/test/static/javascript/beautify.js b/toolkit/components/microformats/test/static/javascript/beautify.js
deleted file mode 100644
index 55d06cb08..000000000
--- a/toolkit/components/microformats/test/static/javascript/beautify.js
+++ /dev/null
@@ -1,518 +0,0 @@
-/*
-
- JS Beautifier
----------------
-
- Written by Einars "elfz" Lielmanis, <elfz@laacz.lv>
- http://elfz.laacz.lv/beautify/
-
- Originally converted to javascript by Vital, <vital76@gmail.com>
- http://my.opera.com/Vital/blog/2007/11/21/javascript-beautify-on-javascript-translated
-
-
- You are free to use this in any way you want, in case you find this useful or working for you.
-
- Usage:
- js_beautify(js_source_text);
-
-
-*/
-
-
-function js_beautify(js_source_text, indent_size, indent_character)
-{
-
- var input, output, token_text, last_type, current_mode, modes, indent_level, indent_string;
- var whitespace, wordchar, punct;
-
- indent_character = indent_character || ' ';
- indent_size = indent_size || 4;
-
- indent_string = '';
- while (indent_size--) indent_string += indent_character;
-
- input = js_source_text;
-
- last_word = ''; // last 'TK_WORD' passed
- last_type = 'TK_START_EXPR'; // last token type
- last_text = ''; // last token text
- output = '';
-
- whitespace = "\n\r\t ".split('');
- wordchar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'.split('');
- punct = '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |='.split(' ');
-
- // words which should always start on new line.
- line_starters = 'continue,try,throw,return,var,if,switch,case,default,for,while,break,function'.split(',');
-
- // states showing if we are currently in expression (i.e. "if" case) - 'EXPRESSION', or in usual block (like, procedure), 'BLOCK'.
- // some formatting depends on that.
- current_mode = 'BLOCK';
- modes = [current_mode];
-
- indent_level = 0;
- parser_pos = 0; // parser position
- in_case = false; // flag for parser that case/default has been processed, and next colon needs special attention
- while (true) {
- var t = get_next_token(parser_pos);
- token_text = t[0];
- token_type = t[1];
- if (token_type == 'TK_EOF') {
- break;
- }
-
- switch (token_type) {
-
- case 'TK_START_EXPR':
-
- set_mode('EXPRESSION');
- if (last_type == 'TK_END_EXPR' || last_type == 'TK_START_EXPR') {
- // do nothing on (( and )( and ][ and ]( ..
- } else if (last_type != 'TK_WORD' && last_type != 'TK_OPERATOR') {
- print_space();
- } else if (in_array(last_word, line_starters) && last_word != 'function') {
- print_space();
- }
- print_token();
- break;
-
- case 'TK_END_EXPR':
-
- print_token();
- restore_mode();
- break;
-
- case 'TK_START_BLOCK':
-
- set_mode('BLOCK');
- if (last_type != 'TK_OPERATOR' && last_type != 'TK_START_EXPR') {
- if (last_type == 'TK_START_BLOCK') {
- print_newline();
- } else {
- print_space();
- }
- }
- print_token();
- indent();
- break;
-
- case 'TK_END_BLOCK':
-
- if (last_type == 'TK_END_EXPR') {
- unindent();
- print_newline();
- } else if (last_type == 'TK_END_BLOCK') {
- unindent();
- print_newline();
- } else if (last_type == 'TK_START_BLOCK') {
- // nothing
- unindent();
- } else {
- unindent();
- print_newline();
- }
- print_token();
- restore_mode();
- break;
-
- case 'TK_WORD':
-
- if (token_text == 'case' || token_text == 'default') {
- if (last_text == ':') {
- // switch cases following one another
- remove_indent();
- } else {
- // case statement starts in the same line where switch
- unindent();
- print_newline();
- indent();
- }
- print_token();
- in_case = true;
- break;
- }
-
- prefix = 'NONE';
- if (last_type == 'TK_END_BLOCK') {
- if (!in_array(token_text.toLowerCase(), ['else', 'catch', 'finally'])) {
- prefix = 'NEWLINE';
- } else {
- prefix = 'SPACE';
- print_space();
- }
- } else if (last_type == 'TK_END_COMMAND' && current_mode == 'BLOCK') {
- prefix = 'NEWLINE';
- } else if (last_type == 'TK_END_COMMAND' && current_mode == 'EXPRESSION') {
- prefix = 'SPACE';
- } else if (last_type == 'TK_WORD') {
- prefix = 'SPACE';
- } else if (last_type == 'TK_START_BLOCK') {
- prefix = 'NEWLINE';
- } else if (last_type == 'TK_END_EXPR') {
- print_space();
- prefix = 'NEWLINE';
- }
-
- if (in_array(token_text, line_starters) || prefix == 'NEWLINE') {
-
- if (last_text == 'else') {
- // no need to force newline on else break
- print_space();
- } else if ((last_type == 'TK_START_EXPR' || last_text == '=') && token_text == 'function') {
- // no need to force newline on 'function': (function
- // DONOTHING
- } else if (last_type == 'TK_WORD' && (last_text == 'return' || last_text == 'throw')) {
- // no newline between 'return nnn'
- print_space();
- } else
- if (last_type != 'TK_END_EXPR') {
- if ((last_type != 'TK_START_EXPR' || token_text != 'var') && last_text != ':') {
- // no need to force newline on 'var': for (var x = 0...)
- if (token_text == 'if' && last_type == 'TK_WORD' && last_word == 'else') {
- // no newline for } else if {
- print_space();
- } else {
- print_newline();
- }
- }
- }
- } else if (prefix == 'SPACE') {
- print_space();
- }
- print_token();
- last_word = token_text;
- break;
-
- case 'TK_END_COMMAND':
-
- print_token();
- break;
-
- case 'TK_STRING':
-
- if (last_type == 'TK_START_BLOCK' || last_type == 'TK_END_BLOCK') {
- print_newline();
- } else if (last_type == 'TK_WORD') {
- print_space();
- }
- print_token();
- break;
-
- case 'TK_OPERATOR':
- start_delim = true;
- end_delim = true;
-
- if (token_text == ':' && in_case) {
- print_token(); // colon really asks for separate treatment
- print_newline();
- break;
- }
-
- in_case = false;
-
- if (token_text == ',') {
- if (last_type == 'TK_END_BLOCK') {
- print_token();
- print_newline();
- } else {
- if (current_mode == 'BLOCK') {
- print_token();
- print_newline();
- } else {
- print_token();
- print_space();
- }
- }
- break;
- } else if (token_text == '--' || token_text == '++') { // unary operators special case
- if (last_text == ';') {
- // space for (;; ++i)
- start_delim = true;
- end_delim = false;
- } else {
- start_delim = false;
- end_delim = false;
- }
- } else if (token_text == '!' && last_type == 'TK_START_EXPR') {
- // special case handling: if (!a)
- start_delim = false;
- end_delim = false;
- } else if (last_type == 'TK_OPERATOR') {
- start_delim = false;
- end_delim = false;
- } else if (last_type == 'TK_END_EXPR') {
- start_delim = true;
- end_delim = true;
- } else if (token_text == '.') {
- // decimal digits or object.property
- start_delim = false;
- end_delim = false;
-
- } else if (token_text == ':') {
- // zz: xx
- // can't differentiate ternary op, so for now it's a ? b: c; without space before colon
- start_delim = false;
- }
- if (start_delim) {
- print_space();
- }
-
- print_token();
-
- if (end_delim) {
- print_space();
- }
- break;
-
- case 'TK_BLOCK_COMMENT':
-
- print_newline();
- print_token();
- print_newline();
- break;
-
- case 'TK_COMMENT':
-
- // print_newline();
- print_space();
- print_token();
- print_newline();
- break;
-
- case 'TK_UNKNOWN':
- print_token();
- break;
- }
-
- if (token_type != 'TK_COMMENT') {
- last_type = token_type;
- last_text = token_text;
- }
- }
-
- return output;
-
-
-
-
- function print_newline(ignore_repeated)
- {
- ignore_repeated = typeof ignore_repeated == 'undefined' ? true: ignore_repeated;
- output = output.replace(/[ \t]+$/, ''); // remove possible indent
- if (output == '') return; // no newline on start of file
- if (output.substr(output.length - 1) != "\n" || !ignore_repeated) {
- output += "\n";
- }
- for (var i = 0; i < indent_level; i++) {
- output += indent_string;
- }
- }
-
-
-
- function print_space()
- {
- if (output && output.substr(output.length - 1) != ' ' && output.substr(output.length - 1) != '\n') { // prevent occassional duplicate space
- output += ' ';
- }
- }
-
-
- function print_token()
- {
- output += token_text;
- }
-
- function indent()
- {
- indent_level++;
- }
-
-
- function unindent()
- {
- if (indent_level) {
- indent_level--;
- }
- }
-
-
- function remove_indent()
- {
- if (output.substr(output.length - indent_string.length) == indent_string) {
- output = output.substr(0, output.length - indent_string.length);
- }
- }
-
-
- function set_mode(mode)
- {
- modes.push(current_mode);
- current_mode = mode;
- }
-
-
- function restore_mode()
- {
- current_mode = modes.pop();
- }
-
-
-
- function get_next_token()
- {
- var n_newlines = 0;
- var c = '';
-
- do {
- if (parser_pos >= input.length) {
- return ['', 'TK_EOF'];
- }
- c = input.charAt(parser_pos);
-
- parser_pos += 1;
- if (c == "\n") {
- n_newlines += 1;
- }
- }
- while (in_array(c, whitespace));
-
- if (n_newlines > 1) {
- for (var i = 0; i < n_newlines; i++) {
- print_newline(i == 0);
- }
- }
- var wanted_newline = n_newlines == 1;
-
-
- if (in_array(c, wordchar)) {
- if (parser_pos < input.length) {
- while (in_array(input.charAt(parser_pos), wordchar)) {
- c += input.charAt(parser_pos);
- parser_pos += 1;
- if (parser_pos == input.length) break;
- }
- }
-
- // small and surprisingly unugly hack for 1E-10 representation
- if (parser_pos != input.length && c.match(/^[0-9]+[Ee]$/) && input.charAt(parser_pos) == '-') {
- parser_pos += 1;
-
- var t = get_next_token(parser_pos);
- next_word = t[0];
- next_type = t[1];
-
- c += '-' + next_word;
- return [c, 'TK_WORD'];
- }
-
- if (c == 'in') { // hack for 'in' operator
- return [c, 'TK_OPERATOR'];
- }
- return [c, 'TK_WORD'];
- }
-
- if (c == '(' || c == '[') {
- return [c, 'TK_START_EXPR'];
- }
-
- if (c == ')' || c == ']') {
- return [c, 'TK_END_EXPR'];
- }
-
- if (c == '{') {
- return [c, 'TK_START_BLOCK'];
- }
-
- if (c == '}') {
- return [c, 'TK_END_BLOCK'];
- }
-
- if (c == ';') {
- return [c, 'TK_END_COMMAND'];
- }
-
- if (c == '/') {
- // peek for comment /* ... */
- if (input.charAt(parser_pos) == '*') {
- comment = '';
- parser_pos += 1;
- if (parser_pos < input.length) {
- while (! (input.charAt(parser_pos) == '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) == '/') && parser_pos < input.length) {
- comment += input.charAt(parser_pos);
- parser_pos += 1;
- if (parser_pos >= input.length) break;
- }
- }
- parser_pos += 2;
- return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT'];
- }
- // peek for comment // ...
- if (input.charAt(parser_pos) == '/') {
- comment = c;
- while (input.charAt(parser_pos) != "\x0d" && input.charAt(parser_pos) != "\x0a") {
- comment += input.charAt(parser_pos);
- parser_pos += 1;
- if (parser_pos >= input.length) break;
- }
- parser_pos += 1;
- if (wanted_newline) {
- print_newline();
- }
- return [comment, 'TK_COMMENT'];
- }
-
- }
-
- if (c == "'" || // string
- c == '"' || // string
- (c == '/' &&
- ((last_type == 'TK_WORD' && last_text == 'return') || (last_type == 'TK_START_EXPR' || last_type == 'TK_END_BLOCK' || last_type == 'TK_OPERATOR' || last_type == 'TK_EOF' || last_type == 'TK_END_COMMAND')))) { // regexp
- sep = c;
- c = '';
- esc = false;
-
- if (parser_pos < input.length) {
-
- while (esc || input.charAt(parser_pos) != sep) {
- c += input.charAt(parser_pos);
- if (!esc) {
- esc = input.charAt(parser_pos) == '\\';
- } else {
- esc = false;
- }
- parser_pos += 1;
- if (parser_pos >= input.length) break;
- }
-
- }
-
- parser_pos += 1;
- if (last_type == 'TK_END_COMMAND') {
- print_newline();
- }
- return [sep + c + sep, 'TK_STRING'];
- }
-
- if (in_array(c, punct)) {
- while (parser_pos < input.length && in_array(c + input.charAt(parser_pos), punct)) {
- c += input.charAt(parser_pos);
- parser_pos += 1;
- if (parser_pos >= input.length) break;
- }
- return [c, 'TK_OPERATOR'];
- }
-
- return [c, 'TK_UNKNOWN'];
- }
-
-
- function in_array(what, arr)
- {
- for (var i = 0; i < arr.length; i++)
- {
- if (arr[i] == what) return true;
- }
- return false;
- }
-}
diff --git a/toolkit/components/microformats/test/static/javascript/chai.js b/toolkit/components/microformats/test/static/javascript/chai.js
deleted file mode 100644
index bbdbe907b..000000000
--- a/toolkit/components/microformats/test/static/javascript/chai.js
+++ /dev/null
@@ -1,5351 +0,0 @@
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.chai = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
-/*!
- * chai
- * Copyright(c) 2011-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-var used = [];
-exports = module.exports = {};
-
-/*!
- * Chai version
- */
-
-exports.version = '3.0.0';
-
-/*!
- * Assertion Error
- */
-
-exports.AssertionError = require('assertion-error');
-
-/*!
- * Utils for plugins (not exported)
- */
-
-var util = require('./chai/utils');
-
-/**
- * # .use(function)
- *
- * Provides a way to extend the internals of Chai
- *
- * @param {Function}
- * @returns {this} for chaining
- * @api public
- */
-
-exports.use = function (fn) {
- if (!~used.indexOf(fn)) {
- fn(this, util);
- used.push(fn);
- }
-
- return this;
-};
-
-/*!
- * Utility Functions
- */
-
-exports.util = util;
-
-/*!
- * Configuration
- */
-
-var config = require('./chai/config');
-exports.config = config;
-
-/*!
- * Primary `Assertion` prototype
- */
-
-var assertion = require('./chai/assertion');
-exports.use(assertion);
-
-/*!
- * Core Assertions
- */
-
-var core = require('./chai/core/assertions');
-exports.use(core);
-
-/*!
- * Expect interface
- */
-
-var expect = require('./chai/interface/expect');
-exports.use(expect);
-
-/*!
- * Should interface
- */
-
-var should = require('./chai/interface/should');
-exports.use(should);
-
-/*!
- * Assert interface
- */
-
-var assert = require('./chai/interface/assert');
-exports.use(assert);
-
-},{"./chai/assertion":2,"./chai/config":3,"./chai/core/assertions":4,"./chai/interface/assert":5,"./chai/interface/expect":6,"./chai/interface/should":7,"./chai/utils":20,"assertion-error":28}],2:[function(require,module,exports){
-/*!
- * chai
- * http://chaijs.com
- * Copyright(c) 2011-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-var config = require('./config');
-
-module.exports = function (_chai, util) {
- /*!
- * Module dependencies.
- */
-
- var AssertionError = _chai.AssertionError
- , flag = util.flag;
-
- /*!
- * Module export.
- */
-
- _chai.Assertion = Assertion;
-
- /*!
- * Assertion Constructor
- *
- * Creates object for chaining.
- *
- * @api private
- */
-
- function Assertion (obj, msg, stack) {
- flag(this, 'ssfi', stack || arguments.callee);
- flag(this, 'object', obj);
- flag(this, 'message', msg);
- }
-
- Object.defineProperty(Assertion, 'includeStack', {
- get: function() {
- console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.');
- return config.includeStack;
- },
- set: function(value) {
- console.warn('Assertion.includeStack is deprecated, use chai.config.includeStack instead.');
- config.includeStack = value;
- }
- });
-
- Object.defineProperty(Assertion, 'showDiff', {
- get: function() {
- console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.');
- return config.showDiff;
- },
- set: function(value) {
- console.warn('Assertion.showDiff is deprecated, use chai.config.showDiff instead.');
- config.showDiff = value;
- }
- });
-
- Assertion.addProperty = function (name, fn) {
- util.addProperty(this.prototype, name, fn);
- };
-
- Assertion.addMethod = function (name, fn) {
- util.addMethod(this.prototype, name, fn);
- };
-
- Assertion.addChainableMethod = function (name, fn, chainingBehavior) {
- util.addChainableMethod(this.prototype, name, fn, chainingBehavior);
- };
-
- Assertion.overwriteProperty = function (name, fn) {
- util.overwriteProperty(this.prototype, name, fn);
- };
-
- Assertion.overwriteMethod = function (name, fn) {
- util.overwriteMethod(this.prototype, name, fn);
- };
-
- Assertion.overwriteChainableMethod = function (name, fn, chainingBehavior) {
- util.overwriteChainableMethod(this.prototype, name, fn, chainingBehavior);
- };
-
- /**
- * ### .assert(expression, message, negateMessage, expected, actual, showDiff)
- *
- * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass.
- *
- * @name assert
- * @param {Philosophical} expression to be tested
- * @param {String or Function} message or function that returns message to display if expression fails
- * @param {String or Function} negatedMessage or function that returns negatedMessage to display if negated expression fails
- * @param {Mixed} expected value (remember to check for negation)
- * @param {Mixed} actual (optional) will default to `this.obj`
- * @param {Boolean} showDiff (optional) when set to `true`, assert will display a diff in addition to the message if expression fails
- * @api private
- */
-
- Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) {
- var ok = util.test(this, arguments);
- if (true !== showDiff) showDiff = false;
- if (true !== config.showDiff) showDiff = false;
-
- if (!ok) {
- msg = util.getMessage(this, arguments)
- var actual = util.getActual(this, arguments);
- throw new AssertionError(msg, {
- actual: actual
- , expected: expected
- , showDiff: showDiff
- }, (config.includeStack) ? this.assert : flag(this, 'ssfi'));
- }
- };
-
- /*!
- * ### ._obj
- *
- * Quick reference to stored `actual` value for plugin developers.
- *
- * @api private
- */
-
- Object.defineProperty(Assertion.prototype, '_obj',
- { get: function () {
- return flag(this, 'object');
- }
- , set: function (val) {
- flag(this, 'object', val);
- }
- });
-};
-
-},{"./config":3}],3:[function(require,module,exports){
-module.exports = {
-
- /**
- * ### config.includeStack
- *
- * User configurable property, influences whether stack trace
- * is included in Assertion error message. Default of false
- * suppresses stack trace in the error message.
- *
- * chai.config.includeStack = true; // enable stack on error
- *
- * @param {Boolean}
- * @api public
- */
-
- includeStack: false,
-
- /**
- * ### config.showDiff
- *
- * User configurable property, influences whether or not
- * the `showDiff` flag should be included in the thrown
- * AssertionErrors. `false` will always be `false`; `true`
- * will be true when the assertion has requested a diff
- * be shown.
- *
- * @param {Boolean}
- * @api public
- */
-
- showDiff: true,
-
- /**
- * ### config.truncateThreshold
- *
- * User configurable property, sets length threshold for actual and
- * expected values in assertion errors. If this threshold is exceeded, for
- * example for large data structures, the value is replaced with something
- * like `[ Array(3) ]` or `{ Object (prop1, prop2) }`.
- *
- * Set it to zero if you want to disable truncating altogether.
- *
- * This is especially userful when doing assertions on arrays: having this
- * set to a reasonable large value makes the failure messages readily
- * inspectable.
- *
- * chai.config.truncateThreshold = 0; // disable truncating
- *
- * @param {Number}
- * @api public
- */
-
- truncateThreshold: 40
-
-};
-
-},{}],4:[function(require,module,exports){
-/*!
- * chai
- * http://chaijs.com
- * Copyright(c) 2011-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-module.exports = function (chai, _) {
- var Assertion = chai.Assertion
- , toString = Object.prototype.toString
- , flag = _.flag;
-
- /**
- * ### Language Chains
- *
- * The following are provided as chainable getters to
- * improve the readability of your assertions. They
- * do not provide testing capabilities unless they
- * have been overwritten by a plugin.
- *
- * **Chains**
- *
- * - to
- * - be
- * - been
- * - is
- * - that
- * - which
- * - and
- * - has
- * - have
- * - with
- * - at
- * - of
- * - same
- *
- * @name language chains
- * @api public
- */
-
- [ 'to', 'be', 'been'
- , 'is', 'and', 'has', 'have'
- , 'with', 'that', 'which', 'at'
- , 'of', 'same' ].forEach(function (chain) {
- Assertion.addProperty(chain, function () {
- return this;
- });
- });
-
- /**
- * ### .not
- *
- * Negates any of assertions following in the chain.
- *
- * expect(foo).to.not.equal('bar');
- * expect(goodFn).to.not.throw(Error);
- * expect({ foo: 'baz' }).to.have.property('foo')
- * .and.not.equal('bar');
- *
- * @name not
- * @api public
- */
-
- Assertion.addProperty('not', function () {
- flag(this, 'negate', true);
- });
-
- /**
- * ### .deep
- *
- * Sets the `deep` flag, later used by the `equal` and
- * `property` assertions.
- *
- * expect(foo).to.deep.equal({ bar: 'baz' });
- * expect({ foo: { bar: { baz: 'quux' } } })
- * .to.have.deep.property('foo.bar.baz', 'quux');
- *
- * `.deep.property` special characters can be escaped
- * by adding two slashes before the `.` or `[]`.
- *
- * var deepCss = { '.link': { '[target]': 42 }};
- * expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42);
- *
- * @name deep
- * @api public
- */
-
- Assertion.addProperty('deep', function () {
- flag(this, 'deep', true);
- });
-
- /**
- * ### .any
- *
- * Sets the `any` flag, (opposite of the `all` flag)
- * later used in the `keys` assertion.
- *
- * expect(foo).to.have.any.keys('bar', 'baz');
- *
- * @name any
- * @api public
- */
-
- Assertion.addProperty('any', function () {
- flag(this, 'any', true);
- flag(this, 'all', false)
- });
-
-
- /**
- * ### .all
- *
- * Sets the `all` flag (opposite of the `any` flag)
- * later used by the `keys` assertion.
- *
- * expect(foo).to.have.all.keys('bar', 'baz');
- *
- * @name all
- * @api public
- */
-
- Assertion.addProperty('all', function () {
- flag(this, 'all', true);
- flag(this, 'any', false);
- });
-
- /**
- * ### .a(type)
- *
- * The `a` and `an` assertions are aliases that can be
- * used either as language chains or to assert a value's
- * type.
- *
- * // typeof
- * expect('test').to.be.a('string');
- * expect({ foo: 'bar' }).to.be.an('object');
- * expect(null).to.be.a('null');
- * expect(undefined).to.be.an('undefined');
- * expect(new Promise).to.be.a('promise');
- * expect(new Float32Array()).to.be.a('float32array');
- * expect(Symbol()).to.be.a('symbol');
- *
- * // es6 overrides
- * expect({[Symbol.toStringTag]:()=>'foo'}).to.be.a('foo');
- *
- * // language chain
- * expect(foo).to.be.an.instanceof(Foo);
- *
- * @name a
- * @alias an
- * @param {String} type
- * @param {String} message _optional_
- * @api public
- */
-
- function an (type, msg) {
- if (msg) flag(this, 'message', msg);
- type = type.toLowerCase();
- var obj = flag(this, 'object')
- , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a ';
-
- this.assert(
- type === _.type(obj)
- , 'expected #{this} to be ' + article + type
- , 'expected #{this} not to be ' + article + type
- );
- }
-
- Assertion.addChainableMethod('an', an);
- Assertion.addChainableMethod('a', an);
-
- /**
- * ### .include(value)
- *
- * The `include` and `contain` assertions can be used as either property
- * based language chains or as methods to assert the inclusion of an object
- * in an array or a substring in a string. When used as language chains,
- * they toggle the `contains` flag for the `keys` assertion.
- *
- * expect([1,2,3]).to.include(2);
- * expect('foobar').to.contain('foo');
- * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
- *
- * @name include
- * @alias contain
- * @alias includes
- * @alias contains
- * @param {Object|String|Number} obj
- * @param {String} message _optional_
- * @api public
- */
-
- function includeChainingBehavior () {
- flag(this, 'contains', true);
- }
-
- function include (val, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- var expected = false;
- if (_.type(obj) === 'array' && _.type(val) === 'object') {
- for (var i in obj) {
- if (_.eql(obj[i], val)) {
- expected = true;
- break;
- }
- }
- } else if (_.type(val) === 'object') {
- if (!flag(this, 'negate')) {
- for (var k in val) new Assertion(obj).property(k, val[k]);
- return;
- }
- var subset = {};
- for (k in val) subset[k] = obj[k];
- expected = _.eql(subset, val);
- } else {
- expected = obj && ~obj.indexOf(val);
- }
- this.assert(
- expected
- , 'expected #{this} to include ' + _.inspect(val)
- , 'expected #{this} to not include ' + _.inspect(val));
- }
-
- Assertion.addChainableMethod('include', include, includeChainingBehavior);
- Assertion.addChainableMethod('contain', include, includeChainingBehavior);
- Assertion.addChainableMethod('contains', include, includeChainingBehavior);
- Assertion.addChainableMethod('includes', include, includeChainingBehavior);
-
- /**
- * ### .ok
- *
- * Asserts that the target is truthy.
- *
- * expect('everthing').to.be.ok;
- * expect(1).to.be.ok;
- * expect(false).to.not.be.ok;
- * expect(undefined).to.not.be.ok;
- * expect(null).to.not.be.ok;
- *
- * @name ok
- * @api public
- */
-
- Assertion.addProperty('ok', function () {
- this.assert(
- flag(this, 'object')
- , 'expected #{this} to be truthy'
- , 'expected #{this} to be falsy');
- });
-
- /**
- * ### .true
- *
- * Asserts that the target is `true`.
- *
- * expect(true).to.be.true;
- * expect(1).to.not.be.true;
- *
- * @name true
- * @api public
- */
-
- Assertion.addProperty('true', function () {
- this.assert(
- true === flag(this, 'object')
- , 'expected #{this} to be true'
- , 'expected #{this} to be false'
- , this.negate ? false : true
- );
- });
-
- /**
- * ### .false
- *
- * Asserts that the target is `false`.
- *
- * expect(false).to.be.false;
- * expect(0).to.not.be.false;
- *
- * @name false
- * @api public
- */
-
- Assertion.addProperty('false', function () {
- this.assert(
- false === flag(this, 'object')
- , 'expected #{this} to be false'
- , 'expected #{this} to be true'
- , this.negate ? true : false
- );
- });
-
- /**
- * ### .null
- *
- * Asserts that the target is `null`.
- *
- * expect(null).to.be.null;
- * expect(undefined).to.not.be.null;
- *
- * @name null
- * @api public
- */
-
- Assertion.addProperty('null', function () {
- this.assert(
- null === flag(this, 'object')
- , 'expected #{this} to be null'
- , 'expected #{this} not to be null'
- );
- });
-
- /**
- * ### .undefined
- *
- * Asserts that the target is `undefined`.
- *
- * expect(undefined).to.be.undefined;
- * expect(null).to.not.be.undefined;
- *
- * @name undefined
- * @api public
- */
-
- Assertion.addProperty('undefined', function () {
- this.assert(
- undefined === flag(this, 'object')
- , 'expected #{this} to be undefined'
- , 'expected #{this} not to be undefined'
- );
- });
-
- /**
- * ### .exist
- *
- * Asserts that the target is neither `null` nor `undefined`.
- *
- * var foo = 'hi'
- * , bar = null
- * , baz;
- *
- * expect(foo).to.exist;
- * expect(bar).to.not.exist;
- * expect(baz).to.not.exist;
- *
- * @name exist
- * @api public
- */
-
- Assertion.addProperty('exist', function () {
- this.assert(
- null != flag(this, 'object')
- , 'expected #{this} to exist'
- , 'expected #{this} to not exist'
- );
- });
-
-
- /**
- * ### .empty
- *
- * Asserts that the target's length is `0`. For arrays and strings, it checks
- * the `length` property. For objects, it gets the count of
- * enumerable keys.
- *
- * expect([]).to.be.empty;
- * expect('').to.be.empty;
- * expect({}).to.be.empty;
- *
- * @name empty
- * @api public
- */
-
- Assertion.addProperty('empty', function () {
- var obj = flag(this, 'object')
- , expected = obj;
-
- if (Array.isArray(obj) || 'string' === typeof object) {
- expected = obj.length;
- } else if (typeof obj === 'object') {
- expected = Object.keys(obj).length;
- }
-
- this.assert(
- !expected
- , 'expected #{this} to be empty'
- , 'expected #{this} not to be empty'
- );
- });
-
- /**
- * ### .arguments
- *
- * Asserts that the target is an arguments object.
- *
- * function test () {
- * expect(arguments).to.be.arguments;
- * }
- *
- * @name arguments
- * @alias Arguments
- * @api public
- */
-
- function checkArguments () {
- var obj = flag(this, 'object')
- , type = Object.prototype.toString.call(obj);
- this.assert(
- '[object Arguments]' === type
- , 'expected #{this} to be arguments but got ' + type
- , 'expected #{this} to not be arguments'
- );
- }
-
- Assertion.addProperty('arguments', checkArguments);
- Assertion.addProperty('Arguments', checkArguments);
-
- /**
- * ### .equal(value)
- *
- * Asserts that the target is strictly equal (`===`) to `value`.
- * Alternately, if the `deep` flag is set, asserts that
- * the target is deeply equal to `value`.
- *
- * expect('hello').to.equal('hello');
- * expect(42).to.equal(42);
- * expect(1).to.not.equal(true);
- * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' });
- * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
- *
- * @name equal
- * @alias equals
- * @alias eq
- * @alias deep.equal
- * @param {Mixed} value
- * @param {String} message _optional_
- * @api public
- */
-
- function assertEqual (val, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- if (flag(this, 'deep')) {
- return this.eql(val);
- } else {
- this.assert(
- val === obj
- , 'expected #{this} to equal #{exp}'
- , 'expected #{this} to not equal #{exp}'
- , val
- , this._obj
- , true
- );
- }
- }
-
- Assertion.addMethod('equal', assertEqual);
- Assertion.addMethod('equals', assertEqual);
- Assertion.addMethod('eq', assertEqual);
-
- /**
- * ### .eql(value)
- *
- * Asserts that the target is deeply equal to `value`.
- *
- * expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
- * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]);
- *
- * @name eql
- * @alias eqls
- * @param {Mixed} value
- * @param {String} message _optional_
- * @api public
- */
-
- function assertEql(obj, msg) {
- if (msg) flag(this, 'message', msg);
- this.assert(
- _.eql(obj, flag(this, 'object'))
- , 'expected #{this} to deeply equal #{exp}'
- , 'expected #{this} to not deeply equal #{exp}'
- , obj
- , this._obj
- , true
- );
- }
-
- Assertion.addMethod('eql', assertEql);
- Assertion.addMethod('eqls', assertEql);
-
- /**
- * ### .above(value)
- *
- * Asserts that the target is greater than `value`.
- *
- * expect(10).to.be.above(5);
- *
- * Can also be used in conjunction with `length` to
- * assert a minimum length. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.above(2);
- * expect([ 1, 2, 3 ]).to.have.length.above(2);
- *
- * @name above
- * @alias gt
- * @alias greaterThan
- * @param {Number} value
- * @param {String} message _optional_
- * @api public
- */
-
- function assertAbove (n, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- if (flag(this, 'doLength')) {
- new Assertion(obj, msg).to.have.property('length');
- var len = obj.length;
- this.assert(
- len > n
- , 'expected #{this} to have a length above #{exp} but got #{act}'
- , 'expected #{this} to not have a length above #{exp}'
- , n
- , len
- );
- } else {
- this.assert(
- obj > n
- , 'expected #{this} to be above ' + n
- , 'expected #{this} to be at most ' + n
- );
- }
- }
-
- Assertion.addMethod('above', assertAbove);
- Assertion.addMethod('gt', assertAbove);
- Assertion.addMethod('greaterThan', assertAbove);
-
- /**
- * ### .least(value)
- *
- * Asserts that the target is greater than or equal to `value`.
- *
- * expect(10).to.be.at.least(10);
- *
- * Can also be used in conjunction with `length` to
- * assert a minimum length. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.of.at.least(2);
- * expect([ 1, 2, 3 ]).to.have.length.of.at.least(3);
- *
- * @name least
- * @alias gte
- * @param {Number} value
- * @param {String} message _optional_
- * @api public
- */
-
- function assertLeast (n, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- if (flag(this, 'doLength')) {
- new Assertion(obj, msg).to.have.property('length');
- var len = obj.length;
- this.assert(
- len >= n
- , 'expected #{this} to have a length at least #{exp} but got #{act}'
- , 'expected #{this} to have a length below #{exp}'
- , n
- , len
- );
- } else {
- this.assert(
- obj >= n
- , 'expected #{this} to be at least ' + n
- , 'expected #{this} to be below ' + n
- );
- }
- }
-
- Assertion.addMethod('least', assertLeast);
- Assertion.addMethod('gte', assertLeast);
-
- /**
- * ### .below(value)
- *
- * Asserts that the target is less than `value`.
- *
- * expect(5).to.be.below(10);
- *
- * Can also be used in conjunction with `length` to
- * assert a maximum length. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.below(4);
- * expect([ 1, 2, 3 ]).to.have.length.below(4);
- *
- * @name below
- * @alias lt
- * @alias lessThan
- * @param {Number} value
- * @param {String} message _optional_
- * @api public
- */
-
- function assertBelow (n, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- if (flag(this, 'doLength')) {
- new Assertion(obj, msg).to.have.property('length');
- var len = obj.length;
- this.assert(
- len < n
- , 'expected #{this} to have a length below #{exp} but got #{act}'
- , 'expected #{this} to not have a length below #{exp}'
- , n
- , len
- );
- } else {
- this.assert(
- obj < n
- , 'expected #{this} to be below ' + n
- , 'expected #{this} to be at least ' + n
- );
- }
- }
-
- Assertion.addMethod('below', assertBelow);
- Assertion.addMethod('lt', assertBelow);
- Assertion.addMethod('lessThan', assertBelow);
-
- /**
- * ### .most(value)
- *
- * Asserts that the target is less than or equal to `value`.
- *
- * expect(5).to.be.at.most(5);
- *
- * Can also be used in conjunction with `length` to
- * assert a maximum length. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.of.at.most(4);
- * expect([ 1, 2, 3 ]).to.have.length.of.at.most(3);
- *
- * @name most
- * @alias lte
- * @param {Number} value
- * @param {String} message _optional_
- * @api public
- */
-
- function assertMost (n, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- if (flag(this, 'doLength')) {
- new Assertion(obj, msg).to.have.property('length');
- var len = obj.length;
- this.assert(
- len <= n
- , 'expected #{this} to have a length at most #{exp} but got #{act}'
- , 'expected #{this} to have a length above #{exp}'
- , n
- , len
- );
- } else {
- this.assert(
- obj <= n
- , 'expected #{this} to be at most ' + n
- , 'expected #{this} to be above ' + n
- );
- }
- }
-
- Assertion.addMethod('most', assertMost);
- Assertion.addMethod('lte', assertMost);
-
- /**
- * ### .within(start, finish)
- *
- * Asserts that the target is within a range.
- *
- * expect(7).to.be.within(5,10);
- *
- * Can also be used in conjunction with `length` to
- * assert a length range. The benefit being a
- * more informative error message than if the length
- * was supplied directly.
- *
- * expect('foo').to.have.length.within(2,4);
- * expect([ 1, 2, 3 ]).to.have.length.within(2,4);
- *
- * @name within
- * @param {Number} start lowerbound inclusive
- * @param {Number} finish upperbound inclusive
- * @param {String} message _optional_
- * @api public
- */
-
- Assertion.addMethod('within', function (start, finish, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object')
- , range = start + '..' + finish;
- if (flag(this, 'doLength')) {
- new Assertion(obj, msg).to.have.property('length');
- var len = obj.length;
- this.assert(
- len >= start && len <= finish
- , 'expected #{this} to have a length within ' + range
- , 'expected #{this} to not have a length within ' + range
- );
- } else {
- this.assert(
- obj >= start && obj <= finish
- , 'expected #{this} to be within ' + range
- , 'expected #{this} to not be within ' + range
- );
- }
- });
-
- /**
- * ### .instanceof(constructor)
- *
- * Asserts that the target is an instance of `constructor`.
- *
- * var Tea = function (name) { this.name = name; }
- * , Chai = new Tea('chai');
- *
- * expect(Chai).to.be.an.instanceof(Tea);
- * expect([ 1, 2, 3 ]).to.be.instanceof(Array);
- *
- * @name instanceof
- * @param {Constructor} constructor
- * @param {String} message _optional_
- * @alias instanceOf
- * @api public
- */
-
- function assertInstanceOf (constructor, msg) {
- if (msg) flag(this, 'message', msg);
- var name = _.getName(constructor);
- this.assert(
- flag(this, 'object') instanceof constructor
- , 'expected #{this} to be an instance of ' + name
- , 'expected #{this} to not be an instance of ' + name
- );
- }
-
- Assertion.addMethod('instanceof', assertInstanceOf);
- Assertion.addMethod('instanceOf', assertInstanceOf);
-
- /**
- * ### .property(name, [value])
- *
- * Asserts that the target has a property `name`, optionally asserting that
- * the value of that property is strictly equal to `value`.
- * If the `deep` flag is set, you can use dot- and bracket-notation for deep
- * references into objects and arrays.
- *
- * // simple referencing
- * var obj = { foo: 'bar' };
- * expect(obj).to.have.property('foo');
- * expect(obj).to.have.property('foo', 'bar');
- *
- * // deep referencing
- * var deepObj = {
- * green: { tea: 'matcha' }
- * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ]
- * };
- *
- * expect(deepObj).to.have.deep.property('green.tea', 'matcha');
- * expect(deepObj).to.have.deep.property('teas[1]', 'matcha');
- * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha');
- *
- * You can also use an array as the starting point of a `deep.property`
- * assertion, or traverse nested arrays.
- *
- * var arr = [
- * [ 'chai', 'matcha', 'konacha' ]
- * , [ { tea: 'chai' }
- * , { tea: 'matcha' }
- * , { tea: 'konacha' } ]
- * ];
- *
- * expect(arr).to.have.deep.property('[0][1]', 'matcha');
- * expect(arr).to.have.deep.property('[1][2].tea', 'konacha');
- *
- * Furthermore, `property` changes the subject of the assertion
- * to be the value of that property from the original object. This
- * permits for further chainable assertions on that property.
- *
- * expect(obj).to.have.property('foo')
- * .that.is.a('string');
- * expect(deepObj).to.have.property('green')
- * .that.is.an('object')
- * .that.deep.equals({ tea: 'matcha' });
- * expect(deepObj).to.have.property('teas')
- * .that.is.an('array')
- * .with.deep.property('[2]')
- * .that.deep.equals({ tea: 'konacha' });
- *
- * Note that dots and bracket in `name` must be backslash-escaped when
- * the `deep` flag is set, while they must NOT be escaped when the `deep`
- * flag is not set.
- *
- * // simple referencing
- * var css = { '.link[target]': 42 };
- * expect(css).to.have.property('.link[target]', 42);
- *
- * // deep referencing
- * var deepCss = { '.link': { '[target]': 42 }};
- * expect(deepCss).to.have.deep.property('\\.link.\\[target\\]', 42);
- *
- * @name property
- * @alias deep.property
- * @param {String} name
- * @param {Mixed} value (optional)
- * @param {String} message _optional_
- * @returns value of property for chaining
- * @api public
- */
-
- Assertion.addMethod('property', function (name, val, msg) {
- if (msg) flag(this, 'message', msg);
-
- var isDeep = !!flag(this, 'deep')
- , descriptor = isDeep ? 'deep property ' : 'property '
- , negate = flag(this, 'negate')
- , obj = flag(this, 'object')
- , pathInfo = isDeep ? _.getPathInfo(name, obj) : null
- , hasProperty = isDeep
- ? pathInfo.exists
- : _.hasProperty(name, obj)
- , value = isDeep
- ? pathInfo.value
- : obj[name];
-
- if (negate && arguments.length > 1) {
- if (undefined === value) {
- msg = (msg != null) ? msg + ': ' : '';
- throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name));
- }
- } else {
- this.assert(
- hasProperty
- , 'expected #{this} to have a ' + descriptor + _.inspect(name)
- , 'expected #{this} to not have ' + descriptor + _.inspect(name));
- }
-
- if (arguments.length > 1) {
- this.assert(
- val === value
- , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}'
- , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}'
- , val
- , value
- );
- }
-
- flag(this, 'object', value);
- });
-
-
- /**
- * ### .ownProperty(name)
- *
- * Asserts that the target has an own property `name`.
- *
- * expect('test').to.have.ownProperty('length');
- *
- * @name ownProperty
- * @alias haveOwnProperty
- * @param {String} name
- * @param {String} message _optional_
- * @api public
- */
-
- function assertOwnProperty (name, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- this.assert(
- obj.hasOwnProperty(name)
- , 'expected #{this} to have own property ' + _.inspect(name)
- , 'expected #{this} to not have own property ' + _.inspect(name)
- );
- }
-
- Assertion.addMethod('ownProperty', assertOwnProperty);
- Assertion.addMethod('haveOwnProperty', assertOwnProperty);
-
- /**
- * ### .ownPropertyDescriptor(name[, descriptor[, message]])
- *
- * Asserts that the target has an own property descriptor `name`, that optionally matches `descriptor`.
- *
- * expect('test').to.have.ownPropertyDescriptor('length');
- * expect('test').to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 });
- * expect('test').not.to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 });
- * expect('test').ownPropertyDescriptor('length').to.have.property('enumerable', false);
- * expect('test').ownPropertyDescriptor('length').to.have.keys('value');
- *
- * @name ownPropertyDescriptor
- * @alias haveOwnPropertyDescriptor
- * @param {String} name
- * @param {Object} descriptor _optional_
- * @param {String} message _optional_
- * @api public
- */
-
- function assertOwnPropertyDescriptor (name, descriptor, msg) {
- if (typeof descriptor === 'string') {
- msg = descriptor;
- descriptor = null;
- }
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- var actualDescriptor = Object.getOwnPropertyDescriptor(Object(obj), name);
- if (actualDescriptor && descriptor) {
- this.assert(
- _.eql(descriptor, actualDescriptor)
- , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to match ' + _.inspect(descriptor) + ', got ' + _.inspect(actualDescriptor)
- , 'expected the own property descriptor for ' + _.inspect(name) + ' on #{this} to not match ' + _.inspect(descriptor)
- , descriptor
- , actualDescriptor
- , true
- );
- } else {
- this.assert(
- actualDescriptor
- , 'expected #{this} to have an own property descriptor for ' + _.inspect(name)
- , 'expected #{this} to not have an own property descriptor for ' + _.inspect(name)
- );
- }
- flag(this, 'object', actualDescriptor);
- }
-
- Assertion.addMethod('ownPropertyDescriptor', assertOwnPropertyDescriptor);
- Assertion.addMethod('haveOwnPropertyDescriptor', assertOwnPropertyDescriptor);
-
- /**
- * ### .length
- *
- * Sets the `doLength` flag later used as a chain precursor to a value
- * comparison for the `length` property.
- *
- * expect('foo').to.have.length.above(2);
- * expect([ 1, 2, 3 ]).to.have.length.above(2);
- * expect('foo').to.have.length.below(4);
- * expect([ 1, 2, 3 ]).to.have.length.below(4);
- * expect('foo').to.have.length.within(2,4);
- * expect([ 1, 2, 3 ]).to.have.length.within(2,4);
- *
- * *Deprecation notice:* Using `length` as an assertion will be deprecated
- * in version 2.4.0 and removed in 3.0.0. Code using the old style of
- * asserting for `length` property value using `length(value)` should be
- * switched to use `lengthOf(value)` instead.
- *
- * @name length
- * @api public
- */
-
- /**
- * ### .lengthOf(value[, message])
- *
- * Asserts that the target's `length` property has
- * the expected value.
- *
- * expect([ 1, 2, 3]).to.have.lengthOf(3);
- * expect('foobar').to.have.lengthOf(6);
- *
- * @name lengthOf
- * @param {Number} length
- * @param {String} message _optional_
- * @api public
- */
-
- function assertLengthChain () {
- flag(this, 'doLength', true);
- }
-
- function assertLength (n, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- new Assertion(obj, msg).to.have.property('length');
- var len = obj.length;
-
- this.assert(
- len == n
- , 'expected #{this} to have a length of #{exp} but got #{act}'
- , 'expected #{this} to not have a length of #{act}'
- , n
- , len
- );
- }
-
- Assertion.addChainableMethod('length', assertLength, assertLengthChain);
- Assertion.addMethod('lengthOf', assertLength);
-
- /**
- * ### .match(regexp)
- *
- * Asserts that the target matches a regular expression.
- *
- * expect('foobar').to.match(/^foo/);
- *
- * @name match
- * @alias matches
- * @param {RegExp} RegularExpression
- * @param {String} message _optional_
- * @api public
- */
- function assertMatch(re, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- this.assert(
- re.exec(obj)
- , 'expected #{this} to match ' + re
- , 'expected #{this} not to match ' + re
- );
- }
-
- Assertion.addMethod('match', assertMatch);
- Assertion.addMethod('matches', assertMatch);
-
- /**
- * ### .string(string)
- *
- * Asserts that the string target contains another string.
- *
- * expect('foobar').to.have.string('bar');
- *
- * @name string
- * @param {String} string
- * @param {String} message _optional_
- * @api public
- */
-
- Assertion.addMethod('string', function (str, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- new Assertion(obj, msg).is.a('string');
-
- this.assert(
- ~obj.indexOf(str)
- , 'expected #{this} to contain ' + _.inspect(str)
- , 'expected #{this} to not contain ' + _.inspect(str)
- );
- });
-
-
- /**
- * ### .keys(key1, [key2], [...])
- *
- * Asserts that the target contains any or all of the passed-in keys.
- * Use in combination with `any`, `all`, `contains`, or `have` will affect
- * what will pass.
- *
- * When used in conjunction with `any`, at least one key that is passed
- * in must exist in the target object. This is regardless whether or not
- * the `have` or `contain` qualifiers are used. Note, either `any` or `all`
- * should be used in the assertion. If neither are used, the assertion is
- * defaulted to `all`.
- *
- * When both `all` and `contain` are used, the target object must have at
- * least all of the passed-in keys but may have more keys not listed.
- *
- * When both `all` and `have` are used, the target object must both contain
- * all of the passed-in keys AND the number of keys in the target object must
- * match the number of keys passed in (in other words, a target object must
- * have all and only all of the passed-in keys).
- *
- * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo', 'baz');
- * expect({ foo: 1, bar: 2 }).to.have.any.keys('foo');
- * expect({ foo: 1, bar: 2 }).to.contain.any.keys('bar', 'baz');
- * expect({ foo: 1, bar: 2 }).to.contain.any.keys(['foo']);
- * expect({ foo: 1, bar: 2 }).to.contain.any.keys({'foo': 6});
- * expect({ foo: 1, bar: 2 }).to.have.all.keys(['bar', 'foo']);
- * expect({ foo: 1, bar: 2 }).to.have.all.keys({'bar': 6, 'foo': 7});
- * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys(['bar', 'foo']);
- * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.all.keys({'bar': 6});
- *
- *
- * @name keys
- * @alias key
- * @param {String...|Array|Object} keys
- * @api public
- */
-
- function assertKeys (keys) {
- var obj = flag(this, 'object')
- , str
- , ok = true
- , mixedArgsMsg = 'keys must be given single argument of Array|Object|String, or multiple String arguments';
-
- switch (_.type(keys)) {
- case "array":
- if (arguments.length > 1) throw (new Error(mixedArgsMsg));
- break;
- case "object":
- if (arguments.length > 1) throw (new Error(mixedArgsMsg));
- keys = Object.keys(keys);
- break;
- default:
- keys = Array.prototype.slice.call(arguments);
- }
-
- if (!keys.length) throw new Error('keys required');
-
- var actual = Object.keys(obj)
- , expected = keys
- , len = keys.length
- , any = flag(this, 'any')
- , all = flag(this, 'all');
-
- if (!any && !all) {
- all = true;
- }
-
- // Has any
- if (any) {
- var intersection = expected.filter(function(key) {
- return ~actual.indexOf(key);
- });
- ok = intersection.length > 0;
- }
-
- // Has all
- if (all) {
- ok = keys.every(function(key){
- return ~actual.indexOf(key);
- });
- if (!flag(this, 'negate') && !flag(this, 'contains')) {
- ok = ok && keys.length == actual.length;
- }
- }
-
- // Key string
- if (len > 1) {
- keys = keys.map(function(key){
- return _.inspect(key);
- });
- var last = keys.pop();
- if (all) {
- str = keys.join(', ') + ', and ' + last;
- }
- if (any) {
- str = keys.join(', ') + ', or ' + last;
- }
- } else {
- str = _.inspect(keys[0]);
- }
-
- // Form
- str = (len > 1 ? 'keys ' : 'key ') + str;
-
- // Have / include
- str = (flag(this, 'contains') ? 'contain ' : 'have ') + str;
-
- // Assertion
- this.assert(
- ok
- , 'expected #{this} to ' + str
- , 'expected #{this} to not ' + str
- , expected.slice(0).sort()
- , actual.sort()
- , true
- );
- }
-
- Assertion.addMethod('keys', assertKeys);
- Assertion.addMethod('key', assertKeys);
-
- /**
- * ### .throw(constructor)
- *
- * Asserts that the function target will throw a specific error, or specific type of error
- * (as determined using `instanceof`), optionally with a RegExp or string inclusion test
- * for the error's message.
- *
- * var err = new ReferenceError('This is a bad function.');
- * var fn = function () { throw err; }
- * expect(fn).to.throw(ReferenceError);
- * expect(fn).to.throw(Error);
- * expect(fn).to.throw(/bad function/);
- * expect(fn).to.not.throw('good function');
- * expect(fn).to.throw(ReferenceError, /bad function/);
- * expect(fn).to.throw(err);
- * expect(fn).to.not.throw(new RangeError('Out of range.'));
- *
- * Please note that when a throw expectation is negated, it will check each
- * parameter independently, starting with error constructor type. The appropriate way
- * to check for the existence of a type of error but for a message that does not match
- * is to use `and`.
- *
- * expect(fn).to.throw(ReferenceError)
- * .and.not.throw(/good function/);
- *
- * @name throw
- * @alias throws
- * @alias Throw
- * @param {ErrorConstructor} constructor
- * @param {String|RegExp} expected error message
- * @param {String} message _optional_
- * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
- * @returns error for chaining (null if no error)
- * @api public
- */
-
- function assertThrows (constructor, errMsg, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- new Assertion(obj, msg).is.a('function');
-
- var thrown = false
- , desiredError = null
- , name = null
- , thrownError = null;
-
- if (arguments.length === 0) {
- errMsg = null;
- constructor = null;
- } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) {
- errMsg = constructor;
- constructor = null;
- } else if (constructor && constructor instanceof Error) {
- desiredError = constructor;
- constructor = null;
- errMsg = null;
- } else if (typeof constructor === 'function') {
- name = constructor.prototype.name || constructor.name;
- if (name === 'Error' && constructor !== Error) {
- name = (new constructor()).name;
- }
- } else {
- constructor = null;
- }
-
- try {
- obj();
- } catch (err) {
- // first, check desired error
- if (desiredError) {
- this.assert(
- err === desiredError
- , 'expected #{this} to throw #{exp} but #{act} was thrown'
- , 'expected #{this} to not throw #{exp}'
- , (desiredError instanceof Error ? desiredError.toString() : desiredError)
- , (err instanceof Error ? err.toString() : err)
- );
-
- flag(this, 'object', err);
- return this;
- }
-
- // next, check constructor
- if (constructor) {
- this.assert(
- err instanceof constructor
- , 'expected #{this} to throw #{exp} but #{act} was thrown'
- , 'expected #{this} to not throw #{exp} but #{act} was thrown'
- , name
- , (err instanceof Error ? err.toString() : err)
- );
-
- if (!errMsg) {
- flag(this, 'object', err);
- return this;
- }
- }
-
- // next, check message
- var message = 'error' === _.type(err) && "message" in err
- ? err.message
- : '' + err;
-
- if ((message != null) && errMsg && errMsg instanceof RegExp) {
- this.assert(
- errMsg.exec(message)
- , 'expected #{this} to throw error matching #{exp} but got #{act}'
- , 'expected #{this} to throw error not matching #{exp}'
- , errMsg
- , message
- );
-
- flag(this, 'object', err);
- return this;
- } else if ((message != null) && errMsg && 'string' === typeof errMsg) {
- this.assert(
- ~message.indexOf(errMsg)
- , 'expected #{this} to throw error including #{exp} but got #{act}'
- , 'expected #{this} to throw error not including #{act}'
- , errMsg
- , message
- );
-
- flag(this, 'object', err);
- return this;
- } else {
- thrown = true;
- thrownError = err;
- }
- }
-
- var actuallyGot = '';
- var expectedThrown = 'an error';
- if (name !== null) {
- expectedThrown = name;
- } else if (desiredError) {
- expectedThrown = '#{exp}'; //_.inspect(desiredError)
- }
-
- if (thrown) {
- actuallyGot = ' but #{act} was thrown'
- }
-
- this.assert(
- thrown === true
- , 'expected #{this} to throw ' + expectedThrown + actuallyGot
- , 'expected #{this} to not throw ' + expectedThrown + actuallyGot
- , (desiredError instanceof Error ? desiredError.toString() : desiredError)
- , (thrownError instanceof Error ? thrownError.toString() : thrownError)
- );
-
- flag(this, 'object', thrownError);
- }
-
- Assertion.addMethod('throw', assertThrows);
- Assertion.addMethod('throws', assertThrows);
- Assertion.addMethod('Throw', assertThrows);
-
- /**
- * ### .respondTo(method)
- *
- * Asserts that the object or class target will respond to a method.
- *
- * Klass.prototype.bar = function(){};
- * expect(Klass).to.respondTo('bar');
- * expect(obj).to.respondTo('bar');
- *
- * To check if a constructor will respond to a static function,
- * set the `itself` flag.
- *
- * Klass.baz = function(){};
- * expect(Klass).itself.to.respondTo('baz');
- *
- * @name respondTo
- * @param {String} method
- * @param {String} message _optional_
- * @api public
- */
-
- Assertion.addMethod('respondTo', function (method, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object')
- , itself = flag(this, 'itself')
- , context = ('function' === _.type(obj) && !itself)
- ? obj.prototype[method]
- : obj[method];
-
- this.assert(
- 'function' === typeof context
- , 'expected #{this} to respond to ' + _.inspect(method)
- , 'expected #{this} to not respond to ' + _.inspect(method)
- );
- });
-
- /**
- * ### .itself
- *
- * Sets the `itself` flag, later used by the `respondTo` assertion.
- *
- * function Foo() {}
- * Foo.bar = function() {}
- * Foo.prototype.baz = function() {}
- *
- * expect(Foo).itself.to.respondTo('bar');
- * expect(Foo).itself.not.to.respondTo('baz');
- *
- * @name itself
- * @api public
- */
-
- Assertion.addProperty('itself', function () {
- flag(this, 'itself', true);
- });
-
- /**
- * ### .satisfy(method)
- *
- * Asserts that the target passes a given truth test.
- *
- * expect(1).to.satisfy(function(num) { return num > 0; });
- *
- * @name satisfy
- * @param {Function} matcher
- * @param {String} message _optional_
- * @api public
- */
-
- Assertion.addMethod('satisfy', function (matcher, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
- var result = matcher(obj);
- this.assert(
- result
- , 'expected #{this} to satisfy ' + _.objDisplay(matcher)
- , 'expected #{this} to not satisfy' + _.objDisplay(matcher)
- , this.negate ? false : true
- , result
- );
- });
-
- /**
- * ### .closeTo(expected, delta)
- *
- * Asserts that the target is equal `expected`, to within a +/- `delta` range.
- *
- * expect(1.5).to.be.closeTo(1, 0.5);
- *
- * @name closeTo
- * @param {Number} expected
- * @param {Number} delta
- * @param {String} message _optional_
- * @api public
- */
-
- Assertion.addMethod('closeTo', function (expected, delta, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
-
- new Assertion(obj, msg).is.a('number');
- if (_.type(expected) !== 'number' || _.type(delta) !== 'number') {
- throw new Error('the arguments to closeTo must be numbers');
- }
-
- this.assert(
- Math.abs(obj - expected) <= delta
- , 'expected #{this} to be close to ' + expected + ' +/- ' + delta
- , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta
- );
- });
-
- function isSubsetOf(subset, superset, cmp) {
- return subset.every(function(elem) {
- if (!cmp) return superset.indexOf(elem) !== -1;
-
- return superset.some(function(elem2) {
- return cmp(elem, elem2);
- });
- })
- }
-
- /**
- * ### .members(set)
- *
- * Asserts that the target is a superset of `set`,
- * or that the target and `set` have the same strictly-equal (===) members.
- * Alternately, if the `deep` flag is set, set members are compared for deep
- * equality.
- *
- * expect([1, 2, 3]).to.include.members([3, 2]);
- * expect([1, 2, 3]).to.not.include.members([3, 2, 8]);
- *
- * expect([4, 2]).to.have.members([2, 4]);
- * expect([5, 2]).to.not.have.members([5, 2, 1]);
- *
- * expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]);
- *
- * @name members
- * @param {Array} set
- * @param {String} message _optional_
- * @api public
- */
-
- Assertion.addMethod('members', function (subset, msg) {
- if (msg) flag(this, 'message', msg);
- var obj = flag(this, 'object');
-
- new Assertion(obj).to.be.an('array');
- new Assertion(subset).to.be.an('array');
-
- var cmp = flag(this, 'deep') ? _.eql : undefined;
-
- if (flag(this, 'contains')) {
- return this.assert(
- isSubsetOf(subset, obj, cmp)
- , 'expected #{this} to be a superset of #{act}'
- , 'expected #{this} to not be a superset of #{act}'
- , obj
- , subset
- );
- }
-
- this.assert(
- isSubsetOf(obj, subset, cmp) && isSubsetOf(subset, obj, cmp)
- , 'expected #{this} to have the same members as #{act}'
- , 'expected #{this} to not have the same members as #{act}'
- , obj
- , subset
- );
- });
-
- /**
- * ### .change(function)
- *
- * Asserts that a function changes an object property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val += 3 };
- * var noChangeFn = function() { return 'foo' + 'bar'; }
- * expect(fn).to.change(obj, 'val');
- * expect(noChangFn).to.not.change(obj, 'val')
- *
- * @name change
- * @alias changes
- * @alias Change
- * @param {String} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- function assertChanges (object, prop, msg) {
- if (msg) flag(this, 'message', msg);
- var fn = flag(this, 'object');
- new Assertion(object, msg).to.have.property(prop);
- new Assertion(fn).is.a('function');
-
- var initial = object[prop];
- fn();
-
- this.assert(
- initial !== object[prop]
- , 'expected .' + prop + ' to change'
- , 'expected .' + prop + ' to not change'
- );
- }
-
- Assertion.addChainableMethod('change', assertChanges);
- Assertion.addChainableMethod('changes', assertChanges);
-
- /**
- * ### .increase(function)
- *
- * Asserts that a function increases an object property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val = 15 };
- * expect(fn).to.increase(obj, 'val');
- *
- * @name increase
- * @alias increases
- * @alias Increase
- * @param {String} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- function assertIncreases (object, prop, msg) {
- if (msg) flag(this, 'message', msg);
- var fn = flag(this, 'object');
- new Assertion(object, msg).to.have.property(prop);
- new Assertion(fn).is.a('function');
-
- var initial = object[prop];
- fn();
-
- this.assert(
- object[prop] - initial > 0
- , 'expected .' + prop + ' to increase'
- , 'expected .' + prop + ' to not increase'
- );
- }
-
- Assertion.addChainableMethod('increase', assertIncreases);
- Assertion.addChainableMethod('increases', assertIncreases);
-
- /**
- * ### .decrease(function)
- *
- * Asserts that a function decreases an object property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val = 5 };
- * expect(fn).to.decrease(obj, 'val');
- *
- * @name decrease
- * @alias decreases
- * @alias Decrease
- * @param {String} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- function assertDecreases (object, prop, msg) {
- if (msg) flag(this, 'message', msg);
- var fn = flag(this, 'object');
- new Assertion(object, msg).to.have.property(prop);
- new Assertion(fn).is.a('function');
-
- var initial = object[prop];
- fn();
-
- this.assert(
- object[prop] - initial < 0
- , 'expected .' + prop + ' to decrease'
- , 'expected .' + prop + ' to not decrease'
- );
- }
-
- Assertion.addChainableMethod('decrease', assertDecreases);
- Assertion.addChainableMethod('decreases', assertDecreases);
-
-};
-
-},{}],5:[function(require,module,exports){
-/*!
- * chai
- * Copyright(c) 2011-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-
-module.exports = function (chai, util) {
-
- /*!
- * Chai dependencies.
- */
-
- var Assertion = chai.Assertion
- , flag = util.flag;
-
- /*!
- * Module export.
- */
-
- /**
- * ### assert(expression, message)
- *
- * Write your own test expressions.
- *
- * assert('foo' !== 'bar', 'foo is not bar');
- * assert(Array.isArray([]), 'empty arrays are arrays');
- *
- * @param {Mixed} expression to test for truthiness
- * @param {String} message to display on error
- * @name assert
- * @api public
- */
-
- var assert = chai.assert = function (express, errmsg) {
- var test = new Assertion(null, null, chai.assert);
- test.assert(
- express
- , errmsg
- , '[ negation message unavailable ]'
- );
- };
-
- /**
- * ### .fail(actual, expected, [message], [operator])
- *
- * Throw a failure. Node.js `assert` module-compatible.
- *
- * @name fail
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @param {String} operator
- * @api public
- */
-
- assert.fail = function (actual, expected, message, operator) {
- message = message || 'assert.fail()';
- throw new chai.AssertionError(message, {
- actual: actual
- , expected: expected
- , operator: operator
- }, assert.fail);
- };
-
- /**
- * ### .ok(object, [message])
- *
- * Asserts that `object` is truthy.
- *
- * assert.ok('everything', 'everything is ok');
- * assert.ok(false, 'this will fail');
- *
- * @name ok
- * @param {Mixed} object to test
- * @param {String} message
- * @api public
- */
-
- assert.ok = function (val, msg) {
- new Assertion(val, msg).is.ok;
- };
-
- /**
- * ### .notOk(object, [message])
- *
- * Asserts that `object` is falsy.
- *
- * assert.notOk('everything', 'this will fail');
- * assert.notOk(false, 'this will pass');
- *
- * @name notOk
- * @param {Mixed} object to test
- * @param {String} message
- * @api public
- */
-
- assert.notOk = function (val, msg) {
- new Assertion(val, msg).is.not.ok;
- };
-
- /**
- * ### .equal(actual, expected, [message])
- *
- * Asserts non-strict equality (`==`) of `actual` and `expected`.
- *
- * assert.equal(3, '3', '== coerces values to strings');
- *
- * @name equal
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.equal = function (act, exp, msg) {
- var test = new Assertion(act, msg, assert.equal);
-
- test.assert(
- exp == flag(test, 'object')
- , 'expected #{this} to equal #{exp}'
- , 'expected #{this} to not equal #{act}'
- , exp
- , act
- );
- };
-
- /**
- * ### .notEqual(actual, expected, [message])
- *
- * Asserts non-strict inequality (`!=`) of `actual` and `expected`.
- *
- * assert.notEqual(3, 4, 'these numbers are not equal');
- *
- * @name notEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.notEqual = function (act, exp, msg) {
- var test = new Assertion(act, msg, assert.notEqual);
-
- test.assert(
- exp != flag(test, 'object')
- , 'expected #{this} to not equal #{exp}'
- , 'expected #{this} to equal #{act}'
- , exp
- , act
- );
- };
-
- /**
- * ### .strictEqual(actual, expected, [message])
- *
- * Asserts strict equality (`===`) of `actual` and `expected`.
- *
- * assert.strictEqual(true, true, 'these booleans are strictly equal');
- *
- * @name strictEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.strictEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.equal(exp);
- };
-
- /**
- * ### .notStrictEqual(actual, expected, [message])
- *
- * Asserts strict inequality (`!==`) of `actual` and `expected`.
- *
- * assert.notStrictEqual(3, '3', 'no coercion for strict equality');
- *
- * @name notStrictEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.notStrictEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.not.equal(exp);
- };
-
- /**
- * ### .deepEqual(actual, expected, [message])
- *
- * Asserts that `actual` is deeply equal to `expected`.
- *
- * assert.deepEqual({ tea: 'green' }, { tea: 'green' });
- *
- * @name deepEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.deepEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.eql(exp);
- };
-
- /**
- * ### .notDeepEqual(actual, expected, [message])
- *
- * Assert that `actual` is not deeply equal to `expected`.
- *
- * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' });
- *
- * @name notDeepEqual
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @api public
- */
-
- assert.notDeepEqual = function (act, exp, msg) {
- new Assertion(act, msg).to.not.eql(exp);
- };
-
- /**
- * ### .isTrue(value, [message])
- *
- * Asserts that `value` is true.
- *
- * var teaServed = true;
- * assert.isTrue(teaServed, 'the tea has been served');
- *
- * @name isTrue
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isAbove = function (val, abv, msg) {
- new Assertion(val, msg).to.be.above(abv);
- };
-
- /**
- * ### .isAbove(valueToCheck, valueToBeAbove, [message])
- *
- * Asserts `valueToCheck` is strictly greater than (>) `valueToBeAbove`
- *
- * assert.isAbove(5, 2, '5 is strictly greater than 2');
- *
- * @name isAbove
- * @param {Mixed} valueToCheck
- * @param {Mixed} valueToBeAbove
- * @param {String} message
- * @api public
- */
-
- assert.isBelow = function (val, blw, msg) {
- new Assertion(val, msg).to.be.below(blw);
- };
-
- /**
- * ### .isBelow(valueToCheck, valueToBeBelow, [message])
- *
- * Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`
- *
- * assert.isBelow(3, 6, '3 is strictly less than 6');
- *
- * @name isBelow
- * @param {Mixed} valueToCheck
- * @param {Mixed} valueToBeBelow
- * @param {String} message
- * @api public
- */
-
- assert.isTrue = function (val, msg) {
- new Assertion(val, msg).is['true'];
- };
-
- /**
- * ### .isFalse(value, [message])
- *
- * Asserts that `value` is false.
- *
- * var teaServed = false;
- * assert.isFalse(teaServed, 'no tea yet? hmm...');
- *
- * @name isFalse
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isFalse = function (val, msg) {
- new Assertion(val, msg).is['false'];
- };
-
- /**
- * ### .isNull(value, [message])
- *
- * Asserts that `value` is null.
- *
- * assert.isNull(err, 'there was no error');
- *
- * @name isNull
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNull = function (val, msg) {
- new Assertion(val, msg).to.equal(null);
- };
-
- /**
- * ### .isNotNull(value, [message])
- *
- * Asserts that `value` is not null.
- *
- * var tea = 'tasty chai';
- * assert.isNotNull(tea, 'great, time for tea!');
- *
- * @name isNotNull
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotNull = function (val, msg) {
- new Assertion(val, msg).to.not.equal(null);
- };
-
- /**
- * ### .isUndefined(value, [message])
- *
- * Asserts that `value` is `undefined`.
- *
- * var tea;
- * assert.isUndefined(tea, 'no tea defined');
- *
- * @name isUndefined
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isUndefined = function (val, msg) {
- new Assertion(val, msg).to.equal(undefined);
- };
-
- /**
- * ### .isDefined(value, [message])
- *
- * Asserts that `value` is not `undefined`.
- *
- * var tea = 'cup of chai';
- * assert.isDefined(tea, 'tea has been defined');
- *
- * @name isDefined
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isDefined = function (val, msg) {
- new Assertion(val, msg).to.not.equal(undefined);
- };
-
- /**
- * ### .isFunction(value, [message])
- *
- * Asserts that `value` is a function.
- *
- * function serveTea() { return 'cup of tea'; };
- * assert.isFunction(serveTea, 'great, we can have tea now');
- *
- * @name isFunction
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isFunction = function (val, msg) {
- new Assertion(val, msg).to.be.a('function');
- };
-
- /**
- * ### .isNotFunction(value, [message])
- *
- * Asserts that `value` is _not_ a function.
- *
- * var serveTea = [ 'heat', 'pour', 'sip' ];
- * assert.isNotFunction(serveTea, 'great, we have listed the steps');
- *
- * @name isNotFunction
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotFunction = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('function');
- };
-
- /**
- * ### .isObject(value, [message])
- *
- * Asserts that `value` is an object (as revealed by
- * `Object.prototype.toString`).
- *
- * var selection = { name: 'Chai', serve: 'with spices' };
- * assert.isObject(selection, 'tea selection is an object');
- *
- * @name isObject
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isObject = function (val, msg) {
- new Assertion(val, msg).to.be.a('object');
- };
-
- /**
- * ### .isNotObject(value, [message])
- *
- * Asserts that `value` is _not_ an object.
- *
- * var selection = 'chai'
- * assert.isNotObject(selection, 'tea selection is not an object');
- * assert.isNotObject(null, 'null is not an object');
- *
- * @name isNotObject
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotObject = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('object');
- };
-
- /**
- * ### .isArray(value, [message])
- *
- * Asserts that `value` is an array.
- *
- * var menu = [ 'green', 'chai', 'oolong' ];
- * assert.isArray(menu, 'what kind of tea do we want?');
- *
- * @name isArray
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isArray = function (val, msg) {
- new Assertion(val, msg).to.be.an('array');
- };
-
- /**
- * ### .isNotArray(value, [message])
- *
- * Asserts that `value` is _not_ an array.
- *
- * var menu = 'green|chai|oolong';
- * assert.isNotArray(menu, 'what kind of tea do we want?');
- *
- * @name isNotArray
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotArray = function (val, msg) {
- new Assertion(val, msg).to.not.be.an('array');
- };
-
- /**
- * ### .isString(value, [message])
- *
- * Asserts that `value` is a string.
- *
- * var teaOrder = 'chai';
- * assert.isString(teaOrder, 'order placed');
- *
- * @name isString
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isString = function (val, msg) {
- new Assertion(val, msg).to.be.a('string');
- };
-
- /**
- * ### .isNotString(value, [message])
- *
- * Asserts that `value` is _not_ a string.
- *
- * var teaOrder = 4;
- * assert.isNotString(teaOrder, 'order placed');
- *
- * @name isNotString
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotString = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('string');
- };
-
- /**
- * ### .isNumber(value, [message])
- *
- * Asserts that `value` is a number.
- *
- * var cups = 2;
- * assert.isNumber(cups, 'how many cups');
- *
- * @name isNumber
- * @param {Number} value
- * @param {String} message
- * @api public
- */
-
- assert.isNumber = function (val, msg) {
- new Assertion(val, msg).to.be.a('number');
- };
-
- /**
- * ### .isNotNumber(value, [message])
- *
- * Asserts that `value` is _not_ a number.
- *
- * var cups = '2 cups please';
- * assert.isNotNumber(cups, 'how many cups');
- *
- * @name isNotNumber
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotNumber = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('number');
- };
-
- /**
- * ### .isBoolean(value, [message])
- *
- * Asserts that `value` is a boolean.
- *
- * var teaReady = true
- * , teaServed = false;
- *
- * assert.isBoolean(teaReady, 'is the tea ready');
- * assert.isBoolean(teaServed, 'has tea been served');
- *
- * @name isBoolean
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isBoolean = function (val, msg) {
- new Assertion(val, msg).to.be.a('boolean');
- };
-
- /**
- * ### .isNotBoolean(value, [message])
- *
- * Asserts that `value` is _not_ a boolean.
- *
- * var teaReady = 'yep'
- * , teaServed = 'nope';
- *
- * assert.isNotBoolean(teaReady, 'is the tea ready');
- * assert.isNotBoolean(teaServed, 'has tea been served');
- *
- * @name isNotBoolean
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.isNotBoolean = function (val, msg) {
- new Assertion(val, msg).to.not.be.a('boolean');
- };
-
- /**
- * ### .typeOf(value, name, [message])
- *
- * Asserts that `value`'s type is `name`, as determined by
- * `Object.prototype.toString`.
- *
- * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object');
- * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array');
- * assert.typeOf('tea', 'string', 'we have a string');
- * assert.typeOf(/tea/, 'regexp', 'we have a regular expression');
- * assert.typeOf(null, 'null', 'we have a null');
- * assert.typeOf(undefined, 'undefined', 'we have an undefined');
- *
- * @name typeOf
- * @param {Mixed} value
- * @param {String} name
- * @param {String} message
- * @api public
- */
-
- assert.typeOf = function (val, type, msg) {
- new Assertion(val, msg).to.be.a(type);
- };
-
- /**
- * ### .notTypeOf(value, name, [message])
- *
- * Asserts that `value`'s type is _not_ `name`, as determined by
- * `Object.prototype.toString`.
- *
- * assert.notTypeOf('tea', 'number', 'strings are not numbers');
- *
- * @name notTypeOf
- * @param {Mixed} value
- * @param {String} typeof name
- * @param {String} message
- * @api public
- */
-
- assert.notTypeOf = function (val, type, msg) {
- new Assertion(val, msg).to.not.be.a(type);
- };
-
- /**
- * ### .instanceOf(object, constructor, [message])
- *
- * Asserts that `value` is an instance of `constructor`.
- *
- * var Tea = function (name) { this.name = name; }
- * , chai = new Tea('chai');
- *
- * assert.instanceOf(chai, Tea, 'chai is an instance of tea');
- *
- * @name instanceOf
- * @param {Object} object
- * @param {Constructor} constructor
- * @param {String} message
- * @api public
- */
-
- assert.instanceOf = function (val, type, msg) {
- new Assertion(val, msg).to.be.instanceOf(type);
- };
-
- /**
- * ### .notInstanceOf(object, constructor, [message])
- *
- * Asserts `value` is not an instance of `constructor`.
- *
- * var Tea = function (name) { this.name = name; }
- * , chai = new String('chai');
- *
- * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea');
- *
- * @name notInstanceOf
- * @param {Object} object
- * @param {Constructor} constructor
- * @param {String} message
- * @api public
- */
-
- assert.notInstanceOf = function (val, type, msg) {
- new Assertion(val, msg).to.not.be.instanceOf(type);
- };
-
- /**
- * ### .include(haystack, needle, [message])
- *
- * Asserts that `haystack` includes `needle`. Works
- * for strings and arrays.
- *
- * assert.include('foobar', 'bar', 'foobar contains string "bar"');
- * assert.include([ 1, 2, 3 ], 3, 'array contains value');
- *
- * @name include
- * @param {Array|String} haystack
- * @param {Mixed} needle
- * @param {String} message
- * @api public
- */
-
- assert.include = function (exp, inc, msg) {
- new Assertion(exp, msg, assert.include).include(inc);
- };
-
- /**
- * ### .notInclude(haystack, needle, [message])
- *
- * Asserts that `haystack` does not include `needle`. Works
- * for strings and arrays.
- *
- * assert.notInclude('foobar', 'baz', 'string not include substring');
- * assert.notInclude([ 1, 2, 3 ], 4, 'array not include contain value');
- *
- * @name notInclude
- * @param {Array|String} haystack
- * @param {Mixed} needle
- * @param {String} message
- * @api public
- */
-
- assert.notInclude = function (exp, inc, msg) {
- new Assertion(exp, msg, assert.notInclude).not.include(inc);
- };
-
- /**
- * ### .match(value, regexp, [message])
- *
- * Asserts that `value` matches the regular expression `regexp`.
- *
- * assert.match('foobar', /^foo/, 'regexp matches');
- *
- * @name match
- * @param {Mixed} value
- * @param {RegExp} regexp
- * @param {String} message
- * @api public
- */
-
- assert.match = function (exp, re, msg) {
- new Assertion(exp, msg).to.match(re);
- };
-
- /**
- * ### .notMatch(value, regexp, [message])
- *
- * Asserts that `value` does not match the regular expression `regexp`.
- *
- * assert.notMatch('foobar', /^foo/, 'regexp does not match');
- *
- * @name notMatch
- * @param {Mixed} value
- * @param {RegExp} regexp
- * @param {String} message
- * @api public
- */
-
- assert.notMatch = function (exp, re, msg) {
- new Assertion(exp, msg).to.not.match(re);
- };
-
- /**
- * ### .property(object, property, [message])
- *
- * Asserts that `object` has a property named by `property`.
- *
- * assert.property({ tea: { green: 'matcha' }}, 'tea');
- *
- * @name property
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.property = function (obj, prop, msg) {
- new Assertion(obj, msg).to.have.property(prop);
- };
-
- /**
- * ### .notProperty(object, property, [message])
- *
- * Asserts that `object` does _not_ have a property named by `property`.
- *
- * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee');
- *
- * @name notProperty
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.notProperty = function (obj, prop, msg) {
- new Assertion(obj, msg).to.not.have.property(prop);
- };
-
- /**
- * ### .deepProperty(object, property, [message])
- *
- * Asserts that `object` has a property named by `property`, which can be a
- * string using dot- and bracket-notation for deep reference.
- *
- * assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green');
- *
- * @name deepProperty
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.deepProperty = function (obj, prop, msg) {
- new Assertion(obj, msg).to.have.deep.property(prop);
- };
-
- /**
- * ### .notDeepProperty(object, property, [message])
- *
- * Asserts that `object` does _not_ have a property named by `property`, which
- * can be a string using dot- and bracket-notation for deep reference.
- *
- * assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong');
- *
- * @name notDeepProperty
- * @param {Object} object
- * @param {String} property
- * @param {String} message
- * @api public
- */
-
- assert.notDeepProperty = function (obj, prop, msg) {
- new Assertion(obj, msg).to.not.have.deep.property(prop);
- };
-
- /**
- * ### .propertyVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property` with value given
- * by `value`.
- *
- * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good');
- *
- * @name propertyVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.propertyVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.have.property(prop, val);
- };
-
- /**
- * ### .propertyNotVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property`, but with a value
- * different from that given by `value`.
- *
- * assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad');
- *
- * @name propertyNotVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.propertyNotVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.not.have.property(prop, val);
- };
-
- /**
- * ### .deepPropertyVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property` with value given
- * by `value`. `property` can use dot- and bracket-notation for deep
- * reference.
- *
- * assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha');
- *
- * @name deepPropertyVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.deepPropertyVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.have.deep.property(prop, val);
- };
-
- /**
- * ### .deepPropertyNotVal(object, property, value, [message])
- *
- * Asserts that `object` has a property named by `property`, but with a value
- * different from that given by `value`. `property` can use dot- and
- * bracket-notation for deep reference.
- *
- * assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha');
- *
- * @name deepPropertyNotVal
- * @param {Object} object
- * @param {String} property
- * @param {Mixed} value
- * @param {String} message
- * @api public
- */
-
- assert.deepPropertyNotVal = function (obj, prop, val, msg) {
- new Assertion(obj, msg).to.not.have.deep.property(prop, val);
- };
-
- /**
- * ### .lengthOf(object, length, [message])
- *
- * Asserts that `object` has a `length` property with the expected value.
- *
- * assert.lengthOf([1,2,3], 3, 'array has length of 3');
- * assert.lengthOf('foobar', 5, 'string has length of 6');
- *
- * @name lengthOf
- * @param {Mixed} object
- * @param {Number} length
- * @param {String} message
- * @api public
- */
-
- assert.lengthOf = function (exp, len, msg) {
- new Assertion(exp, msg).to.have.length(len);
- };
-
- /**
- * ### .throws(function, [constructor/string/regexp], [string/regexp], [message])
- *
- * Asserts that `function` will throw an error that is an instance of
- * `constructor`, or alternately that it will throw an error with message
- * matching `regexp`.
- *
- * assert.throw(fn, 'function throws a reference error');
- * assert.throw(fn, /function throws a reference error/);
- * assert.throw(fn, ReferenceError);
- * assert.throw(fn, ReferenceError, 'function throws a reference error');
- * assert.throw(fn, ReferenceError, /function throws a reference error/);
- *
- * @name throws
- * @alias throw
- * @alias Throw
- * @param {Function} function
- * @param {ErrorConstructor} constructor
- * @param {RegExp} regexp
- * @param {String} message
- * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
- * @api public
- */
-
- assert.Throw = function (fn, errt, errs, msg) {
- if ('string' === typeof errt || errt instanceof RegExp) {
- errs = errt;
- errt = null;
- }
-
- var assertErr = new Assertion(fn, msg).to.Throw(errt, errs);
- return flag(assertErr, 'object');
- };
-
- /**
- * ### .doesNotThrow(function, [constructor/regexp], [message])
- *
- * Asserts that `function` will _not_ throw an error that is an instance of
- * `constructor`, or alternately that it will not throw an error with message
- * matching `regexp`.
- *
- * assert.doesNotThrow(fn, Error, 'function does not throw');
- *
- * @name doesNotThrow
- * @param {Function} function
- * @param {ErrorConstructor} constructor
- * @param {RegExp} regexp
- * @param {String} message
- * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
- * @api public
- */
-
- assert.doesNotThrow = function (fn, type, msg) {
- if ('string' === typeof type) {
- msg = type;
- type = null;
- }
-
- new Assertion(fn, msg).to.not.Throw(type);
- };
-
- /**
- * ### .operator(val1, operator, val2, [message])
- *
- * Compares two values using `operator`.
- *
- * assert.operator(1, '<', 2, 'everything is ok');
- * assert.operator(1, '>', 2, 'this will fail');
- *
- * @name operator
- * @param {Mixed} val1
- * @param {String} operator
- * @param {Mixed} val2
- * @param {String} message
- * @api public
- */
-
- assert.operator = function (val, operator, val2, msg) {
- var ok;
- switch(operator) {
- case '==':
- ok = val == val2;
- break;
- case '===':
- ok = val === val2;
- break;
- case '>':
- ok = val > val2;
- break;
- case '>=':
- ok = val >= val2;
- break;
- case '<':
- ok = val < val2;
- break;
- case '<=':
- ok = val <= val2;
- break;
- case '!=':
- ok = val != val2;
- break;
- case '!==':
- ok = val !== val2;
- break;
- default:
- throw new Error('Invalid operator "' + operator + '"');
- }
- var test = new Assertion(ok, msg);
- test.assert(
- true === flag(test, 'object')
- , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2)
- , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) );
- };
-
- /**
- * ### .closeTo(actual, expected, delta, [message])
- *
- * Asserts that the target is equal `expected`, to within a +/- `delta` range.
- *
- * assert.closeTo(1.5, 1, 0.5, 'numbers are close');
- *
- * @name closeTo
- * @param {Number} actual
- * @param {Number} expected
- * @param {Number} delta
- * @param {String} message
- * @api public
- */
-
- assert.closeTo = function (act, exp, delta, msg) {
- new Assertion(act, msg).to.be.closeTo(exp, delta);
- };
-
- /**
- * ### .sameMembers(set1, set2, [message])
- *
- * Asserts that `set1` and `set2` have the same members.
- * Order is not taken into account.
- *
- * assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members');
- *
- * @name sameMembers
- * @param {Array} set1
- * @param {Array} set2
- * @param {String} message
- * @api public
- */
-
- assert.sameMembers = function (set1, set2, msg) {
- new Assertion(set1, msg).to.have.same.members(set2);
- }
-
- /**
- * ### .sameDeepMembers(set1, set2, [message])
- *
- * Asserts that `set1` and `set2` have the same members - using a deep equality checking.
- * Order is not taken into account.
- *
- * assert.sameDeepMembers([ {b: 3}, {a: 2}, {c: 5} ], [ {c: 5}, {b: 3}, {a: 2} ], 'same deep members');
- *
- * @name sameDeepMembers
- * @param {Array} set1
- * @param {Array} set2
- * @param {String} message
- * @api public
- */
-
- assert.sameDeepMembers = function (set1, set2, msg) {
- new Assertion(set1, msg).to.have.same.deep.members(set2);
- }
-
- /**
- * ### .includeMembers(superset, subset, [message])
- *
- * Asserts that `subset` is included in `superset`.
- * Order is not taken into account.
- *
- * assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members');
- *
- * @name includeMembers
- * @param {Array} superset
- * @param {Array} subset
- * @param {String} message
- * @api public
- */
-
- assert.includeMembers = function (superset, subset, msg) {
- new Assertion(superset, msg).to.include.members(subset);
- }
-
- /**
- * ### .changes(function, object, property)
- *
- * Asserts that a function changes the value of a property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val = 22 };
- * assert.changes(fn, obj, 'val');
- *
- * @name changes
- * @param {Function} modifier function
- * @param {Object} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- assert.changes = function (fn, obj, prop) {
- new Assertion(fn).to.change(obj, prop);
- }
-
- /**
- * ### .doesNotChange(function, object, property)
- *
- * Asserts that a function does not changes the value of a property
- *
- * var obj = { val: 10 };
- * var fn = function() { console.log('foo'); };
- * assert.doesNotChange(fn, obj, 'val');
- *
- * @name doesNotChange
- * @param {Function} modifier function
- * @param {Object} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- assert.doesNotChange = function (fn, obj, prop) {
- new Assertion(fn).to.not.change(obj, prop);
- }
-
- /**
- * ### .increases(function, object, property)
- *
- * Asserts that a function increases an object property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val = 13 };
- * assert.increases(fn, obj, 'val');
- *
- * @name increases
- * @param {Function} modifier function
- * @param {Object} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- assert.increases = function (fn, obj, prop) {
- new Assertion(fn).to.increase(obj, prop);
- }
-
- /**
- * ### .doesNotIncrease(function, object, property)
- *
- * Asserts that a function does not increase object property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val = 8 };
- * assert.doesNotIncrease(fn, obj, 'val');
- *
- * @name doesNotIncrease
- * @param {Function} modifier function
- * @param {Object} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- assert.doesNotIncrease = function (fn, obj, prop) {
- new Assertion(fn).to.not.increase(obj, prop);
- }
-
- /**
- * ### .decreases(function, object, property)
- *
- * Asserts that a function decreases an object property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val = 5 };
- * assert.decreases(fn, obj, 'val');
- *
- * @name decreases
- * @param {Function} modifier function
- * @param {Object} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- assert.decreases = function (fn, obj, prop) {
- new Assertion(fn).to.decrease(obj, prop);
- }
-
- /**
- * ### .doesNotDecrease(function, object, property)
- *
- * Asserts that a function does not decreases an object property
- *
- * var obj = { val: 10 };
- * var fn = function() { obj.val = 15 };
- * assert.doesNotDecrease(fn, obj, 'val');
- *
- * @name doesNotDecrease
- * @param {Function} modifier function
- * @param {Object} object
- * @param {String} property name
- * @param {String} message _optional_
- * @api public
- */
-
- assert.doesNotDecrease = function (fn, obj, prop) {
- new Assertion(fn).to.not.decrease(obj, prop);
- }
-
- /*!
- * ### .ifError(object)
- *
- * Asserts if value is not a false value, and throws if it is a true value.
- * This is added to allow for chai to be a drop-in replacement for Node's
- * assert class.
- *
- * var err = new Error('I am a custom error');
- * assert.ifError(err); // Rethrows err!
- *
- * @name ifError
- * @param {Object} object
- * @api public
- */
-
- assert.ifError = function (val) {
- if (val) {
- throw(val);
- }
- };
-
- /*!
- * Aliases.
- */
-
- (function alias(name, as){
- assert[as] = assert[name];
- return alias;
- })('Throw', 'throw')('Throw', 'throws');
-};
-
-},{}],6:[function(require,module,exports){
-/*!
- * chai
- * Copyright(c) 2011-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-module.exports = function (chai, util) {
- chai.expect = function (val, message) {
- return new chai.Assertion(val, message);
- };
-
- /**
- * ### .fail(actual, expected, [message], [operator])
- *
- * Throw a failure.
- *
- * @name fail
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @param {String} operator
- * @api public
- */
-
- chai.expect.fail = function (actual, expected, message, operator) {
- message = message || 'expect.fail()';
- throw new chai.AssertionError(message, {
- actual: actual
- , expected: expected
- , operator: operator
- }, chai.expect.fail);
- };
-};
-
-},{}],7:[function(require,module,exports){
-/*!
- * chai
- * Copyright(c) 2011-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-module.exports = function (chai, util) {
- var Assertion = chai.Assertion;
-
- function loadShould () {
- // explicitly define this method as function as to have it's name to include as `ssfi`
- function shouldGetter() {
- if (this instanceof String || this instanceof Number || this instanceof Boolean ) {
- return new Assertion(this.valueOf(), null, shouldGetter);
- }
- return new Assertion(this, null, shouldGetter);
- }
- function shouldSetter(value) {
- // See https://github.com/chaijs/chai/issues/86: this makes
- // `whatever.should = someValue` actually set `someValue`, which is
- // especially useful for `global.should = require('chai').should()`.
- //
- // Note that we have to use [[DefineProperty]] instead of [[Put]]
- // since otherwise we would trigger this very setter!
- Object.defineProperty(this, 'should', {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- }
- // modify Object.prototype to have `should`
- Object.defineProperty(Object.prototype, 'should', {
- set: shouldSetter
- , get: shouldGetter
- , configurable: true
- });
-
- var should = {};
-
- /**
- * ### .fail(actual, expected, [message], [operator])
- *
- * Throw a failure.
- *
- * @name fail
- * @param {Mixed} actual
- * @param {Mixed} expected
- * @param {String} message
- * @param {String} operator
- * @api public
- */
-
- should.fail = function (actual, expected, message, operator) {
- message = message || 'should.fail()';
- throw new chai.AssertionError(message, {
- actual: actual
- , expected: expected
- , operator: operator
- }, should.fail);
- };
-
- should.equal = function (val1, val2, msg) {
- new Assertion(val1, msg).to.equal(val2);
- };
-
- should.Throw = function (fn, errt, errs, msg) {
- new Assertion(fn, msg).to.Throw(errt, errs);
- };
-
- should.exist = function (val, msg) {
- new Assertion(val, msg).to.exist;
- }
-
- // negation
- should.not = {}
-
- should.not.equal = function (val1, val2, msg) {
- new Assertion(val1, msg).to.not.equal(val2);
- };
-
- should.not.Throw = function (fn, errt, errs, msg) {
- new Assertion(fn, msg).to.not.Throw(errt, errs);
- };
-
- should.not.exist = function (val, msg) {
- new Assertion(val, msg).to.not.exist;
- }
-
- should['throw'] = should['Throw'];
- should.not['throw'] = should.not['Throw'];
-
- return should;
- }
-
- chai.should = loadShould;
- chai.Should = loadShould;
-};
-
-},{}],8:[function(require,module,exports){
-/*!
- * Chai - addChainingMethod utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Module dependencies
- */
-
-var transferFlags = require('./transferFlags');
-var flag = require('./flag');
-var config = require('../config');
-
-/*!
- * Module variables
- */
-
-// Check whether `__proto__` is supported
-var hasProtoSupport = '__proto__' in Object;
-
-// Without `__proto__` support, this module will need to add properties to a function.
-// However, some Function.prototype methods cannot be overwritten,
-// and there seems no easy cross-platform way to detect them (@see chaijs/chai/issues/69).
-var excludeNames = /^(?:length|name|arguments|caller)$/;
-
-// Cache `Function` properties
-var call = Function.prototype.call,
- apply = Function.prototype.apply;
-
-/**
- * ### addChainableMethod (ctx, name, method, chainingBehavior)
- *
- * Adds a method to an object, such that the method can also be chained.
- *
- * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) {
- * var obj = utils.flag(this, 'object');
- * new chai.Assertion(obj).to.be.equal(str);
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior);
- *
- * The result can then be used as both a method assertion, executing both `method` and
- * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`.
- *
- * expect(fooStr).to.be.foo('bar');
- * expect(fooStr).to.be.foo.equal('foo');
- *
- * @param {Object} ctx object to which the method is added
- * @param {String} name of method to add
- * @param {Function} method function to be used for `name`, when called
- * @param {Function} chainingBehavior function to be called every time the property is accessed
- * @name addChainableMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method, chainingBehavior) {
- if (typeof chainingBehavior !== 'function') {
- chainingBehavior = function () { };
- }
-
- var chainableBehavior = {
- method: method
- , chainingBehavior: chainingBehavior
- };
-
- // save the methods so we can overwrite them later, if we need to.
- if (!ctx.__methods) {
- ctx.__methods = {};
- }
- ctx.__methods[name] = chainableBehavior;
-
- Object.defineProperty(ctx, name,
- { get: function () {
- chainableBehavior.chainingBehavior.call(this);
-
- var assert = function assert() {
- var old_ssfi = flag(this, 'ssfi');
- if (old_ssfi && config.includeStack === false)
- flag(this, 'ssfi', assert);
- var result = chainableBehavior.method.apply(this, arguments);
- return result === undefined ? this : result;
- };
-
- // Use `__proto__` if available
- if (hasProtoSupport) {
- // Inherit all properties from the object by replacing the `Function` prototype
- var prototype = assert.__proto__ = Object.create(this);
- // Restore the `call` and `apply` methods from `Function`
- prototype.call = call;
- prototype.apply = apply;
- }
- // Otherwise, redefine all properties (slow!)
- else {
- var asserterNames = Object.getOwnPropertyNames(ctx);
- asserterNames.forEach(function (asserterName) {
- if (!excludeNames.test(asserterName)) {
- var pd = Object.getOwnPropertyDescriptor(ctx, asserterName);
- Object.defineProperty(assert, asserterName, pd);
- }
- });
- }
-
- transferFlags(this, assert);
- return assert;
- }
- , configurable: true
- });
-};
-
-},{"../config":3,"./flag":11,"./transferFlags":27}],9:[function(require,module,exports){
-/*!
- * Chai - addMethod utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-var config = require('../config');
-
-/**
- * ### .addMethod (ctx, name, method)
- *
- * Adds a method to the prototype of an object.
- *
- * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) {
- * var obj = utils.flag(this, 'object');
- * new chai.Assertion(obj).to.be.equal(str);
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.addMethod('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(fooStr).to.be.foo('bar');
- *
- * @param {Object} ctx object to which the method is added
- * @param {String} name of method to add
- * @param {Function} method function to be used for name
- * @name addMethod
- * @api public
- */
-var flag = require('./flag');
-
-module.exports = function (ctx, name, method) {
- ctx[name] = function () {
- var old_ssfi = flag(this, 'ssfi');
- if (old_ssfi && config.includeStack === false)
- flag(this, 'ssfi', ctx[name]);
- var result = method.apply(this, arguments);
- return result === undefined ? this : result;
- };
-};
-
-},{"../config":3,"./flag":11}],10:[function(require,module,exports){
-/*!
- * Chai - addProperty utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### addProperty (ctx, name, getter)
- *
- * Adds a property to the prototype of an object.
- *
- * utils.addProperty(chai.Assertion.prototype, 'foo', function () {
- * var obj = utils.flag(this, 'object');
- * new chai.Assertion(obj).to.be.instanceof(Foo);
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.addProperty('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(myFoo).to.be.foo;
- *
- * @param {Object} ctx object to which the property is added
- * @param {String} name of property to add
- * @param {Function} getter function to be used for name
- * @name addProperty
- * @api public
- */
-
-module.exports = function (ctx, name, getter) {
- Object.defineProperty(ctx, name,
- { get: function () {
- var result = getter.call(this);
- return result === undefined ? this : result;
- }
- , configurable: true
- });
-};
-
-},{}],11:[function(require,module,exports){
-/*!
- * Chai - flag utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### flag(object, key, [value])
- *
- * Get or set a flag value on an object. If a
- * value is provided it will be set, else it will
- * return the currently set value or `undefined` if
- * the value is not set.
- *
- * utils.flag(this, 'foo', 'bar'); // setter
- * utils.flag(this, 'foo'); // getter, returns `bar`
- *
- * @param {Object} object constructed Assertion
- * @param {String} key
- * @param {Mixed} value (optional)
- * @name flag
- * @api private
- */
-
-module.exports = function (obj, key, value) {
- var flags = obj.__flags || (obj.__flags = Object.create(null));
- if (arguments.length === 3) {
- flags[key] = value;
- } else {
- return flags[key];
- }
-};
-
-},{}],12:[function(require,module,exports){
-/*!
- * Chai - getActual utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * # getActual(object, [actual])
- *
- * Returns the `actual` value for an Assertion
- *
- * @param {Object} object (constructed Assertion)
- * @param {Arguments} chai.Assertion.prototype.assert arguments
- */
-
-module.exports = function (obj, args) {
- return args.length > 4 ? args[4] : obj._obj;
-};
-
-},{}],13:[function(require,module,exports){
-/*!
- * Chai - getEnumerableProperties utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### .getEnumerableProperties(object)
- *
- * This allows the retrieval of enumerable property names of an object,
- * inherited or not.
- *
- * @param {Object} object
- * @returns {Array}
- * @name getEnumerableProperties
- * @api public
- */
-
-module.exports = function getEnumerableProperties(object) {
- var result = [];
- for (var name in object) {
- result.push(name);
- }
- return result;
-};
-
-},{}],14:[function(require,module,exports){
-/*!
- * Chai - message composition utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Module dependancies
- */
-
-var flag = require('./flag')
- , getActual = require('./getActual')
- , inspect = require('./inspect')
- , objDisplay = require('./objDisplay');
-
-/**
- * ### .getMessage(object, message, negateMessage)
- *
- * Construct the error message based on flags
- * and template tags. Template tags will return
- * a stringified inspection of the object referenced.
- *
- * Message template tags:
- * - `#{this}` current asserted object
- * - `#{act}` actual value
- * - `#{exp}` expected value
- *
- * @param {Object} object (constructed Assertion)
- * @param {Arguments} chai.Assertion.prototype.assert arguments
- * @name getMessage
- * @api public
- */
-
-module.exports = function (obj, args) {
- var negate = flag(obj, 'negate')
- , val = flag(obj, 'object')
- , expected = args[3]
- , actual = getActual(obj, args)
- , msg = negate ? args[2] : args[1]
- , flagMsg = flag(obj, 'message');
-
- if(typeof msg === "function") msg = msg();
- msg = msg || '';
- msg = msg
- .replace(/#{this}/g, objDisplay(val))
- .replace(/#{act}/g, objDisplay(actual))
- .replace(/#{exp}/g, objDisplay(expected));
-
- return flagMsg ? flagMsg + ': ' + msg : msg;
-};
-
-},{"./flag":11,"./getActual":12,"./inspect":21,"./objDisplay":22}],15:[function(require,module,exports){
-/*!
- * Chai - getName utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * # getName(func)
- *
- * Gets the name of a function, in a cross-browser way.
- *
- * @param {Function} a function (usually a constructor)
- */
-
-module.exports = function (func) {
- if (func.name) return func.name;
-
- var match = /^\s?function ([^(]*)\(/.exec(func);
- return match && match[1] ? match[1] : "";
-};
-
-},{}],16:[function(require,module,exports){
-/*!
- * Chai - getPathInfo utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-var hasProperty = require('./hasProperty');
-
-/**
- * ### .getPathInfo(path, object)
- *
- * This allows the retrieval of property info in an
- * object given a string path.
- *
- * The path info consists of an object with the
- * following properties:
- *
- * * parent - The parent object of the property referenced by `path`
- * * name - The name of the final property, a number if it was an array indexer
- * * value - The value of the property, if it exists, otherwise `undefined`
- * * exists - Whether the property exists or not
- *
- * @param {String} path
- * @param {Object} object
- * @returns {Object} info
- * @name getPathInfo
- * @api public
- */
-
-module.exports = function getPathInfo(path, obj) {
- var parsed = parsePath(path),
- last = parsed[parsed.length - 1];
-
- var info = {
- parent: parsed.length > 1 ? _getPathValue(parsed, obj, parsed.length - 1) : obj,
- name: last.p || last.i,
- value: _getPathValue(parsed, obj)
- };
- info.exists = hasProperty(info.name, info.parent);
-
- return info;
-};
-
-
-/*!
- * ## parsePath(path)
- *
- * Helper function used to parse string object
- * paths. Use in conjunction with `_getPathValue`.
- *
- * var parsed = parsePath('myobject.property.subprop');
- *
- * ### Paths:
- *
- * * Can be as near infinitely deep and nested
- * * Arrays are also valid using the formal `myobject.document[3].property`.
- * * Literal dots and brackets (not delimiter) must be backslash-escaped.
- *
- * @param {String} path
- * @returns {Object} parsed
- * @api private
- */
-
-function parsePath (path) {
- var str = path.replace(/([^\\])\[/g, '$1.[')
- , parts = str.match(/(\\\.|[^.]+?)+/g);
- return parts.map(function (value) {
- var re = /^\[(\d+)\]$/
- , mArr = re.exec(value);
- if (mArr) return { i: parseFloat(mArr[1]) };
- else return { p: value.replace(/\\([.\[\]])/g, '$1') };
- });
-}
-
-
-/*!
- * ## _getPathValue(parsed, obj)
- *
- * Helper companion function for `.parsePath` that returns
- * the value located at the parsed address.
- *
- * var value = getPathValue(parsed, obj);
- *
- * @param {Object} parsed definition from `parsePath`.
- * @param {Object} object to search against
- * @param {Number} object to search against
- * @returns {Object|Undefined} value
- * @api private
- */
-
-function _getPathValue (parsed, obj, index) {
- var tmp = obj
- , res;
-
- index = (index === undefined ? parsed.length : index);
-
- for (var i = 0, l = index; i < l; i++) {
- var part = parsed[i];
- if (tmp) {
- if ('undefined' !== typeof part.p)
- tmp = tmp[part.p];
- else if ('undefined' !== typeof part.i)
- tmp = tmp[part.i];
- if (i == (l - 1)) res = tmp;
- } else {
- res = undefined;
- }
- }
- return res;
-}
-
-},{"./hasProperty":19}],17:[function(require,module,exports){
-/*!
- * Chai - getPathValue utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * @see https://github.com/logicalparadox/filtr
- * MIT Licensed
- */
-
-var getPathInfo = require('./getPathInfo');
-
-/**
- * ### .getPathValue(path, object)
- *
- * This allows the retrieval of values in an
- * object given a string path.
- *
- * var obj = {
- * prop1: {
- * arr: ['a', 'b', 'c']
- * , str: 'Hello'
- * }
- * , prop2: {
- * arr: [ { nested: 'Universe' } ]
- * , str: 'Hello again!'
- * }
- * }
- *
- * The following would be the results.
- *
- * getPathValue('prop1.str', obj); // Hello
- * getPathValue('prop1.att[2]', obj); // b
- * getPathValue('prop2.arr[0].nested', obj); // Universe
- *
- * @param {String} path
- * @param {Object} object
- * @returns {Object} value or `undefined`
- * @name getPathValue
- * @api public
- */
-module.exports = function(path, obj) {
- var info = getPathInfo(path, obj);
- return info.value;
-};
-
-},{"./getPathInfo":16}],18:[function(require,module,exports){
-/*!
- * Chai - getProperties utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### .getProperties(object)
- *
- * This allows the retrieval of property names of an object, enumerable or not,
- * inherited or not.
- *
- * @param {Object} object
- * @returns {Array}
- * @name getProperties
- * @api public
- */
-
-module.exports = function getProperties(object) {
- var result = Object.getOwnPropertyNames(subject);
-
- function addProperty(property) {
- if (result.indexOf(property) === -1) {
- result.push(property);
- }
- }
-
- var proto = Object.getPrototypeOf(subject);
- while (proto !== null) {
- Object.getOwnPropertyNames(proto).forEach(addProperty);
- proto = Object.getPrototypeOf(proto);
- }
-
- return result;
-};
-
-},{}],19:[function(require,module,exports){
-/*!
- * Chai - hasProperty utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-var type = require('type-detect');
-
-/**
- * ### .hasProperty(object, name)
- *
- * This allows checking whether an object has
- * named property or numeric array index.
- *
- * Basically does the same thing as the `in`
- * operator but works properly with natives
- * and null/undefined values.
- *
- * var obj = {
- * arr: ['a', 'b', 'c']
- * , str: 'Hello'
- * }
- *
- * The following would be the results.
- *
- * hasProperty('str', obj); // true
- * hasProperty('constructor', obj); // true
- * hasProperty('bar', obj); // false
- *
- * hasProperty('length', obj.str); // true
- * hasProperty(1, obj.str); // true
- * hasProperty(5, obj.str); // false
- *
- * hasProperty('length', obj.arr); // true
- * hasProperty(2, obj.arr); // true
- * hasProperty(3, obj.arr); // false
- *
- * @param {Objuect} object
- * @param {String|Number} name
- * @returns {Boolean} whether it exists
- * @name getPathInfo
- * @api public
- */
-
-var literals = {
- 'number': Number
- , 'string': String
-};
-
-module.exports = function hasProperty(name, obj) {
- var ot = type(obj);
-
- // Bad Object, obviously no props at all
- if(ot === 'null' || ot === 'undefined')
- return false;
-
- // The `in` operator does not work with certain literals
- // box these before the check
- if(literals[ot] && typeof obj !== 'object')
- obj = new literals[ot](obj);
-
- return name in obj;
-};
-
-},{"type-detect":33}],20:[function(require,module,exports){
-/*!
- * chai
- * Copyright(c) 2011 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Main exports
- */
-
-exports = module.exports = {};
-
-/*!
- * test utility
- */
-
-exports.test = require('./test');
-
-/*!
- * type utility
- */
-
-exports.type = require('type-detect');
-
-/*!
- * message utility
- */
-
-exports.getMessage = require('./getMessage');
-
-/*!
- * actual utility
- */
-
-exports.getActual = require('./getActual');
-
-/*!
- * Inspect util
- */
-
-exports.inspect = require('./inspect');
-
-/*!
- * Object Display util
- */
-
-exports.objDisplay = require('./objDisplay');
-
-/*!
- * Flag utility
- */
-
-exports.flag = require('./flag');
-
-/*!
- * Flag transferring utility
- */
-
-exports.transferFlags = require('./transferFlags');
-
-/*!
- * Deep equal utility
- */
-
-exports.eql = require('deep-eql');
-
-/*!
- * Deep path value
- */
-
-exports.getPathValue = require('./getPathValue');
-
-/*!
- * Deep path info
- */
-
-exports.getPathInfo = require('./getPathInfo');
-
-/*!
- * Check if a property exists
- */
-
-exports.hasProperty = require('./hasProperty');
-
-/*!
- * Function name
- */
-
-exports.getName = require('./getName');
-
-/*!
- * add Property
- */
-
-exports.addProperty = require('./addProperty');
-
-/*!
- * add Method
- */
-
-exports.addMethod = require('./addMethod');
-
-/*!
- * overwrite Property
- */
-
-exports.overwriteProperty = require('./overwriteProperty');
-
-/*!
- * overwrite Method
- */
-
-exports.overwriteMethod = require('./overwriteMethod');
-
-/*!
- * Add a chainable method
- */
-
-exports.addChainableMethod = require('./addChainableMethod');
-
-/*!
- * Overwrite chainable method
- */
-
-exports.overwriteChainableMethod = require('./overwriteChainableMethod');
-
-
-},{"./addChainableMethod":8,"./addMethod":9,"./addProperty":10,"./flag":11,"./getActual":12,"./getMessage":14,"./getName":15,"./getPathInfo":16,"./getPathValue":17,"./hasProperty":19,"./inspect":21,"./objDisplay":22,"./overwriteChainableMethod":23,"./overwriteMethod":24,"./overwriteProperty":25,"./test":26,"./transferFlags":27,"deep-eql":29,"type-detect":33}],21:[function(require,module,exports){
-// This is (almost) directly from Node.js utils
-// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js
-
-var getName = require('./getName');
-var getProperties = require('./getProperties');
-var getEnumerableProperties = require('./getEnumerableProperties');
-
-module.exports = inspect;
-
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Boolean} showHidden Flag that shows hidden (not enumerable)
- * properties of objects.
- * @param {Number} depth Depth in which to descend in object. Default is 2.
- * @param {Boolean} colors Flag to turn on ANSI escape codes to color the
- * output. Default is false (no coloring).
- */
-function inspect(obj, showHidden, depth, colors) {
- var ctx = {
- showHidden: showHidden,
- seen: [],
- stylize: function (str) { return str; }
- };
- return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth));
-}
-
-// Returns true if object is a DOM element.
-var isDOMElement = function (object) {
- if (typeof HTMLElement === 'object') {
- return object instanceof HTMLElement;
- } else {
- return object &&
- typeof object === 'object' &&
- object.nodeType === 1 &&
- typeof object.nodeName === 'string';
- }
-};
-
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (value && typeof value.inspect === 'function' &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes);
- if (typeof ret !== 'string') {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
-
- // If this is a DOM element, try to get the outer HTML.
- if (isDOMElement(value)) {
- if ('outerHTML' in value) {
- return value.outerHTML;
- // This value does not have an outerHTML attribute,
- // it could still be an XML element
- } else {
- // Attempt to serialize it
- try {
- if (document.xmlVersion) {
- var xmlSerializer = new XMLSerializer();
- return xmlSerializer.serializeToString(value);
- } else {
- // Firefox 11- do not support outerHTML
- // It does, however, support innerHTML
- // Use the following to render the element
- var ns = "http://www.w3.org/1999/xhtml";
- var container = document.createElementNS(ns, '_');
-
- container.appendChild(value.cloneNode(false));
- html = container.innerHTML
- .replace('><', '>' + value.innerHTML + '<');
- container.innerHTML = '';
- return html;
- }
- } catch (err) {
- // This could be a non-native DOM implementation,
- // continue with the normal flow:
- // printing the element as if it is an object.
- }
- }
- }
-
- // Look up the keys of the object.
- var visibleKeys = getEnumerableProperties(value);
- var keys = ctx.showHidden ? getProperties(value) : visibleKeys;
-
- // Some type of object without properties can be shortcutted.
- // In IE, errors have a single `stack` property, or if they are vanilla `Error`,
- // a `stack` plus `description` property; ignore those for consistency.
- if (keys.length === 0 || (isError(value) && (
- (keys.length === 1 && keys[0] === 'stack') ||
- (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack')
- ))) {
- if (typeof value === 'function') {
- var name = getName(value);
- var nameSuffix = name ? ': ' + name : '';
- return ctx.stylize('[Function' + nameSuffix + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toUTCString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
-
- var base = '', array = false, braces = ['{', '}'];
-
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
-
- // Make functions say that they are functions
- if (typeof value === 'function') {
- name = getName(value);
- nameSuffix = name ? ': ' + name : '';
- base = ' [Function' + nameSuffix + ']';
- }
-
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
-
- // Make error with message first say the error
- if (isError(value)) {
- return formatError(value);
- }
-
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
-
- ctx.seen.pop();
-
- return reduceToSingleString(output, base, braces);
-}
-
-
-function formatPrimitive(ctx, value) {
- switch (typeof value) {
- case 'undefined':
- return ctx.stylize('undefined', 'undefined');
-
- case 'string':
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
-
- case 'number':
- if (value === 0 && (1/value) === -Infinity) {
- return ctx.stylize('-0', 'number');
- }
- return ctx.stylize('' + value, 'number');
-
- case 'boolean':
- return ctx.stylize('' + value, 'boolean');
- }
- // For some reason typeof null is "object", so special case here.
- if (value === null) {
- return ctx.stylize('null', 'null');
- }
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (Object.prototype.hasOwnProperty.call(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
-
-
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str;
- if (value.__lookupGetter__) {
- if (value.__lookupGetter__(key)) {
- if (value.__lookupSetter__(key)) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (value.__lookupSetter__(key)) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- }
- if (visibleKeys.indexOf(key) < 0) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(value[key]) < 0) {
- if (recurseTimes === null) {
- str = formatValue(ctx, value[key], null);
- } else {
- str = formatValue(ctx, value[key], recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (typeof name === 'undefined') {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
-}
-
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
-
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-function isArray(ar) {
- return Array.isArray(ar) ||
- (typeof ar === 'object' && objectToString(ar) === '[object Array]');
-}
-
-function isRegExp(re) {
- return typeof re === 'object' && objectToString(re) === '[object RegExp]';
-}
-
-function isDate(d) {
- return typeof d === 'object' && objectToString(d) === '[object Date]';
-}
-
-function isError(e) {
- return typeof e === 'object' && objectToString(e) === '[object Error]';
-}
-
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
-
-},{"./getEnumerableProperties":13,"./getName":15,"./getProperties":18}],22:[function(require,module,exports){
-/*!
- * Chai - flag utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Module dependancies
- */
-
-var inspect = require('./inspect');
-var config = require('../config');
-
-/**
- * ### .objDisplay (object)
- *
- * Determines if an object or an array matches
- * criteria to be inspected in-line for error
- * messages or should be truncated.
- *
- * @param {Mixed} javascript object to inspect
- * @name objDisplay
- * @api public
- */
-
-module.exports = function (obj) {
- var str = inspect(obj)
- , type = Object.prototype.toString.call(obj);
-
- if (config.truncateThreshold && str.length >= config.truncateThreshold) {
- if (type === '[object Function]') {
- return !obj.name || obj.name === ''
- ? '[Function]'
- : '[Function: ' + obj.name + ']';
- } else if (type === '[object Array]') {
- return '[ Array(' + obj.length + ') ]';
- } else if (type === '[object Object]') {
- var keys = Object.keys(obj)
- , kstr = keys.length > 2
- ? keys.splice(0, 2).join(', ') + ', ...'
- : keys.join(', ');
- return '{ Object (' + kstr + ') }';
- } else {
- return str;
- }
- } else {
- return str;
- }
-};
-
-},{"../config":3,"./inspect":21}],23:[function(require,module,exports){
-/*!
- * Chai - overwriteChainableMethod utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### overwriteChainableMethod (ctx, name, method, chainingBehavior)
- *
- * Overwites an already existing chainable method
- * and provides access to the previous function or
- * property. Must return functions to be used for
- * name.
- *
- * utils.overwriteChainableMethod(chai.Assertion.prototype, 'length',
- * function (_super) {
- * }
- * , function (_super) {
- * }
- * );
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.overwriteChainableMethod('foo', fn, fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(myFoo).to.have.length(3);
- * expect(myFoo).to.have.length.above(3);
- *
- * @param {Object} ctx object whose method / property is to be overwritten
- * @param {String} name of method / property to overwrite
- * @param {Function} method function that returns a function to be used for name
- * @param {Function} chainingBehavior function that returns a function to be used for property
- * @name overwriteChainableMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method, chainingBehavior) {
- var chainableBehavior = ctx.__methods[name];
-
- var _chainingBehavior = chainableBehavior.chainingBehavior;
- chainableBehavior.chainingBehavior = function () {
- var result = chainingBehavior(_chainingBehavior).call(this);
- return result === undefined ? this : result;
- };
-
- var _method = chainableBehavior.method;
- chainableBehavior.method = function () {
- var result = method(_method).apply(this, arguments);
- return result === undefined ? this : result;
- };
-};
-
-},{}],24:[function(require,module,exports){
-/*!
- * Chai - overwriteMethod utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### overwriteMethod (ctx, name, fn)
- *
- * Overwites an already existing method and provides
- * access to previous function. Must return function
- * to be used for name.
- *
- * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) {
- * return function (str) {
- * var obj = utils.flag(this, 'object');
- * if (obj instanceof Foo) {
- * new chai.Assertion(obj.value).to.equal(str);
- * } else {
- * _super.apply(this, arguments);
- * }
- * }
- * });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.overwriteMethod('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(myFoo).to.equal('bar');
- *
- * @param {Object} ctx object whose method is to be overwritten
- * @param {String} name of method to overwrite
- * @param {Function} method function that returns a function to be used for name
- * @name overwriteMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method) {
- var _method = ctx[name]
- , _super = function () { return this; };
-
- if (_method && 'function' === typeof _method)
- _super = _method;
-
- ctx[name] = function () {
- var result = method(_super).apply(this, arguments);
- return result === undefined ? this : result;
- }
-};
-
-},{}],25:[function(require,module,exports){
-/*!
- * Chai - overwriteProperty utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### overwriteProperty (ctx, name, fn)
- *
- * Overwites an already existing property getter and provides
- * access to previous value. Must return function to use as getter.
- *
- * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) {
- * return function () {
- * var obj = utils.flag(this, 'object');
- * if (obj instanceof Foo) {
- * new chai.Assertion(obj.name).to.equal('bar');
- * } else {
- * _super.call(this);
- * }
- * }
- * });
- *
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- * chai.Assertion.overwriteProperty('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- * expect(myFoo).to.be.ok;
- *
- * @param {Object} ctx object whose property is to be overwritten
- * @param {String} name of property to overwrite
- * @param {Function} getter function that returns a getter function to be used for name
- * @name overwriteProperty
- * @api public
- */
-
-module.exports = function (ctx, name, getter) {
- var _get = Object.getOwnPropertyDescriptor(ctx, name)
- , _super = function () {};
-
- if (_get && 'function' === typeof _get.get)
- _super = _get.get
-
- Object.defineProperty(ctx, name,
- { get: function () {
- var result = getter(_super).call(this);
- return result === undefined ? this : result;
- }
- , configurable: true
- });
-};
-
-},{}],26:[function(require,module,exports){
-/*!
- * Chai - test utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Module dependancies
- */
-
-var flag = require('./flag');
-
-/**
- * # test(object, expression)
- *
- * Test and object for expression.
- *
- * @param {Object} object (constructed Assertion)
- * @param {Arguments} chai.Assertion.prototype.assert arguments
- */
-
-module.exports = function (obj, args) {
- var negate = flag(obj, 'negate')
- , expr = args[0];
- return negate ? !expr : expr;
-};
-
-},{"./flag":11}],27:[function(require,module,exports){
-/*!
- * Chai - transferFlags utility
- * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### transferFlags(assertion, object, includeAll = true)
- *
- * Transfer all the flags for `assertion` to `object`. If
- * `includeAll` is set to `false`, then the base Chai
- * assertion flags (namely `object`, `ssfi`, and `message`)
- * will not be transferred.
- *
- *
- * var newAssertion = new Assertion();
- * utils.transferFlags(assertion, newAssertion);
- *
- * var anotherAsseriton = new Assertion(myObj);
- * utils.transferFlags(assertion, anotherAssertion, false);
- *
- * @param {Assertion} assertion the assertion to transfer the flags from
- * @param {Object} object the object to transfer the flags to; usually a new assertion
- * @param {Boolean} includeAll
- * @name transferFlags
- * @api private
- */
-
-module.exports = function (assertion, object, includeAll) {
- var flags = assertion.__flags || (assertion.__flags = Object.create(null));
-
- if (!object.__flags) {
- object.__flags = Object.create(null);
- }
-
- includeAll = arguments.length === 3 ? includeAll : true;
-
- for (var flag in flags) {
- if (includeAll ||
- (flag !== 'object' && flag !== 'ssfi' && flag != 'message')) {
- object.__flags[flag] = flags[flag];
- }
- }
-};
-
-},{}],28:[function(require,module,exports){
-/*!
- * assertion-error
- * Copyright(c) 2013 Jake Luer <jake@qualiancy.com>
- * MIT Licensed
- */
-
-/*!
- * Return a function that will copy properties from
- * one object to another excluding any originally
- * listed. Returned function will create a new `{}`.
- *
- * @param {String} excluded properties ...
- * @return {Function}
- */
-
-function exclude () {
- var excludes = [].slice.call(arguments);
-
- function excludeProps (res, obj) {
- Object.keys(obj).forEach(function (key) {
- if (!~excludes.indexOf(key)) res[key] = obj[key];
- });
- }
-
- return function extendExclude () {
- var args = [].slice.call(arguments)
- , i = 0
- , res = {};
-
- for (; i < args.length; i++) {
- excludeProps(res, args[i]);
- }
-
- return res;
- };
-}
-
-/*!
- * Primary Exports
- */
-
-module.exports = AssertionError;
-
-/**
- * ### AssertionError
- *
- * An extension of the JavaScript `Error` constructor for
- * assertion and validation scenarios.
- *
- * @param {String} message
- * @param {Object} properties to include (optional)
- * @param {callee} start stack function (optional)
- */
-
-function AssertionError (message, _props, ssf) {
- var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON')
- , props = extend(_props || {});
-
- // default values
- this.message = message || 'Unspecified AssertionError';
- this.showDiff = false;
-
- // copy from properties
- for (var key in props) {
- this[key] = props[key];
- }
-
- // capture stack trace
- ssf = ssf || arguments.callee;
- if (ssf && Error.captureStackTrace) {
- Error.captureStackTrace(this, ssf);
- } else {
- this.stack = new Error().stack;
- }
-}
-
-/*!
- * Inherit from Error.prototype
- */
-
-AssertionError.prototype = Object.create(Error.prototype);
-
-/*!
- * Statically set name
- */
-
-AssertionError.prototype.name = 'AssertionError';
-
-/*!
- * Ensure correct constructor
- */
-
-AssertionError.prototype.constructor = AssertionError;
-
-/**
- * Allow errors to be converted to JSON for static transfer.
- *
- * @param {Boolean} include stack (default: `true`)
- * @return {Object} object that can be `JSON.stringify`
- */
-
-AssertionError.prototype.toJSON = function (stack) {
- var extend = exclude('constructor', 'toJSON', 'stack')
- , props = extend({ name: this.name }, this);
-
- // include stack if exists and not turned off
- if (false !== stack && this.stack) {
- props.stack = this.stack;
- }
-
- return props;
-};
-
-},{}],29:[function(require,module,exports){
-module.exports = require('./lib/eql');
-
-},{"./lib/eql":30}],30:[function(require,module,exports){
-/*!
- * deep-eql
- * Copyright(c) 2013 Jake Luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Module dependencies
- */
-
-var type = require('type-detect');
-
-/*!
- * Buffer.isBuffer browser shim
- */
-
-var Buffer;
-try { Buffer = require('buffer').Buffer; }
-catch(ex) {
- Buffer = {};
- Buffer.isBuffer = function() { return false; }
-}
-
-/*!
- * Primary Export
- */
-
-module.exports = deepEqual;
-
-/**
- * Assert super-strict (egal) equality between
- * two objects of any type.
- *
- * @param {Mixed} a
- * @param {Mixed} b
- * @param {Array} memoised (optional)
- * @return {Boolean} equal match
- */
-
-function deepEqual(a, b, m) {
- if (sameValue(a, b)) {
- return true;
- } else if ('date' === type(a)) {
- return dateEqual(a, b);
- } else if ('regexp' === type(a)) {
- return regexpEqual(a, b);
- } else if (Buffer.isBuffer(a)) {
- return bufferEqual(a, b);
- } else if ('arguments' === type(a)) {
- return argumentsEqual(a, b, m);
- } else if (!typeEqual(a, b)) {
- return false;
- } else if (('object' !== type(a) && 'object' !== type(b))
- && ('array' !== type(a) && 'array' !== type(b))) {
- return sameValue(a, b);
- } else {
- return objectEqual(a, b, m);
- }
-}
-
-/*!
- * Strict (egal) equality test. Ensures that NaN always
- * equals NaN and `-0` does not equal `+0`.
- *
- * @param {Mixed} a
- * @param {Mixed} b
- * @return {Boolean} equal match
- */
-
-function sameValue(a, b) {
- if (a === b) return a !== 0 || 1 / a === 1 / b;
- return isNaN(a) && isNaN(b);
-}
-
-/*!
- * Compare the types of two given objects and
- * return if they are equal. Note that an Array
- * has a type of `array` (not `object`) and arguments
- * have a type of `arguments` (not `array`/`object`).
- *
- * @param {Mixed} a
- * @param {Mixed} b
- * @return {Boolean} result
- */
-
-function typeEqual(a, b) {
- return type(a) === type(b);
-}
-
-/*!
- * Compare two Date objects by asserting that
- * the time values are equal using `saveValue`.
- *
- * @param {Date} a
- * @param {Date} b
- * @return {Boolean} result
- */
-
-function dateEqual(a, b) {
- if ('date' !== type(b)) return false;
- return sameValue(a.getTime(), b.getTime());
-}
-
-/*!
- * Compare two regular expressions by converting them
- * to string and checking for `sameValue`.
- *
- * @param {RegExp} a
- * @param {RegExp} b
- * @return {Boolean} result
- */
-
-function regexpEqual(a, b) {
- if ('regexp' !== type(b)) return false;
- return sameValue(a.toString(), b.toString());
-}
-
-/*!
- * Assert deep equality of two `arguments` objects.
- * Unfortunately, these must be sliced to arrays
- * prior to test to ensure no bad behavior.
- *
- * @param {Arguments} a
- * @param {Arguments} b
- * @param {Array} memoize (optional)
- * @return {Boolean} result
- */
-
-function argumentsEqual(a, b, m) {
- if ('arguments' !== type(b)) return false;
- a = [].slice.call(a);
- b = [].slice.call(b);
- return deepEqual(a, b, m);
-}
-
-/*!
- * Get enumerable properties of a given object.
- *
- * @param {Object} a
- * @return {Array} property names
- */
-
-function enumerable(a) {
- var res = [];
- for (var key in a) res.push(key);
- return res;
-}
-
-/*!
- * Simple equality for flat iterable objects
- * such as Arrays or Node.js buffers.
- *
- * @param {Iterable} a
- * @param {Iterable} b
- * @return {Boolean} result
- */
-
-function iterableEqual(a, b) {
- if (a.length !== b.length) return false;
-
- var i = 0;
- var match = true;
-
- for (; i < a.length; i++) {
- if (a[i] !== b[i]) {
- match = false;
- break;
- }
- }
-
- return match;
-}
-
-/*!
- * Extension to `iterableEqual` specifically
- * for Node.js Buffers.
- *
- * @param {Buffer} a
- * @param {Mixed} b
- * @return {Boolean} result
- */
-
-function bufferEqual(a, b) {
- if (!Buffer.isBuffer(b)) return false;
- return iterableEqual(a, b);
-}
-
-/*!
- * Block for `objectEqual` ensuring non-existing
- * values don't get in.
- *
- * @param {Mixed} object
- * @return {Boolean} result
- */
-
-function isValue(a) {
- return a !== null && a !== undefined;
-}
-
-/*!
- * Recursively check the equality of two objects.
- * Once basic sameness has been established it will
- * defer to `deepEqual` for each enumerable key
- * in the object.
- *
- * @param {Mixed} a
- * @param {Mixed} b
- * @return {Boolean} result
- */
-
-function objectEqual(a, b, m) {
- if (!isValue(a) || !isValue(b)) {
- return false;
- }
-
- if (a.prototype !== b.prototype) {
- return false;
- }
-
- var i;
- if (m) {
- for (i = 0; i < m.length; i++) {
- if ((m[i][0] === a && m[i][1] === b)
- || (m[i][0] === b && m[i][1] === a)) {
- return true;
- }
- }
- } else {
- m = [];
- }
-
- try {
- var ka = enumerable(a);
- var kb = enumerable(b);
- } catch (ex) {
- return false;
- }
-
- ka.sort();
- kb.sort();
-
- if (!iterableEqual(ka, kb)) {
- return false;
- }
-
- m.push([ a, b ]);
-
- var key;
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!deepEqual(a[key], b[key], m)) {
- return false;
- }
- }
-
- return true;
-}
-
-},{"buffer":undefined,"type-detect":31}],31:[function(require,module,exports){
-module.exports = require('./lib/type');
-
-},{"./lib/type":32}],32:[function(require,module,exports){
-/*!
- * type-detect
- * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Primary Exports
- */
-
-exports = module.exports = getType;
-
-/*!
- * Detectable javascript natives
- */
-
-var natives = {
- '[object Array]': 'array'
- , '[object RegExp]': 'regexp'
- , '[object Function]': 'function'
- , '[object Arguments]': 'arguments'
- , '[object Date]': 'date'
-};
-
-/**
- * ### typeOf (obj)
- *
- * Use several different techniques to determine
- * the type of object being tested.
- *
- *
- * @param {Mixed} object
- * @return {String} object type
- * @api public
- */
-
-function getType (obj) {
- var str = Object.prototype.toString.call(obj);
- if (natives[str]) return natives[str];
- if (obj === null) return 'null';
- if (obj === undefined) return 'undefined';
- if (obj === Object(obj)) return 'object';
- return typeof obj;
-}
-
-exports.Library = Library;
-
-/**
- * ### Library
- *
- * Create a repository for custom type detection.
- *
- * ```js
- * var lib = new type.Library;
- * ```
- *
- */
-
-function Library () {
- this.tests = {};
-}
-
-/**
- * #### .of (obj)
- *
- * Expose replacement `typeof` detection to the library.
- *
- * ```js
- * if ('string' === lib.of('hello world')) {
- * // ...
- * }
- * ```
- *
- * @param {Mixed} object to test
- * @return {String} type
- */
-
-Library.prototype.of = getType;
-
-/**
- * #### .define (type, test)
- *
- * Add a test to for the `.test()` assertion.
- *
- * Can be defined as a regular expression:
- *
- * ```js
- * lib.define('int', /^[0-9]+$/);
- * ```
- *
- * ... or as a function:
- *
- * ```js
- * lib.define('bln', function (obj) {
- * if ('boolean' === lib.of(obj)) return true;
- * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ];
- * if ('string' === lib.of(obj)) obj = obj.toLowerCase();
- * return !! ~blns.indexOf(obj);
- * });
- * ```
- *
- * @param {String} type
- * @param {RegExp|Function} test
- * @api public
- */
-
-Library.prototype.define = function (type, test) {
- if (arguments.length === 1) return this.tests[type];
- this.tests[type] = test;
- return this;
-};
-
-/**
- * #### .test (obj, test)
- *
- * Assert that an object is of type. Will first
- * check natives, and if that does not pass it will
- * use the user defined custom tests.
- *
- * ```js
- * assert(lib.test('1', 'int'));
- * assert(lib.test('yes', 'bln'));
- * ```
- *
- * @param {Mixed} object
- * @param {String} type
- * @return {Boolean} result
- * @api public
- */
-
-Library.prototype.test = function (obj, type) {
- if (type === getType(obj)) return true;
- var test = this.tests[type];
-
- if (test && 'regexp' === getType(test)) {
- return test.test(obj);
- } else if (test && 'function' === getType(test)) {
- return test(obj);
- } else {
- throw new ReferenceError('Type test "' + type + '" not defined or invalid.');
- }
-};
-
-},{}],33:[function(require,module,exports){
-arguments[4][31][0].apply(exports,arguments)
-},{"./lib/type":34,"dup":31}],34:[function(require,module,exports){
-/*!
- * type-detect
- * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Primary Exports
- */
-
-exports = module.exports = getType;
-
-/**
- * ### typeOf (obj)
- *
- * Use several different techniques to determine
- * the type of object being tested.
- *
- *
- * @param {Mixed} object
- * @return {String} object type
- * @api public
- */
-var objectTypeRegexp = /^\[object (.*)\]$/;
-
-function getType(obj) {
- var type = Object.prototype.toString.call(obj).match(objectTypeRegexp)[1].toLowerCase();
- // Let "new String('')" return 'object'
- if (typeof Promise === 'function' && obj instanceof Promise) return 'promise';
- // PhantomJS has type "DOMWindow" for null
- if (obj === null) return 'null';
- // PhantomJS has type "DOMWindow" for undefined
- if (obj === undefined) return 'undefined';
- return type;
-}
-
-exports.Library = Library;
-
-/**
- * ### Library
- *
- * Create a repository for custom type detection.
- *
- * ```js
- * var lib = new type.Library;
- * ```
- *
- */
-
-function Library() {
- if (!(this instanceof Library)) return new Library();
- this.tests = {};
-}
-
-/**
- * #### .of (obj)
- *
- * Expose replacement `typeof` detection to the library.
- *
- * ```js
- * if ('string' === lib.of('hello world')) {
- * // ...
- * }
- * ```
- *
- * @param {Mixed} object to test
- * @return {String} type
- */
-
-Library.prototype.of = getType;
-
-/**
- * #### .define (type, test)
- *
- * Add a test to for the `.test()` assertion.
- *
- * Can be defined as a regular expression:
- *
- * ```js
- * lib.define('int', /^[0-9]+$/);
- * ```
- *
- * ... or as a function:
- *
- * ```js
- * lib.define('bln', function (obj) {
- * if ('boolean' === lib.of(obj)) return true;
- * var blns = [ 'yes', 'no', 'true', 'false', 1, 0 ];
- * if ('string' === lib.of(obj)) obj = obj.toLowerCase();
- * return !! ~blns.indexOf(obj);
- * });
- * ```
- *
- * @param {String} type
- * @param {RegExp|Function} test
- * @api public
- */
-
-Library.prototype.define = function(type, test) {
- if (arguments.length === 1) return this.tests[type];
- this.tests[type] = test;
- return this;
-};
-
-/**
- * #### .test (obj, test)
- *
- * Assert that an object is of type. Will first
- * check natives, and if that does not pass it will
- * use the user defined custom tests.
- *
- * ```js
- * assert(lib.test('1', 'int'));
- * assert(lib.test('yes', 'bln'));
- * ```
- *
- * @param {Mixed} object
- * @param {String} type
- * @return {Boolean} result
- * @api public
- */
-
-Library.prototype.test = function(obj, type) {
- if (type === getType(obj)) return true;
- var test = this.tests[type];
-
- if (test && 'regexp' === getType(test)) {
- return test.test(obj);
- } else if (test && 'function' === getType(test)) {
- return test(obj);
- } else {
- throw new ReferenceError('Type test "' + type + '" not defined or invalid.');
- }
-};
-
-},{}],35:[function(require,module,exports){
-module.exports = require('./lib/chai');
-
-},{"./lib/chai":1}]},{},[35])(35)
-});
diff --git a/toolkit/components/microformats/test/static/javascript/count.js b/toolkit/components/microformats/test/static/javascript/count.js
deleted file mode 100644
index 56a64c05e..000000000
--- a/toolkit/components/microformats/test/static/javascript/count.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/*!
- parse
- Used by http://localhost:3000/
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-window.onload = function() {
-
- var form;
- form= document.getElementById('mf-form');
-
- form.onsubmit = function(e){
- e.preventDefault();
-
- var html,
- doc,
- node,
- options,
- mfJSON,
- parserJSONElt;
-
- // get data from html
- html = document.getElementById('html').value;
- parserJSONElt = document.querySelector('#parser-json pre code')
-
- // createHTMLDocument is not well support below ie9
- doc = document.implementation.createHTMLDocument("New Document");
- node = document.createElement('div');
- node.innerHTML = html;
- doc.body.appendChild(node);
-
- options ={
- 'node': node
- };
-
- // parse direct into Modules to help debugging
- if(window.Modules){
- var parser = new Modules.Parser();
- mfJSON = parser.count(options);
- }else if(window.Microformats){
- mfJSON = Microformats.count(options);
- }
-
-
- // format output
- parserJSONElt.innerHTML = htmlEscape( js_beautify( JSON.stringify(mfJSON) ) );
- //prettyPrint();
-
- }
-
- function htmlEscape(str) {
- return String(str)
- .replace(/&/g, '&amp;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#39;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
- }
-
-
-};
diff --git a/toolkit/components/microformats/test/static/javascript/data.js b/toolkit/components/microformats/test/static/javascript/data.js
deleted file mode 100644
index 3f725c6db..000000000
--- a/toolkit/components/microformats/test/static/javascript/data.js
+++ /dev/null
@@ -1 +0,0 @@
-var testData = {"date":"2015-09-25T12:26:26.421Z","repo":"microformats/tests","version":"0.1.24","data":[{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"],\n \"org\": [\"Mozilla Foundation\"],\n \"url\": [\"http://mozilla.org/\"],\n \"adr\": [{\n \"value\": \"665 3rd St. \\n Suite 207 \\n San Francisco, \\n CA \\n 94107 \\n U.S.A.\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"665 3rd St.\"],\n \"extended-address\": [\"Suite 207\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94107\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-card\">\n <p>\n <a class=\"p-name p-org u-url\" href=\"http://mozilla.org/\">Mozilla Foundation</a>\n <img class=\"logo\" src=\"../logo.jpg\"/>\n </p>\n <p class=\"adr\">\n <span class=\"street-address\">665 3rd St.</span> \n <span class=\"extended-address\">Suite 207</span> \n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n <span class=\"postal-code\">94107</span> \n <span class=\"p-country-name\">U.S.A.</span> \n </p>\n</div>","name":"mf-mixed-h-card-mixedpropertries"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Frances Berriman\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-card vcard\">Frances Berriman</p>","name":"mf-mixed-h-card-tworoots"},{"json":"\n{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"author\": [{\n \"value\": \"aaronparecki.com\\n Aaron Parecki\\n Aaron Parecki\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"photo\": [\"https://aaronparecki.com/images/aaronpk.png\"],\n \"logo\": [\"https://aaronparecki.com/images/aaronpk.png\"],\n \"url\": [\"https://aaronparecki.com/\"],\n \"uid\": [\"https://aaronparecki.com/\"],\n \"name\": [\"Aaron Parecki\"]\n }\n }],\n \"content\": [{\n \"value\": \"Did you play\\n @playmapattackat\\n #realtimeconf? Here is some more info about how we built it!\\n http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/\",\n \"html\": \"Did you play\\n <a href=\\\"http://twitter.com/playmapattack\\\">@playmapattack</a>at\\n <a href=\\\"http://aaronparecki.com/tag/realtimeconf\\\">#<span class=\\\"p-category\\\">realtimeconf</span></a>? Here is some more info about how we built it!\\n <a href=\\\"http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/\\\"><span class=\\\"protocol\\\">http://</span>pdx.esri.com/blog/2013/10/17/introducting-mapattack/</a>\\n \"\n }],\n \"name\": [\"Did you play\\n @playmapattackat\\n #realtimeconf? Here is some more info about how we built it!\\n http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/\"],\n \"category\": [\"realtimeconf\"]\n }\n }],\n \"rels\": {\n \"author\": [\"https://aaronparecki.com/\", \"https://plus.google.com/117847912875913905493\"]\n },\n \"rel-urls\": {\n \"https://aaronparecki.com/\": {\n \"text\": \"aaronparecki.com\",\n \"rels\": [\"author\"]\n },\n \"https://plus.google.com/117847912875913905493\": {\n \"text\": \"Aaron Parecki\",\n \"rels\": [\"author\"]\n }\n }\n}","html":"<!-- simplified version of http://aaronparecki.com/notes/2013/10/18/2/realtimeconf-mapattack -->\n<base href=\"http://aaronparecki.com/\" />\n\n<div class=\"h-entry\">\n <div class=\"h-card vcard author p-author\">\n <img class=\"photo logo u-photo u-logo\" src=\"https://aaronparecki.com/images/aaronpk.png\" alt=\"Aaron Parecki\"/>\n <a href=\"https://aaronparecki.com/\" rel=\"author\" class=\"u-url u-uid url\">aaronparecki.com</a>\n <a class=\"p-name fn value\" href=\"https://aaronparecki.com/\">Aaron Parecki</a>\n <a href=\"https://plus.google.com/117847912875913905493\" rel=\"author\" class=\"google-profile\">Aaron Parecki</a>\n </div>\n <div class=\"entry-content e-content p-name\">Did you play\n <a href=\"http://twitter.com/playmapattack\">@playmapattack</a>at\n <a href=\"/tag/realtimeconf\">#<span class=\"p-category\">realtimeconf</span></a>? Here is some more info about how we built it!\n <a href=\"http://pdx.esri.com/blog/2013/10/17/introducting-mapattack/\"><span class=\"protocol\">http://</span>pdx.esri.com/blog/2013/10/17/introducting-mapattack/</a>\n </div>\n</div>","name":"mf-mixed-h-entry-mixedroots"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"contact\": [{\n \"value\": \"Tim Berners-Lee\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"job-title\": [\"Director of the World Wide Web Foundation\"]\n }\n }],\n \"summary\": [\"Invented the World Wide Web.\"],\n \"experience\": [{\n \"value\": \"World Wide Web Foundation\",\n \"type\": [\"h-event\", \"h-card\"],\n \"properties\": {\n \"job-title\": [\"Director\"],\n \"name\": [\"World Wide Web Foundation\"],\n \"org\": [\"World Wide Web Foundation\"],\n \"url\": [\"http://www.webfoundation.org/\"],\n \"start\": [\"2009-01-18\"],\n \"duration\": [\"P2Y11M\"]\n }\n }],\n \"name\": [\"Tim Berners-Lee\\n Director of the World Wide Web Foundation\\n \\n Invented the World Wide Web.\\n \\n Director\\n World Wide Web Foundation\\n \\n Jan 2009 – Present\\n (2 years 11 month)\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"h-resume\">\n <div class=\"p-contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <div class=\"p-experience vevent vcard\">\n <p class=\"title\">Director</p>\n <p><a class=\"fn org summary url\" href=\"http://www.webfoundation.org/\">World Wide Web Foundation</a></p>\n <p>\n <time class=\"dtstart\" datetime=\"2009-01-18\">Jan 2009</time> – Present\n <time class=\"duration\" datetime=\"P2Y11M\">(2 years 11 month)</time>\n </p>\n </div>\n</div>","name":"mf-mixed-h-resume-mixedroots"},{"json":"{\n \"items\": [{\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"665 3rd St.\"],\n \"extended-address\": [\"Suite 207\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94107\"],\n \"country-name\": [\"U.S.A.\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"adr\">\n <span class=\"street-address\">665 3rd St.</span> \n <span class=\"extended-address\">Suite 207</span> \n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n <span class=\"postal-code\">94107</span> \n <span class=\"country-name\">U.S.A.</span> \n</p>","name":"mf-v1-adr-simpleproperties"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"latitude\": [\"37.408183\"],\n \"longitude\": [\"-122.13855\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<p class=\"geo\">\n <abbr class=\"latitude\" title=\"37.408183\">N 37° 24.491</abbr>, \n <abbr class=\"longitude\" title=\"-122.13855\">W 122° 08.313</abbr>\n</p>","name":"mf-v1-geo-abbrpattern"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"latitude\": [\"51.513458\"],\n \"longitude\": [\"-0.14812\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p>\n <span class=\"geo\">The Bricklayer's Arms\n <span class=\"latitude\">\n <span class=\"value-title\" title=\"51.513458\"> </span> \n </span>\n <span class=\"longitude\">\n <span class=\"value-title\" title=\"-0.14812\"> </span>\n </span>\n </span>\n</p>","name":"mf-v1-geo-hidden"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"latitude\": [\"51.513458\"],\n \"longitude\": [\"-0.14812\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"We are meeting at \n<span class=\"geo\"> \n <span>The Bricklayer's Arms</span>\n (Geo: <span class=\"latitude\">51.513458</span>:\n <span class=\"longitude\">-0.14812</span>)\n</span>","name":"mf-v1-geo-simpleproperties"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"latitude\": [\"51.513458\"],\n \"longitude\": [\"-0.14812\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<p>\n <span class=\"geo\">\n <span class=\"latitude\">\n <span class=\"value-title\" title=\"51.513458\">N 51° 51.345</span>, \n </span>\n <span class=\"longitude\">\n <span class=\"value-title\" title=\"-0.14812\">W -0° 14.812</span>\n </span>\n </span>\n</p>","name":"mf-v1-geo-valuetitleclass"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"The 4th Microformat party\"],\n \"start\": [\n \"2009-06-26 19:00:00\", \n \"2009-06-26 07:00:00\", \n \"2009-06-26 19:00\", \n \"2009-06-26 19\", \n \"2009-06-26 19\", \n \"2009-06-26 19:00\", \n \"2009-06-26 19:00\", \n \"2009-06-26 19:00\", \n \"2009-06-26 07:00\"\n ]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vevent\">\n <span class=\"summary\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00am \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00pm \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00p.m. \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00PM \n </span></li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00am \n </span></li>\n </ul>\n</div>","name":"mf-v1-hcalendar-ampm"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"CPJ Online Press Freedom Summit\"],\n \"start\": [\"2012-10-10\"],\n \"location\": [\"San Francisco\"],\n \"attendee\": [{\n \"value\": \"Brian Warner\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Brian Warner\"]\n }\n }, {\n \"value\": \"Kyle Machulis\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Kyle Machulis\"]\n }\n }, {\n \"value\": \"Tantek Çelik\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek Çelik\"]\n }\n }, {\n \"value\": \"Sid Sutter\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Sid Sutter\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"vevent\">\n <span class=\"summary\">CPJ Online Press Freedom Summit</span>\n (<time class=\"dtstart\" datetime=\"2012-10-10\">10 Nov 2012</time>) in\n <span class=\"location\">San Francisco</span>.\n Attendees:\n <ul>\n <li class=\"attendee vcard\"><span class=\"fn\">Brian Warner</span></li>\n <li class=\"attendee vcard\"><span class=\"fn\">Kyle Machulis</span></li>\n <li class=\"attendee vcard\"><span class=\"fn\">Tantek Çelik</span></li>\n <li class=\"attendee vcard\"><span class=\"fn\">Sid Sutter</span></li>\n </ul>\n</div>\n","name":"mf-v1-hcalendar-attendees"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"IndieWebCamp 2012\"],\n \"url\": [\"http://indiewebcamp.com/2012\"],\n \"start\": [\"2012-06-30\"],\n \"end\": [\"2012-07-01\"],\n \"location\": [{\n \"value\": \"Geoloqi\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Geoloqi\"],\n \"org\": [\"Geoloqi\"],\n \"url\": [\"http://geoloqi.com/\"],\n \"adr\": [{\n \"value\": \"920 SW 3rd Ave. Suite 400, \\n Portland, \\n OR\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"920 SW 3rd Ave. Suite 400\"],\n \"locality\": [\"Portland\"],\n \"region\": [\"Oregon\"]\n }\n }]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vevent\">\n <a class=\"summary url\" href=\"http://indiewebcamp.com/2012\">\n IndieWebCamp 2012\n </a>\n from <time class=\"dtstart\">2012-06-30</time> \n to <time class=\"dtend\">2012-07-01</time> at \n <span class=\"location vcard\">\n <a class=\"fn org url\" href=\"http://geoloqi.com/\">Geoloqi</a>, \n <span class=\"adr\">\n <span class=\"street-address\">920 SW 3rd Ave. Suite 400</span>, \n <span class=\"locality\">Portland</span>, \n <abbr class=\"region\" title=\"Oregon\">OR</abbr>\n </span>\n </span>\n</div>","name":"mf-v1-hcalendar-combining"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"The 4th Microformat party\"],\n \"start\": [\"2009-06-26 19:00\"],\n \"end\": [\"2009-06-26 22:00\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vevent\">\n <span class=\"summary\">The 4th Microformat party</span> will be on \n <span class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time></span> to \n <span class=\"dtend\"><time class=\"value\">22:00</time></span>.\n</div>","name":"mf-v1-hcalendar-concatenate"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"The 4th Microformat party\"],\n \"start\": [\n \"2009-06-26 19:00:00-08:00\", \n \"2009-06-26 19:00:00-08:00\", \n \"2009-06-26 19:00:00+08:00\", \n \"2009-06-26 19:00:00Z\", \n \"2009-06-26 19:00:00\", \n \"2009-06-26 19:00-08:00\", \n \"2009-06-26 19:00+08:00\", \n \"2009-06-26 19:00Z\", \n \"2009-06-26 19:00\"\n ],\n \"end\": [\"2013-034\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vevent\">\n <span class=\"summary\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-08:00</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-0800</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00+0800</time> \n </li> \n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00Z</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00-08:00</time> \n </li> \n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00+08:00</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00z</time> \n </li>\n <li class=\"dtstart\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time> \n </li> \n <li>\n <time class=\"dtend\" datetime=\"2013-034\">3 February 2013</time>\n </li> \n </ul>\n</div>","name":"mf-v1-hcalendar-time"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"John Doe\"],\n \"email\": [\"mailto:john@example.com\", \"mailto:john@example.com\", \"mailto:john@example.com?subject=parser-test\", \"john@example.com\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vcard\">\n <span class=\"fn\">John Doe</span> \n <ul>\n <li><a class=\"email\" href=\"mailto:john@example.com\">notthis@example.com</a></li>\n <li>\n <span class=\"email\">\n <span class=\"type\">internet</span> \n <a class=\"value\" href=\"mailto:john@example.com\">notthis@example.com</a>\n </span>\n </li> \n <li><a class=\"email\" href=\"mailto:john@example.com?subject=parser-test\">notthis@example.com</a></li>\n <li class=\"email\">john@example.com</li>\n </ul>\n</div>","name":"mf-v1-hcard-email"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"John \\n Doe\"],\n \"given-name\": [\"John\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"vcard\">\n <span class=\"profile-name fn n\">\n <span class=\" given-name \">John</span> \n <span class=\"FAMILY-NAME\">Doe</span> \n </span>\n</p>","name":"mf-v1-hcard-format"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {}\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"vcard\" href=\"http://rohit.khare.org/\">\n <img alt=\"Rohit Khare\" src=\"images/photo.gif\" />\n</a>","name":"mf-v1-hcard-hyperlinkedphoto"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {}\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"vcard\" href=\"http://benward.me/\">Ben Ward</a>","name":"mf-v1-hcard-justahyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {}\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"vcard\">Frances Berriman</p>","name":"mf-v1-hcard-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"John Doe\"],\n \"given-name\": [\"John\"],\n \"family-name\": [\"Doe\"],\n \"sound\": [\"http://www.madgex.com/johndoe.mpeg\"],\n \"photo\": [\"http://example.com/images/photo.gif\"],\n \"nickname\": [\"Man with no name\", \"Lost boy\"],\n \"note\": [\"John Doe is one of those names you always have issues with.\", \"It can be a real problem booking a hotel room with the name John Doe.\"],\n \"logo\": [\"http://example.com/images/logo.gif\", \"http://example.com/images/logo.gif\"],\n \"url\": [\"http://www.madgex.com/\", \"http://www.webfeetmedia.com/\"],\n \"org\": [\"Madgex\", \"Web Feet Media Ltd\"],\n \"job-title\": [\"Creative Director\", \"Owner\"],\n \"category\": [\"design\", \"development\", \"web\"],\n \"tel\": [\"+1 415 555 100\", \"+1 415 555 200\", \"+1 415 555 300\"],\n \"email\": [\"mailto:john.doe@madgex.com\", \"mailto:john.doe@webfeetmedia.com\"],\n \"mailer\": [\"PigeonMail 2.1\", \"Outlook 2007\"],\n \"label\": [\"Work: \\n North Street, \\n Brighton, \\n United Kingdom\", \"Home: \\n West Street, \\n Brighton, \\n United Kingdom\"],\n \"adr\": [{\n \"value\": \"Work: \\n North Street, \\n Brighton, \\n United Kingdom\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"North Street\"],\n \"locality\": [\"Brighton\"],\n \"country-name\": [\"United Kingdom\"]\n }\n }, {\n \"value\": \"Home: \\n West Street, \\n Brighton, \\n United Kingdom\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"West Street\"],\n \"locality\": [\"Brighton\"],\n \"country-name\": [\"United Kingdom\"]\n }\n }],\n \"agent\": [\"Jane Doe\", {\n \"value\": \"Dave Doe\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Dave Doe\"]\n }\n }],\n \"key\": [\"hd02$Gfu*d%dh87KTa2=23934532479\"]\n }\n }],\n \"rels\": {\n \"tag\": [\"http://en.wikipedia.org/wiki/design\", \"http://en.wikipedia.org/wiki/development\", \"http://en.wikipedia.org/wiki/web\"]\n },\n \"rel-urls\": {\n \"http://en.wikipedia.org/wiki/design\": {\n \"text\": \"design\",\n \"rels\": [\"tag\"]\n },\n \"http://en.wikipedia.org/wiki/development\": {\n \"text\": \"development\",\n \"rels\": [\"tag\"]\n },\n \"http://en.wikipedia.org/wiki/web\": {\n \"text\": \"web\",\n \"rels\": [\"tag\"]\n }\n }\n}","html":"<base href=\"http://example.com\">\n <div class=\"vcard\">\n \n <div class=\"fn n\"><span class=\"given-name\">John</span> <span class=\"family-name\">Doe</span></div>\n <a class=\"sound\" href=\"http://www.madgex.com/johndoe.mpeg\">Pronunciation of my name</a>\n <div><img class=\"photo\" src=\"images/photo.gif\" alt=\"Photo of John Doe\" /></div>\n\n <p>Nicknames:</p>\n <ul>\n <li class=\"nickname\">Man with no name</li>\n <li class=\"nickname\">Lost boy</li>\n </ul>\n\n <p>About:</p>\n <p class=\"note\">John Doe is one of those names you always have issues with.</p>\n <p class=\"note\">It can be a real problem booking a hotel room with the name John Doe.</p>\n\n <p>Companies:</p>\n <div>\n <img class=\"logo\" src=\"images/logo.gif\" alt=\"Madgex company logo\" />\n <img class=\"logo\" src=\"images/logo.gif\" alt=\"Web Feet Media company logo\" />\n </div>\n <ul>\n <li><a class=\"url org\" href=\"http://www.madgex.com/\">Madgex</a> <span class=\"title\">Creative Director</span></li>\n <li><a class=\"url org\" href=\"http://www.webfeetmedia.com/\">Web Feet Media Ltd</a> <span class=\"title\">Owner</span></li>\n </ul>\n \n <p>Tags: \n <a rel=\"tag\" class=\"category\" href=\"http://en.wikipedia.org/wiki/design\">design</a>, \n <a rel=\"tag\" class=\"category\" href=\"http://en.wikipedia.org/wiki/development\">development</a> and\n <a rel=\"tag\" class=\"category\" href=\"http://en.wikipedia.org/wiki/web\">web</a>\n </p>\n \n <p>Phone numbers:</p>\n <ul>\n <li class=\"tel\">\n <span class=\"type\">Work</span> (<span class=\"type\">pref</span>erred):\n <span class=\"value\">+1 415 555 100</span>\n </li>\n <li class=\"tel\"><span class=\"type\">Home</span>: <span class=\"value\">+1 415 555 200</span></li>\n <li class=\"tel\"><span class=\"type\">Postal</span>: <span class=\"value\">+1 415 555 300</span></li>\n </ul>\n \n <p>Emails:</p>\n <ul>\n <li><a class=\"email\" href=\"mailto:john.doe@madgex.com\">John Doe at Madgex</a></li>\n <li><a class=\"email\" href=\"mailto:john.doe@webfeetmedia.com\">John Doe at Web Feet Media</a></li>\n </ul>\n <p>John Doe uses <span class=\"mailer\">PigeonMail 2.1</span> or <span class=\"mailer\">Outlook 2007</span> for email.</p>\n\n <p>Addresses:</p>\n <ul>\n <li class=\"label\">\n <span class=\"adr\">\n <span class=\"type\">Work</span>: \n <span class=\"street-address\">North Street</span>, \n <span class=\"locality\">Brighton</span>, \n <span class=\"country-name\">United Kingdom</span>\n </span>\n \n </li>\n <li class=\"label\">\n <span class=\"adr\">\n <span class=\"type\">Home</span>: \n <span class=\"street-address\">West Street</span>, \n <span class=\"locality\">Brighton</span>, \n <span class=\"country-name\">United Kingdom</span>\n </span>\n </li>\n </ul>\n \n <p>In emergency contact: <span class=\"agent\">Jane Doe</span> or <span class=\"agent vcard\"><span class=\"fn\">Dave Doe</span></span>.</p>\n <p>Key: <span class=\"key\">hd02$Gfu*d%dh87KTa2=23934532479</span></p>\n</div>","name":"mf-v1-hcard-multiple"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"honorific-prefix\": [\"Dr\"],\n \"given-name\": [\"John\"],\n \"additional-name\": [\"Peter\"],\n \"family-name\": [\"Doe\"],\n \"honorific-suffix\": [\"MSc\", \"PHD\"],\n \"photo\": [\"http://example.com/images/logo.gif\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<base href=\"http://example.com\">\n<div class=\"vcard\">\n <div class=\"name\">\n <span class=\"honorific-prefix\">Dr</span> \n <span class=\"given-name\">John</span> \n <abbr class=\"additional-name\" title=\"Peter\">P</abbr> \n <span class=\"family-name\">Doe</span> \n <data class=\"honorific-suffix\" value=\"MSc\"></data>\n <img class=\"photo honorific-suffix\" src=\"images/logo.gif\" alt=\"PHD\" />\n </div>\n</div>","name":"mf-v1-hcard-name"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"John Doe\"],\n \"given-name\": [\"John\"],\n \"sort-string\": [\"John\"],\n \"bday\": [\"2000-01-01 00:00:00-08:00\"],\n \"role\": [\"Designer\"],\n \"geo\": [{\n \"value\": \"30.267991;-97.739568\",\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"name\": [\"30.267991;-97.739568\"]\n }\n }],\n \"tz\": [\"-05:00\"],\n \"uid\": [\"http://example.com/profiles/johndoe\"],\n \"class\": [\"Public\"],\n \"rev\": [\"2008-01-01 13:45:00\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vcard\">\n \n <div class=\"fn n\"><span class=\"given-name sort-string\">John</span> Doe</div>\n <div>Birthday: <abbr class=\"bday\" title=\"2000-01-01T00:00:00-08:00\">January 1st, 2000</abbr></div>\n <div>Role: <span class=\"role\">Designer</span></div>\n <div>Location: <abbr class=\"geo\" title=\"30.267991;-97.739568\">Brighton</abbr></div>\n <div>Time zone: <abbr class=\"tz\" title=\"-05:00\">Eastern Standard Time</abbr></div>\n \n <div>Profile details:\n <div>Profile id: <span class=\"uid\">http://example.com/profiles/johndoe</span></div>\n <div>Details are: <span class=\"class\">Public</span></div>\n <div>Last updated: <abbr class=\"rev\" title=\"2008-01-01T13:45:00\">January 1st, 2008 - 13:45</abbr></div>\n </div>\n </div>","name":"mf-v1-hcard-single"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service\",\n \"html\": \"\\n <p class=\\\"entry-summary\\\">Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.</p>\\n\\n <p>The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service </p>\\n \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"],\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"hentry\">\n <h1><a class=\"entry-title\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"entry-content\">\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n </p>\n</div>","name":"mf-v1-hentry-summarycontent"},{"json":"{\n \"items\": [{\n \"type\": [\"h-feed\"],\n \"properties\": {\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }],\n \"url\": [\"http://microformats.org/blog\"],\n \"photo\": [\"http://example.com/photo.jpeg\"],\n \"category\": [\"microformats\", \"html\"]\n },\n \"children\": [{\n \"value\": \"microformats.org at 7\\n\\t \\n\\t Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.\\n\\t\\n\\t The microformats tagline “humans first, machines second” \\n\\t forms the basis of many of our \\n\\t principles, and \\n\\t in that regard, we’d like to recognize a few people and \\n\\t thank them for their years of volunteer service \\n\\t \\n\\t Updated \\n\\t June 25th, 2012\",\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.\\n\\t\\n\\t The microformats tagline “humans first, machines second” \\n\\t forms the basis of many of our \\n\\t principles, and \\n\\t in that regard, we’d like to recognize a few people and \\n\\t thank them for their years of volunteer service\",\n \"html\": \"\\n\\t <p class=\\\"entry-summary\\\">Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.</p>\\n\\t\\n\\t <p>The microformats tagline “humans first, machines second” \\n\\t forms the basis of many of our \\n\\t <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n\\t in that regard, we’d like to recognize a few people and \\n\\t thank them for their years of volunteer service </p>\\n\\t \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"]\n }\n }]\n }],\n \"rels\": {\n \"tag\": [\"http://example.com/tags/microformats\", \"http://example.com/tags/html\"],\n \"bookmark\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"]\n },\n \"rel-urls\": {\n \"http://example.com/tags/microformats\": {\n \"text\": \"microformats\",\n \"rels\": [\"tag\"]\n },\n \"http://example.com/tags/html\": {\n \"text\": \"html\",\n \"rels\": [\"tag\"]\n },\n \"http://microformats.org/2012/06/25/microformats-org-at-7\": {\n \"text\": \"microformats.org at 7\",\n \"rels\": [\"bookmark\"]\n }\n }\n}","html":"<section class=\"hfeed\">\n\t<h1 class=\"name\">Microformats blog</h1>\n\t<span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n\t<a class=\"url\" href=\"http://microformats.org/blog\">permlink</a>\n\t<img class=\"photo\" src=\"photo.jpeg\"/>\n\t<p>\n\t\tTags: <a rel=\"tag\" href=\"tags/microformats\">microformats</a>, \n\t\t<a rel=\"tag\" href=\"tags/html\">html</a>\n\t</p>\n\t\n\t<div class=\"hentry\">\n\t <h1><a class=\"entry-title\" rel=\"bookmark\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n\t <div class=\"entry-content\">\n\t <p class=\"entry-summary\">Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.</p>\n\t\n\t <p>The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service </p>\n\t </div> \n\t <p>Updated \n\t <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time>\n\t </p>\n\t</div>\n\t\n</section>","name":"mf-v1-hfeed-simple"},{"json":"\n{\n \"items\": [{\n \"type\": [\"h-news\"],\n \"properties\": {\n \"entry\": [{\n \"value\": \"microformats.org at 7\",\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service\",\n \"html\": \"\\n <p class=\\\"entry-summary\\\">Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.</p>\\n\\n <p>The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service </p>\\n \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"],\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }]\n }\n }],\n \"dateline\": [{\n \"value\": \"San Francisco, \\n CA\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"adr\": [{\n \"value\": \"San Francisco, \\n CA\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"]\n }\n }]\n }\n }],\n \"geo\": [{\n \"value\": \"37.774921;-122.445202\",\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"name\": [\"37.774921;-122.445202\"]\n }\n }],\n \"source-org\": [{\n \"value\": \"microformats.org\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"microformats.org\"],\n \"org\": [\"microformats.org\"],\n \"url\": [\"http://microformats.org/\"]\n }\n }],\n \"principles\": [\"http://microformats.org/wiki/Category:public_domain_license\"]\n }\n }],\n \"rels\": {\n \"bookmark\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"principles\": [\"http://microformats.org/wiki/Category:public_domain_license\"]\n },\n \"rel-urls\": {\n \"http://microformats.org/2012/06/25/microformats-org-at-7\": {\n \"text\": \"microformats.org at 7\",\n \"rels\": [\"bookmark\"]\n },\n \"http://microformats.org/wiki/Category:public_domain_license\": {\n \"text\": \"Publishing policy\",\n \"rels\": [\"principles\"]\n }\n }\n}","html":"<div class=\"hnews\">\n <div class=\"entry hentry\">\n <h1><a class=\"entry-title\" rel=\"bookmark\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"entry-content\">\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n </p>\n </div>\n\n <p>\n <span class=\"dateline vcard\">\n <span class=\"adr\">\n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n </span>\n </span>\n (Geo: <span class=\"geo\">37.774921;-122.445202</span>) \n <span class=\"source-org vcard\">\n <a class=\"fn org url\" href=\"http://microformats.org/\">microformats.org</a>\n </span>\n </p>\n <p>\n <a rel=\"principles\" href=\"http://microformats.org/wiki/Category:public_domain_license\">Publishing policy</a>\n </p>\n</div>","name":"mf-v1-hnews-all"},{"json":"\n{\n \"items\": [{\n \"type\": [\"h-news\"],\n \"properties\": {\n \"entry\": [{\n \"value\": \"microformats.org at 7\",\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service\",\n \"html\": \"\\n <p class=\\\"entry-summary\\\">Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.</p>\\n\\n <p>The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service </p>\\n \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"],\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }]\n }\n }],\n \"source-org\": [{\n \"value\": \"microformats.org\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"microformats.org\"],\n \"org\": [\"microformats.org\"],\n \"url\": [\"http://microformats.org/\"]\n }\n }]\n }\n }],\n \"rels\": {\n \"bookmark\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"]\n },\n \"rel-urls\": {\n \"http://microformats.org/2012/06/25/microformats-org-at-7\": {\n \"text\": \"microformats.org at 7\",\n \"rels\": [\"bookmark\"]\n }\n }\n}","html":"<div class=\"hnews\">\n <div class=\"entry hentry\">\n <h1><a class=\"entry-title\" rel=\"bookmark\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"entry-content\">\n <p class=\"entry-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <span class=\"author vcard\"><a class=\"fn url\" href=\"http://tantek.com/\">Tantek</a></span>\n </p>\n </div>\n\n <p class=\"source-org vcard\">\n <a class=\"fn org url\" href=\"http://microformats.org/\">microformats.org</a> \n </p>\n</div>","name":"mf-v1-hnews-minimum"},{"json":"{\n \"items\": [{\n \"type\": [\"h-product\"],\n \"properties\": {\n \"name\": [\"Raspberry Pi\"],\n \"photo\": [\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\"],\n \"description\": [{\n \"value\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\",\n \"html\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\"\n }],\n \"url\": [\"http://www.raspberrypi.org/\"],\n \"price\": [\"£29.95\"],\n \"review\": [{\n \"value\": \"9.2 out of \\n 10 \\n based on 178 reviews\",\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"rating\": [\"9.2\"],\n \"average\": [\"9.2\"],\n \"best\": [\"10\"],\n \"count\": [\"178\"]\n }\n }],\n \"category\": [\"Computer\", \"Education\"],\n \"brand\": [{\n \"value\": \"The Raspberry Pi Foundation\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"The Raspberry Pi Foundation\"],\n \"org\": [\"The Raspberry Pi Foundation\"],\n \"adr\": [{\n \"value\": \"Cambridge \\n UK\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"Cambridge\"],\n \"country-name\": [\"UK\"]\n }\n }]\n }\n }]\n }\n }],\n \"rels\": {\n \"tag\": [\"http://en.wikipedia.org/wiki/computer\", \"http://en.wikipedia.org/wiki/education\"]\n },\n \"rel-urls\": {\n \"http://en.wikipedia.org/wiki/computer\": {\n \"text\": \"Computer\",\n \"rels\": [\"tag\"]\n },\n \"http://en.wikipedia.org/wiki/education\": {\n \"text\": \"Education\",\n \"rels\": [\"tag\"]\n }\n }\n}","html":"<meta charset=\"utf-8\">\n<div class=\"hproduct\">\n <h2 class=\"fn\">Raspberry Pi</h2>\n <img class=\"photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"price\">£29.95</p>\n <p class=\"review hreview-aggregate\">\n <span class=\"rating\">\n <span class=\"average value\">9.2</span> out of \n <span class=\"best\">10</span> \n based on <span class=\"count\">178</span> reviews\n </span>\n </p>\n <p>Categories: \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/computer\" class=\"category\">Computer</a>, \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/education\" class=\"category\">Education</a>\n </p>\n <p class=\"brand vcard\">From: \n <span class=\"fn org\">The Raspberry Pi Foundation</span> - \n <span class=\"adr\">\n <span class=\"locality\">Cambridge</span> \n <span class=\"country-name\">UK</span>\n </span>\n </p>\n</div>","name":"mf-v1-hproduct-aggregate"},{"json":"{\n \"items\": [{\n \"type\": [\"h-product\"],\n \"properties\": {\n \"name\": [\"Raspberry Pi\"],\n \"photo\": [\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\"],\n \"description\": [{\n \"value\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\",\n \"html\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\"\n }],\n \"url\": [\"http://www.raspberrypi.org/\"],\n \"price\": [\"£29.95\"],\n \"category\": [\"Computer\", \"Education\"],\n \"review\": [{\n \"value\": \"4.5 out of 5\",\n \"type\": [\"h-review\"],\n \"properties\": {\n \"rating\": [\"4.5\"]\n }\n }]\n }\n }],\n \"rels\": {\n \"tag\": [\"http://en.wikipedia.org/wiki/computer\", \"http://en.wikipedia.org/wiki/education\"]\n },\n \"rel-urls\": {\n \"http://en.wikipedia.org/wiki/computer\": {\n \"text\": \"Computer\",\n \"rels\": [\"tag\"]\n },\n \"http://en.wikipedia.org/wiki/education\": {\n \"text\": \"Education\",\n \"rels\": [\"tag\"]\n }\n }\n}","html":"<meta charset=\"utf-8\">\n<div class=\"hproduct\">\n <h2 class=\"fn\">Raspberry Pi</h2>\n <img class=\"photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"price\">£29.95</p>\n <p class=\"review hreview\"><span class=\"rating\">4.5</span> out of 5</p>\n <p>Categories: \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/computer\" class=\"category\">Computer</a>, \n <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/education\" class=\"category\">Education</a>\n </p>\n</div>","name":"mf-v1-hproduct-simpleproperties"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"contact\": [{\n \"value\": \"Tim Berners-Lee\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"]\n }\n }],\n \"summary\": [\"invented the World Wide Web\"],\n \"affiliation\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"W3C\"],\n \"photo\": [\"http://www.w3.org/Icons/WWW/w3c_home_nb.png\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"hresume\">\n <p>\n <span class=\"contact vcard\"><span class=\"fn\">Tim Berners-Lee</span></span>, \n <span class=\"summary\">invented the World Wide Web</span>.\n </p>\n Belongs to following groups:\n <p> \n <a class=\"affiliation vcard\" href=\"http://www.w3.org/\">\n <img class=\"fn photo\" alt=\"W3C\" src=\"http://www.w3.org/Icons/WWW/w3c_home_nb.png\" />\n </a>\n </p> \n</div>","name":"mf-v1-hresume-affiliation"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"contact\": [{\n \"value\": \"Tim Berners-Lee\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"org\": [\"MIT\"],\n \"adr\": [{\n \"value\": \"32 Vassar Street, \\n Room 32-G524, \\n Cambridge, \\n MA \\n 02139, \\n USA. \\n (Work)\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"32 Vassar Street\"],\n \"extended-address\": [\"Room 32-G524\"],\n \"locality\": [\"Cambridge\"],\n \"region\": [\"MA\"],\n \"postal-code\": [\"02139\"],\n \"country-name\": [\"USA\"]\n }\n }],\n \"tel\": [\"+1 (617) 253 5702\"],\n \"email\": [\"mailto:timbl@w3.org\"]\n }\n }],\n \"summary\": [\"Invented the World Wide Web.\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"hresume\">\n <div class=\"contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"org\">MIT</p>\n <p class=\"adr\">\n <span class=\"street-address\">32 Vassar Street</span>, \n <span class=\"extended-address\">Room 32-G524</span>, \n <span class=\"locality\">Cambridge</span>, \n <span class=\"region\">MA</span> \n <span class=\"postal-code\">02139</span>, \n <span class=\"country-name\">USA</span>. \n (<span class=\"type\">Work</span>)\n </p>\n <p>Tel:<span class=\"tel\">+1 (617) 253 5702</span></p>\n <p>Email:<a class=\"email\" href=\"mailto:timbl@w3.org\">timbl@w3.org</a></p>\n </div>\n <p class=\"summary\">Invented the World Wide Web.</p>\n</div>","name":"mf-v1-hresume-contact"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"contact\": [{\n \"value\": \"Tim Berners-Lee\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"job-title\": [\"Director of the World Wide Web Foundation\"]\n }\n }],\n \"summary\": [\"Invented the World Wide Web.\"],\n \"education\": [{\n \"value\": \"The Queen's College, Oxford University\",\n \"type\": [\"h-event\", \"h-card\"],\n \"properties\": {\n \"name\": [\"The Queen's College, Oxford University\"],\n \"org\": [\"The Queen's College, Oxford University\"],\n \"description\": [\"BA Hons (I) Physics\"],\n \"start\": [\"1973-09\"],\n \"end\": [\"1976-06\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"hresume\">\n <div class=\"contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"summary\">Invented the World Wide Web.</p><hr />\n <p class=\"education vevent vcard\">\n <span class=\"fn summary org\">The Queen's College, Oxford University</span>, \n <span class=\"description\">BA Hons (I) Physics</span> \n <time class=\"dtstart\" datetime=\"1973-09\">1973</time> –\n <time class=\"dtend\" datetime=\"1976-06\">1976</time>\n </p>\n</div>","name":"mf-v1-hresume-education"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"contact\": [{\n \"value\": \"Tim Berners-Lee\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"]\n }\n }],\n \"summary\": [\"invented the World Wide Web\"],\n \"skill\": [\"information systems\", \"advocacy\", \"leadership\"]\n }\n }],\n \"rels\": {\n \"tag\": [\"http://example.com/skills/informationsystems\", \"http://example.com/skills/advocacy\", \"http://example.com/skills/leadership\"]\n },\n \"rel-urls\": {\n \"http://example.com/skills/informationsystems\": {\n \"text\": \"information systems\",\n \"rels\": [\"tag\"]\n },\n \"http://example.com/skills/advocacy\": {\n \"text\": \"advocacy\",\n \"rels\": [\"tag\"]\n },\n \"http://example.com/skills/leadership\": {\n \"text\": \"leadership\",\n \"rels\": [\"tag\"]\n }\n }\n}","html":"<div class=\"hresume\"> \n <p>\n <span class=\"contact vcard\"><span class=\"fn\">Tim Berners-Lee</span></span>, \n <span class=\"summary\">invented the World Wide Web</span>.\n </p>\n Skills: \n <ul>\n <li><a class=\"skill\" rel=\"tag\" href=\"http://example.com/skills/informationsystems\">information systems</a></li>\n <li><a class=\"skill\" rel=\"tag\" href=\"http://example.com/skills/advocacy\">advocacy</a></li>\n <li><a class=\"skill\" rel=\"tag\" href=\"http://example.com/skills/leadership\">leadership</a></li>\n </ul>\n</div>","name":"mf-v1-hresume-skill"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"contact\": [{\n \"value\": \"Tim Berners-Lee\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"job-title\": [\"Director of the World Wide Web Foundation\"]\n }\n }],\n \"summary\": [\"Invented the World Wide Web.\"],\n \"experience\": [{\n \"value\": \"World Wide Web Foundation\",\n \"type\": [\"h-event\", \"h-card\"],\n \"properties\": {\n \"job-title\": [\"Director\"],\n \"name\": [\"World Wide Web Foundation\"],\n \"org\": [\"World Wide Web Foundation\"],\n \"url\": [\"http://www.webfoundation.org/\"],\n \"start\": [\"2009-01-18\"],\n \"duration\": [\"P2Y11M\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"hresume\">\n <div class=\"contact vcard\">\n <p class=\"fn\">Tim Berners-Lee</p>\n <p class=\"title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"summary\">Invented the World Wide Web.</p><hr />\n <div class=\"experience vevent vcard\">\n <p class=\"title\">Director</p>\n <p><a class=\"fn summary org url\" href=\"http://www.webfoundation.org/\">World Wide Web Foundation</a></p>\n <p>\n <time class=\"dtstart\" datetime=\"2009-01-18\">Jan 2009</time> – Present\n <time class=\"duration\" datetime=\"P2Y11M\">(2 years 11 month)</time>\n </p>\n </div>\n</div>","name":"mf-v1-hresume-work"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Crepes on Cole\",\n \"type\": [\"h-item\"],\n \"properties\": {\n \"photo\": [\"http://example.com/images/photo.gif\"],\n \"name\": [\"Crepes on Cole\"],\n \"url\": [\"http://example.com/crepeoncole\"]\n }\n }],\n \"rating\": [\"5\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<base href=\"http://example.com\">\n<div class=\"hreview\">\n <p class=\"item\">\n <img class=\"photo\" src=\"images/photo.gif\" />\n <a class=\"fn url\" href=\"http://example.com/crepeoncole\">Crepes on Cole</a>\n </p>\n <p><span class=\"rating\">5</span> out of 5 stars</p>\n</div>","name":"mf-v1-hreview-item"},{"json":"\n{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"rating\": [\"5\"],\n \"name\": [\"Crepes on Cole is awesome\"],\n \"reviewer\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"]\n }\n }],\n \"description\": [{\n \"value\": \"Crepes on Cole is one of the best little \\n creperies in San Francisco.\\n Excellent food and service. Plenty of tables in a variety of sizes \\n for parties large and small. Window seating makes for excellent \\n people watching to/from the N-Judah which stops right outside. \\n I've had many fun social gatherings here, as well as gotten \\n plenty of work done thanks to neighborhood WiFi.\",\n \"html\": \"\\n <p class=\\\"item vcard\\\">\\n <span class=\\\"fn org\\\">Crepes on Cole</span> is one of the best little \\n creperies in <span class=\\\"adr\\\"><span class=\\\"locality\\\">San Francisco</span></span>.\\n Excellent food and service. Plenty of tables in a variety of sizes \\n for parties large and small. Window seating makes for excellent \\n people watching to/from the N-Judah which stops right outside. \\n I've had many fun social gatherings here, as well as gotten \\n plenty of work done thanks to neighborhood WiFi.\\n </p>\\n \"\n }],\n \"item\": [{\n \"value\": \"Crepes on Cole\",\n \"type\": [\"h-item\", \"h-card\"],\n \"properties\": {\n \"name\": [\"Crepes on Cole\"],\n \"org\": [\"Crepes on Cole\"],\n \"adr\": [{\n \"value\": \"San Francisco\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"San Francisco\"]\n }\n }]\n }\n }],\n \"category\": [\"crepe\"],\n \"url\": [\"http://example.com/crepe\"]\n }\n }],\n \"rels\": {\n \"tag\": [\"http://en.wikipedia.org/wiki/crepe\"],\n \"self\": [\"http://example.com/crepe\"],\n \"bookmark\": [\"http://example.com/crepe\"],\n \"license\": [\"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\"]\n },\n \"rel-urls\": {\n \"http://en.wikipedia.org/wiki/crepe\": {\n \"text\": \"crepe\",\n \"rels\": [\"tag\"]\n },\n \"http://example.com/crepe\": {\n \"text\": \"http://example.com/crepe\",\n \"rels\": [\"self\", \"bookmark\"]\n },\n \"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\": {\n \"text\": \"Creative Commons Attribution-ShareAlike License\",\n \"rels\": [\"license\"]\n }\n }\n}","html":"<div class=\"hreview\">\n <span><span class=\"rating\">5</span> out of 5 stars</span>\n <h4 class=\"summary\">Crepes on Cole is awesome</h4>\n <span class=\"reviewer vcard\">\n Reviewer: <span class=\"fn\">Tantek</span> - \n </span>\n <time class=\"reviewed\" datetime=\"2005-04-18\">April 18, 2005</time>\n <div class=\"description\">\n <p class=\"item vcard\">\n <span class=\"fn org\">Crepes on Cole</span> is one of the best little \n creperies in <span class=\"adr\"><span class=\"locality\">San Francisco</span></span>.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.\n </p>\n </div>\n <p>Visit date: <span>April 2005</span></p>\n <p>Food eaten: <a rel=\"tag\" href=\"http://en.wikipedia.org/wiki/crepe\">crepe</a></p>\n <p>Permanent link for review: <a rel=\"self bookmark\" href=\"http://example.com/crepe\">http://example.com/crepe</a></p>\n <p><a rel=\"license\" href=\"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a></p>\n</div>","name":"mf-v1-hreview-vcard"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Mediterranean Wraps\",\n \"type\": [\"h-item\", \"h-card\"],\n \"properties\": {\n \"name\": [\"Mediterranean Wraps\"],\n \"org\": [\"Mediterranean Wraps\"],\n \"adr\": [{\n \"value\": \"433 S California Ave, \\n Palo Alto, \\n CA\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"433 S California Ave\"],\n \"locality\": [\"Palo Alto\"],\n \"region\": [\"CA\"]\n }\n }],\n \"tel\": [\"(650) 321-8189\"]\n }\n }],\n \"rating\": [\"9.2\"],\n \"average\": [\"9.2\"],\n \"best\": [\"10\"],\n \"count\": [\"17\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"hreview-aggregate\">\n <div class=\"item vcard\">\n <h3 class=\"fn org\">Mediterranean Wraps</h3> \n <p>\n <span class=\"adr\">\n <span class=\"street-address\">433 S California Ave</span>, \n <span class=\"locality\">Palo Alto</span>, \n <span class=\"region\">CA</span></span> - \n \n <span class=\"tel\">(650) 321-8189</span>\n </p>\n </div> \n <p class=\"rating\">\n <span class=\"average value\">9.2</span> out of \n <span class=\"best\">10</span> \n based on <span class=\"count\">17</span> reviews\n </p>\n</div>","name":"mf-v1-hreview-aggregate-hcard"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Mediterranean Wraps\",\n \"type\": [\"h-item\"],\n \"properties\": {\n \"name\": [\"Mediterranean Wraps\"],\n \"url\": [\"http://example.com/mediterraneanwraps\"]\n }\n }],\n \"rating\": [\"4.5\"],\n \"count\": [\"6\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}\n","html":"<p class=\"hreview-aggregate\">\n <span class=\"item\">\n <a class=\"fn url\" href=\"http://example.com/mediterraneanwraps\">Mediterranean Wraps</a>\n </span> - Rated: \n <span class=\"rating\">4.5</span> out of 5 (<span class=\"count\">6</span> reviews)\n</p>","name":"mf-v1-hreview-aggregate-justahyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Fullfrontal\",\n \"type\": [\"h-item\", \"h-event\"],\n \"properties\": {\n \"name\": [\"Fullfrontal\"],\n \"description\": [\"A one day JavaScript Conference held in Brighton\"],\n \"start\": [\"2012-11-09\"]\n }\n }],\n \"rating\": [\"9.9\"],\n \"average\": [\"9.9\"],\n \"best\": [\"10\"],\n \"count\": [\"62\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"hreview-aggregate\">\n <div class=\"item vevent\">\n <h3 class=\"summary\">Fullfrontal</h3>\n <p class=\"description\">A one day JavaScript Conference held in Brighton</p>\n <p><time class=\"dtstart\" datetime=\"2012-11-09\">9th November 2012</time></p> \n </div> \n \n <p class=\"rating\">\n <span class=\"average value\">9.9</span> out of \n <span class=\"best\">10</span> \n based on <span class=\"count\">62</span> reviews\n </p>\n</div>","name":"mf-v1-hreview-aggregate-vevent"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"org\": [\"Mozilla\"],\n \"adr\": [{\n \"value\": \"665 3rd St. \\n Suite 207 \\n San Francisco, \\n CA \\n 94107 \\n U.S.A.\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"665 3rd St.\"],\n \"extended-address\": [\"Suite 207\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94107\"],\n \"country-name\": [\"U.S.A.\"]\n }\n }]\n }\n }, {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"org\": [\"Mozilla\"],\n \"adr\": [{\n \"value\": \"665 3rd St. \\n Suite 207 \\n San Francisco, \\n CA \\n 94107 \\n U.S.A.\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"665 3rd St.\"],\n \"extended-address\": [\"Suite 207\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94107\"],\n \"country-name\": [\"U.S.A.\"]\n }\n }]\n }\n }, {\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"665 3rd St.\"],\n \"extended-address\": [\"Suite 207\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94107\"],\n \"country-name\": [\"U.S.A.\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vcard\" itemref=\"mozilla-org mozilla-adr\">\n <span class=\"name\">Brendan Eich</span>\n</div>\n<div class=\"vcard\" itemref=\"mozilla-org mozilla-adr\">\n <span class=\"name\">Mitchell Baker</span>\n</div>\n\n<p id=\"mozilla-org\" class=\"org\">Mozilla</p>\n<p id=\"mozilla-adr\" class=\"adr\">\n <span class=\"street-address\">665 3rd St.</span> \n <span class=\"extended-address\">Suite 207</span> \n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span> \n <span class=\"postal-code\">94107</span> \n <span class=\"country-name\">U.S.A.</span> \n</p>","name":"mf-v1-includes-hcarditemref"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"location\": [{\n \"value\": \"Room 10\\n \\n Moscone Center, \\n San Francisco\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"extended-address\": [\"Room 10\", \"Moscone Center\"],\n \"locality\": [\"San Francisco\"]\n }\n }],\n \"start\": [\"2012-06-27 15:45:00-08:00\"],\n \"end\": [\"2012-06-27 16:45:00-08:00\"]\n }\n }, {\n \"type\": [\"h-event\"],\n \"properties\": {\n \"location\": [{\n \"value\": \"Room 11\\n \\n Moscone Center, \\n San Francisco\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"extended-address\": [\"Room 11\", \"Moscone Center\"],\n \"locality\": [\"San Francisco\"]\n }\n }],\n \"start\": [\"2012-06-27 15:45:00-08:00\"],\n \"end\": [\"2012-06-27 16:45:00-08:00\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vevent\" itemref=\"io-session07\">\n <span class=\"name\">Monetizing Android Apps</span> - spaekers: \n <span class=\"speaker\">Chrix Finne</span>, \n <span class=\"speaker\">Kenneth Lui</span> - \n <span itemref=\"io-location\" class=\"location adr\">\n <span class=\"extended-address\">Room 10</span>\n </span> \n</div>\n<div class=\"vevent\" itemref=\"io-session07\">\n <span class=\"name\">New Low-Level Media APIs in Android</span> - spaekers: \n <span class=\"speaker\">Dave Burke</span> -\n <span itemref=\"io-location\" class=\"location adr\">\n <span class=\"extended-address\">Room 11</span>\n </span> \n</div>\n\n<p id=\"io-session07\">\n Session 01 is between: \n <time class=\"dtstart\" datetime=\"2012-06-27T15:45:00-0800\">3:45PM</time> to \n <time class=\"dtend\" datetime=\"2012-06-27T16:45:00-0800\">4:45PM</time> \n</p> \n<p id=\"io-location\">\n <span class=\"extended-address\">Moscone Center</span>, \n <span class=\"locality\">San Francisco</span> \n</p>","name":"mf-v1-includes-heventitemref"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"org\": [\"Twitter\"],\n \"adr\": [{\n \"value\": \"1355 Market St,\\n San Francisco, \\n CA\\n 94103\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"1355 Market St\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94103\"]\n }\n }]\n }\n }, {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"org\": [\"Twitter\"],\n \"adr\": [{\n \"value\": \"1355 Market St,\\n San Francisco, \\n CA\\n 94103\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"1355 Market St\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94103\"]\n }\n }]\n }\n }, {\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"1355 Market St\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94103\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vcard\">\n <span class=\"name\">Ben Ward</span>\n <a class=\"include\" href=\"#twitter\">Twitter</a>\n</div>\n<div class=\"vcard\">\n <span class=\"name\">Dan Webb</span>\n <a class=\"include\" href=\"#twitter\">Twitter</a>\n</div>\n\n<div id=\"twitter\">\n <p class=\"org\">Twitter</p>\n <p class=\"adr\">\n <span class=\"street-address\">1355 Market St</span>,\n <span class=\"locality\">San Francisco</span>, \n <span class=\"region\">CA</span>\n <span class=\"postal-code\">94103</span>\n </p>\n</div>","name":"mf-v1-includes-hyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"start\": [\"2012-10-30 11:45:00-08:00\"],\n \"name\": [\"Build Conference\"],\n \"location\": [{\n \"value\": \"Redmond, \\n Washington, \\n USA\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"Redmond\"],\n \"region\": [\"Washington\"],\n \"country-name\": [\"USA\"]\n }\n }]\n }\n }, {\n \"type\": [\"h-event\"],\n \"properties\": {\n \"start\": [\"2012-10-31 11:15:00-08:00\"],\n \"name\": [\"Build Conference\"],\n \"location\": [{\n \"value\": \"Redmond, \\n Washington, \\n USA\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"Redmond\"],\n \"region\": [\"Washington\"],\n \"country-name\": [\"USA\"]\n }\n }]\n }\n }, {\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"Redmond\"],\n \"region\": [\"Washington\"],\n \"country-name\": [\"USA\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"vevent\">\n <span class=\"name\">HTML5 & CSS3 latest features in action!</span> - \n <span class=\"speaker\">David Rousset</span> -\n <time class=\"dtstart\" datetime=\"2012-10-30T11:45:00-08:00\">Tue 11:45am</time>\n <object data=\"#buildconf\" class=\"include\" type=\"text/html\" height=\"0\" width=\"0\"></object>\n</div>\n<div class=\"vevent\">\n <span class=\"name\">Building High-Performing JavaScript for Modern Engines</span> -\n <span class=\"speaker\">John-David Dalton</span> and \n <span class=\"speaker\">Amanda Silver</span> -\n <time class=\"dtstart\" datetime=\"2012-10-31T11:15:00-08:00\">Wed 11:15am</time>\n <object data=\"#buildconf\" class=\"include\" type=\"text/html\" height=\"0\" width=\"0\"></object>\n</div>\n\n\n<div id=\"buildconf\">\n <p class=\"summary\">Build Conference</p>\n <p class=\"location adr\">\n <span class=\"locality\">Redmond</span>, \n <span class=\"region\">Washington</span>, \n <span class=\"country-name\">USA</span>\n </p>\n</div>","name":"mf-v1-includes-object"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Chris Mills\"],\n \"url\": [\"http://dev.opera.com/\"],\n \"org\": [\"Opera\"]\n }\n }, {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Erik Möller\"],\n \"url\": [\"http://dev.opera.com/\"],\n \"org\": [\"Opera\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<table>\n <tr>\n <th id=\"org\"><a class=\"url org\" href=\"http://dev.opera.com/\">Opera</a></th>\n </tr>\n <tr>\n <td class=\"vcard\" headers=\"org\"><span class=\"fn\">Chris Mills</span></td>\n </tr>\n <tr>\n <td class=\"vcard\" headers=\"org\"><span class=\"fn\">Erik Möller</span></td>\n </tr>\n </table>","name":"mf-v1-includes-table"},{"json":"{\n \"items\": [{\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"name\": [\"Bricklayer's Arms\"],\n \"label\": [\"3 Charlotte Road, \\n City of London, \\n EC2A 3PE, \\n UK\"],\n \"street-address\": [\"3 Charlotte Road\"],\n \"locality\": [\"City of London\"],\n \"postal-code\": [\"EC2A 3PE\"],\n \"country-name\": [\"UK\"],\n \"geo\": [\"51.526421;-0.081067\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-adr\">\n <span class=\"p-name\">Bricklayer's Arms</span>\n <span class=\"p-label\"> \n <span class=\"p-street-address\">3 Charlotte Road</span>, \n <span class=\"p-locality\">City of London</span>, \n <span class=\"p-postal-code\">EC2A 3PE</span>, \n <span class=\"p-country-name\">UK</span> \n </span> – \n Geo:(<span class=\"p-geo\">51.526421;-0.081067</span>) \n</p>","name":"mf-v2-h-adr-geo"},{"json":"{\n \"items\": [{\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"name\": [\"Bricklayer's Arms\"],\n \"geo\": [\"geo:51.526421;-0.081067;crs=wgs84;u=40\"],\n \"locality\": [\"London\"],\n \"url\": [\"geo:51.526421;-0.081067;crs=wgs84;u=40\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-adr\">\n <a class=\"p-name u-geo\" href=\"geo:51.526421;-0.081067;crs=wgs84;u=40\">Bricklayer's Arms</a>, \n <span class=\"p-locality\">London</span> \n</p>","name":"mf-v2-h-adr-geourl"},{"json":"{\n \"items\": [{\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"name\": [\"665 3rd St. Suite 207 San Francisco, CA 94107 U.S.A.\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-adr\">665 3rd St. Suite 207 San Francisco, CA 94107 U.S.A.</p>","name":"mf-v2-h-adr-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"street-address\": [\"665 3rd St.\"],\n \"extended-address\": [\"Suite 207\"],\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"postal-code\": [\"94107\"],\n \"country-name\": [\"U.S.A.\"],\n \"name\": [\"665 3rd St. \\n Suite 207 \\n San Francisco, \\n CA \\n 94107 \\n U.S.A.\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-adr\">\n <span class=\"p-street-address\">665 3rd St.</span> \n <span class=\"p-extended-address\">Suite 207</span> \n <span class=\"p-locality\">San Francisco</span>, \n <span class=\"p-region\">CA</span> \n <span class=\"p-postal-code\">94107</span> \n <span class=\"p-country-name\">U.S.A.</span> \n</p>","name":"mf-v2-h-adr-simpleproperties"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\", \"h-as-note\"],\n \"properties\": {\n \"in-reply-to\": [{\n \"value\": \"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\",\n \"type\": [\"h-cite\"],\n \"properties\": {\n \"name\": [\"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\"],\n \"url\": [\"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\"]\n }\n },\n {\n \"value\": \"https://twitter.com/benwerd/status/604733231284383744\",\n \"type\": [\"h-cite\"],\n \"properties\": {\n \"name\": [\"https://twitter.com/benwerd/status/604733231284383744\"],\n \"url\": [\"https://twitter.com/benwerd/status/604733231284383744\"]\n }\n }],\n \"author\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek Çelik\"],\n \"photo\": [\"http://tantek.com/images/photo.gif\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }],\n \"name\": [\"@benwerd\\n @erinjoalso proud of you &\\n @withknown— so much #indieweb & especially user empathy. Keep up the great work!\"],\n \"content\": [{\n \"value\": \"@benwerd\\n @erinjoalso proud of you &\\n @withknown— so much #indieweb & especially user empathy. Keep up the great work!\",\n \"html\": \"\\n <a class=\\\"auto-link h-x-username\\\" href=\\\"https://twitter.com/benwerd\\\">@benwerd</a>\\n <a class=\\\"auto-link h-x-username\\\" href=\\\"https://twitter.com/erinjo\\\">@erinjo</a>also proud of you &\\n <a class=\\\"auto-link h-x-username\\\" href=\\\"https://twitter.com/withknown\\\">@withknown</a>— so much #indieweb & especially user empathy. Keep up the great work!\"\n }],\n \"published\": [\"2015-06-01 22:20-07:00\"],\n \"updated\": [\"2015-06-01 22:20-07:00\"],\n \"url\": [\"http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy\"],\n \"uid\": [\"http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy\"],\n \"syndication\": [\"https://twitter.com/t/status/605604965566906369\"]\n },\n \"children\": [{\n \"value\": \"@benwerd\",\n \"type\": [\"h-x-username\"],\n \"properties\": {\n \"name\": [\"@benwerd\"],\n \"url\": [\"https://twitter.com/benwerd\"]\n }\n },\n {\n \"value\": \"@erinjo\",\n \"type\": [\"h-x-username\"],\n \"properties\": {\n \"name\": [\"@erinjo\"],\n \"url\": [\"https://twitter.com/erinjo\"]\n }\n },\n {\n \"value\": \"@withknown\",\n \"type\": [\"h-x-username\"],\n \"properties\": {\n \"name\": [\"@withknown\"],\n \"url\": [\"https://twitter.com/withknown\"]\n }\n }]\n }],\n \"rels\": {\n \"prev\": [\"http://tantek.com/152/t1/congrats-fellow-elected-w3cab-members\"],\n \"next\": [\"http://tantek.com/152/t3/going-indiewebcamp-2015-portland\"],\n \"in-reply-to\": [\"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\", \"https://twitter.com/benwerd/status/604733231284383744\"],\n \"author\": [\"http://tantek.com/\"],\n \"syndication\": [\"https://twitter.com/t/status/605604965566906369\"]\n },\n \"rel-urls\": {\n \"http://tantek.com/152/t1/congrats-fellow-elected-w3cab-members\": {\n \"title\": \"View the previous (older) item in the stream.\",\n \"text\": \"←\",\n \"rels\": [\"prev\"]\n },\n \"http://tantek.com/152/t3/going-indiewebcamp-2015-portland\": {\n \"title\": \"View the next (newer) item in the stream\",\n \"text\": \"→\",\n \"rels\": [\"next\"]\n },\n \"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\": {\n \"text\": \"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\",\n \"rels\": [\"in-reply-to\"]\n },\n \"https://twitter.com/benwerd/status/604733231284383744\": {\n \"text\": \"https://twitter.com/benwerd/status/604733231284383744\",\n \"rels\": [\"in-reply-to\"]\n },\n \"http://tantek.com/\": {\n \"title\": \"Tantek Çelik\",\n \"rels\": [\"author\"]\n },\n \"https://twitter.com/t/status/605604965566906369\": {\n \"text\": \"View \\n Conversation\\n on Twitter\",\n \"rels\": [\"syndication\"]\n }\n }\n}","html":"<!-- http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy -->\n<base href=\"http://tantek.com/\" />\n\n<li class=\"h-entry hentry h-as-note\">\n <div>\n <ul>\n <li>\n <a href=\"152/t1/congrats-fellow-elected-w3cab-members\" id=\"previtem\" title=\"View the previous (older) item in the stream.\"\n rel=\"prev\"><abbr title=\"Previous\">←</abbr></a>\n </li>\n <li>\n <a href=\"152/t3/going-indiewebcamp-2015-portland\" id=\"nextitem\" title=\"View the next (newer) item in the stream\" rel=\"next\"><abbr title=\"Next\">→</abbr></a>\n </li>\n </ul>\n </div>\n <div>In reply to:\n <p>\n <a class=\"u-in-reply-to h-cite\" rel=\"in-reply-to\" href=\"http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far\">http://werd.io/2015/im-super-proud-of-everything-weve-done-on-withknown-so-far</a>\n </p>\n <p>\n <a class=\"u-in-reply-to h-cite\" rel=\"in-reply-to\" href=\"https://twitter.com/benwerd/status/604733231284383744\">https://twitter.com/benwerd/status/604733231284383744</a>\n </p>\n <hr>\n </div>\n <a href=\"../\" class=\"p-author h-card\" rel=\"author\" title=\"Tantek Çelik\"><img src=\"/images/photo.gif\" alt=\"Tantek Çelik\"></a>\n <p class=\"p-name entry-title e-content entry-content article\">\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/benwerd\">@benwerd</a>\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/erinjo\">@erinjo</a>also proud of you &amp;\n <a class=\"auto-link h-x-username\" href=\"https://twitter.com/withknown\">@withknown</a>— so much #indieweb &amp; especially user empathy. Keep up the great work!</p>\n <span>\n <span class=\"dt-published published dt-updated updated\">\n <time class=\"value\" datetime=\"22:20-0700\">22:20</time>on\n <time class=\"value\">2015-06-01</time>\n </span>\n <span class=\"lt\">(ttk.me t4bT2)</span>using\n <span class=\"using\">BBEdit</span>\n </span>\n <div>\n <form action=\"http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy\">\n <div>\n <label>\n <span class=\"lt\">URL:</span>\n <input class=\"u-url url u-uid uid bookmark\" type=\"url\" size=\"70\" style=\"max-width:100%\" value=\"http://tantek.com/2015/152/t2/proud-withknown-indieweb-user-empathy\">\n </label>\n </div>\n </form>\n </div>\n <div>\n <a class=\"u-syndication\" rel=\"syndication\" style=\"float:right;\" href=\"https://twitter.com/t/status/605604965566906369\">\n <img src=\"/images/photo.gif\" style=\"vertical-align:-30%\" alt=\"\"> \n View \n Conversation\n on Twitter\n</a>\n </div>\n</li>","name":"mf-v2-h-as-note-note"},{"json":" {\n\t\"items\": [{\n \"type\": [\n \"h-card\"\n ],\n \"properties\": {\n \"name\": [\n \"Mitchell Baker\"\n ],\n \"url\": [\"http://blog.lizardwrangler.com/\"],\n \"org\": [{\n \"value\": \"Mozilla Foundation\",\n \"type\": [\n \"h-card\"\n ],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"],\n \"url\": [\"http://example.org/bios/mitchell-baker/\"]\n }\n }],\n \"photo\": [\"http://example.org/images/photo.gif\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}\n","html":"<base href=\"http://example.org\"/>\n<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card\" href=\"bios/mitchell-baker/\">Mozilla Foundation</a>)\n <img class=\"u-photo\" src=\"images/photo.gif\"/>\n</div>","name":"mf-v2-h-card-baseurl"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Håkon Wium Lie\"],\n \"photo\": [\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/H%C3%A5kon-Wium-Lie-2009-03.jpg/215px-H%C3%A5kon-Wium-Lie-2009-03.jpg\"],\n \"url\": [\"http://people.opera.com/howcome/\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<a class=\"h-card\" href=\"http://people.opera.com/howcome/\" title=\"Håkon Wium Lie, CTO Opera\">\n <article>\n <h2 class=\"p-name\">Håkon Wium Lie</h2>\n <img src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/H%C3%A5kon-Wium-Lie-2009-03.jpg/215px-H%C3%A5kon-Wium-Lie-2009-03.jpg\" />\n </article>\n</a>","name":"mf-v2-h-card-childimplied"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"photo\": [\"http://blog.mozilla.org/press/files/2012/04/mitchell-baker.jpg\"],\n \"url\": [\"http://blog.lizardwrangler.com/\", \"https://twitter.com/MitchellBaker\"],\n \"name\": [\"Mitchell Baker\"],\n \"org\": [\"Mozilla Foundation\"],\n \"note\": [\"Mitchell is responsible for setting the direction and scope of the Mozilla Foundation and its activities.\"],\n \"category\": [\"Strategy\", \"Leadership\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-card\">\n <img class=\"u-photo\" alt=\"photo of Mitchell\" src=\"http://blog.mozilla.org/press/files/2012/04/mitchell-baker.jpg\" />\n <p>\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a>\n (<a class=\"u-url\" href=\"https://twitter.com/MitchellBaker\">@MitchellBaker</a>)\n <span class=\"p-org\">Mozilla Foundation</span>\n </p>\n <p class=\"p-note\">Mitchell is responsible for setting the direction and scope of the Mozilla Foundation and its activities.</p>\n <p><span class=\"p-category\">Strategy</span> and <span class=\"p-category\">Leadership</span></p>\n</div>","name":"mf-v2-h-card-extendeddescription"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"url\": [\"http://blog.lizardwrangler.com/\"],\n \"name\": [\"Mitchell Baker\"],\n \"org\": [{\n \"value\": \"Mozilla Foundation\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"],\n \"url\": [\"http://mozilla.org/\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card\" href=\"http://mozilla.org/\">Mozilla Foundation</a>)\n</div>","name":"mf-v2-h-card-hcard"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Mitchell Baker\"],\n \"url\": [\"http://blog.lizardwrangler.com/\"],\n \"org\": [{\n \"value\": \"Mozilla Foundation\",\n \"type\": [\"h-card\", \"h-org\"],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"],\n \"url\": [\"http://mozilla.org/\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card h-org\" href=\"http://mozilla.org/\">Mozilla Foundation</a>)\n</div>","name":"mf-v2-h-card-horghcard"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Rohit Khare\"],\n \"photo\": [\"http://example.com/images/photo.gif\"],\n \"url\": [\"http://rohit.khare.org/\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-card\" href=\"http://rohit.khare.org/\">\n <img alt=\"Rohit Khare\" src=\"images/photo.gif\" />\n </a>","name":"mf-v2-h-card-hyperlinkedphoto"},{"json":"{ \n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Name\"]\n },\n \"children\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"John Doe\"],\n \"photo\": [\"http://example.com/john.html\"]\n }\n }]\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Name\"]\n },\n \"children\": [{\n \"value\": \"Name\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"John Doe\"],\n \"photo\": [\"http://example.com/john.html\"]\n }\n }]\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"\n<img class=\"h-card\" src=\"jane.html\" alt=\"Jane Doe\"/>\n<area class=\"h-card\" href=\"jane.html\" alt=\"Jane Doe\"></area>\n<abbr class=\"h-card\" title=\"Jane Doe\">JD</abbr>\n\n<div class=\"h-card\"><img src=\"jane.html\" alt=\"Jane Doe\"/></div>\n<div class=\"h-card\"><area href=\"jane.html\" alt=\"Jane Doe\"></area></div>\n<div class=\"h-card\"><abbr title=\"Jane Doe\">JD</abbr></div>\n\n<div class=\"h-card\"><span><img src=\"jane.html\" alt=\"Jane Doe\"/></span></div>\n<div class=\"h-card\"><span><area href=\"jane.html\" alt=\"Jane Doe\"></area></span></div>\n<div class=\"h-card\"><span><abbr title=\"Jane Doe\">JD</abbr></span></div>\n\n<div class=\"h-card\"><img class=\"h-card\" src=\"john.html\" alt=\"John Doe\"/>Name</div>\n<div class=\"h-card\"><span class=\"h-card\"><img src=\"john.html\" alt=\"John Doe\"/>Name</span></div>\n","name":"mf-v2-h-card-impliedname"},{"json":" {\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"]\n },\n \"children\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n }]\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"]\n },\n \"children\": [{\n \"value\": \"Jane Doe\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"photo\": [\"http://example.com/jane.jpeg\"]\n }\n }]\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<img class=\"h-card\" alt=\"Jane Doe\" src=\"jane.jpeg\"/>\n<object class=\"h-card\" data=\"jane.jpeg\"/>Jane Doe</object>\n\n<div class=\"h-card\"><img alt=\"Jane Doe\" src=\"jane.jpeg\"/></div> \n<div class=\"h-card\"><object data=\"jane.jpeg\"/>Jane Doe</object></div> \n\n<div class=\"h-card\"><span><img alt=\"Jane Doe\" src=\"jane.jpeg\"/></span></div> \n<div class=\"h-card\"><span><object data=\"jane.jpeg\"/>Jane Doe</object></span></div> \n\n<div class=\"h-card\"><img class=\"h-card\" alt=\"Jane Doe\" src=\"jane.jpeg\"/>Jane Doe</div> \n<div class=\"h-card\"><span class=\"h-card\"><object data=\"jane.jpeg\"/>Jane Doe</object></span></div> ","name":"mf-v2-h-card-impliedphoto"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n },\n {\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"]\n },\n \"children\": [{\n \"value\": \"Jane Doe\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Jane Doe\"],\n \"url\": [\"http://example.com/jane.html\"]\n }\n }]\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-card\" href=\"jane.html\">Jane Doe</a>\n<area class=\"h-card\" href=\"jane.html\" alt=\"Jane Doe\"/ >\n<div class=\"h-card\" ><a href=\"jane.html\">Jane Doe</a><p></p></div> \n<div class=\"h-card\" ><area href=\"jane.html\">Jane Doe</area><p></p></div>\n<div class=\"h-card\" ><a class=\"h-card\" href=\"jane.html\">Jane Doe</a><p></p></div> ","name":"mf-v2-h-card-impliedurl"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Ben Ward\"],\n \"url\": [\"http://benward.me/\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-card\" href=\"http://benward.me/\">Ben Ward</a>","name":"mf-v2-h-card-justahyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Frances Berriman\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-card\">Frances Berriman</p>","name":"mf-v2-h-card-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Mitchell Baker\"],\n \"url\": [\"http://blog.lizardwrangler.com/\"]\n },\n \"children\": [{\n \"value\": \"Mozilla Foundation\",\n \"type\": [\"h-org\", \"h-card\"],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"],\n \"url\": [\"http://mozilla.org/\"]\n }\n }]\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"h-org h-card\" href=\"http://mozilla.org/\">Mozilla Foundation</a>)\n</div>","name":"mf-v2-h-card-nested"},{"json":"{\n \"items\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"John Doe\"],\n \"given-name\": [\"John\"],\n \"additional-name\": [\"Peter\"],\n \"family-name\": [\"Doe\"],\n \"honorific-suffix\": [\"MSc\", \"PHD\"],\n \"org\": [\"Madgex\", \"Mozilla\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-card\">\n \n <span class=\"p-name\">\n <span class=\"p-given-name value\">John</span> \n <abbr class=\"p-additional-name\" title=\"Peter\">P</abbr> \n <span class=\"p-family-name value \">Doe</span> \n </span>\n <data class=\"p-honorific-suffix\" value=\"MSc\"></data>\n \n \n <br class=\"p-honorific-suffix\" />BSc<br />\n <hr class=\"p-honorific-suffix\" />BA\n \n \n <img class=\"p-honorific-suffix\" src=\"images/logo.gif\" alt=\"PHD\" />\n <img src=\"images/logo.gif\" alt=\"company logos\" usemap=\"#logomap\" />\n <map name=\"logomap\">\n <area class=\"p-org\" shape=\"rect\" coords=\"0,0,82,126\" href=\"madgex.htm\" alt=\"Madgex\" />\n <area class=\"p-org\" shape=\"circle\" coords=\"90,58,3\" href=\"mozilla.htm\" alt=\"Mozilla\" />\n </map>\n</div>","name":"mf-v2-h-card-p-property"},{"json":"\n {\n\t\"items\": [{\n \"type\": [\n \"h-card\"\n ],\n \"properties\": {\n \"name\": [\n \"Mitchell Baker\"\n ],\n \"url\": [\"http://blog.lizardwrangler.com/\"],\n \"org\": [\n {\n \"value\": \"Mozilla Foundation\",\n \"type\": [\n \"h-card\"\n ],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"],\n \"url\": [\"http://example.com/bios/mitchell-baker/\"]\n }\n }\n ],\n \"photo\": [\"http://example.com/bios/mitchell-baker/picture.jpeg\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}\n","html":"<base href=\"http://example.com\" >\n<div class=\"h-card\">\n <a class=\"p-name u-url\" href=\"http://blog.lizardwrangler.com/\">Mitchell Baker</a> \n (<a class=\"p-org h-card\" href=\"bios/mitchell-baker/\">Mozilla Foundation</a>)\n <img class=\"u-photo\" src=\"bios/mitchell-baker/picture.jpeg\"/>\n</div>","name":"mf-v2-h-card-relativeurls"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"in-reply-to\": [{\n \"type\": [\"h-cite\"],\n \"properties\": {\n \"name\": [\"Example Post\"],\n \"url\": [\"http://example.com/post\"],\n\n \"author\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"url\": [\"http://example.com\"],\n \"name\": [\"Example Author\"]\n },\n \"value\": \"Example Author\"\n }]\n },\n \"value\": \"http://example.com/post\"\n }],\n \"name\": [\"Example Author\\n Home\\n \\n Example Post\"]\n }\n }],\n\t\"rels\": {},\n\t\"rel-urls\": {}\n}","html":"<div class=\"h-entry\">\n <div class=\"u-in-reply-to h-cite\">\n <span class=\"p-author h-card\">\n <span class=\"p-name\">Example Author</span>\n <a class=\"u-url\" href=\"http://example.com\">Home</a>\n </span>\n <a class=\"p-name u-url\" href=\"http://example.com/post\">Example Post</a>\n </div>\n</div>","name":"mf-v2-h-entry-impliedvalue-nested"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-entry\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a>","name":"mf-v2-h-entry-justahyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-entry\">microformats.org at 7</p>","name":"mf-v2-h-entry-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"name\": [\"microformats.org at 7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service\",\n \"html\": \"\\n <p class=\\\"p-summary\\\">Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.</p>\\n\\n <p>The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service </p>\\n \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"],\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"h-entry\">\n <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"e-content\">\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n </p>\n</div>","name":"mf-v2-h-entry-summarycontent"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/\", \"http://microformats.org/2012/06/25/microformats-org-at-7\", \"http://microformats.org/2012/06/25/microformats-org-at-7\", \"http://microformats.org/\", \"http://microformats.org/wiki/microformats2-parsing\", \"http://microformats.org/wiki/value-class-pattern\", \"http://microformats.org/wiki/\", \"http://microformats.org/discuss\"],\n \"photo\": [\"http://example.com/images/logo.gif\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<base href=\"http://example.com\">\n<div class=\"h-entry\">\n <p class=\"p-name\">microformats.org at 7</p>\n\n \n <p class=\"u-url\">\n <span class=\"value-title\" title=\"http://microformats.org/\"> </span>\n Article permalink\n </p>\n <p class=\"u-url\">\n <span class=\"value\">http://microformats.org/</span> - \n <span class=\"value\">2012/06/25/microformats-org-at-7</span> \n </p> \n\n <p><a class=\"u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">Article permalink</a></p>\n\n <img src=\"images/logo.gif\" alt=\"company logos\" usemap=\"#logomap\" />\n <map name=\"logomap\">\n <area class=\"u-url\" shape=\"rect\" coords=\"0,0,82,126\" href=\"http://microformats.org/\" alt=\"microformats.org\" />\n </map>\n\n <img class=\"u-photo\" src=\"images/logo.gif\" alt=\"company logos\" />\n\n <object class=\"u-url\" data=\"http://microformats.org/wiki/microformats2-parsing\"></object>\n\n <abbr class=\"u-url\" title=\"http://microformats.org/wiki/value-class-pattern\">value-class-pattern</abbr> \n <data class=\"u-url\" value=\"http://microformats.org/wiki/\"></data>\n <p class=\"u-url\">http://microformats.org/discuss</p>\n</div>","name":"mf-v2-h-entry-u-property"},{"json":"{\n \"items\": [{\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"Expanding URLs within HTML content\"],\n \"content\": [{\n \"value\": \"Should not change: http://www.w3.org/\\n Should not change: http://example.com/\\n File relative: test.html = http://example.com/test.html\\n Directory relative: /test/test.html = http://example.com/test/test.html\\n Relative to root: /test.html = http://example.com/test.html\",\n \"html\": \"\\n <ul>\\n <li><a href=\\\"http://www.w3.org/\\\">Should not change: http://www.w3.org/</a></li>\\n <li><a href=\\\"http://example.com/\\\">Should not change: http://example.com/</a></li>\\n <li><a href=\\\"http://example.com/test.html\\\">File relative: test.html = http://example.com/test.html</a></li>\\n <li><a href=\\\"http://example.com/test/test.html\\\">Directory relative: /test/test.html = http://example.com/test/test.html</a></li>\\n <li><a href=\\\"http://example.com/test.html\\\">Relative to root: /test.html = http://example.com/test.html</a></li>\\n </ul>\\n <img src=\\\"http://example.com/images/photo.gif\\\" />\\n \"\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-entry\">\n <h1><a class=\"p-name\">Expanding URLs within HTML content</a></h1>\n <div class=\"e-content\">\n <ul>\n <li><a href=\"http://www.w3.org/\">Should not change: http://www.w3.org/</a></li>\n <li><a href=\"http://example.com/\">Should not change: http://example.com/</a></li>\n <li><a href=\"test.html\">File relative: test.html = http://example.com/test.html</a></li>\n <li><a href=\"/test/test.html\">Directory relative: /test/test.html = http://example.com/test/test.html</a></li>\n <li><a href=\"/test.html\">Relative to root: /test.html = http://example.com/test.html</a></li>\n </ul>\n <img src=\"images/photo.gif\" />\n </div> \n</div>","name":"mf-v2-h-entry-urlincontent"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"The 4th Microformat party\"],\n \"start\": [\n \"2009-06-26 19:00:00\", \n \"2009-06-26 07:00:00\", \n \"2009-06-26 19:00\", \n \"2009-06-26 19\", \n \"2009-06-26 19\", \n \"2009-06-26 19:00\", \n \"2009-06-26 19:00\", \n \"2009-06-26 19:00\", \n \"2009-06-26 07:00\"\n ]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<span class=\"h-event\">\n <span class=\"p-name\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00:00am \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00pm \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00p.m. \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">07:00PM \n </span></li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <span class=\"value\">7:00am \n </span></li>\n </ul>\n</span>","name":"mf-v2-h-event-ampm"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"CPJ Online Press Freedom Summit\"],\n \"start\": [\"2012-10-10\"],\n \"location\": [\"San Francisco\"],\n \"attendee\": [{\n \"value\": \"Brian Warner\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Brian Warner\"]\n }\n }, {\n \"value\": \"Kyle Machulis\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Kyle Machulis\"]\n }\n }, {\n \"value\": \"Tantek Çelik\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek Çelik\"]\n }\n }, {\n \"value\": \"Sid Sutter\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Sid Sutter\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"h-event\">\n <span class=\"p-name\">CPJ Online Press Freedom Summit</span>\n (<time class=\"dt-start\" datetime=\"2012-10-10\">10 Nov 2012</time>) in\n <span class=\"p-location\">San Francisco</span>.\n Attendees:\n <ul>\n <li class=\"p-attendee h-card\">Brian Warner</li>\n <li class=\"p-attendee h-card\">Kyle Machulis</li>\n <li class=\"p-attendee h-card\">Tantek Çelik</li>\n <li class=\"p-attendee h-card\">Sid Sutter</li>\n </ul>\n</div>\n","name":"mf-v2-h-event-attendees"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"IndieWebCamp 2012\"],\n \"url\": [\"http://indiewebcamp.com/2012\"],\n \"start\": [\"2012-06-30\"],\n \"end\": [\"2012-07-01\"],\n \"location\": [{\n \"value\": \"Geoloqi\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Geoloqi\"],\n \"org\": [\"Geoloqi\"],\n \"url\": [\"http://geoloqi.com/\"],\n \"street-address\": [\"920 SW 3rd Ave. Suite 400\"],\n \"locality\": [\"Portland\"],\n \"region\": [\"Oregon\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-event\">\n <a class=\"p-name u-url\" href=\"http://indiewebcamp.com/2012\">\n IndieWebCamp 2012\n </a>\n from <time class=\"dt-start\">2012-06-30</time> \n to <time class=\"dt-end\">2012-07-01</time> at \n <span class=\"p-location h-card\">\n <a class=\"p-name p-org u-url\" href=\"http://geoloqi.com/\">Geoloqi</a>, \n <span class=\"p-street-address\">920 SW 3rd Ave. Suite 400</span>, \n <span class=\"p-locality\">Portland</span>, \n <abbr class=\"p-region\" title=\"Oregon\">OR</abbr>\n </span>\n</div>","name":"mf-v2-h-event-combining"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"The 4th Microformat party\"],\n \"start\": [\"2009-06-26 19:00\"],\n \"end\": [\"2009-06-26 22:00\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<span class=\"h-event\">\n <span class=\"p-name\">The 4th Microformat party</span> will be on \n <span class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time></span> to \n <span class=\"dt-end\"><time class=\"value\">22:00</time></span>.\n</span>","name":"mf-v2-h-event-concatenate"},{"json":"{\n \"items\": [\n {\n \"type\": [\n \"h-event\"\n ],\n \"properties\": {\n \"name\": [\n \"The 4th Microformat party\"\n ],\n \"start\": [\n \"2009-06-26 19:00-08:00\",\n \"2009-06-26 19:00-08\",\n \"2009-06-26 19:00-08:00\",\n \"2009-06-26 19:00+08:00\",\n \"2009-06-26 19:00+08:00\",\n \"2009-06-26 19:00Z\",\n \"2009-06-26 19:00-08:00\",\n \"2009-06-26 19:00:00-08:00\"\n ]\n }\n }\n ],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<section class=\"h-event\">\n\t<p><span class=\"p-name\">The 4th Microformat party</span> will be on:</p>\n\t<ul>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00-08:00\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00-08\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00-0800\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00+0800\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00+08:00\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26T19:00Z\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26t19:00-08:00\">26 July</time></li>\n\t\t<li><time class=\"dt-start\" datetime=\"2009-06-26 19:00:00-08:00\">26 July</time></li>\n\t</ul>\n</section>","name":"mf-v2-h-event-dates"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"The party\"],\n \"start\": [\n \"2013-03-14\", \n \"2013-06-25 07:00:00\", \n \"2013-06-26\", \n \"2013-06-27\", \n \"2013-06-28\", \n \"2013-06-29\", \n \"2013-07-01\", \n \"2013-07-02\"\n ]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<span class=\"h-event\">\n <span class=\"p-name\">The party</span> will be on \n \n <p class=\"dt-start\">\n <span class=\"value-title\" title=\"2013-03-14\"> </span>\n March 14th 2013\n </p>\n <p class=\"dt-start\">\n <time class=\"value\" datetime=\"2013-06-25\">25 July</time>, from\n <span class=\"value\">07:00:00am \n </span></p> \n \n <p>\n <time class=\"dt-start\" datetime=\"2013-06-26\">26 June</time>\n \n <ins class=\"dt-start\" datetime=\"2013-06-27\">Just added</ins>, \n <del class=\"dt-start\" datetime=\"2013-06-28\">Removed</del>\n </p>\n <abbr class=\"dt-start\" title=\"2013-06-29\">June 29</abbr> \n <data class=\"dt-start\" value=\"2013-07-01\"></data>\n <p class=\"dt-start\">2013-07-02</p>\n \n</span>","name":"mf-v2-h-event-dt-property"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"IndieWebCamp 2012\"],\n \"url\": [\"http://indiewebcamp.com/2012\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-event\" href=\"http://indiewebcamp.com/2012\">IndieWebCamp 2012</a>","name":"mf-v2-h-event-justahyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"IndieWebCamp 2012\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-event\">IndieWebCamp 2012</p>","name":"mf-v2-h-event-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"The 4th Microformat party\"],\n \"start\": [\n \"2009-06-26 19:00:00-08:00\", \n \"2009-06-26 19:00:00-08:00\", \n \"2009-06-26 19:00:00+08:00\", \n \"2009-06-26 19:00:00Z\", \n \"2009-06-26 19:00:00\", \n \"2009-06-26 19:00-08:00\", \n \"2009-06-26 19:00+08:00\", \n \"2009-06-26 19:00Z\", \n \"2009-06-26 19:00\"\n ],\n \"end\": [\n \"2013-034\", \n \"2013-06-27 15:34\"\n ]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<span class=\"h-event\">\n <span class=\"p-name\">The 4th Microformat party</span> will be on \n <ul>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-08:00</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00-0800</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00+0800</time> \n </li> \n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00Z</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00:00</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00-08:00</time> \n </li> \n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00+08:00</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00Z</time> \n </li>\n <li class=\"dt-start\">\n <time class=\"value\" datetime=\"2009-06-26\">26 July</time>, from\n <time class=\"value\">19:00</time> \n </li> \n <li>\n <time class=\"dt-end\" datetime=\"2013-034\">3 February 2013</time>\n </li>\n <li>\n <time class=\"dt-end\" datetime=\"2013-06-27 15:34\">26 July 2013</time>\n </li> \n </ul>\n</span>","name":"mf-v2-h-event-time"},{"json":"{\n \"items\": [{\n \"type\": [\"h-feed\"],\n \"properties\": {\n \"name\": [\"microformats blog\"]\n },\n \"children\": [{\n \"value\": \"microformats.org at 7\\n\\t\\t \\n\\t\\t Last week the microformats.org community \\n\\t\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t\\t San Francisco and recognized accomplishments, challenges, and \\n\\t\\t opportunities.\\n\\t\\t\\n\\t\\t The microformats tagline “humans first, machines second” \\n\\t\\t forms the basis of many of our \\n\\t\\t principles, and \\n\\t\\t in that regard, we’d like to recognize a few people and \\n\\t\\t thank them for their years of volunteer service \\n\\t\\t \\n\\t\\t Updated \\n\\t\\t June 25th, 2012\",\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n\\t\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t\\t San Francisco and recognized accomplishments, challenges, and \\n\\t\\t opportunities.\\n\\t\\t\\n\\t\\t The microformats tagline “humans first, machines second” \\n\\t\\t forms the basis of many of our \\n\\t\\t principles, and \\n\\t\\t in that regard, we’d like to recognize a few people and \\n\\t\\t thank them for their years of volunteer service\",\n \"html\": \"\\n\\t\\t <p class=\\\"p-summary\\\">Last week the microformats.org community \\n\\t\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t\\t San Francisco and recognized accomplishments, challenges, and \\n\\t\\t opportunities.</p>\\n\\t\\t\\n\\t\\t <p>The microformats tagline “humans first, machines second” \\n\\t\\t forms the basis of many of our \\n\\t\\t <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n\\t\\t in that regard, we’d like to recognize a few people and \\n\\t\\t thank them for their years of volunteer service </p>\\n\\t\\t \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n\\t\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t\\t San Francisco and recognized accomplishments, challenges, and \\n\\t\\t opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"]\n }\n }]\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"\n<html>\n\t<head>\n\t\t<title>microformats blog</title>\n\t</head>\n\t<body>\n\t<section class=\"h-feed\">\n\t\t\n\t\t<div class=\"h-entry\">\n\t\t <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n\t\t <div class=\"e-content\">\n\t\t <p class=\"p-summary\">Last week the microformats.org community \n\t\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t\t San Francisco and recognized accomplishments, challenges, and \n\t\t opportunities.</p>\n\t\t\n\t\t <p>The microformats tagline “humans first, machines second” \n\t\t forms the basis of many of our \n\t\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t\t in that regard, we’d like to recognize a few people and \n\t\t thank them for their years of volunteer service </p>\n\t\t </div> \n\t\t <p>Updated \n\t\t <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time>\n\t\t </p>\n\t\t</div>\n\t\t\n\t</section>\n\t</body>\n</html>","name":"mf-v2-h-feed-implied-title"},{"json":"{\n \"items\": [{\n \"type\": [\"h-feed\"],\n \"properties\": {\n \"name\": [\"Microformats blog\"],\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }],\n \"url\": [\"http://microformats.org/blog\"],\n \"photo\": [\"http://example.com/photo.jpeg\"]\n },\n \"children\": [{\n \"value\": \"microformats.org at 7\\n\\t \\n\\t Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.\\n\\t\\n\\t The microformats tagline “humans first, machines second” \\n\\t forms the basis of many of our \\n\\t principles, and \\n\\t in that regard, we’d like to recognize a few people and \\n\\t thank them for their years of volunteer service \\n\\t \\n\\t Updated \\n\\t June 25th, 2012\",\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.\\n\\t\\n\\t The microformats tagline “humans first, machines second” \\n\\t forms the basis of many of our \\n\\t principles, and \\n\\t in that regard, we’d like to recognize a few people and \\n\\t thank them for their years of volunteer service\",\n \"html\": \"\\n\\t <p class=\\\"p-summary\\\">Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.</p>\\n\\t\\n\\t <p>The microformats tagline “humans first, machines second” \\n\\t forms the basis of many of our \\n\\t <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n\\t in that regard, we’d like to recognize a few people and \\n\\t thank them for their years of volunteer service </p>\\n\\t \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n\\t celebrated its 7th birthday at a gathering hosted by Mozilla in \\n\\t San Francisco and recognized accomplishments, challenges, and \\n\\t opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"]\n }\n }]\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<section class=\"h-feed\">\n\t<h1 class=\"p-name\">Microformats blog</h1>\n\t<a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n\t<a class=\"u-url\" href=\"http://microformats.org/blog\">permlink</a>\n\t<img class=\"u-photo\" src=\"photo.jpeg\"/>\n\t\n\t<div class=\"h-entry\">\n\t <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n\t <div class=\"e-content\">\n\t <p class=\"p-summary\">Last week the microformats.org community \n\t celebrated its 7th birthday at a gathering hosted by Mozilla in \n\t San Francisco and recognized accomplishments, challenges, and \n\t opportunities.</p>\n\t\n\t <p>The microformats tagline “humans first, machines second” \n\t forms the basis of many of our \n\t <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n\t in that regard, we’d like to recognize a few people and \n\t thank them for their years of volunteer service </p>\n\t </div> \n\t <p>Updated \n\t <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time>\n\t </p>\n\t</div>\n\t\n</section>","name":"mf-v2-h-feed-simple"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"latitude\": [\"37.408183\"],\n \"longitude\": [\"-122.13855\"],\n \"name\": [\"N 37° 24.491, \\n W 122° 08.313\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<p class=\"h-geo\">\n <abbr class=\"p-latitude\" title=\"37.408183\">N 37° 24.491</abbr>, \n <abbr class=\"p-longitude\" title=\"-122.13855\">W 122° 08.313</abbr>\n</p>","name":"mf-v2-h-geo-abbrpattern"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"name\": [\"Pen-y-ghent\"],\n \"latitude\": [\"54.155278\"],\n \"longitude\": [\"-2.249722\"],\n \"altitude\": [\"694\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p>My favourite hill in the lakes is \n <span class=\"h-geo\">\n <span class=\"p-name\">Pen-y-ghent</span> \n (Geo: <span class=\"p-latitude\">54.155278</span>,\n <span class=\"p-longitude\">-2.249722</span>). It\n raises to <span class=\"p-altitude\">694</span>m.\n </span>\n</p>","name":"mf-v2-h-geo-altitude"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"latitude\": [\"51.513458\"],\n \"longitude\": [\"-0.14812\"],\n \"name\": [\"The Bricklayer's Arms\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p>\n <span class=\"h-geo\">The Bricklayer's Arms\n <span class=\"p-latitude\">\n <span class=\"value-title\" title=\"51.513458\"> </span> \n </span>\n <span class=\"p-longitude\">\n <span class=\"value-title\" title=\"-0.14812\"> </span>\n </span>\n </span>\n</p>","name":"mf-v2-h-geo-hidden"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"name\": [\"51.513458;-0.14812\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p>On my way to The Bricklayer's Arms\n (Geo: <span class=\"h-geo\">51.513458;-0.14812</span>)\n</p>","name":"mf-v2-h-geo-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"name\": [\"The Bricklayer's Arms\"],\n \"latitude\": [\"51.513458\"],\n \"longitude\": [\"-0.14812\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-geo\">We are meeting at \n <span class=\"p-name\">The Bricklayer's Arms</span>\n (Geo: <span class=\"p-latitude\">51.513458</span>:\n <span class=\"p-longitude\">-0.14812</span>)\n</p>","name":"mf-v2-h-geo-simpleproperties"},{"json":"{\n \"items\": [{\n \"type\": [\"h-geo\"],\n \"properties\": {\n \"latitude\": [\"51.513458\"],\n \"longitude\": [\"-0.14812\"],\n \"name\": [\"N 51° 51.345, \\n \\n \\n W -0° 14.812\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<p>\n <span class=\"h-geo\">\n <span class=\"p-latitude\">\n <span class=\"value-title\" title=\"51.513458\">N 51° 51.345</span>, \n </span>\n <span class=\"p-longitude\">\n <span class=\"value-title\" title=\"-0.14812\">W -0° 14.812</span>\n </span>\n </span>\n</p>","name":"mf-v2-h-geo-valuetitleclass"},{"json":"{\n \"items\": [{\n \"type\": [\"h-news\"],\n \"properties\": {\n \"entry\": [{\n \"value\": \"microformats.org at 7\",\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service\",\n \"html\": \"\\n <p class=\\\"p-summary\\\">Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.</p>\\n\\n <p>The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service </p>\\n \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"],\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }]\n }\n }],\n \"dateline\": [{\n \"value\": \"San Francisco, \\n CA\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"San Francisco\"],\n \"region\": [\"CA\"],\n \"name\": [\"San Francisco, \\n CA\"]\n }\n }],\n \"geo\": [\"37.774921;-122.445202\"],\n \"source-org\": [{\n \"value\": \"microformats.org\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"microformats.org\"],\n \"url\": [\"http://microformats.org/\"]\n }\n }],\n \"principles\": [\"http://microformats.org/wiki/Category:public_domain_license\"],\n \"name\": [\"microformats.org at 7\\n \\n Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service \\n \\n Updated \\n June 25th, 2012 by\\n Tantek\\n \\n \\n\\n \\n \\n San Francisco, \\n CA \\n \\n (Geo: 37.774921;-122.445202) \\n \\n microformats.org\\n \\n \\n \\n Publishing policy\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-news\">\n <div class=\"p-entry h-entry\">\n <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"e-content\">\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n </p>\n </div>\n\n <p>\n <span class=\"p-dateline h-adr\">\n <span class=\"p-locality\">San Francisco</span>, \n <span class=\"p-region\">CA</span> \n </span>\n (Geo: <span class=\"p-geo\">37.774921;-122.445202</span>) \n <span class=\"p-source-org h-card\">\n <a class=\"p-name u-url\" href=\"http://microformats.org/\">microformats.org</a>\n </span>\n </p>\n <p>\n <a class=\"u-principles\" href=\"http://microformats.org/wiki/Category:public_domain_license\">Publishing policy</a>\n </p>\n</div>","name":"mf-v2-h-news-all"},{"json":"{\n \"items\": [{\n \"type\": [\"h-news\"],\n \"properties\": {\n \"entry\": [{\n \"value\": \"microformats.org at 7\",\n \"type\": [\"h-entry\"],\n \"properties\": {\n \"name\": [\"microformats.org at 7\"],\n \"url\": [\"http://microformats.org/2012/06/25/microformats-org-at-7\"],\n \"content\": [{\n \"value\": \"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service\",\n \"html\": \"\\n <p class=\\\"p-summary\\\">Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.</p>\\n\\n <p>The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n <a href=\\\"http://microformats.org/wiki/principles\\\">principles</a>, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service </p>\\n \"\n }],\n \"summary\": [\"Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\"],\n \"updated\": [\"2012-06-25 17:08:26\"],\n \"author\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"],\n \"url\": [\"http://tantek.com/\"]\n }\n }]\n }\n }],\n \"source-org\": [{\n \"value\": \"microformats.org\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"microformats.org\"],\n \"url\": [\"http://microformats.org/\"]\n }\n }],\n \"name\": [\"microformats.org at 7\\n \\n Last week the microformats.org community \\n celebrated its 7th birthday at a gathering hosted by Mozilla in \\n San Francisco and recognized accomplishments, challenges, and \\n opportunities.\\n\\n The microformats tagline “humans first, machines second” \\n forms the basis of many of our \\n principles, and \\n in that regard, we’d like to recognize a few people and \\n thank them for their years of volunteer service \\n \\n Updated \\n June 25th, 2012 by\\n Tantek\\n \\n \\n \\n microformats.org\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-news\">\n <div class=\"p-entry h-entry\">\n <h1><a class=\"p-name u-url\" href=\"http://microformats.org/2012/06/25/microformats-org-at-7\">microformats.org at 7</a></h1>\n <div class=\"e-content\">\n <p class=\"p-summary\">Last week the microformats.org community \n celebrated its 7th birthday at a gathering hosted by Mozilla in \n San Francisco and recognized accomplishments, challenges, and \n opportunities.</p>\n\n <p>The microformats tagline “humans first, machines second” \n forms the basis of many of our \n <a href=\"http://microformats.org/wiki/principles\">principles</a>, and \n in that regard, we’d like to recognize a few people and \n thank them for their years of volunteer service </p>\n </div> \n <p>Updated \n <time class=\"dt-updated\" datetime=\"2012-06-25T17:08:26\">June 25th, 2012</time> by\n <a class=\"p-author h-card\" href=\"http://tantek.com/\">Tantek</a>\n </p>\n </div>\n <p>\n <a class=\"p-source-org h-card\" href=\"http://microformats.org/\">microformats.org</a> \n </p>\n</div>","name":"mf-v2-h-news-minimum"},{"json":"{\n \"items\": [{\n \"type\": [\"h-org\"],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"],\n \"url\": [\"http://mozilla.org/\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-org\" href=\"http://mozilla.org/\">Mozilla Foundation</a>","name":"mf-v2-h-org-hyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-org\"],\n \"properties\": {\n \"name\": [\"Mozilla Foundation\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<span class=\"h-org\">Mozilla Foundation</span>","name":"mf-v2-h-org-simple"},{"json":"{\n \"items\": [{\n \"type\": [\"h-org\"],\n \"properties\": {\n \"organization-name\": [\"W3C\"],\n \"organization-unit\": [\"CSS Working Group\"],\n \"name\": [\"W3C - \\n CSS Working Group\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-org\">\n <span class=\"p-organization-name\">W3C</span> - \n <span class=\"p-organization-unit\">CSS Working Group</span>\n</p>","name":"mf-v2-h-org-simpleproperties"},{"json":"{\n \"items\": [{\n \"type\": [\"h-product\"],\n \"properties\": {\n \"name\": [\"Raspberry Pi\"],\n \"photo\": [\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\"],\n \"description\": [{\n \"value\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\",\n \"html\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\"\n }],\n \"url\": [\"http://www.raspberrypi.org/\"],\n \"price\": [\"£29.95\"],\n \"review\": [{\n \"value\": \"9.2 out of \\n 10 \\n based on 178 reviews\",\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"rating\": [{\n \"value\": \"9.2 out of \\n 10 \\n based on 178 reviews\",\n \"type\": [\"h-rating\"],\n \"properties\": {\n \"average\": [\"9.2\"],\n \"best\": [\"10\"],\n \"count\": [\"178\"],\n \"name\": [\"9.2 out of \\n 10 \\n based on 178 reviews\"]\n }\n }],\n \"name\": [\"9.2 out of \\n 10 \\n based on 178 reviews\"]\n }\n }],\n \"category\": [\"Computer\", \"Education\"],\n \"brand\": [{\n \"value\": \"The Raspberry Pi Foundation\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"The Raspberry Pi Foundation\"],\n \"org\": [\"The Raspberry Pi Foundation\"],\n \"locality\": [\"Cambridge\"],\n \"country-name\": [\"UK\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"h-product\">\n <h2 class=\"p-name\">Raspberry Pi</h2>\n <img class=\"u-photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"e-description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"u-url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"p-price\">£29.95</p>\n <p class=\"p-review h-review-aggregate\">\n <span class=\"p-rating h-rating\">\n <span class=\"p-average\">9.2</span> out of \n <span class=\"p-best\">10</span> \n based on <span class=\"p-count\">178</span> reviews\n </span>\n </p>\n <p>Categories: <span class=\"p-category\">Computer</span>, <span class=\"p-category\">Education</span></p>\n <p class=\"p-brand h-card\">From: \n <span class=\"p-name p-org\">The Raspberry Pi Foundation</span> - \n <span class=\"p-locality\">Cambridge</span> \n <span class=\"p-country-name\">UK</span>\n </p>\n</div>","name":"mf-v2-h-product-aggregate"},{"json":"{\n \"items\": [{\n \"type\": [\"h-product\"],\n \"properties\": {\n \"name\": [\"Raspberry Pi\"],\n \"url\": [\"http://www.raspberrypi.org/\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-product\" href=\"http://www.raspberrypi.org/\">Raspberry Pi</a>","name":"mf-v2-h-product-justahyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-product\"],\n \"properties\": {\n \"name\": [\"Raspberry Pi\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-product\">Raspberry Pi</p>","name":"mf-v2-h-product-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-product\"],\n \"properties\": {\n \"name\": [\"Raspberry Pi\"],\n \"photo\": [\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\"],\n \"description\": [{\n \"value\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\",\n \"html\": \"The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.\"\n }],\n \"url\": [\"http://www.raspberrypi.org/\"],\n \"price\": [\"£29.95\"],\n \"category\": [\"Computer\", \"Education\"],\n \"review\": [{\n \"value\": \"4.5 out of 5\",\n \"type\": [\"h-review\"],\n \"properties\": {\n \"rating\": [\"4.5\"],\n \"name\": [\"4.5 out of 5\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"h-product\">\n <h2 class=\"p-name\">Raspberry Pi</h2>\n <img class=\"u-photo\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/RaspberryPi.jpg/320px-RaspberryPi.jpg\" />\n <p class=\"e-description\">The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It’s a capable little PC which can be used for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video. We want to see it being used by kids all over the world to learn programming.</p>\n <a class=\"u-url\" href=\"http://www.raspberrypi.org/\">More info about the Raspberry Pi</a>\n <p class=\"p-price\">£29.95</p>\n <p class=\"p-review h-review\"><span class=\"p-rating\">4.5</span> out of 5</p>\n <p>Categories: <span class=\"p-category\">Computer</span>, <span class=\"p-category\">Education</span></p>\n</div>","name":"mf-v2-h-product-simpleproperties"},{"json":"{\n \"items\": [{\n \"type\": [\"h-recipe\"],\n \"properties\": {\n \"name\": [\"Yorkshire Puddings\"],\n \"summary\": [\"Makes 6 good sized Yorkshire puddings, the way my mum taught me\"],\n \"yield\": [\"6 good sized Yorkshire puddings\"],\n \"photo\": [\"http://codebits.glennjones.net/semantic/yorkshire-puddings.jpg\"],\n \"review\": [{\n \"value\": \"4.5 stars out 5 based on \\n 35 reviews\",\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"rating\": [\"4.5 stars out 5 based on\"],\n \"average\": [\"4.5\"],\n \"count\": [\"35\"],\n \"name\": [\"4.5 stars out 5 based on \\n 35 reviews\"]\n }\n }],\n \"ingredient\": [{\n \"value\": \"1 egg\",\n \"html\": \"1 egg\"\n }, {\n \"value\": \"75g plain flour\",\n \"html\": \"75g plain flour\"\n }, {\n \"value\": \"70ml milk\",\n \"html\": \"70ml milk\"\n }, {\n \"value\": \"60ml water\",\n \"html\": \"60ml water\"\n }, {\n \"value\": \"Pinch of salt\",\n \"html\": \"Pinch of salt\"\n }],\n \"instructions\": [{\n \"value\": \"Pre-heat oven to 230C or gas mark 8. Pour the vegetable oil evenly into 2 x 4-hole \\n Yorkshire pudding tins and place in the oven to heat through. \\n \\n To make the batter, add all the flour into a bowl and beat in the eggs until smooth. \\n Gradually add the milk and water while beating the mixture. It should be smooth and \\n without lumps. Finally add a pinch of salt.\\n \\n Make sure the oil is piping hot before pouring the batter evenly into the tins. \\n Place in the oven for 20-25 minutes until pudding have risen and look golden brown\",\n \"html\": \"\\n <ol>\\n <li>Pre-heat oven to 230C or gas mark 8. Pour the vegetable oil evenly into 2 x 4-hole \\n Yorkshire pudding tins and place in the oven to heat through.</li> \\n \\n <li>To make the batter, add all the flour into a bowl and beat in the eggs until smooth. \\n Gradually add the milk and water while beating the mixture. It should be smooth and \\n without lumps. Finally add a pinch of salt.</li>\\n \\n <li>Make sure the oil is piping hot before pouring the batter evenly into the tins. \\n Place in the oven for 20-25 minutes until pudding have risen and look golden brown</li>\\n </ol>\\n \"\n }],\n \"nutrition\": [\"Calories: 125\", \"Fat: 3.2g\", \"Cholesterol: 77mg\"],\n \"published\": [\"2011-10-27\"],\n \"author\": [{\n \"value\": \"Glenn Jones\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Glenn Jones\"],\n \"url\": [\"http://glennjones.net\"]\n }\n }],\n \"url\": [\"http://www.flickr.com/photos/dithie/4106528495/\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<section class=\"h-recipe\">\n <h1 class=\"p-name\">Yorkshire Puddings</h1> \n <p class=\"p-summary\">Makes <span class=\"p-yield\">6 good sized Yorkshire puddings</span>, the way my mum taught me</p>\n\n\n <p><img class=\"u-photo\" src=\"http://codebits.glennjones.net/semantic/yorkshire-puddings.jpg\" /></p>\n\n <span class=\"p-review h-review-aggregate\">\n <span class=\"p-rating\">\n <span class=\"p-average\">4.5</span> stars out 5 based on </span>\n <span class=\"p-count\">35</span> reviews</span>\n \n \n\n <div id=\"ingredients-container\">\n <h3>Ingredients</h3>\n <ul>\n <li class=\"e-ingredient\">1 egg</li>\n <li class=\"e-ingredient\">75g plain flour</li>\n <li class=\"e-ingredient\">70ml milk</li>\n <li class=\"e-ingredient\">60ml water</li>\n <li class=\"e-ingredient\">Pinch of salt</li>\n </ul>\n </div>\n\n <h3>Time</h3>\n <ul>\n <li class=\"prepTime\">Preparation <span class=\"value-title\" title=\"PT0H10M\">10 mins</span></li>\n <li class=\"cookTime\">Cook <span class=\"value-title\" title=\"PT0H25M\">25 mins</span></li>\n </ul> \n\n\n <h3>Instructions</h3>\n <div class=\"e-instructions\">\n <ol>\n <li>Pre-heat oven to 230C or gas mark 8. Pour the vegetable oil evenly into 2 x 4-hole \n Yorkshire pudding tins and place in the oven to heat through.</li> \n \n <li>To make the batter, add all the flour into a bowl and beat in the eggs until smooth. \n Gradually add the milk and water while beating the mixture. It should be smooth and \n without lumps. Finally add a pinch of salt.</li>\n \n <li>Make sure the oil is piping hot before pouring the batter evenly into the tins. \n Place in the oven for 20-25 minutes until pudding have risen and look golden brown</li>\n </ol>\n </div>\n\n <h3>Nutrition</h3>\n <ul id=\"nutrition-list\">\n <li class=\"p-nutrition\">Calories: <span class=\"calories\">125</span></li>\n <li class=\"p-nutrition\">Fat: <span class=\"fat\">3.2g</span></li>\n <li class=\"p-nutrition\">Cholesterol: <span class=\"cholesterol\">77mg</span></li>\n </ul>\n <p>(Amount per pudding)</p>\n\n <p>\n Published on <time class=\"dt-published\" datetime=\"2011-10-27\">27 Oct 2011</time> by \n <span class=\"p-author h-card\">\n <a class=\"p-name u-url\" href=\"http://glennjones.net\">Glenn Jones</a>\n </span>\n </p>\n <a href=\"http://www.flickr.com/photos/dithie/4106528495/\">Photo by dithie</a>\n </section>","name":"mf-v2-h-recipe-all"},{"json":"{\n \"items\": [{\n \"type\": [\"h-recipe\"],\n \"properties\": {\n \"name\": [\"Toast\"],\n \"ingredient\": [{\n \"value\": \"Slice of bread\",\n \"html\": \"Slice of bread\"\n }, {\n \"value\": \"Butter\",\n \"html\": \"Butter\"\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-recipe\"> \n <p class=\"p-name\">Toast</p>\n <ul>\n <li class=\"e-ingredient\">Slice of bread</li>\n <li class=\"e-ingredient\">Butter</li>\n </ul>\n</div>","name":"mf-v2-h-recipe-minimum"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"summary\": [\"invented the World Wide Web\"],\n \"affiliation\": [{\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"W3C\"],\n \"photo\": [\"http://www.w3.org/Icons/WWW/w3c_home_nb.png\"],\n \"url\": [\"http://www.w3.org/\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-resume\">\n <p>\n <span class=\"p-name\">Tim Berners-Lee</span>, \n <span class=\"p-summary\">invented the World Wide Web</span>. \n </p> \n Belongs to following groups:\n <p> \n <a class=\"p-affiliation h-card\" href=\"http://www.w3.org/\">\n <img class=\"p-name u-photo\" alt=\"W3C\" src=\"http://www.w3.org/Icons/WWW/w3c_home_nb.png\" />\n </a>\n </p> \n</div>","name":"mf-v2-h-resume-affiliation"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"summary\": [\"Invented the World Wide Web.\"],\n \"contact\": [{\n \"value\": \"MIT\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"MIT\"],\n \"street-address\": [\"32 Vassar Street\"],\n \"extended-address\": [\"Room 32-G524\"],\n \"locality\": [\"Cambridge\"],\n \"region\": [\"MA\"],\n \"postal-code\": [\"02139\"],\n \"country-name\": [\"USA\"],\n \"tel\": [\"+1 (617) 253 5702\"],\n \"email\": [\"mailto:timbl@w3.org\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-resume\">\n <p class=\"p-name\">Tim Berners-Lee</p>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <div class=\"p-contact h-card\">\n <p class=\"p-name\">MIT</p>\n <p>\n <span class=\"p-street-address\">32 Vassar Street</span>, \n <span class=\"p-extended-address\">Room 32-G524</span>, \n <span class=\"p-locality\">Cambridge</span>, \n <span class=\"p-region\">MA</span> \n <span class=\"p-postal-code\">02139</span>, \n <span class=\"p-country-name\">USA</span>.\n </p>\n <p>Tel:<span class=\"p-tel\">+1 (617) 253 5702</span></p>\n <p>Email:<a class=\"u-email\" href=\"mailto:timbl@w3.org\">timbl@w3.org</a></p>\n </div>\n</div>","name":"mf-v2-h-resume-contact"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"contact\": [{\n \"value\": \"Director of the World Wide Web Foundation\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"title\": [\"Director of the World Wide Web Foundation\"],\n \"name\": [\"Director of the World Wide Web Foundation\"]\n }\n }],\n \"summary\": [\"Invented the World Wide Web.\"],\n \"education\": [{\n \"value\": \"The Queen's College, Oxford University\",\n \"type\": [\"h-event\", \"h-card\"],\n \"properties\": {\n \"name\": [\"The Queen's College, Oxford University\"],\n \"org\": [\"The Queen's College, Oxford University\"],\n \"description\": [\"BA Hons (I) Physics\"],\n \"start\": [\"1973-09\"],\n \"end\": [\"1976-06\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-resume\">\n <p class=\"p-name\">Tim Berners-Lee</p>\n <div class=\"p-contact h-card\">\n <p class=\"p-title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <p class=\"p-education h-event h-card\">\n <span class=\"p-name p-org\">The Queen's College, Oxford University</span>, \n <span class=\"p-description\">BA Hons (I) Physics</span> \n <time class=\"dt-start\" datetime=\"1973-09\">1973</time> –\n <time class=\"dt-end\" datetime=\"1976-06\">1976</time>\n </p>\n</div>","name":"mf-v2-h-resume-education"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee, invented the World Wide Web.\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-resume\">Tim Berners-Lee, invented the World Wide Web.</p>","name":"mf-v2-h-resume-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"summary\": [\"invented the World Wide Web\"],\n \"skill\": [\"information systems\", \"advocacy\", \"leadership\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-resume\">\n <p>\n <span class=\"p-name\">Tim Berners-Lee</span>, \n <span class=\"p-summary\">invented the World Wide Web</span>.\n </p>\n Skills: \n <ul>\n <li class=\"p-skill\">information systems</li>\n <li class=\"p-skill\">advocacy</li>\n <li class=\"p-skill\">leadership</li>\n <ul> \n</ul></ul></div>","name":"mf-v2-h-resume-skill"},{"json":"{\n \"items\": [{\n \"type\": [\"h-resume\"],\n \"properties\": {\n \"name\": [\"Tim Berners-Lee\"],\n \"contact\": [{\n \"value\": \"Director of the World Wide Web Foundation\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"title\": [\"Director of the World Wide Web Foundation\"],\n \"name\": [\"Director of the World Wide Web Foundation\"]\n }\n }],\n \"summary\": [\"Invented the World Wide Web.\"],\n \"experience\": [{\n \"value\": \"World Wide Web Foundation\",\n \"type\": [\"h-event\", \"h-card\"],\n \"properties\": {\n \"title\": [\"Director\"],\n \"name\": [\"World Wide Web Foundation\"],\n \"org\": [\"World Wide Web Foundation\"],\n \"url\": [\"http://www.webfoundation.org/\"],\n \"start\": [\"2009-01-18\"],\n \"duration\": [\"P2Y11M\"]\n }\n }]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<meta charset=\"utf-8\">\n<div class=\"h-resume\">\n <p class=\"p-name\">Tim Berners-Lee</p>\n <div class=\"p-contact h-card\">\n <p class=\"p-title\">Director of the World Wide Web Foundation</p>\n </div>\n <p class=\"p-summary\">Invented the World Wide Web.</p><hr />\n <div class=\"p-experience h-event h-card\">\n <p class=\"p-title\">Director</p>\n <p><a class=\"p-name p-org u-url\" href=\"http://www.webfoundation.org/\">World Wide Web Foundation</a></p>\n <p>\n <time class=\"dt-start\" datetime=\"2009-01-18\">Jan 2009</time> – Present\n <time class=\"dt-duration\" datetime=\"P2Y11M\">(2 years 11 month)</time>\n </p>\n </div>\n</div>","name":"mf-v2-h-resume-work"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"name\": [\"Crepes on Cole\"],\n \"url\": [\"https://plus.google.com/116941523817079328322/about\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<a class=\"h-review\" href=\"https://plus.google.com/116941523817079328322/about\">Crepes on Cole</a>","name":"mf-v2-h-review-hyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Crepes on Cole\",\n \"type\": [\"h-item\"],\n \"properties\": {\n \"name\": [\"Crepes on Cole\"],\n \"url\": [\"http://example.com/crepeoncole\"]\n }\n }],\n \"rating\": [\"4.7\"],\n \"name\": [\"Crepes on Cole\\n 4.7 out of 5 stars\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-review\">\n <a class=\"p-item h-item\" href=\"http://example.com/crepeoncole\">Crepes on Cole</a>\n <p><span class=\"p-rating\">4.7</span> out of 5 stars</p>\n</div>","name":"mf-v2-h-review-implieditem"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Crepes on Cole\",\n \"type\": [\"h-item\"],\n \"properties\": {\n \"photo\": [\"http://example.com/images/photo.gif\"],\n \"name\": [\"Crepes on Cole\"],\n \"url\": [\"http://example.com/crepeoncole\"]\n }\n }],\n \"rating\": [\"5\"],\n \"name\": [\"Crepes on Cole\\n \\n 5 out of 5 stars\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<base href=\"http://example.com\" >\n<div class=\"h-review\">\n <p class=\"p-item h-item\">\n <img class=\"u-photo\" src=\"images/photo.gif\" />\n <a class=\"p-name u-url\" href=\"http://example.com/crepeoncole\">Crepes on Cole</a>\n </p>\n <p><span class=\"p-rating\">5</span> out of 5 stars</p>\n</div>","name":"mf-v2-h-review-item"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"name\": [\"Crepes on Cole\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<p class=\"h-review\">Crepes on Cole</p>","name":"mf-v2-h-review-justaname"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"name\": [\"Crepes on Cole\"],\n \"photo\": [\"http://example.com/images/photo.gif\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<base href=\"http://example.com\" ><img class=\"h-review\" src=\"images/photo.gif\" alt=\"Crepes on Cole\" />","name":"mf-v2-h-review-photo"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review\"],\n \"properties\": {\n \"rating\": [\"5\"],\n \"name\": [\"Crepes on Cole is awesome\"],\n \"reviewer\": [{\n \"value\": \"Tantek\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Tantek\"]\n }\n }],\n \"reviewed\": [\"2005-04-18\"],\n \"description\": [{\n \"value\": \"Crepes on Cole is one of the best little \\n creperies in San Francisco.\\n Excellent food and service. Plenty of tables in a variety of sizes \\n for parties large and small. Window seating makes for excellent \\n people watching to/from the N-Judah which stops right outside. \\n I've had many fun social gatherings here, as well as gotten \\n plenty of work done thanks to neighborhood WiFi.\",\n \"html\": \"\\n <p class=\\\"p-item h-card\\\">\\n <span class=\\\"p-name p-org\\\">Crepes on Cole</span> is one of the best little \\n creperies in <span class=\\\"p-adr h-adr\\\"><span class=\\\"p-locality\\\">San Francisco</span></span>.\\n Excellent food and service. Plenty of tables in a variety of sizes \\n for parties large and small. Window seating makes for excellent \\n people watching to/from the N-Judah which stops right outside. \\n I've had many fun social gatherings here, as well as gotten \\n plenty of work done thanks to neighborhood WiFi.\\n </p>\\n \"\n }],\n \"item\": [{\n \"value\": \"Crepes on Cole\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Crepes on Cole\"],\n \"org\": [\"Crepes on Cole\"],\n \"adr\": [{\n \"value\": \"San Francisco\",\n \"type\": [\"h-adr\"],\n \"properties\": {\n \"locality\": [\"San Francisco\"],\n \"name\": [\"San Francisco\"]\n }\n }]\n }\n }],\n \"category\": [\"crepe\"],\n \"url\": [\"http://example.com/crepe\"]\n }\n }],\n \"rels\": {\n \"license\": [\"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\"]\n },\n \"rel-urls\": {\n \"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\": {\n \"text\": \"Creative Commons Attribution-ShareAlike License\",\n \"rels\": [\"license\"]\n }\n }\n}","html":"<div class=\"h-review\">\n <span><span class=\"p-rating\">5</span> out of 5 stars</span>\n <h4 class=\"p-name\">Crepes on Cole is awesome</h4>\n <span class=\"p-reviewer h-card\">\n Reviewer: <span class=\"p-name\">Tantek</span> - \n </span>\n <time class=\"dt-reviewed\" datetime=\"2005-04-18\">April 18, 2005</time>\n <div class=\"e-description\">\n <p class=\"p-item h-card\">\n <span class=\"p-name p-org\">Crepes on Cole</span> is one of the best little \n creperies in <span class=\"p-adr h-adr\"><span class=\"p-locality\">San Francisco</span></span>.\n Excellent food and service. Plenty of tables in a variety of sizes \n for parties large and small. Window seating makes for excellent \n people watching to/from the N-Judah which stops right outside. \n I've had many fun social gatherings here, as well as gotten \n plenty of work done thanks to neighborhood WiFi.\n </p>\n </div>\n <p>Visit date: <span>April 2005</span></p>\n <p>Food eaten: <a class=\"p-category\" href=\"http://en.wikipedia.org/wiki/crepe\">crepe</a></p>\n <p>Permanent link for review: <a class=\"u-url\" href=\"http://example.com/crepe\">http://example.com/crepe</a></p>\n <p><a rel=\"license\" href=\"http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a></p>\n</div>","name":"mf-v2-h-review-vcard"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Fullfrontal\",\n \"type\": [\"h-event\"],\n \"properties\": {\n \"name\": [\"Fullfrontal\"],\n \"description\": [\"A one day JavaScript Conference held in Brighton\"],\n \"start\": [\"2012-11-09\"]\n }\n }],\n \"rating\": [\"9.9\"],\n \"average\": [\"9.9\"],\n \"best\": [\"10\"],\n \"count\": [\"62\"],\n \"name\": [\"Fullfrontal\\n A one day JavaScript Conference held in Brighton\\n 9th November 2012 \\n \\n \\n \\n 9.9 out of \\n 10 \\n based on 62 reviews\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-review-aggregate\">\n <div class=\"p-item h-event\">\n <h3 class=\"p-name\">Fullfrontal</h3>\n <p class=\"p-description\">A one day JavaScript Conference held in Brighton</p>\n <p><time class=\"dt-start\" datetime=\"2012-11-09\">9th November 2012</time></p> \n </div> \n \n <p class=\"p-rating\">\n <span class=\"p-average value\">9.9</span> out of \n <span class=\"p-best\">10</span> \n based on <span class=\"p-count\">62</span> reviews\n </p>\n</div>","name":"mf-v2-h-review-aggregate-hevent"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Mediterranean Wraps\",\n \"type\": [\"h-item\"],\n \"properties\": {\n \"name\": [\"Mediterranean Wraps\"]\n }\n }],\n \"summary\": [\"Customers flock to this small restaurant for their \\n tasty falafel and shawerma wraps and welcoming staff.\"],\n \"rating\": [\"4.5\"],\n \"name\": [\"Mediterranean Wraps\\n \\n Customers flock to this small restaurant for their \\n tasty falafel and shawerma wraps and welcoming staff.\\n \\n 4.5 out of 5\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-review-aggregate\">\n <h3 class=\"p-item h-item\">Mediterranean Wraps</h3>\n <span class=\"p-summary\">\n Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff.\n </span>\n <span class=\"p-rating\">4.5</span> out of 5 \n</div>","name":"mf-v2-h-review-aggregate-justahyperlink"},{"json":"{\n \"items\": [{\n \"type\": [\"h-review-aggregate\"],\n \"properties\": {\n \"item\": [{\n \"value\": \"Mediterranean Wraps\",\n \"type\": [\"h-card\"],\n \"properties\": {\n \"name\": [\"Mediterranean Wraps\"],\n \"street-address\": [\"433 S California Ave\"],\n \"locality\": [\"Palo Alto\"],\n \"region\": [\"CA\"],\n \"tel\": [\"(650) 321-8189\"]\n }\n }],\n \"summary\": [\"Customers flock to this small restaurant for their \\n tasty falafel and shawerma wraps and welcoming staff.\"],\n \"rating\": [\"9.2\"],\n \"average\": [\"9.2\"],\n \"best\": [\"10\"],\n \"count\": [\"17\"],\n \"name\": [\"Mediterranean Wraps\\n \\n 433 S California Ave, \\n Palo Alto, \\n CA - \\n (650) 321-8189\\n \\n \\n Customers flock to this small restaurant for their \\n tasty falafel and shawerma wraps and welcoming staff.\\n \\n 9.2 out of \\n 10 \\n based on 17 reviews\"]\n }\n }],\n \"rels\": {},\n \"rel-urls\": {}\n}","html":"<div class=\"h-review-aggregate\">\n <div class=\"p-item h-card\">\n <h3 class=\"p-name\">Mediterranean Wraps</h3>\n <p>\n <span class=\"p-street-address\">433 S California Ave</span>, \n <span class=\"p-locality\">Palo Alto</span>, \n <span class=\"p-region\">CA</span> - \n <span class=\"p-tel\">(650) 321-8189</span>\n </p>\n </div> \n <span class=\"p-summary\">Customers flock to this small restaurant for their \n tasty falafel and shawerma wraps and welcoming staff.</span>\n <span class=\"p-rating\">\n <span class=\"p-average value\">9.2</span> out of \n <span class=\"p-best\">10</span> \n based on <span class=\"p-count\">17</span> reviews\n </span>\n</div>","name":"mf-v2-h-review-aggregate-simpleproperties"},{"json":"{\n \"rels\": {\n \"bookmark\": [\n \"http://ma.tt/2015/05/beethoven-mozart-bach/\",\n \"http://ma.tt/2015/06/jefferson-on-idleness/\" \n ], \n \"category\": [\n \"http://ma.tt/category/asides/\"\n ], \n \"tag\": [\n \"http://ma.tt/category/asides/\"\n ], \n \"author\": [\n \"http://ma.tt/author/saxmatt/\"\n ]\n }, \n \"items\": [\n {\n \"type\": [\n \"h-card\"\n ], \n \"properties\": {\n \"url\": [\n \"http://ma.tt/author/saxmatt/\"\n ], \n \"name\": [\n \"Matt\"\n ]\n }\n }, \n {\n \"type\": [\n \"h-card\"\n ], \n \"properties\": {\n \"url\": [\n \"http://ma.tt/author/saxmatt/\"\n ], \n \"name\": [\n \"Matt\"\n ]\n }\n }\n ], \n \"rel-urls\": {\n \"http://ma.tt/category/asides/\": {\n \"rels\": [\n \"category\", \n \"tag\"\n ], \n \"text\": \"Asides\"\n }, \n \"http://ma.tt/author/saxmatt/\": {\n \"rels\": [\n \"author\"\n ], \n \"text\": \"Matt\", \n \"title\": \"View all posts by Matt\"\n }, \n \"http://ma.tt/2015/05/beethoven-mozart-bach/\": {\n \"rels\": [\n \"bookmark\"\n ], \n \"text\": \"May 31, 2015\", \n \"title\": \"Permalink to Beethoven, Mozart, Bach\"\n }, \n \"http://ma.tt/2015/06/jefferson-on-idleness/\": {\n \"rels\": [\n \"bookmark\"\n ], \n \"text\": \"June 2, 2015\", \n \"title\": \"Permalink to Jefferson on Idleness\"\n }\n }\n}","html":"<a href=\"http://ma.tt/2015/05/beethoven-mozart-bach/\" \n title=\"Permalink to Beethoven, Mozart, Bach\" rel=\"bookmark\">\n<time class=\"entry-date\" datetime=\"2015-05-31T22:42:00+00:00\">May 31, 2015</time></a></span>\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">Asides</a>\n<span class=\"author vcard\">\n<a class=\"url fn n\" href=\"http://ma.tt/author/saxmatt/\" \n title=\"View all posts by Matt\" rel=\"author\">Matt</a></span>\n<span class=\"date\"><a href=\"http://ma.tt/2015/06/jefferson-on-idleness/\" title=\"Permalink to Jefferson on Idleness\" rel=\"bookmark\"><time class=\"entry-date\" datetime=\"2015-06-02T21:26:00+00:00\">June 2, 2015</time></a></span>\n<span class=\"categories-links\"><a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">Asides</a></span>\n<span class=\"author vcard\"><a class=\"url fn n\" href=\"http://ma.tt/author/saxmatt/\" title=\"View all posts by Matt\" rel=\"author\">Matt</a></span>\n","name":"mf-v2-rel-duplicate-rels"},{"json":"{\n \"items\": [],\n \"rels\": {\n \"license\": [\"http://creativecommons.org/licenses/by/2.5/\"]\n },\n \"rel-urls\": {\n \"http://creativecommons.org/licenses/by/2.5/\": {\n \"text\": \"cc by 2.5\",\n \"rels\": [\"license\"]\n }\n }\n}","html":"<a rel=\"license\" href=\"http://creativecommons.org/licenses/by/2.5/\">cc by 2.5</a>","name":"mf-v2-rel-license"},{"json":"{\n \"items\": [],\n \"rels\": {\n \"nofollow\": [\"http://microformats.org/wiki/microformats:copyrights\"]\n },\n \"rel-urls\": {\n \"http://microformats.org/wiki/microformats:copyrights\": {\n \"text\": \"Copyrights\",\n \"rels\": [\"nofollow\"]\n }\n }\n}","html":"<a rel=\"nofollow\" href=\"http://microformats.org/wiki/microformats:copyrights\">Copyrights</a>","name":"mf-v2-rel-nofollow"},{"json":"{\n \"items\": [],\n \"rels\": { \n \"author\": [ \"http://example.com/a\", \"http://example.com/b\" ],\n \"in-reply-to\": [ \"http://example.com/1\", \"http://example.com/2\" ], \n \"home\": [ \"http://example.com/fr\" ], \n \"alternate\": [ \"http://example.com/fr\" ] \n },\n \"rel-urls\": {\n \"http://example.com/a\": {\n \"rels\": [\"author\"], \n \"text\": \"author a\"\n },\n \"http://example.com/b\": {\n \"rels\": [\"author\"], \n \"text\": \"author b\"\n },\n \"http://example.com/1\": {\n \"rels\": [\"in-reply-to\"], \n \"text\": \"post 1\"\n },\n \"http://example.com/2\": {\n \"rels\": [\"in-reply-to\"], \n \"text\": \"post 2\"\n },\n \"http://example.com/fr\": {\n \"rels\": [\"alternate\", \"home\"],\n \"media\": \"handheld\", \n \"hreflang\": \"fr\", \n \"text\": \"French mobile homepage\"\n }\n }\n}","html":"<a rel=\"author\" href=\"http://example.com/a\">author a</a>\n<a rel=\"author\" href=\"http://example.com/b\">author b</a>\n<a rel=\"in-reply-to\" href=\"http://example.com/1\">post 1</a>\n<a rel=\"in-reply-to\" href=\"http://example.com/2\">post 2</a>\n<a rel=\"alternate home\"\n href=\"http://example.com/fr\"\n media=\"handheld\"\n hreflang=\"fr\">French mobile homepage</a>","name":"mf-v2-rel-rel-urls"},{"json":"{\n \"rels\": {\n \"category\": [\n \"http://ma.tt/category/asides/\"\n ], \n \"tag\": [\n \"http://ma.tt/category/asides/\"\n ]\n }, \n \"items\": [], \n \"rel-urls\": {\n \"http://ma.tt/category/asides/\": {\n \"rels\": [\n \"category\", \n \"tag\"\n ], \n \"text\": \"Asides\"\n }\n }\n}\n","html":"This is a contrived example - not found links like this in the wild:\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">Asides</a>\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">B-sides</a>\n<a href=\"http://ma.tt/category/asides/\" rel=\"category tag\">seasides</a>","name":"mf-v2-rel-varying-text-duplicate-rels"},{"json":"{\n \"items\": [],\n \"rels\": {\n \"friend\": [\"http://example.com/profile/jane\"],\n \"acquaintance\": [\"http://example.com/profile/jeo\"],\n \"contact\": [\"http://example.com/profile/lily\"],\n \"met\": [\"http://example.com/profile/oliver\"],\n \"co-worker\": [\"http://example.com/profile/emily\"],\n \"colleague\": [\"http://example.com/profile/jack\"],\n \"neighbor\": [\"http://example.com/profile/isabella\"],\n \"child\": [\"http://example.com/profile/harry\"],\n \"parent\": [\"http://example.com/profile/sophia\"],\n \"sibling\": [\"http://example.com/profile/charlie\"],\n \"spouse\": [\"http://example.com/profile/olivia\"],\n \"kin\": [\"http://example.com/profile/james\"],\n \"muse\": [\"http://example.com/profile/ava\"],\n \"crush\": [\"http://example.com/profile/joshua\"],\n \"date\": [\"http://example.com/profile/chloe\"],\n \"sweetheart\": [\"http://example.com/profile/alfie\"],\n \"me\": [\"http://example.com/profile/isla\"]\n },\n \"rel-urls\": {\n \"http://example.com/profile/jane\": {\n \"text\": \"jane\",\n \"rels\": [\"friend\"]\n },\n \"http://example.com/profile/jeo\": {\n \"text\": \"jeo\",\n \"rels\": [\"acquaintance\"]\n },\n \"http://example.com/profile/lily\": {\n \"text\": \"lily\",\n \"rels\": [\"contact\"]\n },\n \"http://example.com/profile/oliver\": {\n \"text\": \"oliver\",\n \"rels\": [\"met\"]\n },\n \"http://example.com/profile/emily\": {\n \"text\": \"emily\",\n \"rels\": [\"co-worker\"]\n },\n \"http://example.com/profile/jack\": {\n \"text\": \"jack\",\n \"rels\": [\"colleague\"]\n },\n \"http://example.com/profile/isabella\": {\n \"text\": \"isabella\",\n \"rels\": [\"neighbor\"]\n },\n \"http://example.com/profile/harry\": {\n \"text\": \"harry\",\n \"rels\": [\"child\"]\n },\n \"http://example.com/profile/sophia\": {\n \"text\": \"sophia\",\n \"rels\": [\"parent\"]\n },\n \"http://example.com/profile/charlie\": {\n \"text\": \"charlie\",\n \"rels\": [\"sibling\"]\n },\n \"http://example.com/profile/olivia\": {\n \"text\": \"olivia\",\n \"rels\": [\"spouse\"]\n },\n \"http://example.com/profile/james\": {\n \"text\": \"james\",\n \"rels\": [\"kin\"]\n },\n \"http://example.com/profile/ava\": {\n \"text\": \"ava\",\n \"rels\": [\"muse\"]\n },\n \"http://example.com/profile/joshua\": {\n \"text\": \"joshua\",\n \"rels\": [\"crush\"]\n },\n \"http://example.com/profile/chloe\": {\n \"text\": \"chloe\",\n \"rels\": [\"date\"]\n },\n \"http://example.com/profile/alfie\": {\n \"text\": \"alfie\",\n \"rels\": [\"sweetheart\"]\n },\n \"http://example.com/profile/isla\": {\n \"text\": \"isla\",\n \"rels\": [\"me\"]\n }\n }\n}\n","html":"<ul>\n <li><a rel=\"friend\" href=\"http://example.com/profile/jane\">jane</a></li>\n <li><a rel=\"acquaintance\" href=\"http://example.com/profile/jeo\">jeo</a></li>\n <li><a rel=\"contact\" href=\"http://example.com/profile/lily\">lily</a></li>\n <li><a rel=\"met\" href=\"http://example.com/profile/oliver\">oliver</a></li>\n <li><a rel=\"co-worker\" href=\"http://example.com/profile/emily\">emily</a></li>\n <li><a rel=\"colleague\" href=\"http://example.com/profile/jack\">jack</a></li>\n <li><a rel=\"neighbor\" href=\"http://example.com/profile/isabella\">isabella</a></li>\n <li><a rel=\"child\" href=\"http://example.com/profile/harry\">harry</a></li>\n <li><a rel=\"parent\" href=\"http://example.com/profile/sophia\">sophia</a></li>\n <li><a rel=\"sibling\" href=\"http://example.com/profile/charlie\">charlie</a></li>\n <li><a rel=\"spouse\" href=\"http://example.com/profile/olivia\">olivia</a></li>\n <li><a rel=\"kin\" href=\"http://example.com/profile/james\">james</a></li>\n <li><a rel=\"muse\" href=\"http://example.com/profile/ava\">ava</a></li>\n <li><a rel=\"crush\" href=\"http://example.com/profile/joshua\">joshua</a></li>\n <li><a rel=\"date\" href=\"http://example.com/profile/chloe\">chloe</a></li>\n <li><a rel=\"sweetheart\" href=\"http://example.com/profile/alfie\">alfie</a></li>\n <li><a rel=\"me\" href=\"http://example.com/profile/isla\">isla</a></li>\n</ul>","name":"mf-v2-rel-xfn-all"},{"json":"{\n \"items\": [],\n \"rels\": {\n \"me\": [\"http://twitter.com/glennjones\", \"http://delicious.com/glennjonesnet/\", \"https://plus.google.com/u/0/105161464208920272734/about\", \"http://lanyrd.com/people/glennjones/\", \"http://github.com/glennjones\", \"http://www.flickr.com/photos/glennjonesnet/\", \"http://www.linkedin.com/in/glennjones\", \"http://www.slideshare.net/glennjones/presentations\"]\n },\n \"rel-urls\": {\n \"http://twitter.com/glennjones\": {\n \"text\": \"twitter\",\n \"rels\": [\"me\"]\n },\n \"http://delicious.com/glennjonesnet/\": {\n \"text\": \"delicious\",\n \"rels\": [\"me\"]\n },\n \"https://plus.google.com/u/0/105161464208920272734/about\": {\n \"text\": \"google+\",\n \"rels\": [\"me\"]\n },\n \"http://lanyrd.com/people/glennjones/\": {\n \"text\": \"lanyrd\",\n \"rels\": [\"me\"]\n },\n \"http://github.com/glennjones\": {\n \"text\": \"github\",\n \"rels\": [\"me\"]\n },\n \"http://www.flickr.com/photos/glennjonesnet/\": {\n \"text\": \"flickr\",\n \"rels\": [\"me\"]\n },\n \"http://www.linkedin.com/in/glennjones\": {\n \"text\": \"linkedin\",\n \"rels\": [\"me\"]\n },\n \"http://www.slideshare.net/glennjones/presentations\": {\n \"text\": \"slideshare\",\n \"rels\": [\"me\"]\n }\n }\n}\n","html":"<ul>\n <li><a rel=\"me\" href=\"http://twitter.com/glennjones\">twitter</a></li>\n <li><a rel=\"me\" href=\"http://delicious.com/glennjonesnet/\">delicious</a></li>\n <li><a rel=\"me\" href=\"https://plus.google.com/u/0/105161464208920272734/about\">google+</a></li>\n <li><a rel=\"me\" href=\"http://lanyrd.com/people/glennjones/\">lanyrd</a></li>\n <li><a rel=\"me\" href=\"http://github.com/glennjones\">github</a></li>\n <li><a rel=\"me\" href=\"http://www.flickr.com/photos/glennjonesnet/\">flickr</a></li>\n <li><a rel=\"me\" href=\"http://www.linkedin.com/in/glennjones\">linkedin</a></li>\n <li><a rel=\"me\" href=\"http://www.slideshare.net/glennjones/presentations\">slideshare</a></li>\n</ul>","name":"mf-v2-rel-xfn-elsewhere"}]}
diff --git a/toolkit/components/microformats/test/static/javascript/deep-diff-0.3.1.min.js b/toolkit/components/microformats/test/static/javascript/deep-diff-0.3.1.min.js
deleted file mode 100644
index e200019c0..000000000
--- a/toolkit/components/microformats/test/static/javascript/deep-diff-0.3.1.min.js
+++ /dev/null
@@ -1,5 +0,0 @@
-/*!
- * deep-diff.
- * Licensed under the MIT License.
- */
-(function(e,t){"use strict";if(typeof define==="function"&&define.amd){define([],t)}else if(typeof exports==="object"){module.exports=t()}else{e.DeepDiff=t()}})(this,function(e){"use strict";var t,n,r=[];if(typeof global==="object"&&global){t=global}else if(typeof window!=="undefined"){t=window}else{t={}}n=t.DeepDiff;if(n){r.push(function(){if("undefined"!==typeof n&&t.DeepDiff===p){t.DeepDiff=n;n=e}})}function a(e,t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}function i(e,t){Object.defineProperty(this,"kind",{value:e,enumerable:true});if(t&&t.length){Object.defineProperty(this,"path",{value:t,enumerable:true})}}function f(e,t,n){f.super_.call(this,"E",e);Object.defineProperty(this,"lhs",{value:t,enumerable:true});Object.defineProperty(this,"rhs",{value:n,enumerable:true})}a(f,i);function u(e,t){u.super_.call(this,"N",e);Object.defineProperty(this,"rhs",{value:t,enumerable:true})}a(u,i);function l(e,t){l.super_.call(this,"D",e);Object.defineProperty(this,"lhs",{value:t,enumerable:true})}a(l,i);function s(e,t,n){s.super_.call(this,"A",e);Object.defineProperty(this,"index",{value:t,enumerable:true});Object.defineProperty(this,"item",{value:n,enumerable:true})}a(s,i);function h(e,t,n){var r=e.slice((n||t)+1||e.length);e.length=t<0?e.length+t:t;e.push.apply(e,r);return e}function c(e){var t=typeof e;if(t!=="object"){return t}if(e===Math){return"math"}else if(e===null){return"null"}else if(Array.isArray(e)){return"array"}else if(e instanceof Date){return"date"}else if(/^\/.*\//.test(e.toString())){return"regexp"}return"object"}function o(t,n,r,a,i,p,b){i=i||[];var d=i.slice(0);if(typeof p!=="undefined"){if(a&&a(d,p,{lhs:t,rhs:n})){return}d.push(p)}var v=typeof t;var y=typeof n;if(v==="undefined"){if(y!=="undefined"){r(new u(d,n))}}else if(y==="undefined"){r(new l(d,t))}else if(c(t)!==c(n)){r(new f(d,t,n))}else if(t instanceof Date&&n instanceof Date&&t-n!==0){r(new f(d,t,n))}else if(v==="object"&&t!==null&&n!==null){b=b||[];if(b.indexOf(t)<0){b.push(t);if(Array.isArray(t)){var k,m=t.length;for(k=0;k<t.length;k++){if(k>=n.length){r(new s(d,k,new l(e,t[k])))}else{o(t[k],n[k],r,a,d,k,b)}}while(k<n.length){r(new s(d,k,new u(e,n[k++])))}}else{var g=Object.keys(t);var w=Object.keys(n);g.forEach(function(i,f){var u=w.indexOf(i);if(u>=0){o(t[i],n[i],r,a,d,i,b);w=h(w,u)}else{o(t[i],e,r,a,d,i,b)}});w.forEach(function(t){o(e,n[t],r,a,d,t,b)})}b.length=b.length-1}}else if(t!==n){if(!(v==="number"&&isNaN(t)&&isNaN(n))){r(new f(d,t,n))}}}function p(t,n,r,a){a=a||[];o(t,n,function(e){if(e){a.push(e)}},r);return a.length?a:e}function b(e,t,n){if(n.path&&n.path.length){var r=e[t],a,i=n.path.length-1;for(a=0;a<i;a++){r=r[n.path[a]]}switch(n.kind){case"A":b(r[n.path[a]],n.index,n.item);break;case"D":delete r[n.path[a]];break;case"E":case"N":r[n.path[a]]=n.rhs;break}}else{switch(n.kind){case"A":b(e[t],n.index,n.item);break;case"D":e=h(e,t);break;case"E":case"N":e[t]=n.rhs;break}}return e}function d(e,t,n){if(e&&t&&n&&n.kind){var r=e,a=-1,i=n.path.length-1;while(++a<i){if(typeof r[n.path[a]]==="undefined"){r[n.path[a]]=typeof n.path[a]==="number"?[]:{}}r=r[n.path[a]]}switch(n.kind){case"A":b(r[n.path[a]],n.index,n.item);break;case"D":delete r[n.path[a]];break;case"E":case"N":r[n.path[a]]=n.rhs;break}}}function v(e,t,n){if(n.path&&n.path.length){var r=e[t],a,i=n.path.length-1;for(a=0;a<i;a++){r=r[n.path[a]]}switch(n.kind){case"A":v(r[n.path[a]],n.index,n.item);break;case"D":r[n.path[a]]=n.lhs;break;case"E":r[n.path[a]]=n.lhs;break;case"N":delete r[n.path[a]];break}}else{switch(n.kind){case"A":v(e[t],n.index,n.item);break;case"D":e[t]=n.lhs;break;case"E":e[t]=n.lhs;break;case"N":e=h(e,t);break}}return e}function y(e,t,n){if(e&&t&&n&&n.kind){var r=e,a,i;i=n.path.length-1;for(a=0;a<i;a++){if(typeof r[n.path[a]]==="undefined"){r[n.path[a]]={}}r=r[n.path[a]]}switch(n.kind){case"A":v(r[n.path[a]],n.index,n.item);break;case"D":r[n.path[a]]=n.lhs;break;case"E":r[n.path[a]]=n.lhs;break;case"N":delete r[n.path[a]];break}}}function k(e,t,n){if(e&&t){var r=function(r){if(!n||n(e,t,r)){d(e,t,r)}};o(e,t,r)}}Object.defineProperties(p,{diff:{value:p,enumerable:true},observableDiff:{value:o,enumerable:true},applyDiff:{value:k,enumerable:true},applyChange:{value:d,enumerable:true},revertChange:{value:y,enumerable:true},isConflict:{value:function(){return"undefined"!==typeof n},enumerable:true},noConflict:{value:function(){if(r){r.forEach(function(e){e()});r=null}return p},enumerable:true}});return p});
diff --git a/toolkit/components/microformats/test/static/javascript/mocha.js b/toolkit/components/microformats/test/static/javascript/mocha.js
deleted file mode 100644
index 100850e5d..000000000
--- a/toolkit/components/microformats/test/static/javascript/mocha.js
+++ /dev/null
@@ -1,6573 +0,0 @@
-(function(){
-
-// CommonJS require()
-
-function require(p){
- var path = require.resolve(p)
- , mod = require.modules[path];
- if (!mod) throw new Error('failed to require "' + p + '"');
- if (!mod.exports) {
- mod.exports = {};
- mod.call(mod.exports, mod, mod.exports, require.relative(path));
- }
- return mod.exports;
- }
-
-require.modules = {};
-
-require.resolve = function (path){
- var orig = path
- , reg = path + '.js'
- , index = path + '/index.js';
- return require.modules[reg] && reg
- || require.modules[index] && index
- || orig;
- };
-
-require.register = function (path, fn){
- require.modules[path] = fn;
- };
-
-require.relative = function (parent) {
- return function(p){
- if ('.' != p.charAt(0)) return require(p);
-
- var path = parent.split('/')
- , segs = p.split('/');
- path.pop();
-
- for (var i = 0; i < segs.length; i++) {
- var seg = segs[i];
- if ('..' == seg) path.pop();
- else if ('.' != seg) path.push(seg);
- }
-
- return require(path.join('/'));
- };
- };
-
-
-require.register("browser/debug.js", function(module, exports, require){
-module.exports = function(type){
- return function(){
- }
-};
-
-}); // module: browser/debug.js
-
-require.register("browser/diff.js", function(module, exports, require){
-/* See LICENSE file for terms of use */
-
-/*
- * Text diff implementation.
- *
- * This library supports the following APIS:
- * JsDiff.diffChars: Character by character diff
- * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
- * JsDiff.diffLines: Line based diff
- *
- * JsDiff.diffCss: Diff targeted at CSS content
- *
- * These methods are based on the implementation proposed in
- * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
- * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
- */
-var JsDiff = (function() {
- /*jshint maxparams: 5*/
- function clonePath(path) {
- return { newPos: path.newPos, components: path.components.slice(0) };
- }
- function removeEmpty(array) {
- var ret = [];
- for (var i = 0; i < array.length; i++) {
- if (array[i]) {
- ret.push(array[i]);
- }
- }
- return ret;
- }
- function escapeHTML(s) {
- var n = s;
- n = n.replace(/&/g, '&amp;');
- n = n.replace(/</g, '&lt;');
- n = n.replace(/>/g, '&gt;');
- n = n.replace(/"/g, '&quot;');
-
- return n;
- }
-
- var Diff = function(ignoreWhitespace) {
- this.ignoreWhitespace = ignoreWhitespace;
- };
- Diff.prototype = {
- diff: function(oldString, newString) {
- // Handle the identity case (this is due to unrolling editLength == 0
- if (newString === oldString) {
- return [{ value: newString }];
- }
- if (!newString) {
- return [{ value: oldString, removed: true }];
- }
- if (!oldString) {
- return [{ value: newString, added: true }];
- }
-
- newString = this.tokenize(newString);
- oldString = this.tokenize(oldString);
-
- var newLen = newString.length, oldLen = oldString.length;
- var maxEditLength = newLen + oldLen;
- var bestPath = [{ newPos: -1, components: [] }];
-
- // Seed editLength = 0
- var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
- if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
- return bestPath[0].components;
- }
-
- for (var editLength = 1; editLength <= maxEditLength; editLength++) {
- for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
- var basePath;
- var addPath = bestPath[diagonalPath-1],
- removePath = bestPath[diagonalPath+1];
- oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
- if (addPath) {
- // No one else is going to attempt to use this value, clear it
- bestPath[diagonalPath-1] = undefined;
- }
-
- var canAdd = addPath && addPath.newPos+1 < newLen;
- var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
- if (!canAdd && !canRemove) {
- bestPath[diagonalPath] = undefined;
- continue;
- }
-
- // Select the diagonal that we want to branch from. We select the prior
- // path whose position in the new string is the farthest from the origin
- // and does not pass the bounds of the diff graph
- if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
- basePath = clonePath(removePath);
- this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
- } else {
- basePath = clonePath(addPath);
- basePath.newPos++;
- this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
- }
-
- oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
-
- if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
- return basePath.components;
- } else {
- bestPath[diagonalPath] = basePath;
- }
- }
- }
- },
-
- pushComponent: function(components, value, added, removed) {
- var last = components[components.length-1];
- if (last && last.added === added && last.removed === removed) {
- // We need to clone here as the component clone operation is just
- // as shallow array clone
- components[components.length-1] =
- {value: this.join(last.value, value), added: added, removed: removed };
- } else {
- components.push({value: value, added: added, removed: removed });
- }
- },
- extractCommon: function(basePath, newString, oldString, diagonalPath) {
- var newLen = newString.length,
- oldLen = oldString.length,
- newPos = basePath.newPos,
- oldPos = newPos - diagonalPath;
- while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
- newPos++;
- oldPos++;
-
- this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
- }
- basePath.newPos = newPos;
- return oldPos;
- },
-
- equals: function(left, right) {
- var reWhitespace = /\S/;
- if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
- return true;
- } else {
- return left === right;
- }
- },
- join: function(left, right) {
- return left + right;
- },
- tokenize: function(value) {
- return value;
- }
- };
-
- var CharDiff = new Diff();
-
- var WordDiff = new Diff(true);
- var WordWithSpaceDiff = new Diff();
- WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
- return removeEmpty(value.split(/(\s+|\b)/));
- };
-
- var CssDiff = new Diff(true);
- CssDiff.tokenize = function(value) {
- return removeEmpty(value.split(/([{}:;,]|\s+)/));
- };
-
- var LineDiff = new Diff();
- LineDiff.tokenize = function(value) {
- var retLines = [],
- lines = value.split(/^/m);
-
- for(var i = 0; i < lines.length; i++) {
- var line = lines[i],
- lastLine = lines[i - 1];
-
- // Merge lines that may contain windows new lines
- if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') {
- retLines[retLines.length - 1] += '\n';
- } else if (line) {
- retLines.push(line);
- }
- }
-
- return retLines;
- };
-
- return {
- Diff: Diff,
-
- diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
- diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
- diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
- diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
-
- diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
-
- createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
- var ret = [];
-
- ret.push('Index: ' + fileName);
- ret.push('===================================================================');
- ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
- ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
-
- var diff = LineDiff.diff(oldStr, newStr);
- if (!diff[diff.length-1].value) {
- diff.pop(); // Remove trailing newline add
- }
- diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
-
- function contextLines(lines) {
- return lines.map(function(entry) { return ' ' + entry; });
- }
- function eofNL(curRange, i, current) {
- var last = diff[diff.length-2],
- isLast = i === diff.length-2,
- isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
-
- // Figure out if this is the last line for the given file and missing NL
- if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
- curRange.push('\\ No newline at end of file');
- }
- }
-
- var oldRangeStart = 0, newRangeStart = 0, curRange = [],
- oldLine = 1, newLine = 1;
- for (var i = 0; i < diff.length; i++) {
- var current = diff[i],
- lines = current.lines || current.value.replace(/\n$/, '').split('\n');
- current.lines = lines;
-
- if (current.added || current.removed) {
- if (!oldRangeStart) {
- var prev = diff[i-1];
- oldRangeStart = oldLine;
- newRangeStart = newLine;
-
- if (prev) {
- curRange = contextLines(prev.lines.slice(-4));
- oldRangeStart -= curRange.length;
- newRangeStart -= curRange.length;
- }
- }
- curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
- eofNL(curRange, i, current);
-
- if (current.added) {
- newLine += lines.length;
- } else {
- oldLine += lines.length;
- }
- } else {
- if (oldRangeStart) {
- // Close out any changes that have been output (or join overlapping)
- if (lines.length <= 8 && i < diff.length-2) {
- // Overlapping
- curRange.push.apply(curRange, contextLines(lines));
- } else {
- // end the range and output
- var contextSize = Math.min(lines.length, 4);
- ret.push(
- '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
- + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
- + ' @@');
- ret.push.apply(ret, curRange);
- ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
- if (lines.length <= 4) {
- eofNL(ret, i, current);
- }
-
- oldRangeStart = 0; newRangeStart = 0; curRange = [];
- }
- }
- oldLine += lines.length;
- newLine += lines.length;
- }
- }
-
- return ret.join('\n') + '\n';
- },
-
- applyPatch: function(oldStr, uniDiff) {
- var diffstr = uniDiff.split('\n');
- var diff = [];
- var remEOFNL = false,
- addEOFNL = false;
-
- for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
- if(diffstr[i][0] === '@') {
- var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
- diff.unshift({
- start:meh[3],
- oldlength:meh[2],
- oldlines:[],
- newlength:meh[4],
- newlines:[]
- });
- } else if(diffstr[i][0] === '+') {
- diff[0].newlines.push(diffstr[i].substr(1));
- } else if(diffstr[i][0] === '-') {
- diff[0].oldlines.push(diffstr[i].substr(1));
- } else if(diffstr[i][0] === ' ') {
- diff[0].newlines.push(diffstr[i].substr(1));
- diff[0].oldlines.push(diffstr[i].substr(1));
- } else if(diffstr[i][0] === '\\') {
- if (diffstr[i-1][0] === '+') {
- remEOFNL = true;
- } else if(diffstr[i-1][0] === '-') {
- addEOFNL = true;
- }
- }
- }
-
- var str = oldStr.split('\n');
- for (i = diff.length - 1; i >= 0; i--) {
- var d = diff[i];
- for (var j = 0; j < d.oldlength; j++) {
- if(str[d.start-1+j] !== d.oldlines[j]) {
- return false;
- }
- }
- Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
- }
-
- if (remEOFNL) {
- while (!str[str.length-1]) {
- str.pop();
- }
- } else if (addEOFNL) {
- str.push('');
- }
- return str.join('\n');
- },
-
- convertChangesToXML: function(changes){
- var ret = [];
- for ( var i = 0; i < changes.length; i++) {
- var change = changes[i];
- if (change.added) {
- ret.push('<ins>');
- } else if (change.removed) {
- ret.push('<del>');
- }
-
- ret.push(escapeHTML(change.value));
-
- if (change.added) {
- ret.push('</ins>');
- } else if (change.removed) {
- ret.push('</del>');
- }
- }
- return ret.join('');
- },
-
- // See: http://code.google.com/p/google-diff-match-patch/wiki/API
- convertChangesToDMP: function(changes){
- var ret = [], change;
- for ( var i = 0; i < changes.length; i++) {
- change = changes[i];
- var order = 0;
- if (change.added) {
- order = 1;
- } else if (change.removed) {
- order = -1;
- }
- ret.push([order, change.value]);
- }
- return ret;
- }
- };
-})();
-
-if (typeof module !== 'undefined') {
- module.exports = JsDiff;
-}
-
-}); // module: browser/diff.js
-
-require.register("browser/escape-string-regexp.js", function(module, exports, require){
-'use strict';
-
-var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
-
-module.exports = function (str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
- }
-
- return str.replace(matchOperatorsRe, '\\$&');
-};
-
-}); // module: browser/escape-string-regexp.js
-
-require.register("browser/events.js", function(module, exports, require){
-/**
- * Module exports.
- */
-
-exports.EventEmitter = EventEmitter;
-
-/**
- * Check if `obj` is an array.
- */
-
-function isArray(obj) {
- return '[object Array]' == {}.toString.call(obj);
-}
-
-/**
- * Event emitter constructor.
- *
- * @api public
- */
-
-function EventEmitter(){}
-
-/**
- * Adds a listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.on = function (name, fn) {
- if (!this.$events) {
- this.$events = {};
- }
-
- if (!this.$events[name]) {
- this.$events[name] = fn;
- } else if (isArray(this.$events[name])) {
- this.$events[name].push(fn);
- } else {
- this.$events[name] = [this.$events[name], fn];
- }
-
- return this;
-};
-
-EventEmitter.prototype.addListener = EventEmitter.prototype.on;
-
-/**
- * Adds a volatile listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.once = function (name, fn) {
- var self = this;
-
- function on () {
- self.removeListener(name, on);
- fn.apply(this, arguments);
- }
-
- on.listener = fn;
- this.on(name, on);
-
- return this;
-};
-
-/**
- * Removes a listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.removeListener = function (name, fn) {
- if (this.$events && this.$events[name]) {
- var list = this.$events[name];
-
- if (isArray(list)) {
- var pos = -1;
-
- for (var i = 0, l = list.length; i < l; i++) {
- if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
- pos = i;
- break;
- }
- }
-
- if (pos < 0) {
- return this;
- }
-
- list.splice(pos, 1);
-
- if (!list.length) {
- delete this.$events[name];
- }
- } else if (list === fn || (list.listener && list.listener === fn)) {
- delete this.$events[name];
- }
- }
-
- return this;
-};
-
-/**
- * Removes all listeners for an event.
- *
- * @api public
- */
-
-EventEmitter.prototype.removeAllListeners = function (name) {
- if (name === undefined) {
- this.$events = {};
- return this;
- }
-
- if (this.$events && this.$events[name]) {
- this.$events[name] = null;
- }
-
- return this;
-};
-
-/**
- * Gets all listeners for a certain event.
- *
- * @api public
- */
-
-EventEmitter.prototype.listeners = function (name) {
- if (!this.$events) {
- this.$events = {};
- }
-
- if (!this.$events[name]) {
- this.$events[name] = [];
- }
-
- if (!isArray(this.$events[name])) {
- this.$events[name] = [this.$events[name]];
- }
-
- return this.$events[name];
-};
-
-/**
- * Emits an event.
- *
- * @api public
- */
-
-EventEmitter.prototype.emit = function (name) {
- if (!this.$events) {
- return false;
- }
-
- var handler = this.$events[name];
-
- if (!handler) {
- return false;
- }
-
- var args = [].slice.call(arguments, 1);
-
- if ('function' == typeof handler) {
- handler.apply(this, args);
- } else if (isArray(handler)) {
- var listeners = handler.slice();
-
- for (var i = 0, l = listeners.length; i < l; i++) {
- listeners[i].apply(this, args);
- }
- } else {
- return false;
- }
-
- return true;
-};
-
-}); // module: browser/events.js
-
-require.register("browser/fs.js", function(module, exports, require){
-
-}); // module: browser/fs.js
-
-require.register("browser/glob.js", function(module, exports, require){
-
-}); // module: browser/glob.js
-
-require.register("browser/path.js", function(module, exports, require){
-
-}); // module: browser/path.js
-
-require.register("browser/progress.js", function(module, exports, require){
-/**
- * Expose `Progress`.
- */
-
-module.exports = Progress;
-
-/**
- * Initialize a new `Progress` indicator.
- */
-
-function Progress() {
- this.percent = 0;
- this.size(0);
- this.fontSize(11);
- this.font('helvetica, arial, sans-serif');
-}
-
-/**
- * Set progress size to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.size = function(n){
- this._size = n;
- return this;
-};
-
-/**
- * Set text to `str`.
- *
- * @param {String} str
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.text = function(str){
- this._text = str;
- return this;
-};
-
-/**
- * Set font size to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.fontSize = function(n){
- this._fontSize = n;
- return this;
-};
-
-/**
- * Set font `family`.
- *
- * @param {String} family
- * @return {Progress} for chaining
- */
-
-Progress.prototype.font = function(family){
- this._font = family;
- return this;
-};
-
-/**
- * Update percentage to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- */
-
-Progress.prototype.update = function(n){
- this.percent = n;
- return this;
-};
-
-/**
- * Draw on `ctx`.
- *
- * @param {CanvasRenderingContext2d} ctx
- * @return {Progress} for chaining
- */
-
-Progress.prototype.draw = function(ctx){
- try {
- var percent = Math.min(this.percent, 100)
- , size = this._size
- , half = size / 2
- , x = half
- , y = half
- , rad = half - 1
- , fontSize = this._fontSize;
-
- ctx.font = fontSize + 'px ' + this._font;
-
- var angle = Math.PI * 2 * (percent / 100);
- ctx.clearRect(0, 0, size, size);
-
- // outer circle
- ctx.strokeStyle = '#9f9f9f';
- ctx.beginPath();
- ctx.arc(x, y, rad, 0, angle, false);
- ctx.stroke();
-
- // inner circle
- ctx.strokeStyle = '#eee';
- ctx.beginPath();
- ctx.arc(x, y, rad - 1, 0, angle, true);
- ctx.stroke();
-
- // text
- var text = this._text || (percent | 0) + '%'
- , w = ctx.measureText(text).width;
-
- ctx.fillText(
- text
- , x - w / 2 + 1
- , y + fontSize / 2 - 1);
- } catch (ex) {} //don't fail if we can't render progress
- return this;
-};
-
-}); // module: browser/progress.js
-
-require.register("browser/tty.js", function(module, exports, require){
-exports.isatty = function(){
- return true;
-};
-
-exports.getWindowSize = function(){
- if ('innerHeight' in global) {
- return [global.innerHeight, global.innerWidth];
- } else {
- // In a Web Worker, the DOM Window is not available.
- return [640, 480];
- }
-};
-
-}); // module: browser/tty.js
-
-require.register("context.js", function(module, exports, require){
-/**
- * Expose `Context`.
- */
-
-module.exports = Context;
-
-/**
- * Initialize a new `Context`.
- *
- * @api private
- */
-
-function Context(){}
-
-/**
- * Set or get the context `Runnable` to `runnable`.
- *
- * @param {Runnable} runnable
- * @return {Context}
- * @api private
- */
-
-Context.prototype.runnable = function(runnable){
- if (0 == arguments.length) return this._runnable;
- this.test = this._runnable = runnable;
- return this;
-};
-
-/**
- * Set test timeout `ms`.
- *
- * @param {Number} ms
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.timeout = function(ms){
- if (arguments.length === 0) return this.runnable().timeout();
- this.runnable().timeout(ms);
- return this;
-};
-
-/**
- * Set test timeout `enabled`.
- *
- * @param {Boolean} enabled
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.enableTimeouts = function (enabled) {
- this.runnable().enableTimeouts(enabled);
- return this;
-};
-
-
-/**
- * Set test slowness threshold `ms`.
- *
- * @param {Number} ms
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.slow = function(ms){
- this.runnable().slow(ms);
- return this;
-};
-
-/**
- * Mark a test as skipped.
- *
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.skip = function(){
- this.runnable().skip();
- return this;
-};
-
-/**
- * Inspect the context void of `._runnable`.
- *
- * @return {String}
- * @api private
- */
-
-Context.prototype.inspect = function(){
- return JSON.stringify(this, function(key, val){
- if ('_runnable' == key) return undefined;
- if ('test' == key) return undefined;
- return val;
- }, 2);
-};
-
-}); // module: context.js
-
-require.register("hook.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Runnable = require('./runnable');
-
-/**
- * Expose `Hook`.
- */
-
-module.exports = Hook;
-
-/**
- * Initialize a new `Hook` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Hook(title, fn) {
- Runnable.call(this, title, fn);
- this.type = 'hook';
-}
-
-/**
- * Inherit from `Runnable.prototype`.
- */
-
-function F(){}
-F.prototype = Runnable.prototype;
-Hook.prototype = new F;
-Hook.prototype.constructor = Hook;
-
-
-/**
- * Get or set the test `err`.
- *
- * @param {Error} err
- * @return {Error}
- * @api public
- */
-
-Hook.prototype.error = function(err){
- if (0 == arguments.length) {
- err = this._error;
- this._error = null;
- return err;
- }
-
- this._error = err;
-};
-
-}); // module: hook.js
-
-require.register("interfaces/bdd.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test')
- , utils = require('../utils')
- , escapeRe = require('browser/escape-string-regexp');
-
-/**
- * BDD-style interface:
- *
- * describe('Array', function(){
- * describe('#indexOf()', function(){
- * it('should return -1 when not present', function(){
- *
- * });
- *
- * it('should return the index when present', function(){
- *
- * });
- * });
- * });
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('pre-require', function(context, file, mocha){
-
- var common = require('./common')(suites, context);
-
- context.before = common.before;
- context.after = common.after;
- context.beforeEach = common.beforeEach;
- context.afterEach = common.afterEach;
- context.run = mocha.options.delay && common.runWithSuite(suite);
- /**
- * Describe a "suite" with the given `title`
- * and callback `fn` containing nested suites
- * and/or tests.
- */
-
- context.describe = context.context = function(title, fn){
- var suite = Suite.create(suites[0], title);
- suite.file = file;
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- return suite;
- };
-
- /**
- * Pending describe.
- */
-
- context.xdescribe =
- context.xcontext =
- context.describe.skip = function(title, fn){
- var suite = Suite.create(suites[0], title);
- suite.pending = true;
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- };
-
- /**
- * Exclusive suite.
- */
-
- context.describe.only = function(title, fn){
- var suite = context.describe(title, fn);
- mocha.grep(suite.fullTitle());
- return suite;
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.it = context.specify = function(title, fn){
- var suite = suites[0];
- if (suite.pending) fn = null;
- var test = new Test(title, fn);
- test.file = file;
- suite.addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.it.only = function(title, fn){
- var test = context.it(title, fn);
- var reString = '^' + escapeRe(test.fullTitle()) + '$';
- mocha.grep(new RegExp(reString));
- return test;
- };
-
- /**
- * Pending test case.
- */
-
- context.xit =
- context.xspecify =
- context.it.skip = function(title){
- context.it(title);
- };
-
- });
-};
-
-}); // module: interfaces/bdd.js
-
-require.register("interfaces/common.js", function(module, exports, require){
-/**
- * Functions common to more than one interface
- * @module lib/interfaces/common
- */
-
-'use strict';
-
-module.exports = function (suites, context) {
-
- return {
- /**
- * This is only present if flag --delay is passed into Mocha. It triggers
- * root suite execution. Returns a function which runs the root suite.
- */
- runWithSuite: function runWithSuite(suite) {
- return function run() {
- suite.run();
- };
- },
-
- /**
- * Execute before running tests.
- */
- before: function (name, fn) {
- suites[0].beforeAll(name, fn);
- },
-
- /**
- * Execute after running tests.
- */
- after: function (name, fn) {
- suites[0].afterAll(name, fn);
- },
-
- /**
- * Execute before each test case.
- */
- beforeEach: function (name, fn) {
- suites[0].beforeEach(name, fn);
- },
-
- /**
- * Execute after each test case.
- */
- afterEach: function (name, fn) {
- suites[0].afterEach(name, fn);
- },
-
- test: {
- /**
- * Pending test case.
- */
- skip: function (title) {
- context.test(title);
- }
- }
- }
-};
-
-}); // module: interfaces/common.js
-
-require.register("interfaces/exports.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test');
-
-/**
- * TDD-style interface:
- *
- * exports.Array = {
- * '#indexOf()': {
- * 'should return -1 when the value is not present': function(){
- *
- * },
- *
- * 'should return the correct index when the value is present': function(){
- *
- * }
- * }
- * };
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('require', visit);
-
- function visit(obj, file) {
- var suite;
- for (var key in obj) {
- if ('function' == typeof obj[key]) {
- var fn = obj[key];
- switch (key) {
- case 'before':
- suites[0].beforeAll(fn);
- break;
- case 'after':
- suites[0].afterAll(fn);
- break;
- case 'beforeEach':
- suites[0].beforeEach(fn);
- break;
- case 'afterEach':
- suites[0].afterEach(fn);
- break;
- default:
- var test = new Test(key, fn);
- test.file = file;
- suites[0].addTest(test);
- }
- } else {
- suite = Suite.create(suites[0], key);
- suites.unshift(suite);
- visit(obj[key]);
- suites.shift();
- }
- }
- }
-};
-
-}); // module: interfaces/exports.js
-
-require.register("interfaces/index.js", function(module, exports, require){
-exports.bdd = require('./bdd');
-exports.tdd = require('./tdd');
-exports.qunit = require('./qunit');
-exports.exports = require('./exports');
-
-}); // module: interfaces/index.js
-
-require.register("interfaces/qunit.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test')
- , escapeRe = require('browser/escape-string-regexp')
- , utils = require('../utils');
-
-/**
- * QUnit-style interface:
- *
- * suite('Array');
- *
- * test('#length', function(){
- * var arr = [1,2,3];
- * ok(arr.length == 3);
- * });
- *
- * test('#indexOf()', function(){
- * var arr = [1,2,3];
- * ok(arr.indexOf(1) == 0);
- * ok(arr.indexOf(2) == 1);
- * ok(arr.indexOf(3) == 2);
- * });
- *
- * suite('String');
- *
- * test('#length', function(){
- * ok('foo'.length == 3);
- * });
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('pre-require', function(context, file, mocha){
-
- var common = require('./common')(suites, context);
-
- context.before = common.before;
- context.after = common.after;
- context.beforeEach = common.beforeEach;
- context.afterEach = common.afterEach;
- context.run = mocha.options.delay && common.runWithSuite(suite);
- /**
- * Describe a "suite" with the given `title`.
- */
-
- context.suite = function(title){
- if (suites.length > 1) suites.shift();
- var suite = Suite.create(suites[0], title);
- suite.file = file;
- suites.unshift(suite);
- return suite;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.suite.only = function(title, fn){
- var suite = context.suite(title, fn);
- mocha.grep(suite.fullTitle());
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.test = function(title, fn){
- var test = new Test(title, fn);
- test.file = file;
- suites[0].addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.test.only = function(title, fn){
- var test = context.test(title, fn);
- var reString = '^' + escapeRe(test.fullTitle()) + '$';
- mocha.grep(new RegExp(reString));
- };
-
- context.test.skip = common.test.skip;
-
- });
-};
-
-}); // module: interfaces/qunit.js
-
-require.register("interfaces/tdd.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
- , Test = require('../test')
- , escapeRe = require('browser/escape-string-regexp')
- , utils = require('../utils');
-
-/**
- * TDD-style interface:
- *
- * suite('Array', function(){
- * suite('#indexOf()', function(){
- * suiteSetup(function(){
- *
- * });
- *
- * test('should return -1 when not present', function(){
- *
- * });
- *
- * test('should return the index when present', function(){
- *
- * });
- *
- * suiteTeardown(function(){
- *
- * });
- * });
- * });
- *
- */
-
-module.exports = function(suite){
- var suites = [suite];
-
- suite.on('pre-require', function(context, file, mocha){
-
- var common = require('./common')(suites, context);
-
- context.setup = common.beforeEach;
- context.teardown = common.afterEach;
- context.suiteSetup = common.before;
- context.suiteTeardown = common.after;
- context.run = mocha.options.delay && common.runWithSuite(suite);
- /**
- * Describe a "suite" with the given `title`
- * and callback `fn` containing nested suites
- * and/or tests.
- */
-
- context.suite = function(title, fn){
- var suite = Suite.create(suites[0], title);
- suite.file = file;
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- return suite;
- };
-
- /**
- * Pending suite.
- */
- context.suite.skip = function(title, fn) {
- var suite = Suite.create(suites[0], title);
- suite.pending = true;
- suites.unshift(suite);
- fn.call(suite);
- suites.shift();
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.suite.only = function(title, fn){
- var suite = context.suite(title, fn);
- mocha.grep(suite.fullTitle());
- };
-
- /**
- * Describe a specification or test-case
- * with the given `title` and callback `fn`
- * acting as a thunk.
- */
-
- context.test = function(title, fn){
- var suite = suites[0];
- if (suite.pending) fn = null;
- var test = new Test(title, fn);
- test.file = file;
- suite.addTest(test);
- return test;
- };
-
- /**
- * Exclusive test-case.
- */
-
- context.test.only = function(title, fn){
- var test = context.test(title, fn);
- var reString = '^' + escapeRe(test.fullTitle()) + '$';
- mocha.grep(new RegExp(reString));
- };
-
- context.test.skip = common.test.skip;
- });
-};
-
-}); // module: interfaces/tdd.js
-
-require.register("mocha.js", function(module, exports, require){
-/*!
- * mocha
- * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var path = require('browser/path')
- , escapeRe = require('browser/escape-string-regexp')
- , utils = require('./utils');
-
-/**
- * Expose `Mocha`.
- */
-
-exports = module.exports = Mocha;
-
-/**
- * To require local UIs and reporters when running in node.
- */
-
-if (typeof process !== 'undefined' && typeof process.cwd === 'function') {
- var join = path.join
- , cwd = process.cwd();
- module.paths.push(cwd, join(cwd, 'node_modules'));
-}
-
-/**
- * Expose internals.
- */
-
-exports.utils = utils;
-exports.interfaces = require('./interfaces');
-exports.reporters = require('./reporters');
-exports.Runnable = require('./runnable');
-exports.Context = require('./context');
-exports.Runner = require('./runner');
-exports.Suite = require('./suite');
-exports.Hook = require('./hook');
-exports.Test = require('./test');
-
-/**
- * Return image `name` path.
- *
- * @param {String} name
- * @return {String}
- * @api private
- */
-
-function image(name) {
- return __dirname + '/../images/' + name + '.png';
-}
-
-/**
- * Setup mocha with `options`.
- *
- * Options:
- *
- * - `ui` name "bdd", "tdd", "exports" etc
- * - `reporter` reporter instance, defaults to `mocha.reporters.spec`
- * - `globals` array of accepted globals
- * - `timeout` timeout in milliseconds
- * - `bail` bail on the first test failure
- * - `slow` milliseconds to wait before considering a test slow
- * - `ignoreLeaks` ignore global leaks
- * - `fullTrace` display the full stack-trace on failing
- * - `grep` string or regexp to filter tests with
- *
- * @param {Object} options
- * @api public
- */
-
-function Mocha(options) {
- options = options || {};
- this.files = [];
- this.options = options;
- if (options.grep) this.grep(new RegExp(options.grep));
- if (options.fgrep) this.grep(options.fgrep);
- this.suite = new exports.Suite('', new exports.Context);
- this.ui(options.ui);
- this.bail(options.bail);
- this.reporter(options.reporter, options.reporterOptions);
- if (null != options.timeout) this.timeout(options.timeout);
- this.useColors(options.useColors);
- if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts);
- if (options.slow) this.slow(options.slow);
-
- this.suite.on('pre-require', function (context) {
- exports.afterEach = context.afterEach || context.teardown;
- exports.after = context.after || context.suiteTeardown;
- exports.beforeEach = context.beforeEach || context.setup;
- exports.before = context.before || context.suiteSetup;
- exports.describe = context.describe || context.suite;
- exports.it = context.it || context.test;
- exports.setup = context.setup || context.beforeEach;
- exports.suiteSetup = context.suiteSetup || context.before;
- exports.suiteTeardown = context.suiteTeardown || context.after;
- exports.suite = context.suite || context.describe;
- exports.teardown = context.teardown || context.afterEach;
- exports.test = context.test || context.it;
- exports.run = context.run;
- });
-}
-
-/**
- * Enable or disable bailing on the first failure.
- *
- * @param {Boolean} [bail]
- * @api public
- */
-
-Mocha.prototype.bail = function(bail){
- if (0 == arguments.length) bail = true;
- this.suite.bail(bail);
- return this;
-};
-
-/**
- * Add test `file`.
- *
- * @param {String} file
- * @api public
- */
-
-Mocha.prototype.addFile = function(file){
- this.files.push(file);
- return this;
-};
-
-/**
- * Set reporter to `reporter`, defaults to "spec".
- *
- * @param {String|Function} reporter name or constructor
- * @param {Object} reporterOptions optional options
- * @api public
- */
-Mocha.prototype.reporter = function(reporter, reporterOptions){
- if ('function' == typeof reporter) {
- this._reporter = reporter;
- } else {
- reporter = reporter || 'spec';
- var _reporter;
- try { _reporter = require('./reporters/' + reporter); } catch (err) {}
- if (!_reporter) try { _reporter = require(reporter); } catch (err) {
- err.message.indexOf('Cannot find module') !== -1
- ? console.warn('"' + reporter + '" reporter not found')
- : console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack);
- }
- if (!_reporter && reporter === 'teamcity')
- console.warn('The Teamcity reporter was moved to a package named ' +
- 'mocha-teamcity-reporter ' +
- '(https://npmjs.org/package/mocha-teamcity-reporter).');
- if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
- this._reporter = _reporter;
- }
- this.options.reporterOptions = reporterOptions;
- return this;
-};
-
-/**
- * Set test UI `name`, defaults to "bdd".
- *
- * @param {String} bdd
- * @api public
- */
-
-Mocha.prototype.ui = function(name){
- name = name || 'bdd';
- this._ui = exports.interfaces[name];
- if (!this._ui) try { this._ui = require(name); } catch (err) {}
- if (!this._ui) throw new Error('invalid interface "' + name + '"');
- this._ui = this._ui(this.suite);
- return this;
-};
-
-/**
- * Load registered files.
- *
- * @api private
- */
-
-Mocha.prototype.loadFiles = function(fn){
- var self = this;
- var suite = this.suite;
- var pending = this.files.length;
- this.files.forEach(function(file){
- file = path.resolve(file);
- suite.emit('pre-require', global, file, self);
- suite.emit('require', require(file), file, self);
- suite.emit('post-require', global, file, self);
- --pending || (fn && fn());
- });
-};
-
-/**
- * Enable growl support.
- *
- * @api private
- */
-
-Mocha.prototype._growl = function(runner, reporter) {
- var notify = require('growl');
-
- runner.on('end', function(){
- var stats = reporter.stats;
- if (stats.failures) {
- var msg = stats.failures + ' of ' + runner.total + ' tests failed';
- notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
- } else {
- notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
- name: 'mocha'
- , title: 'Passed'
- , image: image('ok')
- });
- }
- });
-};
-
-/**
- * Add regexp to grep, if `re` is a string it is escaped.
- *
- * @param {RegExp|String} re
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.grep = function(re){
- this.options.grep = 'string' == typeof re
- ? new RegExp(escapeRe(re))
- : re;
- return this;
-};
-
-/**
- * Invert `.grep()` matches.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.invert = function(){
- this.options.invert = true;
- return this;
-};
-
-/**
- * Ignore global leaks.
- *
- * @param {Boolean} ignore
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.ignoreLeaks = function(ignore){
- this.options.ignoreLeaks = !!ignore;
- return this;
-};
-
-/**
- * Enable global leak checking.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.checkLeaks = function(){
- this.options.ignoreLeaks = false;
- return this;
-};
-
-/**
- * Display long stack-trace on failing
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.fullTrace = function() {
- this.options.fullStackTrace = true;
- return this;
-};
-
-/**
- * Enable growl support.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.growl = function(){
- this.options.growl = true;
- return this;
-};
-
-/**
- * Ignore `globals` array or string.
- *
- * @param {Array|String} globals
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.globals = function(globals){
- this.options.globals = (this.options.globals || []).concat(globals);
- return this;
-};
-
-/**
- * Emit color output.
- *
- * @param {Boolean} colors
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.useColors = function(colors){
- if (colors !== undefined) {
- this.options.useColors = colors;
- }
- return this;
-};
-
-/**
- * Use inline diffs rather than +/-.
- *
- * @param {Boolean} inlineDiffs
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.useInlineDiffs = function(inlineDiffs) {
- this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined
- ? inlineDiffs
- : false;
- return this;
-};
-
-/**
- * Set the timeout in milliseconds.
- *
- * @param {Number} timeout
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.timeout = function(timeout){
- this.suite.timeout(timeout);
- return this;
-};
-
-/**
- * Set slowness threshold in milliseconds.
- *
- * @param {Number} slow
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.slow = function(slow){
- this.suite.slow(slow);
- return this;
-};
-
-/**
- * Enable timeouts.
- *
- * @param {Boolean} enabled
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.enableTimeouts = function(enabled) {
- this.suite.enableTimeouts(arguments.length && enabled !== undefined
- ? enabled
- : true);
- return this
-};
-
-/**
- * Makes all tests async (accepting a callback)
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.asyncOnly = function(){
- this.options.asyncOnly = true;
- return this;
-};
-
-/**
- * Disable syntax highlighting (in browser).
- * @returns {Mocha}
- * @api public
- */
-Mocha.prototype.noHighlighting = function() {
- this.options.noHighlighting = true;
- return this;
-};
-
-/**
- * Delay root suite execution.
- * @returns {Mocha}
- * @api public
- */
-Mocha.prototype.delay = function delay() {
- this.options.delay = true;
- return this;
-};
-
-/**
- * Run tests and invoke `fn()` when complete.
- *
- * @param {Function} fn
- * @return {Runner}
- * @api public
- */
-Mocha.prototype.run = function(fn){
- if (this.files.length) this.loadFiles();
- var suite = this.suite;
- var options = this.options;
- options.files = this.files;
- var runner = new exports.Runner(suite, options.delay);
- var reporter = new this._reporter(runner, options);
- runner.ignoreLeaks = false !== options.ignoreLeaks;
- runner.fullStackTrace = options.fullStackTrace;
- runner.asyncOnly = options.asyncOnly;
- if (options.grep) runner.grep(options.grep, options.invert);
- if (options.globals) runner.globals(options.globals);
- if (options.growl) this._growl(runner, reporter);
- if (options.useColors !== undefined) {
- exports.reporters.Base.useColors = options.useColors;
- }
- exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
-
- function done(failures) {
- if (reporter.done) {
- reporter.done(failures, fn);
- } else fn && fn(failures);
- }
-
- return runner.run(done);
-};
-
-}); // module: mocha.js
-
-require.register("ms.js", function(module, exports, require){
-/**
- * Helpers.
- */
-
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-var y = d * 365.25;
-
-/**
- * Parse or format the given `val`.
- *
- * Options:
- *
- * - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} options
- * @return {String|Number}
- * @api public
- */
-
-module.exports = function(val, options){
- options = options || {};
- if ('string' == typeof val) return parse(val);
- return options['long'] ? longFormat(val) : shortFormat(val);
-};
-
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
-
-function parse(str) {
- var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
- if (!match) return undefined;
- var n = parseFloat(match[1]);
- var type = (match[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'y':
- return n * y;
- case 'days':
- case 'day':
- case 'd':
- return n * d;
- case 'hours':
- case 'hour':
- case 'h':
- return n * h;
- case 'minutes':
- case 'minute':
- case 'm':
- return n * m;
- case 'seconds':
- case 'second':
- case 's':
- return n * s;
- case 'ms':
- return n;
- }
-}
-
-/**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function shortFormat(ms) {
- if (ms >= d) return Math.round(ms / d) + 'd';
- if (ms >= h) return Math.round(ms / h) + 'h';
- if (ms >= m) return Math.round(ms / m) + 'm';
- if (ms >= s) return Math.round(ms / s) + 's';
- return ms + 'ms';
-}
-
-/**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function longFormat(ms) {
- return plural(ms, d, 'day')
- || plural(ms, h, 'hour')
- || plural(ms, m, 'minute')
- || plural(ms, s, 'second')
- || ms + ' ms';
-}
-
-/**
- * Pluralization helper.
- */
-
-function plural(ms, n, name) {
- if (ms < n) return undefined;
- if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
- return Math.ceil(ms / n) + ' ' + name + 's';
-}
-
-}); // module: ms.js
-
-require.register("pending.js", function(module, exports, require){
-
-/**
- * Expose `Pending`.
- */
-
-module.exports = Pending;
-
-/**
- * Initialize a new `Pending` error with the given message.
- *
- * @param {String} message
- */
-
-function Pending(message) {
- this.message = message;
-}
-
-}); // module: pending.js
-
-require.register("reporters/base.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var tty = require('browser/tty')
- , diff = require('browser/diff')
- , ms = require('../ms')
- , utils = require('../utils')
- , supportsColor = process.env ? require('supports-color') : null;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Check if both stdio streams are associated with a tty.
- */
-
-var isatty = tty.isatty(1) && tty.isatty(2);
-
-/**
- * Expose `Base`.
- */
-
-exports = module.exports = Base;
-
-/**
- * Enable coloring by default, except in the browser interface.
- */
-
-exports.useColors = process.env
- ? (supportsColor || (process.env.MOCHA_COLORS !== undefined))
- : false;
-
-/**
- * Inline diffs instead of +/-
- */
-
-exports.inlineDiffs = false;
-
-/**
- * Default color map.
- */
-
-exports.colors = {
- 'pass': 90
- , 'fail': 31
- , 'bright pass': 92
- , 'bright fail': 91
- , 'bright yellow': 93
- , 'pending': 36
- , 'suite': 0
- , 'error title': 0
- , 'error message': 31
- , 'error stack': 90
- , 'checkmark': 32
- , 'fast': 90
- , 'medium': 33
- , 'slow': 31
- , 'green': 32
- , 'light': 90
- , 'diff gutter': 90
- , 'diff added': 42
- , 'diff removed': 41
-};
-
-/**
- * Default symbol map.
- */
-
-exports.symbols = {
- ok: '✓',
- err: '✖',
- dot: '․'
-};
-
-// With node.js on Windows: use symbols available in terminal default fonts
-if ('win32' == process.platform) {
- exports.symbols.ok = '\u221A';
- exports.symbols.err = '\u00D7';
- exports.symbols.dot = '.';
-}
-
-/**
- * Color `str` with the given `type`,
- * allowing colors to be disabled,
- * as well as user-defined color
- * schemes.
- *
- * @param {String} type
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-var color = exports.color = function(type, str) {
- if (!exports.useColors) return String(str);
- return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
-};
-
-/**
- * Expose term window size, with some
- * defaults for when stderr is not a tty.
- */
-
-exports.window = {
- width: 75
-};
-if (isatty) {
- exports.window.width = process.stdout.getWindowSize
- ? process.stdout.getWindowSize(1)[0]
- : tty.getWindowSize()[1];
-}
-
-/**
- * Expose some basic cursor interactions
- * that are common among reporters.
- */
-
-exports.cursor = {
- hide: function(){
- isatty && process.stdout.write('\u001b[?25l');
- },
-
- show: function(){
- isatty && process.stdout.write('\u001b[?25h');
- },
-
- deleteLine: function(){
- isatty && process.stdout.write('\u001b[2K');
- },
-
- beginningOfLine: function(){
- isatty && process.stdout.write('\u001b[0G');
- },
-
- CR: function(){
- if (isatty) {
- exports.cursor.deleteLine();
- exports.cursor.beginningOfLine();
- } else {
- process.stdout.write('\r');
- }
- }
-};
-
-/**
- * Outut the given `failures` as a list.
- *
- * @param {Array} failures
- * @api public
- */
-
-exports.list = function(failures){
- console.log();
- failures.forEach(function(test, i){
- // format
- var fmt = color('error title', ' %s) %s:\n')
- + color('error message', ' %s')
- + color('error stack', '\n%s\n');
-
- // msg
- var err = test.err
- , message = err.message || ''
- , stack = err.stack || message
- , index = stack.indexOf(message)
- , actual = err.actual
- , expected = err.expected
- , escape = true;
- if (index === -1) {
- msg = message;
- } else {
- index += message.length;
- msg = stack.slice(0, index);
- // remove msg from stack
- stack = stack.slice(index + 1);
- }
-
- // uncaught
- if (err.uncaught) {
- msg = 'Uncaught ' + msg;
- }
- // explicitly show diff
- if (err.showDiff !== false && sameType(actual, expected)
- && expected !== undefined) {
-
- if ('string' !== typeof actual) {
- escape = false;
- err.actual = actual = utils.stringify(actual);
- err.expected = expected = utils.stringify(expected);
- }
-
- fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
- var match = message.match(/^([^:]+): expected/);
- msg = '\n ' + color('error message', match ? match[1] : msg);
-
- if (exports.inlineDiffs) {
- msg += inlineDiff(err, escape);
- } else {
- msg += unifiedDiff(err, escape);
- }
- }
-
- // indent stack trace
- stack = stack.replace(/^/gm, ' ');
-
- console.log(fmt, (i + 1), test.fullTitle(), msg, stack);
- });
-};
-
-/**
- * Initialize a new `Base` reporter.
- *
- * All other reporters generally
- * inherit from this reporter, providing
- * stats such as test duration, number
- * of tests passed / failed etc.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Base(runner) {
- var self = this
- , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
- , failures = this.failures = [];
-
- if (!runner) return;
- this.runner = runner;
-
- runner.stats = stats;
-
- runner.on('start', function(){
- stats.start = new Date;
- });
-
- runner.on('suite', function(suite){
- stats.suites = stats.suites || 0;
- suite.root || stats.suites++;
- });
-
- runner.on('test end', function(test){
- stats.tests = stats.tests || 0;
- stats.tests++;
- });
-
- runner.on('pass', function(test){
- stats.passes = stats.passes || 0;
-
- var medium = test.slow() / 2;
- if (test.duration > test.slow()) {
- test.speed = 'slow';
- } else if (test.duration > medium) {
- test.speed = 'medium';
- } else {
- test.speed = 'fast';
- }
-
- stats.passes++;
- });
-
- runner.on('fail', function(test, err){
- stats.failures = stats.failures || 0;
- stats.failures++;
- test.err = err;
- failures.push(test);
- });
-
- runner.on('end', function(){
- stats.end = new Date;
- stats.duration = new Date - stats.start;
- });
-
- runner.on('pending', function(){
- stats.pending++;
- });
-}
-
-/**
- * Output common epilogue used by many of
- * the bundled reporters.
- *
- * @api public
- */
-
-Base.prototype.epilogue = function(){
- var stats = this.stats;
- var tests;
- var fmt;
-
- console.log();
-
- // passes
- fmt = color('bright pass', ' ')
- + color('green', ' %d passing')
- + color('light', ' (%s)');
-
- console.log(fmt,
- stats.passes || 0,
- ms(stats.duration));
-
- // pending
- if (stats.pending) {
- fmt = color('pending', ' ')
- + color('pending', ' %d pending');
-
- console.log(fmt, stats.pending);
- }
-
- // failures
- if (stats.failures) {
- fmt = color('fail', ' %d failing');
-
- console.log(fmt, stats.failures);
-
- Base.list(this.failures);
- console.log();
- }
-
- console.log();
-};
-
-/**
- * Pad the given `str` to `len`.
- *
- * @param {String} str
- * @param {String} len
- * @return {String}
- * @api private
- */
-
-function pad(str, len) {
- str = String(str);
- return Array(len - str.length + 1).join(' ') + str;
-}
-
-
-/**
- * Returns an inline diff between 2 strings with coloured ANSI output
- *
- * @param {Error} Error with actual/expected
- * @return {String} Diff
- * @api private
- */
-
-function inlineDiff(err, escape) {
- var msg = errorDiff(err, 'WordsWithSpace', escape);
-
- // linenos
- var lines = msg.split('\n');
- if (lines.length > 4) {
- var width = String(lines.length).length;
- msg = lines.map(function(str, i){
- return pad(++i, width) + ' |' + ' ' + str;
- }).join('\n');
- }
-
- // legend
- msg = '\n'
- + color('diff removed', 'actual')
- + ' '
- + color('diff added', 'expected')
- + '\n\n'
- + msg
- + '\n';
-
- // indent
- msg = msg.replace(/^/gm, ' ');
- return msg;
-}
-
-/**
- * Returns a unified diff between 2 strings
- *
- * @param {Error} Error with actual/expected
- * @return {String} Diff
- * @api private
- */
-
-function unifiedDiff(err, escape) {
- var indent = ' ';
- function cleanUp(line) {
- if (escape) {
- line = escapeInvisibles(line);
- }
- if (line[0] === '+') return indent + colorLines('diff added', line);
- if (line[0] === '-') return indent + colorLines('diff removed', line);
- if (line.match(/\@\@/)) return null;
- if (line.match(/\\ No newline/)) return null;
- else return indent + line;
- }
- function notBlank(line) {
- return line != null;
- }
- var msg = diff.createPatch('string', err.actual, err.expected);
- var lines = msg.split('\n').splice(4);
- return '\n '
- + colorLines('diff added', '+ expected') + ' '
- + colorLines('diff removed', '- actual')
- + '\n\n'
- + lines.map(cleanUp).filter(notBlank).join('\n');
-}
-
-/**
- * Return a character diff for `err`.
- *
- * @param {Error} err
- * @return {String}
- * @api private
- */
-
-function errorDiff(err, type, escape) {
- var actual = escape ? escapeInvisibles(err.actual) : err.actual;
- var expected = escape ? escapeInvisibles(err.expected) : err.expected;
- return diff['diff' + type](actual, expected).map(function(str){
- if (str.added) return colorLines('diff added', str.value);
- if (str.removed) return colorLines('diff removed', str.value);
- return str.value;
- }).join('');
-}
-
-/**
- * Returns a string with all invisible characters in plain text
- *
- * @param {String} line
- * @return {String}
- * @api private
- */
-function escapeInvisibles(line) {
- return line.replace(/\t/g, '<tab>')
- .replace(/\r/g, '<CR>')
- .replace(/\n/g, '<LF>\n');
-}
-
-/**
- * Color lines for `str`, using the color `name`.
- *
- * @param {String} name
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-function colorLines(name, str) {
- return str.split('\n').map(function(str){
- return color(name, str);
- }).join('\n');
-}
-
-/**
- * Check that a / b have the same type.
- *
- * @param {Object} a
- * @param {Object} b
- * @return {Boolean}
- * @api private
- */
-
-function sameType(a, b) {
- a = Object.prototype.toString.call(a);
- b = Object.prototype.toString.call(b);
- return a == b;
-}
-
-}); // module: reporters/base.js
-
-require.register("reporters/doc.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils');
-
-/**
- * Expose `Doc`.
- */
-
-exports = module.exports = Doc;
-
-/**
- * Initialize a new `Doc` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Doc(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , total = runner.total
- , indents = 2;
-
- function indent() {
- return Array(indents).join(' ');
- }
-
- runner.on('suite', function(suite){
- if (suite.root) return;
- ++indents;
- console.log('%s<section class="suite">', indent());
- ++indents;
- console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
- console.log('%s<dl>', indent());
- });
-
- runner.on('suite end', function(suite){
- if (suite.root) return;
- console.log('%s</dl>', indent());
- --indents;
- console.log('%s</section>', indent());
- --indents;
- });
-
- runner.on('pass', function(test){
- console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
- var code = utils.escape(utils.clean(test.fn.toString()));
- console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
- });
-
- runner.on('fail', function(test, err){
- console.log('%s <dt class="error">%s</dt>', indent(), utils.escape(test.title));
- var code = utils.escape(utils.clean(test.fn.toString()));
- console.log('%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code);
- console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err));
- });
-}
-
-}); // module: reporters/doc.js
-
-require.register("reporters/dot.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , color = Base.color;
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = Dot;
-
-/**
- * Initialize a new `Dot` matrix test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Dot(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , width = Base.window.width * .75 | 0
- , n = -1;
-
- runner.on('start', function(){
- process.stdout.write('\n');
- });
-
- runner.on('pending', function(test){
- if (++n % width == 0) process.stdout.write('\n ');
- process.stdout.write(color('pending', Base.symbols.dot));
- });
-
- runner.on('pass', function(test){
- if (++n % width == 0) process.stdout.write('\n ');
- if ('slow' == test.speed) {
- process.stdout.write(color('bright yellow', Base.symbols.dot));
- } else {
- process.stdout.write(color(test.speed, Base.symbols.dot));
- }
- });
-
- runner.on('fail', function(test, err){
- if (++n % width == 0) process.stdout.write('\n ');
- process.stdout.write(color('fail', Base.symbols.dot));
- });
-
- runner.on('end', function(){
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-Dot.prototype = new F;
-Dot.prototype.constructor = Dot;
-
-
-}); // module: reporters/dot.js
-
-require.register("reporters/html-cov.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var JSONCov = require('./json-cov')
- , fs = require('browser/fs');
-
-/**
- * Expose `HTMLCov`.
- */
-
-exports = module.exports = HTMLCov;
-
-/**
- * Initialize a new `JsCoverage` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function HTMLCov(runner) {
- var jade = require('jade')
- , file = __dirname + '/templates/coverage.jade'
- , str = fs.readFileSync(file, 'utf8')
- , fn = jade.compile(str, { filename: file })
- , self = this;
-
- JSONCov.call(this, runner, false);
-
- runner.on('end', function(){
- process.stdout.write(fn({
- cov: self.cov
- , coverageClass: coverageClass
- }));
- });
-}
-
-/**
- * Return coverage class for `n`.
- *
- * @return {String}
- * @api private
- */
-
-function coverageClass(n) {
- if (n >= 75) return 'high';
- if (n >= 50) return 'medium';
- if (n >= 25) return 'low';
- return 'terrible';
-}
-
-}); // module: reporters/html-cov.js
-
-require.register("reporters/html.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils')
- , Progress = require('../browser/progress')
- , escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Expose `HTML`.
- */
-
-exports = module.exports = HTML;
-
-/**
- * Stats template.
- */
-
-var statsTemplate = '<ul id="mocha-stats">'
- + '<li class="progress"><canvas width="40" height="40"></canvas></li>'
- + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
- + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
- + '<li class="duration">duration: <em>0</em>s</li>'
- + '</ul>';
-
-/**
- * Initialize a new `HTML` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function HTML(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , total = runner.total
- , stat = fragment(statsTemplate)
- , items = stat.getElementsByTagName('li')
- , passes = items[1].getElementsByTagName('em')[0]
- , passesLink = items[1].getElementsByTagName('a')[0]
- , failures = items[2].getElementsByTagName('em')[0]
- , failuresLink = items[2].getElementsByTagName('a')[0]
- , duration = items[3].getElementsByTagName('em')[0]
- , canvas = stat.getElementsByTagName('canvas')[0]
- , report = fragment('<ul id="mocha-report"></ul>')
- , stack = [report]
- , progress
- , ctx
- , root = document.getElementById('mocha');
-
- if (canvas.getContext) {
- var ratio = window.devicePixelRatio || 1;
- canvas.style.width = canvas.width;
- canvas.style.height = canvas.height;
- canvas.width *= ratio;
- canvas.height *= ratio;
- ctx = canvas.getContext('2d');
- ctx.scale(ratio, ratio);
- progress = new Progress;
- }
-
- if (!root) return error('#mocha div missing, add it to your document');
-
- // pass toggle
- on(passesLink, 'click', function(){
- unhide();
- var name = /pass/.test(report.className) ? '' : ' pass';
- report.className = report.className.replace(/fail|pass/g, '') + name;
- if (report.className.trim()) hideSuitesWithout('test pass');
- });
-
- // failure toggle
- on(failuresLink, 'click', function(){
- unhide();
- var name = /fail/.test(report.className) ? '' : ' fail';
- report.className = report.className.replace(/fail|pass/g, '') + name;
- if (report.className.trim()) hideSuitesWithout('test fail');
- });
-
- root.appendChild(stat);
- root.appendChild(report);
-
- if (progress) progress.size(40);
-
- runner.on('suite', function(suite){
- if (suite.root) return;
-
- // suite
- var url = self.suiteURL(suite);
- var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
-
- // container
- stack[0].appendChild(el);
- stack.unshift(document.createElement('ul'));
- el.appendChild(stack[0]);
- });
-
- runner.on('suite end', function(suite){
- if (suite.root) return;
- stack.shift();
- });
-
- runner.on('fail', function(test, err){
- if ('hook' == test.type) runner.emit('test end', test);
- });
-
- runner.on('test end', function(test){
- // TODO: add to stats
- var percent = stats.tests / this.total * 100 | 0;
- if (progress) progress.update(percent).draw(ctx);
-
- // update stats
- var ms = new Date - stats.start;
- text(passes, stats.passes);
- text(failures, stats.failures);
- text(duration, (ms / 1000).toFixed(2));
-
- // test
- if ('passed' == test.state) {
- var url = self.testURL(test);
- var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%s" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url);
- } else if (test.pending) {
- el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
- } else {
- el = fragment('<li class="test fail"><h2>%e <a href="%e" class="replay">‣</a></h2></li>', test.title, self.testURL(test));
- var str = test.err.stack || test.err.toString();
-
- // FF / Opera do not add the message
- if (!~str.indexOf(test.err.message)) {
- str = test.err.message + '\n' + str;
- }
-
- // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
- // check for the result of the stringifying.
- if ('[object Error]' == str) str = test.err.message;
-
- // Safari doesn't give you a stack. Let's at least provide a source line.
- if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
- str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
- }
-
- el.appendChild(fragment('<pre class="error">%e</pre>', str));
- }
-
- // toggle code
- // TODO: defer
- if (!test.pending) {
- var h2 = el.getElementsByTagName('h2')[0];
-
- on(h2, 'click', function(){
- pre.style.display = 'none' == pre.style.display
- ? 'block'
- : 'none';
- });
-
- var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
- el.appendChild(pre);
- pre.style.display = 'none';
- }
-
- // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
- if (stack[0]) stack[0].appendChild(el);
- });
-}
-
-/**
- * Makes a URL, preserving querystring ("search") parameters.
- * @param {string} s
- * @returns {string} your new URL
- */
-var makeUrl = function makeUrl(s) {
- var search = window.location.search;
-
- // Remove previous grep query parameter if present
- if (search) {
- search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?');
- }
-
- return window.location.pathname + (search ? search + '&' : '?' ) + 'grep=' + encodeURIComponent(s);
-};
-
-/**
- * Provide suite URL
- *
- * @param {Object} [suite]
- */
-HTML.prototype.suiteURL = function(suite){
- return makeUrl(suite.fullTitle());
-};
-
-/**
- * Provide test URL
- *
- * @param {Object} [test]
- */
-
-HTML.prototype.testURL = function(test){
- return makeUrl(test.fullTitle());
-};
-
-/**
- * Display error `msg`.
- */
-
-function error(msg) {
- document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
-}
-
-/**
- * Return a DOM fragment from `html`.
- */
-
-function fragment(html) {
- var args = arguments
- , div = document.createElement('div')
- , i = 1;
-
- div.innerHTML = html.replace(/%([se])/g, function(_, type){
- switch (type) {
- case 's': return String(args[i++]);
- case 'e': return escape(args[i++]);
- }
- });
-
- return div.firstChild;
-}
-
-/**
- * Check for suites that do not have elements
- * with `classname`, and hide them.
- */
-
-function hideSuitesWithout(classname) {
- var suites = document.getElementsByClassName('suite');
- for (var i = 0; i < suites.length; i++) {
- var els = suites[i].getElementsByClassName(classname);
- if (0 == els.length) suites[i].className += ' hidden';
- }
-}
-
-/**
- * Unhide .hidden suites.
- */
-
-function unhide() {
- var els = document.getElementsByClassName('suite hidden');
- for (var i = 0; i < els.length; ++i) {
- els[i].className = els[i].className.replace('suite hidden', 'suite');
- }
-}
-
-/**
- * Set `el` text to `str`.
- */
-
-function text(el, str) {
- if (el.textContent) {
- el.textContent = str;
- } else {
- el.innerText = str;
- }
-}
-
-/**
- * Listen on `event` with callback `fn`.
- */
-
-function on(el, event, fn) {
- if (el.addEventListener) {
- el.addEventListener(event, fn, false);
- } else {
- el.attachEvent('on' + event, fn);
- }
-}
-
-}); // module: reporters/html.js
-
-require.register("reporters/index.js", function(module, exports, require){
-exports.Base = require('./base');
-exports.Dot = require('./dot');
-exports.Doc = require('./doc');
-exports.TAP = require('./tap');
-exports.JSON = require('./json');
-exports.HTML = require('./html');
-exports.List = require('./list');
-exports.Min = require('./min');
-exports.Spec = require('./spec');
-exports.Nyan = require('./nyan');
-exports.XUnit = require('./xunit');
-exports.Markdown = require('./markdown');
-exports.Progress = require('./progress');
-exports.Landing = require('./landing');
-exports.JSONCov = require('./json-cov');
-exports.HTMLCov = require('./html-cov');
-exports.JSONStream = require('./json-stream');
-
-}); // module: reporters/index.js
-
-require.register("reporters/json-cov.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `JSONCov`.
- */
-
-exports = module.exports = JSONCov;
-
-/**
- * Initialize a new `JsCoverage` reporter.
- *
- * @param {Runner} runner
- * @param {Boolean} output
- * @api public
- */
-
-function JSONCov(runner, output) {
- var self = this;
- output = 1 == arguments.length ? true : output;
-
- Base.call(this, runner);
-
- var tests = []
- , failures = []
- , passes = [];
-
- runner.on('test end', function(test){
- tests.push(test);
- });
-
- runner.on('pass', function(test){
- passes.push(test);
- });
-
- runner.on('fail', function(test){
- failures.push(test);
- });
-
- runner.on('end', function(){
- var cov = global._$jscoverage || {};
- var result = self.cov = map(cov);
- result.stats = self.stats;
- result.tests = tests.map(clean);
- result.failures = failures.map(clean);
- result.passes = passes.map(clean);
- if (!output) return;
- process.stdout.write(JSON.stringify(result, null, 2 ));
- });
-}
-
-/**
- * Map jscoverage data to a JSON structure
- * suitable for reporting.
- *
- * @param {Object} cov
- * @return {Object}
- * @api private
- */
-
-function map(cov) {
- var ret = {
- instrumentation: 'node-jscoverage'
- , sloc: 0
- , hits: 0
- , misses: 0
- , coverage: 0
- , files: []
- };
-
- for (var filename in cov) {
- var data = coverage(filename, cov[filename]);
- ret.files.push(data);
- ret.hits += data.hits;
- ret.misses += data.misses;
- ret.sloc += data.sloc;
- }
-
- ret.files.sort(function(a, b) {
- return a.filename.localeCompare(b.filename);
- });
-
- if (ret.sloc > 0) {
- ret.coverage = (ret.hits / ret.sloc) * 100;
- }
-
- return ret;
-}
-
-/**
- * Map jscoverage data for a single source file
- * to a JSON structure suitable for reporting.
- *
- * @param {String} filename name of the source file
- * @param {Object} data jscoverage coverage data
- * @return {Object}
- * @api private
- */
-
-function coverage(filename, data) {
- var ret = {
- filename: filename,
- coverage: 0,
- hits: 0,
- misses: 0,
- sloc: 0,
- source: {}
- };
-
- data.source.forEach(function(line, num){
- num++;
-
- if (data[num] === 0) {
- ret.misses++;
- ret.sloc++;
- } else if (data[num] !== undefined) {
- ret.hits++;
- ret.sloc++;
- }
-
- ret.source[num] = {
- source: line
- , coverage: data[num] === undefined
- ? ''
- : data[num]
- };
- });
-
- ret.coverage = ret.hits / ret.sloc * 100;
-
- return ret;
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
- return {
- title: test.title
- , fullTitle: test.fullTitle()
- , duration: test.duration
- }
-}
-
-}); // module: reporters/json-cov.js
-
-require.register("reporters/json-stream.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , color = Base.color;
-
-/**
- * Expose `List`.
- */
-
-exports = module.exports = List;
-
-/**
- * Initialize a new `List` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function List(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , total = runner.total;
-
- runner.on('start', function(){
- console.log(JSON.stringify(['start', { total: total }]));
- });
-
- runner.on('pass', function(test){
- console.log(JSON.stringify(['pass', clean(test)]));
- });
-
- runner.on('fail', function(test, err){
- test = clean(test);
- test.err = err.message;
- console.log(JSON.stringify(['fail', test]));
- });
-
- runner.on('end', function(){
- process.stdout.write(JSON.stringify(['end', self.stats]));
- });
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
- return {
- title: test.title
- , fullTitle: test.fullTitle()
- , duration: test.duration
- }
-}
-
-}); // module: reporters/json-stream.js
-
-require.register("reporters/json.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `JSON`.
- */
-
-exports = module.exports = JSONReporter;
-
-/**
- * Initialize a new `JSON` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function JSONReporter(runner) {
- var self = this;
- Base.call(this, runner);
-
- var tests = []
- , pending = []
- , failures = []
- , passes = [];
-
- runner.on('test end', function(test){
- tests.push(test);
- });
-
- runner.on('pass', function(test){
- passes.push(test);
- });
-
- runner.on('fail', function(test){
- failures.push(test);
- });
-
- runner.on('pending', function(test){
- pending.push(test);
- });
-
- runner.on('end', function(){
- var obj = {
- stats: self.stats,
- tests: tests.map(clean),
- pending: pending.map(clean),
- failures: failures.map(clean),
- passes: passes.map(clean)
- };
-
- runner.testResults = obj;
-
- process.stdout.write(JSON.stringify(obj, null, 2));
- });
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
- return {
- title: test.title,
- fullTitle: test.fullTitle(),
- duration: test.duration,
- err: errorJSON(test.err || {})
- }
-}
-
-/**
- * Transform `error` into a JSON object.
- * @param {Error} err
- * @return {Object}
- */
-
-function errorJSON(err) {
- var res = {};
- Object.getOwnPropertyNames(err).forEach(function(key) {
- res[key] = err[key];
- }, err);
- return res;
-}
-
-}); // module: reporters/json.js
-
-require.register("reporters/landing.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `Landing`.
- */
-
-exports = module.exports = Landing;
-
-/**
- * Airplane color.
- */
-
-Base.colors.plane = 0;
-
-/**
- * Airplane crash color.
- */
-
-Base.colors['plane crash'] = 31;
-
-/**
- * Runway color.
- */
-
-Base.colors.runway = 90;
-
-/**
- * Initialize a new `Landing` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Landing(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , width = Base.window.width * .75 | 0
- , total = runner.total
- , stream = process.stdout
- , plane = color('plane', '✈')
- , crashed = -1
- , n = 0;
-
- function runway() {
- var buf = Array(width).join('-');
- return ' ' + color('runway', buf);
- }
-
- runner.on('start', function(){
- stream.write('\n\n\n ');
- cursor.hide();
- });
-
- runner.on('test end', function(test){
- // check if the plane crashed
- var col = -1 == crashed
- ? width * ++n / total | 0
- : crashed;
-
- // show the crash
- if ('failed' == test.state) {
- plane = color('plane crash', '✈');
- crashed = col;
- }
-
- // render landing strip
- stream.write('\u001b['+(width+1)+'D\u001b[2A');
- stream.write(runway());
- stream.write('\n ');
- stream.write(color('runway', Array(col).join('⋅')));
- stream.write(plane)
- stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
- stream.write(runway());
- stream.write('\u001b[0m');
- });
-
- runner.on('end', function(){
- cursor.show();
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-Landing.prototype = new F;
-Landing.prototype.constructor = Landing;
-
-
-}); // module: reporters/landing.js
-
-require.register("reporters/list.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `List`.
- */
-
-exports = module.exports = List;
-
-/**
- * Initialize a new `List` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function List(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , n = 0;
-
- runner.on('start', function(){
- console.log();
- });
-
- runner.on('test', function(test){
- process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
- });
-
- runner.on('pending', function(test){
- var fmt = color('checkmark', ' -')
- + color('pending', ' %s');
- console.log(fmt, test.fullTitle());
- });
-
- runner.on('pass', function(test){
- var fmt = color('checkmark', ' '+Base.symbols.dot)
- + color('pass', ' %s: ')
- + color(test.speed, '%dms');
- cursor.CR();
- console.log(fmt, test.fullTitle(), test.duration);
- });
-
- runner.on('fail', function(test, err){
- cursor.CR();
- console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
- });
-
- runner.on('end', self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-List.prototype = new F;
-List.prototype.constructor = List;
-
-
-}); // module: reporters/list.js
-
-require.register("reporters/markdown.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils');
-
-/**
- * Constants
- */
-
-var SUITE_PREFIX = '$';
-
-/**
- * Expose `Markdown`.
- */
-
-exports = module.exports = Markdown;
-
-/**
- * Initialize a new `Markdown` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Markdown(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , level = 0
- , buf = '';
-
- function title(str) {
- return Array(level).join('#') + ' ' + str;
- }
-
- function indent() {
- return Array(level).join(' ');
- }
-
- function mapTOC(suite, obj) {
- var ret = obj,
- key = SUITE_PREFIX + suite.title;
- obj = obj[key] = obj[key] || { suite: suite };
- suite.suites.forEach(function(suite){
- mapTOC(suite, obj);
- });
- return ret;
- }
-
- function stringifyTOC(obj, level) {
- ++level;
- var buf = '';
- var link;
- for (var key in obj) {
- if ('suite' == key) continue;
- if (key !== SUITE_PREFIX) {
- link = ' - [' + key.substring(1) + ']';
- link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
- buf += Array(level).join(' ') + link;
- }
- buf += stringifyTOC(obj[key], level);
- }
- return buf;
- }
-
- function generateTOC(suite) {
- var obj = mapTOC(suite, {});
- return stringifyTOC(obj, 0);
- }
-
- generateTOC(runner.suite);
-
- runner.on('suite', function(suite){
- ++level;
- var slug = utils.slug(suite.fullTitle());
- buf += '<a name="' + slug + '"></a>' + '\n';
- buf += title(suite.title) + '\n';
- });
-
- runner.on('suite end', function(suite){
- --level;
- });
-
- runner.on('pass', function(test){
- var code = utils.clean(test.fn.toString());
- buf += test.title + '.\n';
- buf += '\n```js\n';
- buf += code + '\n';
- buf += '```\n\n';
- });
-
- runner.on('end', function(){
- process.stdout.write('# TOC\n');
- process.stdout.write(generateTOC(runner.suite));
- process.stdout.write(buf);
- });
-}
-
-}); // module: reporters/markdown.js
-
-require.register("reporters/min.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `Min`.
- */
-
-exports = module.exports = Min;
-
-/**
- * Initialize a new `Min` minimal test reporter (best used with --watch).
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Min(runner) {
- Base.call(this, runner);
-
- runner.on('start', function(){
- // clear screen
- process.stdout.write('\u001b[2J');
- // set cursor position
- process.stdout.write('\u001b[1;3H');
- });
-
- runner.on('end', this.epilogue.bind(this));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-Min.prototype = new F;
-Min.prototype.constructor = Min;
-
-
-}); // module: reporters/min.js
-
-require.register("reporters/nyan.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = NyanCat;
-
-/**
- * Initialize a new `Dot` matrix test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function NyanCat(runner) {
- Base.call(this, runner);
- var self = this
- , stats = this.stats
- , width = Base.window.width * .75 | 0
- , rainbowColors = this.rainbowColors = self.generateColors()
- , colorIndex = this.colorIndex = 0
- , numerOfLines = this.numberOfLines = 4
- , trajectories = this.trajectories = [[], [], [], []]
- , nyanCatWidth = this.nyanCatWidth = 11
- , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
- , scoreboardWidth = this.scoreboardWidth = 5
- , tick = this.tick = 0
- , n = 0;
-
- runner.on('start', function(){
- Base.cursor.hide();
- self.draw();
- });
-
- runner.on('pending', function(test){
- self.draw();
- });
-
- runner.on('pass', function(test){
- self.draw();
- });
-
- runner.on('fail', function(test, err){
- self.draw();
- });
-
- runner.on('end', function(){
- Base.cursor.show();
- for (var i = 0; i < self.numberOfLines; i++) write('\n');
- self.epilogue();
- });
-}
-
-/**
- * Draw the nyan cat
- *
- * @api private
- */
-
-NyanCat.prototype.draw = function(){
- this.appendRainbow();
- this.drawScoreboard();
- this.drawRainbow();
- this.drawNyanCat();
- this.tick = !this.tick;
-};
-
-/**
- * Draw the "scoreboard" showing the number
- * of passes, failures and pending tests.
- *
- * @api private
- */
-
-NyanCat.prototype.drawScoreboard = function(){
- var stats = this.stats;
-
- function draw(type, n) {
- write(' ');
- write(Base.color(type, n));
- write('\n');
- }
-
- draw('green', stats.passes);
- draw('fail', stats.failures);
- draw('pending', stats.pending);
- write('\n');
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Append the rainbow.
- *
- * @api private
- */
-
-NyanCat.prototype.appendRainbow = function(){
- var segment = this.tick ? '_' : '-';
- var rainbowified = this.rainbowify(segment);
-
- for (var index = 0; index < this.numberOfLines; index++) {
- var trajectory = this.trajectories[index];
- if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
- trajectory.push(rainbowified);
- }
-};
-
-/**
- * Draw the rainbow.
- *
- * @api private
- */
-
-NyanCat.prototype.drawRainbow = function(){
- var self = this;
-
- this.trajectories.forEach(function(line, index) {
- write('\u001b[' + self.scoreboardWidth + 'C');
- write(line.join(''));
- write('\n');
- });
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Draw the nyan cat
- *
- * @api private
- */
-
-NyanCat.prototype.drawNyanCat = function() {
- var self = this;
- var startWidth = this.scoreboardWidth + this.trajectories[0].length;
- var dist = '\u001b[' + startWidth + 'C';
- var padding = '';
-
- write(dist);
- write('_,------,');
- write('\n');
-
- write(dist);
- padding = self.tick ? ' ' : ' ';
- write('_|' + padding + '/\\_/\\ ');
- write('\n');
-
- write(dist);
- padding = self.tick ? '_' : '__';
- var tail = self.tick ? '~' : '^';
- var face;
- write(tail + '|' + padding + this.face() + ' ');
- write('\n');
-
- write(dist);
- padding = self.tick ? ' ' : ' ';
- write(padding + '"" "" ');
- write('\n');
-
- this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Draw nyan cat face.
- *
- * @return {String}
- * @api private
- */
-
-NyanCat.prototype.face = function() {
- var stats = this.stats;
- if (stats.failures) {
- return '( x .x)';
- } else if (stats.pending) {
- return '( o .o)';
- } else if(stats.passes) {
- return '( ^ .^)';
- } else {
- return '( - .-)';
- }
-};
-
-/**
- * Move cursor up `n`.
- *
- * @param {Number} n
- * @api private
- */
-
-NyanCat.prototype.cursorUp = function(n) {
- write('\u001b[' + n + 'A');
-};
-
-/**
- * Move cursor down `n`.
- *
- * @param {Number} n
- * @api private
- */
-
-NyanCat.prototype.cursorDown = function(n) {
- write('\u001b[' + n + 'B');
-};
-
-/**
- * Generate rainbow colors.
- *
- * @return {Array}
- * @api private
- */
-
-NyanCat.prototype.generateColors = function(){
- var colors = [];
-
- for (var i = 0; i < (6 * 7); i++) {
- var pi3 = Math.floor(Math.PI / 3);
- var n = (i * (1.0 / 6));
- var r = Math.floor(3 * Math.sin(n) + 3);
- var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
- var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
- colors.push(36 * r + 6 * g + b + 16);
- }
-
- return colors;
-};
-
-/**
- * Apply rainbow to the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-NyanCat.prototype.rainbowify = function(str){
- if (!Base.useColors)
- return str;
- var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
- this.colorIndex += 1;
- return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
-};
-
-/**
- * Stdout helper.
- */
-
-function write(string) {
- process.stdout.write(string);
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-NyanCat.prototype = new F;
-NyanCat.prototype.constructor = NyanCat;
-
-
-}); // module: reporters/nyan.js
-
-require.register("reporters/progress.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `Progress`.
- */
-
-exports = module.exports = Progress;
-
-/**
- * General progress bar color.
- */
-
-Base.colors.progress = 90;
-
-/**
- * Initialize a new `Progress` bar test reporter.
- *
- * @param {Runner} runner
- * @param {Object} options
- * @api public
- */
-
-function Progress(runner, options) {
- Base.call(this, runner);
-
- options = options || {}
- var self = this
- , stats = this.stats
- , width = Base.window.width * .50 | 0
- , total = runner.total
- , complete = 0
- , max = Math.max
- , lastN = -1;
-
- // default chars
- options.open = options.open || '[';
- options.complete = options.complete || '▬';
- options.incomplete = options.incomplete || Base.symbols.dot;
- options.close = options.close || ']';
- options.verbose = false;
-
- // tests started
- runner.on('start', function(){
- console.log();
- cursor.hide();
- });
-
- // tests complete
- runner.on('test end', function(){
- complete++;
- var incomplete = total - complete
- , percent = complete / total
- , n = width * percent | 0
- , i = width - n;
-
- if (lastN === n && !options.verbose) {
- // Don't re-render the line if it hasn't changed
- return;
- }
- lastN = n;
-
- cursor.CR();
- process.stdout.write('\u001b[J');
- process.stdout.write(color('progress', ' ' + options.open));
- process.stdout.write(Array(n).join(options.complete));
- process.stdout.write(Array(i).join(options.incomplete));
- process.stdout.write(color('progress', options.close));
- if (options.verbose) {
- process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
- }
- });
-
- // tests are complete, output some stats
- // and the failures if any
- runner.on('end', function(){
- cursor.show();
- console.log();
- self.epilogue();
- });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-Progress.prototype = new F;
-Progress.prototype.constructor = Progress;
-
-
-}); // module: reporters/progress.js
-
-require.register("reporters/spec.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `Spec`.
- */
-
-exports = module.exports = Spec;
-
-/**
- * Initialize a new `Spec` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Spec(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , indents = 0
- , n = 0;
-
- function indent() {
- return Array(indents).join(' ')
- }
-
- runner.on('start', function(){
- console.log();
- });
-
- runner.on('suite', function(suite){
- ++indents;
- console.log(color('suite', '%s%s'), indent(), suite.title);
- });
-
- runner.on('suite end', function(suite){
- --indents;
- if (1 == indents) console.log();
- });
-
- runner.on('pending', function(test){
- var fmt = indent() + color('pending', ' - %s');
- console.log(fmt, test.title);
- });
-
- runner.on('pass', function(test){
- if ('fast' == test.speed) {
- var fmt = indent()
- + color('checkmark', ' ' + Base.symbols.ok)
- + color('pass', ' %s');
- cursor.CR();
- console.log(fmt, test.title);
- } else {
- fmt = indent()
- + color('checkmark', ' ' + Base.symbols.ok)
- + color('pass', ' %s')
- + color(test.speed, ' (%dms)');
- cursor.CR();
- console.log(fmt, test.title, test.duration);
- }
- });
-
- runner.on('fail', function(test, err){
- cursor.CR();
- console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
- });
-
- runner.on('end', self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-Spec.prototype = new F;
-Spec.prototype.constructor = Spec;
-
-
-}); // module: reporters/spec.js
-
-require.register("reporters/tap.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , cursor = Base.cursor
- , color = Base.color;
-
-/**
- * Expose `TAP`.
- */
-
-exports = module.exports = TAP;
-
-/**
- * Initialize a new `TAP` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function TAP(runner) {
- Base.call(this, runner);
-
- var self = this
- , stats = this.stats
- , n = 1
- , passes = 0
- , failures = 0;
-
- runner.on('start', function(){
- var total = runner.grepTotal(runner.suite);
- console.log('%d..%d', 1, total);
- });
-
- runner.on('test end', function(){
- ++n;
- });
-
- runner.on('pending', function(test){
- console.log('ok %d %s # SKIP -', n, title(test));
- });
-
- runner.on('pass', function(test){
- passes++;
- console.log('ok %d %s', n, title(test));
- });
-
- runner.on('fail', function(test, err){
- failures++;
- console.log('not ok %d %s', n, title(test));
- if (err.stack) console.log(err.stack.replace(/^/gm, ' '));
- });
-
- runner.on('end', function(){
- console.log('# tests ' + (passes + failures));
- console.log('# pass ' + passes);
- console.log('# fail ' + failures);
- });
-}
-
-/**
- * Return a TAP-safe title of `test`
- *
- * @param {Object} test
- * @return {String}
- * @api private
- */
-
-function title(test) {
- return test.fullTitle().replace(/#/g, '');
-}
-
-}); // module: reporters/tap.js
-
-require.register("reporters/xunit.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
- , utils = require('../utils')
- , fs = require('browser/fs')
- , escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Expose `XUnit`.
- */
-
-exports = module.exports = XUnit;
-
-/**
- * Initialize a new `XUnit` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function XUnit(runner, options) {
- Base.call(this, runner);
- var stats = this.stats
- , tests = []
- , self = this;
-
- if (options.reporterOptions && options.reporterOptions.output) {
- if (! fs.createWriteStream) {
- throw new Error('file output not supported in browser');
- }
- self.fileStream = fs.createWriteStream(options.reporterOptions.output);
- }
-
- runner.on('pending', function(test){
- tests.push(test);
- });
-
- runner.on('pass', function(test){
- tests.push(test);
- });
-
- runner.on('fail', function(test){
- tests.push(test);
- });
-
- runner.on('end', function(){
- self.write(tag('testsuite', {
- name: 'Mocha Tests'
- , tests: stats.tests
- , failures: stats.failures
- , errors: stats.failures
- , skipped: stats.tests - stats.failures - stats.passes
- , timestamp: (new Date).toUTCString()
- , time: (stats.duration / 1000) || 0
- }, false));
-
- tests.forEach(function(t) { self.test(t); });
- self.write('</testsuite>');
- });
-}
-
-/**
- * Override done to close the stream (if it's a file).
- */
-XUnit.prototype.done = function(failures, fn) {
- if (this.fileStream) {
- this.fileStream.end(function() {
- fn(failures);
- });
- } else {
- fn(failures);
- }
-};
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){}
-F.prototype = Base.prototype;
-XUnit.prototype = new F;
-XUnit.prototype.constructor = XUnit;
-
-
-/**
- * Write out the given line
- */
-XUnit.prototype.write = function(line) {
- if (this.fileStream) {
- this.fileStream.write(line + '\n');
- } else {
- console.log(line);
- }
-};
-
-/**
- * Output tag for the given `test.`
- */
-
-XUnit.prototype.test = function(test, ostream) {
- var attrs = {
- classname: test.parent.fullTitle()
- , name: test.title
- , time: (test.duration / 1000) || 0
- };
-
- if ('failed' == test.state) {
- var err = test.err;
- this.write(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack))));
- } else if (test.pending) {
- this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));
- } else {
- this.write(tag('testcase', attrs, true) );
- }
-};
-
-/**
- * HTML tag helper.
- */
-
-function tag(name, attrs, close, content) {
- var end = close ? '/>' : '>'
- , pairs = []
- , tag;
-
- for (var key in attrs) {
- pairs.push(key + '="' + escape(attrs[key]) + '"');
- }
-
- tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
- if (content) tag += content + '</' + name + end;
- return tag;
-}
-
-/**
- * Return cdata escaped CDATA `str`.
- */
-
-function cdata(str) {
- return '<![CDATA[' + escape(str) + ']]>';
-}
-
-}); // module: reporters/xunit.js
-
-require.register("runnable.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('mocha:runnable')
- , Pending = require('./pending')
- , milliseconds = require('./ms')
- , utils = require('./utils');
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
- , setTimeout = global.setTimeout
- , setInterval = global.setInterval
- , clearTimeout = global.clearTimeout
- , clearInterval = global.clearInterval;
-
-/**
- * Object#toString().
- */
-
-var toString = Object.prototype.toString;
-
-/**
- * Expose `Runnable`.
- */
-
-module.exports = Runnable;
-
-/**
- * Initialize a new `Runnable` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Runnable(title, fn) {
- this.title = title;
- this.fn = fn;
- this.async = fn && fn.length;
- this.sync = ! this.async;
- this._timeout = 2000;
- this._slow = 75;
- this._enableTimeouts = true;
- this.timedOut = false;
- this._trace = new Error('done() called multiple times')
-}
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-
-function F(){}
-F.prototype = EventEmitter.prototype;
-Runnable.prototype = new F;
-Runnable.prototype.constructor = Runnable;
-
-
-/**
- * Set & get timeout `ms`.
- *
- * @param {Number|String} ms
- * @return {Runnable|Number} ms or self
- * @api private
- */
-
-Runnable.prototype.timeout = function(ms){
- if (0 == arguments.length) return this._timeout;
- if (ms === 0) this._enableTimeouts = false;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('timeout %d', ms);
- this._timeout = ms;
- if (this.timer) this.resetTimeout();
- return this;
-};
-
-/**
- * Set & get slow `ms`.
- *
- * @param {Number|String} ms
- * @return {Runnable|Number} ms or self
- * @api private
- */
-
-Runnable.prototype.slow = function(ms){
- if (0 === arguments.length) return this._slow;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('timeout %d', ms);
- this._slow = ms;
- return this;
-};
-
-/**
- * Set and & get timeout `enabled`.
- *
- * @param {Boolean} enabled
- * @return {Runnable|Boolean} enabled or self
- * @api private
- */
-
-Runnable.prototype.enableTimeouts = function(enabled){
- if (arguments.length === 0) return this._enableTimeouts;
- debug('enableTimeouts %s', enabled);
- this._enableTimeouts = enabled;
- return this;
-};
-
-/**
- * Halt and mark as pending.
- *
- * @api private
- */
-
-Runnable.prototype.skip = function(){
- throw new Pending();
-};
-
-/**
- * Return the full title generated by recursively
- * concatenating the parent's full title.
- *
- * @return {String}
- * @api public
- */
-
-Runnable.prototype.fullTitle = function(){
- return this.parent.fullTitle() + ' ' + this.title;
-};
-
-/**
- * Clear the timeout.
- *
- * @api private
- */
-
-Runnable.prototype.clearTimeout = function(){
- clearTimeout(this.timer);
-};
-
-/**
- * Inspect the runnable void of private properties.
- *
- * @return {String}
- * @api private
- */
-
-Runnable.prototype.inspect = function(){
- return JSON.stringify(this, function(key, val){
- if ('_' == key[0]) return undefined;
- if ('parent' == key) return '#<Suite>';
- if ('ctx' == key) return '#<Context>';
- return val;
- }, 2);
-};
-
-/**
- * Reset the timeout.
- *
- * @api private
- */
-
-Runnable.prototype.resetTimeout = function(){
- var self = this;
- var ms = this.timeout() || 1e9;
-
- if (!this._enableTimeouts) return;
- this.clearTimeout();
- this.timer = setTimeout(function(){
- if (!self._enableTimeouts) return;
- self.callback(new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.'));
- self.timedOut = true;
- }, ms);
-};
-
-/**
- * Whitelist these globals for this test run
- *
- * @api private
- */
-Runnable.prototype.globals = function(arr){
- var self = this;
- this._allowedGlobals = arr;
-};
-
-/**
- * Run the test and invoke `fn(err)`.
- *
- * @param {Function} fn
- * @api private
- */
-
-Runnable.prototype.run = function(fn){
- var self = this
- , start = new Date
- , ctx = this.ctx
- , finished
- , emitted;
-
- // Some times the ctx exists but it is not runnable
- if (ctx && ctx.runnable) ctx.runnable(this);
-
- // called multiple times
- function multiple(err) {
- if (emitted) return;
- emitted = true;
- self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate'));
- }
-
- // finished
- function done(err) {
- var ms = self.timeout();
- if (self.timedOut) return undefined;
- if (finished) return multiple(err || self._trace);
-
- // Discard the resolution if this test has already failed asynchronously
- if (self.state) return undefined;
-
- self.clearTimeout();
- self.duration = new Date - start;
- finished = true;
- if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.');
- fn(err);
- }
-
- // for .resetTimeout()
- this.callback = done;
-
- // explicit async with `done` argument
- if (this.async) {
- this.resetTimeout();
-
- try {
- this.fn.call(ctx, function(err){
- if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
- if (null != err) {
- if (Object.prototype.toString.call(err) === '[object Object]') {
- return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err)));
- } else {
- return done(new Error('done() invoked with non-Error: ' + err));
- }
- }
- done();
- });
- } catch (err) {
- done(utils.getError(err));
- }
- return undefined;
- }
-
- if (this.asyncOnly) {
- return done(new Error('--async-only option in use without declaring `done()`'));
- }
-
- // sync or promise-returning
- try {
- if (this.pending) {
- done();
- } else {
- callFn(this.fn);
- }
- } catch (err) {
- done(utils.getError(err));
- }
-
- function callFn(fn) {
- var result = fn.call(ctx);
- if (result && typeof result.then === 'function') {
- self.resetTimeout();
- result
- .then(function() {
- done()
- },
- function(reason) {
- done(reason || new Error('Promise rejected with no or falsy reason'))
- });
- } else {
- done();
- }
- }
-};
-
-}); // module: runnable.js
-
-require.register("runner.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('mocha:runner')
- , Pending = require('./pending')
- , Test = require('./test')
- , utils = require('./utils')
- , filter = utils.filter
- , keys = utils.keys
- , type = utils.type
- , stringify = utils.stringify
- , stackFilter = utils.stackTraceFilter();
-
-/**
- * Non-enumerable globals.
- */
-
-var globals = [
- 'setTimeout',
- 'clearTimeout',
- 'setInterval',
- 'clearInterval',
- 'XMLHttpRequest',
- 'Date',
- 'setImmediate',
- 'clearImmediate'
-];
-
-/**
- * Expose `Runner`.
- */
-
-module.exports = Runner;
-
-/**
- * Initialize a `Runner` for the given `suite`.
- *
- * Events:
- *
- * - `start` execution started
- * - `end` execution complete
- * - `suite` (suite) test suite execution started
- * - `suite end` (suite) all tests (and sub-suites) have finished
- * - `test` (test) test execution started
- * - `test end` (test) test completed
- * - `hook` (hook) hook execution started
- * - `hook end` (hook) hook complete
- * - `pass` (test) test passed
- * - `fail` (test, err) test failed
- * - `pending` (test) test pending
- *
- * @param {Suite} suite Root suite
- * @param {boolean} [delay] Whether or not to delay execution of root suite
- * until ready.
- * @api public
- */
-
-function Runner(suite, delay) {
- var self = this;
- this._globals = [];
- this._abort = false;
- this._delay = delay;
- this.suite = suite;
- this.total = suite.total();
- this.failures = 0;
- this.on('test end', function(test){ self.checkGlobals(test); });
- this.on('hook end', function(hook){ self.checkGlobals(hook); });
- this.grep(/.*/);
- this.globals(this.globalProps().concat(extraGlobals()));
-}
-
-/**
- * Wrapper for setImmediate, process.nextTick, or browser polyfill.
- *
- * @param {Function} fn
- * @api private
- */
-
-Runner.immediately = global.setImmediate || process.nextTick;
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-
-function F(){}
-F.prototype = EventEmitter.prototype;
-Runner.prototype = new F;
-Runner.prototype.constructor = Runner;
-
-
-/**
- * Run tests with full titles matching `re`. Updates runner.total
- * with number of tests matched.
- *
- * @param {RegExp} re
- * @param {Boolean} invert
- * @return {Runner} for chaining
- * @api public
- */
-
-Runner.prototype.grep = function(re, invert){
- debug('grep %s', re);
- this._grep = re;
- this._invert = invert;
- this.total = this.grepTotal(this.suite);
- return this;
-};
-
-/**
- * Returns the number of tests matching the grep search for the
- * given suite.
- *
- * @param {Suite} suite
- * @return {Number}
- * @api public
- */
-
-Runner.prototype.grepTotal = function(suite) {
- var self = this;
- var total = 0;
-
- suite.eachTest(function(test){
- var match = self._grep.test(test.fullTitle());
- if (self._invert) match = !match;
- if (match) total++;
- });
-
- return total;
-};
-
-/**
- * Return a list of global properties.
- *
- * @return {Array}
- * @api private
- */
-
-Runner.prototype.globalProps = function() {
- var props = utils.keys(global);
-
- // non-enumerables
- for (var i = 0; i < globals.length; ++i) {
- if (~utils.indexOf(props, globals[i])) continue;
- props.push(globals[i]);
- }
-
- return props;
-};
-
-/**
- * Allow the given `arr` of globals.
- *
- * @param {Array} arr
- * @return {Runner} for chaining
- * @api public
- */
-
-Runner.prototype.globals = function(arr){
- if (0 == arguments.length) return this._globals;
- debug('globals %j', arr);
- this._globals = this._globals.concat(arr);
- return this;
-};
-
-/**
- * Check for global variable leaks.
- *
- * @api private
- */
-
-Runner.prototype.checkGlobals = function(test){
- if (this.ignoreLeaks) return;
- var ok = this._globals;
-
- var globals = this.globalProps();
- var leaks;
-
- if (test) {
- ok = ok.concat(test._allowedGlobals || []);
- }
-
- if(this.prevGlobalsLength == globals.length) return;
- this.prevGlobalsLength = globals.length;
-
- leaks = filterLeaks(ok, globals);
- this._globals = this._globals.concat(leaks);
-
- if (leaks.length > 1) {
- this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
- } else if (leaks.length) {
- this.fail(test, new Error('global leak detected: ' + leaks[0]));
- }
-};
-
-/**
- * Fail the given `test`.
- *
- * @param {Test} test
- * @param {Error} err
- * @api private
- */
-
-Runner.prototype.fail = function(test, err) {
- ++this.failures;
- test.state = 'failed';
-
- if (!(err instanceof Error)) {
- err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)');
- }
-
- err.stack = (this.fullStackTrace || !err.stack)
- ? err.stack
- : stackFilter(err.stack);
-
- this.emit('fail', test, err);
-};
-
-/**
- * Fail the given `hook` with `err`.
- *
- * Hook failures work in the following pattern:
- * - If bail, then exit
- * - Failed `before` hook skips all tests in a suite and subsuites,
- * but jumps to corresponding `after` hook
- * - Failed `before each` hook skips remaining tests in a
- * suite and jumps to corresponding `after each` hook,
- * which is run only once
- * - Failed `after` hook does not alter
- * execution order
- * - Failed `after each` hook skips remaining tests in a
- * suite and subsuites, but executes other `after each`
- * hooks
- *
- * @param {Hook} hook
- * @param {Error} err
- * @api private
- */
-
-Runner.prototype.failHook = function(hook, err){
- this.fail(hook, err);
- if (this.suite.bail()) {
- this.emit('end');
- }
-};
-
-/**
- * Run hook `name` callbacks and then invoke `fn()`.
- *
- * @param {String} name
- * @param {Function} function
- * @api private
- */
-
-Runner.prototype.hook = function(name, fn){
- var suite = this.suite
- , hooks = suite['_' + name]
- , self = this
- , timer;
-
- function next(i) {
- var hook = hooks[i];
- if (!hook) return fn();
- self.currentRunnable = hook;
-
- hook.ctx.currentTest = self.test;
-
- self.emit('hook', hook);
-
- hook.on('error', function(err){
- self.failHook(hook, err);
- });
-
- hook.run(function(err){
- hook.removeAllListeners('error');
- var testError = hook.error();
- if (testError) self.fail(self.test, testError);
- if (err) {
- if (err instanceof Pending) {
- suite.pending = true;
- } else {
- self.failHook(hook, err);
-
- // stop executing hooks, notify callee of hook err
- return fn(err);
- }
- }
- self.emit('hook end', hook);
- delete hook.ctx.currentTest;
- next(++i);
- });
- }
-
- Runner.immediately(function(){
- next(0);
- });
-};
-
-/**
- * Run hook `name` for the given array of `suites`
- * in order, and callback `fn(err, errSuite)`.
- *
- * @param {String} name
- * @param {Array} suites
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.hooks = function(name, suites, fn){
- var self = this
- , orig = this.suite;
-
- function next(suite) {
- self.suite = suite;
-
- if (!suite) {
- self.suite = orig;
- return fn();
- }
-
- self.hook(name, function(err){
- if (err) {
- var errSuite = self.suite;
- self.suite = orig;
- return fn(err, errSuite);
- }
-
- next(suites.pop());
- });
- }
-
- next(suites.pop());
-};
-
-/**
- * Run hooks from the top level down.
- *
- * @param {String} name
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.hookUp = function(name, fn){
- var suites = [this.suite].concat(this.parents()).reverse();
- this.hooks(name, suites, fn);
-};
-
-/**
- * Run hooks from the bottom up.
- *
- * @param {String} name
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.hookDown = function(name, fn){
- var suites = [this.suite].concat(this.parents());
- this.hooks(name, suites, fn);
-};
-
-/**
- * Return an array of parent Suites from
- * closest to furthest.
- *
- * @return {Array}
- * @api private
- */
-
-Runner.prototype.parents = function(){
- var suite = this.suite
- , suites = [];
- while (suite = suite.parent) suites.push(suite);
- return suites;
-};
-
-/**
- * Run the current test and callback `fn(err)`.
- *
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.runTest = function(fn){
- var test = this.test
- , self = this;
-
- if (this.asyncOnly) test.asyncOnly = true;
-
- try {
- test.on('error', function(err){
- self.fail(test, err);
- });
- test.run(fn);
- } catch (err) {
- fn(err);
- }
-};
-
-/**
- * Run tests in the given `suite` and invoke
- * the callback `fn()` when complete.
- *
- * @param {Suite} suite
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.runTests = function(suite, fn){
- var self = this
- , tests = suite.tests.slice()
- , test;
-
-
- function hookErr(err, errSuite, after) {
- // before/after Each hook for errSuite failed:
- var orig = self.suite;
-
- // for failed 'after each' hook start from errSuite parent,
- // otherwise start from errSuite itself
- self.suite = after ? errSuite.parent : errSuite;
-
- if (self.suite) {
- // call hookUp afterEach
- self.hookUp('afterEach', function(err2, errSuite2) {
- self.suite = orig;
- // some hooks may fail even now
- if (err2) return hookErr(err2, errSuite2, true);
- // report error suite
- fn(errSuite);
- });
- } else {
- // there is no need calling other 'after each' hooks
- self.suite = orig;
- fn(errSuite);
- }
- }
-
- function next(err, errSuite) {
- // if we bail after first err
- if (self.failures && suite._bail) return fn();
-
- if (self._abort) return fn();
-
- if (err) return hookErr(err, errSuite, true);
-
- // next test
- test = tests.shift();
-
- // all done
- if (!test) return fn();
-
- // grep
- var match = self._grep.test(test.fullTitle());
- if (self._invert) match = !match;
- if (!match) return next();
-
- // pending
- if (test.pending) {
- self.emit('pending', test);
- self.emit('test end', test);
- return next();
- }
-
- // execute test and hook(s)
- self.emit('test', self.test = test);
- self.hookDown('beforeEach', function(err, errSuite){
-
- if (suite.pending) {
- self.emit('pending', test);
- self.emit('test end', test);
- return next();
- }
- if (err) return hookErr(err, errSuite, false);
-
- self.currentRunnable = self.test;
- self.runTest(function(err){
- test = self.test;
-
- if (err) {
- if (err instanceof Pending) {
- self.emit('pending', test);
- } else {
- self.fail(test, err);
- }
- self.emit('test end', test);
-
- if (err instanceof Pending) {
- return next();
- }
-
- return self.hookUp('afterEach', next);
- }
-
- test.state = 'passed';
- self.emit('pass', test);
- self.emit('test end', test);
- self.hookUp('afterEach', next);
- });
- });
- }
-
- this.next = next;
- next();
-};
-
-/**
- * Run the given `suite` and invoke the
- * callback `fn()` when complete.
- *
- * @param {Suite} suite
- * @param {Function} fn
- * @api private
- */
-
-Runner.prototype.runSuite = function(suite, fn){
- var total = this.grepTotal(suite)
- , self = this
- , i = 0;
-
- debug('run suite %s', suite.fullTitle());
-
- if (!total) return fn();
-
- this.emit('suite', this.suite = suite);
-
- function next(errSuite) {
- if (errSuite) {
- // current suite failed on a hook from errSuite
- if (errSuite == suite) {
- // if errSuite is current suite
- // continue to the next sibling suite
- return done();
- } else {
- // errSuite is among the parents of current suite
- // stop execution of errSuite and all sub-suites
- return done(errSuite);
- }
- }
-
- if (self._abort) return done();
-
- var curr = suite.suites[i++];
- if (!curr) return done();
- self.runSuite(curr, next);
- }
-
- function done(errSuite) {
- self.suite = suite;
- self.hook('afterAll', function(){
- self.emit('suite end', suite);
- fn(errSuite);
- });
- }
-
- this.hook('beforeAll', function(err){
- if (err) return done();
- self.runTests(suite, next);
- });
-};
-
-/**
- * Handle uncaught exceptions.
- *
- * @param {Error} err
- * @api private
- */
-
-Runner.prototype.uncaught = function(err){
- if (err) {
- debug('uncaught exception %s', err !== function () {
- return this;
- }.call(err) ? err : ( err.message || err ));
- } else {
- debug('uncaught undefined exception');
- err = utils.undefinedError();
- }
- err.uncaught = true;
-
- var runnable = this.currentRunnable;
- if (!runnable) return;
-
- runnable.clearTimeout();
-
- // Ignore errors if complete
- if (runnable.state) return;
- this.fail(runnable, err);
-
- // recover from test
- if ('test' == runnable.type) {
- this.emit('test end', runnable);
- this.hookUp('afterEach', this.next);
- return;
- }
-
- // bail on hooks
- this.emit('end');
-};
-
-/**
- * Run the root suite and invoke `fn(failures)`
- * on completion.
- *
- * @param {Function} fn
- * @return {Runner} for chaining
- * @api public
- */
-
-Runner.prototype.run = function(fn){
- var self = this,
- rootSuite = this.suite;
-
- fn = fn || function(){};
-
- function uncaught(err){
- self.uncaught(err);
- }
-
- function start() {
- self.emit('start');
- self.runSuite(rootSuite, function(){
- debug('finished running');
- self.emit('end');
- });
- }
-
- debug('start');
-
- // callback
- this.on('end', function(){
- debug('end');
- process.removeListener('uncaughtException', uncaught);
- fn(self.failures);
- });
-
- // uncaught exception
- process.on('uncaughtException', uncaught);
-
- if (this._delay) {
- // for reporters, I guess.
- // might be nice to debounce some dots while we wait.
- this.emit('waiting', rootSuite);
- rootSuite.once('run', start);
- }
- else {
- start();
- }
-
- return this;
-};
-
-/**
- * Cleanly abort execution
- *
- * @return {Runner} for chaining
- * @api public
- */
-Runner.prototype.abort = function(){
- debug('aborting');
- this._abort = true;
-};
-
-/**
- * Filter leaks with the given globals flagged as `ok`.
- *
- * @param {Array} ok
- * @param {Array} globals
- * @return {Array}
- * @api private
- */
-
-function filterLeaks(ok, globals) {
- return filter(globals, function(key){
- // Firefox and Chrome exposes iframes as index inside the window object
- if (/^d+/.test(key)) return false;
-
- // in firefox
- // if runner runs in an iframe, this iframe's window.getInterface method not init at first
- // it is assigned in some seconds
- if (global.navigator && /^getInterface/.test(key)) return false;
-
- // an iframe could be approached by window[iframeIndex]
- // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
- if (global.navigator && /^\d+/.test(key)) return false;
-
- // Opera and IE expose global variables for HTML element IDs (issue #243)
- if (/^mocha-/.test(key)) return false;
-
- var matched = filter(ok, function(ok){
- if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
- return key == ok;
- });
- return matched.length == 0 && (!global.navigator || 'onerror' !== key);
- });
-}
-
-/**
- * Array of globals dependent on the environment.
- *
- * @return {Array}
- * @api private
- */
-
-function extraGlobals() {
- if (typeof(process) === 'object' &&
- typeof(process.version) === 'string') {
-
- var nodeVersion = process.version.split('.').reduce(function(a, v) {
- return a << 8 | v;
- });
-
- // 'errno' was renamed to process._errno in v0.9.11.
-
- if (nodeVersion < 0x00090B) {
- return ['errno'];
- }
- }
-
- return [];
-}
-
-}); // module: runner.js
-
-require.register("suite.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('browser/events').EventEmitter
- , debug = require('browser/debug')('mocha:suite')
- , milliseconds = require('./ms')
- , utils = require('./utils')
- , Hook = require('./hook');
-
-/**
- * Expose `Suite`.
- */
-
-exports = module.exports = Suite;
-
-/**
- * Create a new `Suite` with the given `title`
- * and parent `Suite`. When a suite with the
- * same title is already present, that suite
- * is returned to provide nicer reporter
- * and more flexible meta-testing.
- *
- * @param {Suite} parent
- * @param {String} title
- * @return {Suite}
- * @api public
- */
-
-exports.create = function(parent, title){
- var suite = new Suite(title, parent.ctx);
- suite.parent = parent;
- if (parent.pending) suite.pending = true;
- title = suite.fullTitle();
- parent.addSuite(suite);
- return suite;
-};
-
-/**
- * Initialize a new `Suite` with the given
- * `title` and `ctx`.
- *
- * @param {String} title
- * @param {Context} ctx
- * @api private
- */
-
-function Suite(title, parentContext) {
- this.title = title;
- var context = function() {};
- context.prototype = parentContext;
- this.ctx = new context();
- this.suites = [];
- this.tests = [];
- this.pending = false;
- this._beforeEach = [];
- this._beforeAll = [];
- this._afterEach = [];
- this._afterAll = [];
- this.root = !title;
- this._timeout = 2000;
- this._enableTimeouts = true;
- this._slow = 75;
- this._bail = false;
- this.delayed = false;
-}
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-
-function F(){}
-F.prototype = EventEmitter.prototype;
-Suite.prototype = new F;
-Suite.prototype.constructor = Suite;
-
-
-/**
- * Return a clone of this `Suite`.
- *
- * @return {Suite}
- * @api private
- */
-
-Suite.prototype.clone = function(){
- var suite = new Suite(this.title);
- debug('clone');
- suite.ctx = this.ctx;
- suite.timeout(this.timeout());
- suite.enableTimeouts(this.enableTimeouts());
- suite.slow(this.slow());
- suite.bail(this.bail());
- return suite;
-};
-
-/**
- * Set timeout `ms` or short-hand such as "2s".
- *
- * @param {Number|String} ms
- * @return {Suite|Number} for chaining
- * @api private
- */
-
-Suite.prototype.timeout = function(ms){
- if (0 == arguments.length) return this._timeout;
- if (ms.toString() === '0') this._enableTimeouts = false;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('timeout %d', ms);
- this._timeout = parseInt(ms, 10);
- return this;
-};
-
-/**
- * Set timeout `enabled`.
- *
- * @param {Boolean} enabled
- * @return {Suite|Boolean} self or enabled
- * @api private
- */
-
-Suite.prototype.enableTimeouts = function(enabled){
- if (arguments.length === 0) return this._enableTimeouts;
- debug('enableTimeouts %s', enabled);
- this._enableTimeouts = enabled;
- return this;
-};
-
-/**
- * Set slow `ms` or short-hand such as "2s".
- *
- * @param {Number|String} ms
- * @return {Suite|Number} for chaining
- * @api private
- */
-
-Suite.prototype.slow = function(ms){
- if (0 === arguments.length) return this._slow;
- if ('string' == typeof ms) ms = milliseconds(ms);
- debug('slow %d', ms);
- this._slow = ms;
- return this;
-};
-
-/**
- * Sets whether to bail after first error.
- *
- * @param {Boolean} bail
- * @return {Suite|Number} for chaining
- * @api private
- */
-
-Suite.prototype.bail = function(bail){
- if (0 == arguments.length) return this._bail;
- debug('bail %s', bail);
- this._bail = bail;
- return this;
-};
-
-/**
- * Run `fn(test[, done])` before running tests.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.beforeAll = function(title, fn){
- if (this.pending) return this;
- if ('function' === typeof title) {
- fn = title;
- title = fn.name;
- }
- title = '"before all" hook' + (title ? ': ' + title : '');
-
- var hook = new Hook(title, fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.enableTimeouts(this.enableTimeouts());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._beforeAll.push(hook);
- this.emit('beforeAll', hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` after running tests.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.afterAll = function(title, fn){
- if (this.pending) return this;
- if ('function' === typeof title) {
- fn = title;
- title = fn.name;
- }
- title = '"after all" hook' + (title ? ': ' + title : '');
-
- var hook = new Hook(title, fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.enableTimeouts(this.enableTimeouts());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._afterAll.push(hook);
- this.emit('afterAll', hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` before each test case.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.beforeEach = function(title, fn){
- if (this.pending) return this;
- if ('function' === typeof title) {
- fn = title;
- title = fn.name;
- }
- title = '"before each" hook' + (title ? ': ' + title : '');
-
- var hook = new Hook(title, fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.enableTimeouts(this.enableTimeouts());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._beforeEach.push(hook);
- this.emit('beforeEach', hook);
- return this;
-};
-
-/**
- * Run `fn(test[, done])` after each test case.
- *
- * @param {Function} fn
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.afterEach = function(title, fn){
- if (this.pending) return this;
- if ('function' === typeof title) {
- fn = title;
- title = fn.name;
- }
- title = '"after each" hook' + (title ? ': ' + title : '');
-
- var hook = new Hook(title, fn);
- hook.parent = this;
- hook.timeout(this.timeout());
- hook.enableTimeouts(this.enableTimeouts());
- hook.slow(this.slow());
- hook.ctx = this.ctx;
- this._afterEach.push(hook);
- this.emit('afterEach', hook);
- return this;
-};
-
-/**
- * Add a test `suite`.
- *
- * @param {Suite} suite
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.addSuite = function(suite){
- suite.parent = this;
- suite.timeout(this.timeout());
- suite.enableTimeouts(this.enableTimeouts());
- suite.slow(this.slow());
- suite.bail(this.bail());
- this.suites.push(suite);
- this.emit('suite', suite);
- return this;
-};
-
-/**
- * Add a `test` to this suite.
- *
- * @param {Test} test
- * @return {Suite} for chaining
- * @api private
- */
-
-Suite.prototype.addTest = function(test){
- test.parent = this;
- test.timeout(this.timeout());
- test.enableTimeouts(this.enableTimeouts());
- test.slow(this.slow());
- test.ctx = this.ctx;
- this.tests.push(test);
- this.emit('test', test);
- return this;
-};
-
-/**
- * Return the full title generated by recursively
- * concatenating the parent's full title.
- *
- * @return {String}
- * @api public
- */
-
-Suite.prototype.fullTitle = function(){
- if (this.parent) {
- var full = this.parent.fullTitle();
- if (full) return full + ' ' + this.title;
- }
- return this.title;
-};
-
-/**
- * Return the total number of tests.
- *
- * @return {Number}
- * @api public
- */
-
-Suite.prototype.total = function(){
- return utils.reduce(this.suites, function(sum, suite){
- return sum + suite.total();
- }, 0) + this.tests.length;
-};
-
-/**
- * Iterates through each suite recursively to find
- * all tests. Applies a function in the format
- * `fn(test)`.
- *
- * @param {Function} fn
- * @return {Suite}
- * @api private
- */
-
-Suite.prototype.eachTest = function(fn){
- utils.forEach(this.tests, fn);
- utils.forEach(this.suites, function(suite){
- suite.eachTest(fn);
- });
- return this;
-};
-
-/**
- * This will run the root suite if we happen to be running in delayed mode.
- */
-Suite.prototype.run = function run() {
- if (this.root) {
- this.emit('run');
- }
-};
-
-}); // module: suite.js
-
-require.register("test.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Runnable = require('./runnable');
-
-/**
- * Expose `Test`.
- */
-
-module.exports = Test;
-
-/**
- * Initialize a new `Test` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Test(title, fn) {
- Runnable.call(this, title, fn);
- this.pending = !fn;
- this.type = 'test';
-}
-
-/**
- * Inherit from `Runnable.prototype`.
- */
-
-function F(){}
-F.prototype = Runnable.prototype;
-Test.prototype = new F;
-Test.prototype.constructor = Test;
-
-
-}); // module: test.js
-
-require.register("utils.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var fs = require('browser/fs')
- , path = require('browser/path')
- , basename = path.basename
- , exists = fs.existsSync || path.existsSync
- , glob = require('browser/glob')
- , join = path.join
- , debug = require('browser/debug')('mocha:watch');
-
-/**
- * Ignored directories.
- */
-
-var ignore = ['node_modules', '.git'];
-
-/**
- * Escape special characters in the given string of html.
- *
- * @param {String} html
- * @return {String}
- * @api private
- */
-
-exports.escape = function(html){
- return String(html)
- .replace(/&/g, '&amp;')
- .replace(/"/g, '&quot;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
-};
-
-/**
- * Array#forEach (<=IE8)
- *
- * @param {Array} array
- * @param {Function} fn
- * @param {Object} scope
- * @api private
- */
-
-exports.forEach = function(arr, fn, scope){
- for (var i = 0, l = arr.length; i < l; i++)
- fn.call(scope, arr[i], i);
-};
-
-/**
- * Array#map (<=IE8)
- *
- * @param {Array} array
- * @param {Function} fn
- * @param {Object} scope
- * @api private
- */
-
-exports.map = function(arr, fn, scope){
- var result = [];
- for (var i = 0, l = arr.length; i < l; i++)
- result.push(fn.call(scope, arr[i], i, arr));
- return result;
-};
-
-/**
- * Array#indexOf (<=IE8)
- *
- * @parma {Array} arr
- * @param {Object} obj to find index of
- * @param {Number} start
- * @api private
- */
-
-exports.indexOf = function(arr, obj, start){
- for (var i = start || 0, l = arr.length; i < l; i++) {
- if (arr[i] === obj)
- return i;
- }
- return -1;
-};
-
-/**
- * Array#reduce (<=IE8)
- *
- * @param {Array} array
- * @param {Function} fn
- * @param {Object} initial value
- * @api private
- */
-
-exports.reduce = function(arr, fn, val){
- var rval = val;
-
- for (var i = 0, l = arr.length; i < l; i++) {
- rval = fn(rval, arr[i], i, arr);
- }
-
- return rval;
-};
-
-/**
- * Array#filter (<=IE8)
- *
- * @param {Array} array
- * @param {Function} fn
- * @api private
- */
-
-exports.filter = function(arr, fn){
- var ret = [];
-
- for (var i = 0, l = arr.length; i < l; i++) {
- var val = arr[i];
- if (fn(val, i, arr)) ret.push(val);
- }
-
- return ret;
-};
-
-/**
- * Object.keys (<=IE8)
- *
- * @param {Object} obj
- * @return {Array} keys
- * @api private
- */
-
-exports.keys = Object.keys || function(obj) {
- var keys = []
- , has = Object.prototype.hasOwnProperty; // for `window` on <=IE8
-
- for (var key in obj) {
- if (has.call(obj, key)) {
- keys.push(key);
- }
- }
-
- return keys;
-};
-
-/**
- * Watch the given `files` for changes
- * and invoke `fn(file)` on modification.
- *
- * @param {Array} files
- * @param {Function} fn
- * @api private
- */
-
-exports.watch = function(files, fn){
- var options = { interval: 100 };
- files.forEach(function(file){
- debug('file %s', file);
- fs.watchFile(file, options, function(curr, prev){
- if (prev.mtime < curr.mtime) fn(file);
- });
- });
-};
-
-/**
- * Array.isArray (<=IE8)
- *
- * @param {Object} obj
- * @return {Boolean}
- * @api private
- */
-var isArray = Array.isArray || function (obj) {
- return '[object Array]' == {}.toString.call(obj);
-};
-
-/**
- * @description
- * Buffer.prototype.toJSON polyfill
- * @type {Function}
- */
-if(typeof Buffer !== 'undefined' && Buffer.prototype) {
- Buffer.prototype.toJSON = Buffer.prototype.toJSON || function () {
- return Array.prototype.slice.call(this, 0);
- };
-}
-
-/**
- * Ignored files.
- */
-
-function ignored(path){
- return !~ignore.indexOf(path);
-}
-
-/**
- * Lookup files in the given `dir`.
- *
- * @return {Array}
- * @api private
- */
-
-exports.files = function(dir, ext, ret){
- ret = ret || [];
- ext = ext || ['js'];
-
- var re = new RegExp('\\.(' + ext.join('|') + ')$');
-
- fs.readdirSync(dir)
- .filter(ignored)
- .forEach(function(path){
- path = join(dir, path);
- if (fs.statSync(path).isDirectory()) {
- exports.files(path, ext, ret);
- } else if (path.match(re)) {
- ret.push(path);
- }
- });
-
- return ret;
-};
-
-/**
- * Compute a slug from the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-exports.slug = function(str){
- return str
- .toLowerCase()
- .replace(/ +/g, '-')
- .replace(/[^-\w]/g, '');
-};
-
-/**
- * Strip the function definition from `str`,
- * and re-indent for pre whitespace.
- */
-
-exports.clean = function(str) {
- str = str
- .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
- .replace(/^function *\(.*\)\s*{|\(.*\) *=> *{?/, '')
- .replace(/\s+\}$/, '');
-
- var spaces = str.match(/^\n?( *)/)[1].length
- , tabs = str.match(/^\n?(\t*)/)[1].length
- , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');
-
- str = str.replace(re, '');
-
- return exports.trim(str);
-};
-
-/**
- * Trim the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-exports.trim = function(str){
- return str.replace(/^\s+|\s+$/g, '');
-};
-
-/**
- * Parse the given `qs`.
- *
- * @param {String} qs
- * @return {Object}
- * @api private
- */
-
-exports.parseQuery = function(qs){
- return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
- var i = pair.indexOf('=')
- , key = pair.slice(0, i)
- , val = pair.slice(++i);
-
- obj[key] = decodeURIComponent(val);
- return obj;
- }, {});
-};
-
-/**
- * Highlight the given string of `js`.
- *
- * @param {String} js
- * @return {String}
- * @api private
- */
-
-function highlight(js) {
- return js
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
- .replace(/('.*?')/gm, '<span class="string">$1</span>')
- .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
- .replace(/(\d+)/gm, '<span class="number">$1</span>')
- .replace(/\bnew[ \t]+(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
- .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
-}
-
-/**
- * Highlight the contents of tag `name`.
- *
- * @param {String} name
- * @api private
- */
-
-exports.highlightTags = function(name) {
- var code = document.getElementById('mocha').getElementsByTagName(name);
- for (var i = 0, len = code.length; i < len; ++i) {
- code[i].innerHTML = highlight(code[i].innerHTML);
- }
-};
-
-/**
- * If a value could have properties, and has none, this function is called, which returns
- * a string representation of the empty value.
- *
- * Functions w/ no properties return `'[Function]'`
- * Arrays w/ length === 0 return `'[]'`
- * Objects w/ no properties return `'{}'`
- * All else: return result of `value.toString()`
- *
- * @param {*} value Value to inspect
- * @param {string} [type] The type of the value, if known.
- * @returns {string}
- */
-var emptyRepresentation = function emptyRepresentation(value, type) {
- type = type || exports.type(value);
-
- switch(type) {
- case 'function':
- return '[Function]';
- case 'object':
- return '{}';
- case 'array':
- return '[]';
- default:
- return value.toString();
- }
-};
-
-/**
- * Takes some variable and asks `{}.toString()` what it thinks it is.
- * @param {*} value Anything
- * @example
- * type({}) // 'object'
- * type([]) // 'array'
- * type(1) // 'number'
- * type(false) // 'boolean'
- * type(Infinity) // 'number'
- * type(null) // 'null'
- * type(new Date()) // 'date'
- * type(/foo/) // 'regexp'
- * type('type') // 'string'
- * type(global) // 'global'
- * @api private
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
- * @returns {string}
- */
-exports.type = function type(value) {
- if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
- return 'buffer';
- }
- return Object.prototype.toString.call(value)
- .replace(/^\[.+\s(.+?)\]$/, '$1')
- .toLowerCase();
-};
-
-/**
- * @summary Stringify `value`.
- * @description Different behavior depending on type of value.
- * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.
- * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.
- * - If `value` is an *empty* object, function, or array, return result of function
- * {@link emptyRepresentation}.
- * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of
- * JSON.stringify().
- *
- * @see exports.type
- * @param {*} value
- * @return {string}
- * @api private
- */
-
-exports.stringify = function(value) {
- var type = exports.type(value);
-
- if (!~exports.indexOf(['object', 'array', 'function'], type)) {
- if(type != 'buffer') {
- return jsonStringify(value);
- }
- var json = value.toJSON();
- // Based on the toJSON result
- return jsonStringify(json.data && json.type ? json.data : json, 2)
- .replace(/,(\n|$)/g, '$1');
- }
-
- for (var prop in value) {
- if (Object.prototype.hasOwnProperty.call(value, prop)) {
- return jsonStringify(exports.canonicalize(value), 2).replace(/,(\n|$)/g, '$1');
- }
- }
-
- return emptyRepresentation(value, type);
-};
-
-/**
- * @description
- * like JSON.stringify but more sense.
- * @param {Object} object
- * @param {Number=} spaces
- * @param {number=} depth
- * @returns {*}
- * @private
- */
-function jsonStringify(object, spaces, depth) {
- if(typeof spaces == 'undefined') return _stringify(object); // primitive types
-
- depth = depth || 1;
- var space = spaces * depth
- , str = isArray(object) ? '[' : '{'
- , end = isArray(object) ? ']' : '}'
- , length = object.length || exports.keys(object).length
- , repeat = function(s, n) { return new Array(n).join(s); }; // `.repeat()` polyfill
-
- function _stringify(val) {
- switch (exports.type(val)) {
- case 'null':
- case 'undefined':
- val = '[' + val + ']';
- break;
- case 'array':
- case 'object':
- val = jsonStringify(val, spaces, depth + 1);
- break;
- case 'boolean':
- case 'regexp':
- case 'number':
- val = val === 0 && (1/val) === -Infinity // `-0`
- ? '-0'
- : val.toString();
- break;
- case 'date':
- val = '[Date: ' + val.toISOString() + ']';
- break;
- case 'buffer':
- var json = val.toJSON();
- // Based on the toJSON result
- json = json.data && json.type ? json.data : json;
- val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
- break;
- default:
- val = (val == '[Function]' || val == '[Circular]')
- ? val
- : '"' + val + '"'; //string
- }
- return val;
- }
-
- for(var i in object) {
- if(!object.hasOwnProperty(i)) continue; // not my business
- --length;
- str += '\n ' + repeat(' ', space)
- + (isArray(object) ? '' : '"' + i + '": ') // key
- + _stringify(object[i]) // value
- + (length ? ',' : ''); // comma
- }
-
- return str + (str.length != 1 // [], {}
- ? '\n' + repeat(' ', --space) + end
- : end);
-}
-
-/**
- * Return if obj is a Buffer
- * @param {Object} arg
- * @return {Boolean}
- * @api private
- */
-exports.isBuffer = function (arg) {
- return typeof Buffer !== 'undefined' && Buffer.isBuffer(arg);
-};
-
-/**
- * @summary Return a new Thing that has the keys in sorted order. Recursive.
- * @description If the Thing...
- * - has already been seen, return string `'[Circular]'`
- * - is `undefined`, return string `'[undefined]'`
- * - is `null`, return value `null`
- * - is some other primitive, return the value
- * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
- * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
- * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
- *
- * @param {*} value Thing to inspect. May or may not have properties.
- * @param {Array} [stack=[]] Stack of seen values
- * @return {(Object|Array|Function|string|undefined)}
- * @see {@link exports.stringify}
- * @api private
- */
-
-exports.canonicalize = function(value, stack) {
- var canonicalizedObj,
- type = exports.type(value),
- prop,
- withStack = function withStack(value, fn) {
- stack.push(value);
- fn();
- stack.pop();
- };
-
- stack = stack || [];
-
- if (exports.indexOf(stack, value) !== -1) {
- return '[Circular]';
- }
-
- switch(type) {
- case 'undefined':
- case 'buffer':
- case 'null':
- canonicalizedObj = value;
- break;
- case 'array':
- withStack(value, function () {
- canonicalizedObj = exports.map(value, function (item) {
- return exports.canonicalize(item, stack);
- });
- });
- break;
- case 'function':
- for (prop in value) {
- canonicalizedObj = {};
- break;
- }
- if (!canonicalizedObj) {
- canonicalizedObj = emptyRepresentation(value, type);
- break;
- }
- /* falls through */
- case 'object':
- canonicalizedObj = canonicalizedObj || {};
- withStack(value, function () {
- exports.forEach(exports.keys(value).sort(), function (key) {
- canonicalizedObj[key] = exports.canonicalize(value[key], stack);
- });
- });
- break;
- case 'date':
- case 'number':
- case 'regexp':
- case 'boolean':
- canonicalizedObj = value;
- break;
- default:
- canonicalizedObj = value.toString();
- }
-
- return canonicalizedObj;
-};
-
-/**
- * Lookup file names at the given `path`.
- */
-exports.lookupFiles = function lookupFiles(path, extensions, recursive) {
- var files = [];
- var re = new RegExp('\\.(' + extensions.join('|') + ')$');
-
- if (!exists(path)) {
- if (exists(path + '.js')) {
- path += '.js';
- } else {
- files = glob.sync(path);
- if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'");
- return files;
- }
- }
-
- try {
- var stat = fs.statSync(path);
- if (stat.isFile()) return path;
- }
- catch (ignored) {
- return undefined;
- }
-
- fs.readdirSync(path).forEach(function(file) {
- file = join(path, file);
- try {
- var stat = fs.statSync(file);
- if (stat.isDirectory()) {
- if (recursive) {
- files = files.concat(lookupFiles(file, extensions, recursive));
- }
- return;
- }
- }
- catch (ignored) {
- return;
- }
- if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return;
- files.push(file);
- });
-
- return files;
-};
-
-/**
- * Generate an undefined error with a message warning the user.
- *
- * @return {Error}
- */
-
-exports.undefinedError = function() {
- return new Error('Caught undefined error, did you throw without specifying what?');
-};
-
-/**
- * Generate an undefined error if `err` is not defined.
- *
- * @param {Error} err
- * @return {Error}
- */
-
-exports.getError = function(err) {
- return err || exports.undefinedError();
-};
-
-
-/**
- * @summary
- * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
- * @description
- * When invoking this function you get a filter function that get the Error.stack as an input,
- * and return a prettify output.
- * (i.e: strip Mocha, node_modules, bower and componentJS from stack trace).
- * @returns {Function}
- */
-
-exports.stackTraceFilter = function() {
- var slash = '/'
- , is = typeof document === 'undefined'
- ? { node: true }
- : { browser: true }
- , cwd = is.node
- ? process.cwd() + slash
- : location.href.replace(/\/[^\/]*$/, '/');
-
- function isNodeModule (line) {
- return (~line.indexOf('node_modules'));
- }
-
- function isMochaInternal (line) {
- return (~line.indexOf('node_modules' + slash + 'mocha')) ||
- (~line.indexOf('components' + slash + 'mochajs')) ||
- (~line.indexOf('components' + slash + 'mocha'));
- }
-
- // node_modules, bower, componentJS
- function isBrowserModule(line) {
- return (~line.indexOf('node_modules')) ||
- (~line.indexOf('components'));
- }
-
- function isNodeInternal (line) {
- return (~line.indexOf('(timers.js:')) ||
- (~line.indexOf('(events.js:')) ||
- (~line.indexOf('(node.js:')) ||
- (~line.indexOf('(module.js:')) ||
- (~line.indexOf('GeneratorFunctionPrototype.next (native)')) ||
- false
- }
-
- return function(stack) {
- stack = stack.split('\n');
-
- stack = exports.reduce(stack, function(list, line) {
- if (is.node && (isNodeModule(line) ||
- isMochaInternal(line) ||
- isNodeInternal(line)))
- return list;
-
- if (is.browser && (isBrowserModule(line)))
- return list;
-
- // Clean up cwd(absolute)
- list.push(line.replace(cwd, ''));
- return list;
- }, []);
-
- return stack.join('\n');
- }
-};
-}); // module: utils.js
-// The global object is "self" in Web Workers.
-var global = (function() { return this; })();
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date;
-var setTimeout = global.setTimeout;
-var setInterval = global.setInterval;
-var clearTimeout = global.clearTimeout;
-var clearInterval = global.clearInterval;
-
-/**
- * Node shims.
- *
- * These are meant only to allow
- * mocha.js to run untouched, not
- * to allow running node code in
- * the browser.
- */
-
-var process = {};
-process.exit = function(status){};
-process.stdout = {};
-
-var uncaughtExceptionHandlers = [];
-
-var originalOnerrorHandler = global.onerror;
-
-/**
- * Remove uncaughtException listener.
- * Revert to original onerror handler if previously defined.
- */
-
-process.removeListener = function(e, fn){
- if ('uncaughtException' == e) {
- if (originalOnerrorHandler) {
- global.onerror = originalOnerrorHandler;
- } else {
- global.onerror = function() {};
- }
- var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn);
- if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); }
- }
-};
-
-/**
- * Implements uncaughtException listener.
- */
-
-process.on = function(e, fn){
- if ('uncaughtException' == e) {
- global.onerror = function(err, url, line){
- fn(new Error(err + ' (' + url + ':' + line + ')'));
- return true;
- };
- uncaughtExceptionHandlers.push(fn);
- }
-};
-
-/**
- * Expose mocha.
- */
-
-var Mocha = global.Mocha = require('mocha'),
- mocha = global.mocha = new Mocha({ reporter: 'html' });
-
-// The BDD UI is registered by default, but no UI will be functional in the
-// browser without an explicit call to the overridden `mocha.ui` (see below).
-// Ensure that this default UI does not expose its methods to the global scope.
-mocha.suite.removeAllListeners('pre-require');
-
-var immediateQueue = []
- , immediateTimeout;
-
-function timeslice() {
- var immediateStart = new Date().getTime();
- while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
- immediateQueue.shift()();
- }
- if (immediateQueue.length) {
- immediateTimeout = setTimeout(timeslice, 0);
- } else {
- immediateTimeout = null;
- }
-}
-
-/**
- * High-performance override of Runner.immediately.
- */
-
-Mocha.Runner.immediately = function(callback) {
- immediateQueue.push(callback);
- if (!immediateTimeout) {
- immediateTimeout = setTimeout(timeslice, 0);
- }
-};
-
-/**
- * Function to allow assertion libraries to throw errors directly into mocha.
- * This is useful when running tests in a browser because window.onerror will
- * only receive the 'message' attribute of the Error.
- */
-mocha.throwError = function(err) {
- Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) {
- fn(err);
- });
- throw err;
-};
-
-/**
- * Override ui to ensure that the ui functions are initialized.
- * Normally this would happen in Mocha.prototype.loadFiles.
- */
-
-mocha.ui = function(ui){
- Mocha.prototype.ui.call(this, ui);
- this.suite.emit('pre-require', global, null, this);
- return this;
-};
-
-/**
- * Setup mocha with the given setting options.
- */
-
-mocha.setup = function(opts){
- if ('string' == typeof opts) opts = { ui: opts };
- for (var opt in opts) this[opt](opts[opt]);
- return this;
-};
-
-/**
- * Run mocha, returning the Runner.
- */
-
-mocha.run = function(fn){
- var options = mocha.options;
- mocha.globals('location');
-
- var query = Mocha.utils.parseQuery(global.location.search || '');
- if (query.grep) mocha.grep(new RegExp(query.grep));
- if (query.fgrep) mocha.grep(query.fgrep);
- if (query.invert) mocha.invert();
-
- return Mocha.prototype.run.call(mocha, function(err){
- // The DOM Document is not available in Web Workers.
- var document = global.document;
- if (document && document.getElementById('mocha') && options.noHighlighting !== true) {
- Mocha.utils.highlightTags('code');
- }
- if (fn) fn(err);
- });
-};
-
-/**
- * Expose the process shim.
- */
-
-Mocha.process = process;
-})();
diff --git a/toolkit/components/microformats/test/static/javascript/parse.js b/toolkit/components/microformats/test/static/javascript/parse.js
deleted file mode 100644
index 588e403ee..000000000
--- a/toolkit/components/microformats/test/static/javascript/parse.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/*!
- parse
- Used by http://localhost:3000/
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-window.onload = function() {
-
- var form;
- form= document.getElementById('mf-form');
-
- form.onsubmit = function(e){
- e = (e)? e : window.event;
-
- if (e.preventDefault) {
- e.preventDefault();
- } else {
- event.returnValue = false;
- }
-
-
- var html,
- baseUrl,
- filter,
- collapsewhitespace,
- overlappingversions,
- impliedPropertiesByVersion,
- dateformatElt,
- dateformat,
- doc,
- node,
- options,
- mfJSON,
- parserJSONElt;
-
- // get data from html
- html = document.getElementById('html').value;
- baseUrl = document.getElementById('baseurl').value;
- filters = document.getElementById('filters').value;
- collapsewhitespace = document.getElementById('collapsewhitespace').checked;
- //overlappingversions = document.getElementById('overlappingversions').checked;
- //impliedPropertiesByVersion = document.getElementById('impliedPropertiesByVersion').checked;
- parseLatLonGeo = document.getElementById('parseLatLonGeo').checked;
- dateformatElt = document.getElementById("dateformat");
- dateformat = dateformatElt.options[dateformatElt.selectedIndex].value;
- parserJSONElt = document.querySelector('#parser-json pre code')
-
-
- var dom = new DOMParser();
- doc = dom.parseFromString( html, 'text/html' );
-
- options ={
- 'document': doc,
- 'node': doc,
- 'dateFormat': dateformat,
- 'parseLatLonGeo': false
- };
-
- if(baseUrl.trim() !== ''){
- options.baseUrl = baseUrl;
- }
-
- if(filters.trim() !== ''){
- if(filters.indexOf(',') > -1){
- options.filters = trimArrayItems(filters.split(','));
- }else{
- options.filters = [filters.trim()];
- }
- }
-
- if(collapsewhitespace === true){
- options.textFormat = 'normalised';
- }
-
- /*
- if(overlappingversions === true){
- options.overlappingVersions = false;
- }
-
- if(impliedPropertiesByVersion === true){
- options.impliedPropertiesByVersion = true;
- }
- */
-
- if(parseLatLonGeo === true){
- options.parseLatLonGeo = true
- }
-
- if(options.baseUrl){
- html = '<base href="' + baseUrl+ '">' + html;
- }
-
-
-
- // parse direct into Modules to help debugging
- if(window.Modules){
- var parser = new Modules.Parser();
- mfJSON = parser.get(options);
- }else if(window.Microformats){
- mfJSON = Microformats.get(options);
- }
-
-
- // format output
- parserJSONElt.innerHTML = htmlEscape( js_beautify( JSON.stringify(mfJSON) ) );
- //prettyPrint();
-
- }
-
-
-};
-
-
-
-
-
-function htmlEscape(str) {
- return String(str)
- .replace(/&/g, '&amp;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#39;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
-}
-
-
-function trimArrayItems( arr ){
- return arr.map(function(item){
- return item.trim();
- })
-}
-
diff --git a/toolkit/components/microformats/test/static/javascript/prettify.js b/toolkit/components/microformats/test/static/javascript/prettify.js
deleted file mode 100644
index 879dfd60f..000000000
--- a/toolkit/components/microformats/test/static/javascript/prettify.js
+++ /dev/null
@@ -1,1479 +0,0 @@
-// Copyright (C) 2006 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-
-/**
- * @fileoverview
- * some functions for browser-side pretty printing of code contained in html.
- *
- * <p>
- * For a fairly comprehensive set of languages see the
- * <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
- * file that came with this source. At a minimum, the lexer should work on a
- * number of languages including C and friends, Java, Python, Bash, SQL, HTML,
- * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
- * and a subset of Perl, but, because of commenting conventions, doesn't work on
- * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
- * <p>
- * Usage: <ol>
- * <li> include this source file in an html page via
- * {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
- * <li> define style rules. See the example page for examples.
- * <li> mark the {@code <pre>} and {@code <code>} tags in your source with
- * {@code class=prettyprint.}
- * You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
- * printer needs to do more substantial DOM manipulations to support that, so
- * some css styles may not be preserved.
- * </ol>
- * That's it. I wanted to keep the API as simple as possible, so there's no
- * need to specify which language the code is in, but if you wish, you can add
- * another class to the {@code <pre>} or {@code <code>} element to specify the
- * language, as in {@code <pre class="prettyprint lang-java">}. Any class that
- * starts with "lang-" followed by a file extension, specifies the file type.
- * See the "lang-*.js" files in this directory for code that implements
- * per-language file handlers.
- * <p>
- * Change log:<br>
- * cbeust, 2006/08/22
- * <blockquote>
- * Java annotations (start with "@") are now captured as literals ("lit")
- * </blockquote>
- * @requires console
- */
-
-// JSLint declarations
-/*global console, document, navigator, setTimeout, window */
-
-/**
- * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
- * UI events.
- * If set to {@code false}, {@code prettyPrint()} is synchronous.
- */
-window['PR_SHOULD_USE_CONTINUATION'] = true;
-
-(function () {
- // Keyword lists for various languages.
- // We use things that coerce to strings to make them compact when minified
- // and to defeat aggressive optimizers that fold large string constants.
- var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
- var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
- "double,enum,extern,float,goto,int,long,register,short,signed,sizeof," +
- "static,struct,switch,typedef,union,unsigned,void,volatile"];
- var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
- "new,operator,private,protected,public,this,throw,true,try,typeof"];
- var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
- "concept,concept_map,const_cast,constexpr,decltype," +
- "dynamic_cast,explicit,export,friend,inline,late_check," +
- "mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast," +
- "template,typeid,typename,using,virtual,where"];
- var JAVA_KEYWORDS = [COMMON_KEYWORDS,
- "abstract,boolean,byte,extends,final,finally,implements,import," +
- "instanceof,null,native,package,strictfp,super,synchronized,throws," +
- "transient"];
- var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
- "as,base,by,checked,decimal,delegate,descending,dynamic,event," +
- "fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock," +
- "object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed," +
- "stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];
- var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
- "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
- "true,try,unless,until,when,while,yes";
- var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
- "debugger,eval,export,function,get,null,set,undefined,var,with," +
- "Infinity,NaN"];
- var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
- "goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
- "sub,undef,unless,until,use,wantarray,while,BEGIN,END";
- var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
- "elif,except,exec,finally,from,global,import,in,is,lambda," +
- "nonlocal,not,or,pass,print,raise,try,with,yield," +
- "False,True,None"];
- var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
- "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
- "rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
- "BEGIN,END"];
- var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
- "function,in,local,set,then,until"];
- var ALL_KEYWORDS = [
- CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS +
- PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
- var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;
-
- // token style names. correspond to css classes
- /**
- * token style for a string literal
- * @const
- */
- var PR_STRING = 'str';
- /**
- * token style for a keyword
- * @const
- */
- var PR_KEYWORD = 'kwd';
- /**
- * token style for a comment
- * @const
- */
- var PR_COMMENT = 'com';
- /**
- * token style for a type
- * @const
- */
- var PR_TYPE = 'typ';
- /**
- * token style for a literal value. e.g. 1, null, true.
- * @const
- */
- var PR_LITERAL = 'lit';
- /**
- * token style for a punctuation string.
- * @const
- */
- var PR_PUNCTUATION = 'pun';
- /**
- * token style for a punctuation string.
- * @const
- */
- var PR_PLAIN = 'pln';
-
- /**
- * token style for an sgml tag.
- * @const
- */
- var PR_TAG = 'tag';
- /**
- * token style for a markup declaration such as a DOCTYPE.
- * @const
- */
- var PR_DECLARATION = 'dec';
- /**
- * token style for embedded source.
- * @const
- */
- var PR_SOURCE = 'src';
- /**
- * token style for an sgml attribute name.
- * @const
- */
- var PR_ATTRIB_NAME = 'atn';
- /**
- * token style for an sgml attribute value.
- * @const
- */
- var PR_ATTRIB_VALUE = 'atv';
-
- /**
- * A class that indicates a section of markup that is not code, e.g. to allow
- * embedding of line numbers within code listings.
- * @const
- */
- var PR_NOCODE = 'nocode';
-
-
-
-/**
- * A set of tokens that can precede a regular expression literal in
- * javascript
- * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
- * has the full list, but I've removed ones that might be problematic when
- * seen in languages that don't support regular expression literals.
- *
- * <p>Specifically, I've removed any keywords that can't precede a regexp
- * literal in a syntactically legal javascript program, and I've removed the
- * "in" keyword since it's not a keyword in many languages, and might be used
- * as a count of inches.
- *
- * <p>The link a above does not accurately describe EcmaScript rules since
- * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
- * very well in practice.
- *
- * @private
- * @const
- */
-var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
-
-// CAVEAT: this does not properly handle the case where a regular
-// expression immediately follows another since a regular expression may
-// have flags for case-sensitivity and the like. Having regexp tokens
-// adjacent is not valid in any language I'm aware of, so I'm punting.
-// TODO: maybe style special characters inside a regexp as punctuation.
-
-
- /**
- * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
- * matches the union of the sets of strings matched by the input RegExp.
- * Since it matches globally, if the input strings have a start-of-input
- * anchor (/^.../), it is ignored for the purposes of unioning.
- * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
- * @return {RegExp} a global regex.
- */
- function combinePrefixPatterns(regexs) {
- var capturedGroupIndex = 0;
-
- var needToFoldCase = false;
- var ignoreCase = false;
- for (var i = 0, n = regexs.length; i < n; ++i) {
- var regex = regexs[i];
- if (regex.ignoreCase) {
- ignoreCase = true;
- } else if (/[a-z]/i.test(regex.source.replace(
- /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
- needToFoldCase = true;
- ignoreCase = false;
- break;
- }
- }
-
- var escapeCharToCodeUnit = {
- 'b': 8,
- 't': 9,
- 'n': 0xa,
- 'v': 0xb,
- 'f': 0xc,
- 'r': 0xd
- };
-
- function decodeEscape(charsetPart) {
- var cc0 = charsetPart.charCodeAt(0);
- if (cc0 !== 92 /* \\ */) {
- return cc0;
- }
- var c1 = charsetPart.charAt(1);
- cc0 = escapeCharToCodeUnit[c1];
- if (cc0) {
- return cc0;
- } else if ('0' <= c1 && c1 <= '7') {
- return parseInt(charsetPart.substring(1), 8);
- } else if (c1 === 'u' || c1 === 'x') {
- return parseInt(charsetPart.substring(2), 16);
- } else {
- return charsetPart.charCodeAt(1);
- }
- }
-
- function encodeEscape(charCode) {
- if (charCode < 0x20) {
- return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
- }
- var ch = String.fromCharCode(charCode);
- if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') {
- ch = '\\' + ch;
- }
- return ch;
- }
-
- function caseFoldCharset(charSet) {
- var charsetParts = charSet.substring(1, charSet.length - 1).match(
- new RegExp(
- '\\\\u[0-9A-Fa-f]{4}'
- + '|\\\\x[0-9A-Fa-f]{2}'
- + '|\\\\[0-3][0-7]{0,2}'
- + '|\\\\[0-7]{1,2}'
- + '|\\\\[\\s\\S]'
- + '|-'
- + '|[^-\\\\]',
- 'g'));
- var groups = [];
- var ranges = [];
- var inverse = charsetParts[0] === '^';
- for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
- var p = charsetParts[i];
- if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups.
- groups.push(p);
- } else {
- var start = decodeEscape(p);
- var end;
- if (i + 2 < n && '-' === charsetParts[i + 1]) {
- end = decodeEscape(charsetParts[i + 2]);
- i += 2;
- } else {
- end = start;
- }
- ranges.push([start, end]);
- // If the range might intersect letters, then expand it.
- // This case handling is too simplistic.
- // It does not deal with non-latin case folding.
- // It works for latin source code identifiers though.
- if (!(end < 65 || start > 122)) {
- if (!(end < 65 || start > 90)) {
- ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
- }
- if (!(end < 97 || start > 122)) {
- ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
- }
- }
- }
- }
-
- // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
- // -> [[1, 12], [14, 14], [16, 17]]
- ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
- var consolidatedRanges = [];
- var lastRange = [NaN, NaN];
- for (i = 0; i < ranges.length; ++i) {
- var range = ranges[i];
- if (range[0] <= lastRange[1] + 1) {
- lastRange[1] = Math.max(lastRange[1], range[1]);
- } else {
- consolidatedRanges.push(lastRange = range);
- }
- }
-
- var out = ['['];
- if (inverse) { out.push('^'); }
- out.push.apply(out, groups);
- for (i = 0; i < consolidatedRanges.length; ++i) {
- range = consolidatedRanges[i];
- out.push(encodeEscape(range[0]));
- if (range[1] > range[0]) {
- if (range[1] + 1 > range[0]) { out.push('-'); }
- out.push(encodeEscape(range[1]));
- }
- }
- out.push(']');
- return out.join('');
- }
-
- function allowAnywhereFoldCaseAndRenumberGroups(regex) {
- // Split into character sets, escape sequences, punctuation strings
- // like ('(', '(?:', ')', '^'), and runs of characters that do not
- // include any of the above.
- var parts = regex.source.match(
- new RegExp(
- '(?:'
- + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
- + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
- + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
- + '|\\\\[0-9]+' // a back-reference or octal escape
- + '|\\\\[^ux0-9]' // other escape sequence
- + '|\\(\\?[:!=]' // start of a non-capturing group
- + '|[\\(\\)\\^]' // start/emd of a group, or line start
- + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
- + ')',
- 'g'));
- var n = parts.length;
-
- // Maps captured group numbers to the number they will occupy in
- // the output or to -1 if that has not been determined, or to
- // undefined if they need not be capturing in the output.
- var capturedGroups = [];
-
- // Walk over and identify back references to build the capturedGroups
- // mapping.
- for (var i = 0, groupIndex = 0; i < n; ++i) {
- var p = parts[i];
- if (p === '(') {
- // groups are 1-indexed, so max group index is count of '('
- ++groupIndex;
- } else if ('\\' === p.charAt(0)) {
- var decimalValue = +p.substring(1);
- if (decimalValue && decimalValue <= groupIndex) {
- capturedGroups[decimalValue] = -1;
- }
- }
- }
-
- // Renumber groups and reduce capturing groups to non-capturing groups
- // where possible.
- for (i = 1; i < capturedGroups.length; ++i) {
- if (-1 === capturedGroups[i]) {
- capturedGroups[i] = ++capturedGroupIndex;
- }
- }
- for (i = 0, groupIndex = 0; i < n; ++i) {
- p = parts[i];
- if (p === '(') {
- ++groupIndex;
- if (capturedGroups[groupIndex] === undefined) {
- parts[i] = '(?:';
- }
- } else if ('\\' === p.charAt(0)) {
- decimalValue = +p.substring(1);
- if (decimalValue && decimalValue <= groupIndex) {
- parts[i] = '\\' + capturedGroups[groupIndex];
- }
- }
- }
-
- // Remove any prefix anchors so that the output will match anywhere.
- // ^^ really does mean an anchored match though.
- for (i = 0, groupIndex = 0; i < n; ++i) {
- if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
- }
-
- // Expand letters to groups to handle mixing of case-sensitive and
- // case-insensitive patterns if necessary.
- if (regex.ignoreCase && needToFoldCase) {
- for (i = 0; i < n; ++i) {
- p = parts[i];
- var ch0 = p.charAt(0);
- if (p.length >= 2 && ch0 === '[') {
- parts[i] = caseFoldCharset(p);
- } else if (ch0 !== '\\') {
- // TODO: handle letters in numeric escapes.
- parts[i] = p.replace(
- /[a-zA-Z]/g,
- function (ch) {
- var cc = ch.charCodeAt(0);
- return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
- });
- }
- }
- }
-
- return parts.join('');
- }
-
- var rewritten = [];
- for (i = 0, n = regexs.length; i < n; ++i) {
- regex = regexs[i];
- if (regex.global || regex.multiline) { throw new Error('' + regex); }
- rewritten.push(
- '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
- }
-
- return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
- }
-
-
- /**
- * Split markup into a string of source code and an array mapping ranges in
- * that string to the text nodes in which they appear.
- *
- * <p>
- * The HTML DOM structure:</p>
- * <pre>
- * (Element "p"
- * (Element "b"
- * (Text "print ")) ; #1
- * (Text "'Hello '") ; #2
- * (Element "br") ; #3
- * (Text " + 'World';")) ; #4
- * </pre>
- * <p>
- * corresponds to the HTML
- * {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p>
- *
- * <p>
- * It will produce the output:</p>
- * <pre>
- * {
- * sourceCode: "print 'Hello '\n + 'World';",
- * // 1 2
- * // 012345678901234 5678901234567
- * spans: [0, #1, 6, #2, 14, #3, 15, #4]
- * }
- * </pre>
- * <p>
- * where #1 is a reference to the {@code "print "} text node above, and so
- * on for the other text nodes.
- * </p>
- *
- * <p>
- * The {@code} spans array is an array of pairs. Even elements are the start
- * indices of substrings, and odd elements are the text nodes (or BR elements)
- * that contain the text for those substrings.
- * Substrings continue until the next index or the end of the source.
- * </p>
- *
- * @param {Node} node an HTML DOM subtree containing source-code.
- * @return {Object} source code and the text nodes in which they occur.
- */
- function extractSourceSpans(node) {
- var nocode = /(?:^|\s)nocode(?:\s|$)/;
-
- var chunks = [];
- var length = 0;
- var spans = [];
- var k = 0;
-
- var whitespace;
- if (node.currentStyle) {
- whitespace = node.currentStyle.whiteSpace;
- } else if (window.getComputedStyle) {
- whitespace = document.defaultView.getComputedStyle(node, null)
- .getPropertyValue('white-space');
- }
- var isPreformatted = whitespace && 'pre' === whitespace.substring(0, 3);
-
- function walk(node) {
- switch (node.nodeType) {
- case 1: // Element
- if (nocode.test(node.className)) { return; }
- for (var child = node.firstChild; child; child = child.nextSibling) {
- walk(child);
- }
- var nodeName = node.nodeName;
- if ('BR' === nodeName || 'LI' === nodeName) {
- chunks[k] = '\n';
- spans[k << 1] = length++;
- spans[(k++ << 1) | 1] = node;
- }
- break;
- case 3: case 4: // Text
- var text = node.nodeValue;
- if (text.length) {
- if (!isPreformatted) {
- text = text.replace(/[ \t\r\n]+/g, ' ');
- } else {
- text = text.replace(/\r\n?/g, '\n'); // Normalize newlines.
- }
- // TODO: handle tabs here?
- chunks[k] = text;
- spans[k << 1] = length;
- length += text.length;
- spans[(k++ << 1) | 1] = node;
- }
- break;
- }
- }
-
- walk(node);
-
- return {
- sourceCode: chunks.join('').replace(/\n$/, ''),
- spans: spans
- };
- }
-
-
- /**
- * Apply the given language handler to sourceCode and add the resulting
- * decorations to out.
- * @param {number} basePos the index of sourceCode within the chunk of source
- * whose decorations are already present on out.
- */
- function appendDecorations(basePos, sourceCode, langHandler, out) {
- if (!sourceCode) { return; }
- var job = {
- sourceCode: sourceCode,
- basePos: basePos
- };
- langHandler(job);
- out.push.apply(out, job.decorations);
- }
-
- var notWs = /\S/;
-
- /**
- * Given an element, if it contains only one child element and any text nodes
- * it contains contain only space characters, return the sole child element.
- * Otherwise returns undefined.
- * <p>
- * This is meant to return the CODE element in {@code <pre><code ...>} when
- * there is a single child element that contains all the non-space textual
- * content, but not to return anything where there are multiple child elements
- * as in {@code <pre><code>...</code><code>...</code></pre>} or when there
- * is textual content.
- */
- function childContentWrapper(element) {
- var wrapper = undefined;
- for (var c = element.firstChild; c; c = c.nextSibling) {
- var type = c.nodeType;
- if (type === 1) {
- wrapper = wrapper ? element : c;
- } else if (type === 3) {
- wrapper = notWs.test(c.nodeValue) ? element : wrapper;
- }
- }
- return wrapper === element ? undefined : wrapper;
- }
-
- /** Given triples of [style, pattern, context] returns a lexing function,
- * The lexing function interprets the patterns to find token boundaries and
- * returns a decoration list of the form
- * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
- * where index_n is an index into the sourceCode, and style_n is a style
- * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
- * all characters in sourceCode[index_n-1:index_n].
- *
- * The stylePatterns is a list whose elements have the form
- * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
- *
- * Style is a style constant like PR_PLAIN, or can be a string of the
- * form 'lang-FOO', where FOO is a language extension describing the
- * language of the portion of the token in $1 after pattern executes.
- * E.g., if style is 'lang-lisp', and group 1 contains the text
- * '(hello (world))', then that portion of the token will be passed to the
- * registered lisp handler for formatting.
- * The text before and after group 1 will be restyled using this decorator
- * so decorators should take care that this doesn't result in infinite
- * recursion. For example, the HTML lexer rule for SCRIPT elements looks
- * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
- * '<script>foo()<\/script>', which would cause the current decorator to
- * be called with '<script>' which would not match the same rule since
- * group 1 must not be empty, so it would be instead styled as PR_TAG by
- * the generic tag rule. The handler registered for the 'js' extension would
- * then be called with 'foo()', and finally, the current decorator would
- * be called with '<\/script>' which would not match the original rule and
- * so the generic tag rule would identify it as a tag.
- *
- * Pattern must only match prefixes, and if it matches a prefix, then that
- * match is considered a token with the same style.
- *
- * Context is applied to the last non-whitespace, non-comment token
- * recognized.
- *
- * Shortcut is an optional string of characters, any of which, if the first
- * character, gurantee that this pattern and only this pattern matches.
- *
- * @param {Array} shortcutStylePatterns patterns that always start with
- * a known character. Must have a shortcut string.
- * @param {Array} fallthroughStylePatterns patterns that will be tried in
- * order if the shortcut ones fail. May have shortcuts.
- *
- * @return {function (Object)} a
- * function that takes source code and returns a list of decorations.
- */
- function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
- var shortcuts = {};
- var tokenizer;
- (function () {
- var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
- var allRegexs = [];
- var regexKeys = {};
- for (var i = 0, n = allPatterns.length; i < n; ++i) {
- var patternParts = allPatterns[i];
- var shortcutChars = patternParts[3];
- if (shortcutChars) {
- for (var c = shortcutChars.length; --c >= 0;) {
- shortcuts[shortcutChars.charAt(c)] = patternParts;
- }
- }
- var regex = patternParts[1];
- var k = '' + regex;
- if (!regexKeys.hasOwnProperty(k)) {
- allRegexs.push(regex);
- regexKeys[k] = null;
- }
- }
- allRegexs.push(/[\0-\uffff]/);
- tokenizer = combinePrefixPatterns(allRegexs);
- })();
-
- var nPatterns = fallthroughStylePatterns.length;
-
- /**
- * Lexes job.sourceCode and produces an output array job.decorations of
- * style classes preceded by the position at which they start in
- * job.sourceCode in order.
- *
- * @param {Object} job an object like <pre>{
- * sourceCode: {string} sourceText plain text,
- * basePos: {int} position of job.sourceCode in the larger chunk of
- * sourceCode.
- * }</pre>
- */
- var decorate = function (job) {
- var sourceCode = job.sourceCode, basePos = job.basePos;
- /** Even entries are positions in source in ascending order. Odd enties
- * are style markers (e.g., PR_COMMENT) that run from that position until
- * the end.
- * @type {Array.<number|string>}
- */
- var decorations = [basePos, PR_PLAIN];
- var pos = 0; // index into sourceCode
- var tokens = sourceCode.match(tokenizer) || [];
- var styleCache = {};
-
- for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
- var token = tokens[ti];
- var style = styleCache[token];
- var match = void 0;
-
- var isEmbedded;
- if (typeof style === 'string') {
- isEmbedded = false;
- } else {
- var patternParts = shortcuts[token.charAt(0)];
- if (patternParts) {
- match = token.match(patternParts[1]);
- style = patternParts[0];
- } else {
- for (var i = 0; i < nPatterns; ++i) {
- patternParts = fallthroughStylePatterns[i];
- match = token.match(patternParts[1]);
- if (match) {
- style = patternParts[0];
- break;
- }
- }
-
- if (!match) { // make sure that we make progress
- style = PR_PLAIN;
- }
- }
-
- isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
- if (isEmbedded && !(match && typeof match[1] === 'string')) {
- isEmbedded = false;
- style = PR_SOURCE;
- }
-
- if (!isEmbedded) { styleCache[token] = style; }
- }
-
- var tokenStart = pos;
- pos += token.length;
-
- if (!isEmbedded) {
- decorations.push(basePos + tokenStart, style);
- } else { // Treat group 1 as an embedded block of source code.
- var embeddedSource = match[1];
- var embeddedSourceStart = token.indexOf(embeddedSource);
- var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
- if (match[2]) {
- // If embeddedSource can be blank, then it would match at the
- // beginning which would cause us to infinitely recurse on the
- // entire token, so we catch the right context in match[2].
- embeddedSourceEnd = token.length - match[2].length;
- embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
- }
- var lang = style.substring(5);
- // Decorate the left of the embedded source
- appendDecorations(
- basePos + tokenStart,
- token.substring(0, embeddedSourceStart),
- decorate, decorations);
- // Decorate the embedded source
- appendDecorations(
- basePos + tokenStart + embeddedSourceStart,
- embeddedSource,
- langHandlerForExtension(lang, embeddedSource),
- decorations);
- // Decorate the right of the embedded section
- appendDecorations(
- basePos + tokenStart + embeddedSourceEnd,
- token.substring(embeddedSourceEnd),
- decorate, decorations);
- }
- }
- job.decorations = decorations;
- };
- return decorate;
- }
-
- /** returns a function that produces a list of decorations from source text.
- *
- * This code treats ", ', and ` as string delimiters, and \ as a string
- * escape. It does not recognize perl's qq() style strings.
- * It has no special handling for double delimiter escapes as in basic, or
- * the tripled delimiters used in python, but should work on those regardless
- * although in those cases a single string literal may be broken up into
- * multiple adjacent string literals.
- *
- * It recognizes C, C++, and shell style comments.
- *
- * @param {Object} options a set of optional parameters.
- * @return {function (Object)} a function that examines the source code
- * in the input job and builds the decoration list.
- */
- function sourceDecorator(options) {
- var shortcutStylePatterns = [], fallthroughStylePatterns = [];
- if (options['tripleQuotedStrings']) {
- // '''multi-line-string''', 'single-line-string', and double-quoted
- shortcutStylePatterns.push(
- [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
- null, '\'"']);
- } else if (options['multiLineStrings']) {
- // 'multi-line-string', "multi-line-string"
- shortcutStylePatterns.push(
- [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
- null, '\'"`']);
- } else {
- // 'single-line-string', "single-line-string"
- shortcutStylePatterns.push(
- [PR_STRING,
- /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
- null, '"\'']);
- }
- if (options['verbatimStrings']) {
- // verbatim-string-literal production from the C# grammar. See issue 93.
- fallthroughStylePatterns.push(
- [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
- }
- var hc = options['hashComments'];
- if (hc) {
- if (options['cStyleComments']) {
- if (hc > 1) { // multiline hash comments
- shortcutStylePatterns.push(
- [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
- } else {
- // Stop C preprocessor declarations at an unclosed open comment
- shortcutStylePatterns.push(
- [PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
- null, '#']);
- }
- fallthroughStylePatterns.push(
- [PR_STRING,
- /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,
- null]);
- } else {
- shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
- }
- }
- if (options['cStyleComments']) {
- fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
- fallthroughStylePatterns.push(
- [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
- }
- if (options['regexLiterals']) {
- /**
- * @const
- */
- var REGEX_LITERAL = (
- // A regular expression literal starts with a slash that is
- // not followed by * or / so that it is not confused with
- // comments.
- '/(?=[^/*])'
- // and then contains any number of raw characters,
- + '(?:[^/\\x5B\\x5C]'
- // escape sequences (\x5C),
- + '|\\x5C[\\s\\S]'
- // or non-nesting character sets (\x5B\x5D);
- + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
- // finally closed by a /.
- + '/');
- fallthroughStylePatterns.push(
- ['lang-regex',
- new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
- ]);
- }
-
- var types = options['types'];
- if (types) {
- fallthroughStylePatterns.push([PR_TYPE, types]);
- }
-
- var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
- if (keywords.length) {
- fallthroughStylePatterns.push(
- [PR_KEYWORD,
- new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
- null]);
- }
-
- shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
- fallthroughStylePatterns.push(
- // TODO(mikesamuel): recognize non-latin letters and numerals in idents
- [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
- [PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
- [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
- [PR_LITERAL,
- new RegExp(
- '^(?:'
- // A hex number
- + '0x[a-f0-9]+'
- // or an octal or decimal number,
- + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
- // possibly in scientific notation
- + '(?:e[+\\-]?\\d+)?'
- + ')'
- // with an optional modifier like UL for unsigned long
- + '[a-z]*', 'i'),
- null, '0123456789'],
- // Don't treat escaped quotes in bash as starting strings. See issue 144.
- [PR_PLAIN, /^\\[\s\S]?/, null],
- [PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#\\]*/, null]);
-
- return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
- }
-
- var decorateSource = sourceDecorator({
- 'keywords': ALL_KEYWORDS,
- 'hashComments': true,
- 'cStyleComments': true,
- 'multiLineStrings': true,
- 'regexLiterals': true
- });
-
- /**
- * Given a DOM subtree, wraps it in a list, and puts each line into its own
- * list item.
- *
- * @param {Node} node modified in place. Its content is pulled into an
- * HTMLOListElement, and each line is moved into a separate list item.
- * This requires cloning elements, so the input might not have unique
- * IDs after numbering.
- */
- function numberLines(node, opt_startLineNum) {
- var nocode = /(?:^|\s)nocode(?:\s|$)/;
- var lineBreak = /\r\n?|\n/;
-
- var document = node.ownerDocument;
-
- var whitespace;
- if (node.currentStyle) {
- whitespace = node.currentStyle.whiteSpace;
- } else if (window.getComputedStyle) {
- whitespace = document.defaultView.getComputedStyle(node, null)
- .getPropertyValue('white-space');
- }
- // If it's preformatted, then we need to split lines on line breaks
- // in addition to <BR>s.
- var isPreformatted = whitespace && 'pre' === whitespace.substring(0, 3);
-
- var li = document.createElement('LI');
- while (node.firstChild) {
- li.appendChild(node.firstChild);
- }
- // An array of lines. We split below, so this is initialized to one
- // un-split line.
- var listItems = [li];
-
- function walk(node) {
- switch (node.nodeType) {
- case 1: // Element
- if (nocode.test(node.className)) { break; }
- if ('BR' === node.nodeName) {
- breakAfter(node);
- // Discard the <BR> since it is now flush against a </LI>.
- if (node.parentNode) {
- node.parentNode.removeChild(node);
- }
- } else {
- for (var child = node.firstChild; child; child = child.nextSibling) {
- walk(child);
- }
- }
- break;
- case 3: case 4: // Text
- if (isPreformatted) {
- var text = node.nodeValue;
- var match = text.match(lineBreak);
- if (match) {
- var firstLine = text.substring(0, match.index);
- node.nodeValue = firstLine;
- var tail = text.substring(match.index + match[0].length);
- if (tail) {
- var parent = node.parentNode;
- parent.insertBefore(
- document.createTextNode(tail), node.nextSibling);
- }
- breakAfter(node);
- if (!firstLine) {
- // Don't leave blank text nodes in the DOM.
- node.parentNode.removeChild(node);
- }
- }
- }
- break;
- }
- }
-
- // Split a line after the given node.
- function breakAfter(lineEndNode) {
- // If there's nothing to the right, then we can skip ending the line
- // here, and move root-wards since splitting just before an end-tag
- // would require us to create a bunch of empty copies.
- while (!lineEndNode.nextSibling) {
- lineEndNode = lineEndNode.parentNode;
- if (!lineEndNode) { return; }
- }
-
- function breakLeftOf(limit, copy) {
- // Clone shallowly if this node needs to be on both sides of the break.
- var rightSide = copy ? limit.cloneNode(false) : limit;
- var parent = limit.parentNode;
- if (parent) {
- // We clone the parent chain.
- // This helps us resurrect important styling elements that cross lines.
- // E.g. in <i>Foo<br>Bar</i>
- // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
- var parentClone = breakLeftOf(parent, 1);
- // Move the clone and everything to the right of the original
- // onto the cloned parent.
- var next = limit.nextSibling;
- parentClone.appendChild(rightSide);
- for (var sibling = next; sibling; sibling = next) {
- next = sibling.nextSibling;
- parentClone.appendChild(sibling);
- }
- }
- return rightSide;
- }
-
- var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
-
- // Walk the parent chain until we reach an unattached LI.
- for (var parent;
- // Check nodeType since IE invents document fragments.
- (parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
- copiedListItem = parent;
- }
- // Put it on the list of lines for later processing.
- listItems.push(copiedListItem);
- }
-
- // Split lines while there are lines left to split.
- for (var i = 0; // Number of lines that have been split so far.
- i < listItems.length; // length updated by breakAfter calls.
- ++i) {
- walk(listItems[i]);
- }
-
- // Make sure numeric indices show correctly.
- if (opt_startLineNum === (opt_startLineNum|0)) {
- listItems[0].setAttribute('value', opt_startLineNum);
- }
-
- var ol = document.createElement('OL');
- ol.className = 'linenums';
- var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
- for (i = 0, n = listItems.length; i < n; ++i) {
- li = listItems[i];
- // Stick a class on the LIs so that stylesheets can
- // color odd/even rows, or any other row pattern that
- // is co-prime with 10.
- li.className = 'L' + ((i + offset) % 10);
- if (!li.firstChild) {
- li.appendChild(document.createTextNode('\xA0'));
- }
- ol.appendChild(li);
- }
-
- node.appendChild(ol);
- }
-
- /**
- * Breaks {@code job.sourceCode} around style boundaries in
- * {@code job.decorations} and modifies {@code job.sourceNode} in place.
- * @param {Object} job like <pre>{
- * sourceCode: {string} source as plain text,
- * spans: {Array.<number|Node>} alternating span start indices into source
- * and the text node or element (e.g. {@code <BR>}) corresponding to that
- * span.
- * decorations: {Array.<number|string} an array of style classes preceded
- * by the position at which they start in job.sourceCode in order
- * }</pre>
- * @private
- */
- function recombineTagsAndDecorations(job) {
- var isIE = /\bMSIE\b/.test(navigator.userAgent);
- var newlineRe = /\n/g;
-
- var source = job.sourceCode;
- var sourceLength = source.length;
- // Index into source after the last code-unit recombined.
- var sourceIndex = 0;
-
- var spans = job.spans;
- var nSpans = spans.length;
- // Index into spans after the last span which ends at or before sourceIndex.
- var spanIndex = 0;
-
- var decorations = job.decorations;
- var nDecorations = decorations.length;
- // Index into decorations after the last decoration which ends at or before
- // sourceIndex.
- var decorationIndex = 0;
-
- // Remove all zero-length decorations.
- decorations[nDecorations] = sourceLength;
- var decPos, i;
- for (i = decPos = 0; i < nDecorations;) {
- if (decorations[i] !== decorations[i + 2]) {
- decorations[decPos++] = decorations[i++];
- decorations[decPos++] = decorations[i++];
- } else {
- i += 2;
- }
- }
- nDecorations = decPos;
-
- // Simplify decorations.
- for (i = decPos = 0; i < nDecorations;) {
- var startPos = decorations[i];
- // Conflate all adjacent decorations that use the same style.
- var startDec = decorations[i + 1];
- var end = i + 2;
- while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
- end += 2;
- }
- decorations[decPos++] = startPos;
- decorations[decPos++] = startDec;
- i = end;
- }
-
- nDecorations = decorations.length = decPos;
-
- var decoration = null;
- while (spanIndex < nSpans) {
- var spanStart = spans[spanIndex];
- var spanEnd = spans[spanIndex + 2] || sourceLength;
-
- var decStart = decorations[decorationIndex];
- var decEnd = decorations[decorationIndex + 2] || sourceLength;
-
- end = Math.min(spanEnd, decEnd);
-
- var textNode = spans[spanIndex + 1];
- var styledText;
- if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s
- // Don't introduce spans around empty text nodes.
- && (styledText = source.substring(sourceIndex, end))) {
- // This may seem bizarre, and it is. Emitting LF on IE causes the
- // code to display with spaces instead of line breaks.
- // Emitting Windows standard issue linebreaks (CRLF) causes a blank
- // space to appear at the beginning of every line but the first.
- // Emitting an old Mac OS 9 line separator makes everything spiffy.
- if (isIE) { styledText = styledText.replace(newlineRe, '\r'); }
- textNode.nodeValue = styledText;
- var document = textNode.ownerDocument;
- var span = document.createElement('SPAN');
- span.className = decorations[decorationIndex + 1];
- var parentNode = textNode.parentNode;
- parentNode.replaceChild(span, textNode);
- span.appendChild(textNode);
- if (sourceIndex < spanEnd) { // Split off a text node.
- spans[spanIndex + 1] = textNode
- // TODO: Possibly optimize by using '' if there's no flicker.
- = document.createTextNode(source.substring(end, spanEnd));
- parentNode.insertBefore(textNode, span.nextSibling);
- }
- }
-
- sourceIndex = end;
-
- if (sourceIndex >= spanEnd) {
- spanIndex += 2;
- }
- if (sourceIndex >= decEnd) {
- decorationIndex += 2;
- }
- }
- }
-
-
- /** Maps language-specific file extensions to handlers. */
- var langHandlerRegistry = {};
- /** Register a language handler for the given file extensions.
- * @param {function (Object)} handler a function from source code to a list
- * of decorations. Takes a single argument job which describes the
- * state of the computation. The single parameter has the form
- * {@code {
- * sourceCode: {string} as plain text.
- * decorations: {Array.<number|string>} an array of style classes
- * preceded by the position at which they start in
- * job.sourceCode in order.
- * The language handler should assigned this field.
- * basePos: {int} the position of source in the larger source chunk.
- * All positions in the output decorations array are relative
- * to the larger source chunk.
- * } }
- * @param {Array.<string>} fileExtensions
- */
- function registerLangHandler(handler, fileExtensions) {
- for (var i = fileExtensions.length; --i >= 0;) {
- var ext = fileExtensions[i];
- if (!langHandlerRegistry.hasOwnProperty(ext)) {
- langHandlerRegistry[ext] = handler;
- } else if (window['console']) {
- console['warn']('cannot override language handler %s', ext);
- }
- }
- }
- function langHandlerForExtension(extension, source) {
- if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
- // Treat it as markup if the first non whitespace character is a < and
- // the last non-whitespace character is a >.
- extension = /^\s*</.test(source)
- ? 'default-markup'
- : 'default-code';
- }
- return langHandlerRegistry[extension];
- }
- registerLangHandler(decorateSource, ['default-code']);
- registerLangHandler(
- createSimpleLexer(
- [],
- [
- [PR_PLAIN, /^[^<?]+/],
- [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
- [PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
- // Unescaped content in an unknown language
- ['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
- ['lang-', /^<%([\s\S]+?)(?:%>|$)/],
- [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
- ['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
- // Unescaped content in javascript. (Or possibly vbscript).
- ['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
- // Contains unescaped stylesheet content
- ['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
- ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
- ]),
- ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
- registerLangHandler(
- createSimpleLexer(
- [
- [PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
- [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
- ],
- [
- [PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
- [PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
- ['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
- [PR_PUNCTUATION, /^[=<>\/]+/],
- ['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
- ['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
- ['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
- ['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
- ['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
- ['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
- ]),
- ['in.tag']);
- registerLangHandler(
- createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
- registerLangHandler(sourceDecorator({
- 'keywords': CPP_KEYWORDS,
- 'hashComments': true,
- 'cStyleComments': true,
- 'types': C_TYPES
- }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
- registerLangHandler(sourceDecorator({
- 'keywords': 'null,true,false'
- }), ['json']);
- registerLangHandler(sourceDecorator({
- 'keywords': CSHARP_KEYWORDS,
- 'hashComments': true,
- 'cStyleComments': true,
- 'verbatimStrings': true,
- 'types': C_TYPES
- }), ['cs']);
- registerLangHandler(sourceDecorator({
- 'keywords': JAVA_KEYWORDS,
- 'cStyleComments': true
- }), ['java']);
- registerLangHandler(sourceDecorator({
- 'keywords': SH_KEYWORDS,
- 'hashComments': true,
- 'multiLineStrings': true
- }), ['bsh', 'csh', 'sh']);
- registerLangHandler(sourceDecorator({
- 'keywords': PYTHON_KEYWORDS,
- 'hashComments': true,
- 'multiLineStrings': true,
- 'tripleQuotedStrings': true
- }), ['cv', 'py']);
- registerLangHandler(sourceDecorator({
- 'keywords': PERL_KEYWORDS,
- 'hashComments': true,
- 'multiLineStrings': true,
- 'regexLiterals': true
- }), ['perl', 'pl', 'pm']);
- registerLangHandler(sourceDecorator({
- 'keywords': RUBY_KEYWORDS,
- 'hashComments': true,
- 'multiLineStrings': true,
- 'regexLiterals': true
- }), ['rb']);
- registerLangHandler(sourceDecorator({
- 'keywords': JSCRIPT_KEYWORDS,
- 'cStyleComments': true,
- 'regexLiterals': true
- }), ['js']);
- registerLangHandler(sourceDecorator({
- 'keywords': COFFEE_KEYWORDS,
- 'hashComments': 3, // ### style block comments
- 'cStyleComments': true,
- 'multilineStrings': true,
- 'tripleQuotedStrings': true,
- 'regexLiterals': true
- }), ['coffee']);
- registerLangHandler(createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
-
- function applyDecorator(job) {
- var opt_langExtension = job.langExtension;
-
- try {
- // Extract tags, and convert the source code to plain text.
- var sourceAndSpans = extractSourceSpans(job.sourceNode);
- /** Plain text. @type {string} */
- var source = sourceAndSpans.sourceCode;
- job.sourceCode = source;
- job.spans = sourceAndSpans.spans;
- job.basePos = 0;
-
- // Apply the appropriate language handler
- langHandlerForExtension(opt_langExtension, source)(job);
-
- // Integrate the decorations and tags back into the source code,
- // modifying the sourceNode in place.
- recombineTagsAndDecorations(job);
- } catch (e) {
- if ('console' in window) {
- console['log'](e && e['stack'] ? e['stack'] : e);
- }
- }
- }
-
- /**
- * @param sourceCodeHtml {string} The HTML to pretty print.
- * @param opt_langExtension {string} The language name to use.
- * Typically, a filename extension like 'cpp' or 'java'.
- * @param opt_numberLines {number|boolean} True to number lines,
- * or the 1-indexed number of the first line in sourceCodeHtml.
- */
- function prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
- var container = document.createElement('PRE');
- // This could cause images to load and onload listeners to fire.
- // E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
- // We assume that the inner HTML is from a trusted source.
- container.innerHTML = sourceCodeHtml;
- if (opt_numberLines) {
- numberLines(container, opt_numberLines);
- }
-
- var job = {
- langExtension: opt_langExtension,
- numberLines: opt_numberLines,
- sourceNode: container
- };
- applyDecorator(job);
- return container.innerHTML;
- }
-
- function prettyPrint(opt_whenDone) {
- function byTagName(tn) { return document.getElementsByTagName(tn); }
- // fetch a list of nodes to rewrite
- var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
- var elements = [];
- for (var i = 0; i < codeSegments.length; ++i) {
- for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
- elements.push(codeSegments[i][j]);
- }
- }
- codeSegments = null;
-
- var clock = Date;
- if (!clock['now']) {
- clock = { 'now': function () { return +(new Date); } };
- }
-
- // The loop is broken into a series of continuations to make sure that we
- // don't make the browser unresponsive when rewriting a large page.
- var k = 0;
- var prettyPrintingJob;
-
- var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
- var prettyPrintRe = /\bprettyprint\b/;
-
- function doWork() {
- var endTime = (window['PR_SHOULD_USE_CONTINUATION'] ?
- clock['now']() + 250 /* ms */ :
- Infinity);
- for (; k < elements.length && clock['now']() < endTime; k++) {
- var cs = elements[k];
- var className = cs.className;
- if (className.indexOf('prettyprint') >= 0) {
- // If the classes includes a language extensions, use it.
- // Language extensions can be specified like
- // <pre class="prettyprint lang-cpp">
- // the language extension "cpp" is used to find a language handler as
- // passed to PR.registerLangHandler.
- // HTML5 recommends that a language be specified using "language-"
- // as the prefix instead. Google Code Prettify supports both.
- // http://dev.w3.org/html5/spec-author-view/the-code-element.html
- var langExtension = className.match(langExtensionRe);
- // Support <pre class="prettyprint"><code class="language-c">
- var wrapper;
- if (!langExtension && (wrapper = childContentWrapper(cs))
- && "CODE" === wrapper.tagName) {
- langExtension = wrapper.className.match(langExtensionRe);
- }
-
- if (langExtension) {
- langExtension = langExtension[1];
- }
-
- // make sure this is not nested in an already prettified element
- var nested = false;
- for (var p = cs.parentNode; p; p = p.parentNode) {
- if ((p.tagName === 'pre' || p.tagName === 'code' ||
- p.tagName === 'xmp') &&
- p.className && p.className.indexOf('prettyprint') >= 0) {
- nested = true;
- break;
- }
- }
- if (!nested) {
- // Look for a class like linenums or linenums:<n> where <n> is the
- // 1-indexed number of the first line.
- var lineNums = cs.className.match(/\blinenums\b(?::(\d+))?/);
- if (lineNums) {
- lineNums = lineNums[1] && lineNums[1].length ? +lineNums[1] : true;
- } else {
- lineNums = false;
- }
- if (lineNums) { numberLines(cs, lineNums); }
-
- // do the pretty printing
- prettyPrintingJob = {
- langExtension: langExtension,
- sourceNode: cs,
- numberLines: lineNums
- };
- applyDecorator(prettyPrintingJob);
- }
- }
- }
- if (k < elements.length) {
- // finish up in a continuation
- setTimeout(doWork, 250);
- } else if (opt_whenDone) {
- opt_whenDone();
- }
- }
-
- doWork();
- }
-
- /**
- * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
- * {@code class=prettyprint} and prettify them.
- *
- * @param {Function?} opt_whenDone if specified, called when the last entry
- * has been finished.
- */
- window['prettyPrintOne'] = prettyPrintOne;
- /**
- * Pretty print a chunk of code.
- *
- * @param {string} sourceCodeHtml code as html
- * @return {string} code as html, but prettier
- */
- window['prettyPrint'] = prettyPrint;
- /**
- * Contains functions for creating and registering new language handlers.
- * @type {Object}
- */
- window['PR'] = {
- 'createSimpleLexer': createSimpleLexer,
- 'registerLangHandler': registerLangHandler,
- 'sourceDecorator': sourceDecorator,
- 'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
- 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
- 'PR_COMMENT': PR_COMMENT,
- 'PR_DECLARATION': PR_DECLARATION,
- 'PR_KEYWORD': PR_KEYWORD,
- 'PR_LITERAL': PR_LITERAL,
- 'PR_NOCODE': PR_NOCODE,
- 'PR_PLAIN': PR_PLAIN,
- 'PR_PUNCTUATION': PR_PUNCTUATION,
- 'PR_SOURCE': PR_SOURCE,
- 'PR_STRING': PR_STRING,
- 'PR_TAG': PR_TAG,
- 'PR_TYPE': PR_TYPE
- };
-})();
diff --git a/toolkit/components/microformats/test/static/javascript/testrunner.js b/toolkit/components/microformats/test/static/javascript/testrunner.js
deleted file mode 100644
index db8db492e..000000000
--- a/toolkit/components/microformats/test/static/javascript/testrunner.js
+++ /dev/null
@@ -1,179 +0,0 @@
-/*!
- testrunner
- Used by http://localhost:3000/testrunner.html
- Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
- MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
-*/
-
-var options = {
- 'baseUrl': 'http://example.com',
- 'dateFormat': 'html5',
- 'parseLatLonGeo': false
- };
-
-window.onload = function() {
- var test = testData.data[0],
- versionElt = document.querySelector('#version');
-
- versionElt.innerHTML = 'v' + testData.version;
-
- buildTest( test );
- buildList( testData );
-}
-
-
-function displayTest(e){
- var label = e.target.innerHTML;
- var i = testData.data.length;
- while (i--) {
- if(testData.data[i].name === label){
- buildTest( testData.data[i] );
- break;
- }
- }
-}
-
-
-function buildTest( test ){
- var testDetailElt = document.querySelector('.test-detail'),
- nameElt = document.querySelector('#test-name'),
- htmlElt = document.querySelector('#test-html pre code'),
- jsonElt = document.querySelector('#test-json pre code'),
- parserElt = document.querySelector('#parser-json pre code'),
- diffElt = document.querySelector('#test-diff pre code');
-
- nameElt.innerHTML = test.name;
- htmlElt.innerHTML = htmlEscape( test.html );
- jsonElt.innerHTML = htmlEscape( test.json );
-
- var dom = new DOMParser();
- doc = dom.parseFromString( test.html, 'text/html' );
-
- options.node = doc;
- var mfJSON = Microformats.get( options );
- parserElt.innerHTML = htmlEscape( js_beautify( JSON.stringify(mfJSON) ) );
-
- // diff json
- var diff = DeepDiff(JSON.parse(test.json), mfJSON);
- if(diff !== undefined){
- diffElt.innerHTML = htmlEscape( js_beautify( JSON.stringify(diff) ) );
- }else{
- diffElt.innerHTML = '';
- }
-
- console.log(diff)
- if(diff !== undefined){
- addClass(nameElt, 'failed');
- addClass(testDetailElt, 'test-failed');
- removeClass(testDetailElt, 'test-passed');
- }else{
- removeClass(nameElt, 'failed');
- removeClass(testDetailElt, 'test-failed');
- addClass(testDetailElt, 'test-passed');
- }
-
- testDetailElt.style.display = 'block';
-
- //prettyPrint();
-}
-
-
-
-function passTest( test ){
- var dom = new DOMParser(),
- doc = dom.parseFromString( test.html, 'text/html' );
-
- options.node = doc;
- var mfJSON = Microformats.get( options );
-
- // diff json
- var diff = DeepDiff(JSON.parse(test.json), mfJSON);
- return (diff === undefined);
-}
-
-
-
-
-function buildList( tests ){
- var total = tests.data.length,
- passed = 0,
- testResultListElt = document.querySelector('.test-result-list');
-
- tests.data.forEach(function(item){
- var li = document.createElement('li');
- li.innerHTML = item.name;
- testResultListElt.appendChild(li);
-
- if( passTest( item ) === false ){
- //li.classList.add('failed')
- addClass(li, 'failed');
- }else{
- passed ++;
- }
-
- li.addEventListener('click', function(e){
- e.preventDefault();
- displayTest(e);
- });
-
- });
- updateCounts( {
- 'total': total,
- 'passed': passed,
- 'percentPassed': ((100/total) * passed).toFixed(1)
- } )
-}
-
-
-function updateCounts( data ){
- var testCountsElt = document.querySelector('.test-counts');
- testCountsElt.innerHTML = 'Passed: ' + data.passed + '/' + data.total + ' - ' + data.percentPassed + '% of microformats tests';
-}
-
-
-function htmlEscape(str) {
- return String(str)
- .replace(/&/g, '&amp;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&#39;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
-}
-
-// I needed the opposite function today, so adding here too:
-function htmlUnescape(value){
- return String(value)
- .replace(/&quot;/g, '"')
- .replace(/&#39;/g, "'")
- .replace(/&lt;/g, '<')
- .replace(/&gt;/g, '>')
- .replace(/&amp;/g, '&');
-}
-
-
-// Does the node have a class
-function hasClass(node, className) {
- if (node.className) {
- return node.className.match(
- new RegExp('(\\s|^)' + className + '(\\s|$)'));
- } else {
- return false;
- }
-}
-
-
-// Add a class to an node
-function addClass(node, className) {
- if (!hasClass(node, className)) {
- node.className += " " + className;
- }
-}
-
-
-// Removes a class from an node
-function removeClass(node, className) {
- if (hasClass(node, className)) {
- var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
- node.className = node.className.replace(reg, ' ');
- }
-}
diff --git a/toolkit/components/microformats/test/static/parse-umd.html b/toolkit/components/microformats/test/static/parse-umd.html
deleted file mode 100644
index ec9a0c071..000000000
--- a/toolkit/components/microformats/test/static/parse-umd.html
+++ /dev/null
@@ -1,85 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
-
- <meta charset="UTF-8">
- <title>Parse Microformats</title>
- <meta name="description" content="microformat-shiv - A light-weight cross browser javascript microformats 2 parser" />
-
- <link rel="stylesheet" href="css/testrunner.css">
- <link rel="stylesheet" href="css/prettify.css">
-
-
- <!-- Loads full umd version -->
- <script src="../../thirdparty/es5-shim.min.js"></script>
- <script src="../../microformat-shiv.js"></script>
-
-
- <script src="javascript/beautify.js"></script>
- <script src="javascript/prettify.js"></script>
- <script src="javascript/DOMParser.js"></script>
- <script src="javascript/parse.js"></script>
-
- </head>
-
- <body>
-
- <p>microformat-shiv</p>
- <h1>Parse Microformats - UMD</h1>
- <p>Type or copy and paste the HTML you want to parse into the box below.</p>
-
- <form id="mf-form" class="tool-interface" method="get" action="">
- <p>
- <label for="html">HTML</label>
-<textarea id="html" name="html">&lt;a class="h-card" href="http://glennjones.net"&gt;
- &lt;span class="p-given-name"&gt;Glenn&lt;/span&gt;
- &lt;span class="p-family-name"&gt;Jones&lt;/span&gt;
-&lt;/a&gt;
-</textarea>
- </p>
-
-
- <p>
- <label for="baseurl">BaseURL</label>
- <input id="baseurl" name="baseurl" placeholder="Optional URL to help resolve relative links" value="http://example.com" type="text">
- </p>
-
-
- <p>
- <label for="filters">Filters</label>
- <input id="filters" name="filters" placeholder="Optional comma separted list of formats to filter by" type="text">
- </p>
-
-
- <p class="checkbox">
- <input id="collapsewhitespace" name="collapsewhitespace" id="textformat2" type="checkbox">
- <label class="checkbox-label" for="textformat2"><strong>Experimental</strong> ‐ Text white-space collapsing</label>
- </p>
-
- <p class="checkbox">
- <input id="parseLatLonGeo" name="parseLatLonGeo" id="parseLatLonGeo" type="checkbox">
- <label class="checkbox-label" for="parseLatLonGeo"><strong>Experimental</strong> ‐ Parse geo data writen as latlon i.e. 30.267991;-97.739568</label>
- </p>
-
- <p>
-
- <select id="dateformat" class="indent" name="dateformat" id="dateformat2">
- <option value="auto" selected="selected">auto</option>
- <option value="W3C">w3c</option>
- <option value="HTML5">html5</option>
- <option value="RFC3339">rfc3339</option>
- </select>
-
- <label class="checkbox-label" for="dateformat2"><strong>Experimental</strong> ‐ ISO date profile</label>
- </p>
-
- <input class="button" value="Parse" type="submit">
- </form>
-
- <h1>Parser JSON</h1>
- <div id="parser-json"><pre class="prettyprint"><code class="language-json"></code></pre></div>
-
-
-
- </body>
-</html> \ No newline at end of file
diff --git a/toolkit/components/microformats/test/static/parse.html b/toolkit/components/microformats/test/static/parse.html
deleted file mode 100644
index c8b929fcb..000000000
--- a/toolkit/components/microformats/test/static/parse.html
+++ /dev/null
@@ -1,127 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
-
- <meta charset="UTF-8">
- <title>Parse Microformats</title>
- <meta name="description" content="microformat-shiv - A light-weight cross browser javascript microformats 2 parser" />
-
- <link rel="stylesheet" href="css/testrunner.css">
- <link rel="stylesheet" href="css/prettify.css">
-
- <script src="..././thirdparty/es5-shim.min.js"></script>
-
- <!-- loads Modules to help with debugging ie windows.Modules -->
- <script src="../../lib/utilities.js"></script>
- <script src="../../lib/domutils.js"></script>
- <script src="../../lib/url.js"></script>
- <script src="../../lib/html.js"></script>
- <script src="../../lib/text.js"></script>
- <script src="../../lib/dates.js"></script>
- <script src="../../lib/isodate.js"></script>
- <script src="../../lib/parser.js"></script>
- <script src="../../lib/parser-implied.js"></script>
- <script src="../../lib/parser-includes.js"></script>
- <script src="../../lib/parser-rels.js"></script>
-
- <script src="../../lib/maps/h-adr.js"></script>
- <script src="../../lib/maps/h-card.js"></script>
- <script src="../../lib/maps/h-entry.js"></script>
- <script src="../../lib/maps/h-event.js"></script>
- <script src="../../lib/maps/h-feed.js"></script>
- <script src="../../lib/maps/h-geo.js"></script>
- <script src="../../lib/maps/h-item.js"></script>
- <script src="../../lib/maps/h-listing.js"></script>
- <script src="../../lib/maps/h-news.js"></script>
- <script src="../../lib/maps/h-org.js"></script>
- <script src="../../lib/maps/h-product.js"></script>
- <script src="../../lib/maps/h-recipe.js"></script>
- <script src="../../lib/maps/h-resume.js"></script>
- <script src="../../lib/maps/h-review-aggregate.js"></script>
- <script src="../../lib/maps/h-review.js"></script>
- <script src="../../lib/maps/rel.js"></script>
-
-
- <script src="javascript/beautify.js"></script>
- <script src="javascript/prettify.js"></script>
-
- <script src="javascript/DOMParser.js"></script>
- <script src="javascript/parse.js"></script>
-
- </head>
-
- <body>
-
- <p>microformat-shiv</p>
- <h1>Parse Microformats - Modules</h1>
- <p>Type or copy and paste the HTML you want to parse into the box below.</p>
-
- <form id="mf-form" class="tool-interface" method="get" action="">
- <p>
- <label for="html">HTML</label>
-<textarea id="html" name="html">&lt;a class="h-card" href="glenn.html"&gt;
- &lt;span class="p-given-name"&gt;Glenn&lt;/span&gt;
- &lt;span class="p-family-name"&gt;Jones&lt;/span&gt;
-&lt;/a&gt;
-</textarea>
- </p>
-
-
- <p>
- <label for="baseurl">BaseURL</label>
- <input id="baseurl" name="baseurl" placeholder="Optional URL to help resolve relative links" value="http://example.com" type="text">
- </p>
-
- <p>
- <label for="filters">Filters</label>
- <input id="filters" name="filters" placeholder="Optional comma separted list of formats to filter by" type="text">
- </p>
-
-
-
- <p class="checkbox">
- <input id="collapsewhitespace" name="collapsewhitespace" id="textformat2" type="checkbox">
- <label class="checkbox-label" for="textformat2"><strong>Experimental</strong> ‐ Text white-space collapsing</label>
- </p>
-
- <!--
- <p class="checkbox">
- <input id="overlappingversions" name="overlappingversions" id="overlappingversions" type="checkbox">
- <label class="checkbox-label" for="overlappingversions"><strong>Experimental</strong> ‐ Block overlapping properties from different microformat versions</label>
- </p>
-
- <p class="checkbox">
- <input id="impliedPropertiesByVersion" name="impliedPropertiesByVersion" id="impliedPropertiesByVersion" type="checkbox">
- <label class="checkbox-label" for="impliedPropertiesByVersion"><strong>Experimental</strong> ‐ Set implied properties by microformat version</label>
- </p>
- -->
-
- <p class="checkbox">
- <input id="parseLatLonGeo" name="parseLatLonGeo" id="parseLatLonGeo" type="checkbox">
- <label class="checkbox-label" for="parseLatLonGeo"><strong>Experimental</strong> ‐ Parse geo data writen as latlon i.e. 30.267991;-97.739568</label>
- </p>
-
-
-
- <p>
-
- <select id="dateformat" class="indent" name="dateformat" id="dateformat2">
- <option value="auto" selected="selected">auto</option>
- <option value="W3C">w3c</option>
- <option value="HTML5">html5</option>
- <option value="RFC3339">rfc3339</option>
- </select>
-
- <label class="checkbox-label" for="dateformat2"><strong>Experimental</strong> ‐ Fixed ISO date profile for output</label>
- </p>
-
- <input class="button" value="Parse" type="submit">
- </form>
-
- <h1>Parser JSON</h1>
- <div id="parser-json"><pre class="prettyprint"><code class="language-json"></code></pre></div>
-
-
-
- </body>
-</html> \ No newline at end of file
diff --git a/toolkit/components/microformats/test/static/testrunner.html b/toolkit/components/microformats/test/static/testrunner.html
deleted file mode 100644
index 54e8ceb84..000000000
--- a/toolkit/components/microformats/test/static/testrunner.html
+++ /dev/null
@@ -1,69 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="utf-8" />
- <title>Microformats Test Suite</title>
-
- <link rel="stylesheet" href="css/testrunner.css">
- <link rel="stylesheet" href="css/prettify.css">
-
-
- <script src="../../thirdparty/es5-shim.min.js"></script>
- <script src="../../microformat-shiv.js"></script>
-
-
- <script src="javascript/DOMParser.js"></script>
- <script src="javascript/data.js"></script>
- <script src="javascript/beautify.js"></script>
- <script src="javascript/prettify.js"></script>
- <script src="javascript/deep-diff-0.3.1.min.js"></script>
- <script src="javascript/testrunner.js"></script>
-
-
-</head>
-<body >
-
- <p>microformat-shiv</p>
- <h1>Microformats Tests <span id="version"></span></h1>
-
- <h2 class="test-counts"></h2>
-
-
- <p>Inspect the details of any test from the list</p>
- <section class="flexbox-container">
-
- <section class="test-results">
- <ul class="test-result-list">
- </ul>
- </section>
-
-
- <section class="test-detail">
-
-
- <h2 id="test-name"></h2>
-
- <h1>Test</h1>
- <div id="test-html"><pre class="prettyprint"><code class="language-html"></code></pre></div>
-
- <h1>Expected JSON</h1>
- <div id="test-json"><pre class="prettyprint"><code class="language-json"></code></pre></div>
-
- <h1>Parser JSON</h1>
- <div id="parser-json"><pre class="prettyprint"><code class="language-json"></code></pre></div>
-
- <div class="differences">
- <h1>Differences</h1>
- <div id="test-diff"><pre class="prettyprint"><code class="language-json"></code></pre></div>
- </div>
-
- </section>
-
- </section>
-
- <footer>
-
- </footer>
-</body>
-
-</html> \ No newline at end of file
diff --git a/toolkit/components/mozintl/moz.build b/toolkit/components/mozintl/moz.build
index a92ed50b7..d949f81ef 100644
--- a/toolkit/components/mozintl/moz.build
+++ b/toolkit/components/mozintl/moz.build
@@ -4,16 +4,10 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['test/xpcshell.ini']
-
-XPIDL_SOURCES += [
- 'mozIMozIntl.idl',
-]
+XPIDL_SOURCES += ['mozIMozIntl.idl']
XPIDL_MODULE = 'mozintl'
-SOURCES += [
- 'MozIntl.cpp',
-]
+SOURCES += ['MozIntl.cpp']
FINAL_LIBRARY = 'xul'
diff --git a/toolkit/components/mozintl/test/test_mozintl.js b/toolkit/components/mozintl/test/test_mozintl.js
deleted file mode 100644
index 8d2720bf0..000000000
--- a/toolkit/components/mozintl/test/test_mozintl.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test() {
- const mozIntl = Components.classes["@mozilla.org/mozintl;1"]
- .getService(Components.interfaces.mozIMozIntl);
-
- test_this_global(mozIntl);
- test_cross_global(mozIntl);
- test_methods_presence(mozIntl);
-
- ok(true);
-}
-
-function test_this_global(mozIntl) {
- let x = {};
-
- mozIntl.addGetCalendarInfo(x);
- equal(x.getCalendarInfo instanceof Function, true);
- equal(x.getCalendarInfo() instanceof Object, true);
-}
-
-function test_cross_global(mozIntl) {
- var global = new Components.utils.Sandbox("https://example.com/");
- var x = global.Object();
-
- mozIntl.addGetCalendarInfo(x);
- var waivedX = Components.utils.waiveXrays(x);
- equal(waivedX.getCalendarInfo instanceof Function, false);
- equal(waivedX.getCalendarInfo instanceof global.Function, true);
- equal(waivedX.getCalendarInfo() instanceof Object, false);
- equal(waivedX.getCalendarInfo() instanceof global.Object, true);
-}
-
-function test_methods_presence(mozIntl) {
- equal(mozIntl.addGetCalendarInfo instanceof Function, true);
- equal(mozIntl.addGetDisplayNames instanceof Function, true);
-
- let x = {};
-
- mozIntl.addGetCalendarInfo(x);
- equal(x.getCalendarInfo instanceof Function, true);
-
- mozIntl.addGetDisplayNames(x);
- equal(x.getDisplayNames instanceof Function, true);
-}
diff --git a/toolkit/components/mozintl/test/xpcshell.ini b/toolkit/components/mozintl/test/xpcshell.ini
deleted file mode 100644
index 8fecd3933..000000000
--- a/toolkit/components/mozintl/test/xpcshell.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[DEFAULT]
-head =
-tail =
-
-[test_mozintl.js]
diff --git a/toolkit/components/mozprotocol/moz.build b/toolkit/components/mozprotocol/moz.build
index fa09ade5a..42bbeb518 100644
--- a/toolkit/components/mozprotocol/moz.build
+++ b/toolkit/components/mozprotocol/moz.build
@@ -8,7 +8,3 @@ EXTRA_COMPONENTS += [
'mozProtocolHandler.js',
'mozProtocolHandler.manifest',
]
-
-BROWSER_CHROME_MANIFESTS += [
- 'tests/browser.ini'
-]
diff --git a/toolkit/components/mozprotocol/tests/browser.ini b/toolkit/components/mozprotocol/tests/browser.ini
deleted file mode 100644
index 168882a67..000000000
--- a/toolkit/components/mozprotocol/tests/browser.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[DEFAULT]
-
-[browser_mozprotocol.js]
-support-files =
- mozprotocol.html
diff --git a/toolkit/components/mozprotocol/tests/browser_mozprotocol.js b/toolkit/components/mozprotocol/tests/browser_mozprotocol.js
deleted file mode 100644
index 795ce8a08..000000000
--- a/toolkit/components/mozprotocol/tests/browser_mozprotocol.js
+++ /dev/null
@@ -1,14 +0,0 @@
-// Check that entering moz://a into the address bar directs us to a new url
-add_task(function*() {
- let path = getRootDirectory(gTestPath).substring("chrome://mochitests/content/".length);
- yield SpecialPowers.pushPrefEnv({
- set: [["toolkit.mozprotocol.url", `https://example.com/${path}mozprotocol.html`]],
- });
-
- yield BrowserTestUtils.withNewTab("about:blank", function*() {
- gBrowser.loadURI("moz://a");
- yield BrowserTestUtils.waitForLocationChange(gBrowser,
- `https://example.com/${path}mozprotocol.html`);
- ok(true, "Made it to the expected page");
- });
-});
diff --git a/toolkit/components/mozprotocol/tests/mozprotocol.html b/toolkit/components/mozprotocol/tests/mozprotocol.html
deleted file mode 100644
index 3d6549e00..000000000
--- a/toolkit/components/mozprotocol/tests/mozprotocol.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<body>
-<p><a id="link" href="moz://a">Test</a></p>
-</body>
-</html>
diff --git a/toolkit/components/narrate/moz.build b/toolkit/components/narrate/moz.build
index c5597c369..bd2d298b6 100644
--- a/toolkit/components/narrate/moz.build
+++ b/toolkit/components/narrate/moz.build
@@ -9,5 +9,3 @@ EXTRA_JS_MODULES.narrate = [
'Narrator.jsm',
'VoiceSelect.jsm'
]
-
-BROWSER_CHROME_MANIFESTS += ['test/browser.ini']
diff --git a/toolkit/components/narrate/test/.eslintrc.js b/toolkit/components/narrate/test/.eslintrc.js
deleted file mode 100644
index 5ff0bae7e..000000000
--- a/toolkit/components/narrate/test/.eslintrc.js
+++ /dev/null
@@ -1,23 +0,0 @@
-"use strict";
-
-module.exports = { // eslint-disable-line no-undef
- "extends": [
- "../.eslintrc.js"
- ],
-
- "globals": {
- "is": true,
- "isnot": true,
- "ok": true,
- "NarrateTestUtils": true,
- "content": true,
- "ContentTaskUtils": true,
- "ContentTask": true,
- "BrowserTestUtils": true,
- "gBrowser": true,
- },
-
- "rules": {
- "mozilla/import-headjs-globals": "warn"
- }
-};
diff --git a/toolkit/components/narrate/test/NarrateTestUtils.jsm b/toolkit/components/narrate/test/NarrateTestUtils.jsm
deleted file mode 100644
index b782f66c9..000000000
--- a/toolkit/components/narrate/test/NarrateTestUtils.jsm
+++ /dev/null
@@ -1,148 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 = Components.utils;
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://testing-common/ContentTaskUtils.jsm");
-
-this.EXPORTED_SYMBOLS = [ "NarrateTestUtils" ];
-
-this.NarrateTestUtils = {
- TOGGLE: "#narrate-toggle",
- POPUP: "#narrate-dropdown .dropdown-popup",
- VOICE_SELECT: "#narrate-voices .select-toggle",
- VOICE_OPTIONS: "#narrate-voices .options",
- VOICE_SELECTED: "#narrate-voices .options .option.selected",
- VOICE_SELECT_LABEL: "#narrate-voices .select-toggle .current-voice",
- RATE: "#narrate-rate-input",
- START: "#narrate-dropdown:not(.speaking) #narrate-start-stop",
- STOP: "#narrate-dropdown.speaking #narrate-start-stop",
- BACK: "#narrate-skip-previous",
- FORWARD: "#narrate-skip-next",
-
- isVisible: function(element) {
- let style = element.ownerDocument.defaultView.getComputedStyle(element, "");
- if (style.display == "none") {
- return false;
- } else if (style.visibility != "visible") {
- return false;
- } else if (style.display == "-moz-popup" && element.state != "open") {
- return false;
- }
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument) {
- return this.isVisible(element.parentNode);
- }
-
- return true;
- },
-
- isStoppedState: function(window, ok) {
- let $ = window.document.querySelector.bind(window.document);
- ok($(this.BACK).disabled, "back button is disabled");
- ok($(this.FORWARD).disabled, "forward button is disabled");
- ok(!!$(this.START), "start button is showing");
- ok(!$(this.STOP), "stop button is hidden");
- // This checks for a localized label. Not the best...
- ok($(this.START).title == "Start", "Button tooltip is correct");
- },
-
- isStartedState: function(window, ok) {
- let $ = window.document.querySelector.bind(window.document);
- ok(!$(this.BACK).disabled, "back button is enabled");
- ok(!$(this.FORWARD).disabled, "forward button is enabled");
- ok(!$(this.START), "start button is hidden");
- ok(!!$(this.STOP), "stop button is showing");
- // This checks for a localized label. Not the best...
- ok($(this.STOP).title == "Stop", "Button tooltip is correct");
- },
-
- selectVoice: function(window, voiceUri) {
- if (!this.isVisible(window.document.querySelector(this.VOICE_OPTIONS))) {
- window.document.querySelector(this.VOICE_SELECT).click();
- }
-
- let voiceOption = window.document.querySelector(
- `#narrate-voices .option[data-value="${voiceUri}"]`);
-
- voiceOption.focus();
- voiceOption.click();
-
- return voiceOption.classList.contains("selected");
- },
-
- getEventUtils: function(window) {
- let eventUtils = {
- "_EU_Ci": Components.interfaces,
- "_EU_Cc": Components.classes,
- window: window,
- parent: window,
- navigator: window.navigator,
- KeyboardEvent: window.KeyboardEvent,
- KeyEvent: window.KeyEvent
- };
- Services.scriptloader.loadSubScript(
- "chrome://mochikit/content/tests/SimpleTest/EventUtils.js", eventUtils);
- return eventUtils;
- },
-
- getReaderReadyPromise: function(window) {
- return new Promise(resolve => {
- function observeReady(subject, topic) {
- if (subject == window) {
- Services.obs.removeObserver(observeReady, topic);
- resolve();
- }
- }
-
- if (window.document.body.classList.contains("loaded")) {
- resolve();
- } else {
- Services.obs.addObserver(observeReady, "AboutReader:Ready", false);
- }
- });
- },
-
- waitForNarrateToggle: function(window) {
- let toggle = window.document.querySelector(this.TOGGLE);
- return ContentTaskUtils.waitForCondition(
- () => !toggle.hidden, "");
- },
-
- waitForPrefChange: function(pref) {
- return new Promise(resolve => {
- function observeChange() {
- Services.prefs.removeObserver(pref, observeChange);
- resolve(Preferences.get(pref));
- }
-
- Services.prefs.addObserver(pref, observeChange, false);
- });
- },
-
- sendBoundaryEvent: function(window, name, charIndex) {
- let detail = { type: "boundary", args: { name, charIndex } };
- window.dispatchEvent(new window.CustomEvent("testsynthevent",
- { detail: detail }));
- },
-
- isWordHighlightGone: function(window, ok) {
- let $ = window.document.querySelector.bind(window.document);
- ok(!$(".narrate-word-highlight"), "No more word highlights exist");
- },
-
- getWordHighlights: function(window) {
- let $$ = window.document.querySelectorAll.bind(window.document);
- let nodes = Array.from($$(".narrate-word-highlight"));
- return nodes.map(node => {
- return { word: node.dataset.word,
- left: Number(node.style.left.replace(/px$/, "")),
- top: Number(node.style.top.replace(/px$/, ""))};
- });
- }
-};
diff --git a/toolkit/components/narrate/test/browser.ini b/toolkit/components/narrate/test/browser.ini
deleted file mode 100644
index 0f5d694ac..000000000
--- a/toolkit/components/narrate/test/browser.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- NarrateTestUtils.jsm
- moby_dick.html
-
-[browser_narrate.js]
-[browser_narrate_disable.js]
-[browser_narrate_language.js]
-support-files = inferno.html
-[browser_voiceselect.js]
-[browser_word_highlight.js]
diff --git a/toolkit/components/narrate/test/browser_narrate.js b/toolkit/components/narrate/test/browser_narrate.js
deleted file mode 100644
index b4951ef9f..000000000
--- a/toolkit/components/narrate/test/browser_narrate.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/. */
-
-/* globals is, isnot, registerCleanupFunction, add_task */
-
-"use strict";
-
-registerCleanupFunction(teardown);
-
-add_task(function* testNarrate() {
- setup();
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function* () {
- let TEST_VOICE = "urn:moz-tts:fake-indirect:teresa";
- let $ = content.document.querySelector.bind(content.document);
-
- yield NarrateTestUtils.waitForNarrateToggle(content);
-
- let popup = $(NarrateTestUtils.POPUP);
- ok(!NarrateTestUtils.isVisible(popup), "popup is initially hidden");
-
- let toggle = $(NarrateTestUtils.TOGGLE);
- toggle.click();
-
- ok(NarrateTestUtils.isVisible(popup), "popup toggled");
-
- let voiceOptions = $(NarrateTestUtils.VOICE_OPTIONS);
- ok(!NarrateTestUtils.isVisible(voiceOptions),
- "voice options are initially hidden");
-
- $(NarrateTestUtils.VOICE_SELECT).click();
- ok(NarrateTestUtils.isVisible(voiceOptions), "voice options pop up");
-
- let prefChanged = NarrateTestUtils.waitForPrefChange("narrate.voice");
- ok(NarrateTestUtils.selectVoice(content, TEST_VOICE),
- "test voice selected");
- yield prefChanged;
-
- ok(!NarrateTestUtils.isVisible(voiceOptions), "voice options hidden again");
-
- NarrateTestUtils.isStoppedState(content, ok);
-
- let promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- $(NarrateTestUtils.START).click();
- let speechinfo = (yield promiseEvent).detail;
- is(speechinfo.voice, TEST_VOICE, "correct voice is being used");
- let paragraph = speechinfo.paragraph;
-
- NarrateTestUtils.isStartedState(content, ok);
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- $(NarrateTestUtils.FORWARD).click();
- speechinfo = (yield promiseEvent).detail;
- is(speechinfo.voice, TEST_VOICE, "same voice is used");
- isnot(speechinfo.paragraph, paragraph, "next paragraph is being spoken");
-
- NarrateTestUtils.isStartedState(content, ok);
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- $(NarrateTestUtils.BACK).click();
- speechinfo = (yield promiseEvent).detail;
- is(speechinfo.paragraph, paragraph, "first paragraph being spoken");
-
- NarrateTestUtils.isStartedState(content, ok);
-
- paragraph = speechinfo.paragraph;
- $(NarrateTestUtils.STOP).click();
- yield ContentTaskUtils.waitForCondition(
- () => !$(NarrateTestUtils.STOP), "transitioned to stopped state");
- NarrateTestUtils.isStoppedState(content, ok);
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- $(NarrateTestUtils.START).click();
- speechinfo = (yield promiseEvent).detail;
- is(speechinfo.paragraph, paragraph, "read same paragraph again");
-
- NarrateTestUtils.isStartedState(content, ok);
-
- let eventUtils = NarrateTestUtils.getEventUtils(content);
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- prefChanged = NarrateTestUtils.waitForPrefChange("narrate.rate");
- $(NarrateTestUtils.RATE).focus();
- eventUtils.sendKey("UP", content);
- let newspeechinfo = (yield promiseEvent).detail;
- is(newspeechinfo.paragraph, speechinfo.paragraph, "same paragraph");
- isnot(newspeechinfo.rate, speechinfo.rate, "rate changed");
- yield prefChanged;
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphend");
- $(NarrateTestUtils.STOP).click();
- yield promiseEvent;
-
- yield ContentTaskUtils.waitForCondition(
- () => !$(NarrateTestUtils.STOP), "transitioned to stopped state");
- NarrateTestUtils.isStoppedState(content, ok);
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "scroll");
- content.scrollBy(0, 10);
- yield promiseEvent;
- ok(!NarrateTestUtils.isVisible(popup), "popup is hidden after scroll");
-
- toggle.click();
- ok(NarrateTestUtils.isVisible(popup), "popup is toggled again");
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- $(NarrateTestUtils.START).click();
- yield promiseEvent;
- NarrateTestUtils.isStartedState(content, ok);
-
- promiseEvent = ContentTaskUtils.waitForEvent(content, "scroll");
- content.scrollBy(0, -10);
- yield promiseEvent;
- ok(NarrateTestUtils.isVisible(popup), "popup stays visible after scroll");
-
- toggle.click();
- ok(!NarrateTestUtils.isVisible(popup), "popup is dismissed while speaking");
- NarrateTestUtils.isStartedState(content, ok);
-
- // Go forward all the way to the end of the article. We should eventually
- // stop.
- do {
- promiseEvent = Promise.race([
- ContentTaskUtils.waitForEvent(content, "paragraphstart"),
- ContentTaskUtils.waitForEvent(content, "paragraphsdone")]);
- $(NarrateTestUtils.FORWARD).click();
- } while ((yield promiseEvent).type == "paragraphstart");
-
- // This is to make sure we are not actively scrolling when the tab closes.
- content.scroll(0, 0);
-
- yield ContentTaskUtils.waitForCondition(
- () => !$(NarrateTestUtils.STOP), "transitioned to stopped state");
- NarrateTestUtils.isStoppedState(content, ok);
- });
-});
diff --git a/toolkit/components/narrate/test/browser_narrate_disable.js b/toolkit/components/narrate/test/browser_narrate_disable.js
deleted file mode 100644
index 264815fd1..000000000
--- a/toolkit/components/narrate/test/browser_narrate_disable.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* globals registerCleanupFunction, add_task */
-
-"use strict";
-
-const ENABLE_PREF = "narrate.enabled";
-
-registerCleanupFunction(() => {
- clearUserPref(ENABLE_PREF);
- teardown();
-});
-
-add_task(function* testNarratePref() {
- setup();
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function() {
- is(content.document.querySelectorAll(NarrateTestUtils.TOGGLE).length, 1,
- "narrate is inserted by default");
- });
-
- setBoolPref(ENABLE_PREF, false);
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function() {
- ok(!content.document.querySelector(NarrateTestUtils.TOGGLE),
- "narrate is disabled and is not in reader mode");
- });
-
- setBoolPref(ENABLE_PREF, true);
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function() {
- is(content.document.querySelectorAll(NarrateTestUtils.TOGGLE).length, 1,
- "narrate is re-enabled and appears only once");
- });
-});
diff --git a/toolkit/components/narrate/test/browser_narrate_language.js b/toolkit/components/narrate/test/browser_narrate_language.js
deleted file mode 100644
index 2542a87d6..000000000
--- a/toolkit/components/narrate/test/browser_narrate_language.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/. */
-
-/* globals is, isnot, registerCleanupFunction, add_task */
-
-"use strict";
-
-registerCleanupFunction(teardown);
-
-add_task(function* testVoiceselectDropdownAutoclose() {
- setup("automatic", true);
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function* () {
- let $ = content.document.querySelector.bind(content.document);
-
- yield NarrateTestUtils.waitForNarrateToggle(content);
-
- ok(!!$(".option[data-value='urn:moz-tts:fake-direct:bob']"),
- "Jamaican English voice available");
- ok(!!$(".option[data-value='urn:moz-tts:fake-direct:lenny']"),
- "Canadian English voice available");
- ok(!!$(".option[data-value='urn:moz-tts:fake-direct:amy']"),
- "British English voice available");
-
- ok(!$(".option[data-value='urn:moz-tts:fake-direct:celine']"),
- "Canadian French voice unavailable");
- ok(!$(".option[data-value='urn:moz-tts:fake-direct:julie']"),
- "Mexican Spanish voice unavailable");
-
- $(NarrateTestUtils.TOGGLE).click();
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.POPUP)),
- "popup is toggled");
-
- let prefChanged = NarrateTestUtils.waitForPrefChange(
- "narrate.voice", "getCharPref");
- NarrateTestUtils.selectVoice(content, "urn:moz-tts:fake-direct:lenny");
- let voicePref = JSON.parse(yield prefChanged);
- is(voicePref.en, "urn:moz-tts:fake-direct:lenny", "pref set correctly");
- });
-});
-
-add_task(function* testVoiceselectDropdownAutoclose() {
- setup("automatic", true);
-
- yield spawnInNewReaderTab(TEST_ITALIAN_ARTICLE, function* () {
- let $ = content.document.querySelector.bind(content.document);
-
- yield NarrateTestUtils.waitForNarrateToggle(content);
-
- ok(!!$(".option[data-value='urn:moz-tts:fake-indirect:zanetta']"),
- "Italian voice available");
- ok(!!$(".option[data-value='urn:moz-tts:fake-indirect:margherita']"),
- "Italian voice available");
-
- ok(!$(".option[data-value='urn:moz-tts:fake-direct:bob']"),
- "Jamaican English voice available");
- ok(!$(".option[data-value='urn:moz-tts:fake-direct:celine']"),
- "Canadian French voice unavailable");
- ok(!$(".option[data-value='urn:moz-tts:fake-direct:julie']"),
- "Mexican Spanish voice unavailable");
-
- $(NarrateTestUtils.TOGGLE).click();
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.POPUP)),
- "popup is toggled");
-
- let prefChanged = NarrateTestUtils.waitForPrefChange(
- "narrate.voice", "getCharPref");
- NarrateTestUtils.selectVoice(content, "urn:moz-tts:fake-indirect:zanetta");
- let voicePref = JSON.parse(yield prefChanged);
- is(voicePref.it, "urn:moz-tts:fake-indirect:zanetta", "pref set correctly");
- });
-});
diff --git a/toolkit/components/narrate/test/browser_voiceselect.js b/toolkit/components/narrate/test/browser_voiceselect.js
deleted file mode 100644
index 0de6528dd..000000000
--- a/toolkit/components/narrate/test/browser_voiceselect.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* globals registerCleanupFunction, add_task, is, isnot */
-
-"use strict";
-
-registerCleanupFunction(teardown);
-
-add_task(function* testVoiceselectDropdownAutoclose() {
- setup();
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function* () {
- let $ = content.document.querySelector.bind(content.document);
-
- yield NarrateTestUtils.waitForNarrateToggle(content);
-
- $(NarrateTestUtils.TOGGLE).click();
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.POPUP)),
- "popup is toggled");
-
- ok(!NarrateTestUtils.isVisible($(NarrateTestUtils.VOICE_OPTIONS)),
- "voice options are initially hidden");
-
- $(NarrateTestUtils.VOICE_SELECT).click();
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.VOICE_OPTIONS)),
- "voice options are toggled");
-
- $(NarrateTestUtils.TOGGLE).click();
- // A focus will follow a real click.
- $(NarrateTestUtils.TOGGLE).focus();
- ok(!NarrateTestUtils.isVisible($(NarrateTestUtils.POPUP)),
- "narrate popup is dismissed");
-
- $(NarrateTestUtils.TOGGLE).click();
- // A focus will follow a real click.
- $(NarrateTestUtils.TOGGLE).focus();
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.POPUP)),
- "narrate popup is showing again");
- ok(!NarrateTestUtils.isVisible($(NarrateTestUtils.VOICE_OPTIONS)),
- "voice options are hidden after popup comes back");
- });
-});
-
-add_task(function* testVoiceselectLabelChange() {
- setup();
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function* () {
- let $ = content.document.querySelector.bind(content.document);
-
- yield NarrateTestUtils.waitForNarrateToggle(content);
-
- $(NarrateTestUtils.TOGGLE).click();
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.POPUP)),
- "popup is toggled");
-
- ok(NarrateTestUtils.selectVoice(content, "urn:moz-tts:fake-direct:lenny"),
- "voice selected");
-
- let selectedOption = $(NarrateTestUtils.VOICE_SELECTED);
- let selectLabel = $(NarrateTestUtils.VOICE_SELECT_LABEL);
-
- is(selectedOption.textContent, selectLabel.textContent,
- "new label matches selected voice");
- });
-});
-
-add_task(function* testVoiceselectKeyboard() {
- setup();
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function* () {
- let $ = content.document.querySelector.bind(content.document);
-
- yield NarrateTestUtils.waitForNarrateToggle(content);
-
- $(NarrateTestUtils.TOGGLE).click();
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.POPUP)),
- "popup is toggled");
-
- let eventUtils = NarrateTestUtils.getEventUtils(content);
-
- let firstValue = $(NarrateTestUtils.VOICE_SELECTED).dataset.value;
-
- ok(!NarrateTestUtils.isVisible($(NarrateTestUtils.VOICE_OPTIONS)),
- "voice options initially are hidden");
-
- $(NarrateTestUtils.VOICE_SELECT).focus();
-
- eventUtils.sendKey("DOWN", content);
-
- yield ContentTaskUtils.waitForCondition(
- () => $(NarrateTestUtils.VOICE_SELECTED).dataset.value != firstValue,
- "value changed after pressing DOWN key");
-
- eventUtils.sendKey("RETURN", content);
-
- ok(NarrateTestUtils.isVisible($(NarrateTestUtils.VOICE_OPTIONS)),
- "voice options showing after pressing RETURN");
-
- eventUtils.sendKey("UP", content);
-
- eventUtils.sendKey("RETURN", content);
-
- ok(!NarrateTestUtils.isVisible($(NarrateTestUtils.VOICE_OPTIONS)),
- "voice options hidden after pressing RETURN");
-
- yield ContentTaskUtils.waitForCondition(
- () => $(NarrateTestUtils.VOICE_SELECTED).dataset.value == firstValue,
- "value changed back to original after pressing RETURN");
- });
-});
diff --git a/toolkit/components/narrate/test/browser_word_highlight.js b/toolkit/components/narrate/test/browser_word_highlight.js
deleted file mode 100644
index bfdbcf48e..000000000
--- a/toolkit/components/narrate/test/browser_word_highlight.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* globals is, isnot, registerCleanupFunction, add_task */
-
-"use strict";
-
-registerCleanupFunction(teardown);
-
-add_task(function* testNarrate() {
- setup("urn:moz-tts:fake-indirect:teresa");
-
- yield spawnInNewReaderTab(TEST_ARTICLE, function* () {
- let $ = content.document.querySelector.bind(content.document);
-
- yield NarrateTestUtils.waitForNarrateToggle(content);
-
- let popup = $(NarrateTestUtils.POPUP);
- ok(!NarrateTestUtils.isVisible(popup), "popup is initially hidden");
-
- let toggle = $(NarrateTestUtils.TOGGLE);
- toggle.click();
-
- ok(NarrateTestUtils.isVisible(popup), "popup toggled");
-
- NarrateTestUtils.isStoppedState(content, ok);
-
- let promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- $(NarrateTestUtils.START).click();
- let voice = (yield promiseEvent).detail.voice;
- is(voice, "urn:moz-tts:fake-indirect:teresa", "double-check voice");
-
- // Skip forward to first paragraph.
- let details;
- do {
- promiseEvent = ContentTaskUtils.waitForEvent(content, "paragraphstart");
- $(NarrateTestUtils.FORWARD).click();
- details = (yield promiseEvent).detail;
- } while (details.tag != "p");
-
- let boundaryPat = /(\s+)\S/g;
- let position = { left: 0, top: 0 };
- let text = details.paragraph;
- for (let res = boundaryPat.exec(text); res; res = boundaryPat.exec(text)) {
- promiseEvent = ContentTaskUtils.waitForEvent(content, "wordhighlight");
- NarrateTestUtils.sendBoundaryEvent(content, "word", res.index);
- let { start, end } = (yield promiseEvent).detail;
- let nodes = NarrateTestUtils.getWordHighlights(content);
- for (let node of nodes) {
- // Since this is English we can assume each word is to the right or
- // below the previous one.
- ok(node.left > position.left || node.top > position.top,
- "highlight position is moving");
- position = { left: node.left, top: node.top };
- }
- let wordFromOffset = text.substring(start, end);
- // XXX: Each node should contain the part of the word it highlights.
- // Right now, each node contains the entire word.
- let wordFromHighlight = nodes[0].word;
- is(wordFromOffset, wordFromHighlight, "Correct word is highlighted");
- }
-
- $(NarrateTestUtils.STOP).click();
- yield ContentTaskUtils.waitForCondition(
- () => !$(NarrateTestUtils.STOP), "transitioned to stopped state");
- NarrateTestUtils.isWordHighlightGone(content, ok);
- });
-});
diff --git a/toolkit/components/narrate/test/head.js b/toolkit/components/narrate/test/head.js
deleted file mode 100644
index 491a3da8d..000000000
--- a/toolkit/components/narrate/test/head.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* exported teardown, setup, toggleExtension,
- spawnInNewReaderTab, TEST_ARTICLE, TEST_ITALIAN_ARTICLE */
-
-"use strict";
-
-const TEST_ARTICLE =
- "http://example.com/browser/toolkit/components/narrate/test/moby_dick.html";
-
-const TEST_ITALIAN_ARTICLE =
- "http://example.com/browser/toolkit/components/narrate/test/inferno.html";
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Services",
- "resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
- "resource://gre/modules/AddonManager.jsm");
-
-const TEST_PREFS = {
- "reader.parse-on-load.enabled": true,
- "media.webspeech.synth.enabled": true,
- "media.webspeech.synth.test": true,
- "narrate.enabled": true,
- "narrate.test": true,
- "narrate.voice": null,
- "narrate.filter-voices": false,
-};
-
-function setup(voiceUri = "automatic", filterVoices = false) {
- let prefs = Object.assign({}, TEST_PREFS, {
- "narrate.filter-voices": filterVoices,
- "narrate.voice": JSON.stringify({ en: voiceUri })
- });
-
- // Set required test prefs.
- Object.entries(prefs).forEach(([name, value]) => {
- switch (typeof value) {
- case "boolean":
- setBoolPref(name, value);
- break;
- case "string":
- setCharPref(name, value);
- break;
- }
- });
-}
-
-function teardown() {
- // Reset test prefs.
- Object.entries(TEST_PREFS).forEach(pref => {
- clearUserPref(pref[0]);
- });
-}
-
-function spawnInNewReaderTab(url, func) {
- return BrowserTestUtils.withNewTab(
- { gBrowser,
- url: `about:reader?url=${encodeURIComponent(url)}` },
- function* (browser) {
- yield ContentTask.spawn(browser, null, function* () {
- Components.utils.import("chrome://mochitests/content/browser/" +
- "toolkit/components/narrate/test/NarrateTestUtils.jsm");
-
- yield NarrateTestUtils.getReaderReadyPromise(content);
- });
-
- yield ContentTask.spawn(browser, null, func);
- });
-}
-
-function setBoolPref(name, value) {
- Services.prefs.setBoolPref(name, value);
-}
-
-function setCharPref(name, value) {
- Services.prefs.setCharPref(name, value);
-}
-
-function clearUserPref(name) {
- Services.prefs.clearUserPref(name);
-}
diff --git a/toolkit/components/narrate/test/inferno.html b/toolkit/components/narrate/test/inferno.html
deleted file mode 100644
index 58dfd24df..000000000
--- a/toolkit/components/narrate/test/inferno.html
+++ /dev/null
@@ -1,238 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>Inferno - Canto I</title>
-</head>
-<body>
- <h1>Inferno</h1>
- <h2>Canto I: Dante nella selva oscura</h2>
- <p>
- Nel mezzo del cammin di nostra vita<br>
- mi ritrovai per una selva oscura,<br>
- ché la diritta via era smarrita.
- </p>
- <p>
- Ahi quanto a dir qual era è cosa dura<br>
- esta selva selvaggia e aspra e forte<br>
- che nel pensier rinova la paura!
- </p>
- <p>
- Tant' è amara che poco è più morte;<br>
- ma per trattar del ben ch'i' vi trovai,<br>
- dirò de l'altre cose ch'i' v'ho scorte.
- </p>
- <p>
- Io non so ben ridir com' i' v'intrai,<br>
- tant' era pien di sonno a quel punto<br>
- che la verace via abbandonai.
- </p>
- <p>
- Ma poi ch'i' fui al piè d'un colle giunto,<br>
- là dove terminava quella valle<br>
- che m'avea di paura il cor compunto,
- </p>
- <p>
- guardai in alto e vidi le sue spalle<br>
- vestite già de' raggi del pianeta<br>
- che mena dritto altrui per ogne calle.
- </p>
- <p>
- Allor fu la paura un poco queta,<br>
- che nel lago del cor m'era durata<br>
- la notte ch'i' passai con tanta pieta.
- </p>
- <p>
- E come quei che con lena affannata,<br>
- uscito fuor del pelago a la riva,<br>
- si volge a l'acqua perigliosa e guata,
- </p>
- <p>
- così l'animo mio, ch'ancor fuggiva,<br>
- si volse a retro a rimirar lo passo<br>
- che non lasciò già mai persona viva.
- </p>
- <p>
- Poi ch'èi posato un poco il corpo lasso,<br>
- ripresi via per la piaggia diserta,<br>
- sì che 'l piè fermo sempre era 'l più basso.
- </p>
- <p>
- Ed ecco, quasi al cominciar de l'erta,<br>
- una lonza leggiera e presta molto,<br>
- che di pel macolato era coverta;
- </p>
- <p>
- e non mi si partia dinanzi al volto,<br>
- anzi 'mpediva tanto il mio cammino,<br>
- ch'i' fui per ritornar più volte vòlto.
- </p>
- <p>
- Temp' era dal principio del mattino,<br>
- e 'l sol montava 'n sù con quelle stelle<br>
- ch'eran con lui quando l'amor divino
- </p>
- <p>
- mosse di prima quelle cose belle;<br>
- sì ch'a bene sperar m'era cagione<br>
- di quella fiera a la gaetta pelle
- </p>
- <p>
- l'ora del tempo e la dolce stagione;<br>
- ma non sì che paura non mi desse<br>
- la vista che m'apparve d'un leone.
- </p>
- <p>
- Questi parea che contra me venisse<br>
- con la test' alta e con rabbiosa fame,<br>
- sì che parea che l'aere ne tremesse.
- </p>
- <p>
- Ed una lupa, che di tutte brame<br>
- sembiava carca ne la sua magrezza,<br>
- e molte genti fé già viver grame,
- </p>
- <p>
- questa mi porse tanto di gravezza<br>
- con la paura ch'uscia di sua vista,<br>
- ch'io perdei la speranza de l'altezza.
- </p>
- <p>
- E qual è quei che volontieri acquista,<br>
- e giugne 'l tempo che perder lo face,<br>
- che 'n tutti suoi pensier piange e s'attrista;
- </p>
- <p>
- tal mi fece la bestia sanza pace,<br>
- che, venendomi 'ncontro, a poco a poco<br>
- mi ripigneva là dove 'l sol tace.
- </p>
- <p>
- Mentre ch'i' rovinava in basso loco,<br>
- dinanzi a li occhi mi si fu offerto<br>
- chi per lungo silenzio parea fioco.
- </p>
- <p>
- Quando vidi costui nel gran diserto,<br>
- «<em>Miserere</em> di me», gridai a lui,<br>
- «qual che tu sii, od ombra od omo certo!».
- </p>
- <p>
- Rispuosemi: «Non omo, omo già fui,<br>
- e li parenti miei furon lombardi,<br>
- mantoani per patrïa ambedui.
- </p>
- <p>
- Nacqui <em>sub Iulio</em>, ancor che fosse tardi,<br>
- e vissi a Roma sotto 'l buono Augusto<br>
- nel tempo de li dèi falsi e bugiardi.
- </p>
- <p>
- Poeta fui, e cantai di quel giusto<br>
- figliuol d'Anchise che venne di Troia,<br>
- poi che 'l superbo Ilïón fu combusto.
- </p>
- <p>
- Ma tu perché ritorni a tanta noia?<br>
- perché non sali il dilettoso monte<br>
- ch'è principio e cagion di tutta gioia?».
- </p>
- <p>
- «Or se' tu quel Virgilio e quella fonte<br>
- che spandi di parlar sì largo fiume?»,<br>
- rispuos' io lui con vergognosa fronte.
- </p>
- <p>
- «O de li altri poeti onore e lume,<br>
- vagliami 'l lungo studio e 'l grande amore<br>
- che m'ha fatto cercar lo tuo volume.
- </p>
- <p>
- Tu se' lo mio maestro e 'l mio autore,<br>
- tu se' solo colui da cu' io tolsi<br>
- lo bello stilo che m'ha fatto onore.
- </p>
- <p>
- Vedi la bestia per cu' io mi volsi;<br>
- aiutami da lei, famoso saggio,<br>
- ch'ella mi fa tremar le vene e i polsi».
- </p>
- <p>
- «A te convien tenere altro vïaggio»,<br>
- rispuose, poi che lagrimar mi vide,<br>
- «se vuo' campar d'esto loco selvaggio;
- </p>
- <p>
- ché questa bestia, per la qual tu gride,<br>
- non lascia altrui passar per la sua via,<br>
- ma tanto lo 'mpedisce che l'uccide;
- </p>
- <p>
- e ha natura sì malvagia e ria,<br>
- che mai non empie la bramosa voglia,<br>
- e dopo 'l pasto ha più fame che pria.
- </p>
- <p>
- Molti son li animali a cui s'ammoglia,<br>
- e più saranno ancora, infin che 'l veltro<br>
- verrà, che la farà morir con doglia.
- </p>
- <p>
- Questi non ciberà terra né peltro,<br>
- ma sapïenza, amore e virtute,<br>
- e sua nazion sarà tra feltro e feltro.
- </p>
- <p>
- Di quella umile Italia fia salute<br>
- per cui morì la vergine Cammilla,<br>
- Eurialo e Turno e Niso di ferute.
- </p>
- <p>
- Questi la caccerà per ogne villa,<br>
- fin che l'avrà rimessa ne lo 'nferno,<br>
- là onde 'nvidia prima dipartilla.
- </p>
- <p>
- Ond' io per lo tuo me' penso e discerno<br>
- che tu mi segui, e io sarò tua guida,<br>
- e trarrotti di qui per loco etterno;
- </p>
- <p>
- ove udirai le disperate strida,<br>
- vedrai li antichi spiriti dolenti,<br>
- ch'a la seconda morte ciascun grida;
- </p>
- <p>
- e vederai color che son contenti<br>
- nel foco, perché speran di venire<br>
- quando che sia a le beate genti.
- </p>
- <p>
- A le quai poi se tu vorrai salire,<br>
- anima fia a ciò più di me degna:<br>
- con lei ti lascerò nel mio partire;
- </p>
- <p>
- ché quello imperador che là sù regna,<br>
- perch' i' fu' ribellante a la sua legge,<br>
- non vuol che 'n sua città per me si vegna.
- </p>
- <p>
- In tutte parti impera e quivi regge;<br>
- quivi è la sua città e l'alto seggio:<br>
- oh felice colui cu' ivi elegge!».
- </p>
- <p>
- E io a lui: «Poeta, io ti richeggio<br>
- per quello Dio che tu non conoscesti,<br>
- a ciò ch'io fugga questo male e peggio,
- </p>
- <p>
- che tu mi meni là dov' or dicesti,<br>
- sì ch'io veggia la porta di san Pietro<br>
- e color cui tu fai cotanto mesti».
- </p>
- <p>
- Allor si mosse, e io li tenni dietro.
- </p>
-</body>
-</html>
diff --git a/toolkit/components/narrate/test/moby_dick.html b/toolkit/components/narrate/test/moby_dick.html
deleted file mode 100644
index 0beaa20fd..000000000
--- a/toolkit/components/narrate/test/moby_dick.html
+++ /dev/null
@@ -1,218 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<title>Moby Dick - Chapter 1. Loomings</title>
-</head>
-<body>
- <h1>Moby Dick</h1>
- <h2>Chapter 1. Loomings</h2>
- <p>
- Call me Ishmael. <span>Some <span>years</span></span> ago—never mind how
- long precisely—having little or no money in my purse, and nothing particular
- to interest me on shore, I thought I would sail about a little and see the
- watery part of the world. It is a way I have of driving off the spleen and
- regulating the circulation. Whenever I find myself growing grim about the
- mouth; whenever it is a damp, drizzly November in my soul; whenever I find
- myself involuntarily pausing before coffin warehouses, and bringing up the
- rear of every funeral I meet; and especially whenever my hypos get such an
- upper hand of me, that it requires a strong moral principle to prevent me
- from deliberately stepping into the street, and methodically knocking
- people's hats off—then, I account it high time to get to sea as soon as I
- can. This is my substitute for pistol and ball. With a philosophical
- flourish Cato throws himself upon his sword; I quietly take to the ship.
- There is nothing surprising in this. If they but knew it, almost all men in
- their degree, some time or other, cherish very nearly the same feelings
- towards the ocean with me.
- </p>
- <p>
- There now is your insular city of the Manhattoes, belted round by wharves
- as Indian isles by coral reefs—commerce surrounds it with her surf.
- Right and left, the streets take you waterward. Its extreme downtown is
- the battery, where that noble mole is washed by waves, and cooled by
- breezes, which a few hours previous were out of sight of land. Look at the
- crowds of water-gazers there.
- </p>
- <p>
- Circumambulate the city of a dreamy Sabbath afternoon. Go from Corlears
- Hook to Coenties Slip, and from thence, by Whitehall, northward. What do
- you see?—Posted like silent sentinels all around the town, stand
- thousands upon thousands of mortal men fixed in ocean reveries. Some
- leaning against the spiles; some seated upon the pier-heads; some looking
- over the bulwarks of ships from China; some high aloft in the rigging, as
- if striving to get a still better seaward peep. But these are all
- landsmen; of week days pent up in lath and plaster—tied to counters,
- nailed to benches, clinched to desks. How then is this? Are the green
- fields gone? What do they here?
- </p>
- <p>
- But look! here come more crowds, pacing straight for the water, and
- seemingly bound for a dive. Strange! Nothing will content them but the
- extremest limit of the land; loitering under the shady lee of yonder
- warehouses will not suffice. No. They must get just as nigh the water as
- they possibly can without falling in. And there they stand—miles of
- them—leagues. Inlanders all, they come from lanes and alleys,
- streets and avenues—north, east, south, and west. Yet here they all
- unite. Tell me, does the magnetic virtue of the needles of the compasses
- of all those ships attract them thither?
- </p>
- <p>
- Once more. Say you are in the country; in some high land of lakes. Take
- almost any path you please, and ten to one it carries you down in a dale,
- and leaves you there by a pool in the stream. There is magic in it. Let
- the most absent-minded of men be plunged in his deepest reveries—stand
- that man on his legs, set his feet a-going, and he will infallibly lead
- you to water, if water there be in all that region. Should you ever be
- athirst in the great American desert, try this experiment, if your caravan
- happen to be supplied with a metaphysical professor. Yes, as every one
- knows, meditation and water are wedded for ever.
- </p>
- <p>
- But here is an artist. He desires to paint you the dreamiest, shadiest,
- quietest, most enchanting bit of romantic landscape in all the valley of
- the Saco. What is the chief element he employs? There stand his trees,
- each with a hollow trunk, as if a hermit and a crucifix were within; and
- here sleeps his meadow, and there sleep his cattle; and up from yonder
- cottage goes a sleepy smoke. Deep into distant woodlands winds a mazy way,
- reaching to overlapping spurs of mountains bathed in their hill-side blue.
- But though the picture lies thus tranced, and though this pine-tree shakes
- down its sighs like leaves upon this shepherd's head, yet all were vain,
- unless the shepherd's eye were fixed upon the magic stream before him. Go
- visit the Prairies in June, when for scores on scores of miles you wade
- knee-deep among Tiger-lilies—what is the one charm wanting?—Water—there
- is not a drop of water there! Were Niagara but a cataract of sand, would
- you travel your thousand miles to see it? Why did the poor poet of
- Tennessee, upon suddenly receiving two handfuls of silver, deliberate
- whether to buy him a coat, which he sadly needed, or invest his money in a
- pedestrian trip to Rockaway Beach? Why is almost every robust healthy boy
- with a robust healthy soul in him, at some time or other crazy to go to
- sea? Why upon your first voyage as a passenger, did you yourself feel such
- a mystical vibration, when first told that you and your ship were now out
- of sight of land? Why did the old Persians hold the sea holy? Why did the
- Greeks give it a separate deity, and own brother of Jove? Surely all this
- is not without meaning. And still deeper the meaning of that story of
- Narcissus, who because he could not grasp the tormenting, mild image he
- saw in the fountain, plunged into it and was drowned. But that same image,
- we ourselves see in all rivers and oceans. It is the image of the
- ungraspable phantom of life; and this is the key to it all.
- </p>
- <p>
- Now, when I say that I am in the habit of going to sea whenever I begin to
- grow hazy about the eyes, and begin to be over conscious of my lungs, I do
- not mean to have it inferred that I ever go to sea as a passenger. For to
- go as a passenger you must needs have a purse, and a purse is but a rag
- unless you have something in it. Besides, passengers get sea-sick—grow
- quarrelsome—don't sleep of nights—do not enjoy themselves
- much, as a general thing;—no, I never go as a passenger; nor, though
- I am something of a salt, do I ever go to sea as a Commodore, or a
- Captain, or a Cook. I abandon the glory and distinction of such offices to
- those who like them. For my part, I abominate all honourable respectable
- toils, trials, and tribulations of every kind whatsoever. It is quite as
- much as I can do to take care of myself, without taking care of ships,
- barques, brigs, schooners, and what not. And as for going as cook,—though
- I confess there is considerable glory in that, a cook being a sort of
- officer on ship-board—yet, somehow, I never fancied broiling fowls;—though
- once broiled, judiciously buttered, and judgmatically salted and peppered,
- there is no one who will speak more respectfully, not to say
- reverentially, of a broiled fowl than I will. It is out of the idolatrous
- dotings of the old Egyptians upon broiled ibis and roasted river horse,
- that you see the mummies of those creatures in their huge bake-houses the
- pyramids.
- </p>
- <p>
- No, when I go to sea, I go as a simple sailor, right before the mast,
- plumb down into the forecastle, aloft there to the royal mast-head. True,
- they rather order me about some, and make me jump from spar to spar, like
- a grasshopper in a May meadow. And at first, this sort of thing is
- unpleasant enough. It touches one's sense of honour, particularly if you
- come of an old established family in the land, the Van Rensselaers, or
- Randolphs, or Hardicanutes. And more than all, if just previous to putting
- your hand into the tar-pot, you have been lording it as a country
- schoolmaster, making the tallest boys stand in awe of you. The transition
- is a keen one, I assure you, from a schoolmaster to a sailor, and requires
- a strong decoction of Seneca and the Stoics to enable you to grin and bear
- it. But even this wears off in time.
- </p>
- <p>
- What of it, if some old hunks of a sea-captain orders me to get a broom
- and sweep down the decks? What does that indignity amount to, weighed, I
- mean, in the scales of the New Testament? Do you think the archangel
- Gabriel thinks anything the less of me, because I promptly and
- respectfully obey that old hunks in that particular instance? Who ain't a
- slave? Tell me that. Well, then, however the old sea-captains may order me
- about—however they may thump and punch me about, I have the
- satisfaction of knowing that it is all right; that everybody else is one
- way or other served in much the same way—either in a physical or
- metaphysical point of view, that is; and so the universal thump is passed
- round, and all hands should rub each other's shoulder-blades, and be
- content.
- </p>
- <p>
- Again, I always go to sea as a sailor, because they make a point of paying
- me for my trouble, whereas they never pay passengers a single penny that I
- ever heard of. On the contrary, passengers themselves must pay. And there
- is all the difference in the world between paying and being paid. The act
- of paying is perhaps the most uncomfortable infliction that the two
- orchard thieves entailed upon us. But <i>being paid</i>,—what will compare
- with it? The urbane activity with which a man receives money is really
- marvellous, considering that we so earnestly believe money to be the root
- of all earthly ills, and that on no account can a monied man enter heaven.
- Ah! how cheerfully we consign ourselves to perdition!
- </p>
- <p>
- Finally, I always go to sea as a sailor, because of the wholesome exercise
- and pure air of the fore-castle deck. For as in this world, head winds are
- far more prevalent than winds from astern (that is, if you never violate
- the Pythagorean maxim), so for the most part the Commodore on the
- quarter-deck gets his atmosphere at second hand from the sailors on the
- forecastle. He thinks he breathes it first; but not so. In much the same
- way do the commonalty lead their leaders in many other things, at the same
- time that the leaders little suspect it. But wherefore it was that after
- having repeatedly smelt the sea as a merchant sailor, I should now take it
- into my head to go on a whaling voyage; this the invisible police officer
- of the Fates, who has the constant surveillance of me, and secretly dogs
- me, and influences me in some unaccountable way—he can better answer
- than any one else. And, doubtless, my going on this whaling voyage, formed
- part of the grand programme of Providence that was drawn up a long time
- ago. It came in as a sort of brief interlude and solo between more
- extensive performances. I take it that this part of the bill must have run
- something like this:
- </p>
- <p>
- "<i>Grand Contested Election for the Presidency of the United States.</i>
- "WHALING VOYAGE BY ONE ISHMAEL. "BLOODY BATTLE IN AFFGHANISTAN."
- </p>
- <p>
- Though I cannot tell why it was exactly that those stage managers, the
- Fates, put me down for this shabby part of a whaling voyage, when others
- were set down for magnificent parts in high tragedies, and short and easy
- parts in genteel comedies, and jolly parts in farces—though I cannot
- tell why this was exactly; yet, now that I recall all the circumstances, I
- think I can see a little into the springs and motives which being
- cunningly presented to me under various disguises, induced me to set about
- performing the part I did, besides cajoling me into the delusion that it
- was a choice resulting from my own unbiased freewill and discriminating
- judgment.
- </p>
- <p>
- Chief among these motives was the overwhelming idea of the great whale
- himself. Such a portentous and mysterious monster roused all my curiosity.
- Then the wild and distant seas where he rolled his island bulk; the
- undeliverable, nameless perils of the whale; these, with all the attending
- marvels of a thousand Patagonian sights and sounds, helped to sway me to
- my wish. With other men, perhaps, such things would not have been
- inducements; but as for me, I am tormented with an everlasting itch for
- things remote. I love to sail forbidden seas, and land on barbarous
- coasts. Not ignoring what is good, I am quick to perceive a horror, and
- could still be social with it—would they let me—since it is
- but well to be on friendly terms with all the inmates of the place one
- lodges in.
- </p>
- <p>
- By reason of these things, then, the whaling voyage was welcome; the great
- flood-gates of the wonder-world swung open, and in the wild conceits that
- swayed me to my purpose, two and two there floated into my inmost soul,
- endless processions of the whale, and, mid most of them all, one grand
- hooded phantom, like a snow hill in the air.
- </p>
-</body>
-</html>
diff --git a/toolkit/components/osfile/moz.build b/toolkit/components/osfile/moz.build
index d17da2d60..e407ea3c7 100644
--- a/toolkit/components/osfile/moz.build
+++ b/toolkit/components/osfile/moz.build
@@ -4,32 +4,16 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-DIRS += [
- 'modules',
-]
-
-MOCHITEST_CHROME_MANIFESTS += ['tests/mochi/chrome.ini']
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
-SOURCES += [
- 'NativeOSFileInternals.cpp',
-]
+DIRS += ['modules']
XPIDL_MODULE = 'toolkit_osfile'
-XPIDL_SOURCES += [
- 'nsINativeOSFileInternals.idl',
-]
+XPIDL_SOURCES += ['nsINativeOSFileInternals.idl']
-EXPORTS.mozilla += [
- 'NativeOSFileInternals.h',
-]
+EXPORTS.mozilla += ['NativeOSFileInternals.h']
-EXTRA_PP_JS_MODULES += [
- 'osfile.jsm',
-]
+SOURCES += ['NativeOSFileInternals.cpp']
-FINAL_LIBRARY = 'xul'
+EXTRA_PP_JS_MODULES += ['osfile.jsm']
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'OS.File')
+FINAL_LIBRARY = 'xul'
diff --git a/toolkit/components/osfile/tests/mochi/.eslintrc.js b/toolkit/components/osfile/tests/mochi/.eslintrc.js
deleted file mode 100644
index 8c0f4f574..000000000
--- a/toolkit/components/osfile/tests/mochi/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/osfile/tests/mochi/chrome.ini b/toolkit/components/osfile/tests/mochi/chrome.ini
deleted file mode 100644
index 1da463316..000000000
--- a/toolkit/components/osfile/tests/mochi/chrome.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-skip-if = os == 'android'
-support-files =
- main_test_osfile_async.js
- worker_handler.js
- worker_test_osfile_comms.js
- worker_test_osfile_front.js
- worker_test_osfile_shared.js
- worker_test_osfile_unix.js
- worker_test_osfile_win.js
-
-[test_osfile_async.xul]
-[test_osfile_back.xul]
-[test_osfile_comms.xul]
-[test_osfile_front.xul]
diff --git a/toolkit/components/osfile/tests/mochi/main_test_osfile_async.js b/toolkit/components/osfile/tests/mochi/main_test_osfile_async.js
deleted file mode 100644
index b940a032a..000000000
--- a/toolkit/components/osfile/tests/mochi/main_test_osfile_async.js
+++ /dev/null
@@ -1,443 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Promise.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-Components.utils.import("resource://gre/modules/AsyncShutdown.jsm");
-
-// The following are used to compare against a well-tested reference
-// implementation of file I/O.
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/FileUtils.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-var myok = ok;
-var myis = is;
-var myinfo = info;
-var myisnot = isnot;
-
-var isPromise = function ispromise(value) {
- return value != null && typeof value == "object" && "then" in value;
-};
-
-var maketest = function(prefix, test) {
- let utils = {
- ok: function ok(t, m) {
- myok(t, prefix + ": " + m);
- },
- is: function is(l, r, m) {
- myis(l, r, prefix + ": " + m);
- },
- isnot: function isnot(l, r, m) {
- myisnot(l, r, prefix + ": " + m);
- },
- info: function info(m) {
- myinfo(prefix + ": " + m);
- },
- fail: function fail(m) {
- utils.ok(false, m);
- },
- okpromise: function okpromise(t, m) {
- return t.then(
- function onSuccess() {
- util.ok(true, m);
- },
- function onFailure() {
- util.ok(false, m);
- }
- );
- }
- };
- return function runtest() {
- utils.info("Entering");
- try {
- let result = test.call(this, utils);
- if (!isPromise(result)) {
- throw new TypeError("The test did not return a promise");
- }
- utils.info("This was a promise");
- // The test returns a promise
- result = result.then(function test_complete() {
- utils.info("Complete");
- }, function catch_uncaught_errors(err) {
- utils.fail("Uncaught error " + err);
- if (err && typeof err == "object" && "message" in err) {
- utils.fail("(" + err.message + ")");
- }
- if (err && typeof err == "object" && "stack" in err) {
- utils.fail("at " + err.stack);
- }
- });
- return result;
- } catch (x) {
- utils.fail("Error " + x + " at " + x.stack);
- return null;
- }
- };
-};
-
-/**
- * Fetch asynchronously the contents of a file using xpcom.
- *
- * Used for comparing xpcom-based results to os.file-based results.
- *
- * @param {string} path The _absolute_ path to the file.
- * @return {promise}
- * @resolves {string} The contents of the file.
- */
-var reference_fetch_file = function reference_fetch_file(path, test) {
- test.info("Fetching file " + path);
- let promise = Promise.defer();
- let file = new FileUtils.File(path);
- NetUtil.asyncFetch({
- uri: NetUtil.newURI(file),
- loadUsingSystemPrincipal: true
- }, function(stream, status) {
- if (!Components.isSuccessCode(status)) {
- promise.reject(status);
- return;
- }
- let result, reject;
- try {
- result = NetUtil.readInputStreamToString(stream, stream.available());
- } catch (x) {
- reject = x;
- }
- stream.close();
- if (reject) {
- promise.reject(reject);
- } else {
- promise.resolve(result);
- }
- });
-
- return promise.promise;
-};
-
-/**
- * Compare asynchronously the contents two files using xpcom.
- *
- * Used for comparing xpcom-based results to os.file-based results.
- *
- * @param {string} a The _absolute_ path to the first file.
- * @param {string} b The _absolute_ path to the second file.
- *
- * @resolves {null}
- */
-var reference_compare_files = function reference_compare_files(a, b, test) {
- test.info("Comparing files " + a + " and " + b);
- let a_contents = yield reference_fetch_file(a, test);
- let b_contents = yield reference_fetch_file(b, test);
- is(a_contents, b_contents, "Contents of files " + a + " and " + b + " match");
-};
-
-var reference_dir_contents = function reference_dir_contents(path) {
- let result = [];
- let entries = new FileUtils.File(path).directoryEntries;
- while (entries.hasMoreElements()) {
- let entry = entries.getNext().QueryInterface(Components.interfaces.nsILocalFile);
- result.push(entry.path);
- }
- return result;
-};
-
-// Set/Unset OS.Shared.DEBUG, OS.Shared.TEST and a console listener.
-function toggleDebugTest (pref, consoleListener) {
- Services.prefs.setBoolPref("toolkit.osfile.log", pref);
- Services.prefs.setBoolPref("toolkit.osfile.log.redirect", pref);
- Services.console[pref ? "registerListener" : "unregisterListener"](
- consoleListener);
-}
-
-var test = maketest("Main", function main(test) {
- return Task.spawn(function() {
- SimpleTest.waitForExplicitFinish();
- yield test_stat();
- yield test_debug();
- yield test_info_features_detect();
- yield test_position();
- yield test_iter();
- yield test_exists();
- yield test_debug_test();
- info("Test is over");
- SimpleTest.finish();
- });
-});
-
-/**
- * A file that we know exists and that can be used for reading.
- */
-var EXISTING_FILE = OS.Path.join("chrome", "toolkit", "components",
- "osfile", "tests", "mochi", "main_test_osfile_async.js");
-
-/**
- * Test OS.File.stat and OS.File.prototype.stat
- */
-var test_stat = maketest("stat", function stat(test) {
- return Task.spawn(function() {
- // Open a file and stat it
- let file = yield OS.File.open(EXISTING_FILE);
- let stat1;
-
- try {
- test.info("Stating file");
- stat1 = yield file.stat();
- test.ok(true, "stat has worked " + stat1);
- test.ok(stat1, "stat is not empty");
- } finally {
- yield file.close();
- }
-
- // Stat the same file without opening it
- test.info("Stating a file without opening it");
- let stat2 = yield OS.File.stat(EXISTING_FILE);
- test.ok(true, "stat 2 has worked " + stat2);
- test.ok(stat2, "stat 2 is not empty");
- for (let key in stat2) {
- test.is("" + stat1[key], "" + stat2[key], "Stat field " + key + "is the same");
- }
- });
-});
-
-/**
- * Test feature detection using OS.File.Info.prototype on main thread
- */
-var test_info_features_detect = maketest("features_detect", function features_detect(test) {
- return Task.spawn(function() {
- if (OS.Constants.Win) {
- // see if winBirthDate is defined
- if ("winBirthDate" in OS.File.Info.prototype) {
- test.ok(true, "winBirthDate is defined");
- } else {
- test.fail("winBirthDate not defined though we are under Windows");
- }
- } else if (OS.Constants.libc) {
- // see if unixGroup is defined
- if ("unixGroup" in OS.File.Info.prototype) {
- test.ok(true, "unixGroup is defined");
- } else {
- test.fail("unixGroup is not defined though we are under Unix");
- }
- }
- });
-});
-
-/**
- * Test file.{getPosition, setPosition}
- */
-var test_position = maketest("position", function position(test) {
- return Task.spawn(function() {
- let file = yield OS.File.open(EXISTING_FILE);
-
- try {
- let view = yield file.read();
- test.info("First batch of content read");
- let CHUNK_SIZE = 178;// An arbitrary number of bytes to read from the file
- let pos = yield file.getPosition();
- test.info("Obtained position");
- test.is(pos, view.byteLength, "getPosition returned the end of the file");
- pos = yield file.setPosition(-CHUNK_SIZE, OS.File.POS_END);
- test.info("Changed position");
- test.is(pos, view.byteLength - CHUNK_SIZE, "setPosition returned the correct position");
-
- let view2 = yield file.read();
- test.info("Read the end of the file");
- for (let i = 0; i < CHUNK_SIZE; ++i) {
- if (view2[i] != view[i + view.byteLength - CHUNK_SIZE]) {
- test.is(view2[i], view[i], "setPosition put us in the right position");
- }
- }
- } finally {
- yield file.close();
- }
- });
-});
-
-/**
- * Test OS.File.prototype.{DirectoryIterator}
- */
-var test_iter = maketest("iter", function iter(test) {
- return Task.spawn(function() {
- let currentDir = yield OS.File.getCurrentDirectory();
-
- // Trivial walks through the directory
- test.info("Preparing iteration");
- let iterator = new OS.File.DirectoryIterator(currentDir);
- let temporary_file_name = OS.Path.join(currentDir, "empty-temporary-file.tmp");
- try {
- yield OS.File.remove(temporary_file_name);
- } catch (err) {
- // Ignore errors removing file
- }
- let allFiles1 = yield iterator.nextBatch();
- test.info("Obtained all files through nextBatch");
- test.isnot(allFiles1.length, 0, "There is at least one file");
- test.isnot(allFiles1[0].path, null, "Files have a path");
-
- // Ensure that we have the same entries with |reference_dir_contents|
- let referenceEntries = new Set();
- for (let entry of reference_dir_contents(currentDir)) {
- referenceEntries.add(entry);
- }
- test.is(referenceEntries.size, allFiles1.length, "All the entries in the directory have been listed");
- for (let entry of allFiles1) {
- test.ok(referenceEntries.has(entry.path), "File " + entry.path + " effectively exists");
- // Ensure that we have correct isDir and isSymLink
- // Current directory is {objdir}/_tests/testing/mochitest/, assume it has some dirs and symlinks.
- var f = new FileUtils.File(entry.path);
- test.is(entry.isDir, f.isDirectory(), "Get file " + entry.path + " isDir correctly");
- test.is(entry.isSymLink, f.isSymlink(), "Get file " + entry.path + " isSymLink correctly");
- }
-
- yield iterator.close();
- test.info("Closed iterator");
-
- test.info("Double closing DirectoryIterator");
- iterator = new OS.File.DirectoryIterator(currentDir);
- yield iterator.close();
- yield iterator.close(); //double closing |DirectoryIterator|
- test.ok(true, "|DirectoryIterator| was closed twice successfully");
-
- let allFiles2 = [];
- let i = 0;
- iterator = new OS.File.DirectoryIterator(currentDir);
- yield iterator.forEach(function(entry, index) {
- test.is(i++, index, "Getting the correct index");
- allFiles2.push(entry);
- });
- test.info("Obtained all files through forEach");
- is(allFiles1.length, allFiles2.length, "Both runs returned the same number of files");
- for (let i = 0; i < allFiles1.length; ++i) {
- if (allFiles1[i].path != allFiles2[i].path) {
- test.is(allFiles1[i].path, allFiles2[i].path, "Both runs return the same files");
- break;
- }
- }
-
- // Testing batch iteration + whether an iteration can be stopped early
- let BATCH_LENGTH = 10;
- test.info("Getting some files through nextBatch");
- yield iterator.close();
-
- iterator = new OS.File.DirectoryIterator(currentDir);
- let someFiles1 = yield iterator.nextBatch(BATCH_LENGTH);
- let someFiles2 = yield iterator.nextBatch(BATCH_LENGTH);
- yield iterator.close();
-
- iterator = new OS.File.DirectoryIterator(currentDir);
- yield iterator.forEach(function cb(entry, index, iterator) {
- if (index < BATCH_LENGTH) {
- test.is(entry.path, someFiles1[index].path, "Both runs return the same files (part 1)");
- } else if (index < 2*BATCH_LENGTH) {
- test.is(entry.path, someFiles2[index - BATCH_LENGTH].path, "Both runs return the same files (part 2)");
- } else if (index == 2 * BATCH_LENGTH) {
- test.info("Attempting to stop asynchronous forEach");
- return iterator.close();
- } else {
- test.fail("Can we stop an asynchronous forEach? " + index);
- }
- return null;
- });
- yield iterator.close();
-
- // Ensuring that we find new files if they appear
- let file = yield OS.File.open(temporary_file_name, { write: true } );
- file.close();
- iterator = new OS.File.DirectoryIterator(currentDir);
- try {
- let files = yield iterator.nextBatch();
- is(files.length, allFiles1.length + 1, "The directory iterator has noticed the new file");
- let exists = yield iterator.exists();
- test.ok(exists, "After nextBatch, iterator detects that the directory exists");
- } finally {
- yield iterator.close();
- }
-
- // Ensuring that opening a non-existing directory fails consistently
- // once iteration starts.
- try {
- iterator = null;
- iterator = new OS.File.DirectoryIterator("/I do not exist");
- let exists = yield iterator.exists();
- test.ok(!exists, "Before any iteration, iterator detects that the directory doesn't exist");
- let exn = null;
- try {
- yield iterator.next();
- } catch (ex if ex instanceof OS.File.Error && ex.becauseNoSuchFile) {
- exn = ex;
- let exists = yield iterator.exists();
- test.ok(!exists, "After one iteration, iterator detects that the directory doesn't exist");
- }
- test.ok(exn, "Iterating through a directory that does not exist has failed with becauseNoSuchFile");
- } finally {
- if (iterator) {
- iterator.close();
- }
- }
- test.ok(!!iterator, "The directory iterator for a non-existing directory was correctly created");
- });
-});
-
-/**
- * Test OS.File.prototype.{exists}
- */
-var test_exists = maketest("exists", function exists(test) {
- return Task.spawn(function() {
- let fileExists = yield OS.File.exists(EXISTING_FILE);
- test.ok(fileExists, "file exists");
- fileExists = yield OS.File.exists(EXISTING_FILE + ".tmp");
- test.ok(!fileExists, "file does not exists");
- });
-});
-
-/**
- * Test changes to OS.Shared.DEBUG flag.
- */
-var test_debug = maketest("debug", function debug(test) {
- return Task.spawn(function() {
- function testSetDebugPref (pref) {
- try {
- Services.prefs.setBoolPref("toolkit.osfile.log", pref);
- } catch (x) {
- test.fail("Setting OS.Shared.DEBUG to " + pref +
- " should not cause error.");
- } finally {
- test.is(OS.Shared.DEBUG, pref, "OS.Shared.DEBUG is set correctly.");
- }
- }
- testSetDebugPref(true);
- let workerDEBUG = yield OS.File.GET_DEBUG();
- test.is(workerDEBUG, true, "Worker's DEBUG is set.");
- testSetDebugPref(false);
- workerDEBUG = yield OS.File.GET_DEBUG();
- test.is(workerDEBUG, false, "Worker's DEBUG is unset.");
- });
-});
-
-/**
- * Test logging in the main thread with set OS.Shared.DEBUG and
- * OS.Shared.TEST flags.
- */
-var test_debug_test = maketest("debug_test", function debug_test(test) {
- return Task.spawn(function () {
- // Create a console listener.
- let consoleListener = {
- observe: function (aMessage) {
- // Ignore unexpected messages.
- if (!(aMessage instanceof Components.interfaces.nsIConsoleMessage)) {
- return;
- }
- if (aMessage.message.indexOf("TEST OS") < 0) {
- return;
- }
- test.ok(true, "DEBUG TEST messages are logged correctly.");
- }
- };
- toggleDebugTest(true, consoleListener);
- // Execution of OS.File.exist method will trigger OS.File.LOG several times.
- let fileExists = yield OS.File.exists(EXISTING_FILE);
- toggleDebugTest(false, consoleListener);
- });
-});
-
-
diff --git a/toolkit/components/osfile/tests/mochi/test_osfile_async.xul b/toolkit/components/osfile/tests/mochi/test_osfile_async.xul
deleted file mode 100644
index 1ef103f02..000000000
--- a/toolkit/components/osfile/tests/mochi/test_osfile_async.xul
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0"?>
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<window title="Testing async I/O with OS.File"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
- <script type="application/javascript"
- src="main_test_osfile_async.js"/>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
- <label id="test-result"/>
-</window>
diff --git a/toolkit/components/osfile/tests/mochi/test_osfile_back.xul b/toolkit/components/osfile/tests/mochi/test_osfile_back.xul
deleted file mode 100644
index b6af6303f..000000000
--- a/toolkit/components/osfile/tests/mochi/test_osfile_back.xul
+++ /dev/null
@@ -1,46 +0,0 @@
-<?xml version="1.0"?>
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<window title="Testing OS.File on a chrome worker thread"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
- <script type="application/javascript"
- src="worker_handler.js"/>
- <script type="application/javascript">
- <![CDATA[
-
-let worker;
-
-function test() {
- ok(true, "test_osfile.xul: Starting test");
- if (navigator.platform.indexOf("Win") != -1) {
- ok(true, "test_osfile.xul: Using Windows test suite");
- worker = new ChromeWorker("worker_test_osfile_win.js");
- } else {
- ok(true, "test_osfile.xul: Using Unix test suite");
- worker = new ChromeWorker("worker_test_osfile_unix.js");
- }
- SimpleTest.waitForExplicitFinish();
- ok(true, "test_osfile.xul: Chrome worker created");
- dump("MAIN: go\n");
- worker_handler(worker);
- worker.postMessage(0);
- ok(true, "test_osfile.xul: Test in progress");
-};
-]]>
- </script>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
- <label id="test-result"/>
-</window>
diff --git a/toolkit/components/osfile/tests/mochi/test_osfile_comms.xul b/toolkit/components/osfile/tests/mochi/test_osfile_comms.xul
deleted file mode 100644
index 88e474ce2..000000000
--- a/toolkit/components/osfile/tests/mochi/test_osfile_comms.xul
+++ /dev/null
@@ -1,84 +0,0 @@
-<?xml version="1.0"?>
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<window title="Testing OS.File on a chrome worker thread"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
- <script type="application/javascript">
- <![CDATA[
-
-"use strict";
-
-let worker;
-
-let test = function test() {
- SimpleTest.info("test_osfile_comms.xul: Starting test");
- Components.utils.import("resource://gre/modules/ctypes.jsm");
- Components.utils.import("resource://gre/modules/osfile.jsm");
- worker = new ChromeWorker("worker_test_osfile_comms.js");
- SimpleTest.waitForExplicitFinish();
- try {
- worker.onerror = function onerror(error) {
- SimpleTest.ok(false, "received error "+error);
- }
- worker.onmessage = function onmessage(msg) {
- Components.utils.forceShrinkingGC();
- switch (msg.data.kind) {
- case "is":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- " ("+ msg.data.a + " ==? " + msg.data.b + ")" );
- return;
- case "isnot":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- " ("+ msg.data.a + " !=? " + msg.data.b + ")" );
- return;
- case "ok":
- SimpleTest.ok(msg.data.condition, msg.data.description);
- return;
- case "info":
- SimpleTest.info(msg.data.description);
- return;
- case "finish":
- SimpleTest.finish();
- return;
- case "value":
- SimpleTest.ok(true, "test_osfile_comms.xul: Received value " + JSON.stringify(msg.data.value));
- let type = eval(msg.data.typename);
- let check = eval(msg.data.check);
- let value = msg.data.value;
- let deserialized = type.fromMsg(value);
- check(deserialized, "Main thread test: ");
- return;
- default:
- SimpleTest.ok(false, "test_osfile_comms.xul: wrong message "+JSON.stringify(msg.data));
- return;
- }
- };
- worker.postMessage(0)
- ok(true, "Worker launched");
- } catch(x) {
- // As we have set |waitForExplicitFinish|, we add this fallback
- // in case of uncaught error, to ensure that the test does not
- // just freeze.
- ok(false, "Caught exception " + x + " at " + x.stack);
- SimpleTest.finish();
- }
-};
-
-]]>
- </script>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
- <label id="test-result"/>
-</window>
diff --git a/toolkit/components/osfile/tests/mochi/test_osfile_front.xul b/toolkit/components/osfile/tests/mochi/test_osfile_front.xul
deleted file mode 100644
index 10d3fbd01..000000000
--- a/toolkit/components/osfile/tests/mochi/test_osfile_front.xul
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0"?>
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<window title="Testing OS.File on a chrome worker thread"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
- <script type="application/javascript"
- src="worker_handler.js"/>
- <script type="application/javascript">
- <![CDATA[
-
-let worker;
-let main = this;
-
-function test() {
- info("test_osfile_front.xul: Starting test");
-
- // Test the OS.File worker
-
- worker = new ChromeWorker("worker_test_osfile_front.js");
- SimpleTest.waitForExplicitFinish();
- info("test_osfile_front.xul: Chrome worker created");
- dump("MAIN: go\n");
- worker_handler(worker);
- worker.postMessage(0);
- ok(true, "test_osfile_front.xul: Test in progress");
-};
-]]>
- </script>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
- <label id="test-result"/>
-</window>
diff --git a/toolkit/components/osfile/tests/mochi/worker_handler.js b/toolkit/components/osfile/tests/mochi/worker_handler.js
deleted file mode 100644
index 6c513e6ba..000000000
--- a/toolkit/components/osfile/tests/mochi/worker_handler.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function worker_handler(worker) {
- worker.onerror = function(error) {
- error.preventDefault();
- ok(false, "Worker error " + error.message);
- }
- worker.onmessage = function(msg) {
- ok(true, "MAIN: onmessage " + JSON.stringify(msg.data));
- switch (msg.data.kind) {
- case "is":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- "( "+ msg.data.a + " ==? " + msg.data.b + ")" );
- return;
- case "isnot":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- "( "+ msg.data.a + " !=? " + msg.data.b + ")" );
- return;
- case "ok":
- SimpleTest.ok(msg.data.condition, msg.data.description);
- return;
- case "info":
- SimpleTest.info(msg.data.description);
- return;
- case "finish":
- SimpleTest.finish();
- return;
- default:
- SimpleTest.ok(false, "test_osfile.xul: wrong message " + JSON.stringify(msg.data));
- return;
- }
- };
-}
diff --git a/toolkit/components/osfile/tests/mochi/worker_test_osfile_comms.js b/toolkit/components/osfile/tests/mochi/worker_test_osfile_comms.js
deleted file mode 100644
index 5e8bdd9ca..000000000
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_comms.js
+++ /dev/null
@@ -1,145 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-importScripts('worker_test_osfile_shared.js');
-
-// The set of samples for communications test. Declare as a global
-// variable to prevent this from being garbage-collected too early.
-var samples;
-
-self.onmessage = function(msg) {
- info("Initializing");
- self.onmessage = function on_unexpected_message(msg) {
- throw new Error("Unexpected message " + JSON.stringify(msg.data));
- };
- importScripts("resource://gre/modules/osfile.jsm");
- info("Initialization complete");
-
- samples = [
- { typename: "OS.Shared.Type.char.in_ptr",
- valuedescr: "String",
- value: "This is a test",
- type: OS.Shared.Type.char.in_ptr,
- check: function check_string(candidate, prefix) {
- is(candidate, "This is a test", prefix);
- }},
- { typename: "OS.Shared.Type.char.in_ptr",
- valuedescr: "Typed array",
- value: (function() {
- let view = new Uint8Array(15);
- for (let i = 0; i < 15; ++i) {
- view[i] = i;
- }
- return view;
- })(),
- type: OS.Shared.Type.char.in_ptr,
- check: function check_ArrayBuffer(candidate, prefix) {
- for (let i = 0; i < 15; ++i) {
- is(candidate[i], i % 256, prefix + "Checking that the contents of the ArrayBuffer were preserved");
- }
- }},
- { typename: "OS.Shared.Type.char.in_ptr",
- valuedescr: "Pointer",
- value: new OS.Shared.Type.char.in_ptr.implementation(1),
- type: OS.Shared.Type.char.in_ptr,
- check: function check_ptr(candidate, prefix) {
- let address = ctypes.cast(candidate, ctypes.uintptr_t).value.toString();
- is(address, "1", prefix + "Checking that the pointer address was preserved");
- }},
- { typename: "OS.Shared.Type.char.in_ptr",
- valuedescr: "C array",
- value: (function() {
- let buf = new (ctypes.ArrayType(ctypes.uint8_t, 15))();
- for (let i = 0; i < 15; ++i) {
- buf[i] = i % 256;
- }
- return buf;
- })(),
- type: OS.Shared.Type.char.in_ptr,
- check: function check_array(candidate, prefix) {
- let cast = ctypes.cast(candidate, ctypes.uint8_t.ptr);
- for (let i = 0; i < 15; ++i) {
- is(cast.contents, i % 256, prefix + "Checking that the contents of the C array were preserved, index " + i);
- cast = cast.increment();
- }
- }
- },
- { typename: "OS.File.Error",
- valuedescr: "OS Error",
- type: OS.File.Error,
- value: new OS.File.Error("foo", 1),
- check: function check_error(candidate, prefix) {
- ok(candidate instanceof OS.File.Error,
- prefix + "Error is an OS.File.Error");
- ok(candidate.unixErrno == 1 || candidate.winLastError == 1,
- prefix + "Error code is correct");
- try {
- let string = candidate.toString();
- info(prefix + ".toString() works " + string);
- } catch (x) {
- ok(false, prefix + ".toString() fails " + x);
- }
- }
- }
- ];
- samples.forEach(function test(sample) {
- let type = sample.type;
- let value = sample.value;
- let check = sample.check;
- info("Testing handling of type " + sample.typename + " communicating " + sample.valuedescr);
-
- // 1. Test serialization
- let serialized;
- let exn;
- try {
- serialized = type.toMsg(value);
- } catch (ex) {
- exn = ex;
- }
- is(exn, null, "Can I serialize the following value? " + value +
- " aka " + JSON.stringify(value));
- if (exn) {
- return;
- }
-
- if ("data" in serialized) {
- // Unwrap from `Meta`
- serialized = serialized.data;
- }
-
- // 2. Test deserialization
- let deserialized;
- try {
- deserialized = type.fromMsg(serialized);
- } catch (ex) {
- exn = ex;
- }
- is(exn, null, "Can I deserialize the following message? " + serialized
- + " aka " + JSON.stringify(serialized));
- if (exn) {
- return;
- }
-
- // 3. Local test deserialized value
- info("Running test on deserialized value " + deserialized +
- " aka " + JSON.stringify(deserialized));
- check(deserialized, "Local test: ");
-
- // 4. Test sending serialized
- info("Attempting to send message");
- try {
- self.postMessage({kind:"value",
- typename: sample.typename,
- value: serialized,
- check: check.toSource()});
- } catch (ex) {
- exn = ex;
- }
- is(exn, null, "Can I send the following message? " + serialized
- + " aka " + JSON.stringify(serialized));
- });
-
- finish();
- };
diff --git a/toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js b/toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js
deleted file mode 100644
index 29e613510..000000000
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js
+++ /dev/null
@@ -1,566 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-importScripts('worker_test_osfile_shared.js');
-importScripts("resource://gre/modules/workers/require.js");
-
-var SharedAll = require("resource://gre/modules/osfile/osfile_shared_allthreads.jsm");
-SharedAll.Config.DEBUG = true;
-
-function should_throw(f) {
- try {
- f();
- } catch (x) {
- return x;
- }
- return null;
-}
-
-self.onmessage = function onmessage_start(msg) {
- self.onmessage = function onmessage_ignored(msg) {
- log("ignored message " + JSON.stringify(msg.data));
- };
- try {
- test_init();
- test_open_existing_file();
- test_open_non_existing_file();
- test_flush_open_file();
- test_copy_existing_file();
- test_position();
- test_move_file();
- test_iter_dir();
- test_info();
- test_path();
- test_exists_file();
- test_remove_file();
- } catch (x) {
- log("Catching error: " + x);
- log("Stack: " + x.stack);
- log("Source: " + x.toSource());
- ok(false, x.toString() + "\n" + x.stack);
- }
- finish();
-};
-
-function test_init() {
- info("Starting test_init");
- importScripts("resource://gre/modules/osfile.jsm");
-}
-
-/**
- * Test that we can open an existing file.
- */
-function test_open_existing_file()
-{
- info("Starting test_open_existing");
- let file = OS.File.open("chrome/toolkit/components/osfile/tests/mochi/worker_test_osfile_unix.js");
- file.close();
-}
-
-/**
- * Test that opening a file that does not exist fails with the right error.
- */
-function test_open_non_existing_file()
-{
- info("Starting test_open_non_existing");
- let exn;
- try {
- let file = OS.File.open("/I do not exist");
- } catch (x) {
- exn = x;
- info("test_open_non_existing_file: Exception detail " + exn);
- }
- ok(!!exn, "test_open_non_existing_file: Exception was raised ");
- ok(exn instanceof OS.File.Error, "test_open_non_existing_file: Exception was a OS.File.Error");
- ok(exn.becauseNoSuchFile, "test_open_non_existing_file: Exception confirms that the file does not exist");
-}
-
-/**
- * Test that to ensure that |foo.flush()| does not
- * cause an error, where |foo| is an open file.
- */
-function test_flush_open_file()
-{
- info("Starting test_flush_open_file");
- let tmp = "test_flush.tmp";
- let file = OS.File.open(tmp, {create: true, write: true});
- file.flush();
- file.close();
- OS.File.remove(tmp);
-}
-
-/**
- * Utility function for comparing two files (or a prefix of two files).
- *
- * This function returns nothing but fails of both files (or prefixes)
- * are not identical.
- *
- * @param {string} test The name of the test (used for logging).
- * @param {string} sourcePath The name of the first file.
- * @param {string} destPath The name of the second file.
- * @param {number=} prefix If specified, only compare the |prefix|
- * first bytes of |sourcePath| and |destPath|.
- */
-function compare_files(test, sourcePath, destPath, prefix)
-{
- info(test + ": Comparing " + sourcePath + " and " + destPath);
- let source = OS.File.open(sourcePath);
- let dest = OS.File.open(destPath);
- info("Files are open");
- let sourceResult, destResult;
- try {
- if (prefix != undefined) {
- sourceResult = source.read(prefix);
- destResult = dest.read(prefix);
- } else {
- sourceResult = source.read();
- destResult = dest.read();
- }
- is(sourceResult.length, destResult.length, test + ": Both files have the same size");
- for (let i = 0; i < sourceResult.length; ++i) {
- if (sourceResult[i] != destResult[i]) {
- is(sourceResult[i] != destResult[i], test + ": Comparing char " + i);
- break;
- }
- }
- } finally {
- source.close();
- dest.close();
- }
- info(test + ": Comparison complete");
-}
-
-/**
- * Test that copying a file using |copy| works.
- */
-function test_copy_existing_file()
-{
- let src_file_name =
- OS.Path.join("chrome", "toolkit", "components", "osfile", "tests", "mochi",
- "worker_test_osfile_front.js");
- let tmp_file_name = "test_osfile_front.tmp";
- info("Starting test_copy_existing");
- OS.File.copy(src_file_name, tmp_file_name);
-
- info("test_copy_existing: Copy complete");
- compare_files("test_copy_existing", src_file_name, tmp_file_name);
-
- // Create a bogus file with arbitrary content, then attempt to overwrite
- // it with |copy|.
- let dest = OS.File.open(tmp_file_name, {trunc: true});
- let buf = new Uint8Array(50);
- dest.write(buf);
- dest.close();
-
- OS.File.copy(src_file_name, tmp_file_name);
-
- compare_files("test_copy_existing 2", src_file_name, tmp_file_name);
-
- // Attempt to overwrite with noOverwrite
- let exn;
- try {
- OS.File.copy(src_file_name, tmp_file_name, {noOverwrite: true});
- } catch(x) {
- exn = x;
- }
- ok(!!exn, "test_copy_existing: noOverwrite prevents overwriting existing files");
-
- info("test_copy_existing: Cleaning up");
- OS.File.remove(tmp_file_name);
-}
-
-/**
- * Test that moving a file works.
- */
-function test_move_file()
-{
- info("test_move_file: Starting");
- // 1. Copy file into a temporary file
- let src_file_name =
- OS.Path.join("chrome", "toolkit", "components", "osfile", "tests", "mochi",
- "worker_test_osfile_front.js");
- let tmp_file_name = "test_osfile_front.tmp";
- let tmp2_file_name = "test_osfile_front.tmp2";
- OS.File.copy(src_file_name, tmp_file_name);
-
- info("test_move_file: Copy complete");
-
- // 2. Move
- OS.File.move(tmp_file_name, tmp2_file_name);
-
- info("test_move_file: Move complete");
-
- // 3. Check that destination exists
- compare_files("test_move_file", src_file_name, tmp2_file_name);
-
- // 4. Check that original file does not exist anymore
- let exn;
- try {
- OS.File.open(tmp_file_name);
- } catch (x) {
- exn = x;
- }
- ok(!!exn, "test_move_file: Original file has been removed");
-
- info("test_move_file: Cleaning up");
- OS.File.remove(tmp2_file_name);
-}
-
-function test_iter_dir()
-{
- info("test_iter_dir: Starting");
-
- // Create a file, to be sure that it exists
- let tmp_file_name = "test_osfile_front.tmp";
- let tmp_file = OS.File.open(tmp_file_name, {write: true, trunc:true});
- tmp_file.close();
-
- let parent = OS.File.getCurrentDirectory();
- info("test_iter_dir: directory " + parent);
- let iterator = new OS.File.DirectoryIterator(parent);
- info("test_iter_dir: iterator created");
- let encountered_tmp_file = false;
- for (let entry in iterator) {
- // Checking that |name| can be decoded properly
- info("test_iter_dir: encountering entry " + entry.name);
-
- if (entry.name == tmp_file_name) {
- encountered_tmp_file = true;
- isnot(entry.isDir, "test_iter_dir: The temporary file is not a directory");
- isnot(entry.isSymLink, "test_iter_dir: The temporary file is not a link");
- }
-
- let file;
- let success = true;
- try {
- file = OS.File.open(entry.path);
- } catch (x) {
- if (x.becauseNoSuchFile) {
- success = false;
- }
- }
- if (file) {
- file.close();
- }
- ok(success, "test_iter_dir: Entry " + entry.path + " exists");
-
- if (OS.Win) {
- // We assume that the files are at least as recent as 2009.
- // Since this test was written in 2011 and some of our packaging
- // sets dates arbitrarily to 2010, this should be safe.
- let year = new Date().getFullYear();
- let creation = entry.winCreationDate;
- ok(creation, "test_iter_dir: Windows creation date exists: " + creation);
- ok(creation.getFullYear() >= 2009 && creation.getFullYear() <= year, "test_iter_dir: consistent creation date");
-
- let lastWrite = entry.winLastWriteDate;
- ok(lastWrite, "test_iter_dir: Windows lastWrite date exists: " + lastWrite);
- ok(lastWrite.getFullYear() >= 2009 && lastWrite.getFullYear() <= year, "test_iter_dir: consistent lastWrite date");
-
- let lastAccess = entry.winLastAccessDate;
- ok(lastAccess, "test_iter_dir: Windows lastAccess date exists: " + lastAccess);
- ok(lastAccess.getFullYear() >= 2009 && lastAccess.getFullYear() <= year, "test_iter_dir: consistent lastAccess date");
- }
-
- }
- ok(encountered_tmp_file, "test_iter_dir: We have found the temporary file");
-
- info("test_iter_dir: Cleaning up");
- iterator.close();
-
- // Testing nextBatch()
- iterator = new OS.File.DirectoryIterator(parent);
- let allentries = [];
- for (let x in iterator) {
- allentries.push(x);
- }
- iterator.close();
-
- ok(allentries.length >= 14, "test_iter_dir: Meta-check: the test directory should contain at least 14 items");
-
- iterator = new OS.File.DirectoryIterator(parent);
- let firstten = iterator.nextBatch(10);
- is(firstten.length, 10, "test_iter_dir: nextBatch(10) returns 10 items");
- for (let i = 0; i < firstten.length; ++i) {
- is(allentries[i].path, firstten[i].path, "test_iter_dir: Checking that batch returns the correct entries");
- }
- let nextthree = iterator.nextBatch(3);
- is(nextthree.length, 3, "test_iter_dir: nextBatch(3) returns 3 items");
- for (let i = 0; i < nextthree.length; ++i) {
- is(allentries[i + firstten.length].path, nextthree[i].path, "test_iter_dir: Checking that batch 2 returns the correct entries");
- }
- let everythingelse = iterator.nextBatch();
- ok(everythingelse.length >= 1, "test_iter_dir: nextBatch() returns at least one item");
- for (let i = 0; i < everythingelse.length; ++i) {
- is(allentries[i + firstten.length + nextthree.length].path, everythingelse[i].path, "test_iter_dir: Checking that batch 3 returns the correct entries");
- }
- is(iterator.nextBatch().length, 0, "test_iter_dir: Once there is nothing left, nextBatch returns an empty array");
- iterator.close();
-
- iterator = new OS.File.DirectoryIterator(parent);
- iterator.close();
- is(iterator.nextBatch().length, 0, "test_iter_dir: nextBatch on closed iterator returns an empty array");
-
- iterator = new OS.File.DirectoryIterator(parent);
- let allentries2 = iterator.nextBatch();
- is(allentries.length, allentries2.length, "test_iter_dir: Checking that getBatch(null) returns the right number of entries");
- for (let i = 0; i < allentries.length; ++i) {
- is(allentries[i].path, allentries2[i].path, "test_iter_dir: Checking that getBatch(null) returns everything in the right order");
- }
- iterator.close();
-
- // Test forEach
- iterator = new OS.File.DirectoryIterator(parent);
- let index = 0;
- iterator.forEach(
- function cb(entry, aIndex, aIterator) {
- is(index, aIndex, "test_iter_dir: Checking that forEach index is correct");
- ok(iterator == aIterator, "test_iter_dir: Checking that right iterator is passed");
- if (index < 10) {
- is(allentries[index].path, entry.path, "test_iter_dir: Checking that forEach entry is correct");
- } else if (index == 10) {
- iterator.close();
- } else {
- ok(false, "test_iter_dir: Checking that forEach can be stopped early");
- }
- ++index;
- });
- iterator.close();
-
- //test for prototype |OS.File.DirectoryIterator.unixAsFile|
- if ("unixAsFile" in OS.File.DirectoryIterator.prototype) {
- info("testing property unixAsFile");
- let path = OS.Path.join("chrome", "toolkit", "components", "osfile", "tests", "mochi");
- iterator = new OS.File.DirectoryIterator(path);
-
- let dir_file = iterator.unixAsFile();// return |File|
- let stat0 = dir_file.stat();
- let stat1 = OS.File.stat(path);
-
- let unix_info_to_string = function unix_info_to_string(info) {
- return "| " + info.unixMode + " | " + info.unixOwner + " | " + info.unixGroup + " | " + info.creationDate + " | " + info.lastModificationDate + " | " + info.lastAccessDate + " | " + info.size + " |";
- };
-
- let s0_string = unix_info_to_string(stat0);
- let s1_string = unix_info_to_string(stat1);
-
- ok(stat0.isDir, "unixAsFile returned a directory");
- is(s0_string, s1_string, "unixAsFile returned the correct file");
- dir_file.close();
- iterator.close();
- }
- info("test_iter_dir: Complete");
-}
-
-function test_position() {
- info("test_position: Starting");
-
- ok("POS_START" in OS.File, "test_position: POS_START exists");
- ok("POS_CURRENT" in OS.File, "test_position: POS_CURRENT exists");
- ok("POS_END" in OS.File, "test_position: POS_END exists");
-
- let ARBITRARY_POSITION = 321;
- let src_file_name =
- OS.Path.join("chrome", "toolkit", "components", "osfile", "tests", "mochi",
- "worker_test_osfile_front.js");
-
- let file = OS.File.open(src_file_name);
- is(file.getPosition(), 0, "test_position: Initial position is 0");
-
- let size = 0 + file.stat().size; // Hack: We can remove this 0 + once 776259 has landed
-
- file.setPosition(ARBITRARY_POSITION, OS.File.POS_START);
- is(file.getPosition(), ARBITRARY_POSITION, "test_position: Setting position from start");
-
- file.setPosition(0, OS.File.POS_START);
- is(file.getPosition(), 0, "test_position: Setting position from start back to 0");
-
- file.setPosition(ARBITRARY_POSITION);
- is(file.getPosition(), ARBITRARY_POSITION, "test_position: Setting position without argument");
-
- file.setPosition(-ARBITRARY_POSITION, OS.File.POS_END);
- is(file.getPosition(), size - ARBITRARY_POSITION, "test_position: Setting position from end");
-
- file.setPosition(ARBITRARY_POSITION, OS.File.POS_CURRENT);
- is(file.getPosition(), size, "test_position: Setting position from current");
-
- file.close();
- info("test_position: Complete");
-}
-
-function test_info() {
- info("test_info: Starting");
-
- let filename = "test_info.tmp";
- let size = 261;// An arbitrary file length
- let start = new Date();
-
- // Cleanup any leftover from previous tests
- try {
- OS.File.remove(filename);
- info("test_info: Cleaned up previous garbage");
- } catch (x) {
- if (!x.becauseNoSuchFile) {
- throw x;
- }
- info("test_info: No previous garbage");
- }
-
- let file = OS.File.open(filename, {trunc: true});
- let buf = new ArrayBuffer(size);
- file._write(buf, size);
- file.close();
-
- // Test OS.File.stat on new file
- let stat = OS.File.stat(filename);
- ok(!!stat, "test_info: info acquired");
- ok(!stat.isDir, "test_info: file is not a directory");
- is(stat.isSymLink, false, "test_info: file is not a link");
- is(stat.size.toString(), size, "test_info: correct size");
-
- let stop = new Date();
-
- // We round down/up by 1s as file system precision is lower than
- // Date precision (no clear specifications about that, but it seems
- // that this can be a little over 1 second under ext3 and 2 seconds
- // under FAT).
- let SLOPPY_FILE_SYSTEM_ADJUSTMENT = 3000;
- let startMs = start.getTime() - SLOPPY_FILE_SYSTEM_ADJUSTMENT;
- let stopMs = stop.getTime() + SLOPPY_FILE_SYSTEM_ADJUSTMENT;
- info("Testing stat with bounds [ " + startMs + ", " + stopMs +" ]");
-
- (function() {
- let birth;
- if ("winBirthDate" in stat) {
- birth = stat.winBirthDate;
- } else if ("macBirthDate" in stat) {
- birth = stat.macBirthDate;
- } else {
- ok(true, "Skipping birthdate test");
- return;
- }
- ok(birth.getTime() <= stopMs,
- "test_info: platformBirthDate is consistent");
- // Note: Previous versions of this test checked whether the file
- // has been created after the start of the test. Unfortunately,
- // this sometimes failed under Windows, in specific circumstances:
- // if the file has been removed at the start of the test and
- // recreated immediately, the Windows file system detects this and
- // decides that the file was actually truncated rather than
- // recreated, hence that it should keep its previous creation
- // date. Debugging hilarity ensues.
- });
-
- let change = stat.lastModificationDate;
- info("Testing lastModificationDate: " + change);
- ok(change.getTime() >= startMs && change.getTime() <= stopMs,
- "test_info: lastModificationDate is consistent");
-
- // Test OS.File.prototype.stat on new file
- file = OS.File.open(filename);
- try {
- stat = file.stat();
- } finally {
- file.close();
- }
-
- ok(!!stat, "test_info: info acquired 2");
- ok(!stat.isDir, "test_info: file is not a directory 2");
- ok(!stat.isSymLink, "test_info: file is not a link 2");
- is(stat.size.toString(), size, "test_info: correct size 2");
-
- stop = new Date();
-
- // Round up/down as above
- startMs = start.getTime() - SLOPPY_FILE_SYSTEM_ADJUSTMENT;
- stopMs = stop.getTime() + SLOPPY_FILE_SYSTEM_ADJUSTMENT;
- info("Testing stat 2 with bounds [ " + startMs + ", " + stopMs +" ]");
-
- let access = stat.lastAccessDate;
- info("Testing lastAccessDate: " + access);
- ok(access.getTime() >= startMs && access.getTime() <= stopMs,
- "test_info: lastAccessDate is consistent");
-
- change = stat.lastModificationDate;
- info("Testing lastModificationDate 2: " + change);
- ok(change.getTime() >= startMs && change.getTime() <= stopMs,
- "test_info: lastModificationDate 2 is consistent");
-
- // Test OS.File.stat on directory
- stat = OS.File.stat(OS.File.getCurrentDirectory());
- ok(!!stat, "test_info: info on directory acquired");
- ok(stat.isDir, "test_info: directory is a directory");
-
- info("test_info: Complete");
-}
-
-// Note that most of the features of path are tested in
-// worker_test_osfile_{unix, win}.js
-function test_path()
-{
- info("test_path: starting");
- let abcd = OS.Path.join("a", "b", "c", "d");
- is(OS.Path.basename(abcd), "d", "basename of a/b/c/d");
-
- let abc = OS.Path.join("a", "b", "c");
- is(OS.Path.dirname(abcd), abc, "dirname of a/b/c/d");
-
- let abdotsc = OS.Path.join("a", "b", "..", "c");
- is(OS.Path.normalize(abdotsc), OS.Path.join("a", "c"), "normalize a/b/../c");
-
- let adotsdotsdots = OS.Path.join("a", "..", "..", "..");
- is(OS.Path.normalize(adotsdotsdots), OS.Path.join("..", ".."), "normalize a/../../..");
-
- info("test_path: Complete");
-}
-
-/**
- * Test the file |exists| method.
- */
-function test_exists_file()
-{
- let file_name = OS.Path.join("chrome", "toolkit", "components" ,"osfile",
- "tests", "mochi", "test_osfile_front.xul");
- info("test_exists_file: starting");
- ok(OS.File.exists(file_name), "test_exists_file: file exists (OS.File.exists)");
- ok(!OS.File.exists(file_name + ".tmp"), "test_exists_file: file does not exists (OS.File.exists)");
-
- let dir_name = OS.Path.join("chrome", "toolkit", "components" ,"osfile",
- "tests", "mochi");
- ok(OS.File.exists(dir_name), "test_exists_file: directory exists");
- ok(!OS.File.exists(dir_name) + ".tmp", "test_exists_file: directory does not exist");
-
- info("test_exists_file: complete");
-}
-
-/**
- * Test the file |remove| method.
- */
-function test_remove_file()
-{
- let absent_file_name = "test_osfile_front_absent.tmp";
-
- // Check that removing absent files is handled correctly
- let exn = should_throw(function() {
- OS.File.remove(absent_file_name, {ignoreAbsent: false});
- });
- ok(!!exn, "test_remove_file: throws if there is no such file");
-
- exn = should_throw(function() {
- OS.File.remove(absent_file_name, {ignoreAbsent: true});
- OS.File.remove(absent_file_name);
- });
- ok(!exn, "test_remove_file: ignoreAbsent works");
-
- if (OS.Win) {
- let file_name = "test_osfile_front_file_to_remove.tmp";
- let file = OS.File.open(file_name, {write: true});
- file.close();
- ok(OS.File.exists(file_name), "test_remove_file: test file exists");
- OS.Win.File.SetFileAttributes(file_name,
- OS.Constants.Win.FILE_ATTRIBUTE_READONLY);
- OS.File.remove(file_name);
- ok(!OS.File.exists(file_name),
- "test_remove_file: test file has been removed");
- }
-}
diff --git a/toolkit/components/osfile/tests/mochi/worker_test_osfile_shared.js b/toolkit/components/osfile/tests/mochi/worker_test_osfile_shared.js
deleted file mode 100644
index da82d4b0a..000000000
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_shared.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function log(text) {
- dump("WORKER " + text + "\n");
-}
-
-function send(message) {
- self.postMessage(message);
-}
-
-function finish() {
- send({kind: "finish"});
-}
-
-function ok(condition, description) {
- send({kind: "ok", condition: !!condition, description: "" + description});
-}
-
-function is(a, b, description) {
- let outcome = a == b; // Need to decide outcome here, as not everything can be serialized
- send({kind: "is", outcome: outcome, description: "" + description, a: "" + a, b: "" + b});
-}
-
-function isnot(a, b, description) {
- let outcome = a != b; // Need to decide outcome here, as not everything can be serialized
- send({kind: "isnot", outcome: outcome, description: "" + description, a: "" + a, b: "" + b});
-}
-
-function info(description) {
- send({kind: "info", description: "" + description});
-}
diff --git a/toolkit/components/osfile/tests/mochi/worker_test_osfile_unix.js b/toolkit/components/osfile/tests/mochi/worker_test_osfile_unix.js
deleted file mode 100644
index 9fe2d0b4e..000000000
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_unix.js
+++ /dev/null
@@ -1,201 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-importScripts('worker_test_osfile_shared.js');
-
-self.onmessage = function(msg) {
- log("received message "+JSON.stringify(msg.data));
- self.onmessage = function(msg) {
- log("ignored message "+JSON.stringify(msg.data));
- };
- test_init();
- test_getcwd();
- test_open_close();
- test_create_file();
- test_access();
- test_read_write();
- test_passing_undefined();
- finish();
-};
-
-function test_init() {
- info("Starting test_init");
- importScripts("resource://gre/modules/osfile.jsm");
-}
-
-function test_open_close() {
- info("Starting test_open_close");
- is(typeof OS.Unix.File.open, "function", "OS.Unix.File.open is a function");
- let file = OS.Unix.File.open("chrome/toolkit/components/osfile/tests/mochi/worker_test_osfile_unix.js", OS.Constants.libc.O_RDONLY, 0);
- isnot(file, -1, "test_open_close: opening succeeded");
- info("Close: "+OS.Unix.File.close.toSource());
- let result = OS.Unix.File.close(file);
- is(result, 0, "test_open_close: close succeeded");
-
- file = OS.Unix.File.open("/i do not exist", OS.Constants.libc.O_RDONLY, 0);
- is(file, -1, "test_open_close: opening of non-existing file failed");
- is(ctypes.errno, OS.Constants.libc.ENOENT, "test_open_close: error is ENOENT");
-}
-
-function test_create_file()
-{
- info("Starting test_create_file");
- let file = OS.Unix.File.open("test.tmp", OS.Constants.libc.O_RDWR
- | OS.Constants.libc.O_CREAT
- | OS.Constants.libc.O_TRUNC,
- OS.Constants.libc.S_IRWXU);
- isnot(file, -1, "test_create_file: file created");
- OS.Unix.File.close(file);
-}
-
-function test_access()
-{
- info("Starting test_access");
- let file = OS.Unix.File.open("test1.tmp", OS.Constants.libc.O_RDWR
- | OS.Constants.libc.O_CREAT
- | OS.Constants.libc.O_TRUNC,
- OS.Constants.libc.S_IRWXU);
- let result = OS.Unix.File.access("test1.tmp", OS.Constants.libc.R_OK | OS.Constants.libc.W_OK | OS.Constants.libc.X_OK | OS.Constants.libc.F_OK);
- is(result, 0, "first call to access() succeeded");
- OS.Unix.File.close(file);
-
- file = OS.Unix.File.open("test1.tmp", OS.Constants.libc.O_WRONLY
- | OS.Constants.libc.O_CREAT
- | OS.Constants.libc.O_TRUNC,
- OS.Constants.libc.S_IWUSR);
-
- info("test_access: preparing second call to access()");
- result = OS.Unix.File.access("test2.tmp", OS.Constants.libc.R_OK
- | OS.Constants.libc.W_OK
- | OS.Constants.libc.X_OK
- | OS.Constants.libc.F_OK);
- is(result, -1, "test_access: second call to access() failed as expected");
- is(ctypes.errno, OS.Constants.libc.ENOENT, "This is the correct error");
- OS.Unix.File.close(file);
-}
-
-function test_getcwd()
-{
- let array = new (ctypes.ArrayType(ctypes.char, 32768))();
- let path = OS.Unix.File.getcwd(array, array.length);
- if (ctypes.char.ptr(path).isNull()) {
- ok(false, "test_get_cwd: getcwd returned null, errno: " + ctypes.errno);
- }
- let path2;
- if (OS.Unix.File.get_current_dir_name) {
- path2 = OS.Unix.File.get_current_dir_name();
- } else {
- path2 = OS.Unix.File.getwd_auto(null);
- }
- if (ctypes.char.ptr(path2).isNull()) {
- ok(false, "test_get_cwd: getwd_auto/get_current_dir_name returned null, errno: " + ctypes.errno);
- }
- is(path.readString(), path2.readString(), "test_get_cwd: getcwd and getwd return the same path");
-}
-
-function test_read_write()
-{
- let output_name = "osfile_copy.tmp";
- // Copy file
- let input = OS.Unix.File.open(
- "chrome/toolkit/components/osfile/tests/mochi/worker_test_osfile_unix.js",
- OS.Constants.libc.O_RDONLY, 0);
- isnot(input, -1, "test_read_write: input file opened");
- let output = OS.Unix.File.open("osfile_copy.tmp", OS.Constants.libc.O_RDWR
- | OS.Constants.libc.O_CREAT
- | OS.Constants.libc.O_TRUNC,
- OS.Constants.libc.S_IRWXU);
- isnot(output, -1, "test_read_write: output file opened");
-
- let array = new (ctypes.ArrayType(ctypes.char, 4096))();
- let bytes = -1;
- let total = 0;
- while (true) {
- bytes = OS.Unix.File.read(input, array, 4096);
- ok(bytes != undefined, "test_read_write: bytes is defined");
- isnot(bytes, -1, "test_read_write: no read error");
- let write_from = 0;
- if (bytes == 0) {
- break;
- }
- while (bytes > 0) {
- let ptr = array.addressOfElement(write_from);
- // Note: |write| launches an exception in case of error
- let written = OS.Unix.File.write(output, array, bytes);
- isnot(written, -1, "test_read_write: no write error");
- write_from += written;
- bytes -= written;
- }
- total += write_from;
- }
- info("test_read_write: copy complete " + total);
-
- // Compare files
- let result;
- info("SEEK_SET: " + OS.Constants.libc.SEEK_SET);
- info("Input: " + input + "(" + input.toSource() + ")");
- info("Output: " + output + "(" + output.toSource() + ")");
- result = OS.Unix.File.lseek(input, 0, OS.Constants.libc.SEEK_SET);
- info("Result of lseek: " + result);
- isnot(result, -1, "test_read_write: input seek succeeded " + ctypes.errno);
- result = OS.Unix.File.lseek(output, 0, OS.Constants.libc.SEEK_SET);
- isnot(result, -1, "test_read_write: output seek succeeded " + ctypes.errno);
-
- let array2 = new (ctypes.ArrayType(ctypes.char, 4096))();
- let bytes2 = -1;
- let pos = 0;
- while (true) {
- bytes = OS.Unix.File.read(input, array, 4096);
- isnot(bytes, -1, "test_read_write: input read succeeded");
- bytes2 = OS.Unix.File.read(output, array2, 4096);
- isnot(bytes, -1, "test_read_write: output read succeeded");
- is(bytes > 0, bytes2 > 0, "Both files contain data or neither does "+bytes+", "+bytes2);
- if (bytes == 0) {
- break;
- }
- if (bytes != bytes2) {
- // This would be surprising, but theoretically possible with a
- // remote file system, I believe.
- bytes = Math.min(bytes, bytes2);
- pos += bytes;
- result = OS.Unix.File.lseek(input, pos, OS.Constants.libc.SEEK_SET);
- isnot(result, -1, "test_read_write: input seek succeeded");
- result = OS.Unix.File.lseek(output, pos, OS.Constants.libc.SEEK_SET);
- isnot(result, -1, "test_read_write: output seek succeeded");
- } else {
- pos += bytes;
- }
- for (let i = 0; i < bytes; ++i) {
- if (array[i] != array2[i]) {
- ok(false, "Files do not match at position " + i
- + " ("+array[i] + "/"+array2[i] + ")");
- }
- }
- }
- info("test_read_write test complete");
- result = OS.Unix.File.close(input);
- isnot(result, -1, "test_read_write: input close succeeded");
- result = OS.Unix.File.close(output);
- isnot(result, -1, "test_read_write: output close succeeded");
- result = OS.Unix.File.unlink(output_name);
- isnot(result, -1, "test_read_write: input remove succeeded");
- info("test_read_write cleanup complete");
-}
-
-function test_passing_undefined()
-{
- info("Testing that an exception gets thrown when an FFI function is passed undefined");
- let exceptionRaised = false;
-
- try {
- let file = OS.Unix.File.open(undefined, OS.Constants.libc.O_RDWR
- | OS.Constants.libc.O_CREAT
- | OS.Constants.libc.O_TRUNC,
- OS.Constants.libc.S_IRWXU);
- } catch(e if e instanceof TypeError && e.message.indexOf("open") > -1) {
- exceptionRaised = true;
- }
-
- ok(exceptionRaised, "test_passing_undefined: exception gets thrown")
-}
-
diff --git a/toolkit/components/osfile/tests/mochi/worker_test_osfile_win.js b/toolkit/components/osfile/tests/mochi/worker_test_osfile_win.js
deleted file mode 100644
index f41fdecfe..000000000
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_win.js
+++ /dev/null
@@ -1,211 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-importScripts('worker_test_osfile_shared.js');
-
-self.onmessage = function(msg) {
- self.onmessage = function(msg) {
- log("ignored message "+JSON.stringify(msg.data));
- };
-
- test_init();
- test_GetCurrentDirectory();
- test_OpenClose();
- test_CreateFile();
- test_ReadWrite();
- test_passing_undefined();
- finish();
-};
-
-function test_init() {
- info("Starting test_init");
- importScripts("resource://gre/modules/osfile.jsm");
-}
-
-function test_OpenClose() {
- info("Starting test_OpenClose");
- is(typeof OS.Win.File.CreateFile, "function", "OS.Win.File.CreateFile is a function");
- is(OS.Win.File.CloseHandle(OS.Constants.Win.INVALID_HANDLE_VALUE), true, "CloseHandle returns true given the invalid handle");
- is(OS.Win.File.FindClose(OS.Constants.Win.INVALID_HANDLE_VALUE), true, "FindClose returns true given the invalid handle");
- isnot(OS.Constants.Win.GENERIC_READ, undefined, "GENERIC_READ exists");
- isnot(OS.Constants.Win.FILE_SHARE_READ, undefined, "FILE_SHARE_READ exists");
- isnot(OS.Constants.Win.FILE_ATTRIBUTE_NORMAL, undefined, "FILE_ATTRIBUTE_NORMAL exists");
- let file = OS.Win.File.CreateFile(
- "chrome\\toolkit\\components\\osfile\\tests\\mochi\\worker_test_osfile_win.js",
- OS.Constants.Win.GENERIC_READ,
- 0,
- null,
- OS.Constants.Win.OPEN_EXISTING,
- 0,
- null);
- info("test_OpenClose: Passed open");
- isnot(file, OS.Constants.Win.INVALID_HANDLE_VALUE, "test_OpenClose: file opened");
- let result = OS.Win.File.CloseHandle(file);
- isnot(result, 0, "test_OpenClose: close succeeded");
-
- file = OS.Win.File.CreateFile(
- "\\I do not exist",
- OS.Constants.Win.GENERIC_READ,
- OS.Constants.Win.FILE_SHARE_READ,
- null,
- OS.Constants.Win.OPEN_EXISTING,
- OS.Constants.Win.FILE_ATTRIBUTE_NORMAL,
- null);
- is(file, OS.Constants.Win.INVALID_HANDLE_VALUE, "test_OpenClose: cannot open non-existing file");
- is(ctypes.winLastError, OS.Constants.Win.ERROR_FILE_NOT_FOUND, "test_OpenClose: error is ERROR_FILE_NOT_FOUND");
-}
-
-function test_CreateFile()
-{
- info("Starting test_CreateFile");
- let file = OS.Win.File.CreateFile(
- "test.tmp",
- OS.Constants.Win.GENERIC_READ | OS.Constants.Win.GENERIC_WRITE,
- OS.Constants.Win.FILE_SHARE_READ | OS.Constants.FILE_SHARE_WRITE,
- null,
- OS.Constants.Win.CREATE_ALWAYS,
- OS.Constants.Win.FILE_ATTRIBUTE_NORMAL,
- null);
- isnot(file, OS.Constants.Win.INVALID_HANDLE_VALUE, "test_CreateFile: opening succeeded");
- let result = OS.Win.File.CloseHandle(file);
- isnot(result, 0, "test_CreateFile: close succeeded");
-}
-
-function test_GetCurrentDirectory()
-{
- let array = new (ctypes.ArrayType(ctypes.char16_t, 4096))();
- let result = OS.Win.File.GetCurrentDirectory(4096, array);
- ok(result < array.length, "test_GetCurrentDirectory: length sufficient");
- ok(result > 0, "test_GetCurrentDirectory: length != 0");
-}
-
-function test_ReadWrite()
-{
- info("Starting test_ReadWrite");
- let output_name = "osfile_copy.tmp";
- // Copy file
- let input = OS.Win.File.CreateFile(
- "chrome\\toolkit\\components\\osfile\\tests\\mochi\\worker_test_osfile_win.js",
- OS.Constants.Win.GENERIC_READ,
- 0,
- null,
- OS.Constants.Win.OPEN_EXISTING,
- 0,
- null);
- isnot(input, OS.Constants.Win.INVALID_HANDLE_VALUE, "test_ReadWrite: input file opened");
- let output = OS.Win.File.CreateFile(
- "osfile_copy.tmp",
- OS.Constants.Win.GENERIC_READ | OS.Constants.Win.GENERIC_WRITE,
- 0,
- null,
- OS.Constants.Win.CREATE_ALWAYS,
- OS.Constants.Win.FILE_ATTRIBUTE_NORMAL,
- null);
- isnot(output, OS.Constants.Win.INVALID_HANDLE_VALUE, "test_ReadWrite: output file opened");
- let array = new (ctypes.ArrayType(ctypes.char, 4096))();
- let bytes_read = new ctypes.uint32_t(0);
- let bytes_read_ptr = bytes_read.address();
- log("We have a pointer for bytes read: "+bytes_read_ptr);
- let bytes_written = new ctypes.uint32_t(0);
- let bytes_written_ptr = bytes_written.address();
- log("We have a pointer for bytes written: "+bytes_written_ptr);
- log("test_ReadWrite: buffer and pointers ready");
- let result;
- while (true) {
- log("test_ReadWrite: reading");
- result = OS.Win.File.ReadFile(input, array, 4096, bytes_read_ptr, null);
- isnot (result, 0, "test_ReadWrite: read success");
- let write_from = 0;
- let bytes_left = bytes_read;
- log("test_ReadWrite: read chunk complete " + bytes_left.value);
- if (bytes_left.value == 0) {
- break;
- }
- while (bytes_left.value > 0) {
- log("test_ReadWrite: writing "+bytes_left.value);
- let ptr = array.addressOfElement(write_from);
- // Note: |WriteFile| launches an exception in case of error
- result = OS.Win.File.WriteFile(output, array, bytes_left, bytes_written_ptr, null);
- isnot (result, 0, "test_ReadWrite: write success");
- write_from += bytes_written;
- bytes_left -= bytes_written;
- }
- }
- info("test_ReadWrite: copy complete");
-
- // Compare files
- result = OS.Win.File.SetFilePointer(input, 0, null, OS.Constants.Win.FILE_BEGIN);
- isnot (result, OS.Constants.Win.INVALID_SET_FILE_POINTER, "test_ReadWrite: input reset");
-
- result = OS.Win.File.SetFilePointer(output, 0, null, OS.Constants.Win.FILE_BEGIN);
- isnot (result, OS.Constants.Win.INVALID_SET_FILE_POINTER, "test_ReadWrite: output reset");
-
- let array2 = new (ctypes.ArrayType(ctypes.char, 4096))();
- let bytes_read2 = new ctypes.uint32_t(0);
- let bytes_read2_ptr = bytes_read2.address();
- let pos = 0;
- while (true) {
- result = OS.Win.File.ReadFile(input, array, 4096, bytes_read_ptr, null);
- isnot(result, 0, "test_ReadWrite: input read succeeded");
-
- result = OS.Win.File.ReadFile(output, array2, 4096, bytes_read2_ptr, null);
- isnot(result, 0, "test_ReadWrite: output read succeeded");
-
- is(bytes_read.value > 0, bytes_read2.value > 0,
- "Both files contain data or neither does " + bytes_read.value + ", " + bytes_read2.value);
- if (bytes_read.value == 0) {
- break;
- }
- let bytes;
- if (bytes_read.value != bytes_read2.value) {
- // This would be surprising, but theoretically possible with a
- // remote file system, I believe.
- bytes = Math.min(bytes_read.value, bytes_read2.value);
- pos += bytes;
- result = OS.Win.File.SetFilePointer(input, pos, null, OS.Constants.Win.FILE_BEGIN);
- isnot(result, 0, "test_ReadWrite: input seek succeeded");
-
- result = OS.Win.File.SetFilePointer(output, pos, null, OS.Constants.Win.FILE_BEGIN);
- isnot(result, 0, "test_ReadWrite: output seek succeeded");
-
- } else {
- bytes = bytes_read.value;
- pos += bytes;
- }
- for (let i = 0; i < bytes; ++i) {
- if (array[i] != array2[i]) {
- ok(false, "Files do not match at position " + i
- + " ("+array[i] + "/"+array2[i] + ")");
- }
- }
- }
- info("test_ReadWrite test complete");
- result = OS.Win.File.CloseHandle(input);
- isnot(result, 0, "test_ReadWrite: inpout close succeeded");
- result = OS.Win.File.CloseHandle(output);
- isnot(result, 0, "test_ReadWrite: outpout close succeeded");
- result = OS.Win.File.DeleteFile(output_name);
- isnot(result, 0, "test_ReadWrite: output remove succeeded");
- info("test_ReadWrite cleanup complete");
-}
-
-function test_passing_undefined()
-{
- info("Testing that an exception gets thrown when an FFI function is passed undefined");
- let exceptionRaised = false;
-
- try {
- let file = OS.Win.File.CreateFile(
- undefined,
- OS.Constants.Win.GENERIC_READ,
- 0,
- null,
- OS.Constants.Win.OPEN_EXISTING,
- 0,
- null);
- } catch(e if e instanceof TypeError && e.message.indexOf("CreateFile") > -1) {
- exceptionRaised = true;
- }
-
- ok(exceptionRaised, "test_passing_undefined: exception gets thrown")
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/.eslintrc.js b/toolkit/components/osfile/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/osfile/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/osfile/tests/xpcshell/head.js b/toolkit/components/osfile/tests/xpcshell/head.js
deleted file mode 100644
index eef29962a..000000000
--- a/toolkit/components/osfile/tests/xpcshell/head.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {utils: Cu, interfaces: Ci} = Components;
-
-var {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
-
-// Bug 1014484 can only be reproduced by loading OS.File first from the
-// CommonJS loader, so we do not want OS.File to be loaded eagerly for
-// all the tests in this directory.
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Services",
- "resource://gre/modules/Services.jsm");
-
-var {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
-var {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
-
-Services.prefs.setBoolPref("toolkit.osfile.log", true);
-
-/**
- * As add_task, but execute the test both with native operations and
- * without.
- */
-function add_test_pair(generator) {
- add_task(function*() {
- do_print("Executing test " + generator.name + " with native operations");
- Services.prefs.setBoolPref("toolkit.osfile.native", true);
- return Task.spawn(generator);
- });
- add_task(function*() {
- do_print("Executing test " + generator.name + " without native operations");
- Services.prefs.setBoolPref("toolkit.osfile.native", false);
- return Task.spawn(generator);
- });
-}
-
-/**
- * Fetch asynchronously the contents of a file using xpcom.
- *
- * Used for comparing xpcom-based results to os.file-based results.
- *
- * @param {string} path The _absolute_ path to the file.
- * @return {promise}
- * @resolves {string} The contents of the file.
- */
-function reference_fetch_file(path, test) {
- do_print("Fetching file " + path);
- let deferred = Promise.defer();
- let file = new FileUtils.File(path);
- NetUtil.asyncFetch({
- uri: NetUtil.newURI(file),
- loadUsingSystemPrincipal: true
- }, function(stream, status) {
- if (!Components.isSuccessCode(status)) {
- deferred.reject(status);
- return;
- }
- let result, reject;
- try {
- result = NetUtil.readInputStreamToString(stream, stream.available());
- } catch (x) {
- reject = x;
- }
- stream.close();
- if (reject) {
- deferred.reject(reject);
- } else {
- deferred.resolve(result);
- }
- });
-
- return deferred.promise;
-};
-
-/**
- * Compare asynchronously the contents two files using xpcom.
- *
- * Used for comparing xpcom-based results to os.file-based results.
- *
- * @param {string} a The _absolute_ path to the first file.
- * @param {string} b The _absolute_ path to the second file.
- *
- * @resolves {null}
- */
-function reference_compare_files(a, b, test) {
- return Task.spawn(function*() {
- do_print("Comparing files " + a + " and " + b);
- let a_contents = yield reference_fetch_file(a, test);
- let b_contents = yield reference_fetch_file(b, test);
- do_check_eq(a_contents, b_contents);
- });
-};
diff --git a/toolkit/components/osfile/tests/xpcshell/test_available_free_space.js b/toolkit/components/osfile/tests/xpcshell/test_available_free_space.js
deleted file mode 100644
index 08e67763b..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_available_free_space.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-do_register_cleanup(function() {
- Services.prefs.setBoolPref("toolkit.osfile.log", false);
-});
-
-function run_test() {
- Services.prefs.setBoolPref("toolkit.osfile.log", true);
-
- run_next_test();
-}
-
-/**
- * Test OS.File.getAvailableFreeSpace
- */
-add_task(function() {
- // Set up profile. We will use profile path to query for available free
- // space.
- do_get_profile();
-
- let dir = OS.Constants.Path.profileDir;
-
- // Sanity checking for the test
- do_check_true((yield OS.File.exists(dir)));
-
- // Query for available bytes for user
- let availableBytes = yield OS.File.getAvailableFreeSpace(dir);
-
- do_check_true(!!availableBytes);
- do_check_true(availableBytes > 0);
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_compression.js b/toolkit/components/osfile/tests/xpcshell/test_compression.js
deleted file mode 100644
index b40235615..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_compression.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-
-function run_test() {
- do_test_pending();
- run_next_test();
-}
-
-add_task(function test_compress_lz4() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir, "compression.lz");
- let length = 1024;
- let array = new Uint8Array(length);
- for (let i = 0; i < array.byteLength; ++i) {
- array[i] = i;
- }
- let arrayAsString = Array.prototype.join.call(array);
-
- do_print("Writing data with lz4 compression");
- let bytes = yield OS.File.writeAtomic(path, array, { compression: "lz4" });
- do_print("Compressed " + length + " bytes into " + bytes);
-
- do_print("Reading back with lz4 decompression");
- let decompressed = yield OS.File.read(path, { compression: "lz4" });
- do_print("Decompressed into " + decompressed.byteLength + " bytes");
- do_check_eq(arrayAsString, Array.prototype.join.call(decompressed));
-});
-
-add_task(function test_uncompressed() {
- do_print("Writing data without compression");
- let path = OS.Path.join(OS.Constants.Path.tmpDir, "no_compression.tmp");
- let array = new Uint8Array(1024);
- for (let i = 0; i < array.byteLength; ++i) {
- array[i] = i;
- }
- let bytes = yield OS.File.writeAtomic(path, array); // No compression
-
- let exn;
- // Force decompression, reading should fail
- try {
- yield OS.File.read(path, { compression: "lz4" });
- } catch (ex) {
- exn = ex;
- }
- do_check_true(!!exn);
- // Check the exception message (and that it contains the file name)
- do_check_true(exn.message.indexOf(`Invalid header (no magic number) - Data: ${ path }`) != -1);
-});
-
-add_task(function test_no_header() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir, "no_header.tmp");
- let array = new Uint8Array(8).fill(0,0); // Small array with no header
-
- do_print("Writing data with no header");
-
- let bytes = yield OS.File.writeAtomic(path, array); // No compression
- let exn;
- // Force decompression, reading should fail
- try {
- yield OS.File.read(path, { compression: "lz4" });
- } catch (ex) {
- exn = ex;
- }
- do_check_true(!!exn);
- // Check the exception message (and that it contains the file name)
- do_check_true(exn.message.indexOf(`Buffer is too short (no header) - Data: ${ path }`) != -1);
-});
-
-add_task(function test_invalid_content() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir, "invalid_content.tmp");
- let arr1 = new Uint8Array([109, 111, 122, 76, 122, 52, 48, 0]);
- let arr2 = new Uint8Array(248).fill(1,0);
-
- let array = new Uint8Array(arr1.length + arr2.length);
- array.set(arr1);
- array.set(arr2, arr1.length);
-
- do_print("Writing invalid data (with a valid header and only ones after that)");
-
- let bytes = yield OS.File.writeAtomic(path, array); // No compression
- let exn;
- // Force decompression, reading should fail
- try {
- yield OS.File.read(path, { compression: "lz4" });
- } catch (ex) {
- exn = ex;
- }
- do_check_true(!!exn);
- // Check the exception message (and that it contains the file name)
- do_check_true(exn.message.indexOf(`Invalid content: Decompression stopped at 0 - Data: ${ path }`) != -1);
-});
-
-add_task(function() {
- do_test_finished();
-}); \ No newline at end of file
diff --git a/toolkit/components/osfile/tests/xpcshell/test_constants.js b/toolkit/components/osfile/tests/xpcshell/test_constants.js
deleted file mode 100644
index 5b91484bd..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_constants.js
+++ /dev/null
@@ -1,26 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm", this);
-
-function run_test() {
- run_next_test();
-}
-
-// Test that OS.Constants is defined correctly.
-add_task(function* check_definition() {
- do_check_true(OS.Constants!=null);
- do_check_true(!!OS.Constants.Win || !!OS.Constants.libc);
- do_check_true(OS.Constants.Path!=null);
- do_check_true(OS.Constants.Sys!=null);
- //check system name
- do_check_eq(Services.appinfo.OS, OS.Constants.Sys.Name);
-
- //check if using DEBUG build
- if (Components.classes["@mozilla.org/xpcom/debug;1"].getService(Components.interfaces.nsIDebug2).isDebugBuild == true) {
- do_check_true(OS.Constants.Sys.DEBUG);
- } else {
- do_check_true(typeof(OS.Constants.Sys.DEBUG) == 'undefined');
- }
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_creationDate.js b/toolkit/components/osfile/tests/xpcshell/test_creationDate.js
deleted file mode 100644
index 9c4fa1dfc..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_creationDate.js
+++ /dev/null
@@ -1,31 +0,0 @@
-"use strict";
-
-function run_test() {
- do_test_pending();
- run_next_test();
-}
-
-/**
- * Test to ensure that deprecation warning is issued on use
- * of creationDate.
- */
-add_task(function test_deprecatedCreationDate () {
- let deferred = Promise.defer();
- let consoleListener = {
- observe: function (aMessage) {
- if(aMessage.message.indexOf("Field 'creationDate' is deprecated.") > -1) {
- do_print("Deprecation message printed");
- do_check_true(true);
- Services.console.unregisterListener(consoleListener);
- deferred.resolve();
- }
- }
- };
- let currentDir = yield OS.File.getCurrentDirectory();
- let path = OS.Path.join(currentDir, "test_creationDate.js");
-
- Services.console.registerListener(consoleListener);
- (yield OS.File.stat(path)).creationDate;
-});
-
-add_task(do_test_finished);
diff --git a/toolkit/components/osfile/tests/xpcshell/test_duration.js b/toolkit/components/osfile/tests/xpcshell/test_duration.js
deleted file mode 100644
index 305c03da8..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_duration.js
+++ /dev/null
@@ -1,91 +0,0 @@
-var {OS} = Components.utils.import("resource://gre/modules/osfile.jsm", {});
-var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
-
-/**
- * Test optional duration reporting that can be used for telemetry.
- */
-add_task(function* duration() {
- Services.prefs.setBoolPref("toolkit.osfile.log", true);
- // Options structure passed to a OS.File copy method.
- let copyOptions = {
- // This field should be overridden with the actual duration
- // measurement.
- outExecutionDuration: null
- };
- let currentDir = yield OS.File.getCurrentDirectory();
- let pathSource = OS.Path.join(currentDir, "test_duration.js");
- let copyFile = pathSource + ".bak";
- function testOptions(options, name) {
- do_print("Checking outExecutionDuration for operation: " + name);
- do_print(name + ": Gathered method duration time: " +
- options.outExecutionDuration + "ms");
- // Making sure that duration was updated.
- do_check_eq(typeof options.outExecutionDuration, "number");
- do_check_true(options.outExecutionDuration >= 0);
- };
- // Testing duration of OS.File.copy.
- yield OS.File.copy(pathSource, copyFile, copyOptions);
- testOptions(copyOptions, "OS.File.copy");
- yield OS.File.remove(copyFile);
-
- // Trying an operation where options are cloned.
- let pathDest = OS.Path.join(OS.Constants.Path.tmpDir,
- "osfile async test read writeAtomic.tmp");
- let tmpPath = pathDest + ".tmp";
- let readOptions = {
- outExecutionDuration: null
- };
- let contents = yield OS.File.read(pathSource, undefined, readOptions);
- testOptions(readOptions, "OS.File.read");
- // Options structure passed to a OS.File writeAtomic method.
- let writeAtomicOptions = {
- // This field should be first initialized with the actual
- // duration measurement then progressively incremented.
- outExecutionDuration: null,
- tmpPath: tmpPath
- };
- yield OS.File.writeAtomic(pathDest, contents, writeAtomicOptions);
- testOptions(writeAtomicOptions, "OS.File.writeAtomic");
- yield OS.File.remove(pathDest);
-
- do_print("Ensuring that we can use outExecutionDuration to accumulate durations");
-
- let ARBITRARY_BASE_DURATION = 5;
- copyOptions = {
- // This field should now be incremented with the actual duration
- // measurement.
- outExecutionDuration: ARBITRARY_BASE_DURATION
- };
- let backupDuration = ARBITRARY_BASE_DURATION;
- // Testing duration of OS.File.copy.
- yield OS.File.copy(pathSource, copyFile, copyOptions);
-
- do_check_true(copyOptions.outExecutionDuration >= backupDuration);
-
- backupDuration = copyOptions.outExecutionDuration;
- yield OS.File.remove(copyFile, copyOptions);
- do_check_true(copyOptions.outExecutionDuration >= backupDuration);
-
- // Trying an operation where options are cloned.
- // Options structure passed to a OS.File writeAtomic method.
- writeAtomicOptions = {
- // This field should be overridden with the actual duration
- // measurement.
- outExecutionDuration: copyOptions.outExecutionDuration,
- tmpPath: tmpPath
- };
- backupDuration = writeAtomicOptions.outExecutionDuration;
-
- yield OS.File.writeAtomic(pathDest, contents, writeAtomicOptions);
- do_check_true(copyOptions.outExecutionDuration >= backupDuration);
- OS.File.remove(pathDest);
-
- // Testing an operation that doesn't take arguments at all
- let file = yield OS.File.open(pathSource);
- yield file.stat();
- yield file.close();
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_exception.js b/toolkit/components/osfile/tests/xpcshell/test_exception.js
deleted file mode 100644
index 1282adb3e..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_exception.js
+++ /dev/null
@@ -1,89 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Test that functions throw the appropriate exceptions.
- */
-
-"use strict";
-
-var EXISTING_FILE = do_get_file("xpcshell.ini").path;
-
-
-// Tests on |open|
-
-add_test_pair(function test_typeerror() {
- let exn;
- try {
- let fd = yield OS.File.open("/tmp", {no_such_key: 1});
- do_print("Fd: " + fd);
- } catch (ex) {
- exn = ex;
- }
- do_print("Exception: " + exn);
- do_check_true(exn.constructor.name == "TypeError");
-});
-
-// Tests on |read|
-
-add_test_pair(function* test_bad_encoding() {
- do_print("Testing with a wrong encoding");
- try {
- yield OS.File.read(EXISTING_FILE, { encoding: "baby-speak-encoded" });
- do_throw("Should have thrown with an ex.becauseInvalidArgument");
- } catch (ex if ex.becauseInvalidArgument) {
- do_print("Wrong encoding caused the correct exception");
- }
-
- try {
- yield OS.File.read(EXISTING_FILE, { encoding: 4 });
- do_throw("Should have thrown a TypeError");
- } catch (ex if ex.constructor.name == "TypeError") {
- // Note that TypeError doesn't carry across compartments
- do_print("Non-string encoding caused the correct exception");
- }
- });
-
-add_test_pair(function* test_bad_compression() {
- do_print("Testing with a non-existing compression");
- try {
- yield OS.File.read(EXISTING_FILE, { compression: "mmmh-crunchy" });
- do_throw("Should have thrown with an ex.becauseInvalidArgument");
- } catch (ex if ex.becauseInvalidArgument) {
- do_print("Wrong encoding caused the correct exception");
- }
-
- do_print("Testing with a bad type for option compression");
- try {
- yield OS.File.read(EXISTING_FILE, { compression: 5 });
- do_throw("Should have thrown a TypeError");
- } catch (ex if ex.constructor.name == "TypeError") {
- // Note that TypeError doesn't carry across compartments
- do_print("Non-string encoding caused the correct exception");
- }
-});
-
-add_test_pair(function* test_bad_bytes() {
- do_print("Testing with a bad type for option bytes");
- try {
- yield OS.File.read(EXISTING_FILE, { bytes: "five" });
- do_throw("Should have thrown a TypeError");
- } catch (ex if ex.constructor.name == "TypeError") {
- // Note that TypeError doesn't carry across compartments
- do_print("Non-number bytes caused the correct exception");
- }
-});
-
-add_test_pair(function* read_non_existent() {
- do_print("Testing with a non-existent file");
- try {
- yield OS.File.read("I/do/not/exist");
- do_throw("Should have thrown with an ex.becauseNoSuchFile");
- } catch (ex if ex.becauseNoSuchFile) {
- do_print("Correct exceptions");
- }
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_file_URL_conversion.js b/toolkit/components/osfile/tests/xpcshell/test_file_URL_conversion.js
deleted file mode 100644
index 3ec42065b..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_file_URL_conversion.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- Components.utils.import("resource://gre/modules/Services.jsm");
- Components.utils.import("resource://gre/modules/osfile.jsm");
- Components.utils.import("resource://gre/modules/FileUtils.jsm");
-
- let isWindows = ("@mozilla.org/windows-registry-key;1" in Components.classes);
-
- // Test cases for filePathToURI
- let paths = isWindows ? [
- 'C:\\',
- 'C:\\test',
- 'C:\\test\\',
- 'C:\\test%2f',
- 'C:\\test\\test\\test',
- 'C:\\test;+%',
- 'C:\\test?action=index\\',
- 'C:\\test\ test',
- '\\\\C:\\a\\b\\c',
- '\\\\Server\\a\\b\\c',
-
- // note that per http://support.microsoft.com/kb/177506 (under more info),
- // the following characters are allowed on Windows:
- 'C:\\char^',
- 'C:\\char&',
- 'C:\\char\'',
- 'C:\\char@',
- 'C:\\char{',
- 'C:\\char}',
- 'C:\\char[',
- 'C:\\char]',
- 'C:\\char,',
- 'C:\\char$',
- 'C:\\char=',
- 'C:\\char!',
- 'C:\\char-',
- 'C:\\char#',
- 'C:\\char(',
- 'C:\\char)',
- 'C:\\char%',
- 'C:\\char.',
- 'C:\\char+',
- 'C:\\char~',
- 'C:\\char_'
- ] : [
- '/',
- '/test',
- '/test/',
- '/test%2f',
- '/test/test/test',
- '/test;+%',
- '/test?action=index/',
- '/test\ test',
- '/punctuation/;,/?:@&=+$-_.!~*\'()[]"#',
- '/CasePreserving'
- ];
-
- // some additional URIs to test, beyond those generated from paths
- let uris = isWindows ? [
- 'file:///C:/test/',
- 'file://localhost/C:/test',
- 'file:///c:/test/test.txt',
- //'file:///C:/foo%2f', // trailing, encoded slash
- 'file:///C:/%3f%3F',
- 'file:///C:/%3b%3B',
- 'file:///C:/%3c%3C', // not one of the special-cased ? or ;
- 'file:///C:/%78', // 'x', not usually uri encoded
- 'file:///C:/test#frag', // a fragment identifier
- 'file:///C:/test?action=index' // an actual query component
- ] : [
- 'file:///test/',
- 'file://localhost/test',
- 'file:///test/test.txt',
- 'file:///foo%2f', // trailing, encoded slash
- 'file:///%3f%3F',
- 'file:///%3b%3B',
- 'file:///%3c%3C', // not one of the special-cased ? or ;
- 'file:///%78', // 'x', not usually uri encoded
- 'file:///test#frag', // a fragment identifier
- 'file:///test?action=index' // an actual query component
- ];
-
- for (let path of paths) {
- // convert that to a uri using FileUtils and Services, which toFileURI is trying to model
- let file = FileUtils.File(path);
- let uri = Services.io.newFileURI(file).spec;
- do_check_eq(uri, OS.Path.toFileURI(path));
-
- // keep the resulting URI to try the reverse, except for "C:\" for which the
- // behavior of nsIFileURL and OS.File is inconsistent
- if (path != "C:\\") {
- uris.push(uri);
- }
- }
-
- for (let uri of uris) {
- // convert URIs to paths with nsIFileURI, which fromFileURI is trying to model
- let path = Services.io.newURI(uri, null, null).QueryInterface(Components.interfaces.nsIFileURL).file.path;
- do_check_eq(path, OS.Path.fromFileURI(uri));
- }
-
- // check that non-file URLs aren't allowed
- let thrown = false;
- try {
- OS.Path.fromFileURI('http://test.com')
- } catch (e) {
- do_check_eq(e.message, "fromFileURI expects a file URI");
- thrown = true;
- }
- do_check_true(thrown);
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_loader.js b/toolkit/components/osfile/tests/xpcshell/test_loader.js
deleted file mode 100644
index dcfa819be..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_loader.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * Test that OS.File can be loaded using the CommonJS loader.
- */
-
-var { Loader } = Components.utils.import('resource://gre/modules/commonjs/toolkit/loader.js', {});
-
-function run_test() {
- run_next_test();
-}
-
-
-add_task(function*() {
- let dataDir = Services.io.newFileURI(do_get_file("test_loader/", true)).spec + "/";
- let loader = Loader.Loader({
- paths: {'': dataDir }
- });
-
- let require = Loader.Require(loader, Loader.Module('module_test_loader', 'foo'));
- do_print("Require is ready");
- try {
- require('module_test_loader');
- } catch (error) {
- dump('Bootstrap error: ' +
- (error.message ? error.message : String(error)) + '\n' +
- (error.stack || error.fileName + ': ' + error.lineNumber) + '\n');
-
- throw error;
- }
-
- do_print("Require has worked");
-});
-
diff --git a/toolkit/components/osfile/tests/xpcshell/test_loader/module_test_loader.js b/toolkit/components/osfile/tests/xpcshell/test_loader/module_test_loader.js
deleted file mode 100644
index 18356d6ad..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_loader/module_test_loader.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// Load OS.File from a module loaded with the CommonJS/addon-sdk loader
-
-var {Cu} = require("chrome");
-Cu.import('resource://gre/modules/osfile.jsm');
diff --git a/toolkit/components/osfile/tests/xpcshell/test_logging.js b/toolkit/components/osfile/tests/xpcshell/test_logging.js
deleted file mode 100644
index 133909e0b..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_logging.js
+++ /dev/null
@@ -1,74 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-/**
- * Tests logging by passing OS.Shared.LOG both an object with its own
- * toString method, and one with the default.
- */
-function run_test() {
- do_test_pending();
- let messageCount = 0;
-
- do_print("Test starting");
-
- // Create a console listener.
- let consoleListener = {
- observe: function (aMessage) {
- //Ignore unexpected messages.
- if (!(aMessage instanceof Components.interfaces.nsIConsoleMessage)) {
- return;
- }
- // This is required, as printing to the |Services.console|
- // while in the observe function causes an exception.
- do_execute_soon(function() {
- do_print("Observing message " + aMessage.message);
- if (aMessage.message.indexOf("TEST OS") < 0) {
- return;
- }
-
- ++messageCount;
- if(messageCount == 1) {
- do_check_eq(aMessage.message, "TEST OS {\"name\":\"test\"}\n");
- }
- if(messageCount == 2) {
- do_check_eq(aMessage.message, "TEST OS name is test\n");
- toggleConsoleListener(false);
- do_test_finished();
- }
- });
- }
- };
-
- // Set/Unset the console listener.
- function toggleConsoleListener (pref) {
- do_print("Setting console listener: " + pref);
- Services.prefs.setBoolPref("toolkit.osfile.log", pref);
- Services.prefs.setBoolPref("toolkit.osfile.log.redirect", pref);
- Services.console[pref ? "registerListener" : "unregisterListener"](
- consoleListener);
- }
-
- toggleConsoleListener(true);
-
- let objectDefault = {name: "test"};
- let CustomToString = function() {
- this.name = "test";
- };
- CustomToString.prototype.toString = function() {
- return "name is " + this.name;
- };
- let objectCustom = new CustomToString();
-
- do_print(OS.Shared.LOG.toSource());
-
- do_print("Logging 1");
- OS.Shared.LOG(objectDefault);
-
- do_print("Logging 2");
- OS.Shared.LOG(objectCustom);
- // Once both messages are observed OS.Shared.DEBUG, and OS.Shared.TEST
- // are reset to false.
-}
-
diff --git a/toolkit/components/osfile/tests/xpcshell/test_makeDir.js b/toolkit/components/osfile/tests/xpcshell/test_makeDir.js
deleted file mode 100644
index 5b9740a7f..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_makeDir.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-var Path = OS.Path;
-var profileDir;
-
-do_register_cleanup(function() {
- Services.prefs.setBoolPref("toolkit.osfile.log", false);
-});
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Test OS.File.makeDir
- */
-
-add_task(function init() {
- // Set up profile. We create the directory in the profile, because the profile
- // is removed after every test run.
- do_get_profile();
- profileDir = OS.Constants.Path.profileDir;
- Services.prefs.setBoolPref("toolkit.osfile.log", true);
-});
-
-/**
- * Basic use
- */
-
-add_task(function* test_basic() {
- let dir = Path.join(profileDir, "directory");
-
- // Sanity checking for the test
- do_check_false((yield OS.File.exists(dir)));
-
- // Make a directory
- yield OS.File.makeDir(dir);
-
- //check if the directory exists
- yield OS.File.stat(dir);
-
- // Make a directory that already exists, this should succeed
- yield OS.File.makeDir(dir);
-
- // Make a directory with ignoreExisting
- yield OS.File.makeDir(dir, {ignoreExisting: true});
-
- // Make a directory with ignoreExisting false
- let exception = null;
- try {
- yield OS.File.makeDir(dir, {ignoreExisting: false});
- } catch (ex) {
- exception = ex;
- }
-
- do_check_true(!!exception);
- do_check_true(exception instanceof OS.File.Error);
- do_check_true(exception.becauseExists);
-});
-
-// Make a root directory that already exists
-add_task(function* test_root() {
- if (OS.Constants.Win) {
- yield OS.File.makeDir("C:");
- yield OS.File.makeDir("C:\\");
- } else {
- yield OS.File.makeDir("/");
- }
-});
-
-/**
- * Creating subdirectories
- */
-add_task(function test_option_from() {
- let dir = Path.join(profileDir, "a", "b", "c");
-
- // Sanity checking for the test
- do_check_false((yield OS.File.exists(dir)));
-
- // Make a directory
- yield OS.File.makeDir(dir, {from: profileDir});
-
- //check if the directory exists
- yield OS.File.stat(dir);
-
- // Make a directory that already exists, this should succeed
- yield OS.File.makeDir(dir);
-
- // Make a directory with ignoreExisting
- yield OS.File.makeDir(dir, {ignoreExisting: true});
-
- // Make a directory with ignoreExisting false
- let exception = null;
- try {
- yield OS.File.makeDir(dir, {ignoreExisting: false});
- } catch (ex) {
- exception = ex;
- }
-
- do_check_true(!!exception);
- do_check_true(exception instanceof OS.File.Error);
- do_check_true(exception.becauseExists);
-
- // Make a directory without |from| and fail
- let dir2 = Path.join(profileDir, "g", "h", "i");
- exception = null;
- try {
- yield OS.File.makeDir(dir2);
- } catch (ex) {
- exception = ex;
- }
-
- do_check_true(!!exception);
- do_check_true(exception instanceof OS.File.Error);
- do_check_true(exception.becauseNoSuchFile);
-
- // Test edge cases on paths
-
- let dir3 = Path.join(profileDir, "d", "", "e", "f");
- do_check_false((yield OS.File.exists(dir3)));
- yield OS.File.makeDir(dir3, {from: profileDir});
- do_check_true((yield OS.File.exists(dir3)));
-
- let dir4;
- if (OS.Constants.Win) {
- // Test that we can create a directory recursively even
- // if we have too many "\\".
- dir4 = profileDir + "\\\\g";
- } else {
- dir4 = profileDir + "////g";
- }
- do_check_false((yield OS.File.exists(dir4)));
- yield OS.File.makeDir(dir4, {from: profileDir});
- do_check_true((yield OS.File.exists(dir4)));
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_open.js b/toolkit/components/osfile/tests/xpcshell/test_open.js
deleted file mode 100644
index 78772ad09..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_open.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Test OS.File.open for reading:
- * - with an existing file (should succeed);
- * - with a non-existing file (should fail);
- * - with inconsistent arguments (should fail).
- */
-add_task(function() {
- // Attempt to open a file that does not exist, ensure that it yields the
- // appropriate error.
- try {
- let fd = yield OS.File.open(OS.Path.join(".", "This file does not exist"));
- do_check_true(false, "File opening 1 succeeded (it should fail)");
- } catch (err if err instanceof OS.File.Error && err.becauseNoSuchFile) {
- do_print("File opening 1 failed " + err);
- }
-
- // Attempt to open a file with the wrong args, so that it fails before
- // serialization, ensure that it yields the appropriate error.
- do_print("Attempting to open a file with wrong arguments");
- try {
- let fd = yield OS.File.open(1, 2, 3);
- do_check_true(false, "File opening 2 succeeded (it should fail)" + fd);
- } catch (err) {
- do_print("File opening 2 failed " + err);
- do_check_false(err instanceof OS.File.Error,
- "File opening 2 returned something that is not a file error");
- do_check_true(err.constructor.name == "TypeError",
- "File opening 2 returned a TypeError");
- }
-
- // Attempt to open a file correctly
- do_print("Attempting to open a file correctly");
- let openedFile = yield OS.File.open(OS.Path.join(do_get_cwd().path, "test_open.js"));
- do_print("File opened correctly");
-
- do_print("Attempting to close a file correctly");
- yield openedFile.close();
-
- do_print("Attempting to close a file again");
- yield openedFile.close();
-});
-
-/**
- * Test the error thrown by OS.File.open when attempting to open a directory
- * that does not exist.
- */
-add_task(function test_error_attributes () {
-
- let dir = OS.Path.join(do_get_profile().path, "test_osfileErrorAttrs");
- let fpath = OS.Path.join(dir, "test_error_attributes.txt");
-
- try {
- yield OS.File.open(fpath, {truncate: true}, {});
- do_check_true(false, "Opening path suceeded (it should fail) " + fpath);
- } catch (err) {
- do_check_true(err instanceof OS.File.Error);
- do_check_true(err.becauseNoSuchFile);
- }
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async.js
deleted file mode 100644
index 0f86b2ea8..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async.js
+++ /dev/null
@@ -1,16 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-
-/**
- * A trivial test ensuring that we can call osfile from xpcshell.
- * (see bug 808161)
- */
-
-function run_test() {
- do_test_pending();
- OS.File.getCurrentDirectory().then(
- do_test_finished,
- do_test_finished
- );
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_append.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_append.js
deleted file mode 100644
index 0aef2c58a..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_append.js
+++ /dev/null
@@ -1,122 +0,0 @@
-"use strict";
-
-do_print("starting tests");
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-/**
- * A test to check that the |append| mode flag is correctly implemented.
- * (see bug 925865)
- */
-
-function setup_mode(mode) {
- // Complete mode.
- let realMode = {
- read: true,
- write: true
- };
- for (let k in mode) {
- realMode[k] = mode[k];
- }
- return realMode;
-}
-
-// Test append mode.
-function test_append(mode) {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_append.tmp");
-
- // Clear any left-over files from previous runs.
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore
- }
-
- try {
- mode = setup_mode(mode);
- mode.append = true;
- if (mode.trunc) {
- // Pre-fill file with some data to see if |trunc| actually works.
- yield OS.File.writeAtomic(path, new Uint8Array(500));
- }
- let file = yield OS.File.open(path, mode);
- try {
- yield file.write(new Uint8Array(1000));
- yield file.setPosition(0, OS.File.POS_START);
- yield file.read(100);
- // Should be at offset 100, length 1000 now.
- yield file.write(new Uint8Array(100));
- // Should be at offset 1100, length 1100 now.
- let stat = yield file.stat();
- do_check_eq(1100, stat.size);
- } finally {
- yield file.close();
- }
- } catch(ex) {
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore.
- }
- }
-}
-
-// Test no-append mode.
-function test_no_append(mode) {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_noappend.tmp");
-
- // Clear any left-over files from previous runs.
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore
- }
-
- try {
- mode = setup_mode(mode);
- mode.append = false;
- if (mode.trunc) {
- // Pre-fill file with some data to see if |trunc| actually works.
- yield OS.File.writeAtomic(path, new Uint8Array(500));
- }
- let file = yield OS.File.open(path, mode);
- try {
- yield file.write(new Uint8Array(1000));
- yield file.setPosition(0, OS.File.POS_START);
- yield file.read(100);
- // Should be at offset 100, length 1000 now.
- yield file.write(new Uint8Array(100));
- // Should be at offset 200, length 1000 now.
- let stat = yield file.stat();
- do_check_eq(1000, stat.size);
- } finally {
- yield file.close();
- }
- } finally {
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore.
- }
- }
-}
-
-var test_flags = [
- {},
- {create:true},
- {trunc:true}
-];
-function run_test() {
- do_test_pending();
-
- for (let t of test_flags) {
- add_task(test_append.bind(null, t));
- add_task(test_no_append.bind(null, t));
- }
- add_task(do_test_finished);
-
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_bytes.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_bytes.js
deleted file mode 100644
index 68fa9152c..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_bytes.js
+++ /dev/null
@@ -1,39 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function run_test() {
- do_test_pending();
- run_next_test();
-}
-
-/**
- * Test to ensure that {bytes:} in options to |write| is correctly
- * preserved.
- */
-add_task(function* test_bytes() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_bytes.tmp");
- let file = yield OS.File.open(path, {trunc: true, read: true, write: true});
- try {
- try {
- // 1. Test write, by supplying {bytes:} options smaller than the actual
- // buffer.
- yield file.write(new Uint8Array(2048), {bytes: 1024});
- do_check_eq((yield file.stat()).size, 1024);
-
- // 2. Test that passing nullish values for |options| still works.
- yield file.setPosition(0, OS.File.POS_END);
- yield file.write(new Uint8Array(1024), null);
- yield file.write(new Uint8Array(1024), undefined);
- do_check_eq((yield file.stat()).size, 3072);
- } finally {
- yield file.close();
- }
- } finally {
- yield OS.File.remove(path);
- }
-});
-
-add_task(do_test_finished);
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_copy.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_copy.js
deleted file mode 100644
index 9c52c8a80..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_copy.js
+++ /dev/null
@@ -1,113 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/FileUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/Promise.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function run_test() {
- do_test_pending();
- run_next_test();
-}
-
-/**
- * A file that we know exists and that can be used for reading.
- */
-var EXISTING_FILE = "test_osfile_async_copy.js";
-
-/**
- * Fetch asynchronously the contents of a file using xpcom.
- *
- * Used for comparing xpcom-based results to os.file-based results.
- *
- * @param {string} path The _absolute_ path to the file.
- * @return {promise}
- * @resolves {string} The contents of the file.
- */
-var reference_fetch_file = function reference_fetch_file(path) {
- let promise = Promise.defer();
- let file = new FileUtils.File(path);
- NetUtil.asyncFetch({
- uri: NetUtil.newURI(file),
- loadUsingSystemPrincipal: true
- }, function(stream, status) {
- if (!Components.isSuccessCode(status)) {
- promise.reject(status);
- return;
- }
- let result, reject;
- try {
- result = NetUtil.readInputStreamToString(stream, stream.available());
- } catch (x) {
- reject = x;
- }
- stream.close();
- if (reject) {
- promise.reject(reject);
- } else {
- promise.resolve(result);
- }
- });
-
- return promise.promise;
-};
-
-/**
- * Compare asynchronously the contents two files using xpcom.
- *
- * Used for comparing xpcom-based results to os.file-based results.
- *
- * @param {string} a The _absolute_ path to the first file.
- * @param {string} b The _absolute_ path to the second file.
- *
- * @resolves {null}
- */
-var reference_compare_files = function reference_compare_files(a, b) {
- let a_contents = yield reference_fetch_file(a);
- let b_contents = yield reference_fetch_file(b);
- // Not using do_check_eq to avoid dumping the whole file to the log.
- // It is OK to === compare here, as both variables contain a string.
- do_check_true(a_contents === b_contents);
-};
-
-/**
- * Test to ensure that OS.File.copy works.
- */
-function test_copymove(options = {}) {
- let source = OS.Path.join((yield OS.File.getCurrentDirectory()),
- EXISTING_FILE);
- let dest = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_copy_dest.tmp");
- let dest2 = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_copy_dest2.tmp");
- try {
- // 1. Test copy.
- yield OS.File.copy(source, dest, options);
- yield reference_compare_files(source, dest);
- // 2. Test subsequent move.
- yield OS.File.move(dest, dest2);
- yield reference_compare_files(source, dest2);
- // 3. Check that the moved file was really moved.
- do_check_eq((yield OS.File.exists(dest)), false);
- } finally {
- try {
- yield OS.File.remove(dest);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore
- }
- try {
- yield OS.File.remove(dest2);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore
- }
- }
-}
-
-// Regular copy test.
-add_task(test_copymove);
-// Userland copy test.
-add_task(test_copymove.bind(null, {unixUserland: true}));
-
-add_task(do_test_finished);
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_flush.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_flush.js
deleted file mode 100644
index 9ed087f4e..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_flush.js
+++ /dev/null
@@ -1,30 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function run_test() {
- do_test_pending();
- run_next_test();
-}
-
-/**
- * Test to ensure that |File.prototype.flush| is available in the async API.
- */
-
-add_task(function test_flush() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_flush.tmp");
- let file = yield OS.File.open(path, {trunc: true, write: true});
- try {
- try {
- yield file.flush();
- } finally {
- yield file.close();
- }
- } finally {
- yield OS.File.remove(path);
- }
-});
-
-add_task(do_test_finished);
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_largefiles.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_largefiles.js
deleted file mode 100644
index a9ac776b0..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_largefiles.js
+++ /dev/null
@@ -1,153 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/ctypes.jsm");
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-/**
- * A test to check that .getPosition/.setPosition work with large files.
- * (see bug 952997)
- */
-
-// Test setPosition/getPosition.
-function test_setPosition(forward, current, backward) {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_largefiles.tmp");
-
- // Clear any left-over files from previous runs.
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore
- }
-
- try {
- let file = yield OS.File.open(path, {write:true, append:false});
- try {
- let pos = 0;
-
- // 1. seek forward from start
- do_print("Moving forward: " + forward);
- yield file.setPosition(forward, OS.File.POS_START);
- pos += forward;
- do_check_eq((yield file.getPosition()), pos);
-
- // 2. seek forward from current position
- do_print("Moving current: " + current);
- yield file.setPosition(current, OS.File.POS_CURRENT);
- pos += current;
- do_check_eq((yield file.getPosition()), pos);
-
- // 3. seek backward from current position
- do_print("Moving current backward: " + backward);
- yield file.setPosition(-backward, OS.File.POS_CURRENT);
- pos -= backward;
- do_check_eq((yield file.getPosition()), pos);
-
- } finally {
- yield file.setPosition(0, OS.File.POS_START);
- yield file.close();
- }
- } catch(ex) {
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore.
- }
- do_throw(ex);
- }
-}
-
-// Test setPosition/getPosition expected failures.
-function test_setPosition_failures() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_largefiles.tmp");
-
- // Clear any left-over files from previous runs.
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore
- }
-
- try {
- let file = yield OS.File.open(path, {write:true, append:false});
- try {
- let pos = 0;
-
- // 1. Use an invalid position value
- try {
- yield file.setPosition(0.5, OS.File.POS_START);
- do_throw("Shouldn't have succeeded");
- } catch (ex) {
- do_check_true(ex.toString().includes("can't pass"));
- }
- // Since setPosition should have bailed, it shouldn't have moved the
- // file pointer at all.
- do_check_eq((yield file.getPosition()), 0);
-
- // 2. Use an invalid position value
- try {
- yield file.setPosition(0xffffffff + 0.5, OS.File.POS_START);
- do_throw("Shouldn't have succeeded");
- } catch (ex) {
- do_check_true(ex.toString().includes("can't pass"));
- }
- // Since setPosition should have bailed, it shouldn't have moved the
- // file pointer at all.
- do_check_eq((yield file.getPosition()), 0);
-
- // 3. Use a position that cannot be represented as a double
- try {
- // Not all numbers after 9007199254740992 can be represented as a
- // double. E.g. in js 9007199254740992 + 1 == 9007199254740992
- yield file.setPosition(9007199254740992, OS.File.POS_START);
- yield file.setPosition(1, OS.File.POS_CURRENT);
- do_throw("Shouldn't have succeeded");
- } catch (ex) {
- do_print(ex.toString());
- do_check_true(!!ex);
- }
-
- } finally {
- yield file.setPosition(0, OS.File.POS_START);
- yield file.close();
- try {
- yield OS.File.remove(path);
- } catch (ex if ex.becauseNoSuchFile) {
- // ignore.
- }
- }
- } catch(ex) {
- do_throw(ex);
- }
-}
-
-function run_test() {
- // First verify stuff works for small values.
- add_task(test_setPosition.bind(null, 0, 100, 50));
- add_task(test_setPosition.bind(null, 1000, 100, 50));
- add_task(test_setPosition.bind(null, 1000, -100, -50));
-
- if (OS.Constants.Win || ctypes.off_t.size >= 8) {
- // Now verify stuff still works for large values.
- // 1. Multiple small seeks, which add up to > MAXINT32
- add_task(test_setPosition.bind(null, 0x7fffffff, 0x7fffffff, 0));
- // 2. Plain large seek, that should end up at 0 again.
- // 0xffffffff also happens to be the INVALID_SET_FILE_POINTER value on
- // Windows, so this also tests the error handling
- add_task(test_setPosition.bind(null, 0, 0xffffffff, 0xffffffff));
- // 3. Multiple large seeks that should end up > MAXINT32.
- add_task(test_setPosition.bind(null, 0xffffffff, 0xffffffff, 0xffffffff));
- // 5. Multiple large seeks with negative offsets.
- add_task(test_setPosition.bind(null, 0xffffffff, -0x7fffffff, 0x7fffffff));
-
- // 6. Check failures
- add_task(test_setPosition_failures);
- }
-
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js
deleted file mode 100644
index 6a5ecd5e3..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js
+++ /dev/null
@@ -1,211 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-/**
- * A test to ensure that OS.File.setDates and OS.File.prototype.setDates are
- * working correctly.
- * (see bug 924916)
- */
-
-function run_test() {
- run_next_test();
-}
-
-// Non-prototypical tests, operating on path names.
-add_task(function* test_nonproto() {
- // First, create a file we can mess with.
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_setDates_nonproto.tmp");
- yield OS.File.writeAtomic(path, new Uint8Array(1));
-
- try {
- // 1. Try to set some well known dates.
- // We choose multiples of 2000ms, because the time stamp resolution of
- // the underlying OS might not support something more precise.
- const accDate = 2000;
- const modDate = 4000;
- {
- yield OS.File.setDates(path, accDate, modDate);
- let stat = yield OS.File.stat(path);
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 2.1 Try to omit modificationDate (which should then default to
- // |Date.now()|, expect for resolution differences).
- {
- yield OS.File.setDates(path, accDate);
- let stat = yield OS.File.stat(path);
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_neq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 2.2 Try to omit accessDate as well (which should then default to
- // |Date.now()|, expect for resolution differences).
- {
- yield OS.File.setDates(path);
- let stat = yield OS.File.stat(path);
- do_check_neq(accDate, stat.lastAccessDate.getTime());
- do_check_neq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 3. Repeat 1., but with Date objects this time
- {
- yield OS.File.setDates(path, new Date(accDate), new Date(modDate));
- let stat = yield OS.File.stat(path);
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 4. Check that invalid params will cause an exception/rejection.
- {
- for (let p of ["invalid", new Uint8Array(1), NaN]) {
- try {
- yield OS.File.setDates(path, p, modDate);
- do_throw("Invalid access date should have thrown for: " + p);
- } catch (ex) {
- let stat = yield OS.File.stat(path);
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
- try {
- yield OS.File.setDates(path, accDate, p);
- do_throw("Invalid modification date should have thrown for: " + p);
- } catch (ex) {
- let stat = yield OS.File.stat(path);
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
- try {
- yield OS.File.setDates(path, p, p);
- do_throw("Invalid dates should have thrown for: " + p);
- } catch (ex) {
- let stat = yield OS.File.stat(path);
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
- }
- }
- } finally {
- // Remove the temp file again
- yield OS.File.remove(path);
- }
-});
-
-// Prototypical tests, operating on |File| handles.
-add_task(function* test_proto() {
- if (OS.Constants.Sys.Name == "Android") {
- do_print("File.prototype.setDates is not implemented for Android");
- do_check_eq(OS.File.prototype.setDates, undefined);
- return;
- }
-
- // First, create a file we can mess with.
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_setDates_proto.tmp");
- yield OS.File.writeAtomic(path, new Uint8Array(1));
-
- try {
- let fd = yield OS.File.open(path, {write: true});
-
- try {
- // 1. Try to set some well known dates.
- // We choose multiples of 2000ms, because the time stamp resolution of
- // the underlying OS might not support something more precise.
- const accDate = 2000;
- const modDate = 4000;
- {
- yield fd.setDates(accDate, modDate);
- let stat = yield fd.stat();
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 2.1 Try to omit modificationDate (which should then default to
- // |Date.now()|, expect for resolution differences).
- {
- yield fd.setDates(accDate);
- let stat = yield fd.stat();
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_neq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 2.2 Try to omit accessDate as well (which should then default to
- // |Date.now()|, expect for resolution differences).
- {
- yield fd.setDates();
- let stat = yield fd.stat();
- do_check_neq(accDate, stat.lastAccessDate.getTime());
- do_check_neq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 3. Repeat 1., but with Date objects this time
- {
- yield fd.setDates(new Date(accDate), new Date(modDate));
- let stat = yield fd.stat();
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
-
- // 4. Check that invalid params will cause an exception/rejection.
- {
- for (let p of ["invalid", new Uint8Array(1), NaN]) {
- try {
- yield fd.setDates(p, modDate);
- do_throw("Invalid access date should have thrown for: " + p);
- } catch (ex) {
- let stat = yield fd.stat();
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
- try {
- yield fd.setDates(accDate, p);
- do_throw("Invalid modification date should have thrown for: " + p);
- } catch (ex) {
- let stat = yield fd.stat();
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
- try {
- yield fd.setDates(p, p);
- do_throw("Invalid dates should have thrown for: " + p);
- } catch (ex) {
- let stat = yield fd.stat();
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
- }
- }
- } finally {
- yield fd.close();
- }
- } finally {
- // Remove the temp file again
- yield OS.File.remove(path);
- }
-});
-
-// Tests setting dates on directories.
-add_task(function* test_dirs() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_setDates_dir");
- yield OS.File.makeDir(path);
-
- try {
- // 1. Try to set some well known dates.
- // We choose multiples of 2000ms, because the time stamp resolution of
- // the underlying OS might not support something more precise.
- const accDate = 2000;
- const modDate = 4000;
- {
- yield OS.File.setDates(path, accDate, modDate);
- let stat = yield OS.File.stat(path);
- do_check_eq(accDate, stat.lastAccessDate.getTime());
- do_check_eq(modDate, stat.lastModificationDate.getTime());
- }
- } finally {
- yield OS.File.removeEmptyDir(path);
- }
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setPermissions.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setPermissions.js
deleted file mode 100644
index ab8bf7dd9..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setPermissions.js
+++ /dev/null
@@ -1,103 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * A test to ensure that OS.File.setPermissions and
- * OS.File.prototype.setPermissions are all working correctly.
- * (see bug 1001849)
- * These functions are currently Unix-specific. The manifest skips
- * the test on Windows.
- */
-
-/**
- * Helper function for test logging: prints a POSIX file permission mode as an
- * octal number, with a leading '0' per C (not JS) convention. When the
- * numeric value is 0o777 or lower, it is padded on the left with zeroes to
- * four digits wide.
- * Sample outputs: 0022, 0644, 04755.
- */
-function format_mode(mode) {
- if (mode <= 0o777) {
- return ("0000" + mode.toString(8)).slice(-4);
- } else {
- return "0" + mode.toString(8);
- }
-}
-
-const _umask = OS.Constants.Sys.umask;
-do_print("umask: " + format_mode(_umask));
-
-/**
- * Compute the mode that a file should have after applying the umask,
- * whatever it happens to be.
- */
-function apply_umask(mode) {
- return mode & ~_umask;
-}
-
-// Sequence of setPermission parameters and expected file mode. The first test
-// checks the permissions when the file is first created.
-var testSequence = [
- [null, apply_umask(0o600)],
- [{ unixMode: 0o4777 }, apply_umask(0o4777)],
- [{ unixMode: 0o4777, unixHonorUmask: false }, 0o4777],
- [{ unixMode: 0o4777, unixHonorUmask: true }, apply_umask(0o4777)],
- [undefined, apply_umask(0o600)],
- [{ unixMode: 0o666 }, apply_umask(0o666)],
- [{ unixMode: 0o600 }, apply_umask(0o600)],
- [{ unixMode: 0 }, 0],
- [{}, apply_umask(0o600)],
-];
-
-// Test application to paths.
-add_task(function* test_path_setPermissions() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_setPermissions_path.tmp");
- yield OS.File.writeAtomic(path, new Uint8Array(1));
-
- try {
- for (let [options, expectedMode] of testSequence) {
- if (options !== null) {
- do_print("Setting permissions to " + JSON.stringify(options));
- yield OS.File.setPermissions(path, options);
- }
-
- let stat = yield OS.File.stat(path);
- do_check_eq(format_mode(stat.unixMode), format_mode(expectedMode));
- }
- } finally {
- yield OS.File.remove(path);
- }
-});
-
-// Test application to open files.
-add_task(function* test_file_setPermissions() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_async_setPermissions_file.tmp");
- yield OS.File.writeAtomic(path, new Uint8Array(1));
-
- try {
- let fd = yield OS.File.open(path, { write: true });
- try {
- for (let [options, expectedMode] of testSequence) {
- if (options !== null) {
- do_print("Setting permissions to " + JSON.stringify(options));
- yield fd.setPermissions(options);
- }
-
- let stat = yield fd.stat();
- do_check_eq(format_mode(stat.unixMode), format_mode(expectedMode));
- }
- } finally {
- yield fd.close();
- }
- } finally {
- yield OS.File.remove(path);
- }
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_closed.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_closed.js
deleted file mode 100644
index 5740f7f1a..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_closed.js
+++ /dev/null
@@ -1,48 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function run_test() {
- do_test_pending();
- run_next_test();
-}
-
-add_task(function test_closed() {
- OS.Shared.DEBUG = true;
- let currentDir = yield OS.File.getCurrentDirectory();
- do_print("Open a file, ensure that we can call stat()");
- let path = OS.Path.join(currentDir, "test_osfile_closed.js");
- let file = yield OS.File.open(path);
- yield file.stat();
- do_check_true(true);
-
- yield file.close();
-
- do_print("Ensure that we cannot stat() on closed file");
- let exn;
- try {
- yield file.stat();
- } catch (ex) {
- exn = ex;
- }
- do_print("Ensure that this raises the correct error");
- do_check_true(!!exn);
- do_check_true(exn instanceof OS.File.Error);
- do_check_true(exn.becauseClosed);
-
- do_print("Ensure that we cannot read() on closed file");
- exn = null;
- try {
- yield file.read();
- } catch (ex) {
- exn = ex;
- }
- do_print("Ensure that this raises the correct error");
- do_check_true(!!exn);
- do_check_true(exn instanceof OS.File.Error);
- do_check_true(exn.becauseClosed);
-
-});
-
-add_task(do_test_finished);
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_error.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_error.js
deleted file mode 100644
index a1c319eca..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_error.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {OS: {File, Path, Constants}} = Components.utils.import("resource://gre/modules/osfile.jsm", {});
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* testFileError_with_writeAtomic() {
- let DEFAULT_CONTENTS = "default contents" + Math.random();
- let path = Path.join(Constants.Path.tmpDir,
- "testFileError.tmp");
- yield File.remove(path);
- yield File.writeAtomic(path, DEFAULT_CONTENTS);
- let exception;
- try {
- yield File.writeAtomic(path, DEFAULT_CONTENTS, { noOverwrite: true });
- } catch (ex) {
- exception = ex;
- }
- do_check_true(exception instanceof File.Error);
- do_check_true(exception.path == path);
-});
-
-add_task(function* testFileError_with_makeDir() {
- let path = Path.join(Constants.Path.tmpDir,
- "directory");
- yield File.removeDir(path);
- yield File.makeDir(path);
- let exception;
- try {
- yield File.makeDir(path, { ignoreExisting: false });
- } catch (ex) {
- exception = ex;
- }
- do_check_true(exception instanceof File.Error);
- do_check_true(exception.path == path);
-});
-
-add_task(function* testFileError_with_move() {
- let DEFAULT_CONTENTS = "default contents" + Math.random();
- let sourcePath = Path.join(Constants.Path.tmpDir,
- "src.tmp");
- let destPath = Path.join(Constants.Path.tmpDir,
- "dest.tmp");
- yield File.remove(sourcePath);
- yield File.remove(destPath);
- yield File.writeAtomic(sourcePath, DEFAULT_CONTENTS);
- yield File.writeAtomic(destPath, DEFAULT_CONTENTS);
- let exception;
- try {
- yield File.move(sourcePath, destPath, { noOverwrite: true });
- } catch (ex) {
- exception = ex;
- }
- do_print(exception);
- do_check_true(exception instanceof File.Error);
- do_check_true(exception.path == sourcePath);
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_kill.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_kill.js
deleted file mode 100644
index e32c37224..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_kill.js
+++ /dev/null
@@ -1,100 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-
-// We want the actual global to get at the internals since Scheduler is not
-// exported.
-var AsyncFrontGlobal = Components.utils.import(
- "resource://gre/modules/osfile/osfile_async_front.jsm",
- null);
-var Scheduler = AsyncFrontGlobal.Scheduler;
-
-/**
- * Verify that Scheduler.kill() interacts with other OS.File requests correctly,
- * and that no requests are lost. This is relevant because on B2G we
- * auto-kill the worker periodically, making it very possible for valid requests
- * to be interleaved with the automatic kill().
- *
- * This test is being created with the fix for Bug 1125989 where `kill` queue
- * management was found to be buggy. It is a glass-box test that explicitly
- * re-creates the observed failure situation; it is not guaranteed to prevent
- * all future regressions. The following is a detailed explanation of the test
- * for your benefit if this test ever breaks or you are wondering what was the
- * point of all this. You might want to skim the code below first.
- *
- * OS.File maintains a `queue` of operations to be performed. This queue is
- * nominally implemented as a chain of promises. Every time a new job is
- * OS.File.push()ed, it effectively becomes the new `queue` promise. (An
- * extra promise is interposed with a rejection handler to avoid the rejection
- * cascading, but that does not matter for our purposes.)
- *
- * The flaw in `kill` was that it would wait for the `queue` to complete before
- * replacing `queue`. As a result, another OS.File operation could use `push`
- * (by way of OS.File.post()) to also use .then() on the same `queue` promise.
- * Accordingly, assuming that promise was not yet resolved (due to a pending
- * OS.File request), when it was resolved, both the task scheduled in `kill`
- * and in `post` would be triggered. Both of those tasks would run until
- * encountering a call to worker.post().
- *
- * Re-creating this race is not entirely trivial because of the large number of
- * promises used by the code causing control flow to repeatedly be deferred. In
- * a slightly simpler world we could run the follwing in the same turn of the
- * event loop and trigger the problem.
- * - any OS.File request
- * - Scheduler.kill()
- * - any OS.File request
- *
- * However, we need the Scheduler.kill task to reach the point where it is
- * waiting on the same `queue` that another task has been scheduled against.
- * Since the `kill` task yields on the `killQueue` promise prior to yielding
- * on `queue`, however, some turns of the event loop are required. Happily,
- * for us, as discussed above, the problem triggers when we have two promises
- * scheduled on the `queue`, so we can just wait to schedule the second OS.File
- * request on the queue. (Note that because of the additional then() added to
- * eat rejections, there is an important difference between the value of
- * `queue` and the value returned by the first OS.File request.)
- */
-add_task(function* test_kill_race() {
- // Ensure the worker has been created and that SET_DEBUG has taken effect.
- // We have chosen OS.File.exists for our tests because it does not trigger
- // a rejection and we absolutely do not care what the operation is other
- // than it does not invoke a native fast-path.
- yield OS.File.exists('foo.foo');
-
- do_print('issuing first request');
- let firstRequest = OS.File.exists('foo.bar');
- let secondRequest;
- let secondResolved = false;
-
- // As noted in our big block comment, we want to wait to schedule the
- // second request so that it races `kill`'s call to `worker.post`. Having
- // ourselves wait on the same promise, `queue`, and registering ourselves
- // before we issue the kill request means we will get run before the `kill`
- // task resumes and allow us to precisely create the desired race.
- Scheduler.queue.then(function() {
- do_print('issuing second request');
- secondRequest = OS.File.exists('foo.baz');
- secondRequest.then(function() {
- secondResolved = true;
- });
- });
-
- do_print('issuing kill request');
- let killRequest = Scheduler.kill({ reset: true, shutdown: false });
-
- // Wait on the killRequest so that we can schedule a new OS.File request
- // after it completes...
- yield killRequest;
- // ...because our ordering guarantee ensures that there is at most one
- // worker (and this usage here should not be vulnerable even with the
- // bug present), so when this completes the secondRequest has either been
- // resolved or lost.
- yield OS.File.exists('foo.goz');
-
- ok(secondResolved,
- 'The second request was resolved so we avoided the bug. Victory!');
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_win_async_setPermissions.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_win_async_setPermissions.js
deleted file mode 100644
index 990d722f5..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_win_async_setPermissions.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * A test to ensure that OS.File.setPermissions and
- * OS.File.prototype.setPermissions are all working correctly.
- * (see bug 1022816)
- * The manifest tests on Windows.
- */
-
-// Sequence of setPermission parameters.
-var testSequence = [
- [ { winAttributes: { readOnly: true, system: true, hidden: true } },
- { readOnly: true, system: true, hidden: true } ],
- [ { winAttributes: { readOnly: false } },
- { readOnly: false, system: true, hidden: true } ],
- [ { winAttributes: { system: false } },
- { readOnly: false, system: false, hidden: true } ],
- [ { winAttributes: { hidden: false } },
- { readOnly: false, system: false, hidden: false } ],
- [ { winAttributes: {readOnly: true, system: false, hidden: false} },
- { readOnly: true, system: false, hidden: false } ],
- [ { winAttributes: {readOnly: false, system: true, hidden: false} },
- { readOnly: false, system: true, hidden: false } ],
- [ { winAttributes: {readOnly: false, system: false, hidden: true} },
- { readOnly: false, system: false, hidden: true } ],
-];
-
-// Test application to paths.
-add_task(function* test_path_setPermissions() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_win_async_setPermissions_path.tmp");
- yield OS.File.writeAtomic(path, new Uint8Array(1));
-
- try {
- for (let [options, attributesExpected] of testSequence) {
- if (options !== null) {
- do_print("Setting permissions to " + JSON.stringify(options));
- yield OS.File.setPermissions(path, options);
- }
-
- let stat = yield OS.File.stat(path);
- do_print("Got stat winAttributes: " + JSON.stringify(stat.winAttributes));
-
- do_check_eq(stat.winAttributes.readOnly, attributesExpected.readOnly);
- do_check_eq(stat.winAttributes.system, attributesExpected.system);
- do_check_eq(stat.winAttributes.hidden, attributesExpected.hidden);
-
- }
- } finally {
- yield OS.File.remove(path);
- }
-});
-
-// Test application to open files.
-add_task(function* test_file_setPermissions() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_win_async_setPermissions_file.tmp");
- yield OS.File.writeAtomic(path, new Uint8Array(1));
-
- try {
- let fd = yield OS.File.open(path, { write: true });
- try {
- for (let [options, attributesExpected] of testSequence) {
- if (options !== null) {
- do_print("Setting permissions to " + JSON.stringify(options));
- yield fd.setPermissions(options);
- }
-
- let stat = yield fd.stat();
- do_print("Got stat winAttributes: " + JSON.stringify(stat.winAttributes));
- do_check_eq(stat.winAttributes.readOnly, attributesExpected.readOnly);
- do_check_eq(stat.winAttributes.system, attributesExpected.system);
- do_check_eq(stat.winAttributes.hidden, attributesExpected.hidden);
- }
- } finally {
- yield fd.close();
- }
- } finally {
- yield OS.File.remove(path);
- }
-});
-
-// Test application to Check setPermissions on a non-existant file path.
-add_task(function* test_non_existant_file_path_setPermissions() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_win_async_setPermissions_path.tmp");
- Assert.rejects(OS.File.setPermissions(path, {winAttributes: {readOnly: true}}),
- /The system cannot find the file specified/,
- "setPermissions failed as expected on a non-existant file path");
-});
-
-// Test application to Check setPermissions on a invalid file handle.
-add_task(function* test_closed_file_handle_setPermissions() {
- let path = OS.Path.join(OS.Constants.Path.tmpDir,
- "test_osfile_win_async_setPermissions_path.tmp");
- yield OS.File.writeAtomic(path, new Uint8Array(1));
-
- try {
- let fd = yield OS.File.open(path, { write: true });
- yield fd.close();
- Assert.rejects(fd.setPermissions(path, {winAttributes: {readOnly: true}}),
- /The handle is invalid/,
- "setPermissions failed as expected on a invalid file handle");
- } finally {
- yield OS.File.remove(path);
- }
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_backupTo_option.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_backupTo_option.js
deleted file mode 100644
index adf345b0c..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_backupTo_option.js
+++ /dev/null
@@ -1,143 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {OS: {File, Path, Constants}} = Components.utils.import("resource://gre/modules/osfile.jsm", {});
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-/**
- * Remove all temporary files and back up files, including
- * test_backupTo_option_with_tmpPath.tmp
- * test_backupTo_option_with_tmpPath.tmp.backup
- * test_backupTo_option_without_tmpPath.tmp
- * test_backupTo_option_without_tmpPath.tmp.backup
- * test_non_backupTo_option.tmp
- * test_non_backupTo_option.tmp.backup
- * test_backupTo_option_without_destination_file.tmp
- * test_backupTo_option_without_destination_file.tmp.backup
- * test_backupTo_option_with_backup_file.tmp
- * test_backupTo_option_with_backup_file.tmp.backup
- */
-function clearFiles() {
- return Task.spawn(function () {
- let files = ["test_backupTo_option_with_tmpPath.tmp",
- "test_backupTo_option_without_tmpPath.tmp",
- "test_non_backupTo_option.tmp",
- "test_backupTo_option_without_destination_file.tmp",
- "test_backupTo_option_with_backup_file.tmp"];
- for (let file of files) {
- let path = Path.join(Constants.Path.tmpDir, file);
- yield File.remove(path);
- yield File.remove(path + ".backup");
- }
- });
-}
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* init() {
- yield clearFiles();
-});
-
-/**
- * test when
- * |backupTo| specified
- * |tmpPath| specified
- * destination file exists
- * @result destination file will be backed up
- */
-add_task(function* test_backupTo_option_with_tmpPath() {
- let DEFAULT_CONTENTS = "default contents" + Math.random();
- let WRITE_CONTENTS = "abc" + Math.random();
- let path = Path.join(Constants.Path.tmpDir,
- "test_backupTo_option_with_tmpPath.tmp");
- yield File.writeAtomic(path, DEFAULT_CONTENTS);
- yield File.writeAtomic(path, WRITE_CONTENTS, { tmpPath: path + ".tmp",
- backupTo: path + ".backup" });
- do_check_true((yield File.exists(path + ".backup")));
- let contents = yield File.read(path + ".backup");
- do_check_eq(DEFAULT_CONTENTS, (new TextDecoder()).decode(contents));
-});
-
-/**
- * test when
- * |backupTo| specified
- * |tmpPath| not specified
- * destination file exists
- * @result destination file will be backed up
- */
-add_task(function* test_backupTo_option_without_tmpPath() {
- let DEFAULT_CONTENTS = "default contents" + Math.random();
- let WRITE_CONTENTS = "abc" + Math.random();
- let path = Path.join(Constants.Path.tmpDir,
- "test_backupTo_option_without_tmpPath.tmp");
- yield File.writeAtomic(path, DEFAULT_CONTENTS);
- yield File.writeAtomic(path, WRITE_CONTENTS, { backupTo: path + ".backup" });
- do_check_true((yield File.exists(path + ".backup")));
- let contents = yield File.read(path + ".backup");
- do_check_eq(DEFAULT_CONTENTS, (new TextDecoder()).decode(contents));
-});
-
-/**
- * test when
- * |backupTo| not specified
- * |tmpPath| not specified
- * destination file exists
- * @result destination file will not be backed up
- */
-add_task(function* test_non_backupTo_option() {
- let DEFAULT_CONTENTS = "default contents" + Math.random();
- let WRITE_CONTENTS = "abc" + Math.random();
- let path = Path.join(Constants.Path.tmpDir,
- "test_non_backupTo_option.tmp");
- yield File.writeAtomic(path, DEFAULT_CONTENTS);
- yield File.writeAtomic(path, WRITE_CONTENTS);
- do_check_false((yield File.exists(path + ".backup")));
-});
-
-/**
- * test when
- * |backupTo| specified
- * |tmpPath| not specified
- * destination file not exists
- * @result no back up file exists
- */
-add_task(function* test_backupTo_option_without_destination_file() {
- let DEFAULT_CONTENTS = "default contents" + Math.random();
- let WRITE_CONTENTS = "abc" + Math.random();
- let path = Path.join(Constants.Path.tmpDir,
- "test_backupTo_option_without_destination_file.tmp");
- yield File.remove(path);
- yield File.writeAtomic(path, WRITE_CONTENTS, { backupTo: path + ".backup" });
- do_check_false((yield File.exists(path + ".backup")));
-});
-
-/**
- * test when
- * |backupTo| specified
- * |tmpPath| not specified
- * backup file exists
- * destination file exists
- * @result destination file will be backed up
- */
-add_task(function* test_backupTo_option_with_backup_file() {
- let DEFAULT_CONTENTS = "default contents" + Math.random();
- let WRITE_CONTENTS = "abc" + Math.random();
- let path = Path.join(Constants.Path.tmpDir,
- "test_backupTo_option_with_backup_file.tmp");
- yield File.writeAtomic(path, DEFAULT_CONTENTS);
-
- yield File.writeAtomic(path + ".backup", new Uint8Array(1000));
-
- yield File.writeAtomic(path, WRITE_CONTENTS, { backupTo: path + ".backup" });
- do_check_true((yield File.exists(path + ".backup")));
- let contents = yield File.read(path + ".backup");
- do_check_eq(DEFAULT_CONTENTS, (new TextDecoder()).decode(contents));
-});
-
-add_task(function* cleanup() {
- yield clearFiles();
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_zerobytes.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_zerobytes.js
deleted file mode 100644
index a32a690e6..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_writeAtomic_zerobytes.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-var SHARED_PATH;
-
-add_task(function* init() {
- do_get_profile();
- SHARED_PATH = OS.Path.join(OS.Constants.Path.profileDir, "test_osfile_write_zerobytes.tmp");
-});
-
-add_test_pair(function* test_osfile_writeAtomic_zerobytes() {
- let encoder = new TextEncoder();
- let string1 = "";
- let outbin = encoder.encode(string1);
- yield OS.File.writeAtomic(SHARED_PATH, outbin);
-
- let decoder = new TextDecoder();
- let bin = yield OS.File.read(SHARED_PATH);
- let string2 = decoder.decode(bin);
- // Checking if writeAtomic supports writing encoded zero-byte strings
- Assert.equal(string2, string1, "Read the expected (empty) string.");
-});
-
-function run_test() {
- run_next_test();
-} \ No newline at end of file
diff --git a/toolkit/components/osfile/tests/xpcshell/test_path.js b/toolkit/components/osfile/tests/xpcshell/test_path.js
deleted file mode 100644
index 76a507ee3..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_path.js
+++ /dev/null
@@ -1,159 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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";
-
-Components.utils.import("resource://gre/modules/Services.jsm", this);
-Services.prefs.setBoolPref("toolkit.osfile.test.syslib_necessary", false);
- // We don't need libc/kernel32.dll for this test
-
-var ImportWin = {};
-var ImportUnix = {};
-Components.utils.import("resource://gre/modules/osfile/ospath_win.jsm", ImportWin);
-Components.utils.import("resource://gre/modules/osfile/ospath_unix.jsm", ImportUnix);
-
-var Win = ImportWin;
-var Unix = ImportUnix;
-
-function do_check_fail(f)
-{
- try {
- let result = f();
- do_print("Failed do_check_fail: " + result);
- do_check_true(false);
- } catch (ex) {
- do_check_true(true);
- }
-};
-
-function run_test()
-{
- do_print("Testing Windows paths");
-
- do_print("Backslash-separated, no drive");
- do_check_eq(Win.basename("a\\b"), "b");
- do_check_eq(Win.basename("a\\b\\"), "");
- do_check_eq(Win.basename("abc"), "abc");
- do_check_eq(Win.dirname("a\\b"), "a");
- do_check_eq(Win.dirname("a\\b\\"), "a\\b");
- do_check_eq(Win.dirname("a\\\\\\\\b"), "a");
- do_check_eq(Win.dirname("abc"), ".");
- do_check_eq(Win.normalize("\\a\\b\\c"), "\\a\\b\\c");
- do_check_eq(Win.normalize("\\a\\b\\\\\\\\c"), "\\a\\b\\c");
- do_check_eq(Win.normalize("\\a\\b\\c\\\\\\"), "\\a\\b\\c");
- do_check_eq(Win.normalize("\\a\\b\\c\\..\\..\\..\\d\\e\\f"), "\\d\\e\\f");
- do_check_eq(Win.normalize("a\\b\\c\\..\\..\\..\\d\\e\\f"), "d\\e\\f");
- do_check_fail(() => Win.normalize("\\a\\b\\c\\..\\..\\..\\..\\d\\e\\f"));
-
- do_check_eq(Win.join("\\tmp", "foo", "bar"), "\\tmp\\foo\\bar", "join \\tmp,foo,bar");
- do_check_eq(Win.join("\\tmp", "\\foo", "bar"), "\\foo\\bar", "join \\tmp,\\foo,bar");
- do_check_eq(Win.winGetDrive("\\tmp"), null);
- do_check_eq(Win.winGetDrive("\\tmp\\a\\b\\c\\d\\e"), null);
- do_check_eq(Win.winGetDrive("\\"), null);
-
-
- do_print("Backslash-separated, with a drive");
- do_check_eq(Win.basename("c:a\\b"), "b");
- do_check_eq(Win.basename("c:a\\b\\"), "");
- do_check_eq(Win.basename("c:abc"), "abc");
- do_check_eq(Win.dirname("c:a\\b"), "c:a");
- do_check_eq(Win.dirname("c:a\\b\\"), "c:a\\b");
- do_check_eq(Win.dirname("c:a\\\\\\\\b"), "c:a");
- do_check_eq(Win.dirname("c:abc"), "c:");
- let options = {
- winNoDrive: true
- };
- do_check_eq(Win.dirname("c:a\\b", options), "a");
- do_check_eq(Win.dirname("c:a\\b\\", options), "a\\b");
- do_check_eq(Win.dirname("c:a\\\\\\\\b", options), "a");
- do_check_eq(Win.dirname("c:abc", options), ".");
- do_check_eq(Win.join("c:", "abc"), "c:\\abc", "join c:,abc");
-
- do_check_eq(Win.normalize("c:"), "c:\\");
- do_check_eq(Win.normalize("c:\\"), "c:\\");
- do_check_eq(Win.normalize("c:\\a\\b\\c"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:\\a\\b\\\\\\\\c"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:\\\\\\\\a\\b\\c"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:\\a\\b\\c\\\\\\"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:\\a\\b\\c\\..\\..\\..\\d\\e\\f"), "c:\\d\\e\\f");
- do_check_eq(Win.normalize("c:a\\b\\c\\..\\..\\..\\d\\e\\f"), "c:\\d\\e\\f");
- do_check_fail(() => Win.normalize("c:\\a\\b\\c\\..\\..\\..\\..\\d\\e\\f"));
-
- do_check_eq(Win.join("c:\\", "foo"), "c:\\foo", "join c:\,foo");
- do_check_eq(Win.join("c:\\tmp", "foo", "bar"), "c:\\tmp\\foo\\bar", "join c:\\tmp,foo,bar");
- do_check_eq(Win.join("c:\\tmp", "\\foo", "bar"), "c:\\foo\\bar", "join c:\\tmp,\\foo,bar");
- do_check_eq(Win.join("c:\\tmp", "c:\\foo", "bar"), "c:\\foo\\bar", "join c:\\tmp,c:\\foo,bar");
- do_check_eq(Win.join("c:\\tmp", "c:foo", "bar"), "c:\\foo\\bar", "join c:\\tmp,c:foo,bar");
- do_check_eq(Win.winGetDrive("c:"), "c:");
- do_check_eq(Win.winGetDrive("c:\\"), "c:");
- do_check_eq(Win.winGetDrive("c:abc"), "c:");
- do_check_eq(Win.winGetDrive("c:abc\\d\\e\\f\\g"), "c:");
- do_check_eq(Win.winGetDrive("c:\\abc"), "c:");
- do_check_eq(Win.winGetDrive("c:\\abc\\d\\e\\f\\g"), "c:");
-
- do_print("Forwardslash-separated, no drive");
- do_check_eq(Win.normalize("/a/b/c"), "\\a\\b\\c");
- do_check_eq(Win.normalize("/a/b////c"), "\\a\\b\\c");
- do_check_eq(Win.normalize("/a/b/c///"), "\\a\\b\\c");
- do_check_eq(Win.normalize("/a/b/c/../../../d/e/f"), "\\d\\e\\f");
- do_check_eq(Win.normalize("a/b/c/../../../d/e/f"), "d\\e\\f");
-
- do_print("Forwardslash-separated, with a drive");
- do_check_eq(Win.normalize("c:/"), "c:\\");
- do_check_eq(Win.normalize("c:/a/b/c"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:/a/b////c"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:////a/b/c"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:/a/b/c///"), "c:\\a\\b\\c");
- do_check_eq(Win.normalize("c:/a/b/c/../../../d/e/f"), "c:\\d\\e\\f");
- do_check_eq(Win.normalize("c:a/b/c/../../../d/e/f"), "c:\\d\\e\\f");
-
- do_print("Backslash-separated, UNC-style");
- do_check_eq(Win.basename("\\\\a\\b"), "b");
- do_check_eq(Win.basename("\\\\a\\b\\"), "");
- do_check_eq(Win.basename("\\\\abc"), "");
- do_check_eq(Win.dirname("\\\\a\\b"), "\\\\a");
- do_check_eq(Win.dirname("\\\\a\\b\\"), "\\\\a\\b");
- do_check_eq(Win.dirname("\\\\a\\\\\\\\b"), "\\\\a");
- do_check_eq(Win.dirname("\\\\abc"), "\\\\abc");
- do_check_eq(Win.normalize("\\\\a\\b\\c"), "\\\\a\\b\\c");
- do_check_eq(Win.normalize("\\\\a\\b\\\\\\\\c"), "\\\\a\\b\\c");
- do_check_eq(Win.normalize("\\\\a\\b\\c\\\\\\"), "\\\\a\\b\\c");
- do_check_eq(Win.normalize("\\\\a\\b\\c\\..\\..\\d\\e\\f"), "\\\\a\\d\\e\\f");
- do_check_fail(() => Win.normalize("\\\\a\\b\\c\\..\\..\\..\\d\\e\\f"));
-
- do_check_eq(Win.join("\\\\a\\tmp", "foo", "bar"), "\\\\a\\tmp\\foo\\bar");
- do_check_eq(Win.join("\\\\a\\tmp", "\\foo", "bar"), "\\\\a\\foo\\bar");
- do_check_eq(Win.join("\\\\a\\tmp", "\\\\foo\\", "bar"), "\\\\foo\\bar");
- do_check_eq(Win.winGetDrive("\\\\"), null);
- do_check_eq(Win.winGetDrive("\\\\c"), "\\\\c");
- do_check_eq(Win.winGetDrive("\\\\c\\abc"), "\\\\c");
-
- do_print("Testing unix paths");
- do_check_eq(Unix.basename("a/b"), "b");
- do_check_eq(Unix.basename("a/b/"), "");
- do_check_eq(Unix.basename("abc"), "abc");
- do_check_eq(Unix.dirname("a/b"), "a");
- do_check_eq(Unix.dirname("a/b/"), "a/b");
- do_check_eq(Unix.dirname("a////b"), "a");
- do_check_eq(Unix.dirname("abc"), ".");
- do_check_eq(Unix.normalize("/a/b/c"), "/a/b/c");
- do_check_eq(Unix.normalize("/a/b////c"), "/a/b/c");
- do_check_eq(Unix.normalize("////a/b/c"), "/a/b/c");
- do_check_eq(Unix.normalize("/a/b/c///"), "/a/b/c");
- do_check_eq(Unix.normalize("/a/b/c/../../../d/e/f"), "/d/e/f");
- do_check_eq(Unix.normalize("a/b/c/../../../d/e/f"), "d/e/f");
- do_check_fail(() => Unix.normalize("/a/b/c/../../../../d/e/f"));
-
- do_check_eq(Unix.join("/tmp", "foo", "bar"), "/tmp/foo/bar", "join /tmp,foo,bar");
- do_check_eq(Unix.join("/tmp", "/foo", "bar"), "/foo/bar", "join /tmp,/foo,bar");
-
- do_print("Testing the presence of ospath.jsm");
- let Scope = {};
- try {
- Components.utils.import("resource://gre/modules/osfile/ospath.jsm", Scope);
- } catch (ex) {
- // Can't load ospath
- }
- do_check_true(!!Scope.basename);
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_path_constants.js b/toolkit/components/osfile/tests/xpcshell/test_path_constants.js
deleted file mode 100644
index 9b9868bb2..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_path_constants.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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";
-
-Cu.import("resource://gre/modules/ctypes.jsm", this);
-Cu.import("resource://testing-common/AppData.jsm", this);
-
-
-function run_test() {
- run_next_test();
-}
-
-function compare_paths(ospath, key) {
- let file;
- try {
- file = Services.dirsvc.get(key, Components.interfaces.nsIFile);
- } catch(ex) {}
-
- if (file) {
- do_check_true(!!ospath);
- do_check_eq(ospath, file.path);
- } else {
- do_print("WARNING: " + key + " is not defined. Test may not be testing anything!");
- do_check_false(!!ospath);
- }
-}
-
-// Some path constants aren't set up until the profile is available. This
-// test verifies that behavior.
-add_task(function* test_before_after_profile() {
- do_check_null(OS.Constants.Path.profileDir);
- do_check_null(OS.Constants.Path.localProfileDir);
- do_check_null(OS.Constants.Path.userApplicationDataDir);
-
- do_get_profile();
- do_check_true(!!OS.Constants.Path.profileDir);
- do_check_true(!!OS.Constants.Path.localProfileDir);
-
- // UAppData is still null because the xpcshell profile doesn't set it up.
- // This test is mostly here to fail in case behavior of do_get_profile() ever
- // changes. We want to know if our assumptions no longer hold!
- do_check_null(OS.Constants.Path.userApplicationDataDir);
-
- yield makeFakeAppDir();
- do_check_true(!!OS.Constants.Path.userApplicationDataDir);
-
- // FUTURE: verify AppData too (bug 964291).
-});
-
-// Test simple paths
-add_task(function* test_simple_paths() {
- do_check_true(!!OS.Constants.Path.tmpDir);
- compare_paths(OS.Constants.Path.tmpDir, "TmpD");
-
-});
-
-// Test presence of paths that only exist on Desktop platforms
-add_task(function* test_desktop_paths() {
- if (OS.Constants.Sys.Name == "Android") {
- return;
- }
- do_check_true(!!OS.Constants.Path.desktopDir);
- do_check_true(!!OS.Constants.Path.homeDir);
-
- compare_paths(OS.Constants.Path.homeDir, "Home");
- compare_paths(OS.Constants.Path.desktopDir, "Desk");
- compare_paths(OS.Constants.Path.userApplicationDataDir, "UAppData");
-
- compare_paths(OS.Constants.Path.winAppDataDir, "AppData");
- compare_paths(OS.Constants.Path.winStartMenuProgsDir, "Progs");
-
- compare_paths(OS.Constants.Path.macUserLibDir, "ULibDir");
- compare_paths(OS.Constants.Path.macLocalApplicationsDir, "LocApp");
- compare_paths(OS.Constants.Path.macTrashDir, "Trsh");
-});
-
-// Open libxul
-add_task(function* test_libxul() {
- ctypes.open(OS.Constants.Path.libxul);
- do_print("Linked to libxul");
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_queue.js b/toolkit/components/osfile/tests/xpcshell/test_queue.js
deleted file mode 100644
index c9d23eabc..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_queue.js
+++ /dev/null
@@ -1,38 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-
-function run_test() {
- run_next_test();
-}
-
-// Check if Scheduler.queue returned by OS.File.queue is resolved initially.
-add_task(function* check_init() {
- yield OS.File.queue;
- do_print("Function resolved");
-});
-
-// Check if Scheduler.queue returned by OS.File.queue is resolved
-// after an operation is successful.
-add_task(function* check_success() {
- do_print("Attempting to open a file correctly");
- let openedFile = yield OS.File.open(OS.Path.join(do_get_cwd().path, "test_queue.js"));
- do_print("File opened correctly");
- yield OS.File.queue;
- do_print("Function resolved");
-});
-
-// Check if Scheduler.queue returned by OS.File.queue is resolved
-// after an operation fails.
-add_task(function* check_failure() {
- let exception;
- try {
- do_print("Attempting to open a non existing file");
- yield OS.File.open(OS.Path.join(".", "Bigfoot"));
- } catch (err) {
- exception = err;
- yield OS.File.queue;
- }
- do_check_true(exception!=null);
- do_print("Function resolved");
-}); \ No newline at end of file
diff --git a/toolkit/components/osfile/tests/xpcshell/test_read_write.js b/toolkit/components/osfile/tests/xpcshell/test_read_write.js
deleted file mode 100644
index 00235ed8c..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_read_write.js
+++ /dev/null
@@ -1,103 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {utils: Cu} = Components;
-
-var SHARED_PATH;
-
-var EXISTING_FILE = do_get_file("xpcshell.ini").path;
-
-add_task(function* init() {
- do_get_profile();
- SHARED_PATH = OS.Path.join(OS.Constants.Path.profileDir, "test_osfile_read.tmp");
-});
-
-
-// Check that OS.File.read() is executed after the previous operation
-add_test_pair(function* ordering() {
- let string1 = "Initial state " + Math.random();
- let string2 = "After writing " + Math.random();
- yield OS.File.writeAtomic(SHARED_PATH, string1);
- OS.File.writeAtomic(SHARED_PATH, string2);
- let string3 = yield OS.File.read(SHARED_PATH, { encoding: "utf-8" });
- do_check_eq(string3, string2);
-});
-
-add_test_pair(function* read_write_all() {
- let DEST_PATH = SHARED_PATH + Math.random();
- let TMP_PATH = DEST_PATH + ".tmp";
-
- let test_with_options = function(options, suffix) {
- return Task.spawn(function*() {
- do_print("Running test read_write_all with options " + JSON.stringify(options));
- let TEST = "read_write_all " + suffix;
-
- let optionsBackup = JSON.parse(JSON.stringify(options));
-
- // Check that read + writeAtomic performs a correct copy
- let currentDir = yield OS.File.getCurrentDirectory();
- let pathSource = OS.Path.join(currentDir, EXISTING_FILE);
- let contents = yield OS.File.read(pathSource);
- do_check_true(!!contents); // Content is not empty
- let bytesRead = contents.byteLength;
-
- let bytesWritten = yield OS.File.writeAtomic(DEST_PATH, contents, options);
- do_check_eq(bytesRead, bytesWritten); // Correct number of bytes written
-
- // Check that options are not altered
- do_check_eq(JSON.stringify(options), JSON.stringify(optionsBackup));
- yield reference_compare_files(pathSource, DEST_PATH, TEST);
-
- // Check that temporary file was removed or never created exist
- do_check_false(new FileUtils.File(TMP_PATH).exists());
-
- // Check that writeAtomic fails if noOverwrite is true and the destination
- // file already exists!
- contents = new Uint8Array(300);
- let view = new Uint8Array(contents.buffer, 10, 200);
- try {
- let opt = JSON.parse(JSON.stringify(options));
- opt.noOverwrite = true;
- yield OS.File.writeAtomic(DEST_PATH, view, opt);
- do_throw("With noOverwrite, writeAtomic should have refused to overwrite file (" + suffix + ")");
- } catch (err if err instanceof OS.File.Error && err.becauseExists) {
- do_print("With noOverwrite, writeAtomic correctly failed (" + suffix + ")");
- }
- yield reference_compare_files(pathSource, DEST_PATH, TEST);
-
- // Check that temporary file was removed or never created
- do_check_false(new FileUtils.File(TMP_PATH).exists());
-
- // Now write a subset
- let START = 10;
- let LENGTH = 100;
- contents = new Uint8Array(300);
- for (var i = 0; i < contents.byteLength; i++)
- contents[i] = i % 256;
- view = new Uint8Array(contents.buffer, START, LENGTH);
- bytesWritten = yield OS.File.writeAtomic(DEST_PATH, view, options);
- do_check_eq(bytesWritten, LENGTH);
-
- let array2 = yield OS.File.read(DEST_PATH);
- do_check_eq(LENGTH, array2.length);
- for (var i = 0; i < LENGTH; i++)
- do_check_eq(array2[i], (i + START) % 256);
-
- // Cleanup.
- yield OS.File.remove(DEST_PATH);
- yield OS.File.remove(TMP_PATH);
- });
- };
-
- yield test_with_options({tmpPath: TMP_PATH}, "Renaming, not flushing");
- yield test_with_options({tmpPath: TMP_PATH, flush: true}, "Renaming, flushing");
- yield test_with_options({}, "Not renaming, not flushing");
- yield test_with_options({flush: true}, "Not renaming, flushing");
-});
-
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_remove.js b/toolkit/components/osfile/tests/xpcshell/test_remove.js
deleted file mode 100644
index c8dc33054..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_remove.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-do_register_cleanup(function() {
- Services.prefs.setBoolPref("toolkit.osfile.log", false);
-});
-
-function run_test() {
- Services.prefs.setBoolPref("toolkit.osfile.log", true);
- run_next_test();
-}
-
-add_task(function* test_ignoreAbsent() {
- let absent_file_name = "test_osfile_front_absent.tmp";
-
- // Removing absent files should throw if "ignoreAbsent" is true.
- yield Assert.rejects(OS.File.remove(absent_file_name, {ignoreAbsent: false}),
- "OS.File.remove throws if there is no such file.");
-
- // Removing absent files should not throw if "ignoreAbsent" is true or not
- // defined.
- let exception = null;
- try {
- yield OS.File.remove(absent_file_name, {ignoreAbsent: true});
- yield OS.File.remove(absent_file_name);
- } catch (ex) {
- exception = ex;
- }
- Assert.ok(!exception, "OS.File.remove should not throw when not requested.");
-});
-
-add_task(function* test_ignoreAbsent_directory_missing() {
- let absent_file_name = OS.Path.join("absent_parent", "test.tmp");
-
- // Removing absent files should throw if "ignoreAbsent" is true.
- yield Assert.rejects(OS.File.remove(absent_file_name, {ignoreAbsent: false}),
- "OS.File.remove throws if there is no such file.");
-
- // Removing files from absent directories should not throw if "ignoreAbsent"
- // is true or not defined.
- let exception = null;
- try {
- yield OS.File.remove(absent_file_name, {ignoreAbsent: true});
- yield OS.File.remove(absent_file_name);
- } catch (ex) {
- exception = ex;
- }
- Assert.ok(!exception, "OS.File.remove should not throw when not requested.");
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_removeDir.js b/toolkit/components/osfile/tests/xpcshell/test_removeDir.js
deleted file mode 100644
index 41ad0eb8c..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_removeDir.js
+++ /dev/null
@@ -1,177 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-do_register_cleanup(function() {
- Services.prefs.setBoolPref("toolkit.osfile.log", false);
-});
-
-function run_test() {
- Services.prefs.setBoolPref("toolkit.osfile.log", true);
-
- run_next_test();
-}
-
-add_task(function() {
- // Set up profile. We create the directory in the profile, because the profile
- // is removed after every test run.
- do_get_profile();
-
- let file = OS.Path.join(OS.Constants.Path.profileDir, "file");
- let dir = OS.Path.join(OS.Constants.Path.profileDir, "directory");
- let file1 = OS.Path.join(dir, "file1");
- let file2 = OS.Path.join(dir, "file2");
- let subDir = OS.Path.join(dir, "subdir");
- let fileInSubDir = OS.Path.join(subDir, "file");
-
- // Sanity checking for the test
- do_check_false((yield OS.File.exists(dir)));
-
- // Remove non-existent directory
- let exception = null;
- try {
- yield OS.File.removeDir(dir, {ignoreAbsent: false});
- } catch (ex) {
- exception = ex;
- }
-
- do_check_true(!!exception);
- do_check_true(exception instanceof OS.File.Error);
-
- // Remove non-existent directory with ignoreAbsent
- yield OS.File.removeDir(dir, {ignoreAbsent: true});
- yield OS.File.removeDir(dir);
-
- // Remove file with ignoreAbsent: false
- yield OS.File.writeAtomic(file, "content", { tmpPath: file + ".tmp" });
- exception = null;
- try {
- yield OS.File.removeDir(file, {ignoreAbsent: false});
- } catch (ex) {
- exception = ex;
- }
-
- do_check_true(!!exception);
- do_check_true(exception instanceof OS.File.Error);
-
- // Remove empty directory
- yield OS.File.makeDir(dir);
- yield OS.File.removeDir(dir);
- do_check_false((yield OS.File.exists(dir)));
-
- // Remove directory that contains one file
- yield OS.File.makeDir(dir);
- yield OS.File.writeAtomic(file1, "content", { tmpPath: file1 + ".tmp" });
- yield OS.File.removeDir(dir);
- do_check_false((yield OS.File.exists(dir)));
-
- // Remove directory that contains multiple files
- yield OS.File.makeDir(dir);
- yield OS.File.writeAtomic(file1, "content", { tmpPath: file1 + ".tmp" });
- yield OS.File.writeAtomic(file2, "content", { tmpPath: file2 + ".tmp" });
- yield OS.File.removeDir(dir);
- do_check_false((yield OS.File.exists(dir)));
-
- // Remove directory that contains a file and a directory
- yield OS.File.makeDir(dir);
- yield OS.File.writeAtomic(file1, "content", { tmpPath: file1 + ".tmp" });
- yield OS.File.makeDir(subDir);
- yield OS.File.writeAtomic(fileInSubDir, "content", { tmpPath: fileInSubDir + ".tmp" });
- yield OS.File.removeDir(dir);
- do_check_false((yield OS.File.exists(dir)));
-});
-
-add_task(function* test_unix_symlink() {
- // Windows does not implement OS.File.unixSymLink()
- if (OS.Constants.Win) {
- return;
- }
-
- // Android / B2G file systems typically don't support symlinks.
- if (OS.Constants.Sys.Name == "Android") {
- return;
- }
-
- let file = OS.Path.join(OS.Constants.Path.profileDir, "file");
- let dir = OS.Path.join(OS.Constants.Path.profileDir, "directory");
- let file1 = OS.Path.join(dir, "file1");
-
- // This test will create the following directory structure:
- // <profileDir>/file (regular file)
- // <profileDir>/file.link => file (symlink)
- // <profileDir>/directory (directory)
- // <profileDir>/linkdir => directory (directory)
- // <profileDir>/directory/file1 (regular file)
- // <profileDir>/directory3 (directory)
- // <profileDir>/directory3/file3 (directory)
- // <profileDir>/directory/link2 => ../directory3 (regular file)
-
- // Sanity checking for the test
- do_check_false((yield OS.File.exists(dir)));
-
- yield OS.File.writeAtomic(file, "content", { tmpPath: file + ".tmp" });
- do_check_true((yield OS.File.exists(file)));
- let info = yield OS.File.stat(file, {unixNoFollowingLinks: true});
- do_check_false(info.isDir);
- do_check_false(info.isSymLink);
-
- yield OS.File.unixSymLink(file, file + ".link");
- do_check_true((yield OS.File.exists(file + ".link")));
- info = yield OS.File.stat(file + ".link", {unixNoFollowingLinks: true});
- do_check_false(info.isDir);
- do_check_true(info.isSymLink);
- info = yield OS.File.stat(file + ".link");
- do_check_false(info.isDir);
- do_check_false(info.isSymLink);
- yield OS.File.remove(file + ".link");
- do_check_false((yield OS.File.exists(file + ".link")));
-
- yield OS.File.makeDir(dir);
- do_check_true((yield OS.File.exists(dir)));
- info = yield OS.File.stat(dir, {unixNoFollowingLinks: true});
- do_check_true(info.isDir);
- do_check_false(info.isSymLink);
-
- let link = OS.Path.join(OS.Constants.Path.profileDir, "linkdir");
-
- yield OS.File.unixSymLink(dir, link);
- do_check_true((yield OS.File.exists(link)));
- info = yield OS.File.stat(link, {unixNoFollowingLinks: true});
- do_check_false(info.isDir);
- do_check_true(info.isSymLink);
- info = yield OS.File.stat(link);
- do_check_true(info.isDir);
- do_check_false(info.isSymLink);
-
- let dir3 = OS.Path.join(OS.Constants.Path.profileDir, "directory3");
- let file3 = OS.Path.join(dir3, "file3");
- let link2 = OS.Path.join(dir, "link2");
-
- yield OS.File.writeAtomic(file1, "content", { tmpPath: file1 + ".tmp" });
- do_check_true((yield OS.File.exists(file1)));
- yield OS.File.makeDir(dir3);
- do_check_true((yield OS.File.exists(dir3)));
- yield OS.File.writeAtomic(file3, "content", { tmpPath: file3 + ".tmp" });
- do_check_true((yield OS.File.exists(file3)));
- yield OS.File.unixSymLink("../directory3", link2);
- do_check_true((yield OS.File.exists(link2)));
-
- yield OS.File.removeDir(link);
- do_check_false((yield OS.File.exists(link)));
- do_check_true((yield OS.File.exists(file1)));
- yield OS.File.removeDir(dir);
- do_check_false((yield OS.File.exists(dir)));
- do_check_true((yield OS.File.exists(file3)));
- yield OS.File.removeDir(dir3);
- do_check_false((yield OS.File.exists(dir3)));
-
- // This task will be executed only on Unix-like systems.
- // Please do not add tests independent to operating systems here
- // or implement symlink() on Windows.
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_removeEmptyDir.js b/toolkit/components/osfile/tests/xpcshell/test_removeEmptyDir.js
deleted file mode 100644
index 95f8d5cd1..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_removeEmptyDir.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-do_register_cleanup(function() {
- Services.prefs.setBoolPref("toolkit.osfile.log", false);
-});
-
-function run_test() {
- Services.prefs.setBoolPref("toolkit.osfile.log", true);
-
- run_next_test();
-}
-
-/**
- * Test OS.File.removeEmptyDir
- */
-add_task(function() {
- // Set up profile. We create the directory in the profile, because the profile
- // is removed after every test run.
- do_get_profile();
-
- let dir = OS.Path.join(OS.Constants.Path.profileDir, "directory");
-
- // Sanity checking for the test
- do_check_false((yield OS.File.exists(dir)));
-
- // Remove non-existent directory
- yield OS.File.removeEmptyDir(dir);
-
- // Remove non-existent directory with ignoreAbsent
- yield OS.File.removeEmptyDir(dir, {ignoreAbsent: true});
-
- // Remove non-existent directory with ignoreAbsent false
- let exception = null;
- try {
- yield OS.File.removeEmptyDir(dir, {ignoreAbsent: false});
- } catch (ex) {
- exception = ex;
- }
-
- do_check_true(!!exception);
- do_check_true(exception instanceof OS.File.Error);
- do_check_true(exception.becauseNoSuchFile);
-
- // Remove empty directory
- yield OS.File.makeDir(dir);
- yield OS.File.removeEmptyDir(dir);
- do_check_false((yield OS.File.exists(dir)));
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/test_reset.js b/toolkit/components/osfile/tests/xpcshell/test_reset.js
deleted file mode 100644
index f1e1b14d1..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_reset.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var Path = OS.Constants.Path;
-
-add_task(function* init() {
- do_get_profile();
-});
-
-add_task(function* reset_before_launching() {
- do_print("Reset without launching OS.File, it shouldn't break");
- yield OS.File.resetWorker();
-});
-
-add_task(function* transparent_reset() {
- for (let i = 1; i < 3; ++i) {
- do_print("Do stome stuff before and after " + i + " reset(s), " +
- "it shouldn't break");
- let CONTENT = "some content " + i;
- let path = OS.Path.join(Path.profileDir, "tmp");
- yield OS.File.writeAtomic(path, CONTENT);
- for (let j = 0; j < i; ++j) {
- yield OS.File.resetWorker();
- }
- let data = yield OS.File.read(path);
- let string = (new TextDecoder()).decode(data);
- do_check_eq(string, CONTENT);
- }
-});
-
-add_task(function* file_open_cannot_reset() {
- let TEST_FILE = OS.Path.join(Path.profileDir, "tmp-" + Math.random());
- do_print("Leaking file descriptor " + TEST_FILE + ", we shouldn't be able to reset");
- let openedFile = yield OS.File.open(TEST_FILE, { create: true} );
- let thrown = false;
- try {
- yield OS.File.resetWorker();
- } catch (ex if ex.message.indexOf(OS.Path.basename(TEST_FILE)) != -1 ) {
- thrown = true;
- }
- do_check_true(thrown);
-
- do_print("Closing the file, we should now be able to reset");
- yield openedFile.close();
- yield OS.File.resetWorker();
-});
-
-add_task(function* dir_open_cannot_reset() {
- let TEST_DIR = yield OS.File.getCurrentDirectory();
- do_print("Leaking directory " + TEST_DIR + ", we shouldn't be able to reset");
- let iterator = new OS.File.DirectoryIterator(TEST_DIR);
- let thrown = false;
- try {
- yield OS.File.resetWorker();
- } catch (ex if ex.message.indexOf(OS.Path.basename(TEST_DIR)) != -1 ) {
- thrown = true;
- }
- do_check_true(thrown);
-
- do_print("Closing the directory, we should now be able to reset");
- yield iterator.close();
- yield OS.File.resetWorker();
-});
-
-add_task(function* race_against_itself() {
- do_print("Attempt to get resetWorker() to race against itself");
- // Arbitrary operation, just to wake up the worker
- try {
- yield OS.File.read("/foo");
- } catch (ex) {
- }
-
- let all = [];
- for (let i = 0; i < 100; ++i) {
- all.push(OS.File.resetWorker());
- }
-
- yield Promise.all(all);
-});
-
-
-add_task(function* finish_with_a_reset() {
- do_print("Reset without waiting for the result");
- // Arbitrary operation, just to wake up the worker
- try {
- yield OS.File.read("/foo");
- } catch (ex) {
- }
- // Now reset
- /*don't yield*/ OS.File.resetWorker();
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_shutdown.js b/toolkit/components/osfile/tests/xpcshell/test_shutdown.js
deleted file mode 100644
index 667965d9e..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_shutdown.js
+++ /dev/null
@@ -1,98 +0,0 @@
-Components.utils.import("resource://gre/modules/Services.jsm", this);
-Components.utils.import("resource://gre/modules/Promise.jsm", this);
-Components.utils.import("resource://gre/modules/Task.jsm", this);
-Components.utils.import("resource://gre/modules/osfile.jsm", this);
-
-add_task(function init() {
- do_get_profile();
-});
-
-/**
- * Test logging of file descriptors leaks.
- */
-add_task(function system_shutdown() {
-
- // Test that unclosed files cause warnings
- // Test that unclosed directories cause warnings
- // Test that closed files do not cause warnings
- // Test that closed directories do not cause warnings
- function testLeaksOf(resource, topic) {
- return Task.spawn(function() {
- let deferred = Promise.defer();
-
- // Register observer
- Services.prefs.setBoolPref("toolkit.asyncshutdown.testing", true);
- Services.prefs.setBoolPref("toolkit.osfile.log", true);
- Services.prefs.setBoolPref("toolkit.osfile.log.redirect", true);
- Services.prefs.setCharPref("toolkit.osfile.test.shutdown.observer", topic);
-
- let observer = function(aMessage) {
- try {
- do_print("Got message: " + aMessage);
- if (!(aMessage instanceof Components.interfaces.nsIConsoleMessage)) {
- return;
- }
- let message = aMessage.message;
- do_print("Got message: " + message);
- if (message.indexOf("TEST OS Controller WARNING") < 0) {
- return;
- }
- do_print("Got message: " + message + ", looking for resource " + resource);
- if (message.indexOf(resource) < 0) {
- return;
- }
- do_print("Resource: " + resource + " found");
- do_execute_soon(deferred.resolve);
- } catch (ex) {
- do_execute_soon(function() {
- deferred.reject(ex);
- });
- }
- };
- Services.console.registerListener(observer);
- Services.obs.notifyObservers(null, topic, null);
- do_timeout(1000, function() {
- do_print("Timeout while waiting for resource: " + resource);
- deferred.reject("timeout");
- });
-
- let resolved = false;
- try {
- yield deferred.promise;
- resolved = true;
- } catch (ex if ex == "timeout") {
- resolved = false;
- }
- Services.console.unregisterListener(observer);
- Services.prefs.clearUserPref("toolkit.osfile.log");
- Services.prefs.clearUserPref("toolkit.osfile.log.redirect");
- Services.prefs.clearUserPref("toolkit.osfile.test.shutdown.observer");
- Services.prefs.clearUserPref("toolkit.async_shutdown.testing", true);
-
- throw new Task.Result(resolved);
- });
- }
-
- let TEST_DIR = OS.Path.join((yield OS.File.getCurrentDirectory()), "..");
- do_print("Testing for leaks of directory iterator " + TEST_DIR);
- let iterator = new OS.File.DirectoryIterator(TEST_DIR);
- do_print("At this stage, we leak the directory");
- do_check_true((yield testLeaksOf(TEST_DIR, "test.shutdown.dir.leak")));
- yield iterator.close();
- do_print("At this stage, we don't leak the directory anymore");
- do_check_false((yield testLeaksOf(TEST_DIR, "test.shutdown.dir.noleak")));
-
- let TEST_FILE = OS.Path.join(OS.Constants.Path.profileDir, "test");
- do_print("Testing for leaks of file descriptor: " + TEST_FILE);
- let openedFile = yield OS.File.open(TEST_FILE, { create: true} );
- do_print("At this stage, we leak the file");
- do_check_true((yield testLeaksOf(TEST_FILE, "test.shutdown.file.leak")));
- yield openedFile.close();
- do_print("At this stage, we don't leak the file anymore");
- do_check_false((yield testLeaksOf(TEST_FILE, "test.shutdown.file.leak.2")));
-});
-
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_telemetry.js b/toolkit/components/osfile/tests/xpcshell/test_telemetry.js
deleted file mode 100644
index dc5104443..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_telemetry.js
+++ /dev/null
@@ -1,63 +0,0 @@
-"use strict";
-
-var {OS: {File, Path, Constants}} = Components.utils.import("resource://gre/modules/osfile.jsm", {});
-var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
-
-// Ensure that we have a profile but that the OS.File worker is not launched
-add_task(function* init() {
- do_get_profile();
- yield File.resetWorker();
-});
-
-function getCount(histogram) {
- if (histogram == null) {
- return 0;
- }
-
- let total = 0;
- for (let i of histogram.counts) {
- total += i;
- }
- return total;
-}
-
-// Ensure that launching the OS.File worker adds data to the relevant
-// histograms
-add_task(function* test_startup() {
- let LAUNCH = "OSFILE_WORKER_LAUNCH_MS";
- let READY = "OSFILE_WORKER_READY_MS";
-
- let before = Services.telemetry.histogramSnapshots;
-
- // Launch the OS.File worker
- yield File.getCurrentDirectory();
-
- let after = Services.telemetry.histogramSnapshots;
-
-
- do_print("Ensuring that we have recorded measures for histograms");
- do_check_eq(getCount(after[LAUNCH]), getCount(before[LAUNCH]) + 1);
- do_check_eq(getCount(after[READY]), getCount(before[READY]) + 1);
-
- do_print("Ensuring that launh <= ready");
- do_check_true(after[LAUNCH].sum <= after[READY].sum);
-});
-
-// Ensure that calling writeAtomic adds data to the relevant histograms
-add_task(function* test_writeAtomic() {
- let LABEL = "OSFILE_WRITEATOMIC_JANK_MS";
-
- let before = Services.telemetry.histogramSnapshots;
-
- // Perform a write.
- let path = Path.join(Constants.Path.profileDir, "test_osfile_telemetry.tmp");
- yield File.writeAtomic(path, LABEL, { tmpPath: path + ".tmp" } );
-
- let after = Services.telemetry.histogramSnapshots;
-
- do_check_eq(getCount(after[LABEL]), getCount(before[LABEL]) + 1);
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/osfile/tests/xpcshell/test_unique.js b/toolkit/components/osfile/tests/xpcshell/test_unique.js
deleted file mode 100644
index 8aa81b803..000000000
--- a/toolkit/components/osfile/tests/xpcshell/test_unique.js
+++ /dev/null
@@ -1,88 +0,0 @@
-"use strict";
-
-Components.utils.import("resource://gre/modules/osfile.jsm");
-Components.utils.import("resource://gre/modules/Task.jsm");
-
-function run_test() {
- do_get_profile();
- run_next_test();
-}
-
-function testFiles(filename) {
- return Task.spawn(function() {
- const MAX_TRIES = 10;
- let profileDir = OS.Constants.Path.profileDir;
- let path = OS.Path.join(profileDir, filename);
-
- // Ensure that openUnique() uses the file name if there is no file with that name already.
- let openedFile = yield OS.File.openUnique(path);
- do_print("\nCreate new file: " + openedFile.path);
- yield openedFile.file.close();
- let exists = yield OS.File.exists(openedFile.path);
- do_check_true(exists);
- do_check_eq(path, openedFile.path);
- let fileInfo = yield OS.File.stat(openedFile.path);
- do_check_true(fileInfo.size == 0);
-
- // Ensure that openUnique() creates a new file name using a HEX number, as the original name is already taken.
- openedFile = yield OS.File.openUnique(path);
- do_print("\nCreate unique HEX file: " + openedFile.path);
- yield openedFile.file.close();
- exists = yield OS.File.exists(openedFile.path);
- do_check_true(exists);
- fileInfo = yield OS.File.stat(openedFile.path);
- do_check_true(fileInfo.size == 0);
-
- // Ensure that openUnique() generates different file names each time, using the HEX number algorithm
- let filenames = new Set();
- for (let i=0; i < MAX_TRIES; i++) {
- openedFile = yield OS.File.openUnique(path);
- yield openedFile.file.close();
- filenames.add(openedFile.path);
- }
-
- do_check_eq(filenames.size, MAX_TRIES);
-
- // Ensure that openUnique() creates a new human readable file name using, as the original name is already taken.
- openedFile = yield OS.File.openUnique(path, {humanReadable : true});
- do_print("\nCreate unique Human Readable file: " + openedFile.path);
- yield openedFile.file.close();
- exists = yield OS.File.exists(openedFile.path);
- do_check_true(exists);
- fileInfo = yield OS.File.stat(openedFile.path);
- do_check_true(fileInfo.size == 0);
-
- // Ensure that openUnique() generates different human readable file names each time
- filenames = new Set();
- for (let i=0; i < MAX_TRIES; i++) {
- openedFile = yield OS.File.openUnique(path, {humanReadable : true});
- yield openedFile.file.close();
- filenames.add(openedFile.path);
- }
-
- do_check_eq(filenames.size, MAX_TRIES);
-
- let exn;
- try {
- for (let i=0; i < 100; i++) {
- openedFile = yield OS.File.openUnique(path, {humanReadable : true});
- yield openedFile.file.close();
- }
- } catch (ex) {
- exn = ex;
- }
-
- do_print("Ensure that this raises the correct error");
- do_check_true(!!exn);
- do_check_true(exn instanceof OS.File.Error);
- do_check_true(exn.becauseExists);
- });
-}
-
-add_task(function test_unique() {
- OS.Shared.DEBUG = true;
- // Tests files with extension
- yield testFiles("dummy_unique_file.txt");
- // Tests files with no extension
- yield testFiles("dummy_unique_file_no_ext");
-});
diff --git a/toolkit/components/osfile/tests/xpcshell/xpcshell.ini b/toolkit/components/osfile/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index 58b106d3d..000000000
--- a/toolkit/components/osfile/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,51 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-
-support-files =
- test_loader/module_test_loader.js
-
-[test_available_free_space.js]
-[test_compression.js]
-[test_constants.js]
-[test_creationDate.js]
-[test_duration.js]
-[test_exception.js]
-[test_file_URL_conversion.js]
-[test_loader.js]
-[test_logging.js]
-[test_makeDir.js]
-[test_open.js]
-[test_osfile_async.js]
-[test_osfile_async_append.js]
-[test_osfile_async_bytes.js]
-[test_osfile_async_copy.js]
-[test_osfile_async_flush.js]
-[test_osfile_async_largefiles.js]
-[test_osfile_async_setDates.js]
-# Unimplemented on Windows (bug 1022816).
-# Spurious failure on Android test farm due to non-POSIX behavior of
-# filesystem backing /mnt/sdcard (not worth trying to fix).
-[test_osfile_async_setPermissions.js]
-skip-if = os == "win" || os == "android"
-[test_osfile_closed.js]
-[test_osfile_error.js]
-[test_osfile_kill.js]
-# Windows test
-[test_osfile_win_async_setPermissions.js]
-skip-if = os != "win"
-[test_osfile_writeAtomic_backupTo_option.js]
-[test_osfile_writeAtomic_zerobytes.js]
-[test_path.js]
-[test_path_constants.js]
-[test_queue.js]
-[test_read_write.js]
-requesttimeoutfactor = 4
-[test_remove.js]
-[test_removeDir.js]
-requesttimeoutfactor = 4
-[test_removeEmptyDir.js]
-[test_reset.js]
-[test_shutdown.js]
-[test_telemetry.js]
-[test_unique.js]
diff --git a/toolkit/components/passwordmgr/moz.build b/toolkit/components/passwordmgr/moz.build
index af9a4ab03..189f4925b 100644
--- a/toolkit/components/passwordmgr/moz.build
+++ b/toolkit/components/passwordmgr/moz.build
@@ -7,17 +7,6 @@
if CONFIG['MOZ_PHOENIX']:
DEFINES['MOZ_BUILD_APP_IS_BROWSER'] = True
-MOCHITEST_MANIFESTS += ['test/mochitest.ini', 'test/mochitest/mochitest.ini']
-MOCHITEST_CHROME_MANIFESTS += ['test/chrome/chrome.ini']
-BROWSER_CHROME_MANIFESTS += ['test/browser/browser.ini']
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-
-TESTING_JS_MODULES += [
- # Make this file available from the "resource:" URI of the test environment.
- 'test/browser/form_basic.html',
- 'test/LoginTestUtils.jsm',
-]
-
XPIDL_SOURCES += [
'nsILoginInfo.idl',
'nsILoginManager.idl',
@@ -74,6 +63,3 @@ if CONFIG['MOZ_PHOENIX']:
]
JAR_MANIFESTS += ['jar.mn']
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Password Manager')
diff --git a/toolkit/components/passwordmgr/test/.eslintrc.js b/toolkit/components/passwordmgr/test/.eslintrc.js
deleted file mode 100644
index ca626f31c..000000000
--- a/toolkit/components/passwordmgr/test/.eslintrc.js
+++ /dev/null
@@ -1,13 +0,0 @@
-"use strict";
-
-module.exports = { // eslint-disable-line no-undef
- "extends": [
- "../../../../testing/mochitest/mochitest.eslintrc.js",
- "../../../../testing/mochitest/chrome.eslintrc.js"
- ],
- "rules": {
- "brace-style": "off",
- "no-undef": "off",
- "no-unused-vars": "off",
- },
-};
diff --git a/toolkit/components/passwordmgr/test/LoginTestUtils.jsm b/toolkit/components/passwordmgr/test/LoginTestUtils.jsm
deleted file mode 100644
index 2fd8a31a3..000000000
--- a/toolkit/components/passwordmgr/test/LoginTestUtils.jsm
+++ /dev/null
@@ -1,295 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Shared functions generally available for testing login components.
- */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = [
- "LoginTestUtils",
-];
-
-const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-Cu.import("resource://testing-common/TestUtils.jsm");
-
-const LoginInfo =
- Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- "nsILoginInfo", "init");
-
-// For now, we need consumers to provide a reference to Assert.jsm.
-var Assert = null;
-
-this.LoginTestUtils = {
- set Assert(assert) {
- Assert = assert; // eslint-disable-line no-native-reassign
- },
-
- /**
- * Forces the storage module to save all data, and the Login Manager service
- * to replace the storage module with a newly initialized instance.
- */
- * reloadData() {
- Services.obs.notifyObservers(null, "passwordmgr-storage-replace", null);
- yield TestUtils.topicObserved("passwordmgr-storage-replace-complete");
- },
-
- /**
- * Erases all the data stored by the Login Manager service.
- */
- clearData() {
- Services.logins.removeAllLogins();
- for (let hostname of Services.logins.getAllDisabledHosts()) {
- Services.logins.setLoginSavingEnabled(hostname, true);
- }
- },
-
- /**
- * Checks that the currently stored list of nsILoginInfo matches the provided
- * array. The comparison uses the "equals" method of nsILoginInfo, that does
- * not include nsILoginMetaInfo properties in the test.
- */
- checkLogins(expectedLogins) {
- this.assertLoginListsEqual(Services.logins.getAllLogins(), expectedLogins);
- },
-
- /**
- * Checks that the two provided arrays of nsILoginInfo have the same length,
- * and every login in "expected" is also found in "actual". The comparison
- * uses the "equals" method of nsILoginInfo, that does not include
- * nsILoginMetaInfo properties in the test.
- */
- assertLoginListsEqual(actual, expected) {
- Assert.equal(expected.length, actual.length);
- Assert.ok(expected.every(e => actual.some(a => a.equals(e))));
- },
-
- /**
- * Checks that the two provided arrays of strings contain the same values,
- * maybe in a different order, case-sensitively.
- */
- assertDisabledHostsEqual(actual, expected) {
- Assert.deepEqual(actual.sort(), expected.sort());
- },
-
- /**
- * Checks whether the given time, expressed as the number of milliseconds
- * since January 1, 1970, 00:00:00 UTC, falls within 30 seconds of now.
- */
- assertTimeIsAboutNow(timeMs) {
- Assert.ok(Math.abs(timeMs - Date.now()) < 30000);
- },
-};
-
-/**
- * This object contains functions that return new instances of nsILoginInfo for
- * every call. The returned instances can be compared using their "equals" or
- * "matches" methods, or modified for the needs of the specific test being run.
- *
- * Any modification to the test data requires updating the tests accordingly, in
- * particular the search tests.
- */
-this.LoginTestUtils.testData = {
- /**
- * Returns a new nsILoginInfo for use with form submits.
- *
- * @param modifications
- * Each property of this object replaces the property of the same name
- * in the returned nsILoginInfo or nsILoginMetaInfo.
- */
- formLogin(modifications) {
- let loginInfo = new LoginInfo("http://www3.example.com",
- "http://www.example.com", null,
- "the username", "the password",
- "form_field_username", "form_field_password");
- loginInfo.QueryInterface(Ci.nsILoginMetaInfo);
- if (modifications) {
- for (let [name, value] of Object.entries(modifications)) {
- loginInfo[name] = value;
- }
- }
- return loginInfo;
- },
-
- /**
- * Returns a new nsILoginInfo for use with HTTP authentication.
- *
- * @param modifications
- * Each property of this object replaces the property of the same name
- * in the returned nsILoginInfo or nsILoginMetaInfo.
- */
- authLogin(modifications) {
- let loginInfo = new LoginInfo("http://www.example.org", null,
- "The HTTP Realm", "the username",
- "the password", "", "");
- loginInfo.QueryInterface(Ci.nsILoginMetaInfo);
- if (modifications) {
- for (let [name, value] of Object.entries(modifications)) {
- loginInfo[name] = value;
- }
- }
- return loginInfo;
- },
-
- /**
- * Returns an array of typical nsILoginInfo that could be stored in the
- * database.
- */
- loginList() {
- return [
- // --- Examples of form logins (subdomains of example.com) ---
-
- // Simple form login with named fields for username and password.
- new LoginInfo("http://www.example.com", "http://www.example.com", null,
- "the username", "the password for www.example.com",
- "form_field_username", "form_field_password"),
-
- // Different schemes are treated as completely different sites.
- new LoginInfo("https://www.example.com", "https://www.example.com", null,
- "the username", "the password for https",
- "form_field_username", "form_field_password"),
-
- // Subdomains are treated as completely different sites.
- new LoginInfo("https://example.com", "https://example.com", null,
- "the username", "the password for example.com",
- "form_field_username", "form_field_password"),
-
- // Forms found on the same host, but with different hostnames in the
- // "action" attribute, are handled independently.
- new LoginInfo("http://www3.example.com", "http://www.example.com", null,
- "the username", "the password",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://www3.example.com", "https://www.example.com", null,
- "the username", "the password",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://www3.example.com", "http://example.com", null,
- "the username", "the password",
- "form_field_username", "form_field_password"),
-
- // It is not possible to store multiple passwords for the same username,
- // however multiple passwords can be stored when the usernames differ.
- // An empty username is a valid case and different from the others.
- new LoginInfo("http://www4.example.com", "http://www4.example.com", null,
- "username one", "password one",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://www4.example.com", "http://www4.example.com", null,
- "username two", "password two",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://www4.example.com", "http://www4.example.com", null,
- "", "password three",
- "form_field_username", "form_field_password"),
-
- // Username and passwords fields in forms may have no "name" attribute.
- new LoginInfo("http://www5.example.com", "http://www5.example.com", null,
- "multi username", "multi password", "", ""),
-
- // Forms with PIN-type authentication will typically have no username.
- new LoginInfo("http://www6.example.com", "http://www6.example.com", null,
- "", "12345", "", "form_field_password"),
-
- // --- Examples of authentication logins (subdomains of example.org) ---
-
- // Simple HTTP authentication login.
- new LoginInfo("http://www.example.org", null, "The HTTP Realm",
- "the username", "the password", "", ""),
-
- // Simple FTP authentication login.
- new LoginInfo("ftp://ftp.example.org", null, "ftp://ftp.example.org",
- "the username", "the password", "", ""),
-
- // Multiple HTTP authentication logins can be stored for different realms.
- new LoginInfo("http://www2.example.org", null, "The HTTP Realm",
- "the username", "the password", "", ""),
- new LoginInfo("http://www2.example.org", null, "The HTTP Realm Other",
- "the username other", "the password other", "", ""),
-
- // --- Both form and authentication logins (example.net) ---
-
- new LoginInfo("http://example.net", "http://example.net", null,
- "the username", "the password",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://example.net", "http://www.example.net", null,
- "the username", "the password",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://example.net", "http://www.example.net", null,
- "username two", "the password",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://example.net", null, "The HTTP Realm",
- "the username", "the password", "", ""),
- new LoginInfo("http://example.net", null, "The HTTP Realm Other",
- "username two", "the password", "", ""),
- new LoginInfo("ftp://example.net", null, "ftp://example.net",
- "the username", "the password", "", ""),
-
- // --- Examples of logins added by extensions (chrome scheme) ---
-
- new LoginInfo("chrome://example_extension", null, "Example Login One",
- "the username", "the password one", "", ""),
- new LoginInfo("chrome://example_extension", null, "Example Login Two",
- "the username", "the password two", "", ""),
- ];
- },
-};
-
-this.LoginTestUtils.recipes = {
- getRecipeParent() {
- let { LoginManagerParent } = Cu.import("resource://gre/modules/LoginManagerParent.jsm", {});
- if (!LoginManagerParent.recipeParentPromise) {
- return null;
- }
- return LoginManagerParent.recipeParentPromise.then((recipeParent) => {
- return recipeParent;
- });
- },
-};
-
-this.LoginTestUtils.masterPassword = {
- masterPassword: "omgsecret!",
-
- _set(enable) {
- let oldPW, newPW;
- if (enable) {
- oldPW = "";
- newPW = this.masterPassword;
- } else {
- oldPW = this.masterPassword;
- newPW = "";
- }
-
- let secmodDB = Cc["@mozilla.org/security/pkcs11moduledb;1"]
- .getService(Ci.nsIPKCS11ModuleDB);
- let slot = secmodDB.findSlotByName("");
- if (!slot) {
- throw new Error("Can't find slot");
- }
-
- // Set master password. Note that this does not log you in, so the next
- // invocation of pwmgr can trigger a MP prompt.
- let pk11db = Cc["@mozilla.org/security/pk11tokendb;1"]
- .getService(Ci.nsIPK11TokenDB);
- let token = pk11db.findTokenByName("");
- if (slot.status == Ci.nsIPKCS11Slot.SLOT_UNINITIALIZED) {
- dump("MP initialized to " + newPW + "\n");
- token.initPassword(newPW);
- } else {
- token.checkPassword(oldPW);
- dump("MP change from " + oldPW + " to " + newPW + "\n");
- token.changePassword(oldPW, newPW);
- }
- },
-
- enable() {
- this._set(true);
- },
-
- disable() {
- this._set(false);
- },
-};
diff --git a/toolkit/components/passwordmgr/test/authenticate.sjs b/toolkit/components/passwordmgr/test/authenticate.sjs
deleted file mode 100644
index 42edc3220..000000000
--- a/toolkit/components/passwordmgr/test/authenticate.sjs
+++ /dev/null
@@ -1,228 +0,0 @@
-function handleRequest(request, response)
-{
- try {
- reallyHandleRequest(request, response);
- } catch (e) {
- response.setStatusLine("1.0", 200, "AlmostOK");
- response.write("Error handling request: " + e);
- }
-}
-
-
-function reallyHandleRequest(request, response) {
- var match;
- var requestAuth = true, requestProxyAuth = true;
-
- // Allow the caller to drive how authentication is processed via the query.
- // Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
- // The extra ? allows the user/pass/realm checks to succeed if the name is
- // at the beginning of the query string.
- var query = "?" + request.queryString;
-
- var expected_user = "", expected_pass = "", realm = "mochitest";
- var proxy_expected_user = "", proxy_expected_pass = "", proxy_realm = "mochi-proxy";
- var huge = false, plugin = false, anonymous = false, formauth = false;
- var authHeaderCount = 1;
- // user=xxx
- match = /[^_]user=([^&]*)/.exec(query);
- if (match)
- expected_user = match[1];
-
- // pass=xxx
- match = /[^_]pass=([^&]*)/.exec(query);
- if (match)
- expected_pass = match[1];
-
- // realm=xxx
- match = /[^_]realm=([^&]*)/.exec(query);
- if (match)
- realm = match[1];
-
- // proxy_user=xxx
- match = /proxy_user=([^&]*)/.exec(query);
- if (match)
- proxy_expected_user = match[1];
-
- // proxy_pass=xxx
- match = /proxy_pass=([^&]*)/.exec(query);
- if (match)
- proxy_expected_pass = match[1];
-
- // proxy_realm=xxx
- match = /proxy_realm=([^&]*)/.exec(query);
- if (match)
- proxy_realm = match[1];
-
- // huge=1
- match = /huge=1/.exec(query);
- if (match)
- huge = true;
-
- // plugin=1
- match = /plugin=1/.exec(query);
- if (match)
- plugin = true;
-
- // multiple=1
- match = /multiple=([^&]*)/.exec(query);
- if (match)
- authHeaderCount = match[1]+0;
-
- // anonymous=1
- match = /anonymous=1/.exec(query);
- if (match)
- anonymous = true;
-
- // formauth=1
- match = /formauth=1/.exec(query);
- if (match)
- formauth = true;
-
- // Look for an authentication header, if any, in the request.
- //
- // EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
- //
- // This test only supports Basic auth. The value sent by the client is
- // "username:password", obscured with base64 encoding.
-
- var actual_user = "", actual_pass = "", authHeader, authPresent = false;
- if (request.hasHeader("Authorization")) {
- authPresent = true;
- authHeader = request.getHeader("Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw new Error("Couldn't parse auth header: " + authHeader);
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw new Error("Couldn't decode auth header: " + userpass);
- actual_user = match[1];
- actual_pass = match[2];
- }
-
- var proxy_actual_user = "", proxy_actual_pass = "";
- if (request.hasHeader("Proxy-Authorization")) {
- authHeader = request.getHeader("Proxy-Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw new Error("Couldn't parse auth header: " + authHeader);
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw new Error("Couldn't decode auth header: " + userpass);
- proxy_actual_user = match[1];
- proxy_actual_pass = match[2];
- }
-
- // Don't request authentication if the credentials we got were what we
- // expected.
- if (expected_user == actual_user &&
- expected_pass == actual_pass) {
- requestAuth = false;
- }
- if (proxy_expected_user == proxy_actual_user &&
- proxy_expected_pass == proxy_actual_pass) {
- requestProxyAuth = false;
- }
-
- if (anonymous) {
- if (authPresent) {
- response.setStatusLine("1.0", 400, "Unexpected authorization header found");
- } else {
- response.setStatusLine("1.0", 200, "Authorization header not found");
- }
- } else {
- if (requestProxyAuth) {
- response.setStatusLine("1.0", 407, "Proxy authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("Proxy-Authenticate", "basic realm=\"" + proxy_realm + "\"", true);
- } else if (requestAuth) {
- if (formauth && authPresent)
- response.setStatusLine("1.0", 403, "Form authentication required");
- else
- response.setStatusLine("1.0", 401, "Authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
- } else {
- response.setStatusLine("1.0", 200, "OK");
- }
- }
-
- response.setHeader("Content-Type", "application/xhtml+xml", false);
- response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
- response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Proxy: <span id='proxy'>" + (requestProxyAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
- response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
- response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
-
- if (huge) {
- response.write("<div style='display: none'>");
- for (i = 0; i < 100000; i++) {
- response.write("123456789\n");
- }
- response.write("</div>");
- response.write("<span id='footnote'>This is a footnote after the huge content fill</span>");
- }
-
- if (plugin) {
- response.write("<embed id='embedtest' style='width: 400px; height: 100px;' " +
- "type='application/x-test'></embed>\n");
- }
-
- response.write("</html>");
-}
-
-
-// base64 decoder
-//
-// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
-// doesn't seem to exist. :-(
-/* Convert Base64 data to a string */
-const toBinaryTable = [
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
-];
-const base64Pad = '=';
-
-function base64ToString(data) {
-
- var result = '';
- var leftbits = 0; // number of bits decoded, but yet to be appended
- var leftdata = 0; // bits decoded, but yet to be appended
-
- // Convert one by one.
- for (var i = 0; i < data.length; i++) {
- var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
- var padding = (data[i] == base64Pad);
- // Skip illegal characters and whitespace
- if (c == -1) continue;
-
- // Collect data into leftdata, update bitcount
- leftdata = (leftdata << 6) | c;
- leftbits += 6;
-
- // If we have 8 or more bits, append 8 bits to the result
- if (leftbits >= 8) {
- leftbits -= 8;
- // Append if not padding.
- if (!padding)
- result += String.fromCharCode((leftdata >> leftbits) & 0xff);
- leftdata &= (1 << leftbits) - 1;
- }
- }
-
- // If there are any bits left, the base64 string was corrupted
- if (leftbits)
- throw Components.Exception('Corrupted base64 string');
-
- return result;
-}
diff --git a/toolkit/components/passwordmgr/test/blank.html b/toolkit/components/passwordmgr/test/blank.html
deleted file mode 100644
index 81ddc2235..000000000
--- a/toolkit/components/passwordmgr/test/blank.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- </body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/.eslintrc.js b/toolkit/components/passwordmgr/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/passwordmgr/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/passwordmgr/test/browser/authenticate.sjs b/toolkit/components/passwordmgr/test/browser/authenticate.sjs
deleted file mode 100644
index fe2d2423c..000000000
--- a/toolkit/components/passwordmgr/test/browser/authenticate.sjs
+++ /dev/null
@@ -1,110 +0,0 @@
-function handleRequest(request, response)
-{
- var match;
- var requestAuth = true;
-
- // Allow the caller to drive how authentication is processed via the query.
- // Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
- // The extra ? allows the user/pass/realm checks to succeed if the name is
- // at the beginning of the query string.
- var query = "?" + request.queryString;
-
- var expected_user = "test", expected_pass = "testpass", realm = "mochitest";
-
- // Look for an authentication header, if any, in the request.
- //
- // EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
- //
- // This test only supports Basic auth. The value sent by the client is
- // "username:password", obscured with base64 encoding.
-
- var actual_user = "", actual_pass = "", authHeader, authPresent = false;
- if (request.hasHeader("Authorization")) {
- authPresent = true;
- authHeader = request.getHeader("Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw new Error("Couldn't parse auth header: " + authHeader);
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw new Error("Couldn't decode auth header: " + userpass);
- actual_user = match[1];
- actual_pass = match[2];
- }
-
- // Don't request authentication if the credentials we got were what we
- // expected.
- if (expected_user == actual_user &&
- expected_pass == actual_pass) {
- requestAuth = false;
- }
-
- if (requestAuth) {
- response.setStatusLine("1.0", 401, "Authentication required");
- response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
- } else {
- response.setStatusLine("1.0", 200, "OK");
- }
-
- response.setHeader("Content-Type", "application/xhtml+xml", false);
- response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
- response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
- response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
- response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
- response.write("</html>");
-}
-
-
-// base64 decoder
-//
-// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
-// doesn't seem to exist. :-(
-/* Convert Base64 data to a string */
-const toBinaryTable = [
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
-];
-const base64Pad = '=';
-
-function base64ToString(data) {
-
- var result = '';
- var leftbits = 0; // number of bits decoded, but yet to be appended
- var leftdata = 0; // bits decoded, but yet to be appended
-
- // Convert one by one.
- for (var i = 0; i < data.length; i++) {
- var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
- var padding = (data[i] == base64Pad);
- // Skip illegal characters and whitespace
- if (c == -1) continue;
-
- // Collect data into leftdata, update bitcount
- leftdata = (leftdata << 6) | c;
- leftbits += 6;
-
- // If we have 8 or more bits, append 8 bits to the result
- if (leftbits >= 8) {
- leftbits -= 8;
- // Append if not padding.
- if (!padding)
- result += String.fromCharCode((leftdata >> leftbits) & 0xff);
- leftdata &= (1 << leftbits) - 1;
- }
- }
-
- // If there are any bits left, the base64 string was corrupted
- if (leftbits)
- throw Components.Exception('Corrupted base64 string');
-
- return result;
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser.ini b/toolkit/components/passwordmgr/test/browser/browser.ini
deleted file mode 100644
index b17591436..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser.ini
+++ /dev/null
@@ -1,72 +0,0 @@
-[DEFAULT]
-support-files =
- ../formsubmit.sjs
- authenticate.sjs
- form_basic.html
- form_basic_iframe.html
- formless_basic.html
- form_same_origin_action.html
- form_cross_origin_secure_action.html
- head.js
- insecure_test.html
- insecure_test_subframe.html
- multiple_forms.html
- streamConverter_content.sjs
-
-[browser_autocomplete_insecure_warning.js]
-support-files =
- form_cross_origin_insecure_action.html
-[browser_capture_doorhanger.js]
-support-files =
- subtst_notifications_1.html
- subtst_notifications_2.html
- subtst_notifications_2pw_0un.html
- subtst_notifications_2pw_1un_1text.html
- subtst_notifications_3.html
- subtst_notifications_4.html
- subtst_notifications_5.html
- subtst_notifications_6.html
- subtst_notifications_8.html
- subtst_notifications_9.html
- subtst_notifications_10.html
- subtst_notifications_change_p.html
-[browser_capture_doorhanger_httpsUpgrade.js]
-support-files =
- subtst_notifications_1.html
- subtst_notifications_8.html
-[browser_capture_doorhanger_window_open.js]
-support-files =
- subtst_notifications_11.html
- subtst_notifications_11_popup.html
-skip-if = os == "linux" # Bug 1312981, bug 1313136
-[browser_context_menu_autocomplete_interaction.js]
-[browser_username_select_dialog.js]
-support-files =
- subtst_notifications_change_p.html
-[browser_DOMFormHasPassword.js]
-[browser_DOMInputPasswordAdded.js]
-[browser_exceptions_dialog.js]
-[browser_formless_submit_chrome.js]
-[browser_hasInsecureLoginForms.js]
-[browser_hasInsecureLoginForms_streamConverter.js]
-[browser_http_autofill.js]
-[browser_insecurePasswordConsoleWarning.js]
-support-files =
- form_cross_origin_insecure_action.html
-[browser_master_password_autocomplete.js]
-[browser_notifications.js]
-[browser_notifications_username.js]
-[browser_notifications_password.js]
-[browser_notifications_2.js]
-skip-if = os == "linux" # Bug 1272849 Main action button disabled state intermittent
-[browser_passwordmgr_editing.js]
-skip-if = os == "linux"
-[browser_context_menu.js]
-[browser_context_menu_iframe.js]
-[browser_passwordmgr_contextmenu.js]
-subsuite = clipboard
-[browser_passwordmgr_fields.js]
-[browser_passwordmgr_observers.js]
-[browser_passwordmgr_sort.js]
-[browser_passwordmgr_switchtab.js]
-[browser_passwordmgrdlg.js]
diff --git a/toolkit/components/passwordmgr/test/browser/browser_DOMFormHasPassword.js b/toolkit/components/passwordmgr/test/browser/browser_DOMFormHasPassword.js
deleted file mode 100644
index 80a0dd903..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_DOMFormHasPassword.js
+++ /dev/null
@@ -1,94 +0,0 @@
-const ids = {
- INPUT_ID: "input1",
- FORM1_ID: "form1",
- FORM2_ID: "form2",
- CHANGE_INPUT_ID: "input2",
-};
-
-function task(contentIds) {
- let resolve;
- let promise = new Promise(r => { resolve = r; });
-
- function unexpectedContentEvent(evt) {
- ok(false, "Received a " + evt.type + " event on content");
- }
-
- var gDoc = null;
-
- addEventListener("load", tabLoad, true);
-
- function tabLoad() {
- if (content.location.href == "about:blank")
- return;
- removeEventListener("load", tabLoad, true);
-
- gDoc = content.document;
- gDoc.addEventListener("DOMFormHasPassword", unexpectedContentEvent, false);
- gDoc.defaultView.setTimeout(test_inputAdd, 0);
- }
-
- function test_inputAdd() {
- addEventListener("DOMFormHasPassword", test_inputAddHandler, false);
- let input = gDoc.createElementNS("http://www.w3.org/1999/xhtml", "input");
- input.setAttribute("type", "password");
- input.setAttribute("id", contentIds.INPUT_ID);
- input.setAttribute("data-test", "unique-attribute");
- gDoc.getElementById(contentIds.FORM1_ID).appendChild(input);
- }
-
- function test_inputAddHandler(evt) {
- removeEventListener(evt.type, test_inputAddHandler, false);
- is(evt.target.id, contentIds.FORM1_ID,
- evt.type + " event targets correct form element (added password element)");
- gDoc.defaultView.setTimeout(test_inputChangeForm, 0);
- }
-
- function test_inputChangeForm() {
- addEventListener("DOMFormHasPassword", test_inputChangeFormHandler, false);
- let input = gDoc.getElementById(contentIds.INPUT_ID);
- input.setAttribute("form", contentIds.FORM2_ID);
- }
-
- function test_inputChangeFormHandler(evt) {
- removeEventListener(evt.type, test_inputChangeFormHandler, false);
- is(evt.target.id, contentIds.FORM2_ID,
- evt.type + " event targets correct form element (changed form)");
- gDoc.defaultView.setTimeout(test_inputChangesType, 0);
- }
-
- function test_inputChangesType() {
- addEventListener("DOMFormHasPassword", test_inputChangesTypeHandler, false);
- let input = gDoc.getElementById(contentIds.CHANGE_INPUT_ID);
- input.setAttribute("type", "password");
- }
-
- function test_inputChangesTypeHandler(evt) {
- removeEventListener(evt.type, test_inputChangesTypeHandler, false);
- is(evt.target.id, contentIds.FORM1_ID,
- evt.type + " event targets correct form element (changed type)");
- gDoc.defaultView.setTimeout(finish, 0);
- }
-
- function finish() {
- gDoc.removeEventListener("DOMFormHasPassword", unexpectedContentEvent, false);
- resolve();
- }
-
- return promise;
-}
-
-add_task(function* () {
- let tab = gBrowser.selectedTab = gBrowser.addTab();
-
- let promise = ContentTask.spawn(tab.linkedBrowser, ids, task);
- tab.linkedBrowser.loadURI("data:text/html;charset=utf-8," +
- "<html><body>" +
- "<form id='" + ids.FORM1_ID + "'>" +
- "<input id='" + ids.CHANGE_INPUT_ID + "'></form>" +
- "<form id='" + ids.FORM2_ID + "'></form>" +
- "</body></html>");
- yield promise;
-
- ok(true, "Test completed");
- gBrowser.removeCurrentTab();
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_DOMInputPasswordAdded.js b/toolkit/components/passwordmgr/test/browser/browser_DOMInputPasswordAdded.js
deleted file mode 100644
index f54892e19..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_DOMInputPasswordAdded.js
+++ /dev/null
@@ -1,99 +0,0 @@
-const consts = {
- HTML_NS: "http://www.w3.org/1999/xhtml",
-
- INPUT_ID: "input1",
- FORM1_ID: "form1",
- FORM2_ID: "form2",
- CHANGE_INPUT_ID: "input2",
- BODY_INPUT_ID: "input3",
-};
-
-function task(contentConsts) {
- let resolve;
- let promise = new Promise(r => { resolve = r; });
-
- function unexpectedContentEvent(evt) {
- Assert.ok(false, "Received a " + evt.type + " event on content");
- }
-
- var gDoc = null;
-
- addEventListener("load", tabLoad, true);
-
- function tabLoad() {
- removeEventListener("load", tabLoad, true);
- gDoc = content.document;
- // These events shouldn't escape to content.
- gDoc.addEventListener("DOMInputPasswordAdded", unexpectedContentEvent, false);
- gDoc.defaultView.setTimeout(test_inputAdd, 0);
- }
-
- function test_inputAdd() {
- addEventListener("DOMInputPasswordAdded", test_inputAddHandler, false);
- let input = gDoc.createElementNS(contentConsts.HTML_NS, "input");
- input.setAttribute("type", "password");
- input.setAttribute("id", contentConsts.INPUT_ID);
- input.setAttribute("data-test", "unique-attribute");
- gDoc.getElementById(contentConsts.FORM1_ID).appendChild(input);
- info("Done appending the input element");
- }
-
- function test_inputAddHandler(evt) {
- removeEventListener(evt.type, test_inputAddHandler, false);
- Assert.equal(evt.target.id, contentConsts.INPUT_ID,
- evt.type + " event targets correct input element (added password element)");
- gDoc.defaultView.setTimeout(test_inputAddOutsideForm, 0);
- }
-
- function test_inputAddOutsideForm() {
- addEventListener("DOMInputPasswordAdded", test_inputAddOutsideFormHandler, false);
- let input = gDoc.createElementNS(contentConsts.HTML_NS, "input");
- input.setAttribute("type", "password");
- input.setAttribute("id", contentConsts.BODY_INPUT_ID);
- input.setAttribute("data-test", "unique-attribute");
- gDoc.body.appendChild(input);
- info("Done appending the input element to the body");
- }
-
- function test_inputAddOutsideFormHandler(evt) {
- removeEventListener(evt.type, test_inputAddOutsideFormHandler, false);
- Assert.equal(evt.target.id, contentConsts.BODY_INPUT_ID,
- evt.type + " event targets correct input element (added password element outside form)");
- gDoc.defaultView.setTimeout(test_inputChangesType, 0);
- }
-
- function test_inputChangesType() {
- addEventListener("DOMInputPasswordAdded", test_inputChangesTypeHandler, false);
- let input = gDoc.getElementById(contentConsts.CHANGE_INPUT_ID);
- input.setAttribute("type", "password");
- }
-
- function test_inputChangesTypeHandler(evt) {
- removeEventListener(evt.type, test_inputChangesTypeHandler, false);
- Assert.equal(evt.target.id, contentConsts.CHANGE_INPUT_ID,
- evt.type + " event targets correct input element (changed type)");
- gDoc.defaultView.setTimeout(completeTest, 0);
- }
-
- function completeTest() {
- Assert.ok(true, "Test completed");
- gDoc.removeEventListener("DOMInputPasswordAdded", unexpectedContentEvent, false);
- resolve();
- }
-
- return promise;
-}
-
-add_task(function* () {
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- let promise = ContentTask.spawn(tab.linkedBrowser, consts, task);
- tab.linkedBrowser.loadURI("data:text/html;charset=utf-8," +
- "<html><body>" +
- "<form id='" + consts.FORM1_ID + "'>" +
- "<input id='" + consts.CHANGE_INPUT_ID + "'></form>" +
- "<form id='" + consts.FORM2_ID + "'></form>" +
- "</body></html>");
- yield promise;
- gBrowser.removeCurrentTab();
-});
-
diff --git a/toolkit/components/passwordmgr/test/browser/browser_autocomplete_insecure_warning.js b/toolkit/components/passwordmgr/test/browser/browser_autocomplete_insecure_warning.js
deleted file mode 100644
index 6aa8e5cf7..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_autocomplete_insecure_warning.js
+++ /dev/null
@@ -1,41 +0,0 @@
-"use strict";
-
-const EXPECTED_SUPPORT_URL = Services.urlFormatter.formatURLPref("app.support.baseURL") +
- "insecure-password";
-
-add_task(function* test_clickInsecureFieldWarning() {
- let url = "https://example.com" + DIRECTORY_PATH + "form_cross_origin_insecure_action.html";
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url,
- }, function*(browser) {
- let popup = document.getElementById("PopupAutoComplete");
- ok(popup, "Got popup");
-
- let promiseShown = BrowserTestUtils.waitForEvent(popup, "popupshown");
-
- yield SimpleTest.promiseFocus(browser);
- info("content window focused");
-
- // Focus the username field to open the popup.
- yield ContentTask.spawn(browser, null, function openAutocomplete() {
- content.document.getElementById("form-basic-username").focus();
- });
-
- yield promiseShown;
- ok(promiseShown, "autocomplete shown");
-
- let warningItem = document.getAnonymousElementByAttribute(popup, "type", "insecureWarning");
- ok(warningItem, "Got warning richlistitem");
-
- yield BrowserTestUtils.waitForCondition(() => !warningItem.collapsed, "Wait for warning to show");
-
- info("Clicking on warning");
- let supportTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, EXPECTED_SUPPORT_URL);
- EventUtils.synthesizeMouseAtCenter(warningItem, {});
- let supportTab = yield supportTabPromise;
- ok(supportTab, "Support tab opened");
- yield BrowserTestUtils.removeTab(supportTab);
- });
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger.js b/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger.js
deleted file mode 100644
index b6bfdbf50..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger.js
+++ /dev/null
@@ -1,600 +0,0 @@
-/*
- * Test capture popup notifications
- */
-
-const BRAND_BUNDLE = Services.strings.createBundle("chrome://branding/locale/brand.properties");
-const BRAND_SHORT_NAME = BRAND_BUNDLE.GetStringFromName("brandShortName");
-
-let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-let login1 = new nsLoginInfo("http://example.com", "http://example.com", null,
- "notifyu1", "notifyp1", "user", "pass");
-let login2 = new nsLoginInfo("http://example.com", "http://example.com", null,
- "", "notifyp1", "", "pass");
-let login1B = new nsLoginInfo("http://example.com", "http://example.com", null,
- "notifyu1B", "notifyp1B", "user", "pass");
-let login2B = new nsLoginInfo("http://example.com", "http://example.com", null,
- "", "notifyp1B", "", "pass");
-
-requestLongerTimeout(2);
-
-add_task(function* setup() {
- // Load recipes for this test.
- let recipeParent = yield LoginManagerParent.recipeParentPromise;
- yield recipeParent.load({
- siteRecipes: [{
- hosts: ["example.org"],
- usernameSelector: "#user",
- passwordSelector: "#pass",
- }],
- });
-});
-
-add_task(function* test_remember_opens() {
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
- notif.remove();
- });
-});
-
-add_task(function* test_clickNever() {
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
- is(true, Services.logins.getLoginSavingEnabled("http://example.com"),
- "Checking for login saving enabled");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "notifyp1");
- clickDoorhangerButton(notif, NEVER_BUTTON);
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-
- info("Make sure Never took effect");
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- is(false, Services.logins.getLoginSavingEnabled("http://example.com"),
- "Checking for login saving disabled");
- Services.logins.setLoginSavingEnabled("http://example.com", true);
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_clickRemember() {
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "notifyp1");
- clickDoorhangerButton(notif, REMEMBER_BUTTON);
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username used on the new entry");
- is(login.password, "notifyp1", "Check the password used on the new entry");
- is(login.timesUsed, 1, "Check times used on new entry");
-
- info("Make sure Remember took effect and we don't prompt for an existing login");
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- });
-
- logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username used");
- is(login.password, "notifyp1", "Check the password used");
- is(login.timesUsed, 2, "Check times used incremented");
-
- checkOnlyLoginWasUsedTwice({ justChanged: false });
-
- // remove that login
- Services.logins.removeLogin(login1);
-});
-
-/* signons.rememberSignons pref tests... */
-
-add_task(function* test_rememberSignonsFalse() {
- info("Make sure we don't prompt with rememberSignons=false");
- Services.prefs.setBoolPref("signon.rememberSignons", false);
-
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_rememberSignonsTrue() {
- info("Make sure we prompt with rememberSignons=true");
- Services.prefs.setBoolPref("signon.rememberSignons", true);
-
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
- notif.remove();
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-/* autocomplete=off tests... */
-
-add_task(function* test_autocompleteOffUsername() {
- info("Check for notification popup when autocomplete=off present on username");
-
- yield testSubmittingLoginForm("subtst_notifications_2.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "checking for notification popup");
- notif.remove();
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_autocompleteOffPassword() {
- info("Check for notification popup when autocomplete=off present on password");
-
- yield testSubmittingLoginForm("subtst_notifications_3.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "checking for notification popup");
- notif.remove();
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_autocompleteOffForm() {
- info("Check for notification popup when autocomplete=off present on form");
-
- yield testSubmittingLoginForm("subtst_notifications_4.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "checking for notification popup");
- notif.remove();
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-
-add_task(function* test_noPasswordField() {
- info("Check for no notification popup when no password field present");
-
- yield testSubmittingLoginForm("subtst_notifications_5.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "null", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_pwOnlyLoginMatchesForm() {
- info("Check for update popup when existing pw-only login matches form.");
- Services.logins.addLogin(login2);
-
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "checking for notification popup");
- notif.remove();
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "", "Check the username");
- is(login.password, "notifyp1", "Check the password");
- is(login.timesUsed, 1, "Check times used");
-
- Services.logins.removeLogin(login2);
-});
-
-add_task(function* test_pwOnlyFormMatchesLogin() {
- info("Check for no notification popup when pw-only form matches existing login.");
- Services.logins.addLogin(login1);
-
- yield testSubmittingLoginForm("subtst_notifications_6.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username");
- is(login.password, "notifyp1", "Check the password");
- is(login.timesUsed, 2, "Check times used");
-
- Services.logins.removeLogin(login1);
-});
-
-add_task(function* test_pwOnlyFormDoesntMatchExisting() {
- info("Check for notification popup when pw-only form doesn't match existing login.");
- Services.logins.addLogin(login1B);
-
- yield testSubmittingLoginForm("subtst_notifications_6.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
- notif.remove();
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1B", "Check the username unchanged");
- is(login.password, "notifyp1B", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-
- Services.logins.removeLogin(login1B);
-});
-
-add_task(function* test_changeUPLoginOnUPForm_dont() {
- info("Check for change-password popup, u+p login on u+p form. (not changed)");
- Services.logins.addLogin(login1);
-
- yield testSubmittingLoginForm("subtst_notifications_8.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "pass2", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "got notification popup");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "pass2");
- clickDoorhangerButton(notif, DONT_CHANGE_BUTTON);
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username unchanged");
- is(login.password, "notifyp1", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-
- Services.logins.removeLogin(login1);
-});
-
-add_task(function* test_changeUPLoginOnUPForm_change() {
- info("Check for change-password popup, u+p login on u+p form.");
- Services.logins.addLogin(login1);
-
- yield testSubmittingLoginForm("subtst_notifications_8.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "pass2", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "got notification popup");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "pass2");
- clickDoorhangerButton(notif, CHANGE_BUTTON);
-
- ok(!getCaptureDoorhanger("password-change"), "popup should be gone");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username unchanged");
- is(login.password, "pass2", "Check the password changed");
- is(login.timesUsed, 2, "Check times used");
-
- checkOnlyLoginWasUsedTwice({ justChanged: true });
-
- // cleanup
- login1.password = "pass2";
- Services.logins.removeLogin(login1);
- login1.password = "notifyp1";
-});
-
-add_task(function* test_changePLoginOnUPForm() {
- info("Check for change-password popup, p-only login on u+p form.");
- Services.logins.addLogin(login2);
-
- yield testSubmittingLoginForm("subtst_notifications_9.html", function*(fieldValues) {
- is(fieldValues.username, "", "Checking submitted username");
- is(fieldValues.password, "pass2", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "got notification popup");
-
- yield* checkDoorhangerUsernamePassword("", "pass2");
- clickDoorhangerButton(notif, CHANGE_BUTTON);
-
- ok(!getCaptureDoorhanger("password-change"), "popup should be gone");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "", "Check the username unchanged");
- is(login.password, "pass2", "Check the password changed");
- is(login.timesUsed, 2, "Check times used");
-
- // no cleanup -- saved password to be used in the next test.
-});
-
-add_task(function* test_changePLoginOnPForm() {
- info("Check for change-password popup, p-only login on p-only form.");
-
- yield testSubmittingLoginForm("subtst_notifications_10.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "got notification popup");
-
- yield* checkDoorhangerUsernamePassword("", "notifyp1");
- clickDoorhangerButton(notif, CHANGE_BUTTON);
-
- ok(!getCaptureDoorhanger("password-change"), "popup should be gone");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "", "Check the username unchanged");
- is(login.password, "notifyp1", "Check the password changed");
- is(login.timesUsed, 3, "Check times used");
-
- Services.logins.removeLogin(login2);
-});
-
-add_task(function* test_checkUPSaveText() {
- info("Check text on a user+pass notification popup");
-
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
- // Check the text, which comes from the localized saveLoginText string.
- let notificationText = notif.message;
- let expectedText = "Would you like " + BRAND_SHORT_NAME + " to remember this login?";
- is(expectedText, notificationText, "Checking text: " + notificationText);
- notif.remove();
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_checkPSaveText() {
- info("Check text on a pass-only notification popup");
-
- yield testSubmittingLoginForm("subtst_notifications_6.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
- // Check the text, which comes from the localized saveLoginTextNoUser string.
- let notificationText = notif.message;
- let expectedText = "Would you like " + BRAND_SHORT_NAME + " to remember this password?";
- is(expectedText, notificationText, "Checking text: " + notificationText);
- notif.remove();
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_capture2pw0un() {
- info("Check for notification popup when a form with 2 password fields (no username) " +
- "is submitted and there are no saved logins.");
-
- yield testSubmittingLoginForm("subtst_notifications_2pw_0un.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
- notif.remove();
- });
-
- is(Services.logins.getAllLogins().length, 0, "Should not have any logins yet");
-});
-
-add_task(function* test_change2pw0unExistingDifferentUP() {
- info("Check for notification popup when a form with 2 password fields (no username) " +
- "is submitted and there is a saved login with a username and different password.");
-
- Services.logins.addLogin(login1B);
-
- yield testSubmittingLoginForm("subtst_notifications_2pw_0un.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "got notification popup");
- notif.remove();
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1B", "Check the username unchanged");
- is(login.password, "notifyp1B", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-
- Services.logins.removeLogin(login1B);
-});
-
-add_task(function* test_change2pw0unExistingDifferentP() {
- info("Check for notification popup when a form with 2 password fields (no username) " +
- "is submitted and there is a saved login with no username and different password.");
-
- Services.logins.addLogin(login2B);
-
- yield testSubmittingLoginForm("subtst_notifications_2pw_0un.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "got notification popup");
- notif.remove();
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "", "Check the username unchanged");
- is(login.password, "notifyp1B", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-
- Services.logins.removeLogin(login2B);
-});
-
-add_task(function* test_change2pw0unExistingWithSameP() {
- info("Check for no notification popup when a form with 2 password fields (no username) " +
- "is submitted and there is a saved login with a username and the same password.");
-
- Services.logins.addLogin(login2);
-
- yield testSubmittingLoginForm("subtst_notifications_2pw_0un.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(!notif, "checking for no notification popup");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "", "Check the username unchanged");
- is(login.password, "notifyp1", "Check the password unchanged");
- is(login.timesUsed, 2, "Check times used incremented");
-
- checkOnlyLoginWasUsedTwice({ justChanged: false });
-
- Services.logins.removeLogin(login2);
-});
-
-add_task(function* test_changeUPLoginOnPUpdateForm() {
- info("Check for change-password popup, u+p login on password update form.");
- Services.logins.addLogin(login1);
-
- yield testSubmittingLoginForm("subtst_notifications_change_p.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "pass2", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "got notification popup");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "pass2");
- clickDoorhangerButton(notif, CHANGE_BUTTON);
-
- ok(!getCaptureDoorhanger("password-change"), "popup should be gone");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username unchanged");
- is(login.password, "pass2", "Check the password changed");
- is(login.timesUsed, 2, "Check times used");
-
- checkOnlyLoginWasUsedTwice({ justChanged: true });
-
- // cleanup
- login1.password = "pass2";
- Services.logins.removeLogin(login1);
- login1.password = "notifyp1";
-});
-
-add_task(function* test_recipeCaptureFields_NewLogin() {
- info("Check that we capture the proper fields when a field recipe is in use.");
-
- yield testSubmittingLoginForm("subtst_notifications_2pw_1un_1text.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
-
- // Sanity check, no logins should exist yet.
- let logins = Services.logins.getAllLogins();
- is(logins.length, 0, "Should not have any logins yet");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "notifyp1");
- clickDoorhangerButton(notif, REMEMBER_BUTTON);
-
- }, "http://example.org"); // The recipe is for example.org
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username unchanged");
- is(login.password, "notifyp1", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-});
-
-add_task(function* test_recipeCaptureFields_ExistingLogin() {
- info("Check that we capture the proper fields when a field recipe is in use " +
- "and there is a matching login");
-
- yield testSubmittingLoginForm("subtst_notifications_2pw_1un_1text.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- }, "http://example.org");
-
- checkOnlyLoginWasUsedTwice({ justChanged: false });
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username unchanged");
- is(login.password, "notifyp1", "Check the password unchanged");
- is(login.timesUsed, 2, "Check times used incremented");
-
- Services.logins.removeAllLogins();
-});
-
-add_task(function* test_noShowPasswordOnDismissal() {
- info("Check for no Show Password field when the doorhanger is dismissed");
-
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- info("Opening popup");
- let notif = getCaptureDoorhanger("password-save");
- let { panel } = PopupNotifications;
-
- info("Hiding popup.");
- let promiseHidden = BrowserTestUtils.waitForEvent(panel, "popuphidden");
- panel.hidePopup();
- yield promiseHidden;
-
- info("Clicking on anchor to reshow popup.");
- let promiseShown = BrowserTestUtils.waitForEvent(panel, "popupshown");
- notif.anchorElement.click();
- yield promiseShown;
-
- let passwordVisiblityToggle = panel.querySelector("#password-notification-visibilityToggle");
- is(passwordVisiblityToggle.hidden, true, "Check that the Show Password field is Hidden");
- });
-});
-
-// TODO:
-// * existing login test, form has different password --> change password, no save prompt
diff --git a/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_httpsUpgrade.js b/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_httpsUpgrade.js
deleted file mode 100644
index 9be0aa631..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_httpsUpgrade.js
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Test capture popup notifications with HTTPS upgrades
- */
-
-let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-let login1 = new nsLoginInfo("http://example.com", "http://example.com", null,
- "notifyu1", "notifyp1", "user", "pass");
-let login1HTTPS = new nsLoginInfo("https://example.com", "https://example.com", null,
- "notifyu1", "notifyp1", "user", "pass");
-
-add_task(function* test_httpsUpgradeCaptureFields_noChange() {
- info("Check that we don't prompt to remember when capturing an upgraded login with no change");
- Services.logins.addLogin(login1);
- // Sanity check the HTTP login exists.
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should have the HTTP login");
-
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- }, "https://example.com"); // This is HTTPS whereas the saved login is HTTP
-
- logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login still");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.hostname, "http://example.com", "Check the hostname is unchanged");
- is(login.username, "notifyu1", "Check the username is unchanged");
- is(login.password, "notifyp1", "Check the password is unchanged");
- is(login.timesUsed, 2, "Check times used increased");
-
- Services.logins.removeLogin(login1);
-});
-
-add_task(function* test_httpsUpgradeCaptureFields_changePW() {
- info("Check that we prompt to change when capturing an upgraded login with a new PW");
- Services.logins.addLogin(login1);
- // Sanity check the HTTP login exists.
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should have the HTTP login");
-
- yield testSubmittingLoginForm("subtst_notifications_8.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "pass2", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-change");
- ok(notif, "checking for a change popup");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "pass2");
- clickDoorhangerButton(notif, CHANGE_BUTTON);
-
- ok(!getCaptureDoorhanger("password-change"), "popup should be gone");
- }, "https://example.com"); // This is HTTPS whereas the saved login is HTTP
-
- checkOnlyLoginWasUsedTwice({ justChanged: true });
- logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login still");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.hostname, "https://example.com", "Check the hostname is upgraded");
- is(login.formSubmitURL, "https://example.com", "Check the formSubmitURL is upgraded");
- is(login.username, "notifyu1", "Check the username is unchanged");
- is(login.password, "pass2", "Check the password changed");
- is(login.timesUsed, 2, "Check times used increased");
-
- Services.logins.removeAllLogins();
-});
-
-add_task(function* test_httpsUpgradeCaptureFields_captureMatchingHTTP() {
- info("Capture a new HTTP login which matches a stored HTTPS one.");
- Services.logins.addLogin(login1HTTPS);
-
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(notif, "got notification popup");
-
- is(Services.logins.getAllLogins().length, 1, "Should only have the HTTPS login");
-
- yield* checkDoorhangerUsernamePassword("notifyu1", "notifyp1");
- clickDoorhangerButton(notif, REMEMBER_BUTTON);
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 2, "Should have both HTTP and HTTPS logins");
- for (let login of logins) {
- login = login.QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username used on the new entry");
- is(login.password, "notifyp1", "Check the password used on the new entry");
- is(login.timesUsed, 1, "Check times used on entry");
- }
-
- info("Make sure Remember took effect and we don't prompt for an existing HTTP login");
- yield testSubmittingLoginForm("subtst_notifications_1.html", function*(fieldValues) {
- is(fieldValues.username, "notifyu1", "Checking submitted username");
- is(fieldValues.password, "notifyp1", "Checking submitted password");
- let notif = getCaptureDoorhanger("password-save");
- ok(!notif, "checking for no notification popup");
- });
-
- logins = Services.logins.getAllLogins();
- is(logins.length, 2, "Should have both HTTP and HTTPS still");
-
- let httpsLogins = LoginHelper.searchLoginsWithObject({
- hostname: "https://example.com",
- });
- is(httpsLogins.length, 1, "Check https logins count");
- let httpsLogin = httpsLogins[0].QueryInterface(Ci.nsILoginMetaInfo);
- ok(httpsLogin.equals(login1HTTPS), "Check HTTPS login didn't change");
- is(httpsLogin.timesUsed, 1, "Check times used");
-
- let httpLogins = LoginHelper.searchLoginsWithObject({
- hostname: "http://example.com",
- });
- is(httpLogins.length, 1, "Check http logins count");
- let httpLogin = httpLogins[0].QueryInterface(Ci.nsILoginMetaInfo);
- ok(httpLogin.equals(login1), "Check HTTP login is as expected");
- is(httpLogin.timesUsed, 2, "Check times used increased");
-
- Services.logins.removeLogin(login1);
- Services.logins.removeLogin(login1HTTPS);
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_window_open.js b/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_window_open.js
deleted file mode 100644
index 1bcfec5eb..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger_window_open.js
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Test capture popup notifications in content opened by window.open
- */
-
-let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-let login1 = new nsLoginInfo("http://mochi.test:8888", "http://mochi.test:8888", null,
- "notifyu1", "notifyp1", "user", "pass");
-let login2 = new nsLoginInfo("http://mochi.test:8888", "http://mochi.test:8888", null,
- "notifyu2", "notifyp2", "user", "pass");
-
-
-function withTestTabUntilStorageChange(aPageFile, aTaskFn) {
- function storageChangedObserved(subject, data) {
- // Watch for actions triggered from a doorhanger (not cleanup tasks with removeLogin)
- if (data == "removeLogin") {
- return false;
- }
- return true;
- }
-
- let storageChangedPromised = TestUtils.topicObserved("passwordmgr-storage-changed",
- storageChangedObserved);
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://mochi.test:8888" + DIRECTORY_PATH + aPageFile,
- }, function*(browser) {
- ok(true, "loaded " + aPageFile);
- info("running test case task");
- yield* aTaskFn();
- info("waiting for storage change");
- yield storageChangedPromised;
- });
-}
-
-add_task(function* setup() {
- yield SimpleTest.promiseFocus(window);
-});
-
-add_task(function* test_saveChromeHiddenAutoClose() {
- let notifShownPromise = BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- // query arguments are: username, password, features, auto-close (delimited by '|')
- let url = "subtst_notifications_11.html?notifyu1|notifyp1|" +
- "menubar=no,toolbar=no,location=no|autoclose";
- yield withTestTabUntilStorageChange(url, function*() {
- info("waiting for popupshown");
- yield notifShownPromise;
- // the popup closes and the doorhanger should appear in the opener
- let popup = getCaptureDoorhanger("password-save");
- ok(popup, "got notification popup");
- yield* checkDoorhangerUsernamePassword("notifyu1", "notifyp1");
- // Sanity check, no logins should exist yet.
- let logins = Services.logins.getAllLogins();
- is(logins.length, 0, "Should not have any logins yet");
-
- clickDoorhangerButton(popup, REMEMBER_BUTTON);
- });
- // Check result of clicking Remember
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.timesUsed, 1, "Check times used on new entry");
- is(login.username, "notifyu1", "Check the username used on the new entry");
- is(login.password, "notifyp1", "Check the password used on the new entry");
-});
-
-add_task(function* test_changeChromeHiddenAutoClose() {
- let notifShownPromise = BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- let url = "subtst_notifications_11.html?notifyu1|pass2|menubar=no,toolbar=no,location=no|autoclose";
- yield withTestTabUntilStorageChange(url, function*() {
- info("waiting for popupshown");
- yield notifShownPromise;
- let popup = getCaptureDoorhanger("password-change");
- ok(popup, "got notification popup");
- yield* checkDoorhangerUsernamePassword("notifyu1", "pass2");
- clickDoorhangerButton(popup, CHANGE_BUTTON);
- });
-
- // Check to make sure we updated the password, timestamps and use count for
- // the login being changed with this form.
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username");
- is(login.password, "pass2", "Check password changed");
- is(login.timesUsed, 2, "check .timesUsed incremented on change");
- ok(login.timeCreated < login.timeLastUsed, "timeLastUsed bumped");
- ok(login.timeLastUsed == login.timePasswordChanged, "timeUsed == timeChanged");
-
- login1.password = "pass2";
- Services.logins.removeLogin(login1);
- login1.password = "notifyp1";
-});
-
-add_task(function* test_saveChromeVisibleSameWindow() {
- // This test actually opens a new tab in the same window with default browser settings.
- let url = "subtst_notifications_11.html?notifyu2|notifyp2||";
- let notifShownPromise = BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- yield withTestTabUntilStorageChange(url, function*() {
- yield notifShownPromise;
- let popup = getCaptureDoorhanger("password-save");
- ok(popup, "got notification popup");
- yield* checkDoorhangerUsernamePassword("notifyu2", "notifyp2");
- clickDoorhangerButton(popup, REMEMBER_BUTTON);
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- });
-
- // Check result of clicking Remember
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login now");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu2", "Check the username used on the new entry");
- is(login.password, "notifyp2", "Check the password used on the new entry");
- is(login.timesUsed, 1, "Check times used on new entry");
-});
-
-add_task(function* test_changeChromeVisibleSameWindow() {
- let url = "subtst_notifications_11.html?notifyu2|pass2||";
- let notifShownPromise = BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- yield withTestTabUntilStorageChange(url, function*() {
- yield notifShownPromise;
- let popup = getCaptureDoorhanger("password-change");
- ok(popup, "got notification popup");
- yield* checkDoorhangerUsernamePassword("notifyu2", "pass2");
- clickDoorhangerButton(popup, CHANGE_BUTTON);
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- });
-
- // Check to make sure we updated the password, timestamps and use count for
- // the login being changed with this form.
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should have 1 login");
- let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu2", "Check the username");
- is(login.password, "pass2", "Check password changed");
- is(login.timesUsed, 2, "check .timesUsed incremented on change");
- ok(login.timeCreated < login.timeLastUsed, "timeLastUsed bumped");
- ok(login.timeLastUsed == login.timePasswordChanged, "timeUsed == timeChanged");
-
- // cleanup
- login2.password = "pass2";
- Services.logins.removeLogin(login2);
- login2.password = "notifyp2";
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_context_menu.js b/toolkit/components/passwordmgr/test/browser/browser_context_menu.js
deleted file mode 100644
index 6cfcaa7c2..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_context_menu.js
+++ /dev/null
@@ -1,432 +0,0 @@
-/*
- * Test the password manager context menu.
- */
-
-/* eslint no-shadow:"off" */
-
-"use strict";
-
-// The hostname for the test URIs.
-const TEST_HOSTNAME = "https://example.com";
-const MULTIPLE_FORMS_PAGE_PATH = "/browser/toolkit/components/passwordmgr/test/browser/multiple_forms.html";
-
-const CONTEXT_MENU = document.getElementById("contentAreaContextMenu");
-const POPUP_HEADER = document.getElementById("fill-login");
-
-/**
- * Initialize logins needed for the tests and disable autofill
- * for login forms for easier testing of manual fill.
- */
-add_task(function* test_initialize() {
- Services.prefs.setBoolPref("signon.autofillForms", false);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("signon.autofillForms");
- Services.prefs.clearUserPref("signon.schemeUpgrades");
- });
- for (let login of loginList()) {
- Services.logins.addLogin(login);
- }
-});
-
-/**
- * Check if the context menu is populated with the right
- * menuitems for the target password input field.
- */
-add_task(function* test_context_menu_populate_password_noSchemeUpgrades() {
- Services.prefs.setBoolPref("signon.schemeUpgrades", false);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + MULTIPLE_FORMS_PAGE_PATH,
- }, function* (browser) {
- yield openPasswordContextMenu(browser, "#test-password-1");
-
- // Check the content of the password manager popup
- let popupMenu = document.getElementById("fill-login-popup");
- checkMenu(popupMenu, 2);
-
- CONTEXT_MENU.hidePopup();
- });
-});
-
-/**
- * Check if the context menu is populated with the right
- * menuitems for the target password input field.
- */
-add_task(function* test_context_menu_populate_password_schemeUpgrades() {
- Services.prefs.setBoolPref("signon.schemeUpgrades", true);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + MULTIPLE_FORMS_PAGE_PATH,
- }, function* (browser) {
- yield openPasswordContextMenu(browser, "#test-password-1");
-
- // Check the content of the password manager popup
- let popupMenu = document.getElementById("fill-login-popup");
- checkMenu(popupMenu, 3);
-
- CONTEXT_MENU.hidePopup();
- });
-});
-
-/**
- * Check if the context menu is populated with the right menuitems
- * for the target username field with a password field present.
- */
-add_task(function* test_context_menu_populate_username_with_password_noSchemeUpgrades() {
- Services.prefs.setBoolPref("signon.schemeUpgrades", false);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + "/browser/toolkit/components/" +
- "passwordmgr/test/browser/multiple_forms.html",
- }, function* (browser) {
- yield openPasswordContextMenu(browser, "#test-username-2");
-
- // Check the content of the password manager popup
- let popupMenu = document.getElementById("fill-login-popup");
- checkMenu(popupMenu, 2);
-
- CONTEXT_MENU.hidePopup();
- });
-});
-/**
- * Check if the context menu is populated with the right menuitems
- * for the target username field with a password field present.
- */
-add_task(function* test_context_menu_populate_username_with_password_schemeUpgrades() {
- Services.prefs.setBoolPref("signon.schemeUpgrades", true);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + "/browser/toolkit/components/" +
- "passwordmgr/test/browser/multiple_forms.html",
- }, function* (browser) {
- yield openPasswordContextMenu(browser, "#test-username-2");
-
- // Check the content of the password manager popup
- let popupMenu = document.getElementById("fill-login-popup");
- checkMenu(popupMenu, 3);
-
- CONTEXT_MENU.hidePopup();
- });
-});
-
-/**
- * Check if the password field is correctly filled when one
- * login menuitem is clicked.
- */
-add_task(function* test_context_menu_password_fill() {
- Services.prefs.setBoolPref("signon.schemeUpgrades", true);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + MULTIPLE_FORMS_PAGE_PATH,
- }, function* (browser) {
- let formDescriptions = yield ContentTask.spawn(browser, {}, function*() {
- let forms = Array.from(content.document.getElementsByClassName("test-form"));
- return forms.map((f) => f.getAttribute("description"));
- });
-
- for (let description of formDescriptions) {
- info("Testing form: " + description);
-
- let passwordInputIds = yield ContentTask.spawn(browser, {description}, function*({description}) {
- let formElement = content.document.querySelector(`[description="${description}"]`);
- let passwords = Array.from(formElement.querySelectorAll("input[type='password']"));
- return passwords.map((p) => p.id);
- });
-
- for (let inputId of passwordInputIds) {
- info("Testing password field: " + inputId);
-
- // Synthesize a right mouse click over the username input element.
- yield openPasswordContextMenu(browser, "#" + inputId, function*() {
- let inputDisabled = yield ContentTask
- .spawn(browser, {inputId}, function*({inputId}) {
- let input = content.document.getElementById(inputId);
- return input.disabled || input.readOnly;
- });
-
- // If the password field is disabled or read-only, we want to see
- // the disabled Fill Password popup header.
- if (inputDisabled) {
- Assert.ok(!POPUP_HEADER.hidden, "Popup menu is not hidden.");
- Assert.ok(POPUP_HEADER.disabled, "Popup menu is disabled.");
- CONTEXT_MENU.hidePopup();
- }
-
- return !inputDisabled;
- });
-
- if (CONTEXT_MENU.state != "open") {
- continue;
- }
-
- // The only field affected by the password fill
- // should be the target password field itself.
- yield assertContextMenuFill(browser, description, null, inputId, 1);
- yield ContentTask.spawn(browser, {inputId}, function*({inputId}) {
- let passwordField = content.document.getElementById(inputId);
- Assert.equal(passwordField.value, "password1", "Check upgraded login was actually used");
- });
-
- CONTEXT_MENU.hidePopup();
- }
- }
- });
-});
-
-/**
- * Check if the form is correctly filled when one
- * username context menu login menuitem is clicked.
- */
-add_task(function* test_context_menu_username_login_fill() {
- Services.prefs.setBoolPref("signon.schemeUpgrades", true);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + MULTIPLE_FORMS_PAGE_PATH,
- }, function* (browser) {
-
- let formDescriptions = yield ContentTask.spawn(browser, {}, function*() {
- let forms = Array.from(content.document.getElementsByClassName("test-form"));
- return forms.map((f) => f.getAttribute("description"));
- });
-
- for (let description of formDescriptions) {
- info("Testing form: " + description);
- let usernameInputIds = yield ContentTask
- .spawn(browser, {description}, function*({description}) {
- let formElement = content.document.querySelector(`[description="${description}"]`);
- let inputs = Array.from(formElement.querySelectorAll("input[type='text']"));
- return inputs.map((p) => p.id);
- });
-
- for (let inputId of usernameInputIds) {
- info("Testing username field: " + inputId);
-
- // Synthesize a right mouse click over the username input element.
- yield openPasswordContextMenu(browser, "#" + inputId, function*() {
- let headerHidden = POPUP_HEADER.hidden;
- let headerDisabled = POPUP_HEADER.disabled;
-
- let data = {description, inputId, headerHidden, headerDisabled};
- let shouldContinue = yield ContentTask.spawn(browser, data, function*(data) {
- let {description, inputId, headerHidden, headerDisabled} = data;
- let formElement = content.document.querySelector(`[description="${description}"]`);
- let usernameField = content.document.getElementById(inputId);
- // We always want to check if the first password field is filled,
- // since this is the current behavior from the _fillForm function.
- let passwordField = formElement.querySelector("input[type='password']");
-
- // If we don't want to see the actual popup menu,
- // check if the popup is hidden or disabled.
- if (!passwordField || usernameField.disabled || usernameField.readOnly ||
- passwordField.disabled || passwordField.readOnly) {
- if (!passwordField) {
- Assert.ok(headerHidden, "Popup menu is hidden.");
- } else {
- Assert.ok(!headerHidden, "Popup menu is not hidden.");
- Assert.ok(headerDisabled, "Popup menu is disabled.");
- }
- return false;
- }
- return true;
- });
-
- if (!shouldContinue) {
- CONTEXT_MENU.hidePopup();
- }
-
- return shouldContinue;
- });
-
- if (CONTEXT_MENU.state != "open") {
- continue;
- }
-
- let passwordFieldId = yield ContentTask
- .spawn(browser, {description}, function*({description}) {
- let formElement = content.document.querySelector(`[description="${description}"]`);
- return formElement.querySelector("input[type='password']").id;
- });
-
- // We shouldn't change any field that's not the target username field or the first password field
- yield assertContextMenuFill(browser, description, inputId, passwordFieldId, 1);
-
- yield ContentTask.spawn(browser, {passwordFieldId}, function*({passwordFieldId}) {
- let passwordField = content.document.getElementById(passwordFieldId);
- if (!passwordField.hasAttribute("expectedFail")) {
- Assert.equal(passwordField.value, "password1", "Check upgraded login was actually used");
- }
- });
-
- CONTEXT_MENU.hidePopup();
- }
- }
- });
-});
-
-/**
- * Synthesize mouse clicks to open the password manager context menu popup
- * for a target password input element.
- *
- * assertCallback should return true if we should continue or else false.
- */
-function* openPasswordContextMenu(browser, passwordInput, assertCallback = null) {
- // Synthesize a right mouse click over the password input element.
- let contextMenuShownPromise = BrowserTestUtils.waitForEvent(CONTEXT_MENU, "popupshown");
- let eventDetails = {type: "contextmenu", button: 2};
- BrowserTestUtils.synthesizeMouseAtCenter(passwordInput, eventDetails, browser);
- yield contextMenuShownPromise;
-
- if (assertCallback) {
- let shouldContinue = yield assertCallback();
- if (!shouldContinue) {
- return;
- }
- }
-
- // Synthesize a mouse click over the fill login menu header.
- let popupShownPromise = BrowserTestUtils.waitForEvent(POPUP_HEADER, "popupshown");
- EventUtils.synthesizeMouseAtCenter(POPUP_HEADER, {});
- yield popupShownPromise;
-}
-
-/**
- * Verify that only the expected form fields are filled.
- */
-function* assertContextMenuFill(browser, formId, usernameFieldId, passwordFieldId, loginIndex) {
- let popupMenu = document.getElementById("fill-login-popup");
- let unchangedSelector = `[description="${formId}"] input:not(#${passwordFieldId})`;
-
- if (usernameFieldId) {
- unchangedSelector += `:not(#${usernameFieldId})`;
- }
-
- yield ContentTask.spawn(browser, {unchangedSelector}, function*({unchangedSelector}) {
- let unchangedFields = content.document.querySelectorAll(unchangedSelector);
-
- // Store the value of fields that should remain unchanged.
- if (unchangedFields.length) {
- for (let field of unchangedFields) {
- field.setAttribute("original-value", field.value);
- }
- }
- });
-
- // Execute the default command of the specified login menuitem found in the context menu.
- let loginItem = popupMenu.getElementsByClassName("context-login-item")[loginIndex];
-
- // Find the used login by it's username (Use only unique usernames in this test).
- let {username, password} = getLoginFromUsername(loginItem.label);
-
- let data = {username, password, usernameFieldId, passwordFieldId, formId, unchangedSelector};
- let continuePromise = ContentTask.spawn(browser, data, function*(data) {
- let {username, password, usernameFieldId, passwordFieldId, formId, unchangedSelector} = data;
- let form = content.document.querySelector(`[description="${formId}"]`);
- yield ContentTaskUtils.waitForEvent(form, "input", "Username input value changed");
-
- if (usernameFieldId) {
- let usernameField = content.document.getElementById(usernameFieldId);
-
- // If we have an username field, check if it's correctly filled
- if (usernameField.getAttribute("expectedFail") == null) {
- Assert.equal(username, usernameField.value, "Username filled and correct.");
- }
- }
-
- if (passwordFieldId) {
- let passwordField = content.document.getElementById(passwordFieldId);
-
- // If we have a password field, check if it's correctly filled
- if (passwordField && passwordField.getAttribute("expectedFail") == null) {
- Assert.equal(password, passwordField.value, "Password filled and correct.");
- }
- }
-
- let unchangedFields = content.document.querySelectorAll(unchangedSelector);
-
- // Check that all fields that should not change have the same value as before.
- if (unchangedFields.length) {
- Assert.ok(() => {
- for (let field of unchangedFields) {
- if (field.value != field.getAttribute("original-value")) {
- return false;
- }
- }
- return true;
- }, "Other fields were not changed.");
- }
- });
-
- loginItem.doCommand();
-
- return continuePromise;
-}
-
-/**
- * Check if every login that matches the page hostname are available at the context menu.
- * @param {Element} contextMenu
- * @param {Number} expectedCount - Number of logins expected in the context menu. Used to ensure
-* we continue testing something useful.
- */
-function checkMenu(contextMenu, expectedCount) {
- let logins = loginList().filter(login => {
- return LoginHelper.isOriginMatching(login.hostname, TEST_HOSTNAME, {
- schemeUpgrades: Services.prefs.getBoolPref("signon.schemeUpgrades"),
- });
- });
- // Make an array of menuitems for easier comparison.
- let menuitems = [...CONTEXT_MENU.getElementsByClassName("context-login-item")];
- Assert.equal(menuitems.length, expectedCount, "Expected number of menu items");
- Assert.ok(logins.every(l => menuitems.some(m => l.username == m.label)), "Every login have an item at the menu.");
-}
-
-/**
- * Search for a login by it's username.
- *
- * Only unique login/hostname combinations should be used at this test.
- */
-function getLoginFromUsername(username) {
- return loginList().find(login => login.username == username);
-}
-
-/**
- * List of logins used for the test.
- *
- * We should only use unique usernames in this test,
- * because we need to search logins by username. There is one duplicate u+p combo
- * in order to test de-duping in the menu.
- */
-function loginList() {
- return [
- LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: "username",
- password: "password",
- }),
- // Same as above but HTTP in order to test de-duping.
- LoginTestUtils.testData.formLogin({
- hostname: "http://example.com",
- formSubmitURL: "http://example.com",
- username: "username",
- password: "password",
- }),
- LoginTestUtils.testData.formLogin({
- hostname: "http://example.com",
- formSubmitURL: "http://example.com",
- username: "username1",
- password: "password1",
- }),
- LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: "username2",
- password: "password2",
- }),
- LoginTestUtils.testData.formLogin({
- hostname: "http://example.org",
- formSubmitURL: "http://example.org",
- username: "username-cross-origin",
- password: "password-cross-origin",
- }),
- ];
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_context_menu_autocomplete_interaction.js b/toolkit/components/passwordmgr/test/browser/browser_context_menu_autocomplete_interaction.js
deleted file mode 100644
index 1b37e3f79..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_context_menu_autocomplete_interaction.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Test the password manager context menu interaction with autocomplete.
- */
-
-"use strict";
-
-const TEST_HOSTNAME = "https://example.com";
-const BASIC_FORM_PAGE_PATH = DIRECTORY_PATH + "form_basic.html";
-
-var gUnexpectedIsTODO = false;
-
-/**
- * Initialize logins needed for the tests and disable autofill
- * for login forms for easier testing of manual fill.
- */
-add_task(function* test_initialize() {
- let autocompletePopup = document.getElementById("PopupAutoComplete");
- Services.prefs.setBoolPref("signon.autofillForms", false);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("signon.autofillForms");
- autocompletePopup.removeEventListener("popupshowing", autocompleteUnexpectedPopupShowing);
- });
- for (let login of loginList()) {
- Services.logins.addLogin(login);
- }
- autocompletePopup.addEventListener("popupshowing", autocompleteUnexpectedPopupShowing);
-});
-
-add_task(function* test_context_menu_username() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + BASIC_FORM_PAGE_PATH,
- }, function* (browser) {
- yield openContextMenu(browser, "#form-basic-username");
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
- Assert.equal(contextMenu.state, "open", "Context menu opened");
- contextMenu.hidePopup();
- });
-});
-
-add_task(function* test_context_menu_password() {
- gUnexpectedIsTODO = true;
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + BASIC_FORM_PAGE_PATH,
- }, function* (browser) {
- yield openContextMenu(browser, "#form-basic-password");
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
- Assert.equal(contextMenu.state, "open", "Context menu opened");
- contextMenu.hidePopup();
- });
-});
-
-function autocompleteUnexpectedPopupShowing(event) {
- if (gUnexpectedIsTODO) {
- todo(false, "Autocomplete shouldn't appear");
- } else {
- Assert.ok(false, "Autocomplete shouldn't appear");
- }
- event.target.hidePopup();
-}
-
-/**
- * Synthesize mouse clicks to open the context menu popup
- * for a target login input element.
- */
-function* openContextMenu(browser, loginInput) {
- // First synthesize a mousedown. We need this to get the focus event with the "contextmenu" event.
- let eventDetails1 = {type: "mousedown", button: 2};
- BrowserTestUtils.synthesizeMouseAtCenter(loginInput, eventDetails1, browser);
-
- // Then synthesize the contextmenu click over the input element.
- let contextMenuShownPromise = BrowserTestUtils.waitForEvent(window, "popupshown");
- let eventDetails = {type: "contextmenu", button: 2};
- BrowserTestUtils.synthesizeMouseAtCenter(loginInput, eventDetails, browser);
- yield contextMenuShownPromise;
-
- // Wait to see which popups are shown.
- yield new Promise(resolve => setTimeout(resolve, 1000));
-}
-
-function loginList() {
- return [
- LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: "username",
- password: "password",
- }),
- LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: "username2",
- password: "password2",
- }),
- ];
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_context_menu_iframe.js b/toolkit/components/passwordmgr/test/browser/browser_context_menu_iframe.js
deleted file mode 100644
index c5219789d..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_context_menu_iframe.js
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Test the password manager context menu.
- */
-
-"use strict";
-
-const TEST_HOSTNAME = "https://example.com";
-
-// Test with a page that only has a form within an iframe, not in the top-level document
-const IFRAME_PAGE_PATH = "/browser/toolkit/components/passwordmgr/test/browser/form_basic_iframe.html";
-
-/**
- * Initialize logins needed for the tests and disable autofill
- * for login forms for easier testing of manual fill.
- */
-add_task(function* test_initialize() {
- Services.prefs.setBoolPref("signon.autofillForms", false);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref("signon.autofillForms");
- Services.prefs.clearUserPref("signon.schemeUpgrades");
- });
- for (let login of loginList()) {
- Services.logins.addLogin(login);
- }
-});
-
-/**
- * Check if the password field is correctly filled when it's in an iframe.
- */
-add_task(function* test_context_menu_iframe_fill() {
- Services.prefs.setBoolPref("signon.schemeUpgrades", true);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_HOSTNAME + IFRAME_PAGE_PATH
- }, function* (browser) {
- function getPasswordInput() {
- let frame = content.document.getElementById("test-iframe");
- return frame.contentDocument.getElementById("form-basic-password");
- }
-
- let contextMenuShownPromise = BrowserTestUtils.waitForEvent(window, "popupshown");
- let eventDetails = {type: "contextmenu", button: 2};
-
- // To click at the right point we have to take into account the iframe offset.
- // Synthesize a right mouse click over the password input element.
- BrowserTestUtils.synthesizeMouseAtCenter(getPasswordInput, eventDetails, browser);
- yield contextMenuShownPromise;
-
- // Synthesize a mouse click over the fill login menu header.
- let popupHeader = document.getElementById("fill-login");
- let popupShownPromise = BrowserTestUtils.waitForEvent(popupHeader, "popupshown");
- EventUtils.synthesizeMouseAtCenter(popupHeader, {});
- yield popupShownPromise;
-
- let popupMenu = document.getElementById("fill-login-popup");
-
- // Stores the original value of username
- function promiseFrameInputValue(name) {
- return ContentTask.spawn(browser, name, function(inputname) {
- let iframe = content.document.getElementById("test-iframe");
- let input = iframe.contentDocument.getElementById(inputname);
- return input.value;
- });
- }
- let usernameOriginalValue = yield promiseFrameInputValue("form-basic-username");
-
- // Execute the command of the first login menuitem found at the context menu.
- let passwordChangedPromise = ContentTask.spawn(browser, null, function* () {
- let frame = content.document.getElementById("test-iframe");
- let passwordInput = frame.contentDocument.getElementById("form-basic-password");
- yield ContentTaskUtils.waitForEvent(passwordInput, "input");
- });
-
- let firstLoginItem = popupMenu.getElementsByClassName("context-login-item")[0];
- firstLoginItem.doCommand();
-
- yield passwordChangedPromise;
-
- // Find the used login by it's username.
- let login = getLoginFromUsername(firstLoginItem.label);
- let passwordValue = yield promiseFrameInputValue("form-basic-password");
- is(login.password, passwordValue, "Password filled and correct.");
-
- let usernameNewValue = yield promiseFrameInputValue("form-basic-username");
- is(usernameOriginalValue,
- usernameNewValue,
- "Username value was not changed.");
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
- contextMenu.hidePopup();
- });
-});
-
-/**
- * Search for a login by it's username.
- *
- * Only unique login/hostname combinations should be used at this test.
- */
-function getLoginFromUsername(username) {
- return loginList().find(login => login.username == username);
-}
-
-/**
- * List of logins used for the test.
- *
- * We should only use unique usernames in this test,
- * because we need to search logins by username. There is one duplicate u+p combo
- * in order to test de-duping in the menu.
- */
-function loginList() {
- return [
- LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: "username",
- password: "password",
- }),
- // Same as above but HTTP in order to test de-duping.
- LoginTestUtils.testData.formLogin({
- hostname: "http://example.com",
- formSubmitURL: "http://example.com",
- username: "username",
- password: "password",
- }),
- LoginTestUtils.testData.formLogin({
- hostname: "http://example.com",
- formSubmitURL: "http://example.com",
- username: "username1",
- password: "password1",
- }),
- LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: "username2",
- password: "password2",
- }),
- LoginTestUtils.testData.formLogin({
- hostname: "http://example.org",
- formSubmitURL: "http://example.org",
- username: "username-cross-origin",
- password: "password-cross-origin",
- }),
- ];
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_exceptions_dialog.js b/toolkit/components/passwordmgr/test/browser/browser_exceptions_dialog.js
deleted file mode 100644
index 09fbe0eea..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_exceptions_dialog.js
+++ /dev/null
@@ -1,56 +0,0 @@
-
-"use strict";
-
-const LOGIN_HOST = "http://example.com";
-
-function openExceptionsDialog() {
- return window.openDialog(
- "chrome://browser/content/preferences/permissions.xul",
- "Toolkit:PasswordManagerExceptions", "",
- {
- blockVisible: true,
- sessionVisible: false,
- allowVisible: false,
- hideStatusColumn: true,
- prefilledHost: "",
- permissionType: "login-saving"
- }
- );
-}
-
-function countDisabledHosts(dialog) {
- let doc = dialog.document;
- let rejectsTree = doc.getElementById("permissionsTree");
-
- return rejectsTree.view.rowCount;
-}
-
-function promiseStorageChanged(expectedData) {
- function observer(subject, data) {
- return data == expectedData && subject.QueryInterface(Ci.nsISupportsString).data == LOGIN_HOST;
- }
-
- return TestUtils.topicObserved("passwordmgr-storage-changed", observer);
-}
-
-add_task(function* test_disable() {
- let dialog = openExceptionsDialog();
- let promiseChanged = promiseStorageChanged("hostSavingDisabled");
-
- yield BrowserTestUtils.waitForEvent(dialog, "load");
- Services.logins.setLoginSavingEnabled(LOGIN_HOST, false);
- yield promiseChanged;
- is(countDisabledHosts(dialog), 1, "Verify disabled host added");
- yield BrowserTestUtils.closeWindow(dialog);
-});
-
-add_task(function* test_enable() {
- let dialog = openExceptionsDialog();
- let promiseChanged = promiseStorageChanged("hostSavingEnabled");
-
- yield BrowserTestUtils.waitForEvent(dialog, "load");
- Services.logins.setLoginSavingEnabled(LOGIN_HOST, true);
- yield promiseChanged;
- is(countDisabledHosts(dialog), 0, "Verify disabled host removed");
- yield BrowserTestUtils.closeWindow(dialog);
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_formless_submit_chrome.js b/toolkit/components/passwordmgr/test/browser/browser_formless_submit_chrome.js
deleted file mode 100644
index c6d9ce50a..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_formless_submit_chrome.js
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Test that browser chrome UI interactions don't trigger a capture doorhanger.
- */
-
-"use strict";
-
-function* fillTestPage(aBrowser) {
- yield ContentTask.spawn(aBrowser, null, function*() {
- content.document.getElementById("form-basic-username").value = "my_username";
- content.document.getElementById("form-basic-password").value = "my_password";
- });
- info("fields filled");
-}
-
-function* withTestPage(aTaskFn) {
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://example.com" + DIRECTORY_PATH + "formless_basic.html",
- }, function*(aBrowser) {
- info("tab opened");
- yield fillTestPage(aBrowser);
- yield* aTaskFn(aBrowser);
-
- // Give a chance for the doorhanger to appear
- yield new Promise(resolve => SimpleTest.executeSoon(resolve));
- ok(!getCaptureDoorhanger("any"), "No doorhanger should be present");
- });
-}
-
-add_task(function* setup() {
- yield SimpleTest.promiseFocus(window);
-});
-
-add_task(function* test_urlbar_new_URL() {
- yield withTestPage(function*(aBrowser) {
- gURLBar.value = "";
- let focusPromise = BrowserTestUtils.waitForEvent(gURLBar, "focus");
- gURLBar.focus();
- yield focusPromise;
- info("focused");
- EventUtils.sendString("http://mochi.test:8888/");
- EventUtils.synthesizeKey("VK_RETURN", {});
- yield BrowserTestUtils.browserLoaded(aBrowser, false, "http://mochi.test:8888/");
- });
-});
-
-add_task(function* test_urlbar_fragment_enter() {
- yield withTestPage(function*(aBrowser) {
- gURLBar.focus();
- EventUtils.synthesizeKey("VK_RIGHT", {});
- EventUtils.sendString("#fragment");
- EventUtils.synthesizeKey("VK_RETURN", {});
- });
-});
-
-add_task(function* test_backButton_forwardButton() {
- yield withTestPage(function*(aBrowser) {
- // Load a new page in the tab so we can test going back
- aBrowser.loadURI("https://example.com" + DIRECTORY_PATH + "formless_basic.html?second");
- yield BrowserTestUtils.browserLoaded(aBrowser, false,
- "https://example.com" + DIRECTORY_PATH +
- "formless_basic.html?second");
- yield fillTestPage(aBrowser);
-
- let forwardButton = document.getElementById("forward-button");
- // We need to wait for the forward button transition to complete before we
- // can click it, so we hook up a listener to wait for it to be ready.
- let forwardTransitionPromise = BrowserTestUtils.waitForEvent(forwardButton, "transitionend");
-
- let backPromise = BrowserTestUtils.browserStopped(aBrowser);
- EventUtils.synthesizeMouseAtCenter(document.getElementById("back-button"), {});
- yield backPromise;
-
- // Give a chance for the doorhanger to appear
- yield new Promise(resolve => SimpleTest.executeSoon(resolve));
- ok(!getCaptureDoorhanger("any"), "No doorhanger should be present");
-
- // Now go forward again after filling
- yield fillTestPage(aBrowser);
-
- yield forwardTransitionPromise;
- info("transition done");
- yield BrowserTestUtils.waitForCondition(() => {
- return forwardButton.disabled == false;
- });
- let forwardPromise = BrowserTestUtils.browserStopped(aBrowser);
- info("click the forward button");
- EventUtils.synthesizeMouseAtCenter(forwardButton, {});
- yield forwardPromise;
- });
-});
-
-
-add_task(function* test_reloadButton() {
- yield withTestPage(function*(aBrowser) {
- let reloadButton = document.getElementById("urlbar-reload-button");
- let loadPromise = BrowserTestUtils.browserLoaded(aBrowser, false,
- "https://example.com" + DIRECTORY_PATH +
- "formless_basic.html");
-
- yield BrowserTestUtils.waitForCondition(() => {
- return reloadButton.disabled == false;
- });
- EventUtils.synthesizeMouseAtCenter(reloadButton, {});
- yield loadPromise;
- });
-});
-
-add_task(function* test_back_keyboard_shortcut() {
- if (Services.prefs.getIntPref("browser.backspace_action") != 0) {
- ok(true, "Skipped testing backspace to go back since it's disabled");
- return;
- }
- yield withTestPage(function*(aBrowser) {
- // Load a new page in the tab so we can test going back
- aBrowser.loadURI("https://example.com" + DIRECTORY_PATH + "formless_basic.html?second");
- yield BrowserTestUtils.browserLoaded(aBrowser, false,
- "https://example.com" + DIRECTORY_PATH +
- "formless_basic.html?second");
- yield fillTestPage(aBrowser);
-
- let backPromise = BrowserTestUtils.browserStopped(aBrowser);
- EventUtils.synthesizeKey("VK_BACK_SPACE", {});
- yield backPromise;
- });
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms.js b/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms.js
deleted file mode 100644
index 039312b7d..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Cu.import("resource://gre/modules/LoginManagerParent.jsm", this);
-
-const testUrlPath =
- "://example.com/browser/toolkit/components/passwordmgr/test/browser/";
-
-/**
- * Waits for the given number of occurrences of InsecureLoginFormsStateChange
- * on the given browser element.
- */
-function waitForInsecureLoginFormsStateChange(browser, count) {
- return BrowserTestUtils.waitForEvent(browser, "InsecureLoginFormsStateChange",
- false, () => --count == 0);
-}
-
-/**
- * Checks that hasInsecureLoginForms is true for a simple HTTP page and false
- * for a simple HTTPS page.
- */
-add_task(function* test_simple() {
- for (let scheme of ["http", "https"]) {
- let tab = gBrowser.addTab(scheme + testUrlPath + "form_basic.html");
- let browser = tab.linkedBrowser;
- yield Promise.all([
- BrowserTestUtils.switchTab(gBrowser, tab),
- BrowserTestUtils.browserLoaded(browser),
- // One event is triggered by pageshow and one by DOMFormHasPassword.
- waitForInsecureLoginFormsStateChange(browser, 2),
- ]);
-
- Assert.equal(LoginManagerParent.hasInsecureLoginForms(browser),
- scheme == "http");
-
- gBrowser.removeTab(tab);
- }
-});
-
-/**
- * Checks that hasInsecureLoginForms is true if a password field is present in
- * an HTTP page loaded as a subframe of a top-level HTTPS page, when mixed
- * active content blocking is disabled.
- *
- * When the subframe is navigated to an HTTPS page, hasInsecureLoginForms should
- * be set to false.
- *
- * Moving back in history should set hasInsecureLoginForms to true again.
- */
-add_task(function* test_subframe_navigation() {
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({
- "set": [["security.mixed_content.block_active_content", false]],
- }, resolve));
-
- // Load the page with the subframe in a new tab.
- let tab = gBrowser.addTab("https" + testUrlPath + "insecure_test.html");
- let browser = tab.linkedBrowser;
- yield Promise.all([
- BrowserTestUtils.switchTab(gBrowser, tab),
- BrowserTestUtils.browserLoaded(browser),
- // Two events are triggered by pageshow and one by DOMFormHasPassword.
- waitForInsecureLoginFormsStateChange(browser, 3),
- ]);
-
- Assert.ok(LoginManagerParent.hasInsecureLoginForms(browser));
-
- // Navigate the subframe to a secure page.
- let promiseSubframeReady = Promise.all([
- BrowserTestUtils.browserLoaded(browser, true),
- // One event is triggered by pageshow and one by DOMFormHasPassword.
- waitForInsecureLoginFormsStateChange(browser, 2),
- ]);
- yield ContentTask.spawn(browser, null, function* () {
- content.document.getElementById("test-iframe")
- .contentDocument.getElementById("test-link").click();
- });
- yield promiseSubframeReady;
-
- Assert.ok(!LoginManagerParent.hasInsecureLoginForms(browser));
-
- // Navigate back to the insecure page. We only have to wait for the
- // InsecureLoginFormsStateChange event that is triggered by pageshow.
- let promise = waitForInsecureLoginFormsStateChange(browser, 1);
- yield ContentTask.spawn(browser, null, function* () {
- content.document.getElementById("test-iframe")
- .contentWindow.history.back();
- });
- yield promise;
-
- Assert.ok(LoginManagerParent.hasInsecureLoginForms(browser));
-
- gBrowser.removeTab(tab);
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms_streamConverter.js b/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms_streamConverter.js
deleted file mode 100644
index 2dbffb9cc..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_hasInsecureLoginForms_streamConverter.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Cu.import("resource://gre/modules/LoginManagerParent.jsm", this);
-
-function* registerConverter() {
- Cu.import("resource://gre/modules/Services.jsm", this);
- Cu.import("resource://gre/modules/NetUtil.jsm", this);
-
- /**
- * Converts the "test/content" MIME type, served by the test over HTTP, to an
- * HTML viewer page containing the "form_basic.html" code. The viewer is
- * served from a "resource:" URI while keeping the "resource:" principal.
- */
- function TestStreamConverter() {}
-
- TestStreamConverter.prototype = {
- classID: Components.ID("{5f01d6ef-c090-45a4-b3e5-940d64713eb7}"),
- contractID: "@mozilla.org/streamconv;1?from=test/content&to=*/*",
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIRequestObserver,
- Ci.nsIStreamListener,
- Ci.nsIStreamConverter,
- ]),
-
- // nsIStreamConverter
- convert() {},
-
- // nsIStreamConverter
- asyncConvertData(aFromType, aToType, aListener, aCtxt) {
- this.listener = aListener;
- },
-
- // nsIRequestObserver
- onStartRequest(aRequest, aContext) {
- let channel = NetUtil.newChannel({
- uri: "resource://testing-common/form_basic.html",
- loadUsingSystemPrincipal: true,
- });
- channel.originalURI = aRequest.QueryInterface(Ci.nsIChannel).URI;
- channel.loadGroup = aRequest.loadGroup;
- channel.owner = Services.scriptSecurityManager
- .createCodebasePrincipal(channel.URI, {});
- // In this test, we pass the new channel to the listener but don't fire a
- // redirect notification, even if it would be required. This keeps the
- // test code simpler and doesn't impact the principal check we're testing.
- channel.asyncOpen2(this.listener);
- },
-
- // nsIRequestObserver
- onStopRequest() {},
-
- // nsIStreamListener
- onDataAvailable() {},
- };
-
- let factory = XPCOMUtils._getFactory(TestStreamConverter);
- let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
- registrar.registerFactory(TestStreamConverter.prototype.classID, "",
- TestStreamConverter.prototype.contractID, factory);
- this.cleanupFunction = function () {
- registrar.unregisterFactory(TestStreamConverter.prototype.classID, factory);
- };
-}
-
-/**
- * Waits for the given number of occurrences of InsecureLoginFormsStateChange
- * on the given browser element.
- */
-function waitForInsecureLoginFormsStateChange(browser, count) {
- return BrowserTestUtils.waitForEvent(browser, "InsecureLoginFormsStateChange",
- false, () => --count == 0);
-}
-
-/**
- * Checks that hasInsecureLoginForms is false for a viewer served internally
- * using a "resource:" URI.
- */
-add_task(function* test_streamConverter() {
- let originalBrowser = gBrowser.selectedTab.linkedBrowser;
-
- yield ContentTask.spawn(originalBrowser, null, registerConverter);
-
- let tab = gBrowser.addTab("http://example.com/browser/toolkit/components/" +
- "passwordmgr/test/browser/streamConverter_content.sjs",
- { relatedBrowser: originalBrowser.linkedBrowser });
- let browser = tab.linkedBrowser;
- yield Promise.all([
- BrowserTestUtils.switchTab(gBrowser, tab),
- BrowserTestUtils.browserLoaded(browser),
- // One event is triggered by pageshow and one by DOMFormHasPassword.
- waitForInsecureLoginFormsStateChange(browser, 2),
- ]);
-
- Assert.ok(!LoginManagerParent.hasInsecureLoginForms(browser));
-
- yield BrowserTestUtils.removeTab(tab);
-
- yield ContentTask.spawn(originalBrowser, null, function* () {
- this.cleanupFunction();
- });
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_http_autofill.js b/toolkit/components/passwordmgr/test/browser/browser_http_autofill.js
deleted file mode 100644
index beb928a34..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_http_autofill.js
+++ /dev/null
@@ -1,78 +0,0 @@
-const TEST_URL_PATH = "://example.org/browser/toolkit/components/passwordmgr/test/browser/";
-
-add_task(function* setup() {
- let login = LoginTestUtils.testData.formLogin({
- hostname: "http://example.org",
- formSubmitURL: "http://example.org",
- username: "username",
- password: "password",
- });
- Services.logins.addLogin(login);
- login = LoginTestUtils.testData.formLogin({
- hostname: "http://example.org",
- formSubmitURL: "http://another.domain",
- username: "username",
- password: "password",
- });
- Services.logins.addLogin(login);
- yield SpecialPowers.pushPrefEnv({ "set": [["signon.autofillForms.http", false]] });
-});
-
-add_task(function* test_http_autofill() {
- for (let scheme of ["http", "https"]) {
- let tab = yield BrowserTestUtils
- .openNewForegroundTab(gBrowser, `${scheme}${TEST_URL_PATH}form_basic.html`);
-
- let [username, password] = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- let doc = content.document;
- let contentUsername = doc.getElementById("form-basic-username").value;
- let contentPassword = doc.getElementById("form-basic-password").value;
- return [contentUsername, contentPassword];
- });
-
- is(username, scheme == "http" ? "" : "username", "Username filled correctly");
- is(password, scheme == "http" ? "" : "password", "Password filled correctly");
-
- gBrowser.removeTab(tab);
- }
-});
-
-add_task(function* test_iframe_in_http_autofill() {
- for (let scheme of ["http", "https"]) {
- let tab = yield BrowserTestUtils
- .openNewForegroundTab(gBrowser, `${scheme}${TEST_URL_PATH}form_basic_iframe.html`);
-
- let [username, password] = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- let doc = content.document;
- let iframe = doc.getElementById("test-iframe");
- let contentUsername = iframe.contentWindow.document.getElementById("form-basic-username").value;
- let contentPassword = iframe.contentWindow.document.getElementById("form-basic-password").value;
- return [contentUsername, contentPassword];
- });
-
- is(username, scheme == "http" ? "" : "username", "Username filled correctly");
- is(password, scheme == "http" ? "" : "password", "Password filled correctly");
-
- gBrowser.removeTab(tab);
- }
-});
-
-add_task(function* test_http_action_autofill() {
- for (let type of ["insecure", "secure"]) {
- let tab = yield BrowserTestUtils
- .openNewForegroundTab(gBrowser, `https${TEST_URL_PATH}form_cross_origin_${type}_action.html`);
-
- let [username, password] = yield ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
- let doc = content.document;
- let contentUsername = doc.getElementById("form-basic-username").value;
- let contentPassword = doc.getElementById("form-basic-password").value;
- return [contentUsername, contentPassword];
- });
-
- is(username, type == "insecure" ? "" : "username", "Username filled correctly");
- is(password, type == "insecure" ? "" : "password", "Password filled correctly");
-
- gBrowser.removeTab(tab);
- }
-});
-
diff --git a/toolkit/components/passwordmgr/test/browser/browser_insecurePasswordConsoleWarning.js b/toolkit/components/passwordmgr/test/browser/browser_insecurePasswordConsoleWarning.js
deleted file mode 100644
index f16ae1b98..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_insecurePasswordConsoleWarning.js
+++ /dev/null
@@ -1,94 +0,0 @@
-"use strict";
-
-const WARNING_PATTERN = [{
- key: "INSECURE_FORM_ACTION",
- msg: 'JavaScript Warning: "Password fields present in a form with an insecure (http://) form action. This is a security risk that allows user login credentials to be stolen."'
-}, {
- key: "INSECURE_PAGE",
- msg: 'JavaScript Warning: "Password fields present on an insecure (http://) page. This is a security risk that allows user login credentials to be stolen."'
-}];
-
-add_task(function* testInsecurePasswordWarning() {
- let warningPatternHandler;
-
- function messageHandler(msgObj) {
- function findWarningPattern(msg) {
- return WARNING_PATTERN.find(patternPair => {
- return msg.indexOf(patternPair.msg) !== -1;
- });
- }
-
- let warning = findWarningPattern(msgObj.message);
-
- // Only handle the insecure password related warning messages.
- if (warning) {
- // Prevent any unexpected or redundant matched warning message coming after
- // the test case is ended.
- ok(warningPatternHandler, "Invoke a valid warning message handler");
- warningPatternHandler(warning, msgObj.message);
- }
- }
- Services.console.registerListener(messageHandler);
- registerCleanupFunction(function() {
- Services.console.unregisterListener(messageHandler);
- });
-
- for (let [origin, testFile, expectWarnings] of [
- ["http://127.0.0.1", "form_basic.html", []],
- ["http://127.0.0.1", "formless_basic.html", []],
- ["http://example.com", "form_basic.html", ["INSECURE_PAGE"]],
- ["http://example.com", "formless_basic.html", ["INSECURE_PAGE"]],
- ["https://example.com", "form_basic.html", []],
- ["https://example.com", "formless_basic.html", []],
-
- // For a form with customized action link in the same origin.
- ["http://127.0.0.1", "form_same_origin_action.html", []],
- ["http://example.com", "form_same_origin_action.html", ["INSECURE_PAGE"]],
- ["https://example.com", "form_same_origin_action.html", []],
-
- // For a form with an insecure (http) customized action link.
- ["http://127.0.0.1", "form_cross_origin_insecure_action.html", ["INSECURE_FORM_ACTION"]],
- ["http://example.com", "form_cross_origin_insecure_action.html", ["INSECURE_PAGE"]],
- ["https://example.com", "form_cross_origin_insecure_action.html", ["INSECURE_FORM_ACTION"]],
-
- // For a form with a secure (https) customized action link.
- ["http://127.0.0.1", "form_cross_origin_secure_action.html", []],
- ["http://example.com", "form_cross_origin_secure_action.html", ["INSECURE_PAGE"]],
- ["https://example.com", "form_cross_origin_secure_action.html", []],
- ]) {
- let testURL = origin + DIRECTORY_PATH + testFile;
- let promiseConsoleMessages = new Promise(resolve => {
- warningPatternHandler = function (warning, originMessage) {
- ok(warning, "Handling a warning pattern");
- let fullMessage = `[${warning.msg} {file: "${testURL}" line: 0 column: 0 source: "0"}]`;
- is(originMessage, fullMessage, "Message full matched:" + originMessage);
-
- let index = expectWarnings.indexOf(warning.key);
- isnot(index, -1, "Found warning: " + warning.key + " for URL:" + testURL);
- if (index !== -1) {
- // Remove the shown message.
- expectWarnings.splice(index, 1);
- }
- if (expectWarnings.length === 0) {
- info("All warnings are shown for URL:" + testURL);
- resolve();
- }
- };
- });
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: testURL
- }, function*() {
- if (expectWarnings.length === 0) {
- info("All warnings are shown for URL:" + testURL);
- return Promise.resolve();
- }
- return promiseConsoleMessages;
- });
-
- // Remove warningPatternHandler to stop handling the matched warning pattern
- // and the task should not get any warning anymore.
- warningPatternHandler = null;
- }
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_master_password_autocomplete.js b/toolkit/components/passwordmgr/test/browser/browser_master_password_autocomplete.js
deleted file mode 100644
index f3bc62b0a..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_master_password_autocomplete.js
+++ /dev/null
@@ -1,59 +0,0 @@
-const HOST = "https://example.com";
-const URL = HOST + "/browser/toolkit/components/passwordmgr/test/browser/form_basic.html";
-const TIMEOUT_PREF = "signon.masterPasswordReprompt.timeout_ms";
-
-// Waits for the master password prompt and cancels it.
-function waitForDialog() {
- let dialogShown = TestUtils.topicObserved("common-dialog-loaded");
- return dialogShown.then(function([subject]) {
- let dialog = subject.Dialog;
- is(dialog.args.title, "Password Required");
- dialog.ui.button1.click();
- });
-}
-
-// Test that autocomplete does not trigger a master password prompt
-// for a certain time after it was cancelled.
-add_task(function* test_mpAutocompleteTimeout() {
- let login = LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: "username",
- password: "password",
- });
- Services.logins.addLogin(login);
- LoginTestUtils.masterPassword.enable();
-
- registerCleanupFunction(function() {
- LoginTestUtils.masterPassword.disable();
- Services.logins.removeAllLogins();
- });
-
- // Set master password prompt timeout to 3s.
- // If this test goes intermittent, you likely have to increase this value.
- yield SpecialPowers.pushPrefEnv({set: [[TIMEOUT_PREF, 3000]]});
-
- // Wait for initial master password dialog after opening the tab.
- let dialogShown = waitForDialog();
-
- yield BrowserTestUtils.withNewTab(URL, function*(browser) {
- yield dialogShown;
-
- yield ContentTask.spawn(browser, null, function*() {
- // Focus the password field to trigger autocompletion.
- content.document.getElementById("form-basic-password").focus();
- });
-
- // Wait 4s, dialog should not have been shown
- // (otherwise the code below will not work).
- yield new Promise((c) => setTimeout(c, 4000));
-
- dialogShown = waitForDialog();
- yield ContentTask.spawn(browser, null, function*() {
- // Re-focus the password field to trigger autocompletion.
- content.document.getElementById("form-basic-username").focus();
- content.document.getElementById("form-basic-password").focus();
- });
- yield dialogShown;
- });
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_notifications.js b/toolkit/components/passwordmgr/test/browser/browser_notifications.js
deleted file mode 100644
index 4fb012f14..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_notifications.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Test that the doorhanger notification for password saving is populated with
- * the correct values in various password capture cases.
- */
-add_task(function* test_save_change() {
- let testCases = [{
- username: "username",
- password: "password",
- }, {
- username: "",
- password: "password",
- }, {
- username: "username",
- oldPassword: "password",
- password: "newPassword",
- }, {
- username: "",
- oldPassword: "password",
- password: "newPassword",
- }];
-
- for (let { username, oldPassword, password } of testCases) {
- // Add a login for the origin of the form if testing a change notification.
- if (oldPassword) {
- Services.logins.addLogin(LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username,
- password: oldPassword,
- }));
- }
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://example.com/browser/toolkit/components/" +
- "passwordmgr/test/browser/form_basic.html",
- }, function* (browser) {
- // Submit the form in the content page with the credentials from the test
- // case. This will cause the doorhanger notification to be displayed.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "popupshown",
- (event) => event.target == PopupNotifications.panel);
- yield ContentTask.spawn(browser, [username, password],
- function* ([contentUsername, contentPassword]) {
- let doc = content.document;
- doc.getElementById("form-basic-username").value = contentUsername;
- doc.getElementById("form-basic-password").value = contentPassword;
- doc.getElementById("form-basic").submit();
- });
- yield promiseShown;
- let notificationElement = PopupNotifications.panel.childNodes[0];
- // Style flush to make sure binding is attached
- notificationElement.querySelector("#password-notification-password").clientTop;
-
- // Check the actual content of the popup notification.
- Assert.equal(notificationElement.querySelector("#password-notification-username")
- .value, username);
- Assert.equal(notificationElement.querySelector("#password-notification-password")
- .value, password);
-
- // Simulate the action on the notification to request the login to be
- // saved, and wait for the data to be updated or saved based on the type
- // of operation we expect.
- let expectedNotification = oldPassword ? "modifyLogin" : "addLogin";
- let promiseLogin = TestUtils.topicObserved("passwordmgr-storage-changed",
- (_, data) => data == expectedNotification);
- notificationElement.button.doCommand();
- let [result] = yield promiseLogin;
-
- // Check that the values in the database match the expected values.
- let login = oldPassword ? result.QueryInterface(Ci.nsIArray)
- .queryElementAt(1, Ci.nsILoginInfo)
- : result.QueryInterface(Ci.nsILoginInfo);
- Assert.equal(login.username, username);
- Assert.equal(login.password, password);
- });
-
- // Clean up the database before the next test case is executed.
- Services.logins.removeAllLogins();
- }
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_notifications_2.js b/toolkit/components/passwordmgr/test/browser/browser_notifications_2.js
deleted file mode 100644
index 48c73b0e6..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_notifications_2.js
+++ /dev/null
@@ -1,125 +0,0 @@
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["signon.rememberSignons.visibilityToggle", true]
- ]});
-});
-
-/**
- * Test that the doorhanger main action button is disabled
- * when the password field is empty.
- *
- * Also checks that submiting an empty password throws an error.
- */
-add_task(function* test_empty_password() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://example.com/browser/toolkit/components/" +
- "passwordmgr/test/browser/form_basic.html",
- }, function* (browser) {
- // Submit the form in the content page with the credentials from the test
- // case. This will cause the doorhanger notification to be displayed.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "popupshown",
- (event) => event.target == PopupNotifications.panel);
- yield ContentTask.spawn(browser, null,
- function* () {
- let doc = content.document;
- doc.getElementById("form-basic-username").value = "username";
- doc.getElementById("form-basic-password").value = "p";
- doc.getElementById("form-basic").submit();
- });
- yield promiseShown;
-
- let notificationElement = PopupNotifications.panel.childNodes[0];
- let passwordTextbox = notificationElement.querySelector("#password-notification-password");
- let toggleCheckbox = notificationElement.querySelector("#password-notification-visibilityToggle");
-
- // Synthesize input to empty the field
- passwordTextbox.focus();
- yield EventUtils.synthesizeKey("VK_RIGHT", {});
- yield EventUtils.synthesizeKey("VK_BACK_SPACE", {});
-
- let mainActionButton = document.getAnonymousElementByAttribute(notificationElement.button, "anonid", "button");
- Assert.ok(mainActionButton.disabled, "Main action button is disabled");
-
- // Makes sure submiting an empty password throws an error
- Assert.throws(notificationElement.button.doCommand(),
- "Can't add a login with a null or empty password.",
- "Should fail for an empty password");
- });
-});
-
-/**
- * Test that the doorhanger password field shows plain or * text
- * when the checkbox is checked.
- */
-add_task(function* test_toggle_password() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://example.com/browser/toolkit/components/" +
- "passwordmgr/test/browser/form_basic.html",
- }, function* (browser) {
- // Submit the form in the content page with the credentials from the test
- // case. This will cause the doorhanger notification to be displayed.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "popupshown",
- (event) => event.target == PopupNotifications.panel);
- yield ContentTask.spawn(browser, null,
- function* () {
- let doc = content.document;
- doc.getElementById("form-basic-username").value = "username";
- doc.getElementById("form-basic-password").value = "p";
- doc.getElementById("form-basic").submit();
- });
- yield promiseShown;
-
- let notificationElement = PopupNotifications.panel.childNodes[0];
- let passwordTextbox = notificationElement.querySelector("#password-notification-password");
- let toggleCheckbox = notificationElement.querySelector("#password-notification-visibilityToggle");
-
- yield EventUtils.synthesizeMouseAtCenter(toggleCheckbox, {});
- Assert.ok(toggleCheckbox.checked);
- Assert.equal(passwordTextbox.type, "", "Password textbox changed to plain text");
-
- yield EventUtils.synthesizeMouseAtCenter(toggleCheckbox, {});
- Assert.ok(!toggleCheckbox.checked);
- Assert.equal(passwordTextbox.type, "password", "Password textbox changed to * text");
- });
-});
-
-/**
- * Test that the doorhanger password toggle checkbox is disabled
- * when the master password is set.
- */
-add_task(function* test_checkbox_disabled_if_has_master_password() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://example.com/browser/toolkit/components/" +
- "passwordmgr/test/browser/form_basic.html",
- }, function* (browser) {
- // Submit the form in the content page with the credentials from the test
- // case. This will cause the doorhanger notification to be displayed.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "popupshown",
- (event) => event.target == PopupNotifications.panel);
-
- LoginTestUtils.masterPassword.enable();
-
- yield ContentTask.spawn(browser, null, function* () {
- let doc = content.document;
- doc.getElementById("form-basic-username").value = "username";
- doc.getElementById("form-basic-password").value = "p";
- doc.getElementById("form-basic").submit();
- });
- yield promiseShown;
-
- let notificationElement = PopupNotifications.panel.childNodes[0];
- let passwordTextbox = notificationElement.querySelector("#password-notification-password");
- let toggleCheckbox = notificationElement.querySelector("#password-notification-visibilityToggle");
-
- Assert.equal(passwordTextbox.type, "password", "Password textbox should show * text");
- Assert.ok(toggleCheckbox.getAttribute("hidden"), "checkbox is hidden when master password is set");
- });
-
- LoginTestUtils.masterPassword.disable();
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_notifications_password.js b/toolkit/components/passwordmgr/test/browser/browser_notifications_password.js
deleted file mode 100644
index 8ac49dac5..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_notifications_password.js
+++ /dev/null
@@ -1,145 +0,0 @@
-/**
- * Test changing the password inside the doorhanger notification for passwords.
- *
- * We check the following cases:
- * - Editing the password of a new login.
- * - Editing the password of an existing login.
- * - Changing both username and password to an existing login.
- * - Changing the username to an existing login.
- * - Editing username to an empty one and a new password.
- *
- * If both the username and password matches an already existing login, we should not
- * update it's password, but only it's usage timestamp and count.
- */
-add_task(function* test_edit_password() {
- let testCases = [{
- usernameInPage: "username",
- passwordInPage: "password",
- passwordChangedTo: "newPassword",
- timesUsed: 1,
- }, {
- usernameInPage: "username",
- usernameInPageExists: true,
- passwordInPage: "password",
- passwordInStorage: "oldPassword",
- passwordChangedTo: "newPassword",
- timesUsed: 2,
- }, {
- usernameInPage: "username",
- usernameChangedTo: "newUsername",
- usernameChangedToExists: true,
- passwordInPage: "password",
- passwordChangedTo: "newPassword",
- timesUsed: 2,
- }, {
- usernameInPage: "username",
- usernameChangedTo: "newUsername",
- usernameChangedToExists: true,
- passwordInPage: "password",
- passwordChangedTo: "password",
- timesUsed: 2,
- checkPasswordNotUpdated: true,
- }, {
- usernameInPage: "newUsername",
- usernameChangedTo: "",
- usernameChangedToExists: true,
- passwordInPage: "password",
- passwordChangedTo: "newPassword",
- timesUsed: 2,
- }];
-
- for (let testCase of testCases) {
- info("Test case: " + JSON.stringify(testCase));
-
- // Create the pre-existing logins when needed.
- if (testCase.usernameInPageExists) {
- Services.logins.addLogin(LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: testCase.usernameInPage,
- password: testCase.passwordInStorage,
- }));
- }
-
- if (testCase.usernameChangedToExists) {
- Services.logins.addLogin(LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: testCase.usernameChangedTo,
- password: testCase.passwordChangedTo,
- }));
- }
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://example.com/browser/toolkit/components/" +
- "passwordmgr/test/browser/form_basic.html",
- }, function* (browser) {
- // Submit the form in the content page with the credentials from the test
- // case. This will cause the doorhanger notification to be displayed.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "popupshown",
- (event) => event.target == PopupNotifications.panel);
- yield ContentTask.spawn(browser, testCase,
- function* (contentTestCase) {
- let doc = content.document;
- doc.getElementById("form-basic-username").value = contentTestCase.usernameInPage;
- doc.getElementById("form-basic-password").value = contentTestCase.passwordInPage;
- doc.getElementById("form-basic").submit();
- });
- yield promiseShown;
- let notificationElement = PopupNotifications.panel.childNodes[0];
- // Style flush to make sure binding is attached
- notificationElement.querySelector("#password-notification-password").clientTop;
-
- // Modify the username in the dialog if requested.
- if (testCase.usernameChangedTo) {
- notificationElement.querySelector("#password-notification-username")
- .value = testCase.usernameChangedTo;
- }
-
- // Modify the password in the dialog if requested.
- if (testCase.passwordChangedTo) {
- notificationElement.querySelector("#password-notification-password")
- .value = testCase.passwordChangedTo;
- }
-
- // We expect a modifyLogin notification if the final username used by the
- // dialog exists in the logins database, otherwise an addLogin one.
- let expectModifyLogin = typeof testCase.usernameChangedTo !== "undefined"
- ? testCase.usernameChangedToExists
- : testCase.usernameInPageExists;
-
- // Simulate the action on the notification to request the login to be
- // saved, and wait for the data to be updated or saved based on the type
- // of operation we expect.
- let expectedNotification = expectModifyLogin ? "modifyLogin" : "addLogin";
- let promiseLogin = TestUtils.topicObserved("passwordmgr-storage-changed",
- (_, data) => data == expectedNotification);
- notificationElement.button.doCommand();
- let [result] = yield promiseLogin;
-
- // Check that the values in the database match the expected values.
- let login = expectModifyLogin ? result.QueryInterface(Ci.nsIArray)
- .queryElementAt(1, Ci.nsILoginInfo)
- : result.QueryInterface(Ci.nsILoginInfo);
-
- Assert.equal(login.username, testCase.usernameChangedTo ||
- testCase.usernameInPage);
- Assert.equal(login.password, testCase.passwordChangedTo ||
- testCase.passwordInPage);
-
- let meta = login.QueryInterface(Ci.nsILoginMetaInfo);
- Assert.equal(meta.timesUsed, testCase.timesUsed);
-
- // Check that the password was not updated if the user is empty
- if (testCase.checkPasswordNotUpdated) {
- Assert.ok(meta.timeLastUsed > meta.timeCreated);
- Assert.ok(meta.timeCreated == meta.timePasswordChanged);
- }
- });
-
- // Clean up the database before the next test case is executed.
- Services.logins.removeAllLogins();
- }
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_notifications_username.js b/toolkit/components/passwordmgr/test/browser/browser_notifications_username.js
deleted file mode 100644
index 2c9ea2607..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_notifications_username.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/**
- * Test changing the username inside the doorhanger notification for passwords.
- *
- * We have to test combination of existing and non-existing logins both for
- * the original one from the webpage and the final one used by the dialog.
- *
- * We also check switching to and from empty usernames.
- */
-add_task(function* test_edit_username() {
- let testCases = [{
- usernameInPage: "username",
- usernameChangedTo: "newUsername",
- }, {
- usernameInPage: "username",
- usernameInPageExists: true,
- usernameChangedTo: "newUsername",
- }, {
- usernameInPage: "username",
- usernameChangedTo: "newUsername",
- usernameChangedToExists: true,
- }, {
- usernameInPage: "username",
- usernameInPageExists: true,
- usernameChangedTo: "newUsername",
- usernameChangedToExists: true,
- }, {
- usernameInPage: "",
- usernameChangedTo: "newUsername",
- }, {
- usernameInPage: "newUsername",
- usernameChangedTo: "",
- }, {
- usernameInPage: "",
- usernameChangedTo: "newUsername",
- usernameChangedToExists: true,
- }, {
- usernameInPage: "newUsername",
- usernameChangedTo: "",
- usernameChangedToExists: true,
- }];
-
- for (let testCase of testCases) {
- info("Test case: " + JSON.stringify(testCase));
-
- // Create the pre-existing logins when needed.
- if (testCase.usernameInPageExists) {
- Services.logins.addLogin(LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: testCase.usernameInPage,
- password: "old password",
- }));
- }
-
- if (testCase.usernameChangedToExists) {
- Services.logins.addLogin(LoginTestUtils.testData.formLogin({
- hostname: "https://example.com",
- formSubmitURL: "https://example.com",
- username: testCase.usernameChangedTo,
- password: "old password",
- }));
- }
-
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "https://example.com/browser/toolkit/components/" +
- "passwordmgr/test/browser/form_basic.html",
- }, function* (browser) {
- // Submit the form in the content page with the credentials from the test
- // case. This will cause the doorhanger notification to be displayed.
- let promiseShown = BrowserTestUtils.waitForEvent(PopupNotifications.panel,
- "popupshown",
- (event) => event.target == PopupNotifications.panel);
- yield ContentTask.spawn(browser, testCase.usernameInPage,
- function* (usernameInPage) {
- let doc = content.document;
- doc.getElementById("form-basic-username").value = usernameInPage;
- doc.getElementById("form-basic-password").value = "password";
- doc.getElementById("form-basic").submit();
- });
- yield promiseShown;
- let notificationElement = PopupNotifications.panel.childNodes[0];
- // Style flush to make sure binding is attached
- notificationElement.querySelector("#password-notification-password").clientTop;
-
- // Modify the username in the dialog if requested.
- if (testCase.usernameChangedTo) {
- notificationElement.querySelector("#password-notification-username")
- .value = testCase.usernameChangedTo;
- }
-
- // We expect a modifyLogin notification if the final username used by the
- // dialog exists in the logins database, otherwise an addLogin one.
- let expectModifyLogin = testCase.usernameChangedTo
- ? testCase.usernameChangedToExists
- : testCase.usernameInPageExists;
-
- // Simulate the action on the notification to request the login to be
- // saved, and wait for the data to be updated or saved based on the type
- // of operation we expect.
- let expectedNotification = expectModifyLogin ? "modifyLogin" : "addLogin";
- let promiseLogin = TestUtils.topicObserved("passwordmgr-storage-changed",
- (_, data) => data == expectedNotification);
- notificationElement.button.doCommand();
- let [result] = yield promiseLogin;
-
- // Check that the values in the database match the expected values.
- let login = expectModifyLogin ? result.QueryInterface(Ci.nsIArray)
- .queryElementAt(1, Ci.nsILoginInfo)
- : result.QueryInterface(Ci.nsILoginInfo);
- Assert.equal(login.username, testCase.usernameChangedTo ||
- testCase.usernameInPage);
- Assert.equal(login.password, "password");
- });
-
- // Clean up the database before the next test case is executed.
- Services.logins.removeAllLogins();
- }
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_contextmenu.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_contextmenu.js
deleted file mode 100644
index ece2b731f..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_contextmenu.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
- waitForExplicitFinish();
-
- Services.logins.removeAllLogins();
-
- // Add some initial logins
- let urls = [
- "http://example.com/",
- "http://mozilla.org/",
- "http://spreadfirefox.com/",
- "https://support.mozilla.org/",
- "http://hg.mozilla.org/"
- ];
- let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- let logins = [
- new nsLoginInfo(urls[0], urls[0], null, "", "o hai", "u1", "p1"),
- new nsLoginInfo(urls[1], urls[1], null, "ehsan", "coded", "u2", "p2"),
- new nsLoginInfo(urls[2], urls[2], null, "this", "awesome", "u3", "p3"),
- new nsLoginInfo(urls[3], urls[3], null, "array of", "logins", "u4", "p4"),
- new nsLoginInfo(urls[4], urls[4], null, "then", "i wrote the test", "u5", "p5")
- ];
- logins.forEach(login => Services.logins.addLogin(login));
-
- // Open the password manager dialog
- const PWMGR_DLG = "chrome://passwordmgr/content/passwordManager.xul";
- let pwmgrdlg = window.openDialog(PWMGR_DLG, "Toolkit:PasswordManager", "");
- SimpleTest.waitForFocus(doTest, pwmgrdlg);
-
- // Test if "Copy Username" and "Copy Password" works
- function doTest() {
- let doc = pwmgrdlg.document;
- let selection = doc.getElementById("signonsTree").view.selection;
- let menuitem = doc.getElementById("context-copyusername");
-
- function copyField() {
- info("Select all");
- selection.selectAll();
- assertMenuitemEnabled("copyusername", false);
- assertMenuitemEnabled("editusername", false);
- assertMenuitemEnabled("copypassword", false);
- assertMenuitemEnabled("editpassword", false);
-
- info("Select the first row (with an empty username)");
- selection.select(0);
- assertMenuitemEnabled("copyusername", false, "empty username");
- assertMenuitemEnabled("editusername", true);
- assertMenuitemEnabled("copypassword", true);
- assertMenuitemEnabled("editpassword", false, "password column hidden");
-
- info("Clear the selection");
- selection.clearSelection();
- assertMenuitemEnabled("copyusername", false);
- assertMenuitemEnabled("editusername", false);
- assertMenuitemEnabled("copypassword", false);
- assertMenuitemEnabled("editpassword", false);
-
- info("Select the third row and making the password column visible");
- selection.select(2);
- doc.getElementById("passwordCol").hidden = false;
- assertMenuitemEnabled("copyusername", true);
- assertMenuitemEnabled("editusername", true);
- assertMenuitemEnabled("copypassword", true);
- assertMenuitemEnabled("editpassword", true, "password column visible");
- menuitem.doCommand();
- }
-
- function assertMenuitemEnabled(idSuffix, expected, reason = "") {
- doc.defaultView.UpdateContextMenu();
- let actual = !doc.getElementById("context-" + idSuffix).getAttribute("disabled");
- is(actual, expected, idSuffix + " should be " + (expected ? "enabled" : "disabled") +
- (reason ? ": " + reason : ""));
- }
-
- function cleanUp() {
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- Services.ww.unregisterNotification(arguments.callee);
- Services.logins.removeAllLogins();
- doc.getElementById("passwordCol").hidden = true;
- finish();
- });
- pwmgrdlg.close();
- }
-
- function testPassword() {
- info("Testing Copy Password");
- waitForClipboard("coded", function copyPassword() {
- menuitem = doc.getElementById("context-copypassword");
- menuitem.doCommand();
- }, cleanUp, cleanUp);
- }
-
- info("Testing Copy Username");
- waitForClipboard("ehsan", copyField, testPassword, testPassword);
- }
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js
deleted file mode 100644
index 2b2e42273..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_editing.js
+++ /dev/null
@@ -1,126 +0,0 @@
-const { ContentTaskUtils } = Cu.import("resource://testing-common/ContentTaskUtils.jsm", {});
-const PWMGR_DLG = "chrome://passwordmgr/content/passwordManager.xul";
-
-var doc;
-var pwmgr;
-var pwmgrdlg;
-var signonsTree;
-
-function addLogin(site, username, password) {
- let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- let login = new nsLoginInfo(site, site, null, username, password, "u", "p");
- Services.logins.addLogin(login);
-}
-
-function getUsername(row) {
- return signonsTree.view.getCellText(row, signonsTree.columns.getNamedColumn("userCol"));
-}
-
-function getPassword(row) {
- return signonsTree.view.getCellText(row, signonsTree.columns.getNamedColumn("passwordCol"));
-}
-
-function synthesizeDblClickOnCell(aTree, column, row) {
- let tbo = aTree.treeBoxObject;
- let rect = tbo.getCoordsForCellItem(row, aTree.columns[column], "text");
- let x = rect.x + rect.width / 2;
- let y = rect.y + rect.height / 2;
- // Simulate the double click.
- EventUtils.synthesizeMouse(aTree.body, x, y, { clickCount: 2 },
- aTree.ownerDocument.defaultView);
-}
-
-function* togglePasswords() {
- pwmgrdlg.document.querySelector("#togglePasswords").doCommand();
- yield new Promise(resolve => waitForFocus(resolve, pwmgrdlg));
-}
-
-function* editUsernamePromises(site, oldUsername, newUsername) {
- is(Services.logins.findLogins({}, site, "", "").length, 1, "Correct login found");
- let login = Services.logins.findLogins({}, site, "", "")[0];
- is(login.username, oldUsername, "Correct username saved");
- is(getUsername(0), oldUsername, "Correct username shown");
- synthesizeDblClickOnCell(signonsTree, 1, 0);
- yield ContentTaskUtils.waitForCondition(() => signonsTree.getAttribute("editing"),
- "Waiting for editing");
-
- EventUtils.sendString(newUsername, pwmgrdlg);
- let signonsIntro = doc.querySelector("#signonsIntro");
- EventUtils.sendMouseEvent({type: "click"}, signonsIntro, pwmgrdlg);
- yield ContentTaskUtils.waitForCondition(() => !signonsTree.getAttribute("editing"),
- "Waiting for editing to stop");
-
- is(Services.logins.findLogins({}, site, "", "").length, 1, "Correct login replaced");
- login = Services.logins.findLogins({}, site, "", "")[0];
- is(login.username, newUsername, "Correct username updated");
- is(getUsername(0), newUsername, "Correct username shown after the update");
-}
-
-function* editPasswordPromises(site, oldPassword, newPassword) {
- is(Services.logins.findLogins({}, site, "", "").length, 1, "Correct login found");
- let login = Services.logins.findLogins({}, site, "", "")[0];
- is(login.password, oldPassword, "Correct password saved");
- is(getPassword(0), oldPassword, "Correct password shown");
-
- synthesizeDblClickOnCell(signonsTree, 2, 0);
- yield ContentTaskUtils.waitForCondition(() => signonsTree.getAttribute("editing"),
- "Waiting for editing");
-
- EventUtils.sendString(newPassword, pwmgrdlg);
- let signonsIntro = doc.querySelector("#signonsIntro");
- EventUtils.sendMouseEvent({type: "click"}, signonsIntro, pwmgrdlg);
- yield ContentTaskUtils.waitForCondition(() => !signonsTree.getAttribute("editing"),
- "Waiting for editing to stop");
-
- is(Services.logins.findLogins({}, site, "", "").length, 1, "Correct login replaced");
- login = Services.logins.findLogins({}, site, "", "")[0];
- is(login.password, newPassword, "Correct password updated");
- is(getPassword(0), newPassword, "Correct password shown after the update");
-}
-
-add_task(function* test_setup() {
- registerCleanupFunction(function() {
- Services.logins.removeAllLogins();
- });
-
- Services.logins.removeAllLogins();
- // Open the password manager dialog.
- pwmgrdlg = window.openDialog(PWMGR_DLG, "Toolkit:PasswordManager", "");
-
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- if (aTopic == "domwindowopened") {
- let win = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
- SimpleTest.waitForFocus(function() {
- EventUtils.sendKey("RETURN", win);
- }, win);
- } else if (aSubject.location == pwmgrdlg.location && aTopic == "domwindowclosed") {
- // Unregister ourself.
- Services.ww.unregisterNotification(arguments.callee);
- }
- });
-
- yield new Promise((resolve) => {
- SimpleTest.waitForFocus(() => {
- doc = pwmgrdlg.document;
- signonsTree = doc.querySelector("#signonsTree");
- resolve();
- }, pwmgrdlg);
- });
-});
-
-add_task(function* test_edit_multiple_logins() {
- function* testLoginChange(site, oldUsername, oldPassword, newUsername, newPassword) {
- addLogin(site, oldUsername, oldPassword);
- yield* editUsernamePromises(site, oldUsername, newUsername);
- yield* togglePasswords();
- yield* editPasswordPromises(site, oldPassword, newPassword);
- yield* togglePasswords();
- }
-
- yield* testLoginChange("http://c.tn/", "userC", "passC", "usernameC", "passwordC");
- yield* testLoginChange("http://b.tn/", "userB", "passB", "usernameB", "passwordB");
- yield* testLoginChange("http://a.tn/", "userA", "passA", "usernameA", "passwordA");
-
- pwmgrdlg.close();
-});
diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js
deleted file mode 100644
index 95bcee9ed..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
- waitForExplicitFinish();
-
- let pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
- pwmgr.removeAllLogins();
-
- // add login data
- let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- let login = new nsLoginInfo("http://example.com/", "http://example.com/", null,
- "user", "password", "u1", "p1");
- pwmgr.addLogin(login);
-
- // Open the password manager dialog
- const PWMGR_DLG = "chrome://passwordmgr/content/passwordManager.xul";
- let pwmgrdlg = window.openDialog(PWMGR_DLG, "Toolkit:PasswordManager", "");
- SimpleTest.waitForFocus(doTest, pwmgrdlg);
-
- function doTest() {
- let doc = pwmgrdlg.document;
-
- let signonsTree = doc.querySelector("#signonsTree");
- is(signonsTree.view.rowCount, 1, "One entry in the passwords list");
-
- is(signonsTree.view.getCellText(0, signonsTree.columns.getNamedColumn("siteCol")),
- "http://example.com/",
- "Correct website saved");
-
- is(signonsTree.view.getCellText(0, signonsTree.columns.getNamedColumn("userCol")),
- "user",
- "Correct user saved");
-
- let timeCreatedCol = doc.getElementById("timeCreatedCol");
- is(timeCreatedCol.getAttribute("hidden"), "true",
- "Time created column is not displayed");
-
-
- let timeLastUsedCol = doc.getElementById("timeLastUsedCol");
- is(timeLastUsedCol.getAttribute("hidden"), "true",
- "Last Used column is not displayed");
-
- let timePasswordChangedCol = doc.getElementById("timePasswordChangedCol");
- is(timePasswordChangedCol.getAttribute("hidden"), "",
- "Last Changed column is displayed");
-
- // cleanup
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- if (aSubject.location == pwmgrdlg.location && aTopic == "domwindowclosed") {
- // unregister ourself
- Services.ww.unregisterNotification(arguments.callee);
-
- pwmgr.removeAllLogins();
-
- finish();
- }
- });
-
- pwmgrdlg.close();
- }
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js
deleted file mode 100644
index 1dc7076aa..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js
+++ /dev/null
@@ -1,129 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function test() {
- waitForExplicitFinish();
-
- const LOGIN_HOST = "http://example.com";
- const LOGIN_COUNT = 5;
-
- let nsLoginInfo = new Components.Constructor(
- "@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo, "init");
- let pmDialog = window.openDialog(
- "chrome://passwordmgr/content/passwordManager.xul",
- "Toolkit:PasswordManager", "");
-
- let logins = [];
- let loginCounter = 0;
- let loginOrder = null;
- let modifiedLogin;
- let testNumber = 0;
- let testObserver = {
- observe: function (subject, topic, data) {
- if (topic == "passwordmgr-dialog-updated") {
- switch (testNumber) {
- case 1:
- case 2:
- case 3:
- case 4:
- case 5:
- is(countLogins(), loginCounter, "Verify login added");
- ok(getLoginOrder().startsWith(loginOrder), "Verify login order");
- runNextTest();
- break;
- case 6:
- is(countLogins(), loginCounter, "Verify login count");
- is(getLoginOrder(), loginOrder, "Verify login order");
- is(getLoginPassword(), "newpassword0", "Verify login modified");
- runNextTest();
- break;
- case 7:
- is(countLogins(), loginCounter, "Verify login removed");
- ok(loginOrder.endsWith(getLoginOrder()), "Verify login order");
- runNextTest();
- break;
- case 8:
- is(countLogins(), 0, "Verify all logins removed");
- runNextTest();
- break;
- }
- }
- }
- };
-
- SimpleTest.waitForFocus(startTest, pmDialog);
-
- function createLogins() {
- let login;
- for (let i = 0; i < LOGIN_COUNT; i++) {
- login = new nsLoginInfo(LOGIN_HOST + "?n=" + i, LOGIN_HOST + "?n=" + i,
- null, "user" + i, "password" + i, "u" + i, "p" + i);
- logins.push(login);
- }
- modifiedLogin = new nsLoginInfo(LOGIN_HOST + "?n=0", LOGIN_HOST + "?n=0",
- null, "user0", "newpassword0", "u0", "p0");
- is(logins.length, LOGIN_COUNT, "Verify logins created");
- }
-
- function countLogins() {
- let doc = pmDialog.document;
- let signonsTree = doc.getElementById("signonsTree");
- return signonsTree.view.rowCount;
- }
-
- function getLoginOrder() {
- let doc = pmDialog.document;
- let signonsTree = doc.getElementById("signonsTree");
- let column = signonsTree.columns[0]; // host column
- let order = [];
- for (let i = 0; i < signonsTree.view.rowCount; i++) {
- order.push(signonsTree.view.getCellText(i, column));
- }
- return order.join(',');
- }
-
- function getLoginPassword() {
- let doc = pmDialog.document;
- let loginsTree = doc.getElementById("signonsTree");
- let column = loginsTree.columns[2]; // password column
- return loginsTree.view.getCellText(0, column);
- }
-
- function startTest() {
- Services.obs.addObserver(
- testObserver, "passwordmgr-dialog-updated", false);
- is(countLogins(), 0, "Verify starts with 0 logins");
- createLogins();
- runNextTest();
- }
-
- function runNextTest() {
- switch (++testNumber) {
- case 1: // add the logins
- for (let i = 0; i < logins.length; i++) {
- loginCounter++;
- loginOrder = getLoginOrder();
- Services.logins.addLogin(logins[i]);
- }
- break;
- case 6: // modify a login
- loginOrder = getLoginOrder();
- Services.logins.modifyLogin(logins[0], modifiedLogin);
- break;
- case 7: // remove a login
- loginCounter--;
- loginOrder = getLoginOrder();
- Services.logins.removeLogin(modifiedLogin);
- break;
- case 8: // remove all logins
- Services.logins.removeAllLogins();
- break;
- case 9: // finish
- Services.obs.removeObserver(
- testObserver, "passwordmgr-dialog-updated", false);
- pmDialog.close();
- finish();
- break;
- }
- }
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js
deleted file mode 100644
index 83272a9c4..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_sort.js
+++ /dev/null
@@ -1,208 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
- waitForExplicitFinish();
-
- let pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
- pwmgr.removeAllLogins();
-
- // Add some initial logins
- let urls = [
- "http://example.com/",
- "http://example.org/",
- "http://mozilla.com/",
- "http://mozilla.org/",
- "http://spreadfirefox.com/",
- "http://planet.mozilla.org/",
- "https://developer.mozilla.org/",
- "http://hg.mozilla.org/",
- "http://dxr.mozilla.org/",
- "http://feeds.mozilla.org/",
- ];
- let users = [
- "user",
- "username",
- "ehsan",
- "ehsan",
- "john",
- "what?",
- "really?",
- "you sure?",
- "my user name",
- "my username",
- ];
- let pwds = [
- "password",
- "password",
- "mypass",
- "mypass",
- "smith",
- "very secret",
- "super secret",
- "absolutely",
- "mozilla",
- "mozilla.com",
- ];
- let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- for (let i = 0; i < 10; i++)
- pwmgr.addLogin(new nsLoginInfo(urls[i], urls[i], null, users[i], pwds[i],
- "u" + (i + 1), "p" + (i + 1)));
-
- // Open the password manager dialog
- const PWMGR_DLG = "chrome://passwordmgr/content/passwordManager.xul";
- let pwmgrdlg = window.openDialog(PWMGR_DLG, "Toolkit:PasswordManager", "");
- SimpleTest.waitForFocus(doTest, pwmgrdlg);
-
- // the meat of the test
- function doTest() {
- let doc = pwmgrdlg.document;
- let win = doc.defaultView;
- let sTree = doc.getElementById("signonsTree");
- let filter = doc.getElementById("filter");
- let siteCol = doc.getElementById("siteCol");
- let userCol = doc.getElementById("userCol");
- let passwordCol = doc.getElementById("passwordCol");
-
- let toggleCalls = 0;
- function toggleShowPasswords(func) {
- let toggleButton = doc.getElementById("togglePasswords");
- let showMode = (toggleCalls++ % 2) == 0;
-
- // only watch for a confirmation dialog every other time being called
- if (showMode) {
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- if (aTopic == "domwindowclosed")
- Services.ww.unregisterNotification(arguments.callee);
- else if (aTopic == "domwindowopened") {
- let targetWin = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
- SimpleTest.waitForFocus(function() {
- EventUtils.sendKey("RETURN", targetWin);
- }, targetWin);
- }
- });
- }
-
- Services.obs.addObserver(function (aSubject, aTopic, aData) {
- if (aTopic == "passwordmgr-password-toggle-complete") {
- Services.obs.removeObserver(arguments.callee, aTopic);
- func();
- }
- }, "passwordmgr-password-toggle-complete", false);
-
- EventUtils.synthesizeMouse(toggleButton, 1, 1, {}, win);
- }
-
- function clickCol(col) {
- EventUtils.synthesizeMouse(col, 20, 1, {}, win);
- setTimeout(runNextTest, 0);
- }
-
- function setFilter(string) {
- filter.value = string;
- filter.doCommand();
- setTimeout(runNextTest, 0);
- }
-
- function checkSortMarkers(activeCol) {
- let isOk = true;
- let col = null;
- let hasAttr = false;
- let treecols = activeCol.parentNode;
- for (let i = 0; i < treecols.childNodes.length; i++) {
- col = treecols.childNodes[i];
- if (col.nodeName != "treecol")
- continue;
- hasAttr = col.hasAttribute("sortDirection");
- isOk &= col == activeCol ? hasAttr : !hasAttr;
- }
- ok(isOk, "Only " + activeCol.id + " has a sort marker");
- }
-
- function checkSortDirection(col, ascending) {
- checkSortMarkers(col);
- let direction = ascending ? "ascending" : "descending";
- is(col.getAttribute("sortDirection"), direction,
- col.id + ": sort direction is " + direction);
- }
-
- function checkColumnEntries(aCol, expectedValues) {
- let actualValues = getColumnEntries(aCol);
- is(actualValues.length, expectedValues.length, "Checking length of expected column");
- for (let i = 0; i < expectedValues.length; i++)
- is(actualValues[i], expectedValues[i], "Checking column entry #" + i);
- }
-
- function getColumnEntries(aCol) {
- let entries = [];
- let column = sTree.columns[aCol];
- let numRows = sTree.view.rowCount;
- for (let i = 0; i < numRows; i++)
- entries.push(sTree.view.getCellText(i, column));
- return entries;
- }
-
- let testCounter = 0;
- let expectedValues;
- function runNextTest() {
- switch (testCounter++) {
- case 0:
- expectedValues = urls.slice().sort();
- checkColumnEntries(0, expectedValues);
- checkSortDirection(siteCol, true);
- // Toggle sort direction on Host column
- clickCol(siteCol);
- break;
- case 1:
- expectedValues.reverse();
- checkColumnEntries(0, expectedValues);
- checkSortDirection(siteCol, false);
- // Sort by Username
- clickCol(userCol);
- break;
- case 2:
- expectedValues = users.slice().sort();
- checkColumnEntries(1, expectedValues);
- checkSortDirection(userCol, true);
- // Sort by Password
- clickCol(passwordCol);
- break;
- case 3:
- expectedValues = pwds.slice().sort();
- checkColumnEntries(2, expectedValues);
- checkSortDirection(passwordCol, true);
- // Set filter
- setFilter("moz");
- break;
- case 4:
- expectedValues = [ "absolutely", "mozilla", "mozilla.com",
- "mypass", "mypass", "super secret",
- "very secret" ];
- checkColumnEntries(2, expectedValues);
- checkSortDirection(passwordCol, true);
- // Reset filter
- setFilter("");
- break;
- case 5:
- expectedValues = pwds.slice().sort();
- checkColumnEntries(2, expectedValues);
- checkSortDirection(passwordCol, true);
- // cleanup
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- // unregister ourself
- Services.ww.unregisterNotification(arguments.callee);
-
- pwmgr.removeAllLogins();
- finish();
- });
- pwmgrdlg.close();
- }
- }
-
- // Toggle Show Passwords to display Password column, then start tests
- toggleShowPasswords(runNextTest);
- }
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js
deleted file mode 100644
index bd4f265b5..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const PROMPT_URL = "chrome://global/content/commonDialog.xul";
-var { interfaces: Ci } = Components;
-
-function test() {
- waitForExplicitFinish();
-
- let tab = gBrowser.addTab();
- isnot(tab, gBrowser.selectedTab, "New tab shouldn't be selected");
-
- let listener = {
- onOpenWindow: function(window) {
- var domwindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- waitForFocus(() => {
- is(domwindow.document.location.href, PROMPT_URL, "Should have seen a prompt window");
- is(domwindow.args.promptType, "promptUserAndPass", "Should be an authenticate prompt");
-
- is(gBrowser.selectedTab, tab, "Should have selected the new tab");
-
- domwindow.document.documentElement.cancelDialog();
- }, domwindow);
- },
-
- onCloseWindow: function() {
- }
- };
-
- Services.wm.addListener(listener);
- registerCleanupFunction(() => {
- Services.wm.removeListener(listener);
- gBrowser.removeTab(tab);
- });
-
- tab.linkedBrowser.addEventListener("load", () => {
- finish();
- }, true);
- tab.linkedBrowser.loadURI("http://example.com/browser/toolkit/components/passwordmgr/test/browser/authenticate.sjs");
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js b/toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js
deleted file mode 100644
index 57cfa9f83..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgrdlg.js
+++ /dev/null
@@ -1,192 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
- waitForExplicitFinish();
-
- let pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
- pwmgr.removeAllLogins();
-
- // Add some initial logins
- let urls = [
- "http://example.com/",
- "http://example.org/",
- "http://mozilla.com/",
- "http://mozilla.org/",
- "http://spreadfirefox.com/",
- "http://planet.mozilla.org/",
- "https://developer.mozilla.org/",
- "http://hg.mozilla.org/",
- "http://dxr.mozilla.org/",
- "http://feeds.mozilla.org/",
- ];
- let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- let logins = [
- new nsLoginInfo(urls[0], urls[0], null, "user", "password", "u1", "p1"),
- new nsLoginInfo(urls[1], urls[1], null, "username", "password", "u2", "p2"),
- new nsLoginInfo(urls[2], urls[2], null, "ehsan", "mypass", "u3", "p3"),
- new nsLoginInfo(urls[3], urls[3], null, "ehsan", "mypass", "u4", "p4"),
- new nsLoginInfo(urls[4], urls[4], null, "john", "smith", "u5", "p5"),
- new nsLoginInfo(urls[5], urls[5], null, "what?", "very secret", "u6", "p6"),
- new nsLoginInfo(urls[6], urls[6], null, "really?", "super secret", "u7", "p7"),
- new nsLoginInfo(urls[7], urls[7], null, "you sure?", "absolutely", "u8", "p8"),
- new nsLoginInfo(urls[8], urls[8], null, "my user name", "mozilla", "u9", "p9"),
- new nsLoginInfo(urls[9], urls[9], null, "my username", "mozilla.com", "u10", "p10"),
- ];
- logins.forEach(login => pwmgr.addLogin(login));
-
- // Open the password manager dialog
- const PWMGR_DLG = "chrome://passwordmgr/content/passwordManager.xul";
- let pwmgrdlg = window.openDialog(PWMGR_DLG, "Toolkit:PasswordManager", "");
- SimpleTest.waitForFocus(doTest, pwmgrdlg);
-
- // the meat of the test
- function doTest() {
- let doc = pwmgrdlg.document;
- let win = doc.defaultView;
- let filter = doc.getElementById("filter");
- let tree = doc.getElementById("signonsTree");
- let view = tree.view;
-
- is(filter.value, "", "Filter box should initially be empty");
- is(view.rowCount, 10, "There should be 10 passwords initially");
-
- // Prepare a set of tests
- // filter: the text entered in the filter search box
- // count: the number of logins which should match the respective filter
- // count2: the number of logins which should match the respective filter
- // if the passwords are being shown as well
- // Note: if a test doesn't have count2 set, count is used instead.
- let tests = [
- {filter: "pass", count: 0, count2: 4},
- {filter: "", count: 10}, // test clearing the filter
- {filter: "moz", count: 7},
- {filter: "mozi", count: 7},
- {filter: "mozil", count: 7},
- {filter: "mozill", count: 7},
- {filter: "mozilla", count: 7},
- {filter: "mozilla.com", count: 1, count2: 2},
- {filter: "user", count: 4},
- {filter: "user ", count: 1},
- {filter: " user", count: 2},
- {filter: "http", count: 10},
- {filter: "https", count: 1},
- {filter: "secret", count: 0, count2: 2},
- {filter: "secret!", count: 0},
- ];
-
- let toggleCalls = 0;
- function toggleShowPasswords(func) {
- let toggleButton = doc.getElementById("togglePasswords");
- let showMode = (toggleCalls++ % 2) == 0;
-
- // only watch for a confirmation dialog every other time being called
- if (showMode) {
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- if (aTopic == "domwindowclosed")
- Services.ww.unregisterNotification(arguments.callee);
- else if (aTopic == "domwindowopened") {
- let targetWin = aSubject.QueryInterface(Ci.nsIDOMEventTarget);
- SimpleTest.waitForFocus(function() {
- EventUtils.sendKey("RETURN", targetWin);
- }, targetWin);
- }
- });
- }
-
- Services.obs.addObserver(function (aSubject, aTopic, aData) {
- if (aTopic == "passwordmgr-password-toggle-complete") {
- Services.obs.removeObserver(arguments.callee, aTopic);
- func();
- }
- }, "passwordmgr-password-toggle-complete", false);
-
- EventUtils.synthesizeMouse(toggleButton, 1, 1, {}, win);
- }
-
- function runTests(mode, endFunction) {
- let testCounter = 0;
-
- function setFilter(string) {
- filter.value = string;
- filter.doCommand();
- }
-
- function runOneTest(testCase) {
- function tester() {
- is(view.rowCount, expected, expected + " logins should match '" + testCase.filter + "'");
- }
-
- let expected;
- switch (mode) {
- case 1: // without showing passwords
- expected = testCase.count;
- break;
- case 2: // showing passwords
- expected = ("count2" in testCase) ? testCase.count2 : testCase.count;
- break;
- case 3: // toggle
- expected = testCase.count;
- tester();
- toggleShowPasswords(function () {
- expected = ("count2" in testCase) ? testCase.count2 : testCase.count;
- tester();
- toggleShowPasswords(proceed);
- });
- return;
- }
- tester();
- proceed();
- }
-
- function proceed() {
- // run the next test if necessary or proceed with the tests
- if (testCounter != tests.length)
- runNextTest();
- else
- endFunction();
- }
-
- function runNextTest() {
- let testCase = tests[testCounter++];
- setFilter(testCase.filter);
- setTimeout(runOneTest, 0, testCase);
- }
-
- runNextTest();
- }
-
- function step1() {
- runTests(1, step2);
- }
-
- function step2() {
- toggleShowPasswords(function() {
- runTests(2, step3);
- });
- }
-
- function step3() {
- toggleShowPasswords(function() {
- runTests(3, lastStep);
- });
- }
-
- function lastStep() {
- // cleanup
- Services.ww.registerNotification(function (aSubject, aTopic, aData) {
- // unregister ourself
- Services.ww.unregisterNotification(arguments.callee);
-
- pwmgr.removeAllLogins();
- finish();
- });
- pwmgrdlg.close();
- }
-
- step1();
- }
-}
diff --git a/toolkit/components/passwordmgr/test/browser/browser_username_select_dialog.js b/toolkit/components/passwordmgr/test/browser/browser_username_select_dialog.js
deleted file mode 100644
index 8df89b510..000000000
--- a/toolkit/components/passwordmgr/test/browser/browser_username_select_dialog.js
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Test username selection dialog, on password update from a p-only form,
- * when there are multiple saved logins on the domain.
- */
-
-// Copied from prompt_common.js. TODO: share the code.
-function getSelectDialogDoc() {
- // Trudge through all the open windows, until we find the one
- // that has selectDialog.xul loaded.
- var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
- getService(Ci.nsIWindowMediator);
- // var enumerator = wm.getEnumerator("navigator:browser");
- var enumerator = wm.getXULWindowEnumerator(null);
-
- while (enumerator.hasMoreElements()) {
- var win = enumerator.getNext();
- var windowDocShell = win.QueryInterface(Ci.nsIXULWindow).docShell;
-
- var containedDocShells = windowDocShell.getDocShellEnumerator(
- Ci.nsIDocShellTreeItem.typeChrome,
- Ci.nsIDocShell.ENUMERATE_FORWARDS);
- while (containedDocShells.hasMoreElements()) {
- // Get the corresponding document for this docshell
- var childDocShell = containedDocShells.getNext();
- // We don't want it if it's not done loading.
- if (childDocShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE)
- continue;
- var childDoc = childDocShell.QueryInterface(Ci.nsIDocShell)
- .contentViewer
- .DOMDocument;
-
- if (childDoc.location.href == "chrome://global/content/selectDialog.xul")
- return childDoc;
- }
- }
-
- return null;
-}
-
-let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-let login1 = new nsLoginInfo("http://example.com", "http://example.com", null,
- "notifyu1", "notifyp1", "user", "pass");
-let login1B = new nsLoginInfo("http://example.com", "http://example.com", null,
- "notifyu1B", "notifyp1B", "user", "pass");
-
-add_task(function* test_changeUPLoginOnPUpdateForm_accept() {
- info("Select an u+p login from multiple logins, on password update form, and accept.");
- Services.logins.addLogin(login1);
- Services.logins.addLogin(login1B);
-
- yield testSubmittingLoginForm("subtst_notifications_change_p.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "pass2", "Checking submitted password");
-
- yield ContentTaskUtils.waitForCondition(() => {
- return getSelectDialogDoc();
- }, "Wait for selection dialog to be accessible.");
-
- let doc = getSelectDialogDoc();
- let dialog = doc.getElementsByTagName("dialog")[0];
- let listbox = doc.getElementById("list");
-
- is(listbox.selectedIndex, 0, "Checking selected index");
- is(listbox.itemCount, 2, "Checking selected length");
- ['notifyu1', 'notifyu1B'].forEach((username, i) => {
- is(listbox.getItemAtIndex(i).label, username, "Check username selection on dialog");
- });
-
- dialog.acceptDialog();
-
- yield ContentTaskUtils.waitForCondition(() => {
- return !getSelectDialogDoc();
- }, "Wait for selection dialog to disappear.");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 2, "Should have 2 logins");
-
- let login = SpecialPowers.wrap(logins[0]).QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username unchanged");
- is(login.password, "pass2", "Check the password changed");
- is(login.timesUsed, 2, "Check times used");
-
- login = SpecialPowers.wrap(logins[1]).QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1B", "Check the username unchanged");
- is(login.password, "notifyp1B", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-
- // cleanup
- login1.password = "pass2";
- Services.logins.removeLogin(login1);
- login1.password = "notifyp1";
-
- Services.logins.removeLogin(login1B);
-});
-
-add_task(function* test_changeUPLoginOnPUpdateForm_cancel() {
- info("Select an u+p login from multiple logins, on password update form, and cancel.");
- Services.logins.addLogin(login1);
- Services.logins.addLogin(login1B);
-
- yield testSubmittingLoginForm("subtst_notifications_change_p.html", function*(fieldValues) {
- is(fieldValues.username, "null", "Checking submitted username");
- is(fieldValues.password, "pass2", "Checking submitted password");
-
- yield ContentTaskUtils.waitForCondition(() => {
- return getSelectDialogDoc();
- }, "Wait for selection dialog to be accessible.");
-
- let doc = getSelectDialogDoc();
- let dialog = doc.getElementsByTagName("dialog")[0];
- let listbox = doc.getElementById("list");
-
- is(listbox.selectedIndex, 0, "Checking selected index");
- is(listbox.itemCount, 2, "Checking selected length");
- ['notifyu1', 'notifyu1B'].forEach((username, i) => {
- is(listbox.getItemAtIndex(i).label, username, "Check username selection on dialog");
- });
-
- dialog.cancelDialog();
-
- yield ContentTaskUtils.waitForCondition(() => {
- return !getSelectDialogDoc();
- }, "Wait for selection dialog to disappear.");
- });
-
- let logins = Services.logins.getAllLogins();
- is(logins.length, 2, "Should have 2 logins");
-
- let login = SpecialPowers.wrap(logins[0]).QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1", "Check the username unchanged");
- is(login.password, "notifyp1", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-
- login = SpecialPowers.wrap(logins[1]).QueryInterface(Ci.nsILoginMetaInfo);
- is(login.username, "notifyu1B", "Check the username unchanged");
- is(login.password, "notifyp1B", "Check the password unchanged");
- is(login.timesUsed, 1, "Check times used");
-
- // cleanup
- Services.logins.removeLogin(login1);
- Services.logins.removeLogin(login1B);
-});
diff --git a/toolkit/components/passwordmgr/test/browser/form_autofocus_js.html b/toolkit/components/passwordmgr/test/browser/form_autofocus_js.html
deleted file mode 100644
index 76056e375..000000000
--- a/toolkit/components/passwordmgr/test/browser/form_autofocus_js.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head>
-<body onload="document.getElementById('form-basic-username').focus();">
-<!-- Username field is focused by js onload -->
-<form id="form-basic">
- <input id="form-basic-username" name="username">
- <input id="form-basic-password" name="password" type="password">
- <input id="form-basic-submit" type="submit">
-</form>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/form_basic.html b/toolkit/components/passwordmgr/test/browser/form_basic.html
deleted file mode 100644
index df2083a93..000000000
--- a/toolkit/components/passwordmgr/test/browser/form_basic.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<!-- Simplest form with username and password fields. -->
-<form id="form-basic">
- <input id="form-basic-username" name="username">
- <input id="form-basic-password" name="password" type="password">
- <input id="form-basic-submit" type="submit">
-</form>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/form_basic_iframe.html b/toolkit/components/passwordmgr/test/browser/form_basic_iframe.html
deleted file mode 100644
index 616f56947..000000000
--- a/toolkit/components/passwordmgr/test/browser/form_basic_iframe.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE html>
-<html>
-
-<head>
- <meta charset="utf-8">
-</head>
-
-<body>
- <!-- Form in an iframe -->
- <iframe src="https://example.org/browser/toolkit/components/passwordmgr/test/browser/form_basic.html" id="test-iframe"></iframe>
-</body>
-
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/form_cross_origin_insecure_action.html b/toolkit/components/passwordmgr/test/browser/form_cross_origin_insecure_action.html
deleted file mode 100644
index e8aa8b215..000000000
--- a/toolkit/components/passwordmgr/test/browser/form_cross_origin_insecure_action.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<!-- Simplest form with username and password fields. -->
-<form id="form-basic" action="http://another.domain/custom_action.html">
- <input id="form-basic-username" name="username">
- <input id="form-basic-password" name="password" type="password">
- <input id="form-basic-submit" type="submit">
-</form>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/form_cross_origin_secure_action.html b/toolkit/components/passwordmgr/test/browser/form_cross_origin_secure_action.html
deleted file mode 100644
index 892a9f6f6..000000000
--- a/toolkit/components/passwordmgr/test/browser/form_cross_origin_secure_action.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<!-- Simplest form with username and password fields. -->
-<form id="form-basic" action="https://another.domain/custom_action.html">
- <input id="form-basic-username" name="username">
- <input id="form-basic-password" name="password" type="password">
- <input id="form-basic-submit" type="submit">
-</form>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/form_same_origin_action.html b/toolkit/components/passwordmgr/test/browser/form_same_origin_action.html
deleted file mode 100644
index 8f0c9a14e..000000000
--- a/toolkit/components/passwordmgr/test/browser/form_same_origin_action.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<!-- Simplest form with username and password fields. -->
-<form id="form-basic" action="./custom_action.html">
- <input id="form-basic-username" name="username">
- <input id="form-basic-password" name="password" type="password">
- <input id="form-basic-submit" type="submit">
-</form>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/formless_basic.html b/toolkit/components/passwordmgr/test/browser/formless_basic.html
deleted file mode 100644
index 2f4c5de52..000000000
--- a/toolkit/components/passwordmgr/test/browser/formless_basic.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-
-<!-- Simplest form with username and password fields. -->
- <input id="form-basic-username" name="username">
- <input id="form-basic-password" name="password" type="password">
- <input id="form-basic-submit" type="submit">
-
- <button id="add">Add input[type=password]</button>
-
- <script>
- document.getElementById("add").addEventListener("click", function () {
- var node = document.createElement("input");
- node.setAttribute("type", "password");
- document.querySelector("body").appendChild(node);
- });
- </script>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/head.js b/toolkit/components/passwordmgr/test/browser/head.js
deleted file mode 100644
index 926cb6616..000000000
--- a/toolkit/components/passwordmgr/test/browser/head.js
+++ /dev/null
@@ -1,137 +0,0 @@
-const DIRECTORY_PATH = "/browser/toolkit/components/passwordmgr/test/browser/";
-
-Cu.import("resource://testing-common/LoginTestUtils.jsm", this);
-Cu.import("resource://testing-common/ContentTaskUtils.jsm", this);
-
-registerCleanupFunction(function* cleanup_removeAllLoginsAndResetRecipes() {
- Services.logins.removeAllLogins();
-
- let recipeParent = LoginTestUtils.recipes.getRecipeParent();
- if (!recipeParent) {
- // No need to reset the recipes if the recipe module wasn't even loaded.
- return;
- }
- yield recipeParent.then(recipeParentResult => recipeParentResult.reset());
-});
-
-/**
- * Loads a test page in `DIRECTORY_URL` which automatically submits to formsubmit.sjs and returns a
- * promise resolving with the field values when the optional `aTaskFn` is done.
- *
- * @param {String} aPageFile - test page file name which auto-submits to formsubmit.sjs
- * @param {Function} aTaskFn - task which can be run before the tab closes.
- * @param {String} [aOrigin="http://example.com"] - origin of the server to use
- * to load `aPageFile`.
- */
-function testSubmittingLoginForm(aPageFile, aTaskFn, aOrigin = "http://example.com") {
- return BrowserTestUtils.withNewTab({
- gBrowser,
- url: aOrigin + DIRECTORY_PATH + aPageFile,
- }, function*(browser) {
- ok(true, "loaded " + aPageFile);
- let fieldValues = yield ContentTask.spawn(browser, undefined, function*() {
- yield ContentTaskUtils.waitForCondition(() => {
- return content.location.pathname.endsWith("/formsubmit.sjs") &&
- content.document.readyState == "complete";
- }, "Wait for form submission load (formsubmit.sjs)");
- let username = content.document.getElementById("user").textContent;
- let password = content.document.getElementById("pass").textContent;
- return {
- username,
- password,
- };
- });
- ok(true, "form submission loaded");
- if (aTaskFn) {
- yield* aTaskFn(fieldValues);
- }
- return fieldValues;
- });
-}
-
-function checkOnlyLoginWasUsedTwice({ justChanged }) {
- // Check to make sure we updated the timestamps and use count on the
- // existing login that was submitted for the test.
- let logins = Services.logins.getAllLogins();
- is(logins.length, 1, "Should only have 1 login");
- ok(logins[0] instanceof Ci.nsILoginMetaInfo, "metainfo QI");
- is(logins[0].timesUsed, 2, "check .timesUsed for existing login submission");
- ok(logins[0].timeCreated < logins[0].timeLastUsed, "timeLastUsed bumped");
- if (justChanged) {
- is(logins[0].timeLastUsed, logins[0].timePasswordChanged, "timeLastUsed == timePasswordChanged");
- } else {
- is(logins[0].timeCreated, logins[0].timePasswordChanged, "timeChanged not updated");
- }
-}
-
-// Begin popup notification (doorhanger) functions //
-
-const REMEMBER_BUTTON = 0;
-const NEVER_BUTTON = 1;
-
-const CHANGE_BUTTON = 0;
-const DONT_CHANGE_BUTTON = 1;
-
-/**
- * Checks if we have a password capture popup notification
- * of the right type and with the right label.
- *
- * @param {String} aKind The desired `passwordNotificationType`
- * @param {Object} [popupNotifications = PopupNotifications]
- * @return the found password popup notification.
- */
-function getCaptureDoorhanger(aKind, popupNotifications = PopupNotifications) {
- ok(true, "Looking for " + aKind + " popup notification");
- let notification = popupNotifications.getNotification("password");
- if (notification) {
- is(notification.options.passwordNotificationType, aKind, "Notification type matches.");
- if (aKind == "password-change") {
- is(notification.mainAction.label, "Update", "Main action label matches update doorhanger.");
- } else if (aKind == "password-save") {
- is(notification.mainAction.label, "Remember", "Main action label matches save doorhanger.");
- }
- }
- return notification;
-}
-
-/**
- * Clicks the specified popup notification button.
- *
- * @param {Element} aPopup Popup Notification element
- * @param {Number} aButtonIndex Number indicating which button to click.
- * See the constants in this file.
- */
-function clickDoorhangerButton(aPopup, aButtonIndex) {
- ok(true, "Looking for action at index " + aButtonIndex);
-
- let notifications = aPopup.owner.panel.childNodes;
- ok(notifications.length > 0, "at least one notification displayed");
- ok(true, notifications.length + " notification(s)");
- let notification = notifications[0];
-
- if (aButtonIndex == 0) {
- ok(true, "Triggering main action");
- notification.button.doCommand();
- } else if (aButtonIndex <= aPopup.secondaryActions.length) {
- ok(true, "Triggering secondary action " + aButtonIndex);
- notification.childNodes[aButtonIndex].doCommand();
- }
-}
-
-/**
- * Checks the doorhanger's username and password.
- *
- * @param {String} username The username.
- * @param {String} password The password.
- */
-function* checkDoorhangerUsernamePassword(username, password) {
- yield BrowserTestUtils.waitForCondition(() => {
- return document.getElementById("password-notification-username").value == username;
- }, "Wait for nsLoginManagerPrompter writeDataToUI()");
- is(document.getElementById("password-notification-username").value, username,
- "Check doorhanger username");
- is(document.getElementById("password-notification-password").value, password,
- "Check doorhanger password");
-}
-
-// End popup notification (doorhanger) functions //
diff --git a/toolkit/components/passwordmgr/test/browser/insecure_test.html b/toolkit/components/passwordmgr/test/browser/insecure_test.html
deleted file mode 100644
index fedea1428..000000000
--- a/toolkit/components/passwordmgr/test/browser/insecure_test.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<!-- This frame is initially loaded over HTTP. -->
-<iframe id="test-iframe"
- src="http://example.org/browser/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html"/>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html b/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html
deleted file mode 100644
index 3f01e36a6..000000000
--- a/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<form>
- <input name="password" type="password">
-</form>
-
-<!-- Link to reload this page over HTTPS. -->
-<a id="test-link"
- href="https://example.org/browser/toolkit/components/passwordmgr/test/browser/insecure_test_subframe.html">HTTPS</a>
-
-</body></html>
diff --git a/toolkit/components/passwordmgr/test/browser/multiple_forms.html b/toolkit/components/passwordmgr/test/browser/multiple_forms.html
deleted file mode 100644
index 3f64f8993..000000000
--- a/toolkit/components/passwordmgr/test/browser/multiple_forms.html
+++ /dev/null
@@ -1,129 +0,0 @@
-<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-
-<form class="test-form"
- description="Password only form">
- <input id='test-password-1' type='password' name='pname' value=''>
- <input type='submit'>Submit</input>
-</form>
-
-
-<form class="test-form"
- description="Username only form">
- <input id='test-username-1' type='text' name='uname' value=''>
- <input type='submit'>Submit</input>
-</form>
-
-
-<form class="test-form"
- description="Simple username and password blank form">
- <input id='test-username-2' type='text' name='uname' value=''>
- <input id='test-password-2' type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="Simple username and password form, prefilled username">
- <input id='test-username-3' type='text' name='uname' value='testuser'>
- <input id='test-password-3' type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="Simple username and password form, prefilled username and password">
- <input id='test-username-4' type='text' name='uname' value='testuser'>
- <input id='test-password-4' type='password' name='pname' value='testpass'>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="One username and two passwords empty form">
- <input id='test-username-5' type='text' name='uname'>
- <input id='test-password-5' type='password' name='pname'>
- <input id='test-password2-5' type='password' name='pname2'>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="One username and two passwords form, fields prefiled">
- <input id='test-username-6' type='text' name='uname' value="testuser">
- <input id='test-password-6' type='password' name='pname' value="testpass">
- <input id='test-password2-6' type='password' name='pname2' value="testpass">
- <button type='submit'>Submit</button>
-</form>
-
-
-<div class="test-form"
- description="Username and password fields with no form">
- <input id='test-username-7' type='text' name='uname' value="testuser">
- <input id='test-password-7' type='password' name='pname' value="testpass">
-</div>
-
-
-<form class="test-form"
- description="Simple username and password blank form, with disabled password">
- <input id='test-username-8' type='text' name='uname' value=''>
- <input id='test-password-8' type='password' name='pname' value='' disabled>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="Simple username and password blank form, with disabled username">
- <input id='test-username-9' type='text' name='uname' value='' disabled>
- <input id='test-password-9' type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="Simple username and password blank form, with readonly password">
- <input id='test-username-10' type='text' name='uname' value=''>
- <input id='test-password-10' type='password' name='pname' value='' readonly>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="Simple username and password blank form, with readonly username">
- <input id='test-username-11' type='text' name='uname' value='' readonly>
- <input id='test-password-11' type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="Two username and one passwords form, fields prefiled">
- <input id='test-username-12' type='text' name='uname' value="testuser">
- <input id='test-username2-12' type='text' name='uname2' value="testuser">
- <input id='test-password-12' type='password' name='pname' value="testpass">
- <button type='submit'>Submit</button>
-</form>
-
-
-<form class="test-form"
- description="Two username and one passwords form, one disabled username field">
- <input id='test-username-13' type='text' name='uname'>
- <input id='test-username2-13' type='text' name='uname2' disabled>
- <input id='test-password-13' type='password' name='pname'>
- <button type='submit'>Submit</button>
-</form>
-
-
-<div class="test-form"
- description="Second username and password fields with no form">
- <input id='test-username-14' type='text' name='uname'>
- <input id='test-password-14' type='password' name='pname' expectedFail>
-</div>
-
-<!-- Form in an iframe -->
-<iframe src="https://example.org/browser/toolkit/components/passwordmgr/test/browser/form_basic.html" id="test-iframe"></iframe>
-
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/streamConverter_content.sjs b/toolkit/components/passwordmgr/test/browser/streamConverter_content.sjs
deleted file mode 100644
index 84c75437e..000000000
--- a/toolkit/components/passwordmgr/test/browser/streamConverter_content.sjs
+++ /dev/null
@@ -1,6 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function handleRequest(request, response) {
- response.setHeader("Content-Type", "test/content", false);
-}
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_1.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_1.html
deleted file mode 100644
index b96faf2ee..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_1.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications - Basic 1un 1pw</title>
-</head>
-<body>
-<h2>Subtest 1</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_10.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_10.html
deleted file mode 100644
index 2dc96b4fd..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_10.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications</title>
-</head>
-<body>
-<h2>Subtest 10</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_11.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_11.html
deleted file mode 100644
index cf3df5275..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_11.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications - Popup Windows</title>
-</head>
-<body>
-<h2>Subtest 11 (popup windows)</h2>
-<script>
-
-// Ignore the '?' and split on |
-[username, password, features, autoClose] = window.location.search.substring(1).split('|');
-
-var url = "subtst_notifications_11_popup.html?" + username + "|" + password;
-var popupWin = window.open(url, "subtst_11", features);
-
-// Popup window will call this function on form submission.
-function formSubmitted() {
- if (autoClose)
- popupWin.close();
-}
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_11_popup.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_11_popup.html
deleted file mode 100644
index 2e8e4135c..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_11_popup.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications</title>
-</head>
-<body>
-<h2>Subtest 11</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- // Get the password from the query string (exclude '?').
- [username, password] = window.location.search.substring(1).split('|');
- userField.value = username;
- passField.value = password;
- form.submit();
- window.opener.formSubmitted();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_2.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_2.html
deleted file mode 100644
index 72651d6c1..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_2.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications - autocomplete=off on the username field</title>
-</head>
-<body>
-<h2>Subtest 2</h2>
-(username autocomplete=off)
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user" autocomplete="off">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_0un.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_0un.html
deleted file mode 100644
index 7ddbf0851..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_0un.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications with 2 password fields and no username</title>
-</head>
-<body>
-<h2>Subtest 24</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="pass1" name="pass1" type="password" value="staticpw">
- <input id="pass" name="pass" type="password">
- <button type="submit">Submit</button>
-</form>
-
-<script>
-function submitForm() {
- pass.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var pass = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_1un_1text.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_1un_1text.html
deleted file mode 100644
index 893f18724..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_2pw_1un_1text.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications with 2 password fields and 1 username field and one other text field before the first password field</title>
-</head>
-<body>
-<h2>1 username field followed by a text field followed by 2 username fields</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user" value="staticpw">
- <input id="city" name="city" value="city">
- <input id="pass" name="pass" type="password">
- <input id="pin" name="pin" type="password" value="static-pin">
- <button type="submit">Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_3.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_3.html
deleted file mode 100644
index 291e735d0..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_3.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications - autocomplete=off on the password field</title>
-</head>
-<body>
-<h2>Subtest 3</h2>
-(password autocomplete=off)
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user">
- <input id="pass" name="pass" type="password" autocomplete="off">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_4.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_4.html
deleted file mode 100644
index 63df3a42d..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_4.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8" >
- <title>Subtest for Login Manager notifications</title>
-</head>
-<body>
-<h2>Subtest 4</h2>
-(form autocomplete=off)
-<form id="form" action="formsubmit.sjs" autocomplete="off">
- <input id="user" name="user">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_5.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_5.html
deleted file mode 100644
index 72a3df95f..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_5.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications - Form with only a username field</title>
-</head>
-<body>
-<h2>Subtest 5</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_6.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_6.html
deleted file mode 100644
index 47e23e972..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_6.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications</title>
-</head>
-<body>
-<h2>Subtest 6</h2>
-(password-only form)
-<form id="form" action="formsubmit.sjs">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_8.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_8.html
deleted file mode 100644
index abeea4262..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_8.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications</title>
-</head>
-<body>
-<h2>Subtest 8</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- passField.value = "pass2";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_9.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_9.html
deleted file mode 100644
index c6f741068..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_9.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications</title>
-</head>
-<body>
-<h2>Subtest 9</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "";
- passField.value = "pass2";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/browser/subtst_notifications_change_p.html b/toolkit/components/passwordmgr/test/browser/subtst_notifications_change_p.html
deleted file mode 100644
index d74f3bcdf..000000000
--- a/toolkit/components/passwordmgr/test/browser/subtst_notifications_change_p.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications</title>
-</head>
-<body>
-<h2>Change password</h2>
-<form id="form" action="formsubmit.sjs">
- <input id="pass_current" name="pass_current" type="password" value="notifyp1">
- <input id="pass" name="pass" type="password">
- <input id="pass_confirm" name="pass_confirm" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- passField.value = "pass2";
- passConfirmField.value = "pass2";
-
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-var passConfirmField = document.getElementById("pass_confirm");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/chrome/chrome.ini b/toolkit/components/passwordmgr/test/chrome/chrome.ini
deleted file mode 100644
index 093b87b7d..000000000
--- a/toolkit/components/passwordmgr/test/chrome/chrome.ini
+++ /dev/null
@@ -1,13 +0,0 @@
-[DEFAULT]
-skip-if = os == 'android'
-
-[test_privbrowsing_perwindowpb.html]
-skip-if = true # Bug 1173337
-support-files =
- ../formsubmit.sjs
- notification_common.js
- privbrowsing_perwindowpb_iframe.html
- subtst_privbrowsing_1.html
- subtst_privbrowsing_2.html
- subtst_privbrowsing_3.html
- subtst_privbrowsing_4.html
diff --git a/toolkit/components/passwordmgr/test/chrome/notification_common.js b/toolkit/components/passwordmgr/test/chrome/notification_common.js
deleted file mode 100644
index e8a52929d..000000000
--- a/toolkit/components/passwordmgr/test/chrome/notification_common.js
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Initialization: for each test, remove any prior notifications.
- */
-function cleanUpPopupNotifications() {
- var container = getPopupNotifications(window.top);
- var notes = container._currentNotifications;
- info(true, "Removing " + notes.length + " popup notifications.");
- for (var i = notes.length - 1; i >= 0; i--) {
- notes[i].remove();
- }
-}
-cleanUpPopupNotifications();
-
-/*
- * getPopupNotifications
- *
- * Fetches the popup notification for the specified window.
- */
-function getPopupNotifications(aWindow) {
- var Ci = SpecialPowers.Ci;
- var Cc = SpecialPowers.Cc;
- ok(Ci != null, "Access Ci");
- ok(Cc != null, "Access Cc");
-
- var chromeWin = SpecialPowers.wrap(aWindow)
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShell)
- .chromeEventHandler.ownerDocument.defaultView;
-
- var popupNotifications = chromeWin.PopupNotifications;
- return popupNotifications;
-}
-
-
-/**
- * Checks if we have a password popup notification
- * of the right type and with the right label.
- *
- * @deprecated Write a browser-chrome test instead and use the fork of this method there.
- * @returns the found password popup notification.
- */
-function getPopup(aPopupNote, aKind) {
- ok(true, "Looking for " + aKind + " popup notification");
- var notification = aPopupNote.getNotification("password");
- if (notification) {
- is(notification.options.passwordNotificationType, aKind, "Notification type matches.");
- if (aKind == "password-change") {
- is(notification.mainAction.label, "Update", "Main action label matches update doorhanger.");
- } else if (aKind == "password-save") {
- is(notification.mainAction.label, "Remember", "Main action label matches save doorhanger.");
- }
- }
- return notification;
-}
-
-
-/**
- * @deprecated - Use a browser chrome test instead.
- *
- * Clicks the specified popup notification button.
- */
-function clickPopupButton(aPopup, aButtonIndex) {
- ok(true, "Looking for action at index " + aButtonIndex);
-
- var notifications = SpecialPowers.wrap(aPopup.owner).panel.childNodes;
- ok(notifications.length > 0, "at least one notification displayed");
- ok(true, notifications.length + " notifications");
- var notification = notifications[0];
-
- if (aButtonIndex == 0) {
- ok(true, "Triggering main action");
- notification.button.doCommand();
- } else if (aButtonIndex <= aPopup.secondaryActions.length) {
- var index = aButtonIndex;
- ok(true, "Triggering secondary action " + index);
- notification.childNodes[index].doCommand();
- }
-}
-
-const kRememberButton = 0;
-const kNeverButton = 1;
-
-const kChangeButton = 0;
-const kDontChangeButton = 1;
-
-function dumpNotifications() {
- try {
- // PopupNotifications
- var container = getPopupNotifications(window.top);
- ok(true, "is popup panel open? " + container.isPanelOpen);
- var notes = container._currentNotifications;
- ok(true, "Found " + notes.length + " popup notifications.");
- for (let i = 0; i < notes.length; i++) {
- ok(true, "#" + i + ": " + notes[i].id);
- }
-
- // Notification bars
- var chromeWin = SpecialPowers.wrap(window.top)
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShell)
- .chromeEventHandler.ownerDocument.defaultView;
- var nb = chromeWin.getNotificationBox(window.top);
- notes = nb.allNotifications;
- ok(true, "Found " + notes.length + " notification bars.");
- for (let i = 0; i < notes.length; i++) {
- ok(true, "#" + i + ": " + notes[i].getAttribute("value"));
- }
- } catch (e) { todo(false, "WOAH! " + e); }
-}
diff --git a/toolkit/components/passwordmgr/test/chrome/privbrowsing_perwindowpb_iframe.html b/toolkit/components/passwordmgr/test/chrome/privbrowsing_perwindowpb_iframe.html
deleted file mode 100644
index 2efdab265..000000000
--- a/toolkit/components/passwordmgr/test/chrome/privbrowsing_perwindowpb_iframe.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
-</head>
-<body>
-<iframe id="iframe"></iframe>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_1.html b/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_1.html
deleted file mode 100644
index 8c7202dd0..000000000
--- a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_1.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications (private browsing)</title>
-</head>
-<body>
-<h2>Subtest 1</h2>
-<!--
- Make sure that the password-save notification appears outside of
- the private mode, but not inside it.
--->
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user" type="text">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- userField.value = "notifyu1";
- passField.value = "notifyp1";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-var passField = document.getElementById("pass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_2.html b/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_2.html
deleted file mode 100644
index bf3b85159..000000000
--- a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_2.html
+++ /dev/null
@@ -1,33 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications (private browsing)</title>
-</head>
-<body>
-<h2>Subtest 2</h2>
-<!--
- Make sure that the password-change notification appears outside of
- the private mode, but not inside it.
--->
-<form id="form" action="formsubmit.sjs">
- <input id="pass" name="pass" type="password">
- <input id="newpass" name="newpass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- passField.value = "notifyp1";
- passField2.value = "notifyp2";
- form.submit();
-}
-
-window.onload = submitForm;
-var form = document.getElementById("form");
-var passField = document.getElementById("pass");
-var passField2 = document.getElementById("newpass");
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_3.html b/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_3.html
deleted file mode 100644
index e88a302e0..000000000
--- a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_3.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications (private browsing)</title>
-</head>
-<body>
-<h2>Subtest 3</h2>
-<!--
- Make sure that the user/pass fields are auto-filled outside of
- the private mode, but not inside it.
--->
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user" type="text">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function submitForm() {
- form.submit();
-}
-
-var form = document.getElementById("form");
-window.addEventListener('message', () => { submitForm(); });
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_4.html b/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_4.html
deleted file mode 100644
index 184142743..000000000
--- a/toolkit/components/passwordmgr/test/chrome/subtst_privbrowsing_4.html
+++ /dev/null
@@ -1,40 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Subtest for Login Manager notifications (private browsing)</title>
- <script type="text/javascript" src="pwmgr_common.js"></script>
-</head>
-<body>
-<h2>Subtest 4</h2>
-<!--
- Make sure that the user/pass fields have manual filling enabled
- in private mode.
--->
-<form id="form" action="formsubmit.sjs">
- <input id="user" name="user" type="text">
- <input id="pass" name="pass" type="password">
- <button type='submit'>Submit</button>
-</form>
-
-<script>
-function startAutocomplete() {
- userField.focus();
- doKey("down");
- setTimeout(submitForm, 100);
-}
-
-function submitForm() {
- doKey("down");
- doKey("return");
- setTimeout(function() { form.submit(); }, 100);
-}
-
-var form = document.getElementById("form");
-var userField = document.getElementById("user");
-
-window.addEventListener('message', () => { startAutocomplete(); });
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html b/toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html
deleted file mode 100644
index 6b7d4abb3..000000000
--- a/toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html
+++ /dev/null
@@ -1,322 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=248970
--->
-<head>
- <meta charset="utf-8">
- <title>Test for Private Browsing</title>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="notification_common.js"></script>
- <link rel="stylesheet" type="text/css"
- href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=248970">Mozilla Bug 248970</a>
-<p id="display"></p>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Bug 248970 **/
-// based on test_notifications.html
-
-const Ci = SpecialPowers.Ci;
-const Cc = SpecialPowers.Cc;
-const Cr = SpecialPowers.Cr;
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-var testpath = "/chrome/toolkit/components/passwordmgr/test/chrome/";
-var prefix = "http://test2.example.com" + testpath;
-var subtests = [
- "subtst_privbrowsing_1.html", // 1
- "subtst_privbrowsing_1.html", // 2
- "subtst_privbrowsing_1.html", // 3
- "subtst_privbrowsing_2.html", // 4
- "subtst_privbrowsing_2.html", // 5
- "subtst_privbrowsing_2.html", // 6
- "subtst_privbrowsing_3.html", // 7
- "subtst_privbrowsing_3.html", // 8
- "subtst_privbrowsing_4.html", // 9
- "subtst_privbrowsing_3.html" // 10
- ];
-var observer;
-
-var testNum = 0;
-function loadNextTest() {
- // run the initialization code for each test
- switch (++ testNum) {
- case 1:
- popupNotifications = normalWindowPopupNotifications;
- iframe = normalWindowIframe;
- break;
-
- case 2:
- popupNotifications = privateWindowPopupNotifications;
- iframe = privateWindowIframe;
- break;
-
- case 3:
- popupNotifications = normalWindowPopupNotifications;
- iframe = normalWindowIframe;
- break;
-
- case 4:
- pwmgr.addLogin(login);
- break;
-
- case 5:
- popupNotifications = privateWindowPopupNotifications;
- iframe = privateWindowIframe;
- break;
-
- case 6:
- popupNotifications = normalWindowPopupNotifications;
- iframe = normalWindowIframe;
- break;
-
- case 7:
- pwmgr.addLogin(login);
- break;
-
- case 8:
- popupNotifications = privateWindowPopupNotifications;
- iframe = privateWindowIframe;
- break;
-
- case 9:
- break;
-
- case 10:
- popupNotifications = normalWindowPopupNotifications;
- iframe = normalWindowIframe;
- break;
-
- default:
- ok(false, "Unexpected call to loadNextTest for test #" + testNum);
- }
-
- if (testNum === 7) {
- observer = SpecialPowers.wrapCallback(function(subject, topic, data) {
- SimpleTest.executeSoon(() => { iframe.contentWindow.postMessage("go", "*"); });
- });
- SpecialPowers.addObserver(observer, "passwordmgr-processed-form", false);
- }
-
- ok(true, "Starting test #" + testNum);
- iframe.src = prefix + subtests[testNum - 1];
-}
-
-function checkTest() {
- var popup;
- var gotUser;
- var gotPass;
-
- switch (testNum) {
- case 1:
- // run outside of private mode, popup notification should appear
- popup = getPopup(popupNotifications, "password-save");
- ok(popup, "got popup notification");
- popup.remove();
- break;
-
- case 2:
- // run inside of private mode, popup notification should not appear
- popup = getPopup(popupNotifications, "password-save");
- ok(!popup, "checking for no popup notification");
- break;
-
- case 3:
- // run outside of private mode, popup notification should appear
- popup = getPopup(popupNotifications, "password-save");
- ok(popup, "got popup notification");
- popup.remove();
- break;
-
- case 4:
- // run outside of private mode, popup notification should appear
- popup = getPopup(popupNotifications, "password-change");
- ok(popup, "got popup notification");
- popup.remove();
- break;
-
- case 5:
- // run inside of private mode, popup notification should not appear
- popup = getPopup(popupNotifications, "password-change");
- ok(!popup, "checking for no popup notification");
- break;
-
- case 6:
- // run outside of private mode, popup notification should appear
- popup = getPopup(popupNotifications, "password-change");
- ok(popup, "got popup notification");
- popup.remove();
- pwmgr.removeLogin(login);
- break;
-
- case 7:
- // verify that the user/pass pair was autofilled
- gotUser = iframe.contentDocument.getElementById("user").textContent;
- gotPass = iframe.contentDocument.getElementById("pass").textContent;
- is(gotUser, "notifyu1", "Checking submitted username");
- is(gotPass, "notifyp1", "Checking submitted password");
- break;
-
- case 8:
- // verify that the user/pass pair was not autofilled
- gotUser = iframe.contentDocument.getElementById("user").textContent;
- gotPass = iframe.contentDocument.getElementById("pass").textContent;
- is(gotUser, "", "Checking submitted username");
- is(gotPass, "", "Checking submitted password");
- break;
-
- case 9:
- // verify that the user/pass pair was available for autocomplete
- gotUser = iframe.contentDocument.getElementById("user").textContent;
- gotPass = iframe.contentDocument.getElementById("pass").textContent;
- is(gotUser, "notifyu1", "Checking submitted username");
- is(gotPass, "notifyp1", "Checking submitted password");
- break;
-
- case 10:
- // verify that the user/pass pair was autofilled
- gotUser = iframe.contentDocument.getElementById("user").textContent;
- gotPass = iframe.contentDocument.getElementById("pass").textContent;
- is(gotUser, "notifyu1", "Checking submitted username");
- is(gotPass, "notifyp1", "Checking submitted password");
- pwmgr.removeLogin(login);
- break;
-
- default:
- ok(false, "Unexpected call to checkTest for test #" + testNum);
-
- }
-}
-
-var mainWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShellTreeItem)
- .rootTreeItem
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
-var contentPage = "http://mochi.test:8888/chrome/toolkit/components/passwordmgr/test/chrome/privbrowsing_perwindowpb_iframe.html";
-var testWindows = [];
-
-function whenDelayedStartupFinished(aWindow, aCallback) {
- Services.obs.addObserver(function obs(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(obs, aTopic);
- setTimeout(aCallback, 0);
- }
- }, "browser-delayed-startup-finished", false);
-}
-
-function testOnWindow(aIsPrivate, aCallback) {
- var win = mainWindow.OpenBrowserWindow({private: aIsPrivate});
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- whenDelayedStartupFinished(win, function() {
- win.addEventListener("DOMContentLoaded", function onInnerLoad() {
- if (win.content.location.href != contentPage) {
- win.gBrowser.loadURI(contentPage);
- return;
- }
- win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
-
- win.content.addEventListener('load', function innerLoad2() {
- win.content.removeEventListener('load', innerLoad2, false);
- testWindows.push(win);
- SimpleTest.executeSoon(function() { aCallback(win); });
- }, false, true);
- }, true);
- SimpleTest.executeSoon(function() { win.gBrowser.loadURI(contentPage); });
- });
- }, true);
-}
-
-var ignoreLoad = false;
-function handleLoad(aEvent) {
- // ignore every other load event ... We get one for loading the subtest (which
- // we want to ignore), and another when the subtest's form submits itself
- // (which we want to handle, to start the next test).
- ignoreLoad = !ignoreLoad;
- if (ignoreLoad) {
- ok(true, "Ignoring load of subtest #" + testNum);
- return;
- }
- ok(true, "Processing submission of subtest #" + testNum);
-
- checkTest();
-
- if (testNum < subtests.length) {
- loadNextTest();
- } else {
- ok(true, "private browsing notification tests finished.");
-
- testWindows.forEach(function(aWin) {
- aWin.close();
- });
-
- SpecialPowers.removeObserver(observer, "passwordmgr-processed-form");
- SimpleTest.finish();
- }
-}
-
-var pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
-ok(pwmgr != null, "Access pwmgr");
-
-// We need to make sure no logins have been stored by previous tests
-// for forms in |url|, otherwise the change password notification
-// would turn into a prompt, and the test will fail.
-var url = "http://test2.example.com";
-is(pwmgr.countLogins(url, "", null), 0, "No logins should be stored for " + url);
-
-var nsLoginInfo = new SpecialPowers.wrap(SpecialPowers.Components).Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-var login = new nsLoginInfo(url, url, null, "notifyu1", "notifyp1", "user", "pass");
-
-var normalWindow;
-var privateWindow;
-
-var iframe;
-var normalWindowIframe;
-var privateWindowIframe;
-
-var popupNotifications;
-var normalWindowPopupNotifications;
-var privateWindowPopupNotifications;
-
-testOnWindow(false, function(aWin) {
- var selectedBrowser = aWin.gBrowser.selectedBrowser;
- normalWindowIframe = selectedBrowser.contentDocument.getElementById("iframe");
- normalWindowIframe.onload = handleLoad;
- selectedBrowser.focus();
-
- normalWindowPopupNotifications = getPopupNotifications(selectedBrowser.contentWindow.top);
- ok(normalWindowPopupNotifications, "Got popupNotifications in normal window");
- // ignore the first load for this window;
- ignoreLoad = false;
-
- testOnWindow(true, function(aPrivateWin) {
- selectedBrowser = aPrivateWin.gBrowser.selectedBrowser;
- privateWindowIframe = selectedBrowser.contentDocument.getElementById("iframe");
- privateWindowIframe.onload = handleLoad;
- selectedBrowser.focus();
-
- privateWindowPopupNotifications = getPopupNotifications(selectedBrowser.contentWindow.top);
- ok(privateWindowPopupNotifications, "Got popupNotifications in private window");
- // ignore the first load for this window;
- ignoreLoad = false;
-
- SimpleTest.executeSoon(loadNextTest);
- });
-});
-
-SimpleTest.waitForExplicitFinish();
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/chrome_timeout.js b/toolkit/components/passwordmgr/test/chrome_timeout.js
deleted file mode 100644
index 9049d0bea..000000000
--- a/toolkit/components/passwordmgr/test/chrome_timeout.js
+++ /dev/null
@@ -1,11 +0,0 @@
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-
-addMessageListener('setTimeout', msg => {
- let timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
- timer.init(_ => {
- sendAsyncMessage('timeout');
- }, msg.delay, Ci.nsITimer.TYPE_ONE_SHOT);
-});
-
-sendAsyncMessage('ready');
diff --git a/toolkit/components/passwordmgr/test/formsubmit.sjs b/toolkit/components/passwordmgr/test/formsubmit.sjs
deleted file mode 100644
index 4b4a387f7..000000000
--- a/toolkit/components/passwordmgr/test/formsubmit.sjs
+++ /dev/null
@@ -1,37 +0,0 @@
-function handleRequest(request, response)
-{
- try {
- reallyHandleRequest(request, response);
- } catch (e) {
- response.setStatusLine("1.0", 200, "AlmostOK");
- response.write("Error handling request: " + e);
- }
-}
-
-
-function reallyHandleRequest(request, response) {
- var match;
- var requestAuth = true;
-
- // XXX I bet this doesn't work for POST requests.
- var query = request.queryString;
-
- var user = null, pass = null;
- // user=xxx
- match = /user=([^&]*)/.exec(query);
- if (match)
- user = match[1];
-
- // pass=xxx
- match = /pass=([^&]*)/.exec(query);
- if (match)
- pass = match[1];
-
- response.setStatusLine("1.0", 200, "OK");
-
- response.setHeader("Content-Type", "application/xhtml+xml", false);
- response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
- response.write("<p>User: <span id='user'>" + user + "</span></p>\n");
- response.write("<p>Pass: <span id='pass'>" + pass + "</span></p>\n");
- response.write("</html>");
-}
diff --git a/toolkit/components/passwordmgr/test/mochitest.ini b/toolkit/components/passwordmgr/test/mochitest.ini
deleted file mode 100644
index 640f5c256..000000000
--- a/toolkit/components/passwordmgr/test/mochitest.ini
+++ /dev/null
@@ -1,20 +0,0 @@
-[DEFAULT]
-skip-if = e10s
-support-files =
- authenticate.sjs
- blank.html
- formsubmit.sjs
- prompt_common.js
- pwmgr_common.js
- subtst_master_pass.html
- subtst_prompt_async.html
- chrome_timeout.js
-
-[test_master_password.html]
-skip-if = toolkit == 'android' # Tests desktop prompts
-[test_prompt_async.html]
-skip-if = toolkit == 'android' # Tests desktop prompts
-[test_xhr.html]
-skip-if = toolkit == 'android' # Tests desktop prompts
-[test_xml_load.html]
-skip-if = toolkit == 'android' # Tests desktop prompts
diff --git a/toolkit/components/passwordmgr/test/mochitest/auth2/authenticate.sjs b/toolkit/components/passwordmgr/test/mochitest/auth2/authenticate.sjs
deleted file mode 100644
index d2f650013..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/auth2/authenticate.sjs
+++ /dev/null
@@ -1,220 +0,0 @@
-function handleRequest(request, response)
-{
- try {
- reallyHandleRequest(request, response);
- } catch (e) {
- response.setStatusLine("1.0", 200, "AlmostOK");
- response.write("Error handling request: " + e);
- }
-}
-
-
-function reallyHandleRequest(request, response) {
- var match;
- var requestAuth = true, requestProxyAuth = true;
-
- // Allow the caller to drive how authentication is processed via the query.
- // Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
- // The extra ? allows the user/pass/realm checks to succeed if the name is
- // at the beginning of the query string.
- var query = "?" + request.queryString;
-
- var expected_user = "", expected_pass = "", realm = "mochitest";
- var proxy_expected_user = "", proxy_expected_pass = "", proxy_realm = "mochi-proxy";
- var huge = false, plugin = false, anonymous = false;
- var authHeaderCount = 1;
- // user=xxx
- match = /[^_]user=([^&]*)/.exec(query);
- if (match)
- expected_user = match[1];
-
- // pass=xxx
- match = /[^_]pass=([^&]*)/.exec(query);
- if (match)
- expected_pass = match[1];
-
- // realm=xxx
- match = /[^_]realm=([^&]*)/.exec(query);
- if (match)
- realm = match[1];
-
- // proxy_user=xxx
- match = /proxy_user=([^&]*)/.exec(query);
- if (match)
- proxy_expected_user = match[1];
-
- // proxy_pass=xxx
- match = /proxy_pass=([^&]*)/.exec(query);
- if (match)
- proxy_expected_pass = match[1];
-
- // proxy_realm=xxx
- match = /proxy_realm=([^&]*)/.exec(query);
- if (match)
- proxy_realm = match[1];
-
- // huge=1
- match = /huge=1/.exec(query);
- if (match)
- huge = true;
-
- // plugin=1
- match = /plugin=1/.exec(query);
- if (match)
- plugin = true;
-
- // multiple=1
- match = /multiple=([^&]*)/.exec(query);
- if (match)
- authHeaderCount = match[1]+0;
-
- // anonymous=1
- match = /anonymous=1/.exec(query);
- if (match)
- anonymous = true;
-
- // Look for an authentication header, if any, in the request.
- //
- // EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
- //
- // This test only supports Basic auth. The value sent by the client is
- // "username:password", obscured with base64 encoding.
-
- var actual_user = "", actual_pass = "", authHeader, authPresent = false;
- if (request.hasHeader("Authorization")) {
- authPresent = true;
- authHeader = request.getHeader("Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw new Error("Couldn't parse auth header: " + authHeader);
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw new Error("Couldn't decode auth header: " + userpass);
- actual_user = match[1];
- actual_pass = match[2];
- }
-
- var proxy_actual_user = "", proxy_actual_pass = "";
- if (request.hasHeader("Proxy-Authorization")) {
- authHeader = request.getHeader("Proxy-Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw new Error("Couldn't parse auth header: " + authHeader);
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw new Error("Couldn't decode auth header: " + userpass);
- proxy_actual_user = match[1];
- proxy_actual_pass = match[2];
- }
-
- // Don't request authentication if the credentials we got were what we
- // expected.
- if (expected_user == actual_user &&
- expected_pass == actual_pass) {
- requestAuth = false;
- }
- if (proxy_expected_user == proxy_actual_user &&
- proxy_expected_pass == proxy_actual_pass) {
- requestProxyAuth = false;
- }
-
- if (anonymous) {
- if (authPresent) {
- response.setStatusLine("1.0", 400, "Unexpected authorization header found");
- } else {
- response.setStatusLine("1.0", 200, "Authorization header not found");
- }
- } else {
- if (requestProxyAuth) {
- response.setStatusLine("1.0", 407, "Proxy authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("Proxy-Authenticate", "basic realm=\"" + proxy_realm + "\"", true);
- } else if (requestAuth) {
- response.setStatusLine("1.0", 401, "Authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
- } else {
- response.setStatusLine("1.0", 200, "OK");
- }
- }
-
- response.setHeader("Content-Type", "application/xhtml+xml", false);
- response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
- response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Proxy: <span id='proxy'>" + (requestProxyAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
- response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
- response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
-
- if (huge) {
- response.write("<div style='display: none'>");
- for (i = 0; i < 100000; i++) {
- response.write("123456789\n");
- }
- response.write("</div>");
- response.write("<span id='footnote'>This is a footnote after the huge content fill</span>");
- }
-
- if (plugin) {
- response.write("<embed id='embedtest' style='width: 400px; height: 100px;' " +
- "type='application/x-test'></embed>\n");
- }
-
- response.write("</html>");
-}
-
-
-// base64 decoder
-//
-// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
-// doesn't seem to exist. :-(
-/* Convert Base64 data to a string */
-const toBinaryTable = [
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
-];
-const base64Pad = '=';
-
-function base64ToString(data) {
-
- var result = '';
- var leftbits = 0; // number of bits decoded, but yet to be appended
- var leftdata = 0; // bits decoded, but yet to be appended
-
- // Convert one by one.
- for (var i = 0; i < data.length; i++) {
- var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
- var padding = (data[i] == base64Pad);
- // Skip illegal characters and whitespace
- if (c == -1) continue;
-
- // Collect data into leftdata, update bitcount
- leftdata = (leftdata << 6) | c;
- leftbits += 6;
-
- // If we have 8 or more bits, append 8 bits to the result
- if (leftbits >= 8) {
- leftbits -= 8;
- // Append if not padding.
- if (!padding)
- result += String.fromCharCode((leftdata >> leftbits) & 0xff);
- leftdata &= (1 << leftbits) - 1;
- }
- }
-
- // If there are any bits left, the base64 string was corrupted
- if (leftbits)
- throw Components.Exception('Corrupted base64 string');
-
- return result;
-}
diff --git a/toolkit/components/passwordmgr/test/mochitest/mochitest.ini b/toolkit/components/passwordmgr/test/mochitest/mochitest.ini
deleted file mode 100644
index a4170d7e0..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/mochitest.ini
+++ /dev/null
@@ -1,69 +0,0 @@
-[DEFAULT]
-support-files =
- ../../../prompts/test/chromeScript.js
- ../../../prompts/test/prompt_common.js
- ../../../satchel/test/parent_utils.js
- ../../../satchel/test/satchel_common.js
- ../authenticate.sjs
- ../blank.html
- ../browser/form_autofocus_js.html
- ../browser/form_basic.html
- ../browser/form_cross_origin_secure_action.html
- ../pwmgr_common.js
- auth2/authenticate.sjs
-
-[test_autocomplete_https_upgrade.html]
-skip-if = toolkit == 'android' # autocomplete
-[test_autofill_https_upgrade.html]
-skip-if = toolkit == 'android' # Bug 1259768
-[test_autofill_password-only.html]
-[test_autofocus_js.html]
-skip-if = toolkit == 'android' # autocomplete
-[test_basic_form.html]
-[test_basic_form_0pw.html]
-[test_basic_form_1pw.html]
-[test_basic_form_1pw_2.html]
-[test_basic_form_2pw_1.html]
-[test_basic_form_2pw_2.html]
-[test_basic_form_3pw_1.html]
-[test_basic_form_autocomplete.html]
-skip-if = toolkit == 'android' # android:autocomplete.
-[test_insecure_form_field_autocomplete.html]
-skip-if = toolkit == 'android' # android:autocomplete.
-[test_password_field_autocomplete.html]
-skip-if = toolkit == 'android' # android:autocomplete.
-[test_insecure_form_field_no_saved_login.html]
-skip-if = toolkit == 'android' || os == 'linux' # android:autocomplete., linux: bug 1325778
-[test_basic_form_html5.html]
-[test_basic_form_pwevent.html]
-[test_basic_form_pwonly.html]
-[test_bug_627616.html]
-skip-if = toolkit == 'android' # Tests desktop prompts
-[test_bug_776171.html]
-[test_case_differences.html]
-skip-if = toolkit == 'android' # autocomplete
-[test_form_action_1.html]
-[test_form_action_2.html]
-[test_form_action_javascript.html]
-[test_formless_autofill.html]
-[test_formless_submit.html]
-[test_formless_submit_navigation.html]
-[test_formless_submit_navigation_negative.html]
-[test_input_events.html]
-[test_input_events_for_identical_values.html]
-[test_maxlength.html]
-[test_passwords_in_type_password.html]
-[test_prompt.html]
-skip-if = os == "linux" || toolkit == 'android' # Tests desktop prompts
-[test_prompt_http.html]
-skip-if = os == "linux" || toolkit == 'android' # Tests desktop prompts
-[test_prompt_noWindow.html]
-skip-if = e10s || toolkit == 'android' # Tests desktop prompts. e10s: bug 1217876
-[test_prompt_promptAuth.html]
-skip-if = os == "linux" || toolkit == 'android' # Tests desktop prompts
-[test_prompt_promptAuth_proxy.html]
-skip-if = e10s || os == "linux" || toolkit == 'android' # Tests desktop prompts
-[test_recipe_login_fields.html]
-[test_username_focus.html]
-skip-if = toolkit == 'android' # android:autocomplete.
-[test_xhr_2.html]
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_autocomplete_https_upgrade.html b/toolkit/components/passwordmgr/test/mochitest/test_autocomplete_https_upgrade.html
deleted file mode 100644
index 7d5725322..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_autocomplete_https_upgrade.html
+++ /dev/null
@@ -1,218 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test autocomplete on an HTTPS page using upgraded HTTP logins</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script>
-const chromeScript = runChecksAfterCommonInit(false);
-
-runInParent(function addLogins() {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- // Create some logins just for this form, since we'll be deleting them.
- let nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-
- // We have two actual HTTPS to avoid autofill before the schemeUpgrades pref flips to true.
- let login0 = new nsLoginInfo("https://example.org", "https://example.org", null,
- "name", "pass", "uname", "pword");
-
- let login1 = new nsLoginInfo("https://example.org", "https://example.org", null,
- "name1", "pass1", "uname", "pword");
-
- // Same as above but HTTP instead of HTTPS (to test de-duping)
- let login2 = new nsLoginInfo("http://example.org", "http://example.org", null,
- "name1", "passHTTP", "uname", "pword");
-
- // Different HTTP login to upgrade with secure formSubmitURL
- let login3 = new nsLoginInfo("http://example.org", "https://example.org", null,
- "name2", "passHTTPtoHTTPS", "uname", "pword");
-
- try {
- Services.logins.addLogin(login0);
- Services.logins.addLogin(login1);
- Services.logins.addLogin(login2);
- Services.logins.addLogin(login3);
- } catch (e) {
- assert.ok(false, "addLogin threw: " + e);
- }
-});
-</script>
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
- <iframe src="https://example.org/tests/toolkit/components/passwordmgr/test/mochitest/form_basic.html"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-const shiftModifier = SpecialPowers.Ci.nsIDOMEvent.SHIFT_MASK;
-
-let iframe = SpecialPowers.wrap(document.getElementsByTagName("iframe")[0]);
-let iframeDoc;
-let uname;
-let pword;
-
-// Restore the form to the default state.
-function restoreForm() {
- pword.focus();
- uname.value = "";
- pword.value = "";
- uname.focus();
-}
-
-// Check for expected username/password in form.
-function checkACForm(expectedUsername, expectedPassword) {
- let formID = uname.parentNode.id;
- is(uname.value, expectedUsername, "Checking " + formID + " username");
- is(pword.value, expectedPassword, "Checking " + formID + " password");
-}
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({"set": [["signon.schemeUpgrades", true]]});
-
- yield new Promise(resolve => {
- iframe.addEventListener("load", function onLoad() {
- iframe.removeEventListener("load", onLoad);
- resolve();
- });
- });
-
- iframeDoc = iframe.contentDocument;
- uname = iframeDoc.getElementById("form-basic-username");
- pword = iframeDoc.getElementById("form-basic-password");
-});
-
-add_task(function* test_empty_first_entry() {
- // Make sure initial form is empty.
- checkACForm("", "");
- // Trigger autocomplete popup
- restoreForm();
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is initially closed");
- let shownPromise = promiseACShown();
- doKey("down");
- let results = yield shownPromise;
- popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected");
- checkArrayValues(results, ["name", "name1", "name2"], "initial");
-
- // Check first entry
- let index0Promise = notifySelectedIndex(0);
- doKey("down");
- yield index0Promise;
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("name", "pass");
-});
-
-add_task(function* test_empty_second_entry() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
- doKey("down"); // first
- doKey("down"); // second
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("name1", "pass1");
-});
-
-add_task(function* test_search() {
- restoreForm();
- let shownPromise = promiseACShown();
- // We need to blur for the autocomplete controller to notice the forced value below.
- uname.blur();
- uname.value = "name";
- uname.focus();
- sendChar("1");
- doKey("down"); // open
- let results = yield shownPromise;
- checkArrayValues(results, ["name1"], "check result deduping for 'name1'");
- doKey("down"); // first
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("name1", "pass1");
-
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is now closed");
-});
-
-add_task(function* test_delete_first_entry() {
- restoreForm();
- uname.focus();
- let shownPromise = promiseACShown();
- doKey("down");
- yield shownPromise;
-
- let index0Promise = notifySelectedIndex(0);
- doKey("down");
- yield index0Promise;
-
- let deletionPromise = promiseStorageChanged(["removeLogin"]);
- // On OS X, shift-backspace and shift-delete work, just delete does not.
- // On Win/Linux, shift-backspace does not work, delete and shift-delete do.
- doKey("delete", shiftModifier);
- yield deletionPromise;
- checkACForm("", "");
-
- let results = yield notifyMenuChanged(2, "name1");
-
- checkArrayValues(results, ["name1", "name2"], "two should remain after deleting the first");
- let popupState = yield getPopupState();
- is(popupState.open, true, "Check popup stays open after deleting");
- doKey("escape");
- popupState = yield getPopupState();
- is(popupState.open, false, "Check popup closed upon ESC");
-});
-
-add_task(function* test_delete_duplicate_entry() {
- restoreForm();
- uname.focus();
- let shownPromise = promiseACShown();
- doKey("down");
- yield shownPromise;
-
- let index0Promise = notifySelectedIndex(0);
- doKey("down");
- yield index0Promise;
-
- let deletionPromise = promiseStorageChanged(["removeLogin"]);
- // On OS X, shift-backspace and shift-delete work, just delete does not.
- // On Win/Linux, shift-backspace does not work, delete and shift-delete do.
- doKey("delete", shiftModifier);
- yield deletionPromise;
- checkACForm("", "");
-
- is(LoginManager.countLogins("http://example.org", "http://example.org", null), 1,
- "Check that the HTTP login remains");
- is(LoginManager.countLogins("https://example.org", "https://example.org", null), 0,
- "Check that the HTTPS login was deleted");
-
- // Two menu items should remain as the HTTPS login should have been deleted but
- // the HTTP would remain.
- let results = yield notifyMenuChanged(1, "name2");
-
- checkArrayValues(results, ["name2"], "one should remain after deleting the HTTPS name1");
- let popupState = yield getPopupState();
- is(popupState.open, true, "Check popup stays open after deleting");
- doKey("escape");
- popupState = yield getPopupState();
- is(popupState.open, false, "Check popup closed upon ESC");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_autofill_https_upgrade.html b/toolkit/components/passwordmgr/test/mochitest/test_autofill_https_upgrade.html
deleted file mode 100644
index ee1424002..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_autofill_https_upgrade.html
+++ /dev/null
@@ -1,117 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test autocomplete on an HTTPS page using upgraded HTTP logins</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script>
-const MISSING_ACTION_PATH = TESTS_DIR + "mochitest/form_basic.html";
-const CROSS_ORIGIN_SECURE_PATH = TESTS_DIR + "mochitest/form_cross_origin_secure_action.html";
-
-const chromeScript = runChecksAfterCommonInit(false);
-
-let nsLoginInfo = SpecialPowers.wrap(SpecialPowers.Components).Constructor("@mozilla.org/login-manager/loginInfo;1",
-SpecialPowers.Ci.nsILoginInfo,
-"init");
-</script>
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
- <iframe></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-let iframe = SpecialPowers.wrap(document.getElementsByTagName("iframe")[0]);
-
-// Check for expected username/password in form.
-function checkACForm(expectedUsername, expectedPassword) {
- let iframeDoc = iframe.contentDocument;
- let uname = iframeDoc.getElementById("form-basic-username");
- let pword = iframeDoc.getElementById("form-basic-password");
- let formID = uname.parentNode.id;
- is(uname.value, expectedUsername, "Checking " + formID + " username");
- is(pword.value, expectedPassword, "Checking " + formID + " password");
-}
-function* prepareLoginsAndProcessForm(url, logins = []) {
- LoginManager.removeAllLogins();
-
- let dates = Date.now();
- for (let login of logins) {
- SpecialPowers.do_QueryInterface(login, SpecialPowers.Ci.nsILoginMetaInfo);
- // Force all dates to be the same so they don't affect things like deduping.
- login.timeCreated = login.timePasswordChanged = login.timeLastUsed = dates;
- LoginManager.addLogin(login);
- }
-
- iframe.src = url;
- yield promiseFormsProcessed();
-}
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({"set": [["signon.schemeUpgrades", true]]});
-});
-
-add_task(function* test_simpleNoDupesNoAction() {
- yield prepareLoginsAndProcessForm("https://example.com" + MISSING_ACTION_PATH, [
- new nsLoginInfo("http://example.com", "http://example.com", null,
- "name2", "pass2", "uname", "pword"),
- ]);
-
- checkACForm("name2", "pass2");
-});
-
-add_task(function* test_simpleNoDupesUpgradeOriginAndAction() {
- yield prepareLoginsAndProcessForm("https://example.com" + CROSS_ORIGIN_SECURE_PATH, [
- new nsLoginInfo("http://example.com", "http://another.domain", null,
- "name2", "pass2", "uname", "pword"),
- ]);
-
- checkACForm("name2", "pass2");
-});
-
-add_task(function* test_simpleNoDupesUpgradeOriginOnly() {
- yield prepareLoginsAndProcessForm("https://example.com" + CROSS_ORIGIN_SECURE_PATH, [
- new nsLoginInfo("http://example.com", "https://another.domain", null,
- "name2", "pass2", "uname", "pword"),
- ]);
-
- checkACForm("name2", "pass2");
-});
-
-add_task(function* test_simpleNoDupesUpgradeActionOnly() {
- yield prepareLoginsAndProcessForm("https://example.com" + CROSS_ORIGIN_SECURE_PATH, [
- new nsLoginInfo("https://example.com", "http://another.domain", null,
- "name2", "pass2", "uname", "pword"),
- ]);
-
- checkACForm("name2", "pass2");
-});
-
-add_task(function* test_dedupe() {
- yield prepareLoginsAndProcessForm("https://example.com" + MISSING_ACTION_PATH, [
- new nsLoginInfo("https://example.com", "https://example.com", null,
- "name1", "passHTTPStoHTTPS", "uname", "pword"),
- new nsLoginInfo("http://example.com", "http://example.com", null,
- "name1", "passHTTPtoHTTP", "uname", "pword"),
- new nsLoginInfo("http://example.com", "https://example.com", null,
- "name1", "passHTTPtoHTTPS", "uname", "pword"),
- new nsLoginInfo("https://example.com", "http://example.com", null,
- "name1", "passHTTPStoHTTP", "uname", "pword"),
- ]);
-
- checkACForm("name1", "passHTTPStoHTTPS");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_autofill_password-only.html b/toolkit/components/passwordmgr/test/mochitest/test_autofill_password-only.html
deleted file mode 100644
index 983356371..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_autofill_password-only.html
+++ /dev/null
@@ -1,143 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test password-only forms should prefer a password-only login when present</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: Bug 444968
-<script>
-let pwmgrCommonScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-pwmgrCommonScript.sendSyncMessage("setupParent", { selfFilling: true });
-
-SimpleTest.waitForExplicitFinish();
-
-let chromeScript = runInParent(function chromeSetup() {
- const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
- let pwmgr = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
-
- let login1A = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login1B = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
- login1A.init("http://mochi.test:8888", "http://bug444968-1", null,
- "testuser1A", "testpass1A", "", "");
- login1B.init("http://mochi.test:8888", "http://bug444968-1", null,
- "", "testpass1B", "", "");
-
- login2A.init("http://mochi.test:8888", "http://bug444968-2", null,
- "testuser2A", "testpass2A", "", "");
- login2B.init("http://mochi.test:8888", "http://bug444968-2", null,
- "", "testpass2B", "", "");
- login2C.init("http://mochi.test:8888", "http://bug444968-2", null,
- "testuser2C", "testpass2C", "", "");
-
- pwmgr.addLogin(login1A);
- pwmgr.addLogin(login1B);
- pwmgr.addLogin(login2A);
- pwmgr.addLogin(login2B);
- pwmgr.addLogin(login2C);
-
- addMessageListener("removeLogins", function removeLogins() {
- pwmgr.removeLogin(login1A);
- pwmgr.removeLogin(login1B);
- pwmgr.removeLogin(login2A);
- pwmgr.removeLogin(login2B);
- pwmgr.removeLogin(login2C);
- });
-});
-
-SimpleTest.registerCleanupFunction(() => chromeScript.sendSyncMessage("removeLogins"));
-
-registerRunTests();
-</script>
-
-<p id="display"></p>
-<div id="content" style="display: none">
- <!-- first 3 forms have matching user+pass and pass-only logins -->
-
- <!-- user+pass form. -->
- <form id="form1" action="http://bug444968-1">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- password-only form. -->
- <form id="form2" action="http://bug444968-1">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form, username prefilled -->
- <form id="form3" action="http://bug444968-1">
- <input type="text" name="uname" value="testuser1A">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
-
- <!-- next 4 forms have matching user+pass (2x) and pass-only (1x) logins -->
-
- <!-- user+pass form. -->
- <form id="form4" action="http://bug444968-2">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- password-only form. -->
- <form id="form5" action="http://bug444968-2">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form, username prefilled -->
- <form id="form6" action="http://bug444968-2">
- <input type="text" name="uname" value="testuser2A">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form, username prefilled -->
- <form id="form7" action="http://bug444968-2">
- <input type="text" name="uname" value="testuser2C">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/* Test for Login Manager: 444968 (password-only forms should prefer a
- * password-only login when present )
- */
-function startTest() {
- checkForm(1, "testuser1A", "testpass1A");
- checkForm(2, "testpass1B");
- checkForm(3, "testuser1A", "testpass1A");
-
- checkUnmodifiedForm(4); // 2 logins match
- checkForm(5, "testpass2B");
- checkForm(6, "testuser2A", "testpass2A");
- checkForm(7, "testuser2C", "testpass2C");
-
- SimpleTest.finish();
-}
-
-window.addEventListener("runTests", startTest);
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_autofocus_js.html b/toolkit/components/passwordmgr/test/mochitest/test_autofocus_js.html
deleted file mode 100644
index 2ce3293dd..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_autofocus_js.html
+++ /dev/null
@@ -1,115 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test login autocomplete is activated when focused by js on load</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script>
-const chromeScript = runChecksAfterCommonInit(false);
-
-runInParent(function addLogins() {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- // Create some logins just for this form, since we'll be deleting them.
- let nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-
- let login0 = new nsLoginInfo("https://example.org", "https://example.org", null,
- "name", "pass", "uname", "pword");
-
- let login1 = new nsLoginInfo("https://example.org", "https://example.org", null,
- "name1", "pass1", "uname", "pword");
-
- try {
- Services.logins.addLogin(login0);
- Services.logins.addLogin(login1);
- } catch (e) {
- assert.ok(false, "addLogin threw: " + e);
- }
-});
-</script>
-<p id="display"></p>
-
-<div id="content">
- <iframe src="https://example.org/tests/toolkit/components/passwordmgr/test/mochitest/form_autofocus_js.html"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-let iframe = SpecialPowers.wrap(document.getElementsByTagName("iframe")[0]);
-let iframeDoc;
-
-add_task(function* setup() {
- yield new Promise(resolve => {
- iframe.addEventListener("load", function onLoad() {
- iframe.removeEventListener("load", onLoad);
- resolve();
- });
- });
-
- iframeDoc = iframe.contentDocument;
-
- SimpleTest.requestFlakyTimeout("Giving a chance for the unexpected popupshown to occur");
-});
-
-add_task(function* test_initial_focus() {
- let results = yield notifyMenuChanged(2, "name");
- checkArrayValues(results, ["name", "name1"], "Two results");
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- is(iframeDoc.getElementById("form-basic-password").value, "pass", "Check first password filled");
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is now closed");
-});
-
-// This depends on the filling from the previous test.
-add_task(function* test_not_reopened_if_filled() {
- listenForUnexpectedPopupShown();
- let usernameField = iframeDoc.getElementById("form-basic-username");
- usernameField.focus();
- info("Waiting to see if a popupshown occurs");
- yield new Promise(resolve => setTimeout(resolve, 1000));
-
- // cleanup
- gPopupShownExpected = true;
- iframeDoc.getElementById("form-basic-submit").focus();
-});
-
-add_task(function* test_reopened_after_edit_not_matching_saved() {
- let usernameField = iframeDoc.getElementById("form-basic-username");
- usernameField.value = "nam";
- let shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
- iframeDoc.getElementById("form-basic-submit").focus();
-});
-
-add_task(function* test_not_reopened_after_selecting() {
- let formFillController = SpecialPowers.Cc["@mozilla.org/satchel/form-fill-controller;1"].
- getService(SpecialPowers.Ci.nsIFormFillController);
- let usernameField = iframeDoc.getElementById("form-basic-username");
- usernameField.value = "";
- iframeDoc.getElementById("form-basic-password").value = "";
- listenForUnexpectedPopupShown();
- formFillController.markAsLoginManagerField(usernameField);
- info("Waiting to see if a popupshown occurs");
- yield new Promise(resolve => setTimeout(resolve, 1000));
-
- // Cleanup
- gPopupShownExpected = true;
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form.html
deleted file mode 100644
index 3c38343a5..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form.html
+++ /dev/null
@@ -1,44 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test basic autofill</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: simple form fill
-
-<script>
-runChecksAfterCommonInit(startTest);
-
-/** Test for Login Manager: form fill, multiple forms. **/
-
-function startTest() {
- is($_(1, "uname").value, "testuser", "Checking for filled username");
- is($_(1, "pword").value, "testpass", "Checking for filled password");
-
- SimpleTest.finish();
-}
-</script>
-
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
- <form id="form1" action="formtest.js">
- <p>This is form 1.</p>
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
-</div>
-
-<pre id="test"></pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_0pw.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_0pw.html
deleted file mode 100644
index 0b416673b..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_0pw.html
+++ /dev/null
@@ -1,72 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test forms with no password fields</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: forms with no password fields
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
- <!-- Form with no user field or password field -->
- <form id="form1" action="formtest.js">
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Form with no user field or password field, but one other field -->
- <form id="form2" action="formtest.js">
- <input type="checkbox">
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Form with no user field or password field, but one other field -->
- <form id="form3" action="formtest.js">
- <input type="checkbox" name="uname" value="">
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Form with a text field, but no password field -->
- <form id="form4" action="formtest.js">
- <input type="text" name="yyyyy">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Form with a user field, but no password field -->
- <form id="form5" action="formtest.js">
- <input type="text" name="uname">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: form fill, no password fields. **/
-
-function startTest() {
- is($_(3, "uname").value, "", "Checking for unfilled checkbox (form 3)");
- is($_(4, "yyyyy").value, "", "Checking for unfilled text field (form 4)");
- is($_(5, "uname").value, "", "Checking for unfilled text field (form 5)");
-
- SimpleTest.finish();
-}
-
-runChecksAfterCommonInit(startTest);
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw.html
deleted file mode 100644
index 3937fad4b..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw.html
+++ /dev/null
@@ -1,167 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test autofill for forms with 1 password field</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: forms with 1 password field
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
-<!-- no username fields -->
-
-<form id='form1' action='formtest.js'> 1
- <!-- Blank, so fill in the password -->
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form2' action='formtest.js'> 2
- <!-- Already contains the password, so nothing to do. -->
- <input type='password' name='pname' value='testpass'>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form3' action='formtest.js'> 3
- <!-- Contains unknown password, so don't change it -->
- <input type='password' name='pname' value='xxxxxxxx'>
- <button type='submit'>Submit</button>
-</form>
-
-
-<!-- username fields -->
-
-<form id='form4' action='formtest.js'> 4
- <!-- Blanks, so fill in login -->
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form5' action='formtest.js'> 5
- <!-- Username already set, so fill in password -->
- <input type='text' name='uname' value='testuser'>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form6' action='formtest.js'> 6
- <!-- Unknown username, so don't fill in password -->
- <input type='text' name='uname' value='xxxxxxxx'>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form7' action='formtest.js'> 7
- <!-- Password already set, could fill in username but that's weird so we don't -->
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='testpass'>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form8' action='formtest.js'> 8
- <!-- Unknown password, so don't fill in a username -->
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='xxxxxxxx'>
- <button type='submit'>Submit</button>
-</form>
-
-
-
-<!-- extra text fields -->
-
-<form id='form9' action='formtest.js'> 9
- <!-- text field _after_ password should never be treated as a username field -->
- <input type='password' name='pname' value=''>
- <input type='text' name='uname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form10' action='formtest.js'> 10
- <!-- only the first text field before the password should be for username -->
- <input type='text' name='other' value=''>
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form11' action='formtest.js'> 11
- <!-- variation just to make sure extra text field is still ignored -->
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
- <input type='text' name='other' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-
-
-<!-- same as last bunch, but with xxxx in the extra field. -->
-
-<form id='form12' action='formtest.js'> 12
- <!-- text field _after_ password should never be treated as a username field -->
- <input type='password' name='pname' value=''>
- <input type='text' name='uname' value='xxxxxxxx'>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form13' action='formtest.js'> 13
- <!-- only the first text field before the password should be for username -->
- <input type='text' name='other' value='xxxxxxxx'>
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form14' action='formtest.js'> 14
- <!-- variation just to make sure extra text field is still ignored -->
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
- <input type='text' name='other' value='xxxxxxxx'>
- <button type='submit'>Submit</button>
-</form>
-
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: simple form fill **/
-
-function startTest() {
- var f = 1;
-
- // 1-3
- checkForm(f++, "testpass");
- checkForm(f++, "testpass");
- checkForm(f++, "xxxxxxxx");
-
- // 4-8
- checkForm(f++, "testuser", "testpass");
- checkForm(f++, "testuser", "testpass");
- checkForm(f++, "xxxxxxxx", "");
- checkForm(f++, "", "testpass");
- checkForm(f++, "", "xxxxxxxx");
-
- // 9-14
- checkForm(f++, "testpass", "");
- checkForm(f++, "", "testuser", "testpass");
- checkForm(f++, "testuser", "testpass", "");
- checkForm(f++, "testpass", "xxxxxxxx");
- checkForm(f++, "xxxxxxxx", "testuser", "testpass");
- checkForm(f++, "testuser", "testpass", "xxxxxxxx");
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw_2.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw_2.html
deleted file mode 100644
index 0f6566b9c..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_1pw_2.html
+++ /dev/null
@@ -1,109 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test forms with 1 password field, part 2</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: forms with 1 password field, part 2
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
-<form id='form1' action='formtest.js'> 1
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form2' action='formtest.js'> 2
- <input type='password' name='pname' value='' disabled>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form3' action='formtest.js'> 3
- <input type='password' name='pname' value='' readonly>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form4' action='formtest.js'> 4
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form5' action='formtest.js'> 5
- <input type='text' name='uname' value='' disabled>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form6' action='formtest.js'> 6
- <input type='text' name='uname' value='' readonly>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form7' action='formtest.js'> 7
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='' disabled>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form8' action='formtest.js'> 8
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='' readonly>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form9' action='formtest.js'> 9
- <input type='text' name='uname' value='TESTUSER'>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form10' action='formtest.js'> 10
- <input type='text' name='uname' value='TESTUSER' readonly>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form11' action='formtest.js'> 11
- <input type='text' name='uname' value='TESTUSER' disabled>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: simple form fill, part 2 **/
-
-function startTest() {
- var f;
-
- // Test various combinations of disabled/readonly inputs
- checkForm(1, "testpass"); // control
- checkUnmodifiedForm(2);
- checkUnmodifiedForm(3);
- checkForm(4, "testuser", "testpass"); // control
- for (f = 5; f <= 8; f++) { checkUnmodifiedForm(f); }
- // Test case-insensitive comparison of username field
- checkForm(9, "testuser", "testpass");
- checkForm(10, "TESTUSER", "testpass");
- checkForm(11, "TESTUSER", "testpass");
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_1.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_1.html
deleted file mode 100644
index 128ffca7c..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_1.html
+++ /dev/null
@@ -1,187 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test autofill for forms with 2 password fields</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: forms with 2 password fields
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
-
-<!-- no username fields -->
-
-<form id='form1' action='formtest.js'> 1
- <!-- simple form, fill in first pw -->
- <input type='password' name='pname' value=''>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form2' action='formtest.js'> 2
- <!-- same but reverse pname and qname, field names are ignored. -->
- <input type='password' name='qname' value=''>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form3' action='formtest.js'> 3
- <!-- text field after password fields should be ignored, no username. -->
- <input type='password' name='pname' value=''>
- <input type='password' name='qname' value=''>
- <input type='text' name='uname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form4' action='formtest.js'> 4
- <!-- nothing to do, password already present -->
- <input type='password' name='pname' value='testpass'>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form5' action='formtest.js'> 5
- <!-- don't clobber an existing unrecognized password -->
- <input type='password' name='pname' value='xxxxxxxx'>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form6' action='formtest.js'> 6
- <!-- fill in first field, 2nd field shouldn't be touched anyway. -->
- <input type='password' name='pname' value=''>
- <input type='password' name='qname' value='xxxxxxxx'>
- <button type='submit'>Submit</button>
-</form>
-
-
-
-<!-- with username fields -->
-
-
-
-<form id='form7' action='formtest.js'> 7
- <!-- simple form, should fill in username and first pw -->
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form8' action='formtest.js'> 8
- <!-- reverse pname and qname, field names are ignored. -->
- <input type='text' name='uname' value=''>
- <input type='password' name='qname' value=''>
- <input type='password' name='pname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form9' action='formtest.js'> 9
- <!-- username already filled, so just fill first password -->
- <input type='text' name='uname' value='testuser'>
- <input type='password' name='pname' value=''>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form10' action='formtest.js'> 10
- <!-- unknown username, don't fill in a password -->
- <input type='text' name='uname' value='xxxxxxxx'>
- <input type='password' name='pname' value=''>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form11' action='formtest.js'> 11
- <!-- don't clobber unknown password -->
- <input type='text' name='uname' value='testuser'>
- <input type='password' name='pname' value='xxxxxxxx'>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form12' action='formtest.js'> 12
- <!-- fill in 1st pass, don't clobber 2nd pass -->
- <input type='text' name='uname' value='testuser'>
- <input type='password' name='pname' value=''>
- <input type='password' name='qname' value='xxxxxxxx'>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form13' action='formtest.js'> 13
- <!-- nothing to do, user and pass prefilled. life is easy. -->
- <input type='text' name='uname' value='testuser'>
- <input type='password' name='pname' value='testpass'>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form14' action='formtest.js'> 14
- <!-- shouldn't fill in username because 1st pw field is unknown. -->
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='xxxxxxxx'>
- <input type='password' name='qname' value='testpass'>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form15' action='formtest.js'> 15
- <!-- textfield in the middle of pw fields should be ignored -->
- <input type='password' name='pname' value=''>
- <input type='text' name='uname' value=''>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-<form id='form16' action='formtest.js'> 16
- <!-- same, and don't clobber existing unknown password -->
- <input type='password' name='pname' value='xxxxxxxx'>
- <input type='text' name='uname' value=''>
- <input type='password' name='qname' value=''>
- <button type='submit'>Submit</button>
-</form>
-
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: simple form fill **/
-
-function startTest() {
- var f = 1;
-
- // 1-6 no username
- checkForm(f++, "testpass", "");
- checkForm(f++, "testpass", "");
- checkForm(f++, "testpass", "", "");
- checkForm(f++, "testpass", "");
- checkForm(f++, "xxxxxxxx", "");
- checkForm(f++, "testpass", "xxxxxxxx");
-
- // 7-15 with username
- checkForm(f++, "testuser", "testpass", "");
- checkForm(f++, "testuser", "testpass", "");
- checkForm(f++, "testuser", "testpass", "");
- checkForm(f++, "xxxxxxxx", "", "");
- checkForm(f++, "testuser", "xxxxxxxx", "");
- checkForm(f++, "testuser", "testpass", "xxxxxxxx");
- checkForm(f++, "testuser", "testpass", "");
- checkForm(f++, "", "xxxxxxxx", "testpass");
- checkForm(f++, "testpass", "", "");
- checkForm(f++, "xxxxxxxx", "", "");
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_2.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_2.html
deleted file mode 100644
index eba811cf9..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_2pw_2.html
+++ /dev/null
@@ -1,105 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for form fill with 2 password fields</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: form fill, 2 password fields
-<p id="display"></p>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: form fill, 2 password fields **/
-
-/*
- * If a form has two password fields, other things may be going on....
- *
- * 1 - The user might be creating a new login (2nd field for typo checking)
- * 2 - The user is changing a password (old and new password each have field)
- *
- * This test is for case #1.
- */
-
-var numSubmittedForms = 0;
-var numStartingLogins = 0;
-
-function startTest() {
- // Check for unfilled forms
- is($_(1, "uname").value, "", "Checking username 1");
- is($_(1, "pword").value, "", "Checking password 1A");
- is($_(1, "qword").value, "", "Checking password 1B");
-
- // Fill in the username and password fields, for account creation.
- // Form 1
- $_(1, "uname").value = "newuser1";
- $_(1, "pword").value = "newpass1";
- $_(1, "qword").value = "newpass1";
-
- var button = getFormSubmitButton(1);
-
- todo(false, "form submission disabled, can't auto-accept dialog yet");
- SimpleTest.finish();
-}
-
-
-// Called by each form's onsubmit handler.
-function checkSubmit(formNum) {
- numSubmittedForms++;
-
- // End the test at the last form.
- if (formNum == 999) {
- is(numSubmittedForms, 999, "Ensuring all forms submitted for testing.");
-
- var numEndingLogins = LoginManager.countLogins("", "", "");
-
- ok(numEndingLogins > 0, "counting logins at end");
- is(numStartingLogins, numEndingLogins + 222, "counting logins at end");
-
- SimpleTest.finish();
- return false; // return false to cancel current form submission
- }
-
- // submit the next form.
- var button = getFormSubmitButton(formNum + 1);
- button.click();
-
- return false; // return false to cancel current form submission
-}
-
-
-function getFormSubmitButton(formNum) {
- var form = $("form" + formNum); // by id, not name
- ok(form != null, "getting form " + formNum);
-
- // we can't just call form.submit(), because that doesn't seem to
- // invoke the form onsubmit handler.
- var button = form.firstChild;
- while (button && button.type != "submit") { button = button.nextSibling; }
- ok(button != null, "getting form submit button");
-
- return button;
-}
-
-runChecksAfterCommonInit(startTest);
-
-</script>
-</pre>
-<div id="content" style="display: none">
- <form id="form1" onsubmit="return checkSubmit(1)" action="http://newuser.com">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <input type="password" name="qword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
-</div>
-
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_3pw_1.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_3pw_1.html
deleted file mode 100644
index 30b5a319f..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_3pw_1.html
+++ /dev/null
@@ -1,177 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test autofill for forms with 3 password fields</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: forms with 3 password fields (form filling)
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-
-<div id="content" style="display: none">
- <p>The next three forms are <b>user/pass/passB/passC</b>, as all-empty, preuser(only), and preuser/pass</p>
- <form id="form1" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <input type="password" name="qword">
- <input type="password" name="rword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <form id="form2" action="formtest.js">
- <input type="text" name="uname" value="testuser">
- <input type="password" name="pword">
- <input type="password" name="qword">
- <input type="password" name="rword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <form id="form3" action="formtest.js">
- <input type="text" name="uname" value="testuser">
- <input type="password" name="pword" value="testpass">
- <input type="password" name="qword">
- <input type="password" name="rword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
-
- <p>The next three forms are <b>user/passB/pass/passC</b>, as all-empty, preuser(only), and preuser/pass</p>
- <form id="form4" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="qword">
- <input type="password" name="pword">
- <input type="password" name="rword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <form id="form5" action="formtest.js">
- <input type="text" name="uname" value="testuser">
- <input type="password" name="qword">
- <input type="password" name="pword">
- <input type="password" name="rword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <form id="form6" action="formtest.js">
- <input type="text" name="uname" value="testuser">
- <input type="password" name="qword">
- <input type="password" name="pword" value="testpass">
- <input type="password" name="rword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <p>The next three forms are <b>user/passB/passC/pass</b>, as all-empty, preuser(only), and preuser/pass</p>
- <form id="form7" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="qword">
- <input type="password" name="rword">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <form id="form8" action="formtest.js">
- <input type="text" name="uname" value="testuser">
- <input type="password" name="qword">
- <input type="password" name="rword">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <form id="form9" action="formtest.js">
- <input type="text" name="uname" value="testuser">
- <input type="password" name="qword">
- <input type="password" name="rword">
- <input type="password" name="pword" value="testpass">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: form fill, 3 password fields **/
-
-// Test to make sure 3-password forms are filled properly.
-
-function startTest() {
- // Check form 1
- is($_(1, "uname").value, "testuser", "Checking username 1");
- is($_(1, "pword").value, "testpass", "Checking password 1");
- is($_(1, "qword").value, "", "Checking password 1 (q)");
- is($_(1, "rword").value, "", "Checking password 1 (r)");
- // Check form 2
- is($_(2, "uname").value, "testuser", "Checking username 2");
- is($_(2, "pword").value, "testpass", "Checking password 2");
- is($_(2, "qword").value, "", "Checking password 2 (q)");
- is($_(2, "rword").value, "", "Checking password 2 (r)");
- // Check form 3
- is($_(3, "uname").value, "testuser", "Checking username 3");
- is($_(3, "pword").value, "testpass", "Checking password 3");
- is($_(3, "qword").value, "", "Checking password 3 (q)");
- is($_(3, "rword").value, "", "Checking password 3 (r)");
-
- // Check form 4
- is($_(4, "uname").value, "testuser", "Checking username 4");
- todo_is($_(4, "qword").value, "", "Checking password 4 (q)");
- todo_is($_(4, "pword").value, "testpass", "Checking password 4");
- is($_(4, "rword").value, "", "Checking password 4 (r)");
- // Check form 5
- is($_(5, "uname").value, "testuser", "Checking username 5");
- todo_is($_(5, "qword").value, "", "Checking password 5 (q)");
- todo_is($_(5, "pword").value, "testpass", "Checking password 5");
- is($_(5, "rword").value, "", "Checking password 5 (r)");
- // Check form 6
- is($_(6, "uname").value, "testuser", "Checking username 6");
- todo_is($_(6, "qword").value, "", "Checking password 6 (q)");
- is($_(6, "pword").value, "testpass", "Checking password 6");
- is($_(6, "rword").value, "", "Checking password 6 (r)");
-
- // Check form 7
- is($_(7, "uname").value, "testuser", "Checking username 7");
- todo_is($_(7, "qword").value, "", "Checking password 7 (q)");
- is($_(7, "rword").value, "", "Checking password 7 (r)");
- todo_is($_(7, "pword").value, "testpass", "Checking password 7");
- // Check form 8
- is($_(8, "uname").value, "testuser", "Checking username 8");
- todo_is($_(8, "qword").value, "", "Checking password 8 (q)");
- is($_(8, "rword").value, "", "Checking password 8 (r)");
- todo_is($_(8, "pword").value, "testpass", "Checking password 8");
- // Check form 9
- is($_(9, "uname").value, "testuser", "Checking username 9");
- todo_is($_(9, "qword").value, "", "Checking password 9 (q)");
- is($_(9, "rword").value, "", "Checking password 9 (r)");
- is($_(9, "pword").value, "testpass", "Checking password 9");
-
- // TODO: as with the 2-password cases, add tests to check for creating new
- // logins and changing passwords.
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_autocomplete.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_autocomplete.html
deleted file mode 100644
index 0eee8e696..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_autocomplete.html
+++ /dev/null
@@ -1,859 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test basic login autocomplete</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: multiple login autocomplete
-
-<script>
-var chromeScript = runChecksAfterCommonInit();
-
-var setupScript = runInParent(function setup() {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- // Create some logins just for this form, since we'll be deleting them.
- var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- assert.ok(nsLoginInfo != null, "nsLoginInfo constructor");
-
- // login0 has no username, so should be filtered out from the autocomplete list.
- var login0 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "", "user0pass", "", "pword");
-
- var login1 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "tempuser1", "temppass1", "uname", "pword");
-
- var login2 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser2", "testpass2", "uname", "pword");
-
- var login3 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser3", "testpass3", "uname", "pword");
-
- var login4 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "zzzuser4", "zzzpass4", "uname", "pword");
-
- // login 5 only used in the single-user forms
- var login5 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete2", null,
- "singleuser5", "singlepass5", "uname", "pword");
-
- var login6A = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete3", null,
- "form7user1", "form7pass1", "uname", "pword");
- var login6B = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete3", null,
- "form7user2", "form7pass2", "uname", "pword");
-
- var login7 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete4", null,
- "form8user", "form8pass", "uname", "pword");
-
- var login8A = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete5", null,
- "form9userAB", "form9pass", "uname", "pword");
- var login8B = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete5", null,
- "form9userAAB", "form9pass", "uname", "pword");
- var login8C = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete5", null,
- "form9userAABzz", "form9pass", "uname", "pword");
-
- var login10 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete7", null,
- "testuser10", "testpass10", "uname", "pword");
-
-
- // try/catch in case someone runs the tests manually, twice.
- try {
- Services.logins.addLogin(login0);
- Services.logins.addLogin(login1);
- Services.logins.addLogin(login2);
- Services.logins.addLogin(login3);
- Services.logins.addLogin(login4);
- Services.logins.addLogin(login5);
- Services.logins.addLogin(login6A);
- Services.logins.addLogin(login6B);
- Services.logins.addLogin(login7);
- Services.logins.addLogin(login8A);
- Services.logins.addLogin(login8B);
- // login8C is added later
- Services.logins.addLogin(login10);
- } catch (e) {
- assert.ok(false, "addLogin threw: " + e);
- }
-
- addMessageListener("addLogin", loginVariableName => {
- let login = eval(loginVariableName);
- assert.ok(!!login, "Login to add is defined: " + loginVariableName);
- Services.logins.addLogin(login);
- });
- addMessageListener("removeLogin", loginVariableName => {
- let login = eval(loginVariableName);
- assert.ok(!!login, "Login to delete is defined: " + loginVariableName);
- Services.logins.removeLogin(login);
- });
-});
-</script>
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
-
- <!-- form1 tests multiple matching logins -->
- <form id="form1" action="http://autocomplete:8888/formtest.js" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- other forms test single logins, with autocomplete=off set -->
- <form id="form2" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword" autocomplete="off">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form3" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname" autocomplete="off">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form4" action="http://autocomplete2" onsubmit="return false;" autocomplete="off">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form5" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname" autocomplete="off">
- <input type="password" name="pword" autocomplete="off">
- <button type="submit">Submit</button>
- </form>
-
- <!-- control -->
- <form id="form6" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- This form will be manipulated to insert a different username field. -->
- <form id="form7" action="http://autocomplete3" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- test for no autofill after onblur with blank username -->
- <form id="form8" action="http://autocomplete4" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- test autocomplete dropdown -->
- <form id="form9" action="http://autocomplete5" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- test for onUsernameInput recipe testing -->
- <form id="form11" action="http://autocomplete7" onsubmit="return false;">
- <input type="text" name="1">
- <input type="text" name="2">
- <button type="submit">Submit</button>
- </form>
-
- <!-- tests <form>-less autocomplete -->
- <div id="form12">
- <input type="text" name="uname" id="uname">
- <input type="password" name="pword" id="pword">
- <button type="submit">Submit</button>
- </div>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: multiple login autocomplete. **/
-
-var uname = $_(1, "uname");
-var pword = $_(1, "pword");
-const shiftModifier = SpecialPowers.Ci.nsIDOMEvent.SHIFT_MASK;
-
-// Restore the form to the default state.
-function restoreForm() {
- uname.value = "";
- pword.value = "";
- uname.focus();
-}
-
-// Check for expected username/password in form.
-function checkACForm(expectedUsername, expectedPassword) {
- var formID = uname.parentNode.id;
- is(uname.value, expectedUsername, "Checking " + formID + " username is: " + expectedUsername);
- is(pword.value, expectedPassword, "Checking " + formID + " password is: " + expectedPassword);
-}
-
-function sendFakeAutocompleteEvent(element) {
- var acEvent = document.createEvent("HTMLEvents");
- acEvent.initEvent("DOMAutoComplete", true, false);
- element.dispatchEvent(acEvent);
-}
-
-function spinEventLoop() {
- return Promise.resolve();
-}
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({"set": [["security.insecure_field_warning.contextual.enabled", false],
- ["signon.autofillForms.http", true]]});
- listenForUnexpectedPopupShown();
-});
-
-add_task(function* test_form1_initial_empty() {
- yield SimpleTest.promiseFocus(window);
-
- // Make sure initial form is empty.
- checkACForm("", "");
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is initially closed");
-});
-
-add_task(function* test_form1_menuitems() {
- yield SimpleTest.promiseFocus(window);
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- let results = yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- let expectedMenuItems = ["tempuser1",
- "testuser2",
- "testuser3",
- "zzzuser4"];
- checkArrayValues(results, expectedMenuItems, "Check all menuitems are displayed correctly.");
-
- checkACForm("", ""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield spinEventLoop(); // let focus happen
- checkACForm("", "");
-});
-
-add_task(function* test_form1_first_entry() {
- yield SimpleTest.promiseFocus(window);
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- doKey("down"); // first
- checkACForm("", ""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("tempuser1", "temppass1");
-});
-
-add_task(function* test_form1_second_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // first
- doKey("down"); // second
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_third_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // first
- doKey("down"); // second
- doKey("down"); // third
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser3", "testpass3");
-});
-
-add_task(function* test_form1_fourth_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // first
- doKey("down"); // second
- doKey("down"); // third
- doKey("down"); // fourth
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_wraparound_first_entry() {
- // Trigger autocomplete popup
- restoreForm();
- yield spinEventLoop(); // let focus happen
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // first
- doKey("down"); // second
- doKey("down"); // third
- doKey("down"); // fourth
- doKey("down"); // deselects
- doKey("down"); // first
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("tempuser1", "temppass1");
-});
-
-add_task(function* test_form1_wraparound_up_last_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("up"); // last (fourth)
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_wraparound_down_up_up() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // select first entry
- doKey("up"); // selects nothing!
- doKey("up"); // select last entry
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_wraparound_up_last() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down");
- doKey("up"); // deselects
- doKey("up"); // last entry
- doKey("up");
- doKey("up");
- doKey("up"); // first entry
- doKey("up"); // deselects
- doKey("up"); // last entry
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_fill_username_without_autofill_right() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Set first entry w/o triggering autocomplete
- doKey("down"); // first
- doKey("right");
- yield spinEventLoop();
- checkACForm("tempuser1", ""); // empty password
-});
-
-add_task(function* test_form1_fill_username_without_autofill_left() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Set first entry w/o triggering autocomplete
- doKey("down"); // first
- doKey("left");
- checkACForm("tempuser1", ""); // empty password
-});
-
-add_task(function* test_form1_pageup_first() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check first entry (page up)
- doKey("down"); // first
- doKey("down"); // second
- doKey("page_up"); // first
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("tempuser1", "temppass1");
-});
-
-add_task(function* test_form1_pagedown_last() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- /* test 13 */
- // Check last entry (page down)
- doKey("down"); // first
- doKey("page_down"); // last
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_untrusted_event() {
- restoreForm();
- yield spinEventLoop();
-
- // Send a fake (untrusted) event.
- checkACForm("", "");
- uname.value = "zzzuser4";
- sendFakeAutocompleteEvent(uname);
- yield spinEventLoop();
- checkACForm("zzzuser4", "");
-});
-
-add_task(function* test_form1_delete() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // XXX tried sending character "t" before/during dropdown to test
- // filtering, but had no luck. Seemed like the character was getting lost.
- // Setting uname.value didn't seem to work either. This works with a human
- // driver, so I'm not sure what's up.
-
- // Delete the first entry (of 4), "tempuser1"
- doKey("down");
- var numLogins;
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 5, "Correct number of logins before deleting one");
-
- let countChangedPromise = notifyMenuChanged(3);
- var deletionPromise = promiseStorageChanged(["removeLogin"]);
- // On OS X, shift-backspace and shift-delete work, just delete does not.
- // On Win/Linux, shift-backspace does not work, delete and shift-delete do.
- doKey("delete", shiftModifier);
- yield deletionPromise;
-
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 4, "Correct number of logins after deleting one");
- yield countChangedPromise;
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_first_after_deletion() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check the new first entry (of 3)
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_delete_second() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Delete the second entry (of 3), "testuser3"
- doKey("down");
- doKey("down");
- doKey("delete", shiftModifier);
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 3, "Correct number of logins after deleting one");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_first_after_deletion2() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check the new first entry (of 2)
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_delete_last() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- /* test 54 */
- // Delete the last entry (of 2), "zzzuser4"
- doKey("down");
- doKey("down");
- doKey("delete", shiftModifier);
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 2, "Correct number of logins after deleting one");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_first_after_3_deletions() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check the only remaining entry
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_check_only_entry_remaining() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- /* test 56 */
- // Delete the only remaining entry, "testuser2"
- doKey("down");
- doKey("delete", shiftModifier);
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 1, "Correct number of logins after deleting one");
-
- // remove the login that's not shown in the list.
- setupScript.sendSyncMessage("removeLogin", "login0");
-});
-
-/* Tests for single-user forms for ignoring autocomplete=off */
-add_task(function* test_form2() {
- // Turn our attention to form2
- uname = $_(2, "uname");
- pword = $_(2, "pword");
- checkACForm("singleuser5", "singlepass5");
-
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form3() {
- uname = $_(3, "uname");
- pword = $_(3, "pword");
- checkACForm("singleuser5", "singlepass5");
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form4() {
- uname = $_(4, "uname");
- pword = $_(4, "pword");
- checkACForm("singleuser5", "singlepass5");
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form5() {
- uname = $_(5, "uname");
- pword = $_(5, "pword");
- checkACForm("singleuser5", "singlepass5");
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form6() {
- // (this is a control, w/o autocomplete=off, to ensure the login
- // that was being suppressed would have been filled in otherwise)
- uname = $_(6, "uname");
- pword = $_(6, "pword");
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form6_changeUsername() {
- // Test that the password field remains filled in after changing
- // the username.
- uname.focus();
- doKey("right");
- sendChar("X");
- // Trigger the 'blur' event on uname
- pword.focus();
- yield spinEventLoop();
- checkACForm("singleuser5X", "singlepass5");
-
- setupScript.sendSyncMessage("removeLogin", "login5");
-});
-
-add_task(function* test_form7() {
- uname = $_(7, "uname");
- pword = $_(7, "pword");
- checkACForm("", "");
-
- // Insert a new username field into the form. We'll then make sure
- // that invoking the autocomplete doesn't try to fill the form.
- var newField = document.createElement("input");
- newField.setAttribute("type", "text");
- newField.setAttribute("name", "uname2");
- pword.parentNode.insertBefore(newField, pword);
- is($_(7, "uname2").value, "", "Verifying empty uname2");
-
- // Delete login6B. It was created just to prevent filling in a login
- // automatically, removing it makes it more likely that we'll catch a
- // future regression with form filling here.
- setupScript.sendSyncMessage("removeLogin", "login6B");
-});
-
-add_task(function* test_form7_2() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- // The form changes, so we expect the old username field to get the
- // selected autocomplete value, but neither the new username field nor
- // the password field should have any values filled in.
- yield spinEventLoop();
- checkACForm("form7user1", "");
- is($_(7, "uname2").value, "", "Verifying empty uname2");
- restoreForm(); // clear field, so reloading test doesn't fail
-
- setupScript.sendSyncMessage("removeLogin", "login6A");
-});
-
-add_task(function* test_form8() {
- uname = $_(8, "uname");
- pword = $_(8, "pword");
- checkACForm("form8user", "form8pass");
- restoreForm();
-});
-
-add_task(function* test_form8_blur() {
- checkACForm("", "");
- // Focus the previous form to trigger a blur.
- $_(7, "uname").focus();
-});
-
-add_task(function* test_form8_2() {
- checkACForm("", "");
- restoreForm();
-});
-
-add_task(function* test_form8_3() {
- checkACForm("", "");
- setupScript.sendSyncMessage("removeLogin", "login7");
-});
-
-add_task(function* test_form9_filtering() {
- // Turn our attention to form9 to test the dropdown - bug 497541
- uname = $_(9, "uname");
- pword = $_(9, "pword");
- uname.focus();
- let shownPromise = promiseACShown();
- sendString("form9userAB");
- yield shownPromise;
-
- checkACForm("form9userAB", "");
- uname.focus();
- doKey("left");
- shownPromise = promiseACShown();
- sendChar("A");
- let results = yield shownPromise;
-
- checkACForm("form9userAAB", "");
- checkArrayValues(results, ["form9userAAB"], "Check dropdown is updated after inserting 'A'");
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("form9userAAB", "form9pass");
-});
-
-add_task(function* test_form9_autocomplete_cache() {
- // Note that this addLogin call will only be seen by the autocomplete
- // attempt for the sendChar if we do not successfully cache the
- // autocomplete results.
- setupScript.sendSyncMessage("addLogin", "login8C");
- uname.focus();
- let promise0 = notifyMenuChanged(0);
- sendChar("z");
- yield promise0;
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup shouldn't open");
-
- // check that empty results are cached - bug 496466
- promise0 = notifyMenuChanged(0);
- sendChar("z");
- yield promise0;
- popupState = yield getPopupState();
- is(popupState.open, false, "Check popup stays closed due to cached empty result");
-});
-
-add_task(function* test_form11_recipes() {
- yield loadRecipes({
- siteRecipes: [{
- "hosts": ["mochi.test:8888"],
- "usernameSelector": "input[name='1']",
- "passwordSelector": "input[name='2']"
- }],
- });
- uname = $_(11, "1");
- pword = $_(11, "2");
-
- // First test DOMAutocomplete
- // Switch the password field to type=password so _fillForm marks the username
- // field for autocomplete.
- pword.type = "password";
- yield promiseFormsProcessed();
- restoreForm();
- checkACForm("", "");
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("testuser10", "testpass10");
-
- // Now test recipes with blur on the username field.
- restoreForm();
- checkACForm("", "");
- uname.value = "testuser10";
- checkACForm("testuser10", "");
- doKey("tab");
- yield promiseFormsProcessed();
- checkACForm("testuser10", "testpass10");
- yield resetRecipes();
-});
-
-add_task(function* test_form12_formless() {
- // Test form-less autocomplete
- uname = $_(12, "uname");
- pword = $_(12, "pword");
- restoreForm();
- checkACForm("", "");
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Trigger autocomplete
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- let processedPromise = promiseFormsProcessed();
- doKey("return"); // not "enter"!
- yield processedPromise;
- checkACForm("testuser", "testpass");
-});
-
-add_task(function* test_form12_open_on_trusted_focus() {
- uname = $_(12, "uname");
- pword = $_(12, "pword");
- uname.value = "";
- pword.value = "";
-
- // Move focus to the password field so we can test the first click on the
- // username field.
- pword.focus();
- checkACForm("", "");
- const firePrivEventPromise = new Promise((resolve) => {
- uname.addEventListener("click", (e) => {
- ok(e.isTrusted, "Ensure event is trusted");
- resolve();
- });
- });
- const shownPromise = promiseACShown();
- synthesizeMouseAtCenter(uname, {});
- yield firePrivEventPromise;
- yield shownPromise;
- doKey("down");
- const processedPromise = promiseFormsProcessed();
- doKey("return"); // not "enter"!
- yield processedPromise;
- checkACForm("testuser", "testpass");
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_html5.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_html5.html
deleted file mode 100644
index 40e322afd..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_html5.html
+++ /dev/null
@@ -1,164 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for html5 input types (email, tel, url, etc.)</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: html5 input types (email, tel, url, etc.)
-<script>
-runChecksAfterCommonInit(() => startTest());
-
-runInParent(function setup() {
- const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
- let pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
-
- login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login3 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login4 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
- login1.init("http://mochi.test:8888", "http://bug600551-1", null,
- "testuser@example.com", "testpass1", "", "");
- login2.init("http://mochi.test:8888", "http://bug600551-2", null,
- "555-555-5555", "testpass2", "", "");
- login3.init("http://mochi.test:8888", "http://bug600551-3", null,
- "http://mozilla.org", "testpass3", "", "");
- login4.init("http://mochi.test:8888", "http://bug600551-4", null,
- "123456789", "testpass4", "", "");
-
- pwmgr.addLogin(login1);
- pwmgr.addLogin(login2);
- pwmgr.addLogin(login3);
- pwmgr.addLogin(login4);
-});
-</script>
-
-<p id="display"></p>
-<div id="content" style="display: none">
-
- <form id="form1" action="http://bug600551-1">
- <input type="email" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form2" action="http://bug600551-2">
- <input type="tel" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form3" action="http://bug600551-3">
- <input type="url" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form4" action="http://bug600551-4">
- <input type="number" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- The following forms should not be filled with usernames -->
- <form id="form5" action="formtest.js">
- <input type="search" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form6" action="formtest.js">
- <input type="datetime" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form7" action="formtest.js">
- <input type="date" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form8" action="formtest.js">
- <input type="month" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form9" action="formtest.js">
- <input type="week" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form10" action="formtest.js">
- <input type="time" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form11" action="formtest.js">
- <input type="datetime-local" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form12" action="formtest.js">
- <input type="range" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form13" action="formtest.js">
- <input type="color" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/* Test for Login Manager: 600551
- (Password manager not working with input type=email)
- */
-function startTest() {
- checkForm(1, "testuser@example.com", "testpass1");
- checkForm(2, "555-555-5555", "testpass2");
- checkForm(3, "http://mozilla.org", "testpass3");
- checkForm(4, "123456789", "testpass4");
-
- is($_(5, "uname").value, "", "type=search should not be considered a username");
-
- is($_(6, "uname").value, "", "type=datetime should not be considered a username");
-
- is($_(7, "uname").value, "", "type=date should not be considered a username");
-
- is($_(8, "uname").value, "", "type=month should not be considered a username");
-
- is($_(9, "uname").value, "", "type=week should not be considered a username");
-
- is($_(10, "uname").value, "", "type=time should not be considered a username");
-
- is($_(11, "uname").value, "", "type=datetime-local should not be considered a username");
-
- is($_(12, "uname").value, "50", "type=range should not be considered a username");
-
- is($_(13, "uname").value, "#000000", "type=color should not be considered a username");
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwevent.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwevent.html
deleted file mode 100644
index e0a2883c8..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwevent.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=355063
--->
-<head>
- <meta charset="utf-8"/>
- <title>Test for Bug 355063</title>
- <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="application/javascript">
- /** Test for Bug 355063 **/
-
- runChecksAfterCommonInit(function startTest() {
- info("startTest");
- // Password Manager's own listener should always have been added first, so
- // the test's listener should be called after the pwmgr's listener fills in
- // a login.
- //
- SpecialPowers.addChromeEventListener("DOMFormHasPassword", function eventFired() {
- SpecialPowers.removeChromeEventListener("DOMFormHasPassword", eventFired);
- var passField = $("p1");
- passField.addEventListener("input", checkForm);
- });
- addForm();
- });
-
- function addForm() {
- info("addForm");
- var c = document.getElementById("content");
- c.innerHTML = "<form id=form1>form1: <input id=u1><input type=password id=p1></form><br>";
- }
-
- function checkForm() {
- info("checkForm");
- var userField = document.getElementById("u1");
- var passField = document.getElementById("p1");
- is(userField.value, "testuser", "checking filled username");
- is(passField.value, "testpass", "checking filled password");
-
- SimpleTest.finish();
- }
-</script>
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=355063">Mozilla Bug 355063</a>
-<p id="display"></p>
-<div id="content">
-forms go here!
-</div>
-<pre id="test">
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwonly.html b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwonly.html
deleted file mode 100644
index 40fec8c46..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwonly.html
+++ /dev/null
@@ -1,213 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test forms and logins without a username</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: forms and logins without a username.
-<script>
-runChecksAfterCommonInit(() => startTest());
-runInParent(() => {
- const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
- var pwmgr = Cc["@mozilla.org/login-manager;1"]
- .getService(Ci.nsILoginManager);
-
- var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo);
-
- // pwlogin1 uses a unique formSubmitURL, to check forms where no other logins
- // will apply. pwlogin2 uses the normal formSubmitURL, so that we can test
- // forms with a mix of username and non-username logins that might apply.
- //
- // Note: pwlogin2 is deleted at the end of the test.
-
- pwlogin1 = new nsLoginInfo();
- pwlogin2 = new nsLoginInfo();
-
- pwlogin1.init("http://mochi.test:8888", "http://mochi.test:1111", null,
- "", "1234", "uname", "pword");
-
- pwlogin2.init("http://mochi.test:8888", "http://mochi.test:8888", null,
- "", "1234", "uname", "pword");
-
-
- pwmgr.addLogin(pwlogin1);
- pwmgr.addLogin(pwlogin2);
-});
-</script>
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
-
-<!-- simple form: no username field, 1 password field -->
-<form id='form1' action='http://mochi.test:1111/formtest.js'> 1
- <input type='password' name='pname' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- simple form: no username field, 2 password fields -->
-<form id='form2' action='http://mochi.test:1111/formtest.js'> 2
- <input type='password' name='pname1' value=''>
- <input type='password' name='pname2' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- simple form: no username field, 3 password fields -->
-<form id='form3' action='http://mochi.test:1111/formtest.js'> 3
- <input type='password' name='pname1' value=''>
- <input type='password' name='pname2' value=''>
- <input type='password' name='pname3' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- 4 password fields, should be ignored. -->
-<form id='form4' action='http://mochi.test:1111/formtest.js'> 4
- <input type='password' name='pname1' value=''>
- <input type='password' name='pname2' value=''>
- <input type='password' name='pname3' value=''>
- <input type='password' name='pname4' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-
-
-<!-- 1 username field -->
-<form id='form5' action='http://mochi.test:1111/formtest.js'> 5
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-
-<!-- 1 username field, with a value set -->
-<form id='form6' action='http://mochi.test:1111/formtest.js'> 6
- <input type='text' name='uname' value='someuser'>
- <input type='password' name='pname' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-
-
-<!--
-(The following forms have 2 potentially-matching logins, on is
-password-only, the other is username+password)
--->
-
-
-
-<!-- 1 username field, with value set. Fill in the matching U+P login -->
-<form id='form7' action='formtest.js'> 7
- <input type='text' name='uname' value='testuser'>
- <input type='password' name='pname' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- 1 username field, with value set. Don't fill in U+P login-->
-<form id='form8' action='formtest.js'> 8
- <input type='text' name='uname' value='someuser'>
- <input type='password' name='pname' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-
-
-<!-- 1 username field, too small for U+P login -->
-<form id='form9' action='formtest.js'> 9
- <input type='text' name='uname' value='' maxlength="4">
- <input type='password' name='pname' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- 1 username field, too small for U+P login -->
-<form id='form10' action='formtest.js'> 10
- <input type='text' name='uname' value='' maxlength="0">
- <input type='password' name='pname' value=''>
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- 1 username field, too small for U+P login -->
-<form id='form11' action='formtest.js'> 11
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='' maxlength="4">
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- 1 username field, too small for either login -->
-<form id='form12' action='formtest.js'> 12
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='' maxlength="1">
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-<!-- 1 username field, too small for either login -->
-<form id='form13' action='formtest.js'> 13
- <input type='text' name='uname' value=''>
- <input type='password' name='pname' value='' maxlength="0">
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: password-only logins **/
-function startTest() {
-
- checkForm(1, "1234");
- checkForm(2, "1234", "");
- checkForm(3, "1234", "", "");
- checkUnmodifiedForm(4);
-
- checkForm(5, "", "1234");
- checkForm(6, "someuser", "");
-
- checkForm(7, "testuser", "testpass");
- checkForm(8, "someuser", "");
-
- checkForm(9, "", "1234");
- checkForm(10, "", "1234");
- checkForm(11, "", "1234");
-
- checkUnmodifiedForm(12);
- checkUnmodifiedForm(13);
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_bug_627616.html b/toolkit/components/passwordmgr/test/mochitest/test_bug_627616.html
deleted file mode 100644
index ad4a41cdb..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_bug_627616.html
+++ /dev/null
@@ -1,145 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test bug 627616 related to proxy authentication</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script class="testbody" type="text/javascript">
- SimpleTest.waitForExplicitFinish();
-
- var Ci = SpecialPowers.Ci;
-
- function makeXHR(expectedStatus, expectedText, extra) {
- var xhr = new XMLHttpRequest();
- xhr.open("GET", "authenticate.sjs?" +
- "proxy_user=proxy_user&" +
- "proxy_pass=proxy_pass&" +
- "proxy_realm=proxy_realm&" +
- "user=user1name&" +
- "pass=user1pass&" +
- "realm=mochirealm&" +
- extra || "");
- xhr.onloadend = function() {
- is(xhr.status, expectedStatus, "xhr.status");
- is(xhr.statusText, expectedText, "xhr.statusText");
- runNextTest();
- };
- return xhr;
- }
-
- function testNonAnonymousCredentials() {
- var xhr = makeXHR(200, "OK");
- xhr.send();
- }
-
- function testAnonymousCredentials() {
- // Test that an anonymous request correctly performs proxy authentication
- var xhr = makeXHR(401, "Authentication required");
- SpecialPowers.wrap(xhr).channel.loadFlags |= Ci.nsIChannel.LOAD_ANONYMOUS;
- xhr.send();
- }
-
- function testAnonymousNoAuth() {
- // Next, test that an anonymous request still does not include any non-proxy
- // authentication headers.
- var xhr = makeXHR(200, "Authorization header not found", "anonymous=1");
- SpecialPowers.wrap(xhr).channel.loadFlags |= Ci.nsIChannel.LOAD_ANONYMOUS;
- xhr.send();
- }
-
- var gExpectedDialogs = 0;
- var gCurrentTest;
- function runNextTest() {
- is(gExpectedDialogs, 0, "received expected number of auth dialogs");
- mm.sendAsyncMessage("prepareForNextTest");
- mm.addMessageListener("prepareForNextTestDone", function prepared(msg) {
- mm.removeMessageListener("prepareForNextTestDone", prepared);
- if (pendingTests.length > 0) {
- ({expectedDialogs: gExpectedDialogs,
- test: gCurrentTest} = pendingTests.shift());
- gCurrentTest.call(this);
- } else {
- mm.sendAsyncMessage("cleanup");
- mm.addMessageListener("cleanupDone", () => {
- // mm.destroy() is called as a cleanup function by runInParent(), no
- // need to do it here.
- SimpleTest.finish();
- });
- }
- });
- }
-
- var pendingTests = [{expectedDialogs: 2, test: testNonAnonymousCredentials},
- {expectedDialogs: 1, test: testAnonymousCredentials},
- {expectedDialogs: 0, test: testAnonymousNoAuth}];
-
- let mm = runInParent(() => {
- const { classes: parentCc, interfaces: parentCi, utils: parentCu } = Components;
-
- parentCu.import("resource://gre/modules/Services.jsm");
- parentCu.import("resource://gre/modules/NetUtil.jsm");
- parentCu.import("resource://gre/modules/Timer.jsm");
- parentCu.import("resource://gre/modules/XPCOMUtils.jsm");
-
- let channel = NetUtil.newChannel({
- uri: "http://example.com",
- loadUsingSystemPrincipal: true
- });
-
- let pps = parentCc["@mozilla.org/network/protocol-proxy-service;1"].
- getService(parentCi.nsIProtocolProxyService);
- pps.asyncResolve(channel, 0, {
- onProxyAvailable(req, uri, pi, status) {
- let mozproxy = "moz-proxy://" + pi.host + ":" + pi.port;
- let login = parentCc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(parentCi.nsILoginInfo);
- login.init(mozproxy, null, "proxy_realm", "proxy_user", "proxy_pass",
- "", "");
- Services.logins.addLogin(login);
-
- let login2 = parentCc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(parentCi.nsILoginInfo);
- login2.init("http://mochi.test:8888", null, "mochirealm", "user1name",
- "user1pass", "", "");
- Services.logins.addLogin(login2);
-
- sendAsyncMessage("setupDone");
- },
- QueryInterface: XPCOMUtils.generateQI([parentCi.nsIProtocolProxyCallback]),
- });
-
- addMessageListener("prepareForNextTest", message => {
- parentCc["@mozilla.org/network/http-auth-manager;1"].
- getService(parentCi.nsIHttpAuthManager).
- clearAll();
- sendAsyncMessage("prepareForNextTestDone");
- });
-
- let dialogObserverTopic = "common-dialog-loaded";
-
- function dialogObserver(subj, topic, data) {
- subj.Dialog.ui.prompt.document.documentElement.acceptDialog();
- sendAsyncMessage("promptAccepted");
- }
-
- Services.obs.addObserver(dialogObserver, dialogObserverTopic, false);
-
- addMessageListener("cleanup", message => {
- Services.obs.removeObserver(dialogObserver, dialogObserverTopic);
- sendAsyncMessage("cleanupDone");
- });
- });
-
- mm.addMessageListener("promptAccepted", msg => {
- gExpectedDialogs--;
- });
- mm.addMessageListener("setupDone", msg => {
- runNextTest();
- });
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_bug_776171.html b/toolkit/components/passwordmgr/test/mochitest/test_bug_776171.html
deleted file mode 100644
index 4ad08bee2..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_bug_776171.html
+++ /dev/null
@@ -1,56 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=776171
--->
-<head>
- <meta charset="utf-8">
- <title>Test for Bug 776171 related to HTTP auth</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body onload="startTest()">
-<script class="testbody" type="text/javascript">
-
-/**
- * This test checks we correctly ignore authentication entry
- * for a subpath and use creds from the URL when provided when XHR
- * is used with filled user name and password.
- *
- * 1. connect auth2/authenticate.sjs that expects user1:pass1 password
- * 2. connect a dummy URL at the same path
- * 3. connect authenticate.sjs that again expects user1:pass1 password
- * in this case, however, we have an entry without an identity
- * for this path (that is a parent for auth2 path in the first step)
- */
-
-SimpleTest.waitForExplicitFinish();
-
-function doxhr(URL, user, pass, next) {
- var xhr = new XMLHttpRequest();
- if (user && pass)
- xhr.open("POST", URL, true, user, pass);
- else
- xhr.open("POST", URL, true);
- xhr.onload = function() {
- is(xhr.status, 200, "Got status 200");
- next();
- };
- xhr.onerror = function() {
- ok(false, "request passed");
- finishTest();
- };
- xhr.send();
-}
-
-function startTest() {
- doxhr("auth2/authenticate.sjs?user=user1&pass=pass1&realm=realm1", "user1", "pass1", function() {
- doxhr("auth2", null, null, function() {
- doxhr("authenticate.sjs?user=user1&pass=pass1&realm=realm1", "user1", "pass1", SimpleTest.finish);
- });
- });
-}
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_case_differences.html b/toolkit/components/passwordmgr/test/mochitest/test_case_differences.html
deleted file mode 100644
index 316f59da7..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_case_differences.html
+++ /dev/null
@@ -1,147 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test autocomplete due to multiple matching logins</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: autocomplete due to multiple matching logins
-
-<script>
-runChecksAfterCommonInit(false);
-
-SpecialPowers.loadChromeScript(function addLogins() {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- // Create some logins just for this form, since we'll be deleting them.
- var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-
- var login0 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "name", "pass", "uname", "pword");
-
- var login1 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "Name", "Pass", "uname", "pword");
-
- var login2 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "USER", "PASS", "uname", "pword");
-
- try {
- Services.logins.addLogin(login0);
- Services.logins.addLogin(login1);
- Services.logins.addLogin(login2);
- } catch (e) {
- assert.ok(false, "addLogin threw: " + e);
- }
-});
-</script>
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
-
- <!-- form1 tests multiple matching logins -->
- <form id="form1" action="http://autocomplete:8888/formtest.js" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: autocomplete due to multiple matching logins **/
-
-var uname = $_(1, "uname");
-var pword = $_(1, "pword");
-
-// Restore the form to the default state.
-function restoreForm() {
- uname.value = "";
- pword.value = "";
- uname.focus();
-}
-
-// Check for expected username/password in form.
-function checkACForm(expectedUsername, expectedPassword) {
- var formID = uname.parentNode.id;
- is(uname.value, expectedUsername, "Checking " + formID + " username");
- is(pword.value, expectedPassword, "Checking " + formID + " password");
-}
-
-add_task(function* test_empty_first_entry() {
- /* test 1 */
- // Make sure initial form is empty.
- checkACForm("", "");
- // Trigger autocomplete popup
- restoreForm();
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is initially closed");
- let shownPromise = promiseACShown();
- doKey("down");
- let results = yield shownPromise;
- popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected");
- checkArrayValues(results, ["name", "Name", "USER"], "initial");
-
- // Check first entry
- let index0Promise = notifySelectedIndex(0);
- doKey("down");
- yield index0Promise;
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("name", "pass");
-});
-
-add_task(function* test_empty_second_entry() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
- doKey("down"); // first
- doKey("down"); // second
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("Name", "Pass");
-});
-
-add_task(function* test_empty_third_entry() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
- doKey("down"); // first
- doKey("down"); // second
- doKey("down"); // third
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("USER", "PASS");
-});
-
-add_task(function* test_preserve_matching_username_case() {
- restoreForm();
- uname.value = "user";
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check that we don't clobber user-entered text when tabbing away
- // (even with no autocomplete entry selected)
- doKey("tab");
- yield promiseFormsProcessed();
- checkACForm("user", "PASS");
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_form_action_1.html b/toolkit/components/passwordmgr/test/mochitest/test_form_action_1.html
deleted file mode 100644
index 430081b3a..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_form_action_1.html
+++ /dev/null
@@ -1,137 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for considering form action</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: Bug 360493
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-<div id="content" style="display: none">
-
- <!-- normal form with normal relative action. -->
- <form id="form1" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- fully specify the action URL -->
- <form id="form2" action="http://mochi.test:8888/tests/toolkit/components/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- fully specify the action URL, and change the path -->
- <form id="form3" action="http://mochi.test:8888/zomg/wtf/bbq/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- fully specify the action URL, and change the path and filename -->
- <form id="form4" action="http://mochi.test:8888/zomg/wtf/bbq/passwordmgr/test/not_a_test.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- specify the action URL relative to the current document-->
- <form id="form5" action="./formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- specify the action URL relative to the current server -->
- <form id="form6" action="/tests/toolkit/components/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Change the method from get to post -->
- <form id="form7" action="formtest.js" method="POST">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Blank action URL specified -->
- <form id="form8" action="">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- |action| attribute entirely missing -->
- <form id="form9" >
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- action url as javascript -->
- <form id="form10" action="javascript:alert('this form is not submitted so this alert should not be invoked');">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- TODO: action=IP.ADDRESS instead of HOSTNAME? -->
- <!-- TODO: test with |base href="http://othersite//"| ? -->
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: 360493 (Cross-Site Forms + Password
- Manager = Security Failure) **/
-
-// This test is designed to make sure variations on the form's |action|
-// and |method| continue to work with the fix for 360493.
-
-function startTest() {
- for (var i = 1; i <= 9; i++) {
- // Check form i
- is($_(i, "uname").value, "testuser", "Checking for filled username " + i);
- is($_(i, "pword").value, "testpass", "Checking for filled password " + i);
- }
-
- // The login's formSubmitURL isn't "javascript:", so don't fill it in.
- isnot($_(10, "uname"), "testuser", "Checking username w/ JS action URL");
- isnot($_(10, "pword"), "testpass", "Checking password w/ JS action URL");
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_form_action_2.html b/toolkit/components/passwordmgr/test/mochitest/test_form_action_2.html
deleted file mode 100644
index 0f0056de0..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_form_action_2.html
+++ /dev/null
@@ -1,170 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for considering form action</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: Bug 360493
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-<div id="content" style="display: none">
-
- <!-- The tests in this page exercise things that shouldn't work. -->
-
- <!-- Change port # of action URL from 8888 to 7777 -->
- <form id="form1" action="http://localhost:7777/tests/toolkit/components/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- No port # in action URL -->
- <form id="form2" action="http://localhost/tests/toolkit/components/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Change protocol from http:// to ftp://, include the expected 8888 port # -->
- <form id="form3" action="ftp://localhost:8888/tests/toolkit/components/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Change protocol from http:// to ftp://, no port # specified -->
- <form id="form4" action="ftp://localhost/tests/toolkit/components/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Try a weird URL. -->
- <form id="form5" action="about:blank">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Try a weird URL. (If the normal embedded action URL doesn't work, that should mean other URLs won't either) -->
- <form id="form6" action="view-source:http://localhost:8888/tests/toolkit/components/passwordmgr/test/formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Try a weird URL. -->
- <form id="form7" action="view-source:formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Action URL points to a different host (this is the archetypical exploit) -->
- <form id="form8" action="http://www.cnn.com/">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Action URL points to a different host, user field prefilled -->
- <form id="form9" action="http://www.cnn.com/">
- <input type="text" name="uname" value="testuser">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- Try wrapping a evil form around a good form, to see if we can confuse the parser. -->
- <form id="form10-A" action="http://www.cnn.com/">
- <form id="form10-B" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit (inner)</button>
- <button type="reset"> Reset (inner)</button>
- </form>
- <button type="submit" id="neutered_submit10">Submit (outer)</button>
- <button type="reset">Reset (outer)</button>
- </form>
-
- <!-- Try wrapping a good form around an evil form, to see if we can confuse the parser. -->
- <form id="form11-A" action="formtest.js">
- <form id="form11-B" action="http://www.cnn.com/">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit (inner)</button>
- <button type="reset"> Reset (inner)</button>
- </form>
- <button type="submit" id="neutered_submit11">Submit (outer)</button>
- <button type="reset">Reset (outer)</button>
- </form>
-
-<!-- TODO: probably should have some accounts which have no port # in the action url. JS too. And different host/proto. -->
-<!-- TODO: www.site.com vs. site.com? -->
-<!-- TODO: foo.site.com vs. bar.site.com? -->
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: 360493 (Cross-Site Forms + Password Manager = Security Failure) **/
-
-function startTest() {
- for (var i = 1; i <= 8; i++) {
- // Check form i
- is($_(i, "uname").value, "", "Checking for unfilled username " + i);
- is($_(i, "pword").value, "", "Checking for unfilled password " + i);
- }
-
- is($_(9, "uname").value, "testuser", "Checking for unmodified username 9");
- is($_(9, "pword").value, "", "Checking for unfilled password 9");
-
- is($_("10-A", "uname").value, "", "Checking for unfilled username 10A");
- is($_("10-A", "pword").value, "", "Checking for unfilled password 10A");
-
- // The DOM indicates this form could be filled, as the evil inner form
- // is discarded. And yet pwmgr seems not to fill it. Not sure why.
- todo(false, "Mangled form combo not being filled when maybe it could be?");
- is($_("11-A", "uname").value, "testuser", "Checking filled username 11A");
- is($_("11-A", "pword").value, "testpass", "Checking filled password 11A");
-
- // Verify this by making sure there are no extra forms in the document, and
- // that the submit button for the neutered forms don't do anything.
- // If the test finds extra forms the submit() causes the test to timeout, then
- // there may be a security issue.
- is(document.forms.length, 11, "Checking for unexpected forms");
- $("neutered_submit10").click();
- $("neutered_submit11").click();
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_form_action_javascript.html b/toolkit/components/passwordmgr/test/mochitest/test_form_action_javascript.html
deleted file mode 100644
index d37e92c40..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_form_action_javascript.html
+++ /dev/null
@@ -1,52 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test forms with a JS submit action</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: form with JS submit action
-<script>
-runChecksAfterCommonInit(() => startTest());
-
-runInParent(function setup() {
- const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- let jslogin = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo);
- jslogin.init("http://mochi.test:8888", "javascript:", null,
- "jsuser", "jspass123", "uname", "pword");
- Services.logins.addLogin(jslogin);
-});
-
-/** Test for Login Manager: JS action URL **/
-
-function startTest() {
- checkForm(1, "jsuser", "jspass123");
-
- SimpleTest.finish();
-}
-</script>
-
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
-
-<form id='form1' action='javascript:alert("never shows")'> 1
- <input name="uname">
- <input name="pword" type="password">
-
- <button type='submit'>Submit</button>
- <button type='reset'> Reset </button>
-</form>
-
-</div>
-
-<pre id="test"></pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_formless_autofill.html b/toolkit/components/passwordmgr/test/mochitest/test_formless_autofill.html
deleted file mode 100644
index 6263c818d..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_formless_autofill.html
+++ /dev/null
@@ -1,147 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test autofilling of fields outside of a form</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script type="application/javascript;version=1.8">
-let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-document.addEventListener("DOMContentLoaded", () => {
- document.getElementById("loginFrame").addEventListener("load", (evt) => {
- // Tell the parent to setup test logins.
- chromeScript.sendAsyncMessage("setupParent", { selfFilling: true });
- });
-});
-
-let doneSetupPromise = new Promise(resolve => {
- // When the setup is done, load a recipe for this test.
- chromeScript.addMessageListener("doneSetup", function doneSetup() {
- resolve();
- });
-});
-
-add_task(function* setup() {
- info("Waiting for loads and setup");
- yield doneSetupPromise;
-
- yield loadRecipes({
- siteRecipes: [{
- hosts: ["mochi.test:8888"],
- usernameSelector: "input[name='recipeuname']",
- passwordSelector: "input[name='recipepword']",
- }],
- });
-});
-
-
-const DEFAULT_ORIGIN = "http://mochi.test:8888";
-const TESTCASES = [
- {
- // Inputs
- document: `<input type=password>`,
-
- // Expected outputs
- expectedInputValues: ["testpass"],
- },
- {
- document: `<input>
- <input type=password>`,
- expectedInputValues: ["testuser", "testpass"],
- },
- {
- document: `<input>
- <input type=password>
- <input type=password>`,
- expectedInputValues: ["testuser", "testpass", ""],
- },
- {
- document: `<input>
- <input type=password>
- <input type=password>
- <input type=password>`,
- expectedInputValues: ["testuser", "testpass", "", ""],
- },
- {
- document: `<input>
- <input type=password form="form1">
- <input type=password>
- <form id="form1">
- <input>
- <input type=password>
- </form>`,
- expectedFormCount: 2,
- expectedInputValues: ["testuser", "testpass", "testpass", "", ""],
- },
- {
- document: `<!-- formless password field selector recipe test -->
- <input>
- <input type=password>
- <input>
- <input type=password name="recipepword">`,
- expectedInputValues: ["", "", "testuser", "testpass"],
- },
- {
- document: `<!-- formless username and password field selector recipe test -->
- <input name="recipeuname">
- <input>
- <input type=password>
- <input type=password name="recipepword">`,
- expectedInputValues: ["testuser", "", "", "testpass"],
- },
- {
- document: `<!-- form and formless recipe field selector test -->
- <input name="recipeuname">
- <input>
- <input type=password form="form1"> <!-- not filled since recipe affects both FormLikes -->
- <input type=password>
- <input type=password name="recipepword">
- <form id="form1">
- <input>
- <input type=password>
- </form>`,
- expectedFormCount: 2,
- expectedInputValues: ["testuser", "", "", "", "testpass", "", ""],
- },
-];
-
-add_task(function* test() {
- let loginFrame = document.getElementById("loginFrame");
- let frameDoc = loginFrame.contentWindow.document;
-
- for (let tc of TESTCASES) {
- info("Starting testcase: " + JSON.stringify(tc));
-
- let numFormLikesExpected = tc.expectedFormCount || 1;
-
- let processedFormPromise = promiseFormsProcessed(numFormLikesExpected);
-
- frameDoc.documentElement.innerHTML = tc.document;
- info("waiting for " + numFormLikesExpected + " processed form(s)");
- yield processedFormPromise;
-
- let testInputs = frameDoc.documentElement.querySelectorAll("input");
- is(testInputs.length, tc.expectedInputValues.length, "Check number of inputs");
- for (let i = 0; i < tc.expectedInputValues.length; i++) {
- let expectedValue = tc.expectedInputValues[i];
- is(testInputs[i].value, expectedValue,
- "Check expected input value " + i + ": " + expectedValue);
- }
- }
-});
-
-</script>
-
-<p id="display"></p>
-
-<div id="content">
- <iframe id="loginFrame" src="http://mochi.test:8888/tests/toolkit/components/passwordmgr/test/blank.html"></iframe>
-</div>
-<pre id="test"></pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_formless_submit.html b/toolkit/components/passwordmgr/test/mochitest/test_formless_submit.html
deleted file mode 100644
index 468da1e7f..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_formless_submit.html
+++ /dev/null
@@ -1,183 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test capturing of fields outside of a form</title>
- <script src="/tests/SimpleTest/SimpleTest.js"></script>
- <script src="/tests/SimpleTest/SpawnTask.js"></script>
- <script src="pwmgr_common.js"></script>
- <link rel="stylesheet" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script type="application/javascript;version=1.8">
-const LMCBackstagePass = SpecialPowers.Cu.import("resource://gre/modules/LoginManagerContent.jsm");
-const { LoginManagerContent, LoginFormFactory } = LMCBackstagePass;
-
-let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-let loadPromise = new Promise(resolve => {
- document.addEventListener("DOMContentLoaded", () => {
- document.getElementById("loginFrame").addEventListener("load", (evt) => {
- resolve();
- });
- });
-});
-
-add_task(function* setup() {
- info("Waiting for page and frame loads");
- yield loadPromise;
-
- yield loadRecipes({
- siteRecipes: [{
- hosts: ["mochi.test:8888"],
- usernameSelector: "input[name='recipeuname']",
- passwordSelector: "input[name='recipepword']",
- }],
- });
-});
-
-const DEFAULT_ORIGIN = "http://mochi.test:8888";
-const TESTCASES = [
- {
- // Inputs
- document: `<input type=password value="pass1">`,
- inputIndexForFormLike: 0,
-
- // Expected outputs similar to RemoteLogins:onFormSubmit
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: null,
- newPasswordFieldValue: "pass1",
- oldPasswordFieldValue: null,
- },
- {
- document: `<input value="user1">
- <input type=password value="pass1">`,
- inputIndexForFormLike: 0,
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass1",
- oldPasswordFieldValue: null,
- },
- {
- document: `<input value="user1">
- <input type=password value="pass1">`,
- inputIndexForFormLike: 1,
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass1",
- oldPasswordFieldValue: null,
- },
- {
- document: `<input value="user1">
- <input type=password value="pass1">
- <input type=password value="pass2">`,
- inputIndexForFormLike: 2,
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass2",
- oldPasswordFieldValue: "pass1",
- },
- {
- document: `<input value="user1">
- <input type=password value="pass1">
- <input type=password value="pass2">
- <input type=password value="pass2">`,
- inputIndexForFormLike: 3,
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass2",
- oldPasswordFieldValue: "pass1",
- },
- {
- document: `<input value="user1">
- <input type=password value="user2" form="form1">
- <input type=password value="pass1">
- <form id="form1">
- <input value="user3">
- <input type=password value="pass2">
- </form>`,
- inputIndexForFormLike: 2,
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass1",
- oldPasswordFieldValue: null,
- },
- {
- document: `<!-- recipe field override -->
- <input name="recipeuname" value="username from recipe">
- <input value="default field username">
- <input type=password value="pass1">
- <input name="recipepword" type=password value="pass2">`,
- inputIndexForFormLike: 2,
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "username from recipe",
- newPasswordFieldValue: "pass2",
- oldPasswordFieldValue: null,
- },
-];
-
-function getSubmitMessage() {
- info("getSubmitMessage");
- return new Promise((resolve, reject) => {
- chromeScript.addMessageListener("formSubmissionProcessed", function processed(...args) {
- info("got formSubmissionProcessed");
- chromeScript.removeMessageListener("formSubmissionProcessed", processed);
- resolve(...args);
- });
- });
-}
-
-add_task(function* test() {
- let loginFrame = document.getElementById("loginFrame");
- let frameDoc = loginFrame.contentWindow.document;
-
- for (let tc of TESTCASES) {
- info("Starting testcase: " + JSON.stringify(tc));
- frameDoc.documentElement.innerHTML = tc.document;
- let inputForFormLike = frameDoc.querySelectorAll("input")[tc.inputIndexForFormLike];
-
- let formLike = LoginFormFactory.createFromField(inputForFormLike);
-
- info("Calling _onFormSubmit with FormLike");
- let processedPromise = getSubmitMessage();
- LoginManagerContent._onFormSubmit(formLike);
-
- let submittedResult = yield processedPromise;
-
- // Check data sent via RemoteLogins:onFormSubmit
- is(submittedResult.hostname, tc.hostname, "Check hostname");
- is(submittedResult.formSubmitURL, tc.formSubmitURL, "Check formSubmitURL");
-
- if (tc.usernameFieldValue === null) {
- is(submittedResult.usernameField, tc.usernameFieldValue, "Check usernameField");
- } else {
- is(submittedResult.usernameField.value, tc.usernameFieldValue, "Check usernameField");
- }
-
- is(submittedResult.newPasswordField.value, tc.newPasswordFieldValue, "Check newPasswordFieldValue");
-
- if (tc.oldPasswordFieldValue === null) {
- is(submittedResult.oldPasswordField, tc.oldPasswordFieldValue, "Check oldPasswordFieldValue");
- } else {
- is(submittedResult.oldPasswordField.value, tc.oldPasswordFieldValue, "Check oldPasswordFieldValue");
- }
- }
-});
-
-</script>
-
-<p id="display"></p>
-
-<div id="content">
- <iframe id="loginFrame" src="http://mochi.test:8888/tests/toolkit/components/passwordmgr/test/blank.html"></iframe>
-</div>
-<pre id="test"></pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation.html b/toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation.html
deleted file mode 100644
index b07d0886c..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation.html
+++ /dev/null
@@ -1,191 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test capturing of fields outside of a form due to navigation</title>
- <script src="/tests/SimpleTest/SimpleTest.js"></script>
- <script src="/tests/SimpleTest/SpawnTask.js"></script>
- <script src="pwmgr_common.js"></script>
- <link rel="stylesheet" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script type="application/javascript;version=1.8">
-const LMCBackstagePass = SpecialPowers.Cu.import("resource://gre/modules/LoginManagerContent.jsm");
-const { LoginManagerContent, LoginFormFactory } = LMCBackstagePass;
-
-let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-let loadPromise = new Promise(resolve => {
- document.addEventListener("DOMContentLoaded", () => {
- document.getElementById("loginFrame").addEventListener("load", (evt) => {
- resolve();
- });
- });
-});
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [
- ["signon.formlessCapture.enabled", true],
- ],
- });
-
- info("Waiting for page and frame loads");
- yield loadPromise;
-
- yield loadRecipes({
- siteRecipes: [{
- hosts: ["test1.mochi.test:8888"],
- usernameSelector: "input[name='recipeuname']",
- passwordSelector: "input[name='recipepword']",
- }],
- });
-});
-
-const DEFAULT_ORIGIN = "http://test1.mochi.test:8888";
-const SCRIPTS = {
- PUSHSTATE: `history.pushState({}, "Pushed state", "?pushed");`,
- WINDOW_LOCATION: `window.location = "data:text/html;charset=utf-8,window.location";`,
-};
-const TESTCASES = [
- {
- // Inputs
- document: `<input type=password value="pass1">`,
-
- // Expected outputs similar to RemoteLogins:onFormSubmit
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: null,
- newPasswordFieldValue: "pass1",
- oldPasswordFieldValue: null,
- },
- {
- document: `<input value="user1">
- <input type=password value="pass1">`,
-
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass1",
- oldPasswordFieldValue: null,
- },
- {
- document: `<input value="user1">
- <input type=password value="pass1">
- <input type=password value="pass2">`,
-
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass2",
- oldPasswordFieldValue: "pass1",
- },
- {
- document: `<input value="user1">
- <input type=password value="pass1">
- <input type=password value="pass2">
- <input type=password value="pass2">`,
-
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass2",
- oldPasswordFieldValue: "pass1",
- },
- {
- document: `<input value="user1">
- <input type=password value="user2" form="form1">
- <input type=password value="pass1">
- <form id="form1">
- <input value="user3">
- <input type=password value="pass2">
- </form>`,
-
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "user1",
- newPasswordFieldValue: "pass1",
- oldPasswordFieldValue: null,
- },
- {
- document: `<!-- recipe field override -->
- <input name="recipeuname" value="username from recipe">
- <input value="default field username">
- <input type=password value="pass1">
- <input name="recipepword" type=password value="pass2">`,
-
- hostname: DEFAULT_ORIGIN,
- formSubmitURL: DEFAULT_ORIGIN,
- usernameFieldValue: "username from recipe",
- newPasswordFieldValue: "pass2",
- oldPasswordFieldValue: null,
- },
-];
-
-function getSubmitMessage() {
- info("getSubmitMessage");
- return new Promise((resolve, reject) => {
- chromeScript.addMessageListener("formSubmissionProcessed", function processed(...args) {
- info("got formSubmissionProcessed");
- chromeScript.removeMessageListener("formSubmissionProcessed", processed);
- resolve(...args);
- });
- });
-}
-
-add_task(function* test() {
- let loginFrame = document.getElementById("loginFrame");
-
- for (let tc of TESTCASES) {
- for (let scriptName of Object.keys(SCRIPTS)) {
- info("Starting testcase with script " + scriptName + ": " + JSON.stringify(tc));
- let loadedPromise = new Promise((resolve) => {
- loginFrame.addEventListener("load", function frameLoaded() {
- loginFrame.removeEventListener("load", frameLoaded);
- resolve();
- });
- });
- loginFrame.src = DEFAULT_ORIGIN + "/tests/toolkit/components/passwordmgr/test/mochitest/blank.html";
- yield loadedPromise;
-
- let frameDoc = SpecialPowers.wrap(loginFrame.contentWindow).document;
- frameDoc.documentElement.innerHTML = tc.document;
- // Wait for the form to be processed before trying to submit.
- yield promiseFormsProcessed();
- let processedPromise = getSubmitMessage();
- info("Running " + scriptName + " script to cause a submission");
- frameDoc.defaultView.eval(SCRIPTS[scriptName]);
-
- let submittedResult = yield processedPromise;
-
- // Check data sent via RemoteLogins:onFormSubmit
- is(submittedResult.hostname, tc.hostname, "Check hostname");
- is(submittedResult.formSubmitURL, tc.formSubmitURL, "Check formSubmitURL");
-
- if (tc.usernameFieldValue === null) {
- is(submittedResult.usernameField, tc.usernameFieldValue, "Check usernameField");
- } else {
- is(submittedResult.usernameField.value, tc.usernameFieldValue, "Check usernameField");
- }
-
- is(submittedResult.newPasswordField.value, tc.newPasswordFieldValue, "Check newPasswordFieldValue");
-
- if (tc.oldPasswordFieldValue === null) {
- is(submittedResult.oldPasswordField, tc.oldPasswordFieldValue, "Check oldPasswordFieldValue");
- } else {
- is(submittedResult.oldPasswordField.value, tc.oldPasswordFieldValue, "Check oldPasswordFieldValue");
- }
- }
- }
-});
-
-</script>
-
-<p id="display"></p>
-
-<div id="content">
- <iframe id="loginFrame" src="http://test1.mochi.test:8888/tests/toolkit/components/passwordmgr/test/mochitest/blank.html"></iframe>
-</div>
-<pre id="test"></pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation_negative.html b/toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation_negative.html
deleted file mode 100644
index 4283f128c..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_formless_submit_navigation_negative.html
+++ /dev/null
@@ -1,121 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test no capturing of fields outside of a form due to navigation</title>
- <script src="/tests/SimpleTest/SimpleTest.js"></script>
- <script src="/tests/SimpleTest/SpawnTask.js"></script>
- <script src="pwmgr_common.js"></script>
- <link rel="stylesheet" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script type="application/javascript;version=1.8">
-const LMCBackstagePass = SpecialPowers.Cu.import("resource://gre/modules/LoginManagerContent.jsm");
-const { LoginManagerContent, LoginFormFactory } = LMCBackstagePass;
-
-SimpleTest.requestFlakyTimeout("Testing that a message doesn't arrive");
-
-let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-let loadPromise = new Promise(resolve => {
- document.addEventListener("DOMContentLoaded", () => {
- document.getElementById("loginFrame").addEventListener("load", (evt) => {
- resolve();
- });
- });
-});
-
-function submissionProcessed(...args) {
- ok(false, "No formSubmissionProcessed should occur in this test");
- info("got: " + JSON.stringify(args));
-}
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({
- set: [
- ["signon.formlessCapture.enabled", true],
- ],
- });
-
- info("Waiting for page and frame loads");
- yield loadPromise;
-
- chromeScript.addMessageListener("formSubmissionProcessed", submissionProcessed);
-
- SimpleTest.registerCleanupFunction(() => {
- chromeScript.removeMessageListener("formSubmissionProcessed", submissionProcessed);
- });
-});
-
-const DEFAULT_ORIGIN = "http://test1.mochi.test:8888";
-const SCRIPTS = {
- PUSHSTATE: `history.pushState({}, "Pushed state", "?pushed");`,
- WINDOW_LOCATION: `window.location = "data:text/html;charset=utf-8,window.location";`,
- WINDOW_LOCATION_RELOAD: `window.location.reload();`,
- HISTORY_BACK: `history.back();`,
- HISTORY_GO_MINUS1: `history.go(-1);`,
-};
-const TESTCASES = [
- // Begin test cases that shouldn't trigger capture.
- {
- // For now we don't trigger upon navigation if <form> is used.
- document: `<form><input type=password value="pass1"></form>`,
- },
- {
- // Empty password field
- document: `<input type=password value="">`,
- },
- {
- // Test with an input that would normally be captured but with SCRIPTS that
- // shouldn't trigger capture.
- document: `<input type=password value="pass2">`,
- wouldCapture: true,
- },
-];
-
-add_task(function* test() {
- let loginFrame = document.getElementById("loginFrame");
-
- for (let tc of TESTCASES) {
- for (let scriptName of Object.keys(SCRIPTS)) {
- if (tc.wouldCapture && ["PUSHSTATE", "WINDOW_LOCATION"].includes(scriptName)) {
- // Don't run scripts that should actually capture for this testcase.
- continue;
- }
-
- info("Starting testcase with script " + scriptName + ": " + JSON.stringify(tc));
- let loadedPromise = new Promise((resolve) => {
- loginFrame.addEventListener("load", function frameLoaded() {
- loginFrame.removeEventListener("load", frameLoaded);
- resolve();
- });
- });
- loginFrame.src = DEFAULT_ORIGIN + "/tests/toolkit/components/passwordmgr/test/mochitest/blank.html";
- yield loadedPromise;
-
- let frameDoc = SpecialPowers.wrap(loginFrame.contentWindow).document;
- frameDoc.documentElement.innerHTML = tc.document;
-
- // Wait for the form to be processed before trying to submit.
- yield promiseFormsProcessed();
-
- info("Running " + scriptName + " script to check for a submission");
- frameDoc.defaultView.eval(SCRIPTS[scriptName]);
-
- // Wait for 5000ms to see if the promise above resolves.
- yield new Promise(resolve => setTimeout(resolve, 5000));
- ok(true, "Done waiting for captures");
- }
- }
-});
-
-</script>
-
-<p id="display"></p>
-
-<div id="content">
- <iframe id="loginFrame" src="http://test1.mochi.test:8888/tests/toolkit/components/passwordmgr/test/mochitest/blank.html"></iframe>
-</div>
-<pre id="test"></pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_input_events.html b/toolkit/components/passwordmgr/test/mochitest/test_input_events.html
deleted file mode 100644
index 0e77956d8..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_input_events.html
+++ /dev/null
@@ -1,96 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for input events in Login Manager</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body onload="onNewEvent(event)">
-Login Manager test: input events should fire.
-
-<script>
-runChecksAfterCommonInit();
-
-SimpleTest.requestFlakyTimeout("untriaged");
-
-/** Test for Login Manager: form fill, should get input events. **/
-
-var usernameInputFired = false;
-var passwordInputFired = false;
-var usernameChangeFired = false;
-var passwordChangeFired = false;
-var onloadFired = false;
-
-function onNewEvent(e) {
- info("Got " + e.type + " event.");
- if (e.type == "load") {
- onloadFired = true;
- } else if (e.type == "input") {
- if (e.target.name == "uname") {
- is(e.target.value, "testuser", "Should get 'testuser' as username");
- ok(!usernameInputFired, "Should not have gotten an input event for the username field yet.");
- usernameInputFired = true;
- } else if (e.target.name == "pword") {
- is(e.target.value, "testpass", "Should get 'testpass' as password");
- ok(!passwordInputFired, "Should not have gotten an input event for the password field yet.");
- passwordInputFired = true;
- }
- } else if (e.type == "change") {
- if (e.target.name == "uname") {
- is(e.target.value, "testuser", "Should get 'testuser' as username");
- ok(usernameInputFired, "Should get input event before change event for username field.");
- ok(!usernameChangeFired, "Should not have gotten a change event for the username field yet.");
- usernameChangeFired = true;
- } else if (e.target.name == "pword") {
- is(e.target.value, "testpass", "Should get 'testpass' as password");
- ok(passwordInputFired, "Should get input event before change event for password field.");
- ok(!passwordChangeFired, "Should not have gotten a change event for the password field yet.");
- passwordChangeFired = true;
- }
- }
- if (onloadFired && usernameInputFired && passwordInputFired && usernameChangeFired && passwordChangeFired) {
- ok(true, "All events fired as expected, we're done.");
- SimpleTest.finish();
- }
-}
-
-SimpleTest.registerCleanupFunction(function cleanup() {
- clearTimeout(timeout);
- $_(1, "uname").removeAttribute("oninput");
- $_(1, "pword").removeAttribute("oninput");
- $_(1, "uname").removeAttribute("onchange");
- $_(1, "pword").removeAttribute("onchange");
- document.body.removeAttribute("onload");
-});
-
-var timeout = setTimeout(function() {
- ok(usernameInputFired, "Username input event should have fired by now.");
- ok(passwordInputFired, "Password input event should have fired by now.");
- ok(usernameChangeFired, "Username change event should have fired by now.");
- ok(passwordChangeFired, "Password change event should have fired by now.");
- ok(onloadFired, "Window load event should have fired by now.");
- ok(false, "Not all events fired yet.");
- SimpleTest.finish();
-}, 10000);
-
-</script>
-
-<p id="display"></p>
-
-<div id="content" style="display: none">
-
- <form id="form1" action="formtest.js">
- <p>This is form 1.</p>
- <input type="text" name="uname" oninput="onNewEvent(event)" onchange="onNewEvent(event)">
- <input type="password" name="pword" oninput="onNewEvent(event)" onchange="onNewEvent(event)">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
-</div>
-<pre id="test"></pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_input_events_for_identical_values.html b/toolkit/components/passwordmgr/test/mochitest/test_input_events_for_identical_values.html
deleted file mode 100644
index d058a87f9..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_input_events_for_identical_values.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for input events in Login Manager when username/password are filled in already</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body onload="onNewEvent(event)">
-Login Manager test: input events should fire.
-
-<script>
-runChecksAfterCommonInit();
-
-SimpleTest.requestFlakyTimeout("untriaged");
-
-/** Test for Login Manager: form fill when form is already filled, should not get input events. **/
-
-var onloadFired = false;
-
-function onNewEvent(e) {
- console.error("Got " + e.type + " event.");
- if (e.type == "load") {
- onloadFired = true;
- $_(1, "uname").focus();
- sendKey("Tab");
- } else {
- ok(false, "Got an input event for " + e.target.name + " field, which shouldn't happen.");
- }
-}
-</script>
-
-<p id="display"></p>
-
-<div id="content">
-
- <form id="form1" action="formtest.js">
- <p>This is form 1.</p>
- <input type="text" name="uname" oninput="onNewEvent(event)" value="testuser">
- <input type="password" name="pword" oninput="onNewEvent(event)" onfocus="setTimeout(function() { SimpleTest.finish() }, 1000);" value="testpass">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
-</div>
-<pre id="test"></pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_autocomplete.html b/toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_autocomplete.html
deleted file mode 100644
index c5d0a44fa..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_autocomplete.html
+++ /dev/null
@@ -1,861 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test insecure form field autocomplete</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-
-<script>
-var chromeScript = runChecksAfterCommonInit();
-
-var setupScript = runInParent(function setup() {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- // Create some logins just for this form, since we'll be deleting them.
- var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- assert.ok(nsLoginInfo != null, "nsLoginInfo constructor");
-
- // login0 has no username, so should be filtered out from the autocomplete list.
- var login0 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "", "user0pass", "", "pword");
-
- var login1 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "tempuser1", "temppass1", "uname", "pword");
-
- var login2 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser2", "testpass2", "uname", "pword");
-
- var login3 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser3", "testpass3", "uname", "pword");
-
- var login4 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "zzzuser4", "zzzpass4", "uname", "pword");
-
- // login 5 only used in the single-user forms
- var login5 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete2", null,
- "singleuser5", "singlepass5", "uname", "pword");
-
- var login6A = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete3", null,
- "form7user1", "form7pass1", "uname", "pword");
- var login6B = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete3", null,
- "form7user2", "form7pass2", "uname", "pword");
-
- var login7 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete4", null,
- "form8user", "form8pass", "uname", "pword");
-
- var login8A = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete5", null,
- "form9userAB", "form9pass", "uname", "pword");
- var login8B = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete5", null,
- "form9userAAB", "form9pass", "uname", "pword");
- var login8C = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete5", null,
- "form9userAABzz", "form9pass", "uname", "pword");
-
- var login10 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete7", null,
- "testuser10", "testpass10", "uname", "pword");
-
-
- // try/catch in case someone runs the tests manually, twice.
- try {
- Services.logins.addLogin(login0);
- Services.logins.addLogin(login1);
- Services.logins.addLogin(login2);
- Services.logins.addLogin(login3);
- Services.logins.addLogin(login4);
- Services.logins.addLogin(login5);
- Services.logins.addLogin(login6A);
- Services.logins.addLogin(login6B);
- Services.logins.addLogin(login7);
- Services.logins.addLogin(login8A);
- Services.logins.addLogin(login8B);
- // login8C is added later
- Services.logins.addLogin(login10);
- } catch (e) {
- assert.ok(false, "addLogin threw: " + e);
- }
-
- addMessageListener("addLogin", loginVariableName => {
- let login = eval(loginVariableName);
- assert.ok(!!login, "Login to add is defined: " + loginVariableName);
- Services.logins.addLogin(login);
- });
- addMessageListener("removeLogin", loginVariableName => {
- let login = eval(loginVariableName);
- assert.ok(!!login, "Login to delete is defined: " + loginVariableName);
- Services.logins.removeLogin(login);
- });
-});
-</script>
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
-
- <!-- form1 tests multiple matching logins -->
- <form id="form1" action="http://autocomplete:8888/formtest.js" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- other forms test single logins, with autocomplete=off set -->
- <form id="form2" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword" autocomplete="off">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form3" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname" autocomplete="off">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form4" action="http://autocomplete2" onsubmit="return false;" autocomplete="off">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form5" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname" autocomplete="off">
- <input type="password" name="pword" autocomplete="off">
- <button type="submit">Submit</button>
- </form>
-
- <!-- control -->
- <form id="form6" action="http://autocomplete2" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- This form will be manipulated to insert a different username field. -->
- <form id="form7" action="http://autocomplete3" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- test for no autofill after onblur with blank username -->
- <form id="form8" action="http://autocomplete4" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- test autocomplete dropdown -->
- <form id="form9" action="http://autocomplete5" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- test for onUsernameInput recipe testing -->
- <form id="form11" action="http://autocomplete7" onsubmit="return false;">
- <input type="text" name="1">
- <input type="text" name="2">
- <button type="submit">Submit</button>
- </form>
-
- <!-- tests <form>-less autocomplete -->
- <div id="form12">
- <input type="text" name="uname" id="uname">
- <input type="password" name="pword" id="pword">
- <button type="submit">Submit</button>
- </div>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: multiple login autocomplete. **/
-
-var uname = $_(1, "uname");
-var pword = $_(1, "pword");
-const shiftModifier = SpecialPowers.Ci.nsIDOMEvent.SHIFT_MASK;
-
-// Restore the form to the default state.
-function restoreForm() {
- uname.value = "";
- pword.value = "";
- uname.focus();
-}
-
-// Check for expected username/password in form.
-function checkACForm(expectedUsername, expectedPassword) {
- var formID = uname.parentNode.id;
- is(uname.value, expectedUsername, "Checking " + formID + " username is: " + expectedUsername);
- is(pword.value, expectedPassword, "Checking " + formID + " password is: " + expectedPassword);
-}
-
-function sendFakeAutocompleteEvent(element) {
- var acEvent = document.createEvent("HTMLEvents");
- acEvent.initEvent("DOMAutoComplete", true, false);
- element.dispatchEvent(acEvent);
-}
-
-function spinEventLoop() {
- return Promise.resolve();
-}
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({"set": [["security.insecure_field_warning.contextual.enabled", true],
- ["signon.autofillForms.http", true]]});
- listenForUnexpectedPopupShown();
-});
-
-add_task(function* test_form1_initial_empty() {
- yield SimpleTest.promiseFocus(window);
-
- // Make sure initial form is empty.
- checkACForm("", "");
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is initially closed");
-});
-
-add_task(function* test_form1_warning_entry() {
- yield SimpleTest.promiseFocus(window);
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- let results = yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- let expectedMenuItems = ["This connection is not secure. Logins entered here could be compromised. Learn More",
- "tempuser1",
- "testuser2",
- "testuser3",
- "zzzuser4"];
- checkArrayValues(results, expectedMenuItems, "Check all menuitems are displayed correctly.");
-
- doKey("down"); // select insecure warning
- checkACForm("", ""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield spinEventLoop(); // let focus happen
- checkACForm("", "");
-});
-
-add_task(function* test_form1_first_entry() {
- yield SimpleTest.promiseFocus(window);
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- checkACForm("", ""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("tempuser1", "temppass1");
-});
-
-add_task(function* test_form1_second_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- doKey("down"); // second
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_third_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- doKey("down"); // second
- doKey("down"); // third
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser3", "testpass3");
-});
-
-add_task(function* test_form1_fourth_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- doKey("down"); // second
- doKey("down"); // third
- doKey("down"); // fourth
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_wraparound_first_entry() {
- // Trigger autocomplete popup
- restoreForm();
- yield spinEventLoop(); // let focus happen
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- doKey("down"); // second
- doKey("down"); // third
- doKey("down"); // fourth
- doKey("down"); // deselects
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("tempuser1", "temppass1");
-});
-
-add_task(function* test_form1_wraparound_up_last_entry() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("up"); // last (fourth)
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_wraparound_down_up_up() {
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // select first entry
- doKey("up"); // selects nothing!
- doKey("up"); // select last entry
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_wraparound_up_last() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down");
- doKey("up"); // deselects
- doKey("up"); // last entry
- doKey("up");
- doKey("up");
- doKey("up"); // skip insecure warning
- doKey("up"); // first entry
- doKey("up"); // deselects
- doKey("up"); // last entry
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_fill_username_without_autofill_right() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Set first entry w/o triggering autocomplete
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- doKey("right");
- yield spinEventLoop();
- checkACForm("tempuser1", ""); // empty password
-});
-
-add_task(function* test_form1_fill_username_without_autofill_left() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Set first entry w/o triggering autocomplete
- doKey("down"); // skip insecure warning
- doKey("down"); // first
- doKey("left");
- checkACForm("tempuser1", ""); // empty password
-});
-
-add_task(function* test_form1_pageup_first() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // Check first entry (page up)
- doKey("down"); // first
- doKey("down"); // second
- doKey("page_up"); // first
- doKey("down"); // skip insecure warning
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("tempuser1", "temppass1");
-});
-
-add_task(function* test_form1_pagedown_last() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // test 13
- // Check last entry (page down)
- doKey("down"); // first
- doKey("page_down"); // last
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_untrusted_event() {
- restoreForm();
- yield spinEventLoop();
-
- // Send a fake (untrusted) event.
- checkACForm("", "");
- uname.value = "zzzuser4";
- sendFakeAutocompleteEvent(uname);
- yield spinEventLoop();
- checkACForm("zzzuser4", "");
-});
-
-add_task(function* test_form1_delete() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- // XXX tried sending character "t" before/during dropdown to test
- // filtering, but had no luck. Seemed like the character was getting lost.
- // Setting uname.value didn't seem to work either. This works with a human
- // driver, so I'm not sure what's up.
-
- doKey("down"); // skip insecure warning
- // Delete the first entry (of 4), "tempuser1"
- doKey("down");
- var numLogins;
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 5, "Correct number of logins before deleting one");
-
- let countChangedPromise = notifyMenuChanged(4);
- var deletionPromise = promiseStorageChanged(["removeLogin"]);
- // On OS X, shift-backspace and shift-delete work, just delete does not.
- // On Win/Linux, shift-backspace does not work, delete and shift-delete do.
- doKey("delete", shiftModifier);
- yield deletionPromise;
-
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 4, "Correct number of logins after deleting one");
- yield countChangedPromise;
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_first_after_deletion() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check the new first entry (of 3)
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_delete_second() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Delete the second entry (of 3), "testuser3"
- doKey("down");
- doKey("down");
- doKey("delete", shiftModifier);
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 3, "Correct number of logins after deleting one");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("zzzuser4", "zzzpass4");
-});
-
-add_task(function* test_form1_first_after_deletion2() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check the new first entry (of 2)
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_delete_last() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // test 54
- // Delete the last entry (of 2), "zzzuser4"
- doKey("down");
- doKey("down");
- doKey("delete", shiftModifier);
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 2, "Correct number of logins after deleting one");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_first_after_3_deletions() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check the only remaining entry
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("testuser2", "testpass2");
-});
-
-add_task(function* test_form1_check_only_entry_remaining() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // test 56
- // Delete the only remaining entry, "testuser2"
- doKey("down");
- doKey("delete", shiftModifier);
- checkACForm("", "");
- numLogins = LoginManager.countLogins("http://mochi.test:8888", "http://autocomplete:8888", null);
- is(numLogins, 1, "Correct number of logins after deleting one");
-
- // remove the login that's not shown in the list.
- setupScript.sendSyncMessage("removeLogin", "login0");
-});
-
-// Tests for single-user forms for ignoring autocomplete=off
-add_task(function* test_form2() {
- // Turn our attention to form2
- uname = $_(2, "uname");
- pword = $_(2, "pword");
- checkACForm("singleuser5", "singlepass5");
-
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form3() {
- uname = $_(3, "uname");
- pword = $_(3, "pword");
- checkACForm("singleuser5", "singlepass5");
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form4() {
- uname = $_(4, "uname");
- pword = $_(4, "pword");
- checkACForm("singleuser5", "singlepass5");
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form5() {
- uname = $_(5, "uname");
- pword = $_(5, "pword");
- checkACForm("singleuser5", "singlepass5");
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form6() {
- // (this is a control, w/o autocomplete=off, to ensure the login
- // that was being suppressed would have been filled in otherwise)
- uname = $_(6, "uname");
- pword = $_(6, "pword");
- checkACForm("singleuser5", "singlepass5");
-});
-
-add_task(function* test_form6_changeUsername() {
- // Test that the password field remains filled in after changing
- // the username.
- uname.focus();
- doKey("right");
- sendChar("X");
- // Trigger the 'blur' event on uname
- pword.focus();
- yield spinEventLoop();
- checkACForm("singleuser5X", "singlepass5");
-
- setupScript.sendSyncMessage("removeLogin", "login5");
-});
-
-add_task(function* test_form7() {
- uname = $_(7, "uname");
- pword = $_(7, "pword");
- checkACForm("", "");
-
- // Insert a new username field into the form. We'll then make sure
- // that invoking the autocomplete doesn't try to fill the form.
- var newField = document.createElement("input");
- newField.setAttribute("type", "text");
- newField.setAttribute("name", "uname2");
- pword.parentNode.insertBefore(newField, pword);
- is($_(7, "uname2").value, "", "Verifying empty uname2");
-
- // Delete login6B. It was created just to prevent filling in a login
- // automatically, removing it makes it more likely that we'll catch a
- // future regression with form filling here.
- setupScript.sendSyncMessage("removeLogin", "login6B");
-});
-
-add_task(function* test_form7_2() {
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Check first entry
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- // The form changes, so we expect the old username field to get the
- // selected autocomplete value, but neither the new username field nor
- // the password field should have any values filled in.
- yield spinEventLoop();
- checkACForm("form7user1", "");
- is($_(7, "uname2").value, "", "Verifying empty uname2");
- restoreForm(); // clear field, so reloading test doesn't fail
-
- setupScript.sendSyncMessage("removeLogin", "login6A");
-});
-
-add_task(function* test_form8() {
- uname = $_(8, "uname");
- pword = $_(8, "pword");
- checkACForm("form8user", "form8pass");
- restoreForm();
-});
-
-add_task(function* test_form8_blur() {
- checkACForm("", "");
- // Focus the previous form to trigger a blur.
- $_(7, "uname").focus();
-});
-
-add_task(function* test_form8_2() {
- checkACForm("", "");
- restoreForm();
-});
-
-add_task(function* test_form8_3() {
- checkACForm("", "");
- setupScript.sendSyncMessage("removeLogin", "login7");
-});
-
-add_task(function* test_form9_filtering() {
- // Turn our attention to form9 to test the dropdown - bug 497541
- uname = $_(9, "uname");
- pword = $_(9, "pword");
- uname.focus();
- let shownPromise = promiseACShown();
- sendString("form9userAB");
- yield shownPromise;
-
- checkACForm("form9userAB", "");
- uname.focus();
- doKey("left");
- shownPromise = promiseACShown();
- sendChar("A");
- let results = yield shownPromise;
-
- checkACForm("form9userAAB", "");
- checkArrayValues(results, ["This connection is not secure. Logins entered here could be compromised. Learn More", "form9userAAB"],
- "Check dropdown is updated after inserting 'A'");
- doKey("down"); // skip insecure warning
- doKey("down");
- doKey("return");
- yield promiseFormsProcessed();
- checkACForm("form9userAAB", "form9pass");
-});
-
-add_task(function* test_form9_autocomplete_cache() {
- // Note that this addLogin call will only be seen by the autocomplete
- // attempt for the sendChar if we do not successfully cache the
- // autocomplete results.
- setupScript.sendSyncMessage("addLogin", "login8C");
- uname.focus();
- let promise0 = notifyMenuChanged(1);
- let shownPromise = promiseACShown();
- sendChar("z");
- yield promise0;
- yield shownPromise;
- let popupState = yield getPopupState();
- is(popupState.open, true, "Check popup should open");
-
- // check that empty results are cached - bug 496466
- promise0 = notifyMenuChanged(1);
- sendChar("z");
- yield promise0;
- popupState = yield getPopupState();
- is(popupState.open, true, "Check popup stays opened due to cached empty result");
-});
-
-add_task(function* test_form11_recipes() {
- yield loadRecipes({
- siteRecipes: [{
- "hosts": ["mochi.test:8888"],
- "usernameSelector": "input[name='1']",
- "passwordSelector": "input[name='2']"
- }],
- });
- uname = $_(11, "1");
- pword = $_(11, "2");
-
- // First test DOMAutocomplete
- // Switch the password field to type=password so _fillForm marks the username
- // field for autocomplete.
- pword.type = "password";
- yield promiseFormsProcessed();
- restoreForm();
- checkACForm("", "");
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- doKey("return"); // not "enter"!
- yield promiseFormsProcessed();
- checkACForm("testuser10", "testpass10");
-
- // Now test recipes with blur on the username field.
- restoreForm();
- checkACForm("", "");
- uname.value = "testuser10";
- checkACForm("testuser10", "");
- doKey("tab");
- yield promiseFormsProcessed();
- checkACForm("testuser10", "testpass10");
- yield resetRecipes();
-});
-
-add_task(function* test_form12_formless() {
- // Test form-less autocomplete
- uname = $_(12, "uname");
- pword = $_(12, "pword");
- restoreForm();
- checkACForm("", "");
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- doKey("down"); // skip insecure warning
- // Trigger autocomplete
- doKey("down");
- checkACForm("", ""); // value shouldn't update
- let processedPromise = promiseFormsProcessed();
- doKey("return"); // not "enter"!
- yield processedPromise;
- checkACForm("testuser", "testpass");
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_no_saved_login.html b/toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_no_saved_login.html
deleted file mode 100644
index c3a894958..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_insecure_form_field_no_saved_login.html
+++ /dev/null
@@ -1,103 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test basic login, contextual inscure password warning without saved logins</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: contextual inscure password warning without saved logins
-
-<script>
-let chromeScript = runChecksAfterCommonInit();
-</script>
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
-
- <form id="form1" action="http://autocomplete:8888/formtest.js" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: contextual inscure password warning without saved logins. **/
-
-// Set to pref before the document loads.
-SpecialPowers.setBoolPref(
- "security.insecure_field_warning.contextual.enabled", true);
-
-SimpleTest.registerCleanupFunction(() => {
- SpecialPowers.clearUserPref(
- "security.insecure_field_warning.contextual.enabled");
-});
-
-let uname = $_(1, "uname");
-let pword = $_(1, "pword");
-const shiftModifier = SpecialPowers.Ci.nsIDOMEvent.SHIFT_MASK;
-
-// Restore the form to the default state.
-function restoreForm() {
- uname.value = "";
- pword.value = "";
- uname.focus();
-}
-
-// Check for expected username/password in form.
-function checkACForm(expectedUsername, expectedPassword) {
- let formID = uname.parentNode.id;
- is(uname.value, expectedUsername, "Checking " + formID + " username is: " + expectedUsername);
- is(pword.value, expectedPassword, "Checking " + formID + " password is: " + expectedPassword);
-}
-
-function spinEventLoop() {
- return Promise.resolve();
-}
-
-add_task(function* setup() {
- listenForUnexpectedPopupShown();
-});
-
-add_task(function* test_form1_initial_empty() {
- yield SimpleTest.promiseFocus(window);
-
- // Make sure initial form is empty.
- checkACForm("", "");
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is initially closed");
-});
-
-add_task(function* test_form1_warning_entry() {
- yield SimpleTest.promiseFocus(window);
- // Trigger autocomplete popup
- restoreForm();
- let shownPromise = promiseACShown();
- doKey("down"); // open
- yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.open, true, "Check popup is opened");
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- doKey("down"); // select insecure warning
- checkACForm("", ""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield spinEventLoop(); // let focus happen
- checkACForm("", "");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_maxlength.html b/toolkit/components/passwordmgr/test/mochitest/test_maxlength.html
deleted file mode 100644
index 2b6da33ec..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_maxlength.html
+++ /dev/null
@@ -1,137 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for maxlength attributes</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: Bug 391514
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-<div id="content" style="display: none">
- <!-- normal form. -->
- <form id="form1" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- limited username -->
- <form id="form2" action="formtest.js">
- <input type="text" name="uname" maxlength="4">
- <input type="password" name="pword">
- </form>
-
- <!-- limited password -->
- <form id="form3" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword" maxlength="4">
- </form>
-
- <!-- limited username and password -->
- <form id="form4" action="formtest.js">
- <input type="text" name="uname" maxlength="4">
- <input type="password" name="pword" maxlength="4">
- </form>
-
-
- <!-- limited username -->
- <form id="form5" action="formtest.js">
- <input type="text" name="uname" maxlength="0">
- <input type="password" name="pword">
- </form>
-
- <!-- limited password -->
- <form id="form6" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword" maxlength="0">
- </form>
-
- <!-- limited username and password -->
- <form id="form7" action="formtest.js">
- <input type="text" name="uname" maxlength="0">
- <input type="password" name="pword" maxlength="0">
- </form>
-
-
- <!-- limited, but ok, username -->
- <form id="form8" action="formtest.js">
- <input type="text" name="uname" maxlength="999">
- <input type="password" name="pword">
- </form>
-
- <!-- limited, but ok, password -->
- <form id="form9" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword" maxlength="999">
- </form>
-
- <!-- limited, but ok, username and password -->
- <form id="form10" action="formtest.js">
- <input type="text" name="uname" maxlength="999">
- <input type="password" name="pword" maxlength="999">
- </form>
-
-
- <!-- limited, but ok, username -->
- <!-- (note that filled values are exactly 8 characters) -->
- <form id="form11" action="formtest.js">
- <input type="text" name="uname" maxlength="8">
- <input type="password" name="pword">
- </form>
-
- <!-- limited, but ok, password -->
- <!-- (note that filled values are exactly 8 characters) -->
- <form id="form12" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword" maxlength="8">
- </form>
-
- <!-- limited, but ok, username and password -->
- <!-- (note that filled values are exactly 8 characters) -->
- <form id="form13" action="formtest.js">
- <input type="text" name="uname" maxlength="8">
- <input type="password" name="pword" maxlength="8">
- </form>
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/* Test for Login Manager: 391514 (Login Manager gets confused with
- * password/PIN on usaa.com)
- */
-
-function startTest() {
- var i;
-
- is($_(1, "uname").value, "testuser", "Checking for filled username 1");
- is($_(1, "pword").value, "testpass", "Checking for filled password 1");
-
- for (i = 2; i < 8; i++) {
- is($_(i, "uname").value, "", "Checking for unfilled username " + i);
- is($_(i, "pword").value, "", "Checking for unfilled password " + i);
- }
-
- for (i = 8; i < 14; i++) {
- is($_(i, "uname").value, "testuser", "Checking for filled username " + i);
- is($_(i, "pword").value, "testpass", "Checking for filled password " + i);
- }
-
- // Note that tests 11-13 are limited to exactly the expected value.
- // Assert this lest someone change the login we're testing with.
- is($_(11, "uname").value.length, 8, "asserting test assumption is valid.");
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_password_field_autocomplete.html b/toolkit/components/passwordmgr/test/mochitest/test_password_field_autocomplete.html
deleted file mode 100644
index 443c8a5e9..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_password_field_autocomplete.html
+++ /dev/null
@@ -1,291 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test basic login autocomplete</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: multiple login autocomplete
-
-<script>
-var chromeScript = runChecksAfterCommonInit();
-
-var setupScript = runInParent(function setup() {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- // Create some logins just for this form, since we'll be deleting them.
- var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
- assert.ok(nsLoginInfo != null, "nsLoginInfo constructor");
-
- // login0 has no username, so should be filtered out from the autocomplete list.
- var login0 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "", "user0pass", "", "pword");
-
- var login1 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "tempuser1", "temppass1", "uname", "pword");
-
- var login2 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser2", "testpass2", "uname", "pword");
-
- var login3 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser3", "testpass3", "uname", "pword");
-
- var login4 = new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "zzzuser4", "zzzpass4", "uname", "pword");
-
-
- // try/catch in case someone runs the tests manually, twice.
- try {
- Services.logins.addLogin(login0);
- Services.logins.addLogin(login1);
- Services.logins.addLogin(login2);
- Services.logins.addLogin(login3);
- Services.logins.addLogin(login4);
- } catch (e) {
- assert.ok(false, "addLogin threw: " + e);
- }
-
- addMessageListener("addLogin", loginVariableName => {
- let login = eval(loginVariableName);
- assert.ok(!!login, "Login to add is defined: " + loginVariableName);
- Services.logins.addLogin(login);
- });
- addMessageListener("removeLogin", loginVariableName => {
- let login = eval(loginVariableName);
- assert.ok(!!login, "Login to delete is defined: " + loginVariableName);
- Services.logins.removeLogin(login);
- });
-});
-</script>
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
-
- <!-- form1 tests multiple matching logins -->
- <form id="form1" action="http://autocomplete:8888/formtest.js" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form2" action="http://autocomplete:8888/formtest.js" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword" readonly="true">
- <button type="submit">Submit</button>
- </form>
-
- <form id="form3" action="http://autocomplete:8888/formtest.js" onsubmit="return false;">
- <input type="text" name="uname">
- <input type="password" name="pword" disabled="true">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: multiple login autocomplete. **/
-
-var uname = $_(1, "uname");
-var pword = $_(1, "pword");
-const shiftModifier = SpecialPowers.Ci.nsIDOMEvent.SHIFT_MASK;
-
-// Restore the form to the default state.
-function* reinitializeForm(index) {
- // Using innerHTML is for creating the autocomplete popup again, so the
- // preference value will be applied to the constructor of
- // UserAutoCompleteResult.
- let form = document.getElementById("form" + index);
- let temp = form.innerHTML;
- form.innerHTML = "";
- form.innerHTML = temp;
-
- yield new Promise(resolve => {
- let observer = SpecialPowers.wrapCallback(() => {
- SpecialPowers.removeObserver(observer, "passwordmgr-processed-form");
- resolve();
- });
- SpecialPowers.addObserver(observer, "passwordmgr-processed-form", false);
- });
-
- yield SimpleTest.promiseFocus(window);
-
- uname = $_(index, "uname");
- pword = $_(index, "pword");
- uname.value = "";
- pword.value = "";
- pword.focus();
-}
-
-function generateDateString(date) {
- let dateAndTimeFormatter = new Intl.DateTimeFormat(undefined,
- { day: "numeric", month: "short", year: "numeric" });
- return dateAndTimeFormatter.format(date);
-}
-
-const DATE_NOW_STRING = generateDateString(new Date());
-
-// Check for expected username/password in form.
-function checkACFormPasswordField(expectedPassword) {
- var formID = uname.parentNode.id;
- is(pword.value, expectedPassword, "Checking " + formID + " password is: " + expectedPassword);
-}
-
-function spinEventLoop() {
- return Promise.resolve();
-}
-
-add_task(function* setup() {
- listenForUnexpectedPopupShown();
-});
-
-add_task(function* test_form1_initial_empty() {
- yield SimpleTest.promiseFocus(window);
-
- // Make sure initial form is empty.
- checkACFormPasswordField("");
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is initially closed");
-});
-
-add_task(function* test_form2_password_readonly() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["security.insecure_field_warning.contextual.enabled", true],
- ["signon.autofillForms.http", true]
- ]});
- yield reinitializeForm(2);
-
- // Trigger autocomplete popup
- doKey("down"); // open
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is closed for a readonly field.");
-});
-
-add_task(function* test_form3_password_disabled() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["security.insecure_field_warning.contextual.enabled", true],
- ["signon.autofillForms.http", true]
- ]});
- yield reinitializeForm(3);
-
- // Trigger autocomplete popup
- doKey("down"); // open
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is closed for a disabled field.");
-});
-
-add_task(function* test_form1_enabledInsecureFieldWarning_enabledInsecureAutoFillForm() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["security.insecure_field_warning.contextual.enabled", true],
- ["signon.autofillForms.http", true]
- ]});
- yield reinitializeForm(1);
- // Trigger autocomplete popup
- let shownPromise = promiseACShown();
- doKey("down"); // open
- let results = yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- let expectedMenuItems = ["This connection is not secure. Logins entered here could be compromised. Learn More",
- "No username (" + DATE_NOW_STRING + ")",
- "tempuser1",
- "testuser2",
- "testuser3",
- "zzzuser4"];
- checkArrayValues(results, expectedMenuItems, "Check all menuitems are displayed correctly.");
-
- doKey("down"); // select insecure warning
- checkACFormPasswordField(""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield spinEventLoop(); // let focus happen
- checkACFormPasswordField("");
-});
-
-add_task(function* test_form1_disabledInsecureFieldWarning_enabledInsecureAutoFillForm() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["security.insecure_field_warning.contextual.enabled", false],
- ["signon.autofillForms.http", true]
- ]});
- yield reinitializeForm(1);
-
- // Trigger autocomplete popup
- let shownPromise = promiseACShown();
- doKey("down"); // open
- let results = yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- let expectedMenuItems = ["No username (" + DATE_NOW_STRING + ")",
- "tempuser1",
- "testuser2",
- "testuser3",
- "zzzuser4"];
- checkArrayValues(results, expectedMenuItems, "Check all menuitems are displayed correctly.");
-
- doKey("down"); // select first item
- checkACFormPasswordField(""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield spinEventLoop(); // let focus happen
- checkACFormPasswordField("user0pass");
-});
-
-add_task(function* test_form1_enabledInsecureFieldWarning_disabledInsecureAutoFillForm() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["security.insecure_field_warning.contextual.enabled", true],
- ["signon.autofillForms.http", false]
- ]});
- yield reinitializeForm(1);
-
- // Trigger autocomplete popup
- let shownPromise = promiseACShown();
- doKey("down"); // open
- let results = yield shownPromise;
-
- let popupState = yield getPopupState();
- is(popupState.selectedIndex, -1, "Check no entries are selected upon opening");
-
- let expectedMenuItems = ["This connection is not secure. Logins entered here could be compromised. Learn More",
- "No username (" + DATE_NOW_STRING + ")",
- "tempuser1",
- "testuser2",
- "testuser3",
- "zzzuser4"];
- checkArrayValues(results, expectedMenuItems, "Check all menuitems are displayed correctly.");
-
- doKey("down"); // select insecure warning
- checkACFormPasswordField(""); // value shouldn't update just by selecting
- doKey("return"); // not "enter"!
- yield spinEventLoop(); // let focus happen
- checkACFormPasswordField("");
-});
-
-add_task(function* test_form1_disabledInsecureFieldWarning_disabledInsecureAutoFillForm() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["security.insecure_field_warning.contextual.enabled", false],
- ["signon.autofillForms.http", false]
- ]});
- yield reinitializeForm(1);
-
- // Trigger autocomplete popup
- doKey("down"); // open
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is closed with no AutoFillForms.");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_passwords_in_type_password.html b/toolkit/components/passwordmgr/test/mochitest/test_passwords_in_type_password.html
deleted file mode 100644
index e107cebe6..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_passwords_in_type_password.html
+++ /dev/null
@@ -1,122 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test that passwords only get filled in type=password</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: Bug 242956
-<script>
-runChecksAfterCommonInit(() => startTest());
-</script>
-<p id="display"></p>
-<div id="content" style="display: none">
- <!-- pword is not a type=password input -->
- <form id="form1" action="formtest.js">
- <input type="text" name="uname">
- <input type="text" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- uname is not a type=text input -->
- <form id="form2" action="formtest.js">
- <input type="password" name="uname">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- two "pword" inputs, (text + password) -->
- <form id="form3" action="formtest.js">
- <input type="text" name="uname">
- <input type="text" name="pword">
- <input type="password" name="qword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- same thing, different order -->
- <form id="form4" action="formtest.js">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <input type="text" name="qword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- uname is not a type=text input (try a checkbox just for variety) -->
- <form id="form5" action="formtest.js">
- <input type="checkbox" name="uname" value="">
- <input type="password" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- pword is not a type=password input (try a checkbox just for variety) -->
- <form id="form6" action="formtest.js">
- <input type="text" name="uname">
- <input type="checkbox" name="pword" value="">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
- <!-- pword is not a type=password input -->
- <form id="form7" action="formtest.js">
- <input type="text" name="uname" value="testuser">
- <input type="text" name="pword">
-
- <button type="submit">Submit</button>
- <button type="reset"> Reset </button>
- </form>
-
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: 242956 (Stored password is inserted into a
- readable text input on a second page) **/
-
-// Make sure that pwmgr only puts passwords into type=password <input>s.
-// Might as well test the converse, too (username in password field).
-
-function startTest() {
- is($_(1, "uname").value, "", "Checking for unfilled username 1");
- is($_(1, "pword").value, "", "Checking for unfilled password 1");
-
- is($_(2, "uname").value, "testpass", "Checking for password not username 2");
- is($_(2, "pword").value, "", "Checking for unfilled password 2");
-
- is($_(3, "uname").value, "", "Checking for unfilled username 3");
- is($_(3, "pword").value, "testuser", "Checking for unfilled password 3");
- is($_(3, "qword").value, "testpass", "Checking for unfilled qassword 3");
-
- is($_(4, "uname").value, "testuser", "Checking for password not username 4");
- is($_(4, "pword").value, "testpass", "Checking for unfilled password 4");
- is($_(4, "qword").value, "", "Checking for unfilled qassword 4");
-
- is($_(5, "uname").value, "", "Checking for unfilled username 5");
- is($_(5, "pword").value, "testpass", "Checking for filled password 5");
-
- is($_(6, "uname").value, "", "Checking for unfilled username 6");
- is($_(6, "pword").value, "", "Checking for unfilled password 6");
-
- is($_(7, "uname").value, "testuser", "Checking for unmodified username 7");
- is($_(7, "pword").value, "", "Checking for unfilled password 7");
-
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt.html
deleted file mode 100644
index 1050ab66b..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt.html
+++ /dev/null
@@ -1,705 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test prompter.{prompt,promptPassword,promptUsernameAndPassword}</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-
-<div id="content" style="display: none">
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-var state, action;
-var uname = { value: null };
-var pword = { value: null };
-var result = { value: null };
-var isOk;
-
-// Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
-isTabModal = false;
-
-let prompterParent = runInParent(() => {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- const promptFac = Cc["@mozilla.org/passwordmanager/authpromptfactory;1"].
- getService(Ci.nsIPromptFactory);
-
- Cu.import("resource://gre/modules/Services.jsm");
- let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
- let prompter1 = promptFac.getPrompt(chromeWin, Ci.nsIAuthPrompt);
-
- addMessageListener("proxyPrompter", function onMessage(msg) {
- let rv = prompter1[msg.methodName](...msg.args);
- return {
- rv,
- // Send the args back to content so out/inout args can be checked.
- args: msg.args,
- };
- });
-});
-
-let prompter1 = new PrompterProxy(prompterParent);
-
-const defaultTitle = "the title";
-const defaultMsg = "the message";
-
-function initLogins() {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- var login1, login2A, login2B, login2C, login2D, login2E;
- var pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
-
- login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2D = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2E = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
- login1.init("http://example.com", null, "http://example.com",
- "", "examplepass", "", "");
- login2A.init("http://example2.com", null, "http://example2.com",
- "user1name", "user1pass", "", "");
- login2B.init("http://example2.com", null, "http://example2.com",
- "user2name", "user2pass", "", "");
- login2C.init("http://example2.com", null, "http://example2.com",
- "user3.name@host", "user3pass", "", "");
- login2D.init("http://example2.com", null, "http://example2.com",
- "100@beef", "user3pass", "", "");
- login2E.init("http://example2.com", null, "http://example2.com",
- "100%beef", "user3pass", "", "");
-
- pwmgr.addLogin(login1);
- pwmgr.addLogin(login2A);
- pwmgr.addLogin(login2B);
- pwmgr.addLogin(login2C);
- pwmgr.addLogin(login2D);
- pwmgr.addLogin(login2E);
-}
-
-add_task(function* setup() {
- runInParent(initLogins);
-});
-
-add_task(function* test_prompt_accept() {
- state = {
- msg : "the message",
- title : "the title",
- textValue : "abc",
- passValue : "",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- textField : "xyz",
- };
- promptDone = handlePrompt(state, action);
- isOk = prompter1.prompt(defaultTitle, defaultMsg, "http://example.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, "abc", result);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- is(result.value, "xyz", "Checking prompt() returned value");
-});
-
-add_task(function* test_prompt_cancel() {
- state = {
- msg : "the message",
- title : "the title",
- textValue : "abc",
- passValue : "",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "cancel",
- };
- promptDone = handlePrompt(state, action);
- isOk = prompter1.prompt(defaultTitle, defaultMsg, "http://example.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, "abc", result);
- yield promptDone;
- ok(!isOk, "Checking dialog return value (cancel)");
-});
-
-add_task(function* test_promptPassword_defaultAccept() {
- // Default password provided, existing logins are ignored.
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "inputpw",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "secret",
- };
- pword.value = "inputpw";
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://example.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "secret", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_defaultCancel() {
- // Default password provided, existing logins are ignored.
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "inputpw",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "cancel",
- };
- pword.value = "inputpw";
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://example.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- yield promptDone;
- ok(!isOk, "Checking dialog return value (cancel)");
-});
-
-add_task(function* test_promptPassword_emptyAccept() {
- // No default password provided, realm does not match existing login.
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "secret",
- };
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://nonexample.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "secret", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_saved() {
- // No default password provided, matching login is returned w/o prompting.
- pword.value = null;
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://example.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "examplepass", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_noMatchingPasswordForEmptyUN() {
- // No default password provided, none of the logins from this host are
- // password-only so the user is prompted.
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "secret",
- };
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "secret", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_matchingPWForUN() {
- // No default password provided, matching login is returned w/o prompting.
- pword.value = null;
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://user1name@example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "user1pass", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_matchingPWForUN2() {
- // No default password provided, matching login is returned w/o prompting.
- pword.value = null;
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://user2name@example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "user2pass", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_matchingPWForUN3() {
- // No default password provided, matching login is returned w/o prompting.
- pword.value = null;
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://user3%2Ename%40host@example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "user3pass", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_extraAt() {
- // No default password provided, matching login is returned w/o prompting.
- pword.value = null;
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://100@beef@example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "user3pass", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_usernameEncoding() {
- // No default password provided, matching login is returned w/o prompting.
- pword.value = null;
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "http://100%25beef@example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "user3pass", "Checking returned password");
-
- // XXX test saving a password with Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY
-});
-
-add_task(function* test_promptPassword_realm() {
- // We don't pre-fill or save for NS_GetAuthKey-generated realms, but we should still prompt
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "fill2pass",
- };
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "example2.com:80 (somerealm)",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "fill2pass", "Checking returned password");
-});
-
-add_task(function* test_promptPassword_realm2() {
- // We don't pre-fill or save for NS_GetAuthKey-generated realms, but we should still prompt
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "fill2pass",
- };
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptPassword(defaultTitle, defaultMsg, "example2.com:80 (somerealm)",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(pword.value, "fill2pass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_accept() {
- state = {
- msg : "the message",
- title : "the title",
- textValue : "inuser",
- passValue : "inpass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- textField : "outuser",
- passField : "outpass",
- };
- uname.value = "inuser";
- pword.value = "inpass";
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://nonexample.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "outuser", "Checking returned username");
- is(pword.value, "outpass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_cancel() {
- state = {
- msg : "the message",
- title : "the title",
- textValue : "inuser",
- passValue : "inpass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "cancel",
- };
- uname.value = "inuser";
- pword.value = "inpass";
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://nonexample.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, uname, pword);
- yield promptDone;
- ok(!isOk, "Checking dialog return value (cancel)");
-});
-
-add_task(function* test_promptUsernameAndPassword_autofill() {
- // test filling in existing password-only login
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "examplepass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- checkMsg : "Use Password Manager to remember this password.",
- checked : true,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- uname.value = null;
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://example.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "", "Checking returned username");
- is(pword.value, "examplepass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_multipleExisting() {
- // test filling in existing login (undetermined from multiple selection)
- // user2name/user2pass would also be valid to fill here.
- state = {
- msg : "the message",
- title : "the title",
- textValue : "user1name",
- passValue : "user1pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- checkMsg : "Use Password Manager to remember this password.",
- checked : true,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- uname.value = null;
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- ok(uname.value == "user1name" || uname.value == "user2name", "Checking returned username");
- ok(pword.value == "user1pass" || uname.value == "user2pass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_multipleExisting1() {
- // test filling in existing login (user1 from multiple selection)
- state = {
- msg : "the message",
- title : "the title",
- textValue : "user1name",
- passValue : "user1pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- checkMsg : "Use Password Manager to remember this password.",
- checked : true,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- uname.value = "user1name";
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "user1name", "Checking returned username");
- is(pword.value, "user1pass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_multipleExisting2() {
- // test filling in existing login (user2 from multiple selection)
- state = {
- msg : "the message",
- title : "the title",
- textValue : "user2name",
- passValue : "user2pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- checkMsg : "Use Password Manager to remember this password.",
- checked : true,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- uname.value = "user2name";
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "user2name", "Checking returned username");
- is(pword.value, "user2pass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_passwordChange() {
- // test changing password
- state = {
- msg : "the message",
- title : "the title",
- textValue : "user2name",
- passValue : "user2pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- checkMsg : "Use Password Manager to remember this password.",
- checked : true,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "NEWuser2pass",
- };
- uname.value = "user2name";
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "user2name", "Checking returned username");
- is(pword.value, "NEWuser2pass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_changePasswordBack() {
- // test changing password (back to original value)
- state = {
- msg : "the message",
- title : "the title",
- textValue : "user2name",
- passValue : "NEWuser2pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- checkMsg : "Use Password Manager to remember this password.",
- checked : true,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "user2pass",
- };
- uname.value = "user2name";
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "http://example2.com",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "user2name", "Checking returned username");
- is(pword.value, "user2pass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_realm() {
- // We don't pre-fill or save for NS_GetAuthKey-generated realms, but we should still prompt
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- textField : "fill2user",
- passField : "fill2pass",
- };
- uname.value = null;
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "example2.com:80 (somerealm)",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_NEVER, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "fill2user", "Checking returned username");
- is(pword.value, "fill2pass", "Checking returned password");
-});
-
-add_task(function* test_promptUsernameAndPassword_realm2() {
- // We don't pre-fill or save for NS_GetAuthKey-generated realms, but we should still prompt
- state = {
- msg : "the message",
- title : "the title",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- textField : "fill2user",
- passField : "fill2pass",
- };
- uname.value = null;
- pword.value = null;
- promptDone = handlePrompt(state, action);
- isOk = prompter1.promptUsernameAndPassword(defaultTitle, defaultMsg, "example2.com:80 (somerealm)",
- Ci.nsIAuthPrompt.SAVE_PASSWORD_PERMANENTLY, uname, pword);
- yield promptDone;
- ok(isOk, "Checking dialog return value (accept)");
- is(uname.value, "fill2user", "Checking returned username");
- is(pword.value, "fill2pass", "Checking returned password");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt_http.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt_http.html
deleted file mode 100644
index 0dc8fdf9c..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_http.html
+++ /dev/null
@@ -1,362 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test HTTP auth prompts by loading authenticate.sjs</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-
-<div id="content" style="display: none">
- <iframe id="iframe"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-var iframe = document.getElementById("iframe");
-
-// Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
-isTabModal = false;
-
-const AUTHENTICATE_PATH = new URL("authenticate.sjs", window.location.href).pathname;
-
-let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-runInParent(() => {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- let pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
-
- let login3A, login3B, login4;
- login3A = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login3B = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login4 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let httpUpgradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let httpsDowngradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let dedupeHttpUpgradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let dedupeHttpsUpgradeLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
-
- login3A.init("http://mochi.test:8888", null, "mochitest",
- "mochiuser1", "mochipass1", "", "");
- login3B.init("http://mochi.test:8888", null, "mochitest2",
- "mochiuser2", "mochipass2", "", "");
- login4.init("http://mochi.test:8888", null, "mochitest3",
- "mochiuser3", "mochipass3-old", "", "");
- // Logins to test scheme upgrades (allowed) and downgrades (disallowed)
- httpUpgradeLogin.init("http://example.com", null, "schemeUpgrade",
- "httpUser", "httpPass", "", "");
- httpsDowngradeLogin.init("https://example.com", null, "schemeDowngrade",
- "httpsUser", "httpsPass", "", "");
- // HTTP and HTTPS version of the same domain and realm but with different passwords.
- dedupeHttpUpgradeLogin.init("http://example.org", null, "schemeUpgradeDedupe",
- "dedupeUser", "httpPass", "", "");
- dedupeHttpsUpgradeLogin.init("https://example.org", null, "schemeUpgradeDedupe",
- "dedupeUser", "httpsPass", "", "");
-
-
- pwmgr.addLogin(login3A);
- pwmgr.addLogin(login3B);
- pwmgr.addLogin(login4);
- pwmgr.addLogin(httpUpgradeLogin);
- pwmgr.addLogin(httpsDowngradeLogin);
- pwmgr.addLogin(dedupeHttpUpgradeLogin);
- pwmgr.addLogin(dedupeHttpsUpgradeLogin);
-});
-
-add_task(function* test_iframe() {
- let state = {
- msg : "http://mochi.test:8888 is requesting your username and password. The site says: “mochitest”",
- title : "Authentication Required",
- textValue : "mochiuser1",
- passValue : "mochipass1",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- let action = {
- buttonClick : "ok",
- };
- promptDone = handlePrompt(state, action);
-
- // The following tests are driven by iframe loads
-
- var iframeLoaded = onloadPromiseFor("iframe");
- iframe.src = "authenticate.sjs?user=mochiuser1&pass=mochipass1";
- yield promptDone;
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "mochiuser1", pass: "mochipass1"},
- iframe.contentDocument);
-
- state = {
- msg : "http://mochi.test:8888 is requesting your username and password. The site says: “mochitest2”",
- title : "Authentication Required",
- textValue : "mochiuser2",
- passValue : "mochipass2",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- promptDone = handlePrompt(state, action);
- // We've already authenticated to this host:port. For this next
- // request, the existing auth should be sent, we'll get a 401 reply,
- // and we should prompt for new auth.
- iframeLoaded = onloadPromiseFor("iframe");
- iframe.src = "authenticate.sjs?user=mochiuser2&pass=mochipass2&realm=mochitest2";
- yield promptDone;
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "mochiuser2", pass: "mochipass2"},
- iframe.contentDocument);
-
- // Now make a load that requests the realm from test 1000. It was
- // already provided there, so auth will *not* be prompted for -- the
- // networking layer already knows it!
- iframeLoaded = onloadPromiseFor("iframe");
- iframe.src = "authenticate.sjs?user=mochiuser1&pass=mochipass1";
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "mochiuser1", pass: "mochipass1"},
- iframe.contentDocument);
-
- // Same realm we've already authenticated to, but with a different
- // expected password (to trigger an auth prompt, and change-password
- // popup notification).
- state = {
- msg : "http://mochi.test:8888 is requesting your username and password. The site says: “mochitest”",
- title : "Authentication Required",
- textValue : "mochiuser1",
- passValue : "mochipass1",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "mochipass1-new",
- };
- promptDone = handlePrompt(state, action);
- iframeLoaded = onloadPromiseFor("iframe");
- let promptShownPromise = promisePromptShown("passwordmgr-prompt-change");
- iframe.src = "authenticate.sjs?user=mochiuser1&pass=mochipass1-new";
- yield promptDone;
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "mochiuser1", pass: "mochipass1-new"},
- iframe.contentDocument);
- yield promptShownPromise;
-
- // Same as last test, but for a realm we haven't already authenticated
- // to (but have an existing saved login for, so that we'll trigger
- // a change-password popup notification.
- state = {
- msg : "http://mochi.test:8888 is requesting your username and password. The site says: “mochitest3”",
- title : "Authentication Required",
- textValue : "mochiuser3",
- passValue : "mochipass3-old",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- passField : "mochipass3-new",
- };
- promptDone = handlePrompt(state, action);
- iframeLoaded = onloadPromiseFor("iframe");
- promptShownPromise = promisePromptShown("passwordmgr-prompt-change");
- iframe.src = "authenticate.sjs?user=mochiuser3&pass=mochipass3-new&realm=mochitest3";
- yield promptDone;
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "mochiuser3", pass: "mochipass3-new"},
- iframe.contentDocument);
- yield promptShownPromise;
-
- // Housekeeping: Delete login4 to test the save prompt in the next test.
- runInParent(() => {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- var tmpLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- tmpLogin.init("http://mochi.test:8888", null, "mochitest3",
- "mochiuser3", "mochipass3-old", "", "");
- Services.logins.removeLogin(tmpLogin);
-
- // Clear cached auth from this subtest, and avoid leaking due to bug 459620.
- var authMgr = Cc['@mozilla.org/network/http-auth-manager;1'].
- getService(Ci.nsIHttpAuthManager);
- authMgr.clearAll();
- });
-
- state = {
- msg : "http://mochi.test:8888 is requesting your username and password. The site says: “mochitest3”",
- title : "Authentication Required",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- textField : "mochiuser3",
- passField : "mochipass3-old",
- };
- // Trigger a new prompt, so we can test adding a new login.
- promptDone = handlePrompt(state, action);
-
- iframeLoaded = onloadPromiseFor("iframe");
- promptShownPromise = promisePromptShown("passwordmgr-prompt-save");
- iframe.src = "authenticate.sjs?user=mochiuser3&pass=mochipass3-old&realm=mochitest3";
- yield promptDone;
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "mochiuser3", pass: "mochipass3-old"},
- iframe.contentDocument);
- yield promptShownPromise;
-});
-
-add_task(function* test_schemeUpgrade() {
- let state = {
- msg : "https://example.com is requesting your username and password. " +
- "WARNING: Your password will not be sent to the website you are currently visiting!",
- title : "Authentication Required",
- textValue : "httpUser",
- passValue : "httpPass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- let action = {
- buttonClick : "ok",
- };
- let promptDone = handlePrompt(state, action);
-
- // The following tests are driven by iframe loads
-
- let iframeLoaded = onloadPromiseFor("iframe");
- iframe.src = "https://example.com" + AUTHENTICATE_PATH +
- "?user=httpUser&pass=httpPass&realm=schemeUpgrade";
- yield promptDone;
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "httpUser", pass: "httpPass"},
- SpecialPowers.wrap(iframe).contentDocument);
-});
-
-add_task(function* test_schemeDowngrade() {
- let state = {
- msg : "http://example.com is requesting your username and password. " +
- "WARNING: Your password will not be sent to the website you are currently visiting!",
- title : "Authentication Required",
- textValue : "", // empty because we shouldn't downgrade
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- let action = {
- buttonClick : "cancel",
- };
- let promptDone = handlePrompt(state, action);
-
- // The following tests are driven by iframe loads
-
- let iframeLoaded = onloadPromiseFor("iframe");
- iframe.src = "http://example.com" + AUTHENTICATE_PATH +
- "?user=unused&pass=unused&realm=schemeDowngrade";
- yield promptDone;
- yield iframeLoaded;
-});
-
-add_task(function* test_schemeUpgrade_dedupe() {
- let state = {
- msg : "https://example.org is requesting your username and password. " +
- "WARNING: Your password will not be sent to the website you are currently visiting!",
- title : "Authentication Required",
- textValue : "dedupeUser",
- passValue : "httpsPass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- let action = {
- buttonClick : "ok",
- };
- let promptDone = handlePrompt(state, action);
-
- // The following tests are driven by iframe loads
-
- let iframeLoaded = onloadPromiseFor("iframe");
- iframe.src = "https://example.org" + AUTHENTICATE_PATH +
- "?user=dedupeUser&pass=httpsPass&realm=schemeUpgradeDedupe";
- yield promptDone;
- yield iframeLoaded;
- checkEchoedAuthInfo({user: "dedupeUser", pass: "httpsPass"},
- SpecialPowers.wrap(iframe).contentDocument);
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt_noWindow.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt_noWindow.html
deleted file mode 100644
index 92af172ca..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_noWindow.html
+++ /dev/null
@@ -1,81 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test HTTP auth prompts by loading authenticate.sjs with no window</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-
-<div id="content" style="display: none">
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-// Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
-isTabModal = false;
-
-let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-runInParent(() => {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
-
- let login = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login.init("http://mochi.test:8888", null, "mochitest",
- "mochiuser1", "mochipass1", "", "");
- Services.logins.addLogin(login);
-});
-
-add_task(function* test_sandbox_xhr() {
- let state = {
- msg : "http://mochi.test:8888 is requesting your username and password. The site says: “mochitest”",
- title : "Authentication Required",
- textValue : "mochiuser1",
- passValue : "mochipass1",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- let action = {
- buttonClick : "ok",
- };
- let promptDone = handlePrompt(state, action);
-
- let url = new URL("authenticate.sjs?user=mochiuser1&pass=mochipass1", window.location.href);
- let sandboxConstructor = SpecialPowers.Cu.Sandbox;
- let sandbox = new sandboxConstructor(this, {wantXrays: true});
- function sandboxedRequest(sandboxedUrl) {
- let req = SpecialPowers.Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
- .createInstance(SpecialPowers.Ci.nsIXMLHttpRequest);
- req.open("GET", sandboxedUrl, true);
- req.send(null);
- }
-
- let loginModifiedPromise = promiseStorageChanged(["modifyLogin"]);
- sandbox.sandboxedRequest = sandboxedRequest(url);
- info("send the XHR request in the sandbox");
- SpecialPowers.Cu.evalInSandbox("sandboxedRequest;", sandbox);
-
- yield promptDone;
- info("prompt shown, waiting for metadata updates");
- // Ensure the timeLastUsed and timesUsed metadata are updated.
- yield loginModifiedPromise;
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth.html
deleted file mode 100644
index 36f53a54a..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth.html
+++ /dev/null
@@ -1,406 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test promptAuth prompts</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-
-<div id="content" style="display: none">
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-var state, action;
-var isOk;
-
-var level = Ci.nsIAuthPrompt2.LEVEL_NONE;
-var authinfo = {
- username : "",
- password : "",
- domain : "",
-
- flags : Ci.nsIAuthInformation.AUTH_HOST,
- authenticationScheme : "basic",
- realm : ""
-};
-
-// Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
-isTabModal = false;
-
-let chromeScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-let prompterParent = runInParent(() => {
- const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
- const promptFac = Cc["@mozilla.org/passwordmanager/authpromptfactory;1"].
- getService(Ci.nsIPromptFactory);
-
- Cu.import("resource://gre/modules/Services.jsm");
- let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
- let prompter2 = promptFac.getPrompt(chromeWin, Ci.nsIAuthPrompt2);
-
- let ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- let channels = {};
- channels.channel1 = ioService.newChannel2("http://example.com",
- null,
- null,
- null, // aLoadingNode
- Services.
- scriptSecurityManager.getSystemPrincipal(),
- null, // aTriggeringPrincipal
- Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
- Ci.nsIContentPolicy.TYPE_OTHER);
-
- channels.channel2 = ioService.newChannel2("http://example2.com",
- null,
- null,
- null, // aLoadingNode
- Services.
- scriptSecurityManager.getSystemPrincipal(),
- null, // aTriggeringPrincipal
- Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
- Ci.nsIContentPolicy.TYPE_OTHER);
-
- addMessageListener("proxyPrompter", function onMessage(msg) {
- let args = [...msg.args];
- let channelName = args.shift();
- // Replace the channel name string (arg. 0) with the channel by that name.
- args.unshift(channels[channelName]);
-
- let rv = prompter2[msg.methodName](...args);
- return {
- rv,
- // Send the args back to content so out/inout args can be checked.
- args: msg.args,
- };
- });
-
- Cu.import("resource://gre/modules/Services.jsm");
-
- let pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
-
- let login1, login2A, login2B, login2C, login2D, login2E;
- login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2D = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2E = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
- login1.init("http://example.com", null, "http://example.com",
- "", "examplepass", "", "");
- login2A.init("http://example2.com", null, "http://example2.com",
- "user1name", "user1pass", "", "");
- login2B.init("http://example2.com", null, "http://example2.com",
- "user2name", "user2pass", "", "");
- login2C.init("http://example2.com", null, "http://example2.com",
- "user3.name@host", "user3pass", "", "");
- login2D.init("http://example2.com", null, "http://example2.com",
- "100@beef", "user3pass", "", "");
- login2E.init("http://example2.com", null, "http://example2.com",
- "100%beef", "user3pass", "", "");
-
- pwmgr.addLogin(login1);
- pwmgr.addLogin(login2A);
- pwmgr.addLogin(login2B);
- pwmgr.addLogin(login2C);
- pwmgr.addLogin(login2D);
- pwmgr.addLogin(login2E);
-});
-
-let prompter2 = new PrompterProxy(prompterParent);
-
-add_task(function* test_accept() {
- state = {
- msg : "http://example.com is requesting your username and password. The site says: “some realm”",
- title : "Authentication Required",
- textValue : "inuser",
- passValue : "inpass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- textField : "outuser",
- passField : "outpass",
- };
- authinfo.username = "inuser";
- authinfo.password = "inpass";
- authinfo.realm = "some realm";
-
- promptDone = handlePrompt(state, action);
- // Since prompter2 is actually a proxy to send a message to a chrome script and
- // we can't send a channel in a message, we instead send the channel name that
- // already exists in the chromeScript.
- isOk = prompter2.promptAuth("channel1", level, authinfo);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- is(authinfo.username, "outuser", "Checking returned username");
- is(authinfo.password, "outpass", "Checking returned password");
-});
-
-add_task(function* test_cancel() {
- state = {
- msg : "http://example.com is requesting your username and password. The site says: “some realm”",
- title : "Authentication Required",
- textValue : "outuser",
- passValue : "outpass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "cancel",
- };
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth("channel1", level, authinfo);
- yield promptDone;
-
- ok(!isOk, "Checking dialog return value (cancel)");
-});
-
-add_task(function* test_pwonly() {
- // test filling in password-only login
- state = {
- msg : "http://example.com is requesting your username and password. The site says: “http://example.com”",
- title : "Authentication Required",
- textValue : "",
- passValue : "examplepass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- authinfo.username = "";
- authinfo.password = "";
- authinfo.realm = "http://example.com";
-
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth("channel1", level, authinfo);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- is(authinfo.username, "", "Checking returned username");
- is(authinfo.password, "examplepass", "Checking returned password");
-});
-
-add_task(function* test_multipleExisting() {
- // test filling in existing login (undetermined from multiple selection)
- // user2name/user2pass would also be valid to fill here.
- state = {
- msg : "http://example2.com is requesting your username and password. The site says: “http://example2.com”",
- title : "Authentication Required",
- textValue : "user1name",
- passValue : "user1pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- authinfo.username = "";
- authinfo.password = "";
- authinfo.realm = "http://example2.com";
-
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth("channel2", level, authinfo);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- ok(authinfo.username == "user1name" || authinfo.username == "user2name", "Checking returned username");
- ok(authinfo.password == "user1pass" || authinfo.password == "user2pass", "Checking returned password");
-});
-
-add_task(function* test_multipleExisting2() {
- // test filling in existing login (undetermined --> user1)
- // user2name/user2pass would also be valid to fill here.
- state = {
- msg : "http://example2.com is requesting your username and password. The site says: “http://example2.com”",
- title : "Authentication Required",
- textValue : "user1name",
- passValue : "user1pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- // enter one of the known logins, test 504+505 exercise the two possible states.
- action = {
- buttonClick : "ok",
- textField : "user1name",
- passField : "user1pass",
- };
- authinfo.username = "";
- authinfo.password = "";
- authinfo.realm = "http://example2.com";
-
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth("channel2", level, authinfo);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- is(authinfo.username, "user1name", "Checking returned username");
- is(authinfo.password, "user1pass", "Checking returned password");
-});
-
-add_task(function* test_multipleExisting3() {
- // test filling in existing login (undetermined --> user2)
- // user2name/user2pass would also be valid to fill here.
- state = {
- msg : "http://example2.com is requesting your username and password. The site says: “http://example2.com”",
- title : "Authentication Required",
- textValue : "user1name",
- passValue : "user1pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- // enter one of the known logins, test 504+505 exercise the two possible states.
- action = {
- buttonClick : "ok",
- textField : "user2name",
- passField : "user2pass",
- };
- authinfo.username = "";
- authinfo.password = "";
- authinfo.realm = "http://example2.com";
-
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth("channel2", level, authinfo);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- is(authinfo.username, "user2name", "Checking returned username");
- is(authinfo.password, "user2pass", "Checking returned password");
-});
-
-add_task(function* test_changingMultiple() {
- // test changing a password (undetermined --> user2 w/ newpass)
- // user2name/user2pass would also be valid to fill here.
- state = {
- msg : "http://example2.com is requesting your username and password. The site says: “http://example2.com”",
- title : "Authentication Required",
- textValue : "user1name",
- passValue : "user1pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- // force to user2, and change the password
- action = {
- buttonClick : "ok",
- textField : "user2name",
- passField : "NEWuser2pass",
- };
- authinfo.username = "";
- authinfo.password = "";
- authinfo.realm = "http://example2.com";
-
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth("channel2", level, authinfo);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- is(authinfo.username, "user2name", "Checking returned username");
- is(authinfo.password, "NEWuser2pass", "Checking returned password");
-});
-
-add_task(function* test_changingMultiple2() {
- // test changing a password (undetermined --> user2 w/ origpass)
- // user2name/user2pass would also be valid to fill here.
- state = {
- msg : "http://example2.com is requesting your username and password. The site says: “http://example2.com”",
- title : "Authentication Required",
- textValue : "user1name",
- passValue : "user1pass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- // force to user2, and change the password back
- action = {
- buttonClick : "ok",
- textField : "user2name",
- passField : "user2pass",
- };
- authinfo.username = "";
- authinfo.password = "";
- authinfo.realm = "http://example2.com";
-
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth("channel2", level, authinfo);
- yield promptDone;
-
- ok(isOk, "Checking dialog return value (accept)");
- is(authinfo.username, "user2name", "Checking returned username");
- is(authinfo.password, "user2pass", "Checking returned password");
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html b/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html
deleted file mode 100644
index 95dd4c7bc..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_prompt_promptAuth_proxy.html
+++ /dev/null
@@ -1,264 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test promptAuth proxy prompts</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-
-<div id="content" style="display: none">
- <iframe id="iframe"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-var state, action;
-var pwmgr;
-var proxyLogin;
-var isOk;
-var mozproxy, proxiedHost = "http://mochi.test:8888";
-var proxyChannel;
-var systemPrincipal = SpecialPowers.Services.scriptSecurityManager.getSystemPrincipal();
-var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
-
-var prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
-
-var level = Ci.nsIAuthPrompt2.LEVEL_NONE;
-
-var proxyAuthinfo = {
- username : "",
- password : "",
- domain : "",
-
- flags : Ci.nsIAuthInformation.AUTH_PROXY,
- authenticationScheme : "basic",
- realm : ""
-};
-
-// Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
-isTabModal = false;
-
-const Cc_promptFac = Cc["@mozilla.org/passwordmanager/authpromptfactory;1"];
-ok(Cc_promptFac != null, "Access Cc[@mozilla.org/passwordmanager/authpromptfactory;1]");
-
-const Ci_promptFac = Ci.nsIPromptFactory;
-ok(Ci_promptFac != null, "Access Ci.nsIPromptFactory");
-
-const promptFac = Cc_promptFac.getService(Ci_promptFac);
-ok(promptFac != null, "promptFac getService()");
-
-var prompter2 = promptFac.getPrompt(window, Ci.nsIAuthPrompt2);
-
-function initLogins(pi) {
- pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
-
- mozproxy = "moz-proxy://" + SpecialPowers.wrap(pi).host + ":" +
- SpecialPowers.wrap(pi).port;
-
- proxyLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
- proxyLogin.init(mozproxy, null, "Proxy Realm",
- "proxuser", "proxpass", "", "");
-
- pwmgr.addLogin(proxyLogin);
-}
-
-var startupCompleteResolver;
-var startupComplete = new Promise(resolve => startupCompleteResolver = resolve);
-
-function proxyChannelListener() { }
-proxyChannelListener.prototype = {
- onStartRequest: function(request, context) {
- startupCompleteResolver();
- },
- onStopRequest: function(request, context, status) { }
-};
-
-var resolveCallback = SpecialPowers.wrapCallbackObject({
- QueryInterface : function (iid) {
- const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports];
-
- if (!interfaces.some( function(v) { return iid.equals(v); } ))
- throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- onProxyAvailable : function (req, uri, pi, status) {
- initLogins(pi);
-
- // I'm cheating a bit here... We should probably do some magic foo to get
- // something implementing nsIProxiedProtocolHandler and then call
- // NewProxiedChannel(), so we have something that's definately a proxied
- // channel. But Mochitests use a proxy for a number of hosts, so just
- // requesting a normal channel will give us a channel that's proxied.
- // The proxyChannel needs to move to at least on-modify-request to
- // have valid ProxyInfo, but we use OnStartRequest during startup()
- // for simplicity.
- proxyChannel = ioService.newChannel2(proxiedHost,
- null,
- null,
- null, // aLoadingNode
- systemPrincipal,
- null, // aTriggeringPrincipal
- Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
- Ci.nsIContentPolicy.TYPE_OTHER);
- proxyChannel.asyncOpen2(SpecialPowers.wrapCallbackObject(new proxyChannelListener()));
- }
-});
-
-function startup() {
- // Need to allow for arbitrary network servers defined in PAC instead of a hardcoded moz-proxy.
- var ios = SpecialPowers.Cc["@mozilla.org/network/io-service;1"].
- getService(SpecialPowers.Ci.nsIIOService);
-
- var pps = SpecialPowers.Cc["@mozilla.org/network/protocol-proxy-service;1"].getService();
-
- var channel = ios.newChannel2("http://example.com",
- null,
- null,
- null, // aLoadingNode
- systemPrincipal,
- null, // aTriggeringPrincipal
- Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
- Ci.nsIContentPolicy.TYPE_OTHER);
- pps.asyncResolve(channel, 0, resolveCallback);
-}
-
-startup();
-
-add_task(function* setup() {
- info("Waiting for startup to complete...");
- yield startupComplete;
-});
-
-add_task(function* test_noAutologin() {
- // test proxy login (default = no autologin), make sure it prompts.
- state = {
- msg : "The proxy moz-proxy://127.0.0.1:8888 is requesting a username and password. The site says: “Proxy Realm”",
- title : "Authentication Required",
- textValue : "proxuser",
- passValue : "proxpass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
- proxyAuthinfo.username = "";
- proxyAuthinfo.password = "";
- proxyAuthinfo.realm = "Proxy Realm";
- proxyAuthinfo.flags = Ci.nsIAuthInformation.AUTH_PROXY;
-
- var time1 = pwmgr.findLogins({}, mozproxy, null, "Proxy Realm")[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth(proxyChannel, level, proxyAuthinfo);
- yield promptDone;
- var time2 = pwmgr.findLogins({}, mozproxy, null, "Proxy Realm")[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
-
- ok(isOk, "Checking dialog return value (accept)");
- isnot(time1, time2, "Checking that timeLastUsed was updated");
- is(proxyAuthinfo.username, "proxuser", "Checking returned username");
- is(proxyAuthinfo.password, "proxpass", "Checking returned password");
-});
-
-add_task(function* test_autologin() {
- // test proxy login (with autologin)
-
- // Enable the autologin pref.
- prefs.setBoolPref("signon.autologin.proxy", true);
-
- proxyAuthinfo.username = "";
- proxyAuthinfo.password = "";
- proxyAuthinfo.realm = "Proxy Realm";
- proxyAuthinfo.flags = Ci.nsIAuthInformation.AUTH_PROXY;
-
- time1 = pwmgr.findLogins({}, mozproxy, null, "Proxy Realm")[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
- isOk = prompter2.promptAuth(proxyChannel, level, proxyAuthinfo);
- time2 = pwmgr.findLogins({}, mozproxy, null, "Proxy Realm")[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
-
- ok(isOk, "Checking dialog return value (accept)");
- isnot(time1, time2, "Checking that timeLastUsed was updated");
- is(proxyAuthinfo.username, "proxuser", "Checking returned username");
- is(proxyAuthinfo.password, "proxpass", "Checking returned password");
-});
-
-add_task(function* test_autologin_incorrect() {
- // test proxy login (with autologin), ensure it prompts after a failed auth.
- state = {
- msg : "The proxy moz-proxy://127.0.0.1:8888 is requesting a username and password. The site says: “Proxy Realm”",
- title : "Authentication Required",
- textValue : "proxuser",
- passValue : "proxpass",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- };
-
- proxyAuthinfo.username = "";
- proxyAuthinfo.password = "";
- proxyAuthinfo.realm = "Proxy Realm";
- proxyAuthinfo.flags = (Ci.nsIAuthInformation.AUTH_PROXY | Ci.nsIAuthInformation.PREVIOUS_FAILED);
-
- time1 = pwmgr.findLogins({}, mozproxy, null, "Proxy Realm")[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
- promptDone = handlePrompt(state, action);
- isOk = prompter2.promptAuth(proxyChannel, level, proxyAuthinfo);
- yield promptDone;
- time2 = pwmgr.findLogins({}, mozproxy, null, "Proxy Realm")[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
-
- ok(isOk, "Checking dialog return value (accept)");
- isnot(time1, time2, "Checking that timeLastUsed was updated");
- is(proxyAuthinfo.username, "proxuser", "Checking returned username");
- is(proxyAuthinfo.password, "proxpass", "Checking returned password");
-});
-
-add_task(function* test_autologin_private() {
- // test proxy login (with autologin), ensure it prompts in Private Browsing mode.
- state = {
- msg : "the message",
- title : "the title",
- textValue : "proxuser",
- passValue : "proxpass",
- };
- action = {
- buttonClick : "ok",
- };
-
- proxyAuthinfo.username = "";
- proxyAuthinfo.password = "";
- proxyAuthinfo.realm = "Proxy Realm";
- proxyAuthinfo.flags = Ci.nsIAuthInformation.AUTH_PROXY;
-
- prefs.clearUserPref("signon.autologin.proxy");
-
- // XXX check for and kill popup notification??
- // XXX check for checkbox / checkstate on old prompts?
- // XXX check NTLM domain stuff
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_recipe_login_fields.html b/toolkit/components/passwordmgr/test/mochitest/test_recipe_login_fields.html
deleted file mode 100644
index 943bffc52..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_recipe_login_fields.html
+++ /dev/null
@@ -1,145 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for recipes overriding login fields</title>
- <script src="/tests/SimpleTest/SimpleTest.js"></script>
- <script src="/tests/SimpleTest/SpawnTask.js"></script>
- <script src="pwmgr_common.js"></script>
- <link rel="stylesheet" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script>
-var chromeScript = runChecksAfterCommonInit();
-
-let fillPromiseResolvers = [];
-
-function waitForFills(fillCount) {
- let promises = [];
- while (fillCount--) {
- let promise = new Promise(resolve => fillPromiseResolvers.push(resolve));
- promises.push(promise);
- }
-
- return Promise.all(promises);
-}
-
-add_task(function* setup() {
- if (document.readyState !== "complete") {
- yield new Promise((resolve) => {
- document.onreadystatechange = () => {
- if (document.readyState !== "complete") {
- return;
- }
- document.onreadystatechange = null;
- resolve();
- };
- });
- }
-
- document.getElementById("content")
- .addEventListener("input", function handleInputEvent(evt) {
- let resolve = fillPromiseResolvers.shift();
- if (!resolve) {
- ok(false, "Too many fills");
- return;
- }
-
- resolve(evt.target);
- });
-});
-
-add_task(function* loadUsernamePasswordSelectorRecipes() {
- yield loadRecipes({
- siteRecipes: [{
- hosts: ["mochi.test:8888"],
- usernameSelector: "input[name='uname1']",
- passwordSelector: "input[name='pword2']",
- }],
- });
-});
-
-add_task(function* testOverriddingFields() {
- // Insert the form dynamically so autofill is triggered after setup above.
- document.getElementById("content").innerHTML = `
- <!-- form with recipe for the username and password -->
- <form id="form1">
- <input type="text" name="uname1" data-expected="true">
- <input type="text" name="uname2" data-expected="false">
- <input type="password" name="pword1" data-expected="false">
- <input type="password" name="pword2" data-expected="true">
- </form>`;
-
- let elements = yield waitForFills(2);
- for (let element of elements) {
- is(element.dataset.expected, "true", `${element.name} was filled`);
- }
-});
-
-add_task(function* testDefaultHeuristics() {
- // Insert the form dynamically so autofill is triggered after setup above.
- document.getElementById("content").innerHTML = `
- <!-- Fallback to the default heuristics since the selectors don't match -->
- <form id="form2">
- <input type="text" name="uname3" data-expected="false">
- <input type="text" name="uname4" data-expected="true">
- <input type="password" name="pword3" data-expected="true">
- <input type="password" name="pword4" data-expected="false">
- </form>`;
-
- let elements = yield waitForFills(2);
- for (let element of elements) {
- is(element.dataset.expected, "true", `${element.name} was filled`);
- }
-});
-
-add_task(function* loadNotUsernameSelectorRecipes() {
- yield resetRecipes();
- yield loadRecipes({
- siteRecipes: [{
- hosts: ["mochi.test:8888"],
- notUsernameSelector: "input[name='not_uname1']"
- }],
- });
-});
-
-add_task(function* testNotUsernameField() {
- document.getElementById("content").innerHTML = `
- <!-- The field matching notUsernameSelector should be skipped -->
- <form id="form3">
- <input type="text" name="uname5" data-expected="true">
- <input type="text" name="not_uname1" data-expected="false">
- <input type="password" name="pword5" data-expected="true">
- </form>`;
-
- let elements = yield waitForFills(2);
- for (let element of elements) {
- is(element.dataset.expected, "true", `${element.name} was filled`);
- }
-});
-
-add_task(function* testNotUsernameFieldNoUsername() {
- document.getElementById("content").innerHTML = `
- <!-- The field matching notUsernameSelector should be skipped.
- No username field should be found and filled in this case -->
- <form id="form4">
- <input type="text" name="not_uname1" data-expected="false">
- <input type="password" name="pword6" data-expected="true">
- </form>`;
-
- let elements = yield waitForFills(1);
- for (let element of elements) {
- is(element.dataset.expected, "true", `${element.name} was filled`);
- }
-});
-
-</script>
-
-<p id="display"></p>
-
-<div id="content">
- // Forms are inserted dynamically
-</div>
-<pre id="test"></pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_username_focus.html b/toolkit/components/passwordmgr/test/mochitest/test_username_focus.html
deleted file mode 100644
index c93c1e9c9..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_username_focus.html
+++ /dev/null
@@ -1,263 +0,0 @@
-
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test interaction between autocomplete and focus on username fields</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<script>
-let pwmgrCommonScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
-
-let readyPromise = registerRunTests();
-let chromeScript = runInParent(function chromeSetup() {
- const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
- let pwmgr = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
-
- let login1A = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login1B = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login2A = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login2B = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- let login2C = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
- login1A.init("http://mochi.test:8888", "http://username-focus-1", null,
- "testuser1A", "testpass1A", "", "");
-
- login2A.init("http://mochi.test:8888", "http://username-focus-2", null,
- "testuser2A", "testpass2A", "", "");
- login2B.init("http://mochi.test:8888", "http://username-focus-2", null,
- "testuser2B", "testpass2B", "", "");
-
- pwmgr.addLogin(login1A);
- pwmgr.addLogin(login2A);
- pwmgr.addLogin(login2B);
-});
-</script>
-
-<p id="display"></p>
-<div id="content">
- <!-- first 3 forms have a matching user+pass login -->
-
- <!-- user+pass form. -->
- <form id="form-autofilled" action="http://username-focus-1">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit" name="submit">Submit</button>
- </form>
-
- <!-- user+pass form, username prefilled -->
- <form id="form-autofilled-prefilled-un" action="http://username-focus-1">
- <input type="text" name="uname" value="testuser1A">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form. -->
- <form id="form-autofilled-focused-dynamic" action="http://username-focus-1">
- <input type="text" name="uname">
- <input type="not-yet-password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
-
- <!-- next 5 forms have matching user+pass (2x) logins -->
-
- <!-- user+pass form. -->
- <form id="form-multiple" action="http://username-focus-2">
- <input type="text" name="uname">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form dynamic with existing focus -->
- <form id="form-multiple-dynamic" action="http://username-focus-2">
- <input type="text" name="uname">
- <input type="not-yet-password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form, username prefilled -->
- <form id="form-multiple-prefilled-un1" action="http://username-focus-2">
- <input type="text" name="uname" value="testuser2A">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form, different username prefilled -->
- <form id="form-multiple-prefilled-un2" action="http://username-focus-2">
- <input type="text" name="uname" value="testuser2B">
- <input type="password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
- <!-- user+pass form, username prefilled with existing focus -->
- <form id="form-multiple-prefilled-focused-dynamic" action="http://username-focus-2">
- <input type="text" name="uname" value="testuser2B">
- <input type="not-yet-password" name="pword">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-function removeFocus() {
- $_("-autofilled", "submit").focus();
-}
-
-add_task(function* setup() {
- yield SpecialPowers.pushPrefEnv({"set": [
- ["security.insecure_field_warning.contextual.enabled", false],
- ]});
-
- ok(readyPromise, "check promise is available");
- yield readyPromise;
-});
-
-add_task(function* test_autofilled() {
- let usernameField = $_("-autofilled", "uname");
- info("Username and password already filled so don't show autocomplete");
- let noPopupPromise = promiseNoUnexpectedPopupShown();
- usernameField.focus();
- yield noPopupPromise;
-
- removeFocus();
- usernameField.value = "testuser";
- info("Focus when we don't have an exact match");
- shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
-});
-
-add_task(function* test_autofilled_prefilled_un() {
- let usernameField = $_("-autofilled-prefilled-un", "uname");
- info("Username and password already filled so don't show autocomplete");
- let noPopupPromise = promiseNoUnexpectedPopupShown();
- usernameField.focus();
- yield noPopupPromise;
-
- removeFocus();
- usernameField.value = "testuser";
- info("Focus when we don't have an exact match");
- shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
-});
-
-add_task(function* test_autofilled_focused_dynamic() {
- let usernameField = $_("-autofilled-focused-dynamic", "uname");
- let passwordField = $_("-autofilled-focused-dynamic", "pword");
- info("Username and password will be filled while username focused");
- let noPopupPromise = promiseNoUnexpectedPopupShown();
- usernameField.focus();
- yield noPopupPromise;
- info("triggering autofill");
- noPopupPromise = promiseNoUnexpectedPopupShown();
- passwordField.type = "password";
- yield noPopupPromise;
-
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is closed");
-
- removeFocus();
- passwordField.value = "test";
- info("Focus when we don't have an exact match");
- shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
-});
-
-// Begin testing forms that have multiple saved logins
-
-add_task(function* test_multiple() {
- let usernameField = $_("-multiple", "uname");
- info("Fields not filled due to multiple so autocomplete upon focus");
- shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
-});
-
-add_task(function* test_multiple_dynamic() {
- let usernameField = $_("-multiple-dynamic", "uname");
- let passwordField = $_("-multiple-dynamic", "pword");
- info("Fields not filled but username is focused upon marking so open");
- let noPopupPromise = promiseNoUnexpectedPopupShown();
- usernameField.focus();
- yield noPopupPromise;
-
- info("triggering _fillForm code");
- let shownPromise = promiseACShown();
- passwordField.type = "password";
- yield shownPromise;
-});
-
-add_task(function* test_multiple_prefilled_un1() {
- let usernameField = $_("-multiple-prefilled-un1", "uname");
- info("Username and password already filled so don't show autocomplete");
- let noPopupPromise = promiseNoUnexpectedPopupShown();
- usernameField.focus();
- yield noPopupPromise;
-
- removeFocus();
- usernameField.value = "testuser";
- info("Focus when we don't have an exact match");
- shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
-});
-
-add_task(function* test_multiple_prefilled_un2() {
- let usernameField = $_("-multiple-prefilled-un2", "uname");
- info("Username and password already filled so don't show autocomplete");
- let noPopupPromise = promiseNoUnexpectedPopupShown();
- usernameField.focus();
- yield noPopupPromise;
-
- removeFocus();
- usernameField.value = "testuser";
- info("Focus when we don't have an exact match");
- shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
-});
-
-add_task(function* test_multiple_prefilled_focused_dynamic() {
- let usernameField = $_("-multiple-prefilled-focused-dynamic", "uname");
- let passwordField = $_("-multiple-prefilled-focused-dynamic", "pword");
- info("Username and password will be filled while username focused");
- let noPopupPromise = promiseNoUnexpectedPopupShown();
- usernameField.focus();
- yield noPopupPromise;
- info("triggering autofill");
- noPopupPromise = promiseNoUnexpectedPopupShown();
- passwordField.type = "password";
- yield noPopupPromise;
-
- let popupState = yield getPopupState();
- is(popupState.open, false, "Check popup is closed");
-
- removeFocus();
- passwordField.value = "test";
- info("Focus when we don't have an exact match");
- shownPromise = promiseACShown();
- usernameField.focus();
- yield shownPromise;
-});
-
-add_task(function* cleanup() {
- removeFocus();
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/mochitest/test_xhr_2.html b/toolkit/components/passwordmgr/test/mochitest/test_xhr_2.html
deleted file mode 100644
index fa8357792..000000000
--- a/toolkit/components/passwordmgr/test/mochitest/test_xhr_2.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=654348
--->
-<head>
- <meta charset="utf-8">
- <title>Test XHR auth with user and pass arguments</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body onload="startTest()">
-<script class="testbody" type="text/javascript">
-
-/**
- * This test checks we correctly ignore authentication entry
- * for a subpath and use creds from the URL when provided when XHR
- * is used with filled user name and password.
- *
- * 1. connect authenticate.sjs that excepts user1:pass1 password
- * 2. connect authenticate.sjs that this time expects differentuser2:pass2 password
- * we must use the creds that are provided to the xhr witch are different and expected
- */
-
-function doxhr(URL, user, pass, code, next) {
- var xhr = new XMLHttpRequest();
- if (user && pass)
- xhr.open("POST", URL, true, user, pass);
- else
- xhr.open("POST", URL, true);
- xhr.onload = function() {
- is(xhr.status, code, "expected response code " + code);
- next();
- };
- xhr.onerror = function() {
- ok(false, "request passed");
- finishTest();
- };
- xhr.send();
-}
-
-function startTest() {
- doxhr("authenticate.sjs?user=dummy&pass=pass1&realm=realm1&formauth=1", "dummy", "dummy", 403, function() {
- doxhr("authenticate.sjs?user=dummy&pass=pass1&realm=realm1&formauth=1", "dummy", "pass1", 200, finishTest);
- });
-}
-
-function finishTest() {
- SimpleTest.finish();
-}
-
-</script>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/prompt_common.js b/toolkit/components/passwordmgr/test/prompt_common.js
deleted file mode 100644
index 267e697ae..000000000
--- a/toolkit/components/passwordmgr/test/prompt_common.js
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * NOTE:
- * This file is currently only being used for tests which haven't been
- * fixed to work with e10s. Favor using the `prompt_common.js` file that
- * is in `toolkit/components/prompts/test/` instead.
- */
-
-var Ci = SpecialPowers.Ci;
-ok(Ci != null, "Access Ci");
-var Cc = SpecialPowers.Cc;
-ok(Cc != null, "Access Cc");
-
-var didDialog;
-
-var timer; // keep in outer scope so it's not GC'd before firing
-function startCallbackTimer() {
- didDialog = false;
-
- // Delay before the callback twiddles the prompt.
- const dialogDelay = 10;
-
- // Use a timer to invoke a callback to twiddle the authentication dialog
- timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.init(observer, dialogDelay, Ci.nsITimer.TYPE_ONE_SHOT);
-}
-
-
-var observer = SpecialPowers.wrapCallbackObject({
- QueryInterface : function (iid) {
- const interfaces = [Ci.nsIObserver,
- Ci.nsISupports, Ci.nsISupportsWeakReference];
-
- if (!interfaces.some( function(v) { return iid.equals(v); } ))
- throw SpecialPowers.Components.results.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- observe : function (subject, topic, data) {
- var doc = getDialogDoc();
- if (doc)
- handleDialog(doc, testNum);
- else
- startCallbackTimer(); // try again in a bit
- }
-});
-
-function getDialogDoc() {
- // Find the <browser> which contains notifyWindow, by looking
- // through all the open windows and all the <browsers> in each.
- var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
- getService(Ci.nsIWindowMediator);
- // var enumerator = wm.getEnumerator("navigator:browser");
- var enumerator = wm.getXULWindowEnumerator(null);
-
- while (enumerator.hasMoreElements()) {
- var win = enumerator.getNext();
- var windowDocShell = win.QueryInterface(Ci.nsIXULWindow).docShell;
-
- var containedDocShells = windowDocShell.getDocShellEnumerator(
- Ci.nsIDocShellTreeItem.typeChrome,
- Ci.nsIDocShell.ENUMERATE_FORWARDS);
- while (containedDocShells.hasMoreElements()) {
- // Get the corresponding document for this docshell
- var childDocShell = containedDocShells.getNext();
- // We don't want it if it's not done loading.
- if (childDocShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE)
- continue;
- var childDoc = childDocShell.QueryInterface(Ci.nsIDocShell)
- .contentViewer
- .DOMDocument;
-
- // ok(true, "Got window: " + childDoc.location.href);
- if (childDoc.location.href == "chrome://global/content/commonDialog.xul")
- return childDoc;
- }
- }
-
- return null;
-}
diff --git a/toolkit/components/passwordmgr/test/pwmgr_common.js b/toolkit/components/passwordmgr/test/pwmgr_common.js
deleted file mode 100644
index fa7c4fd85..000000000
--- a/toolkit/components/passwordmgr/test/pwmgr_common.js
+++ /dev/null
@@ -1,509 +0,0 @@
-const TESTS_DIR = "/tests/toolkit/components/passwordmgr/test/";
-
-/**
- * Returns the element with the specified |name| attribute.
- */
-function $_(formNum, name) {
- var form = document.getElementById("form" + formNum);
- if (!form) {
- logWarning("$_ couldn't find requested form " + formNum);
- return null;
- }
-
- var element = form.children.namedItem(name);
- if (!element) {
- logWarning("$_ couldn't find requested element " + name);
- return null;
- }
-
- // Note that namedItem is a bit stupid, and will prefer an
- // |id| attribute over a |name| attribute when looking for
- // the element. Login Mananger happens to use .namedItem
- // anyway, but let's rigorously check it here anyway so
- // that we don't end up with tests that mistakenly pass.
-
- if (element.getAttribute("name") != name) {
- logWarning("$_ got confused.");
- return null;
- }
-
- return element;
-}
-
-/**
- * Check a form for expected values. If an argument is null, a field's
- * expected value will be the default value.
- *
- * <form id="form#">
- * checkForm(#, "foo");
- */
-function checkForm(formNum, val1, val2, val3) {
- var e, form = document.getElementById("form" + formNum);
- ok(form, "Locating form " + formNum);
-
- var numToCheck = arguments.length - 1;
-
- if (!numToCheck--)
- return;
- e = form.elements[0];
- if (val1 == null)
- is(e.value, e.defaultValue, "Test default value of field " + e.name +
- " in form " + formNum);
- else
- is(e.value, val1, "Test value of field " + e.name +
- " in form " + formNum);
-
-
- if (!numToCheck--)
- return;
- e = form.elements[1];
- if (val2 == null)
- is(e.value, e.defaultValue, "Test default value of field " + e.name +
- " in form " + formNum);
- else
- is(e.value, val2, "Test value of field " + e.name +
- " in form " + formNum);
-
-
- if (!numToCheck--)
- return;
- e = form.elements[2];
- if (val3 == null)
- is(e.value, e.defaultValue, "Test default value of field " + e.name +
- " in form " + formNum);
- else
- is(e.value, val3, "Test value of field " + e.name +
- " in form " + formNum);
-}
-
-/**
- * Check a form for unmodified values from when page was loaded.
- *
- * <form id="form#">
- * checkUnmodifiedForm(#);
- */
-function checkUnmodifiedForm(formNum) {
- var form = document.getElementById("form" + formNum);
- ok(form, "Locating form " + formNum);
-
- for (var i = 0; i < form.elements.length; i++) {
- var ele = form.elements[i];
-
- // No point in checking form submit/reset buttons.
- if (ele.type == "submit" || ele.type == "reset")
- continue;
-
- is(ele.value, ele.defaultValue, "Test to default value of field " +
- ele.name + " in form " + formNum);
- }
-}
-
-/**
- * Mochitest gives us a sendKey(), but it's targeted to a specific element.
- * This basically sends an untargeted key event, to whatever's focused.
- */
-function doKey(aKey, modifier) {
- var keyName = "DOM_VK_" + aKey.toUpperCase();
- var key = KeyEvent[keyName];
-
- // undefined --> null
- if (!modifier)
- modifier = null;
-
- // Window utils for sending fake sey events.
- var wutils = SpecialPowers.wrap(window).
- QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor).
- getInterface(SpecialPowers.Ci.nsIDOMWindowUtils);
-
- if (wutils.sendKeyEvent("keydown", key, 0, modifier)) {
- wutils.sendKeyEvent("keypress", key, 0, modifier);
- }
- wutils.sendKeyEvent("keyup", key, 0, modifier);
-}
-
-/**
- * Init with a common login
- * If selfFilling is true or non-undefined, fires an event at the page so that
- * the test can start checking filled-in values. Tests that check observer
- * notifications might be confused by this.
- */
-function commonInit(selfFilling) {
- var pwmgr = SpecialPowers.Cc["@mozilla.org/login-manager;1"].
- getService(SpecialPowers.Ci.nsILoginManager);
- ok(pwmgr != null, "Access LoginManager");
-
- // Check that initial state has no logins
- var logins = pwmgr.getAllLogins();
- is(logins.length, 0, "Not expecting logins to be present");
- var disabledHosts = pwmgr.getAllDisabledHosts();
- if (disabledHosts.length) {
- ok(false, "Warning: wasn't expecting disabled hosts to be present.");
- for (var host of disabledHosts)
- pwmgr.setLoginSavingEnabled(host, true);
- }
-
- // Add a login that's used in multiple tests
- var login = SpecialPowers.Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(SpecialPowers.Ci.nsILoginInfo);
- login.init("http://mochi.test:8888", "http://mochi.test:8888", null,
- "testuser", "testpass", "uname", "pword");
- pwmgr.addLogin(login);
-
- // Last sanity check
- logins = pwmgr.getAllLogins();
- is(logins.length, 1, "Checking for successful init login");
- disabledHosts = pwmgr.getAllDisabledHosts();
- is(disabledHosts.length, 0, "Checking for no disabled hosts");
-
- if (selfFilling)
- return;
-
- if (this.sendAsyncMessage) {
- sendAsyncMessage("registerRunTests");
- } else {
- registerRunTests();
- }
-}
-
-function registerRunTests() {
- return new Promise(resolve => {
- // We provide a general mechanism for our tests to know when they can
- // safely run: we add a final form that we know will be filled in, wait
- // for the login manager to tell us that it's filled in and then continue
- // with the rest of the tests.
- window.addEventListener("DOMContentLoaded", (event) => {
- var form = document.createElement('form');
- form.id = 'observerforcer';
- var username = document.createElement('input');
- username.name = 'testuser';
- form.appendChild(username);
- var password = document.createElement('input');
- password.name = 'testpass';
- password.type = 'password';
- form.appendChild(password);
-
- var observer = SpecialPowers.wrapCallback(function(subject, topic, data) {
- var formLikeRoot = subject.QueryInterface(SpecialPowers.Ci.nsIDOMNode);
- if (formLikeRoot.id !== 'observerforcer')
- return;
- SpecialPowers.removeObserver(observer, "passwordmgr-processed-form");
- formLikeRoot.remove();
- SimpleTest.executeSoon(() => {
- var runTestEvent = new Event("runTests");
- window.dispatchEvent(runTestEvent);
- resolve();
- });
- });
- SpecialPowers.addObserver(observer, "passwordmgr-processed-form", false);
-
- document.body.appendChild(form);
- });
- });
-}
-
-const masterPassword = "omgsecret!";
-
-function enableMasterPassword() {
- setMasterPassword(true);
-}
-
-function disableMasterPassword() {
- setMasterPassword(false);
-}
-
-function setMasterPassword(enable) {
- var oldPW, newPW;
- if (enable) {
- oldPW = "";
- newPW = masterPassword;
- } else {
- oldPW = masterPassword;
- newPW = "";
- }
- // Set master password. Note that this does not log you in, so the next
- // invocation of pwmgr can trigger a MP prompt.
-
- var pk11db = Cc["@mozilla.org/security/pk11tokendb;1"].getService(Ci.nsIPK11TokenDB);
- var token = pk11db.findTokenByName("");
- info("MP change from " + oldPW + " to " + newPW);
- token.changePassword(oldPW, newPW);
-}
-
-function logoutMasterPassword() {
- var sdr = Cc["@mozilla.org/security/sdr;1"].getService(Ci.nsISecretDecoderRing);
- sdr.logoutAndTeardown();
-}
-
-function dumpLogins(pwmgr) {
- var logins = pwmgr.getAllLogins();
- ok(true, "----- dumpLogins: have " + logins.length + " logins. -----");
- for (var i = 0; i < logins.length; i++)
- dumpLogin("login #" + i + " --- ", logins[i]);
-}
-
-function dumpLogin(label, login) {
- var loginText = "";
- loginText += "host: ";
- loginText += login.hostname;
- loginText += " / formURL: ";
- loginText += login.formSubmitURL;
- loginText += " / realm: ";
- loginText += login.httpRealm;
- loginText += " / user: ";
- loginText += login.username;
- loginText += " / pass: ";
- loginText += login.password;
- loginText += " / ufield: ";
- loginText += login.usernameField;
- loginText += " / pfield: ";
- loginText += login.passwordField;
- ok(true, label + loginText);
-}
-
-function getRecipeParent() {
- var { LoginManagerParent } = SpecialPowers.Cu.import("resource://gre/modules/LoginManagerParent.jsm", {});
- if (!LoginManagerParent.recipeParentPromise) {
- return null;
- }
- return LoginManagerParent.recipeParentPromise.then((recipeParent) => {
- return SpecialPowers.wrap(recipeParent);
- });
-}
-
-/**
- * Resolves when a specified number of forms have been processed.
- */
-function promiseFormsProcessed(expectedCount = 1) {
- var processedCount = 0;
- return new Promise((resolve, reject) => {
- function onProcessedForm(subject, topic, data) {
- processedCount++;
- if (processedCount == expectedCount) {
- SpecialPowers.removeObserver(onProcessedForm, "passwordmgr-processed-form");
- resolve(SpecialPowers.Cu.waiveXrays(subject), data);
- }
- }
- SpecialPowers.addObserver(onProcessedForm, "passwordmgr-processed-form", false);
- });
-}
-
-function loadRecipes(recipes) {
- info("Loading recipes");
- return new Promise(resolve => {
- chromeScript.addMessageListener("loadedRecipes", function loaded() {
- chromeScript.removeMessageListener("loadedRecipes", loaded);
- resolve(recipes);
- });
- chromeScript.sendAsyncMessage("loadRecipes", recipes);
- });
-}
-
-function resetRecipes() {
- info("Resetting recipes");
- return new Promise(resolve => {
- chromeScript.addMessageListener("recipesReset", function reset() {
- chromeScript.removeMessageListener("recipesReset", reset);
- resolve();
- });
- chromeScript.sendAsyncMessage("resetRecipes");
- });
-}
-
-function promiseStorageChanged(expectedChangeTypes) {
- return new Promise((resolve, reject) => {
- function onStorageChanged({ topic, data }) {
- let changeType = expectedChangeTypes.shift();
- is(data, changeType, "Check expected passwordmgr-storage-changed type");
- if (expectedChangeTypes.length === 0) {
- chromeScript.removeMessageListener("storageChanged", onStorageChanged);
- resolve();
- }
- }
- chromeScript.addMessageListener("storageChanged", onStorageChanged);
- });
-}
-
-function promisePromptShown(expectedTopic) {
- return new Promise((resolve, reject) => {
- function onPromptShown({ topic, data }) {
- is(topic, expectedTopic, "Check expected prompt topic");
- chromeScript.removeMessageListener("promptShown", onPromptShown);
- resolve();
- }
- chromeScript.addMessageListener("promptShown", onPromptShown);
- });
-}
-
-/**
- * Run a function synchronously in the parent process and destroy it in the test cleanup function.
- * @param {Function|String} aFunctionOrURL - either a function that will be stringified and run
- * or the URL to a JS file.
- * @return {Object} - the return value of loadChromeScript providing message-related methods.
- * @see loadChromeScript in specialpowersAPI.js
- */
-function runInParent(aFunctionOrURL) {
- let chromeScript = SpecialPowers.loadChromeScript(aFunctionOrURL);
- SimpleTest.registerCleanupFunction(() => {
- chromeScript.destroy();
- });
- return chromeScript;
-}
-
-/**
- * Run commonInit synchronously in the parent then run the test function after the runTests event.
- *
- * @param {Function} aFunction The test function to run
- */
-function runChecksAfterCommonInit(aFunction = null) {
- SimpleTest.waitForExplicitFinish();
- let pwmgrCommonScript = runInParent(SimpleTest.getTestFileURL("pwmgr_common.js"));
- if (aFunction) {
- window.addEventListener("runTests", aFunction);
- pwmgrCommonScript.addMessageListener("registerRunTests", () => registerRunTests());
- }
- pwmgrCommonScript.sendSyncMessage("setupParent");
- return pwmgrCommonScript;
-}
-
-// Code to run when loaded as a chrome script in tests via loadChromeScript
-if (this.addMessageListener) {
- const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
- var SpecialPowers = { Cc, Ci, Cr, Cu, };
- var ok, is;
- // Ignore ok/is in commonInit since they aren't defined in a chrome script.
- ok = is = () => {}; // eslint-disable-line no-native-reassign
-
- Cu.import("resource://gre/modules/LoginHelper.jsm");
- Cu.import("resource://gre/modules/LoginManagerParent.jsm");
- Cu.import("resource://gre/modules/Services.jsm");
- Cu.import("resource://gre/modules/Task.jsm");
-
- function onStorageChanged(subject, topic, data) {
- sendAsyncMessage("storageChanged", {
- topic,
- data,
- });
- }
- Services.obs.addObserver(onStorageChanged, "passwordmgr-storage-changed", false);
-
- function onPrompt(subject, topic, data) {
- sendAsyncMessage("promptShown", {
- topic,
- data,
- });
- }
- Services.obs.addObserver(onPrompt, "passwordmgr-prompt-change", false);
- Services.obs.addObserver(onPrompt, "passwordmgr-prompt-save", false);
-
- addMessageListener("setupParent", ({selfFilling = false} = {selfFilling: false}) => {
- // Force LoginManagerParent to init for the tests since it's normally delayed
- // by apps such as on Android.
- LoginManagerParent.init();
-
- commonInit(selfFilling);
- sendAsyncMessage("doneSetup");
- });
-
- addMessageListener("loadRecipes", Task.async(function*(recipes) {
- var recipeParent = yield LoginManagerParent.recipeParentPromise;
- yield recipeParent.load(recipes);
- sendAsyncMessage("loadedRecipes", recipes);
- }));
-
- addMessageListener("resetRecipes", Task.async(function*() {
- let recipeParent = yield LoginManagerParent.recipeParentPromise;
- yield recipeParent.reset();
- sendAsyncMessage("recipesReset");
- }));
-
- addMessageListener("proxyLoginManager", msg => {
- // Recreate nsILoginInfo objects from vanilla JS objects.
- let recreatedArgs = msg.args.map((arg, index) => {
- if (msg.loginInfoIndices.includes(index)) {
- return LoginHelper.vanillaObjectToLogin(arg);
- }
-
- return arg;
- });
-
- let rv = Services.logins[msg.methodName](...recreatedArgs);
- if (rv instanceof Ci.nsILoginInfo) {
- rv = LoginHelper.loginToVanillaObject(rv);
- }
- return rv;
- });
-
- var globalMM = Cc["@mozilla.org/globalmessagemanager;1"].getService(Ci.nsIMessageListenerManager);
- globalMM.addMessageListener("RemoteLogins:onFormSubmit", function onFormSubmit(message) {
- sendAsyncMessage("formSubmissionProcessed", message.data, message.objects);
- });
-} else {
- // Code to only run in the mochitest pages (not in the chrome script).
- SpecialPowers.pushPrefEnv({"set": [["signon.autofillForms.http", true],
- ["security.insecure_field_warning.contextual.enabled", false]]
- });
-
- SimpleTest.registerCleanupFunction(() => {
- SpecialPowers.popPrefEnv();
- runInParent(function cleanupParent() {
- const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
- Cu.import("resource://gre/modules/Services.jsm");
- Cu.import("resource://gre/modules/LoginManagerParent.jsm");
-
- // Remove all logins and disabled hosts
- Services.logins.removeAllLogins();
-
- let disabledHosts = Services.logins.getAllDisabledHosts();
- disabledHosts.forEach(host => Services.logins.setLoginSavingEnabled(host, true));
-
- let authMgr = Cc["@mozilla.org/network/http-auth-manager;1"].
- getService(Ci.nsIHttpAuthManager);
- authMgr.clearAll();
-
- if (LoginManagerParent._recipeManager) {
- LoginManagerParent._recipeManager.reset();
- }
-
- // Cleanup PopupNotifications (if on a relevant platform)
- let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
- if (chromeWin && chromeWin.PopupNotifications) {
- let notes = chromeWin.PopupNotifications._currentNotifications;
- if (notes.length > 0) {
- dump("Removing " + notes.length + " popup notifications.\n");
- }
- for (let note of notes) {
- note.remove();
- }
- }
- });
- });
-
-
- let { LoginHelper } = SpecialPowers.Cu.import("resource://gre/modules/LoginHelper.jsm", {});
- /**
- * Proxy for Services.logins (nsILoginManager).
- * Only supports arguments which support structured clone plus {nsILoginInfo}
- * Assumes properties are methods.
- */
- this.LoginManager = new Proxy({}, {
- get(target, prop, receiver) {
- return (...args) => {
- let loginInfoIndices = [];
- let cloneableArgs = args.map((val, index) => {
- if (SpecialPowers.call_Instanceof(val, SpecialPowers.Ci.nsILoginInfo)) {
- loginInfoIndices.push(index);
- return LoginHelper.loginToVanillaObject(val);
- }
-
- return val;
- });
-
- return chromeScript.sendSyncMessage("proxyLoginManager", {
- args: cloneableArgs,
- loginInfoIndices,
- methodName: prop,
- })[0][0];
- };
- },
- });
-}
diff --git a/toolkit/components/passwordmgr/test/subtst_master_pass.html b/toolkit/components/passwordmgr/test/subtst_master_pass.html
deleted file mode 100644
index 20211866a..000000000
--- a/toolkit/components/passwordmgr/test/subtst_master_pass.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<h2>MP subtest</h2>
-This form triggers a MP and gets filled in.<br>
-<form>
-Username: <input type="text" id="userfield" name="u"><br>
-Password: <input type="password" id="passfield" name="p"><br>
-<script>
- // Only notify when we fill in the password field.
- document.getElementById("passfield").addEventListener("input", function() {
- parent.postMessage("filled", "*");
- });
-</script>
-</form>
diff --git a/toolkit/components/passwordmgr/test/subtst_prompt_async.html b/toolkit/components/passwordmgr/test/subtst_prompt_async.html
deleted file mode 100644
index f60f63814..000000000
--- a/toolkit/components/passwordmgr/test/subtst_prompt_async.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Multiple auth request</title>
-</head>
-<body>
- <iframe id="iframe1" src="http://example.com/tests/toolkit/components/passwordmgr/test/authenticate.sjs?r=1&user=user3name&pass=user3pass&realm=mochirealm3&proxy_user=proxy_user2&proxy_pass=proxy_pass2&proxy_realm=proxy_realm2"></iframe>
- <iframe id="iframe2" src="http://example.com/tests/toolkit/components/passwordmgr/test/authenticate.sjs?r=2&user=user3name&pass=user3pass&realm=mochirealm3&proxy_user=proxy_user2&proxy_pass=proxy_pass2&proxy_realm=proxy_realm2"></iframe>
- <iframe id="iframe3" src="http://example.com/tests/toolkit/components/passwordmgr/test/authenticate.sjs?r=3&user=user3name&pass=user3pass&realm=mochirealm3&proxy_user=proxy_user2&proxy_pass=proxy_pass2&proxy_realm=proxy_realm2"></iframe>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/test_master_password.html b/toolkit/components/passwordmgr/test/test_master_password.html
deleted file mode 100644
index c8884811f..000000000
--- a/toolkit/components/passwordmgr/test/test_master_password.html
+++ /dev/null
@@ -1,308 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for master password</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: master password.
-<script>
-"use strict";
-
-commonInit();
-SimpleTest.waitForExplicitFinish();
-SimpleTest.requestFlakyTimeout("untriaged");
-
-var pwmgr = SpecialPowers.Cc["@mozilla.org/login-manager;1"]
- .getService(SpecialPowers.Ci.nsILoginManager);
-var pwcrypt = SpecialPowers.Cc["@mozilla.org/login-manager/crypto/SDR;1"]
- .getService(Ci.nsILoginManagerCrypto);
-
-var nsLoginInfo = new SpecialPowers.wrap(SpecialPowers.Components).Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo);
-
-var exampleCom = "http://example.com/tests/toolkit/components/passwordmgr/test/";
-var exampleOrg = "http://example.org/tests/toolkit/components/passwordmgr/test/";
-
-var login1 = new nsLoginInfo();
-var login2 = new nsLoginInfo();
-
-login1.init("http://example.com", "http://example.com", null,
- "user1", "pass1", "uname", "pword");
-login2.init("http://example.org", "http://example.org", null,
- "user2", "pass2", "uname", "pword");
-
-pwmgr.addLogin(login1);
-pwmgr.addLogin(login2);
-</script>
-
-<p id="display"></p>
-
-<div id="content" style="display: none">
-<iframe id="iframe1"></iframe>
-<iframe id="iframe2"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-var testNum = 1;
-var iframe1 = document.getElementById("iframe1");
-var iframe2 = document.getElementById("iframe2");
-
-// A couple of tests have to wait until the password manager gets around to
-// filling in the password in the subtest (after we dismiss the master
-// password dialog). In order to accomplish this, the test waits for an event
-// and then posts a message back up to us telling us to continue.
-var continuation = null;
-addEventListener("message", () => {
- if (continuation) {
- var c = continuation;
- continuation = null;
- c();
- }
-});
-
-/*
- * handleDialog
- *
- * Invoked a short period of time after calling startCallbackTimer(), and
- * allows testing the actual auth dialog while it's being displayed. Tests
- * should call startCallbackTimer() each time the auth dialog is expected (the
- * timer is a one-shot).
- */
-function handleDialog(doc, testNumber) {
- ok(true, "handleDialog running for test " + testNumber);
-
- var clickOK = true;
- var doNothing = false;
- var passfield = doc.getElementById("password1Textbox");
- var dialog = doc.getElementById("commonDialog");
-
- switch (testNumber) {
- case 1:
- is(passfield.getAttribute("value"), "", "Checking empty prompt");
- passfield.setAttribute("value", masterPassword);
- is(passfield.getAttribute("value"), masterPassword, "Checking filled prompt");
- break;
-
- case 2:
- clickOK = false;
- break;
-
- case 3:
- is(passfield.getAttribute("value"), "", "Checking empty prompt");
- passfield.setAttribute("value", masterPassword);
- break;
-
- case 4:
- doNothing = true;
- break;
-
- case 5:
- is(passfield.getAttribute("value"), "", "Checking empty prompt");
- passfield.setAttribute("value", masterPassword);
- break;
-
- default:
- ok(false, "Uhh, unhandled switch for testNum #" + testNumber);
- break;
- }
-
- didDialog = true;
-
- if (!doNothing) {
- SpecialPowers.addObserver(outerWindowObserver, "outer-window-destroyed", false);
- if (clickOK)
- dialog.acceptDialog();
- else
- dialog.cancelDialog();
- }
-
- ok(true, "handleDialog done for test " + testNumber);
-
- if (testNumber == 4)
- checkTest4A();
-}
-
-var outerWindowObserver = {
- observe: function(id) {
- SpecialPowers.removeObserver(outerWindowObserver, "outer-window-destroyed");
- var func;
- if (testNum == 1)
- func = startTest2;
- else if (testNum == 2)
- func = startTest3;
-
- // For tests 3 and 4C, we use the 'continuation' mechanism, described
- // above.
- if (func)
- setTimeout(func, 300);
- }
-};
-
-
-function startTest1() {
- ok(pwcrypt.isLoggedIn, "should be initially logged in (no MP)");
- enableMasterPassword();
- ok(!pwcrypt.isLoggedIn, "should be logged out after setting MP");
-
- // --- Test 1 ---
- // Trigger a MP prompt via the API
- startCallbackTimer();
- var logins = pwmgr.getAllLogins();
- ok(didDialog, "handleDialog was invoked");
- is(logins.length, 3, "expected number of logins");
-
- ok(pwcrypt.isLoggedIn, "should be logged in after MP prompt");
- logoutMasterPassword();
- ok(!pwcrypt.isLoggedIn, "should be logged out");
-}
-
-function startTest2() {
- // Try again but click cancel.
- testNum++;
- startCallbackTimer();
- var failedAsExpected = false;
- logins = null;
- try {
- logins = pwmgr.getAllLogins();
- } catch (e) { failedAsExpected = true; }
- ok(didDialog, "handleDialog was invoked");
- ok(failedAsExpected, "getAllLogins should have thrown");
- is(logins, null, "shouldn't have gotten logins");
- ok(!pwcrypt.isLoggedIn, "should still be logged out");
-}
-
-function startTest3() {
- // Load a single iframe to trigger a MP
- testNum++;
- iframe1.src = exampleCom + "subtst_master_pass.html";
- continuation = checkTest3;
- startCallbackTimer();
-}
-
-function checkTest3() {
- ok(true, "checkTest3 starting");
- ok(didDialog, "handleDialog was invoked");
-
- // check contents of iframe1 fields
- var u = SpecialPowers.wrap(iframe1).contentDocument.getElementById("userfield");
- var p = SpecialPowers.wrap(iframe1).contentDocument.getElementById("passfield");
- is(u.value, "user1", "checking expected user to have been filled in");
- is(p.value, "pass1", "checking expected pass to have been filled in");
-
- ok(pwcrypt.isLoggedIn, "should be logged in");
- logoutMasterPassword();
- ok(!pwcrypt.isLoggedIn, "should be logged out");
-
-
- // --- Test 4 ---
- // first part of loading 2 MP-triggering iframes
- testNum++;
- iframe1.src = exampleOrg + "subtst_master_pass.html";
- // start the callback, but we'll not enter the MP, just call checkTest4A
- startCallbackTimer();
-}
-
-function checkTest4A() {
- ok(true, "checkTest4A starting");
- ok(didDialog, "handleDialog was invoked");
-
- // check contents of iframe1 fields
- var u = SpecialPowers.wrap(iframe1).contentDocument.getElementById("userfield");
- var p = SpecialPowers.wrap(iframe1).contentDocument.getElementById("passfield");
- is(u.value, "", "checking expected empty user");
- is(p.value, "", "checking expected empty pass");
-
-
- ok(!pwcrypt.isLoggedIn, "should be logged out");
-
- // XXX check that there's 1 MP window open
-
- // Load another iframe with a login form
- // This should detect that there's already a pending MP prompt, and not
- // put up a second one. The load event will fire (note that when pwmgr is
- // driven from DOMContentLoaded, if that blocks due to prompting for a MP,
- // the load even will also be blocked until the prompt is dismissed).
- iframe2.onload = checkTest4B_delay;
- iframe2.src = exampleCom + "subtst_master_pass.html";
-}
-
-function checkTest4B_delay() {
- // Testing a negative, wait a little to give the login manager a chance to
- // (incorrectly) fill in the form. Note, we cannot use setTimeout()
- // here because the modal window suspends all window timers. Instead we
- // must use a chrome script to use nsITimer directly.
- let chromeURL = SimpleTest.getTestFileURL("chrome_timeout.js");
- let script = SpecialPowers.loadChromeScript(chromeURL);
- script.addMessageListener('ready', _ => {
- script.sendAsyncMessage('setTimeout', { delay: 500 });
- });
- script.addMessageListener('timeout', checkTest4B);
-}
-
-function checkTest4B() {
- ok(true, "checkTest4B starting");
- // iframe2 should load without having triggered a MP prompt (because one
- // is already waiting)
-
- // check contents of iframe2 fields
- var u = SpecialPowers.wrap(iframe2).contentDocument.getElementById("userfield");
- var p = SpecialPowers.wrap(iframe2).contentDocument.getElementById("passfield");
- is(u.value, "", "checking expected empty user");
- is(p.value, "", "checking expected empty pass");
-
- // XXX check that there's 1 MP window open
- ok(!pwcrypt.isLoggedIn, "should be logged out");
-
- continuation = checkTest4C;
-
- // Ok, now enter the MP. The MP prompt is already up, but we'll just reuse startCallBackTimer.
- // --- Test 5 ---
- testNum++;
- startCallbackTimer();
-}
-
-function checkTest4C() {
- ok(true, "checkTest4C starting");
- ok(didDialog, "handleDialog was invoked");
-
- // We shouldn't have to worry about iframe1's load event racing with
- // filling of iframe2's data. We notify observers synchronously, so
- // iframe2's observer will process iframe2 before iframe1 even finishes
- // processing the form (which is blocking its load event).
- ok(pwcrypt.isLoggedIn, "should be logged in");
-
- // check contents of iframe1 fields
- var u = SpecialPowers.wrap(iframe1).contentDocument.getElementById("userfield");
- var p = SpecialPowers.wrap(iframe1).contentDocument.getElementById("passfield");
- is(u.value, "user2", "checking expected user to have been filled in");
- is(p.value, "pass2", "checking expected pass to have been filled in");
-
- // check contents of iframe2 fields
- u = SpecialPowers.wrap(iframe2).contentDocument.getElementById("userfield");
- p = SpecialPowers.wrap(iframe2).contentDocument.getElementById("passfield");
- is(u.value, "user1", "checking expected user to have been filled in");
- is(p.value, "pass1", "checking expected pass to have been filled in");
-
- SimpleTest.finish();
-}
-
-// XXX do a test5ABC with clicking cancel?
-
-SimpleTest.registerCleanupFunction(function finishTest() {
- disableMasterPassword();
-
- pwmgr.removeLogin(login1);
- pwmgr.removeLogin(login2);
-});
-
-window.addEventListener("runTests", startTest1);
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/passwordmgr/test/test_prompt_async.html b/toolkit/components/passwordmgr/test/test_prompt_async.html
deleted file mode 100644
index 38b34679a..000000000
--- a/toolkit/components/passwordmgr/test/test_prompt_async.html
+++ /dev/null
@@ -1,540 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for Async Auth Prompt</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-
- <script class="testbody" type="text/javascript">
- SimpleTest.waitForExplicitFinish();
- SimpleTest.requestFlakyTimeout("untriaged");
-
- const { NetUtil } = SpecialPowers.Cu.import('resource://gre/modules/NetUtil.jsm');
-
- var prefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
- prefs.setIntPref("network.auth.subresource-http-auth-allow", 2);
- // Class monitoring number of open dialog windows
- // It checks there is always open just a single dialog per application
- function dialogMonitor() {
- var observerService = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
- .getService(Ci.nsIObserverService);
- observerService.addObserver(this, "domwindowopened", false);
- observerService.addObserver(this, "domwindowclosed", false);
- }
-
- /*
- * As documented in Bug 718543, checking equality of objects pulled
- * from SpecialPowers-wrapped objects is unreliable. Because of that,
- * `dialogMonitor` now tracks the number of open windows rather than
- * specific window objects.
- *
- * NB: Because the constructor (above) adds |this| directly as an observer,
- * we need to do SpecialPowers.wrapCallbackObject directly on the prototype.
- */
- dialogMonitor.prototype = SpecialPowers.wrapCallbackObject({
- windowsOpen : 0,
- windowsRegistered : 0,
-
- QueryInterface : function (iid) {
- const interfaces = [Ci.nsIObserver, Ci.nsISupports];
-
- if (!interfaces.some( function(v) { return iid.equals(v); } ))
- throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- observe: function(subject, topic, data) {
- if (topic === "domwindowopened") {
- this.windowsOpen++;
- this.windowsRegistered++;
- return;
- }
- if (topic === "domwindowclosed") {
- this.windowsOpen--;
- return;
- }
- },
-
- shutdown: function() {
- var observerService = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
- .getService(Ci.nsIObserverService);
- observerService.removeObserver(this, "domwindowopened");
- observerService.removeObserver(this, "domwindowclosed");
- },
-
- reset: function() {
- this.windowsOpen = 0;
- this.windowsRegistered = 0;
- }
- });
-
- var monitor = new dialogMonitor();
-
- var pwmgr, logins = [];
-
- function initLogins(pi) {
- pwmgr = SpecialPowers.Cc["@mozilla.org/login-manager;1"]
- .getService(Ci.nsILoginManager);
-
- function addLogin(host, realm, user, pass) {
- var login = SpecialPowers.Cc["@mozilla.org/login-manager/loginInfo;1"]
- .createInstance(Ci.nsILoginInfo);
- login.init(host, null, realm, user, pass, "", "");
- pwmgr.addLogin(login);
- logins.push(login);
- }
-
- var mozproxy = "moz-proxy://" +
- SpecialPowers.wrap(pi).host + ":" +
- SpecialPowers.wrap(pi).port;
-
- addLogin(mozproxy, "proxy_realm",
- "proxy_user", "proxy_pass");
- addLogin(mozproxy, "proxy_realm2",
- "proxy_user2", "proxy_pass2");
- addLogin(mozproxy, "proxy_realm3",
- "proxy_user3", "proxy_pass3");
- addLogin(mozproxy, "proxy_realm4",
- "proxy_user4", "proxy_pass4");
- addLogin(mozproxy, "proxy_realm5",
- "proxy_user5", "proxy_pass5");
- addLogin("http://example.com", "mochirealm",
- "user1name", "user1pass");
- addLogin("http://example.org", "mochirealm2",
- "user2name", "user2pass");
- addLogin("http://example.com", "mochirealm3",
- "user3name", "user3pass");
- addLogin("http://example.com", "mochirealm4",
- "user4name", "user4pass");
- addLogin("http://example.com", "mochirealm5",
- "user5name", "user5pass");
- addLogin("http://example.com", "mochirealm6",
- "user6name", "user6pass");
- }
-
- function finishTest() {
- ok(true, "finishTest removing testing logins...");
- for (i in logins)
- pwmgr.removeLogin(logins[i]);
-
- var authMgr = SpecialPowers.Cc['@mozilla.org/network/http-auth-manager;1']
- .getService(Ci.nsIHttpAuthManager);
- authMgr.clearAll();
-
- monitor.shutdown();
- SimpleTest.finish();
- }
-
- var resolveCallback = SpecialPowers.wrapCallbackObject({
- QueryInterface : function (iid) {
- const interfaces = [Ci.nsIProtocolProxyCallback, Ci.nsISupports];
-
- if (!interfaces.some( function(v) { return iid.equals(v); } ))
- throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
- return this;
- },
-
- onProxyAvailable : function (req, uri, pi, status) {
- initLogins(pi);
- doTest(testNum);
- }
- });
-
- function startup() {
- // Need to allow for arbitrary network servers defined in PAC instead of a hardcoded moz-proxy.
- var channel = NetUtil.newChannel({
- uri: "http://example.com",
- loadUsingSystemPrincipal: true
- });
-
- var pps = SpecialPowers.Cc["@mozilla.org/network/protocol-proxy-service;1"]
- .getService();
-
- pps.asyncResolve(channel, 0, resolveCallback);
- }
-
- // --------------- Test loop spin ----------------
- var testNum = 1;
- var iframe1;
- var iframe2a;
- var iframe2b;
- window.onload = function () {
- iframe1 = document.getElementById("iframe1");
- iframe2a = document.getElementById("iframe2a");
- iframe2b = document.getElementById("iframe2b");
- iframe1.onload = onFrameLoad;
- iframe2a.onload = onFrameLoad;
- iframe2b.onload = onFrameLoad;
-
- startup();
- };
-
- var expectedLoads;
- var expectedDialogs;
- function onFrameLoad()
- {
- if (--expectedLoads == 0) {
- // All pages expected to load has loaded, continue with the next test
- ok(true, "Expected frames loaded");
-
- doCheck(testNum);
- monitor.reset();
-
- testNum++;
- doTest(testNum);
- }
- }
-
- function doTest(testNumber)
- {
- /*
- * These contentDocument variables are located here,
- * rather than in the global scope, because SpecialPowers threw
- * errors (complaining that the objects were deleted)
- * when these were in the global scope.
- */
- var iframe1Doc = SpecialPowers.wrap(iframe1).contentDocument;
- var iframe2aDoc = SpecialPowers.wrap(iframe2a).contentDocument;
- var iframe2bDoc = SpecialPowers.wrap(iframe2b).contentDocument;
- var exampleCom = "http://example.com/tests/toolkit/components/passwordmgr/test/";
- var exampleOrg = "http://example.org/tests/toolkit/components/passwordmgr/test/";
-
- switch (testNumber)
- {
- case 1:
- // Load through a single proxy with authentication required 3 different
- // pages, first with one login, other two with their own different login.
- // We expect to show just a single dialog for proxy authentication and
- // then two dialogs to authenticate to login 1 and then login 2.
- ok(true, "doTest testNum 1");
- expectedLoads = 3;
- expectedDialogs = 3;
- iframe1.src = exampleCom + "authenticate.sjs?" +
- "r=1&" +
- "user=user1name&" +
- "pass=user1pass&" +
- "realm=mochirealm&" +
- "proxy_user=proxy_user&" +
- "proxy_pass=proxy_pass&" +
- "proxy_realm=proxy_realm";
- iframe2a.src = exampleOrg + "authenticate.sjs?" +
- "r=2&" +
- "user=user2name&" +
- "pass=user2pass&" +
- "realm=mochirealm2&" +
- "proxy_user=proxy_user&" +
- "proxy_pass=proxy_pass&" +
- "proxy_realm=proxy_realm";
- iframe2b.src = exampleOrg + "authenticate.sjs?" +
- "r=3&" +
- "user=user2name&" +
- "pass=user2pass&" +
- "realm=mochirealm2&" +
- "proxy_user=proxy_user&" +
- "proxy_pass=proxy_pass&" +
- "proxy_realm=proxy_realm";
- break;
-
- case 2:
- // Load an iframe with 3 subpages all requiring the same login through
- // anuthenticated proxy. We expect 2 dialogs, proxy authentication
- // and web authentication.
- ok(true, "doTest testNum 2");
- expectedLoads = 3;
- expectedDialogs = 2;
- iframe1.src = exampleCom + "subtst_prompt_async.html";
- iframe2a.src = "about:blank";
- iframe2b.src = "about:blank";
- break;
-
- case 3:
- // Load in the iframe page through unauthenticated proxy
- // and discard the proxy authentication. We expect to see
- // unauthenticated page content and just a single dialog.
- ok(true, "doTest testNum 3");
- expectedLoads = 1;
- expectedDialogs = 1;
- iframe1.src = exampleCom + "authenticate.sjs?" +
- "user=user4name&" +
- "pass=user4pass&" +
- "realm=mochirealm4&" +
- "proxy_user=proxy_user3&" +
- "proxy_pass=proxy_pass3&" +
- "proxy_realm=proxy_realm3";
- break;
-
- case 4:
- // Reload the frame from previous step and pass the proxy authentication
- // but cancel the WWW authentication. We should get the proxy=ok and WWW=fail
- // content as a result.
- ok(true, "doTest testNum 4");
- expectedLoads = 1;
- expectedDialogs = 2;
- iframe1.src = exampleCom + "authenticate.sjs?" +
- "user=user4name&" +
- "pass=user4pass&" +
- "realm=mochirealm4&" +
- "proxy_user=proxy_user3&" +
- "proxy_pass=proxy_pass3&" +
- "proxy_realm=proxy_realm3";
-
-
- break;
-
- case 5:
- // Same as the previous two steps but let the server generate
- // huge content load to check http channel is capable to handle
- // case when auth dialog is canceled or accepted before unauthenticated
- // content data is load from the server. (This would be better to
- // implement using delay of server response).
- ok(true, "doTest testNum 5");
- expectedLoads = 1;
- expectedDialogs = 1;
- iframe1.src = exampleCom + "authenticate.sjs?" +
- "user=user5name&" +
- "pass=user5pass&" +
- "realm=mochirealm5&" +
- "proxy_user=proxy_user4&" +
- "proxy_pass=proxy_pass4&" +
- "proxy_realm=proxy_realm4&" +
- "huge=1";
- break;
-
- case 6:
- // Reload the frame from the previous step and let the proxy
- // authentication pass but WWW fail. We expect two dialogs
- // and an unathenticated page content load.
- ok(true, "doTest testNum 6");
- expectedLoads = 1;
- expectedDialogs = 2;
- iframe1.src = exampleCom + "authenticate.sjs?" +
- "user=user5name&" +
- "pass=user5pass&" +
- "realm=mochirealm5&" +
- "proxy_user=proxy_user4&" +
- "proxy_pass=proxy_pass4&" +
- "proxy_realm=proxy_realm4&" +
- "huge=1";
- break;
-
- case 7:
- // Reload again and let pass all authentication dialogs.
- // Check we get the authenticated content not broken by
- // the unauthenticated content.
- ok(true, "doTest testNum 7");
- expectedLoads = 1;
- expectedDialogs = 1;
- iframe1Doc.location.reload();
- break;
-
- case 8:
- // Check we proccess all challenges sent by server when
- // user cancels prompts
- ok(true, "doTest testNum 8");
- expectedLoads = 1;
- expectedDialogs = 5;
- iframe1.src = exampleCom + "authenticate.sjs?" +
- "user=user6name&" +
- "pass=user6pass&" +
- "realm=mochirealm6&" +
- "proxy_user=proxy_user5&" +
- "proxy_pass=proxy_pass5&" +
- "proxy_realm=proxy_realm5&" +
- "huge=1&" +
- "multiple=3";
- break;
-
- case 9:
- finishTest();
- return;
- }
-
- startCallbackTimer();
- }
-
- function handleDialog(doc, testNumber)
- {
- var dialog = doc.getElementById("commonDialog");
-
- switch (testNumber)
- {
- case 1:
- case 2:
- dialog.acceptDialog();
- break;
-
- case 3:
- dialog.cancelDialog();
- setTimeout(onFrameLoad, 10); // there are no successful frames for test 3
- break;
-
- case 4:
- if (expectedDialogs == 2)
- dialog.acceptDialog();
- else
- dialog.cancelDialog();
- break;
-
- case 5:
- dialog.cancelDialog();
- setTimeout(onFrameLoad, 10); // there are no successful frames for test 5
- break;
-
- case 6:
- if (expectedDialogs == 2)
- dialog.acceptDialog();
- else
- dialog.cancelDialog();
- break;
-
- case 7:
- dialog.acceptDialog();
- break;
-
- case 8:
- if (expectedDialogs == 3 || expectedDialogs == 1)
- dialog.acceptDialog();
- else
- dialog.cancelDialog();
- break;
-
- default:
- ok(false, "Unhandled testNum " + testNumber + " in handleDialog");
- }
-
- if (--expectedDialogs > 0)
- startCallbackTimer();
- }
-
- function doCheck(testNumber)
- {
- var iframe1Doc = SpecialPowers.wrap(iframe1).contentDocument;
- var iframe2aDoc = SpecialPowers.wrap(iframe2a).contentDocument;
- var iframe2bDoc = SpecialPowers.wrap(iframe2b).contentDocument;
- var authok1;
- var proxyok1;
- var footnote;
- switch (testNumber)
- {
- case 1:
- ok(true, "doCheck testNum 1");
- is(monitor.windowsRegistered, 3, "Registered 3 open dialogs");
-
- authok1 = iframe1Doc.getElementById("ok").textContent;
- proxyok1 = iframe1Doc.getElementById("proxy").textContent;
-
- var authok2a = iframe2aDoc.getElementById("ok").textContent;
- var proxyok2a = iframe2aDoc.getElementById("proxy").textContent;
-
- var authok2b = iframe2bDoc.getElementById("ok").textContent;
- var proxyok2b = iframe2bDoc.getElementById("proxy").textContent;
-
- is(authok1, "PASS", "WWW Authorization OK, frame1");
- is(authok2a, "PASS", "WWW Authorization OK, frame2a");
- is(authok2b, "PASS", "WWW Authorization OK, frame2b");
- is(proxyok1, "PASS", "Proxy Authorization OK, frame1");
- is(proxyok2a, "PASS", "Proxy Authorization OK, frame2a");
- is(proxyok2b, "PASS", "Proxy Authorization OK, frame2b");
- break;
-
- case 2:
- is(monitor.windowsRegistered, 2, "Registered 2 open dialogs");
- ok(true, "doCheck testNum 2");
-
- function checkIframe(frame) {
- var doc = SpecialPowers.wrap(frame).contentDocument;
-
- var authok = doc.getElementById("ok").textContent;
- var proxyok = doc.getElementById("proxy").textContent;
-
- is(authok, "PASS", "WWW Authorization OK, " + frame.id);
- is(proxyok, "PASS", "Proxy Authorization OK, " + frame.id);
- }
-
- checkIframe(iframe1Doc.getElementById("iframe1"));
- checkIframe(iframe1Doc.getElementById("iframe2"));
- checkIframe(iframe1Doc.getElementById("iframe3"));
- break;
-
- case 3:
- ok(true, "doCheck testNum 3");
- is(monitor.windowsRegistered, 1, "Registered 1 open dialog");
-
- // ensure that the page content is not displayed on failed proxy auth
- is(iframe1Doc.getElementById("ok"), null, "frame did not load");
- break;
-
- case 4:
- ok(true, "doCheck testNum 4");
- is(monitor.windowsRegistered, 2, "Registered 2 open dialogs");
- authok1 = iframe1Doc.getElementById("ok").textContent;
- proxyok1 = iframe1Doc.getElementById("proxy").textContent;
-
- is(authok1, "FAIL", "WWW Authorization FAILED, frame1");
- is(proxyok1, "PASS", "Proxy Authorization OK, frame1");
- break;
-
- case 5:
- ok(true, "doCheck testNum 5");
- is(monitor.windowsRegistered, 1, "Registered 1 open dialog");
-
- // ensure that the page content is not displayed on failed proxy auth
- is(iframe1Doc.getElementById("footnote"), null, "frame did not load");
- break;
-
- case 6:
- ok(true, "doCheck testNum 6");
- is(monitor.windowsRegistered, 2, "Registered 2 open dialogs");
- authok1 = iframe1Doc.getElementById("ok").textContent;
- proxyok1 = iframe1Doc.getElementById("proxy").textContent;
- footnote = iframe1Doc.getElementById("footnote").textContent;
-
- is(authok1, "FAIL", "WWW Authorization FAILED, frame1");
- is(proxyok1, "PASS", "Proxy Authorization OK, frame1");
- is(footnote, "This is a footnote after the huge content fill",
- "Footnote present and loaded completely");
- break;
-
- case 7:
- ok(true, "doCheck testNum 7");
- is(monitor.windowsRegistered, 1, "Registered 1 open dialogs");
- authok1 = iframe1Doc.getElementById("ok").textContent;
- proxyok1 = iframe1Doc.getElementById("proxy").textContent;
- footnote = iframe1Doc.getElementById("footnote").textContent;
-
- is(authok1, "PASS", "WWW Authorization OK, frame1");
- is(proxyok1, "PASS", "Proxy Authorization OK, frame1");
- is(footnote, "This is a footnote after the huge content fill",
- "Footnote present and loaded completely");
- break;
-
- case 8:
- ok(true, "doCheck testNum 8");
- is(monitor.windowsRegistered, 5, "Registered 5 open dialogs");
- authok1 = iframe1Doc.getElementById("ok").textContent;
- proxyok1 = iframe1Doc.getElementById("proxy").textContent;
- footnote = iframe1Doc.getElementById("footnote").textContent;
-
- is(authok1, "PASS", "WWW Authorization OK, frame1");
- is(proxyok1, "PASS", "Proxy Authorization OK, frame1");
- is(footnote, "This is a footnote after the huge content fill",
- "Footnote present and loaded completely");
- break;
-
- default:
- ok(false, "Unhandled testNum " + testNumber + " in doCheck");
- }
- }
-
- </script>
-</head>
-<body>
- <iframe id="iframe1"></iframe>
- <iframe id="iframe2a"></iframe>
- <iframe id="iframe2b"></iframe>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/test_xhr.html b/toolkit/components/passwordmgr/test/test_xhr.html
deleted file mode 100644
index 296371685..000000000
--- a/toolkit/components/passwordmgr/test/test_xhr.html
+++ /dev/null
@@ -1,201 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for XHR prompts</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: XHR prompt
-<p id="display"></p>
-
-<div id="content" style="display: none">
- <iframe id="iframe"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: XHR prompts. **/
-var pwmgr, login1, login2;
-
-function initLogins() {
- pwmgr = Cc["@mozilla.org/login-manager;1"].
- getService(Ci.nsILoginManager);
-
- login1 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
- login2 = Cc["@mozilla.org/login-manager/loginInfo;1"].
- createInstance(Ci.nsILoginInfo);
-
- login1.init("http://mochi.test:8888", null, "xhr",
- "xhruser1", "xhrpass1", "", "");
- login2.init("http://mochi.test:8888", null, "xhr2",
- "xhruser2", "xhrpass2", "", "");
-
- pwmgr.addLogin(login1);
- pwmgr.addLogin(login2);
-}
-
-function finishTest() {
- ok(true, "finishTest removing testing logins...");
- pwmgr.removeLogin(login1);
- pwmgr.removeLogin(login2);
-
- SimpleTest.finish();
-}
-
-function handleDialog(doc, testNum) {
- ok(true, "handleDialog running for test " + testNum);
-
- var clickOK = true;
- var userfield = doc.getElementById("loginTextbox");
- var passfield = doc.getElementById("password1Textbox");
- var username = userfield.getAttribute("value");
- var password = passfield.getAttribute("value");
- var dialog = doc.getElementById("commonDialog");
-
- switch (testNum) {
- case 1:
- is(username, "xhruser1", "Checking provided username");
- is(password, "xhrpass1", "Checking provided password");
- break;
-
- case 2:
- is(username, "xhruser2", "Checking provided username");
- is(password, "xhrpass2", "Checking provided password");
-
- // Check that the dialog is modal, chrome and dependent;
- // We can't just check window.opener because that'll be
- // a content window, which therefore isn't exposed (it'll lie and
- // be null).
- var win = doc.defaultView;
- var Ci = SpecialPowers.Ci;
- var treeOwner = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).
- QueryInterface(Ci.nsIDocShellTreeItem).treeOwner;
- treeOwner.QueryInterface(Ci.nsIInterfaceRequestor);
- var flags = treeOwner.getInterface(Ci.nsIXULWindow).chromeFlags;
- var wbc = treeOwner.getInterface(Ci.nsIWebBrowserChrome);
- info("Flags: " + flags);
- ok((flags & Ci.nsIWebBrowserChrome.CHROME_OPENAS_CHROME) != 0,
- "Dialog should be opened as chrome");
- ok((flags & Ci.nsIWebBrowserChrome.CHROME_OPENAS_DIALOG) != 0,
- "Dialog should be opened as a dialog");
- ok((flags & Ci.nsIWebBrowserChrome.CHROME_DEPENDENT) != 0,
- "Dialog should be opened as dependent.");
- ok(wbc.isWindowModal(), "Dialog should be modal");
-
- // Check that the right tab is focused:
- var browserWin = SpecialPowers.Services.wm.getMostRecentWindow("navigator:browser");
- var spec = browserWin.gBrowser.selectedBrowser.currentURI.spec;
- ok(spec.startsWith("http://mochi.test:8888"),
- "Tab with remote URI (rather than about:blank) should be focused (" + spec + ")");
-
-
- break;
-
- default:
- ok(false, "Uhh, unhandled switch for testNum #" + testNum);
- break;
- }
-
- // Explicitly cancel the dialog and report a fail in this failure
- // case, rather than letting the dialog get stuck due to an auth
- // failure and having the test timeout.
- if (!username && !password) {
- ok(false, "No values prefilled");
- clickOK = false;
- }
-
- if (clickOK)
- dialog.acceptDialog();
- else
- dialog.cancelDialog();
-
- ok(true, "handleDialog done");
- didDialog = true;
-}
-
-var newWin;
-function xhrLoad(xmlDoc) {
- ok(true, "xhrLoad running for test " + testNum);
-
- // The server echos back the user/pass it received.
- var username = xmlDoc.getElementById("user").textContent;
- var password = xmlDoc.getElementById("pass").textContent;
- var authok = xmlDoc.getElementById("ok").textContent;
-
-
- switch (testNum) {
- case 1:
- is(username, "xhruser1", "Checking provided username");
- is(password, "xhrpass1", "Checking provided password");
- break;
-
- case 2:
- is(username, "xhruser2", "Checking provided username");
- is(password, "xhrpass2", "Checking provided password");
-
- newWin.close();
- break;
-
- default:
- ok(false, "Uhh, unhandled switch for testNum #" + testNum);
- break;
- }
-
- doTest();
-}
-
-function doTest() {
- switch (++testNum) {
- case 1:
- startCallbackTimer();
- makeRequest("authenticate.sjs?user=xhruser1&pass=xhrpass1&realm=xhr");
- break;
-
- case 2:
- // Test correct parenting, by opening another tab in the foreground,
- // and making sure the prompt re-focuses the original tab when shown:
- newWin = window.open();
- newWin.focus();
- startCallbackTimer();
- makeRequest("authenticate.sjs?user=xhruser2&pass=xhrpass2&realm=xhr2");
- break;
-
- default:
- finishTest();
- }
-}
-
-function makeRequest(uri) {
- var request = new XMLHttpRequest();
- request.open("GET", uri, true);
- request.onreadystatechange = function () {
- if (request.readyState == 4)
- xhrLoad(request.responseXML);
- };
- request.send(null);
-}
-
-
-initLogins();
-
-// clear plain HTTP auth sessions before the test, to allow
-// running them more than once.
-var authMgr = SpecialPowers.Cc['@mozilla.org/network/http-auth-manager;1']
- .getService(SpecialPowers.Ci.nsIHttpAuthManager);
-authMgr.clearAll();
-
-// start the tests
-testNum = 0;
-doTest();
-
-SimpleTest.waitForExplicitFinish();
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/test_xml_load.html b/toolkit/components/passwordmgr/test/test_xml_load.html
deleted file mode 100644
index 5672c7117..000000000
--- a/toolkit/components/passwordmgr/test/test_xml_load.html
+++ /dev/null
@@ -1,191 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test XML document prompts</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="pwmgr_common.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Login Manager test: XML prompt
-<p id="display"></p>
-
-<div id="content" style="display: none">
- <iframe id="iframe"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Login Manager: XML prompts. **/
-var pwmgr, login1, login2;
-
-function initLogins() {
- pwmgr = SpecialPowers.Cc["@mozilla.org/login-manager;1"]
- .getService(Ci.nsILoginManager);
-
- login1 = SpecialPowers.Cc["@mozilla.org/login-manager/loginInfo;1"]
- .createInstance(Ci.nsILoginInfo);
- login2 = SpecialPowers.Cc["@mozilla.org/login-manager/loginInfo;1"]
- .createInstance(Ci.nsILoginInfo);
-
- login1.init("http://mochi.test:8888", null, "xml",
- "xmluser1", "xmlpass1", "", "");
- login2.init("http://mochi.test:8888", null, "xml2",
- "xmluser2", "xmlpass2", "", "");
-
- pwmgr.addLogin(login1);
- pwmgr.addLogin(login2);
-}
-
-function handleDialog(doc, testNum) {
- ok(true, "handleDialog running for test " + testNum);
-
- var clickOK = true;
- var userfield = doc.getElementById("loginTextbox");
- var passfield = doc.getElementById("password1Textbox");
- var username = userfield.getAttribute("value");
- var password = passfield.getAttribute("value");
- var dialog = doc.getElementById("commonDialog");
-
- switch (testNum) {
- case 1:
- is(username, "xmluser1", "Checking provided username");
- is(password, "xmlpass1", "Checking provided password");
- break;
-
- case 2:
- is(username, "xmluser2", "Checking provided username");
- is(password, "xmlpass2", "Checking provided password");
-
- // Check that the dialog is modal, chrome and dependent;
- // We can't just check window.opener because that'll be
- // a content window, which therefore isn't exposed (it'll lie and
- // be null).
- var win = doc.defaultView;
- var Ci = SpecialPowers.Ci;
- var treeOwner = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).
- QueryInterface(Ci.nsIDocShellTreeItem).treeOwner;
- treeOwner.QueryInterface(Ci.nsIInterfaceRequestor);
- var flags = treeOwner.getInterface(Ci.nsIXULWindow).chromeFlags;
- var wbc = treeOwner.getInterface(Ci.nsIWebBrowserChrome);
- info("Flags: " + flags);
- ok((flags & Ci.nsIWebBrowserChrome.CHROME_OPENAS_CHROME) != 0,
- "Dialog should be opened as chrome");
- ok((flags & Ci.nsIWebBrowserChrome.CHROME_OPENAS_DIALOG) != 0,
- "Dialog should be opened as a dialog");
- ok((flags & Ci.nsIWebBrowserChrome.CHROME_DEPENDENT) != 0,
- "Dialog should be opened as dependent.");
- ok(wbc.isWindowModal(), "Dialog should be modal");
-
- // Check that the right tab is focused:
- var browserWin = SpecialPowers.Services.wm.getMostRecentWindow("navigator:browser");
- var spec = browserWin.gBrowser.selectedBrowser.currentURI.spec;
- ok(spec.startsWith("http://mochi.test:8888"),
- "Tab with remote URI (rather than about:blank) should be focused (" + spec + ")");
-
- break;
-
- default:
- ok(false, "Uhh, unhandled switch for testNum #" + testNum);
- break;
- }
-
- // Explicitly cancel the dialog and report a fail in this failure
- // case, rather than letting the dialog get stuck due to an auth
- // failure and having the test timeout.
- if (!username && !password) {
- ok(false, "No values prefilled");
- clickOK = false;
- }
-
- if (clickOK)
- dialog.acceptDialog();
- else
- dialog.cancelDialog();
-
- ok(true, "handleDialog done");
- didDialog = true;
-}
-
-var newWin;
-function xmlLoad(responseDoc) {
- ok(true, "xmlLoad running for test " + testNum);
-
- // The server echos back the user/pass it received.
- var username = responseDoc.getElementById("user").textContent;
- var password = responseDoc.getElementById("pass").textContent;
- var authok = responseDoc.getElementById("ok").textContent;
-
- switch (testNum) {
- case 1:
- is(username, "xmluser1", "Checking provided username");
- is(password, "xmlpass1", "Checking provided password");
- break;
-
- case 2:
- is(username, "xmluser2", "Checking provided username");
- is(password, "xmlpass2", "Checking provided password");
-
- newWin.close();
- break;
-
- default:
- ok(false, "Uhh, unhandled switch for testNum #" + testNum);
- break;
- }
-
- doTest();
-}
-
-function doTest() {
- switch (++testNum) {
- case 1:
- startCallbackTimer();
- makeRequest("authenticate.sjs?user=xmluser1&pass=xmlpass1&realm=xml");
- break;
-
- case 2:
- // Test correct parenting, by opening another tab in the foreground,
- // and making sure the prompt re-focuses the original tab when shown:
- newWin = window.open();
- newWin.focus();
- startCallbackTimer();
- makeRequest("authenticate.sjs?user=xmluser2&pass=xmlpass2&realm=xml2");
- break;
-
- default:
- SimpleTest.finish();
- }
-}
-
-function makeRequest(uri) {
- var xmlDoc = document.implementation.createDocument("", "test", null);
-
- function documentLoaded(e) {
- xmlLoad(xmlDoc);
- }
- xmlDoc.addEventListener("load", documentLoaded, false);
- xmlDoc.load(uri);
-}
-
-
-initLogins();
-
-// clear plain HTTP auth sessions before the test, to allow
-// running them more than once.
-var authMgr = SpecialPowers.Cc['@mozilla.org/network/http-auth-manager;1']
- .getService(SpecialPowers.Ci.nsIHttpAuthManager);
-authMgr.clearAll();
-
-// start the tests
-testNum = 0;
-doTest();
-
-SimpleTest.waitForExplicitFinish();
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/passwordmgr/test/unit/.eslintrc.js b/toolkit/components/passwordmgr/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/passwordmgr/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/passwordmgr/test/unit/data/corruptDB.sqlite b/toolkit/components/passwordmgr/test/unit/data/corruptDB.sqlite
deleted file mode 100644
index b234246ca..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/corruptDB.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/key3.db b/toolkit/components/passwordmgr/test/unit/data/key3.db
deleted file mode 100644
index a83a0a577..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/key3.db
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v1.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v1.sqlite
deleted file mode 100644
index fe030b61f..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v1.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v1v2.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v1v2.sqlite
deleted file mode 100644
index 729512a12..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v1v2.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v2.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v2.sqlite
deleted file mode 100644
index a6c72b31e..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v2.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v2v3.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v2v3.sqlite
deleted file mode 100644
index 359df5d31..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v2v3.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v3.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v3.sqlite
deleted file mode 100644
index 918f4142f..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v3.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v3v4.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v3v4.sqlite
deleted file mode 100644
index e06c33aae..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v3v4.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v4.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v4.sqlite
deleted file mode 100644
index 227c09c81..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v4.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v4v5.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v4v5.sqlite
deleted file mode 100644
index 4534cf255..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v4v5.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v5v6.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v5v6.sqlite
deleted file mode 100644
index eb4ee6d01..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v5v6.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v999-2.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v999-2.sqlite
deleted file mode 100644
index e09c4f710..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v999-2.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/data/signons-v999.sqlite b/toolkit/components/passwordmgr/test/unit/data/signons-v999.sqlite
deleted file mode 100644
index 0328a1a02..000000000
--- a/toolkit/components/passwordmgr/test/unit/data/signons-v999.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/passwordmgr/test/unit/head.js b/toolkit/components/passwordmgr/test/unit/head.js
deleted file mode 100644
index baf958ab4..000000000
--- a/toolkit/components/passwordmgr/test/unit/head.js
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * Provides infrastructure for automated login components tests.
- */
-
-"use strict";
-
-// Globals
-
-let { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/LoginRecipes.jsm");
-Cu.import("resource://gre/modules/LoginHelper.jsm");
-Cu.import("resource://testing-common/MockDocument.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths",
- "resource://gre/modules/DownloadPaths.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-
-const LoginInfo =
- Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- "nsILoginInfo", "init");
-
-// Import LoginTestUtils.jsm as LoginTestUtils.
-XPCOMUtils.defineLazyModuleGetter(this, "LoginTestUtils",
- "resource://testing-common/LoginTestUtils.jsm");
-LoginTestUtils.Assert = Assert;
-const TestData = LoginTestUtils.testData;
-const newPropertyBag = LoginHelper.newPropertyBag;
-
-/**
- * All the tests are implemented with add_task, this starts them automatically.
- */
-function run_test()
-{
- do_get_profile();
- run_next_test();
-}
-
-// Global helpers
-
-// Some of these functions are already implemented in other parts of the source
-// tree, see bug 946708 about sharing more code.
-
-// While the previous test file should have deleted all the temporary files it
-// used, on Windows these might still be pending deletion on the physical file
-// system. Thus, start from a new base number every time, to make a collision
-// with a file that is still pending deletion highly unlikely.
-let gFileCounter = Math.floor(Math.random() * 1000000);
-
-/**
- * Returns a reference to a temporary file, that is guaranteed not to exist, and
- * to have never been created before.
- *
- * @param aLeafName
- * Suggested leaf name for the file to be created.
- *
- * @return nsIFile pointing to a non-existent file in a temporary directory.
- *
- * @note It is not enough to delete the file if it exists, or to delete the file
- * after calling nsIFile.createUnique, because on Windows the delete
- * operation in the file system may still be pending, preventing a new
- * file with the same name to be created.
- */
-function getTempFile(aLeafName)
-{
- // Prepend a serial number to the extension in the suggested leaf name.
- let [base, ext] = DownloadPaths.splitBaseNameAndExtension(aLeafName);
- let leafName = base + "-" + gFileCounter + ext;
- gFileCounter++;
-
- // Get a file reference under the temporary directory for this test file.
- let file = FileUtils.getFile("TmpD", [leafName]);
- do_check_false(file.exists());
-
- do_register_cleanup(function () {
- if (file.exists()) {
- file.remove(false);
- }
- });
-
- return file;
-}
-
-const RecipeHelpers = {
- initNewParent() {
- return (new LoginRecipesParent({ defaults: null })).initializationPromise;
- },
-};
-
-// Initialization functions common to all tests
-
-add_task(function* test_common_initialize()
-{
- // Before initializing the service for the first time, we should copy the key
- // file required to decrypt the logins contained in the SQLite databases used
- // by migration tests. This file is not required for the other tests.
- yield OS.File.copy(do_get_file("data/key3.db").path,
- OS.Path.join(OS.Constants.Path.profileDir, "key3.db"));
-
- // Ensure that the service and the storage module are initialized.
- yield Services.logins.initializationPromise;
-
- // Ensure that every test file starts with an empty database.
- LoginTestUtils.clearData();
-
- // Clean up after every test.
- do_register_cleanup(() => LoginTestUtils.clearData());
-});
-
-/**
- * Compare two FormLike to see if they represent the same information. Elements
- * are compared using their @id attribute.
- */
-function formLikeEqual(a, b) {
- Assert.strictEqual(Object.keys(a).length, Object.keys(b).length,
- "Check the formLikes have the same number of properties");
-
- for (let propName of Object.keys(a)) {
- if (propName == "elements") {
- Assert.strictEqual(a.elements.length, b.elements.length, "Check element count");
- for (let i = 0; i < a.elements.length; i++) {
- Assert.strictEqual(a.elements[i].id, b.elements[i].id, "Check element " + i + " id");
- }
- continue;
- }
- Assert.strictEqual(a[propName], b[propName], "Compare formLike " + propName + " property");
- }
-}
diff --git a/toolkit/components/passwordmgr/test/unit/test_OSCrypto_win.js b/toolkit/components/passwordmgr/test/unit/test_OSCrypto_win.js
deleted file mode 100644
index 94d2e50c0..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_OSCrypto_win.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Tests the OSCrypto object.
- */
-
-"use strict";
-
-// Globals
-
-XPCOMUtils.defineLazyModuleGetter(this, "OSCrypto",
- "resource://gre/modules/OSCrypto.jsm");
-
-var crypto = new OSCrypto();
-
-// Tests
-
-add_task(function test_getIELoginHash()
-{
- do_check_eq(crypto.getIELoginHash("https://bugzilla.mozilla.org/page.cgi"),
- "4A66FE96607885790F8E67B56EEE52AB539BAFB47D");
-
- do_check_eq(crypto.getIELoginHash("https://github.com/login"),
- "0112F7DCE67B8579EA01367678AA44AB9868B5A143");
-
- do_check_eq(crypto.getIELoginHash("https://login.live.com/login.srf"),
- "FBF92E5D804C82717A57856533B779676D92903688");
-
- do_check_eq(crypto.getIELoginHash("https://preview.c9.io/riadh/w1/pass.1.html"),
- "6935CF27628830605927F86AB53831016FC8973D1A");
-
-
- do_check_eq(crypto.getIELoginHash("https://reviewboard.mozilla.org/account/login/"),
- "09141FD287E2E59A8B1D3BB5671537FD3D6B61337A");
-
- do_check_eq(crypto.getIELoginHash("https://www.facebook.com/"),
- "EF44D3E034009CB0FD1B1D81A1FF3F3335213BD796");
-
-});
-
-add_task(function test_decryptData_encryptData()
-{
- function decryptEncryptTest(key) {
- do_check_eq(crypto.decryptData(crypto.encryptData("", key), key),
- "");
-
- do_check_eq(crypto.decryptData(crypto.encryptData("secret", key), key),
- "secret");
-
- do_check_eq(crypto.decryptData(crypto.encryptData("https://www.mozilla.org", key),
- key),
- "https://www.mozilla.org");
-
- do_check_eq(crypto.decryptData(crypto.encryptData("https://reviewboard.mozilla.org", key),
- key),
- "https://reviewboard.mozilla.org");
-
- do_check_eq(crypto.decryptData(crypto.encryptData("https://bugzilla.mozilla.org/page.cgi",
- key),
- key),
- "https://bugzilla.mozilla.org/page.cgi");
- }
-
- let keys = [null, "a", "keys", "abcdedf", "pass", "https://bugzilla.mozilla.org/page.cgi",
- "https://login.live.com/login.srf"];
- for (let key of keys) {
- decryptEncryptTest(key);
- }
- let url = "https://twitter.com/";
- let value = [1, 0, 0, 0, 208, 140, 157, 223, 1, 21, 209, 17, 140, 122, 0, 192, 79, 194, 151, 235, 1, 0, 0, 0, 254, 58, 230, 75, 132, 228, 181, 79, 184, 160, 37, 106, 201, 29, 42, 152, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 16, 102, 0, 0, 0, 1, 0, 0, 32, 0, 0, 0, 90, 136, 17, 124, 122, 57, 178, 24, 34, 86, 209, 198, 184, 107, 58, 58, 32, 98, 61, 239, 129, 101, 56, 239, 114, 159, 139, 165, 183, 40, 183, 85, 0, 0, 0, 0, 14, 128, 0, 0, 0, 2, 0, 0, 32, 0, 0, 0, 147, 170, 34, 21, 53, 227, 191, 6, 201, 84, 106, 31, 57, 227, 46, 127, 219, 199, 80, 142, 37, 104, 112, 223, 26, 165, 223, 55, 176, 89, 55, 37, 112, 0, 0, 0, 98, 70, 221, 109, 5, 152, 46, 11, 190, 213, 226, 58, 244, 20, 180, 217, 63, 155, 227, 132, 7, 151, 235, 6, 37, 232, 176, 182, 141, 191, 251, 50, 20, 123, 53, 11, 247, 233, 112, 121, 130, 27, 168, 68, 92, 144, 192, 7, 12, 239, 53, 217, 253, 155, 54, 109, 236, 216, 225, 245, 79, 234, 165, 225, 104, 36, 77, 13, 195, 237, 143, 165, 100, 107, 230, 70, 54, 19, 179, 35, 8, 101, 93, 202, 121, 210, 222, 28, 93, 122, 36, 84, 185, 249, 238, 3, 102, 149, 248, 94, 137, 16, 192, 22, 251, 220, 22, 223, 16, 58, 104, 187, 64, 0, 0, 0, 70, 72, 15, 119, 144, 66, 117, 203, 190, 82, 131, 46, 111, 130, 238, 191, 170, 63, 186, 117, 46, 88, 171, 3, 94, 146, 75, 86, 243, 159, 63, 195, 149, 25, 105, 141, 42, 217, 108, 18, 63, 62, 98, 182, 241, 195, 12, 216, 152, 230, 176, 253, 202, 129, 41, 185, 135, 111, 226, 92, 27, 78, 27, 198];
-
- let arr1 = crypto.arrayToString(value);
- let arr2 = crypto.stringToArray(crypto.decryptData(crypto.encryptData(arr1, url), url));
- for (let i = 0; i < arr1.length; i++) {
- do_check_eq(arr2[i], value[i]);
- }
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_context_menu.js b/toolkit/components/passwordmgr/test/unit/test_context_menu.js
deleted file mode 100644
index 722c13e15..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_context_menu.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Test the password manager context menu.
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/LoginManagerContextMenu.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "_stringBundle", function() {
- return Services.strings.
- createBundle("chrome://passwordmgr/locale/passwordmgr.properties");
-});
-
-/**
- * Prepare data for the following tests.
- */
-add_task(function* test_initialize() {
- for (let login of loginList()) {
- Services.logins.addLogin(login);
- }
-});
-
-/**
- * Tests if the LoginManagerContextMenu returns the correct login items.
- */
-add_task(function* test_contextMenuAddAndRemoveLogins() {
- const DOCUMENT_CONTENT = "<form><input id='pw' type=password></form>";
- const INPUT_QUERY = "input[type='password']";
-
- let testHostnames = [
- "http://www.example.com",
- "http://www2.example.com",
- "http://www3.example.com",
- "http://empty.example.com",
- ];
-
- for (let hostname of testHostnames) {
- do_print("test for hostname: " + hostname);
- // Get expected logins for this test.
- let logins = getExpectedLogins(hostname);
-
- // Create the logins menuitems fragment.
- let {fragment, document} = createLoginsFragment(hostname, DOCUMENT_CONTENT, INPUT_QUERY);
-
- if (!logins.length) {
- Assert.ok(fragment === null, "Null returned. No logins where found.");
- continue;
- }
- let items = [...fragment.querySelectorAll("menuitem")];
-
- // Check if the items are those expected to be listed.
- Assert.ok(checkLoginItems(logins, items), "All expected logins found.");
- document.body.appendChild(fragment);
-
- // Try to clear the fragment.
- LoginManagerContextMenu.clearLoginsFromMenu(document);
- Assert.equal(fragment.querySelectorAll("menuitem").length, 0, "All items correctly cleared.");
- }
-
- Services.logins.removeAllLogins();
-});
-
-/**
- * Create a fragment with a menuitem for each login.
- */
-function createLoginsFragment(url, content, elementQuery) {
- const CHROME_URL = "chrome://mock-chrome";
-
- // Create a mock document.
- let document = MockDocument.createTestDocument(CHROME_URL, content);
- let inputElement = document.querySelector(elementQuery);
- MockDocument.mockOwnerDocumentProperty(inputElement, document, url);
-
- // We also need a simple mock Browser object for this test.
- let browser = {
- ownerDocument: document
- };
-
- let URI = Services.io.newURI(url, null, null);
- return {
- document,
- fragment: LoginManagerContextMenu.addLoginsToMenu(inputElement, browser, URI),
- };
-}
-
-/**
- * Check if every login have it's corresponding menuitem.
- * Duplicates and empty usernames have a date appended.
- */
-function checkLoginItems(logins, items) {
- function findDuplicates(unfilteredLoginList) {
- var seen = new Set();
- var duplicates = new Set();
- for (let login of unfilteredLoginList) {
- if (seen.has(login.username)) {
- duplicates.add(login.username);
- }
- seen.add(login.username);
- }
- return duplicates;
- }
- let duplicates = findDuplicates(logins);
-
- let dateAndTimeFormatter = new Intl.DateTimeFormat(undefined,
- { day: "numeric", month: "short", year: "numeric" });
- for (let login of logins) {
- if (login.username && !duplicates.has(login.username)) {
- // If login is not duplicate and we can't find an item for it, fail.
- if (!items.find(item => item.label == login.username)) {
- return false;
- }
- continue;
- }
-
- let meta = login.QueryInterface(Ci.nsILoginMetaInfo);
- let time = dateAndTimeFormatter.format(new Date(meta.timePasswordChanged));
- // If login is duplicate, check if we have a login item with appended date.
- if (login.username && !items.find(item => item.label == login.username + " (" + time + ")")) {
- return false;
- }
- // If login is empty, check if we have a login item with appended date.
- if (!login.username &&
- !items.find(item => item.label == _stringBundle.GetStringFromName("noUsername") + " (" + time + ")")) {
- return false;
- }
- }
- return true;
-}
-
-/**
- * Gets the list of expected logins for a hostname.
- */
-function getExpectedLogins(hostname) {
- return Services.logins.getAllLogins().filter(entry => entry["hostname"] === hostname);
-}
-
-function loginList() {
- return [
- new LoginInfo("http://www.example.com", "http://www.example.com", null,
- "username1", "password",
- "form_field_username", "form_field_password"),
-
- new LoginInfo("http://www.example.com", "http://www.example.com", null,
- "username2", "password",
- "form_field_username", "form_field_password"),
-
- new LoginInfo("http://www2.example.com", "http://www.example.com", null,
- "username", "password",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://www2.example.com", "http://www2.example.com", null,
- "username", "password2",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://www2.example.com", "http://www2.example.com", null,
- "username2", "password2",
- "form_field_username", "form_field_password"),
-
- new LoginInfo("http://www3.example.com", "http://www.example.com", null,
- "", "password",
- "form_field_username", "form_field_password"),
- new LoginInfo("http://www3.example.com", "http://www3.example.com", null,
- "", "password2",
- "form_field_username", "form_field_password"),
- ];
-}
diff --git a/toolkit/components/passwordmgr/test/unit/test_dedupeLogins.js b/toolkit/components/passwordmgr/test/unit/test_dedupeLogins.js
deleted file mode 100644
index d688a6dbf..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_dedupeLogins.js
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Test LoginHelper.dedupeLogins
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/LoginHelper.jsm");
-
-const DOMAIN1_HTTP_TO_HTTP_U1_P1 = TestData.formLogin({
- timePasswordChanged: 3000,
- timeLastUsed: 2000,
-});
-const DOMAIN1_HTTP_TO_HTTP_U1_P2 = TestData.formLogin({
- password: "password two",
-});
-const DOMAIN1_HTTP_TO_HTTP_U2_P2 = TestData.formLogin({
- password: "password two",
- username: "username two",
-});
-const DOMAIN1_HTTPS_TO_HTTPS_U1_P1 = TestData.formLogin({
- formSubmitURL: "http://www.example.com",
- hostname: "https://www3.example.com",
- timePasswordChanged: 4000,
- timeLastUsed: 1000,
-});
-const DOMAIN1_HTTPS_TO_EMPTY_U1_P1 = TestData.formLogin({
- formSubmitURL: "",
- hostname: "https://www3.example.com",
-});
-const DOMAIN1_HTTPS_TO_EMPTYU_P1 = TestData.formLogin({
- hostname: "https://www3.example.com",
- username: "",
-});
-const DOMAIN1_HTTP_AUTH = TestData.authLogin({
- hostname: "http://www3.example.com",
-});
-const DOMAIN1_HTTPS_AUTH = TestData.authLogin({
- hostname: "https://www3.example.com",
-});
-
-
-add_task(function test_dedupeLogins() {
- // [description, expectedOutput, dedupe arg. 0, dedupe arg 1, ...]
- let testcases = [
- [
- "exact dupes",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- [], // force no resolveBy logic to test behavior of preferring the first..
- ],
- [
- "default uniqueKeys is un + pw",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P2],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P2],
- undefined,
- [],
- ],
- [
- "same usernames, different passwords, dedupe username only",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P2],
- ["username"],
- [],
- ],
- [
- "same un+pw, different scheme",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- undefined,
- [],
- ],
- [
- "same un+pw, different scheme, reverse order",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- [],
- ],
- [
- "same un+pw, different scheme, include hostname",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- ["hostname", "username", "password"],
- [],
- ],
- [
- "empty username is not deduped with non-empty",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_EMPTYU_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_EMPTYU_P1],
- undefined,
- [],
- ],
- [
- "empty username is deduped with same passwords",
- [DOMAIN1_HTTPS_TO_EMPTYU_P1],
- [DOMAIN1_HTTPS_TO_EMPTYU_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- ["password"],
- [],
- ],
- [
- "mix of form and HTTP auth",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTP_AUTH],
- undefined,
- [],
- ],
- ];
-
- for (let tc of testcases) {
- let description = tc.shift();
- let expected = tc.shift();
- let actual = LoginHelper.dedupeLogins(...tc);
- Assert.strictEqual(actual.length, expected.length, `Check: ${description}`);
- for (let [i, login] of expected.entries()) {
- Assert.strictEqual(actual[i], login, `Check index ${i}`);
- }
- }
-});
-
-
-add_task(function* test_dedupeLogins_resolveBy() {
- Assert.ok(DOMAIN1_HTTP_TO_HTTP_U1_P1.timeLastUsed > DOMAIN1_HTTPS_TO_HTTPS_U1_P1.timeLastUsed,
- "Sanity check timeLastUsed difference");
- Assert.ok(DOMAIN1_HTTP_TO_HTTP_U1_P1.timePasswordChanged < DOMAIN1_HTTPS_TO_HTTPS_U1_P1.timePasswordChanged,
- "Sanity check timePasswordChanged difference");
-
- let testcases = [
- [
- "default resolveBy is timeLastUsed",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- ],
- [
- "default resolveBy is timeLastUsed, reversed input",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- ],
- [
- "resolveBy timeLastUsed + timePasswordChanged",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["timeLastUsed", "timePasswordChanged"],
- ],
- [
- "resolveBy timeLastUsed + timePasswordChanged, reversed input",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- undefined,
- ["timeLastUsed", "timePasswordChanged"],
- ],
- [
- "resolveBy timePasswordChanged",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["timePasswordChanged"],
- ],
- [
- "resolveBy timePasswordChanged, reversed",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- undefined,
- ["timePasswordChanged"],
- ],
- [
- "resolveBy timePasswordChanged + timeLastUsed",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["timePasswordChanged", "timeLastUsed"],
- ],
- [
- "resolveBy timePasswordChanged + timeLastUsed, reversed",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- undefined,
- ["timePasswordChanged", "timeLastUsed"],
- ],
- [
- "resolveBy scheme + timePasswordChanged, prefer HTTP",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["scheme", "timePasswordChanged"],
- DOMAIN1_HTTP_TO_HTTP_U1_P1.hostname,
- ],
- [
- "resolveBy scheme + timePasswordChanged, prefer HTTP, reversed input",
- [DOMAIN1_HTTP_TO_HTTP_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- undefined,
- ["scheme", "timePasswordChanged"],
- DOMAIN1_HTTP_TO_HTTP_U1_P1.hostname,
- ],
- [
- "resolveBy scheme + timePasswordChanged, prefer HTTPS",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["scheme", "timePasswordChanged"],
- DOMAIN1_HTTPS_TO_HTTPS_U1_P1.hostname,
- ],
- [
- "resolveBy scheme + timePasswordChanged, prefer HTTPS, reversed input",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTP_TO_HTTP_U1_P1, DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- undefined,
- ["scheme", "timePasswordChanged"],
- DOMAIN1_HTTPS_TO_HTTPS_U1_P1.hostname,
- ],
- [
- "resolveBy scheme HTTP auth",
- [DOMAIN1_HTTPS_AUTH],
- [DOMAIN1_HTTP_AUTH, DOMAIN1_HTTPS_AUTH],
- undefined,
- ["scheme"],
- DOMAIN1_HTTPS_AUTH.hostname,
- ],
- [
- "resolveBy scheme HTTP auth, reversed input",
- [DOMAIN1_HTTPS_AUTH],
- [DOMAIN1_HTTPS_AUTH, DOMAIN1_HTTP_AUTH],
- undefined,
- ["scheme"],
- DOMAIN1_HTTPS_AUTH.hostname,
- ],
- [
- "resolveBy scheme, empty form submit URL",
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1],
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTPS_TO_EMPTY_U1_P1],
- undefined,
- ["scheme"],
- DOMAIN1_HTTPS_TO_HTTPS_U1_P1.hostname,
- ],
- ];
-
- for (let tc of testcases) {
- let description = tc.shift();
- let expected = tc.shift();
- let actual = LoginHelper.dedupeLogins(...tc);
- Assert.strictEqual(actual.length, expected.length, `Check: ${description}`);
- for (let [i, login] of expected.entries()) {
- Assert.strictEqual(actual[i], login, `Check index ${i}`);
- }
- }
-
-});
-
-add_task(function* test_dedupeLogins_preferredOriginMissing() {
- let testcases = [
- [
- "resolveBy scheme + timePasswordChanged, missing preferredOrigin",
- /preferredOrigin/,
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["scheme", "timePasswordChanged"],
- ],
- [
- "resolveBy timePasswordChanged + scheme, missing preferredOrigin",
- /preferredOrigin/,
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["timePasswordChanged", "scheme"],
- ],
- [
- "resolveBy scheme + timePasswordChanged, empty preferredOrigin",
- /preferredOrigin/,
- [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
- undefined,
- ["scheme", "timePasswordChanged"],
- "",
- ],
- ];
-
- for (let tc of testcases) {
- let description = tc.shift();
- let expectedException = tc.shift();
- Assert.throws(() => {
- LoginHelper.dedupeLogins(...tc);
- }, expectedException, `Check: ${description}`);
- }
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_disabled_hosts.js b/toolkit/components/passwordmgr/test/unit/test_disabled_hosts.js
deleted file mode 100644
index ff3b7e868..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_disabled_hosts.js
+++ /dev/null
@@ -1,196 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests getLoginSavingEnabled, setLoginSavingEnabled, and getAllDisabledHosts.
- */
-
-"use strict";
-
-// Tests
-
-/**
- * Tests setLoginSavingEnabled and getAllDisabledHosts.
- */
-add_task(function test_setLoginSavingEnabled_getAllDisabledHosts()
-{
- // Add some disabled hosts, and verify that different schemes for the same
- // domain are considered different hosts.
- let hostname1 = "http://disabled1.example.com";
- let hostname2 = "http://disabled2.example.com";
- let hostname3 = "https://disabled2.example.com";
- Services.logins.setLoginSavingEnabled(hostname1, false);
- Services.logins.setLoginSavingEnabled(hostname2, false);
- Services.logins.setLoginSavingEnabled(hostname3, false);
-
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- [hostname1, hostname2, hostname3]);
-
- // Adding the same host twice should not result in an error.
- Services.logins.setLoginSavingEnabled(hostname2, false);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- [hostname1, hostname2, hostname3]);
-
- // Removing a disabled host should work.
- Services.logins.setLoginSavingEnabled(hostname2, true);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- [hostname1, hostname3]);
-
- // Removing the last disabled host should work.
- Services.logins.setLoginSavingEnabled(hostname1, true);
- Services.logins.setLoginSavingEnabled(hostname3, true);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- []);
-});
-
-/**
- * Tests setLoginSavingEnabled and getLoginSavingEnabled.
- */
-add_task(function test_setLoginSavingEnabled_getLoginSavingEnabled()
-{
- let hostname1 = "http://disabled.example.com";
- let hostname2 = "https://disabled.example.com";
-
- // Hosts should not be disabled by default.
- do_check_true(Services.logins.getLoginSavingEnabled(hostname1));
- do_check_true(Services.logins.getLoginSavingEnabled(hostname2));
-
- // Test setting initial values.
- Services.logins.setLoginSavingEnabled(hostname1, false);
- Services.logins.setLoginSavingEnabled(hostname2, true);
- do_check_false(Services.logins.getLoginSavingEnabled(hostname1));
- do_check_true(Services.logins.getLoginSavingEnabled(hostname2));
-
- // Test changing values.
- Services.logins.setLoginSavingEnabled(hostname1, true);
- Services.logins.setLoginSavingEnabled(hostname2, false);
- do_check_true(Services.logins.getLoginSavingEnabled(hostname1));
- do_check_false(Services.logins.getLoginSavingEnabled(hostname2));
-
- // Clean up.
- Services.logins.setLoginSavingEnabled(hostname2, true);
-});
-
-/**
- * Tests setLoginSavingEnabled with invalid NUL characters in the hostname.
- */
-add_task(function test_setLoginSavingEnabled_invalid_characters()
-{
- let hostname = "http://null\0X.example.com";
- Assert.throws(() => Services.logins.setLoginSavingEnabled(hostname, false),
- /Invalid hostname/);
-
- // Verify that no data was stored by the previous call.
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- []);
-});
-
-/**
- * Tests different values of the "signon.rememberSignons" property.
- */
-add_task(function test_rememberSignons()
-{
- let hostname1 = "http://example.com";
- let hostname2 = "http://localhost";
-
- // The default value for the preference should be true.
- do_check_true(Services.prefs.getBoolPref("signon.rememberSignons"));
-
- // Hosts should not be disabled by default.
- Services.logins.setLoginSavingEnabled(hostname1, false);
- do_check_false(Services.logins.getLoginSavingEnabled(hostname1));
- do_check_true(Services.logins.getLoginSavingEnabled(hostname2));
-
- // Disable storage of saved passwords globally.
- Services.prefs.setBoolPref("signon.rememberSignons", false);
- do_register_cleanup(
- () => Services.prefs.clearUserPref("signon.rememberSignons"));
-
- // All hosts should now appear disabled.
- do_check_false(Services.logins.getLoginSavingEnabled(hostname1));
- do_check_false(Services.logins.getLoginSavingEnabled(hostname2));
-
- // The list of disabled hosts should be unaltered.
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- [hostname1]);
-
- // Changing values with the preference set should work.
- Services.logins.setLoginSavingEnabled(hostname1, true);
- Services.logins.setLoginSavingEnabled(hostname2, false);
-
- // All hosts should still appear disabled.
- do_check_false(Services.logins.getLoginSavingEnabled(hostname1));
- do_check_false(Services.logins.getLoginSavingEnabled(hostname2));
-
- // The list of disabled hosts should have been changed.
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- [hostname2]);
-
- // Enable storage of saved passwords again.
- Services.prefs.setBoolPref("signon.rememberSignons", true);
-
- // Hosts should now appear enabled as requested.
- do_check_true(Services.logins.getLoginSavingEnabled(hostname1));
- do_check_false(Services.logins.getLoginSavingEnabled(hostname2));
-
- // Clean up.
- Services.logins.setLoginSavingEnabled(hostname2, true);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- []);
-});
-
-/**
- * Tests storing disabled hosts with non-ASCII characters where IDN is supported.
- */
-add_task(function* test_storage_setLoginSavingEnabled_nonascii_IDN_is_supported()
-{
- let hostname = "http://大.net";
- let encoding = "http://xn--pss.net";
-
- // Test adding disabled host with nonascii URL (http://大.net).
- Services.logins.setLoginSavingEnabled(hostname, false);
- yield* LoginTestUtils.reloadData();
- Assert.equal(Services.logins.getLoginSavingEnabled(hostname), false);
- Assert.equal(Services.logins.getLoginSavingEnabled(encoding), false);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(), [hostname]);
-
- LoginTestUtils.clearData();
-
- // Test adding disabled host with IDN ("http://xn--pss.net").
- Services.logins.setLoginSavingEnabled(encoding, false);
- yield* LoginTestUtils.reloadData();
- Assert.equal(Services.logins.getLoginSavingEnabled(hostname), false);
- Assert.equal(Services.logins.getLoginSavingEnabled(encoding), false);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(), [hostname]);
-
- LoginTestUtils.clearData();
-});
-
-/**
- * Tests storing disabled hosts with non-ASCII characters where IDN is not supported.
- */
-add_task(function* test_storage_setLoginSavingEnabled_nonascii_IDN_not_supported()
-{
- let hostname = "http://√.com";
- let encoding = "http://xn--19g.com";
-
- // Test adding disabled host with nonascii URL (http://√.com).
- Services.logins.setLoginSavingEnabled(hostname, false);
- yield* LoginTestUtils.reloadData();
- Assert.equal(Services.logins.getLoginSavingEnabled(hostname), false);
- Assert.equal(Services.logins.getLoginSavingEnabled(encoding), false);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(), [encoding]);
-
- LoginTestUtils.clearData();
-
- // Test adding disabled host with IDN ("http://xn--19g.com").
- Services.logins.setLoginSavingEnabled(encoding, false);
- yield* LoginTestUtils.reloadData();
- Assert.equal(Services.logins.getLoginSavingEnabled(hostname), false);
- Assert.equal(Services.logins.getLoginSavingEnabled(encoding), false);
- LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(), [encoding]);
-
- LoginTestUtils.clearData();
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_getFormFields.js b/toolkit/components/passwordmgr/test/unit/test_getFormFields.js
deleted file mode 100644
index 46912ab8f..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_getFormFields.js
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Test for LoginManagerContent._getFormFields.
- */
-
-"use strict";
-
-// Services.prefs.setBoolPref("signon.debug", true);
-
-Cu.importGlobalProperties(["URL"]);
-
-const LMCBackstagePass = Cu.import("resource://gre/modules/LoginManagerContent.jsm");
-const { LoginManagerContent, LoginFormFactory } = LMCBackstagePass;
-const TESTCASES = [
- {
- description: "1 password field outside of a <form>",
- document: `<input id="pw1" type=password>`,
- returnedFieldIDs: [null, "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "1 text field outside of a <form> without a password field",
- document: `<input id="un1">`,
- returnedFieldIDs: [null, null, null],
- skipEmptyFields: undefined,
- },
- {
- description: "1 username & password field outside of a <form>",
- document: `<input id="un1">
- <input id="pw1" type=password>`,
- returnedFieldIDs: ["un1", "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "1 username & password field in a <form>",
- document: `<form>
- <input id="un1">
- <input id="pw1" type=password>
- </form>`,
- returnedFieldIDs: ["un1", "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "4 empty password fields outside of a <form>",
- document: `<input id="pw1" type=password>
- <input id="pw2" type=password>
- <input id="pw3" type=password>
- <input id="pw4" type=password>`,
- returnedFieldIDs: [null, null, null],
- skipEmptyFields: undefined,
- },
- {
- description: "4 password fields outside of a <form> (1 empty, 3 full) with skipEmpty",
- document: `<input id="pw1" type=password>
- <input id="pw2" type=password value="pass2">
- <input id="pw3" type=password value="pass3">
- <input id="pw4" type=password value="pass4">`,
- returnedFieldIDs: [null, null, null],
- skipEmptyFields: true,
- },
- {
- description: "Form with 1 password field",
- document: `<form><input id="pw1" type=password></form>`,
- returnedFieldIDs: [null, "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "Form with 2 password fields",
- document: `<form><input id="pw1" type=password><input id='pw2' type=password></form>`,
- returnedFieldIDs: [null, "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "1 password field in a form, 1 outside (not processed)",
- document: `<form><input id="pw1" type=password></form><input id="pw2" type=password>`,
- returnedFieldIDs: [null, "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "1 password field in a form, 1 text field outside (not processed)",
- document: `<form><input id="pw1" type=password></form><input>`,
- returnedFieldIDs: [null, "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "1 text field in a form, 1 password field outside (not processed)",
- document: `<form><input></form><input id="pw1" type=password>`,
- returnedFieldIDs: [null, null, null],
- skipEmptyFields: undefined,
- },
- {
- description: "2 password fields outside of a <form> with 1 linked via @form",
- document: `<input id="pw1" type=password><input id="pw2" type=password form='form1'>
- <form id="form1"></form>`,
- returnedFieldIDs: [null, "pw1", null],
- skipEmptyFields: undefined,
- },
- {
- description: "2 password fields outside of a <form> with 1 linked via @form + skipEmpty",
- document: `<input id="pw1" type=password><input id="pw2" type=password form="form1">
- <form id="form1"></form>`,
- returnedFieldIDs: [null, null, null],
- skipEmptyFields: true,
- },
- {
- description: "2 password fields outside of a <form> with 1 linked via @form + skipEmpty with 1 empty",
- document: `<input id="pw1" type=password value="pass1"><input id="pw2" type=password form="form1">
- <form id="form1"></form>`,
- returnedFieldIDs: [null, "pw1", null],
- skipEmptyFields: true,
- },
-];
-
-for (let tc of TESTCASES) {
- do_print("Sanity checking the testcase: " + tc.description);
-
- (function() {
- let testcase = tc;
- add_task(function*() {
- do_print("Starting testcase: " + testcase.description);
- let document = MockDocument.createTestDocument("http://localhost:8080/test/",
- testcase.document);
-
- let input = document.querySelector("input");
- MockDocument.mockOwnerDocumentProperty(input, document, "http://localhost:8080/test/");
-
- let formLike = LoginFormFactory.createFromField(input);
-
- let actual = LoginManagerContent._getFormFields(formLike,
- testcase.skipEmptyFields,
- new Set());
-
- Assert.strictEqual(testcase.returnedFieldIDs.length, 3,
- "_getFormFields returns 3 elements");
-
- for (let i = 0; i < testcase.returnedFieldIDs.length; i++) {
- let expectedID = testcase.returnedFieldIDs[i];
- if (expectedID === null) {
- Assert.strictEqual(actual[i], expectedID,
- "Check returned field " + i + " is null");
- } else {
- Assert.strictEqual(actual[i].id, expectedID,
- "Check returned field " + i + " ID");
- }
- }
- });
- })();
-}
diff --git a/toolkit/components/passwordmgr/test/unit/test_getPasswordFields.js b/toolkit/components/passwordmgr/test/unit/test_getPasswordFields.js
deleted file mode 100644
index 08fa422ab..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_getPasswordFields.js
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Test for LoginManagerContent._getPasswordFields using LoginFormFactory.
- */
-
-"use strict";
-
-const LMCBackstagePass = Cu.import("resource://gre/modules/LoginManagerContent.jsm");
-const { LoginManagerContent, LoginFormFactory } = LMCBackstagePass;
-const TESTCASES = [
- {
- description: "Empty document",
- document: ``,
- returnedFieldIDsByFormLike: [],
- skipEmptyFields: undefined,
- },
- {
- description: "Non-password input with no <form> present",
- document: `<input>`,
- // Only the IDs of password fields should be in this array
- returnedFieldIDsByFormLike: [[]],
- skipEmptyFields: undefined,
- },
- {
- description: "1 password field outside of a <form>",
- document: `<input id="pw1" type=password>`,
- returnedFieldIDsByFormLike: [["pw1"]],
- skipEmptyFields: undefined,
- },
- {
- description: "4 empty password fields outside of a <form>",
- document: `<input id="pw1" type=password>
- <input id="pw2" type=password>
- <input id="pw3" type=password>
- <input id="pw4" type=password>`,
- returnedFieldIDsByFormLike: [[]],
- skipEmptyFields: undefined,
- },
- {
- description: "4 password fields outside of a <form> (1 empty, 3 full) with skipEmpty",
- document: `<input id="pw1" type=password>
- <input id="pw2" type=password value="pass2">
- <input id="pw3" type=password value="pass3">
- <input id="pw4" type=password value="pass4">`,
- returnedFieldIDsByFormLike: [["pw2", "pw3", "pw4"]],
- skipEmptyFields: true,
- },
- {
- description: "Form with 1 password field",
- document: `<form><input id="pw1" type=password></form>`,
- returnedFieldIDsByFormLike: [["pw1"]],
- skipEmptyFields: undefined,
- },
- {
- description: "Form with 2 password fields",
- document: `<form><input id="pw1" type=password><input id='pw2' type=password></form>`,
- returnedFieldIDsByFormLike: [["pw1", "pw2"]],
- skipEmptyFields: undefined,
- },
- {
- description: "1 password field in a form, 1 outside",
- document: `<form><input id="pw1" type=password></form><input id="pw2" type=password>`,
- returnedFieldIDsByFormLike: [["pw1"], ["pw2"]],
- skipEmptyFields: undefined,
- },
- {
- description: "2 password fields outside of a <form> with 1 linked via @form",
- document: `<input id="pw1" type=password><input id="pw2" type=password form='form1'>
- <form id="form1"></form>`,
- returnedFieldIDsByFormLike: [["pw1"], ["pw2"]],
- skipEmptyFields: undefined,
- },
- {
- description: "2 password fields outside of a <form> with 1 linked via @form + skipEmpty",
- document: `<input id="pw1" type=password><input id="pw2" type=password form="form1">
- <form id="form1"></form>`,
- returnedFieldIDsByFormLike: [[], []],
- skipEmptyFields: true,
- },
- {
- description: "skipEmptyFields should also skip white-space only fields",
- document: `<input id="pw-space" type=password value=" ">
- <input id="pw-tab" type=password value=" ">
- <input id="pw-newline" type=password form="form1" value="
-">
- <form id="form1"></form>`,
- returnedFieldIDsByFormLike: [[], []],
- skipEmptyFields: true,
- },
- {
- description: "2 password fields outside of a <form> with 1 linked via @form + skipEmpty with 1 empty",
- document: `<input id="pw1" type=password value=" pass1 "><input id="pw2" type=password form="form1">
- <form id="form1"></form>`,
- returnedFieldIDsByFormLike: [["pw1"], []],
- skipEmptyFields: true,
- },
-];
-
-for (let tc of TESTCASES) {
- do_print("Sanity checking the testcase: " + tc.description);
-
- (function() {
- let testcase = tc;
- add_task(function*() {
- do_print("Starting testcase: " + testcase.description);
- let document = MockDocument.createTestDocument("http://localhost:8080/test/",
- testcase.document);
-
- let mapRootElementToFormLike = new Map();
- for (let input of document.querySelectorAll("input")) {
- let formLike = LoginFormFactory.createFromField(input);
- let existingFormLike = mapRootElementToFormLike.get(formLike.rootElement);
- if (!existingFormLike) {
- mapRootElementToFormLike.set(formLike.rootElement, formLike);
- continue;
- }
-
- // If the formLike is already present, ensure that the properties are the same.
- do_print("Checking if the new FormLike for the same root has the same properties");
- formLikeEqual(formLike, existingFormLike);
- }
-
- Assert.strictEqual(mapRootElementToFormLike.size, testcase.returnedFieldIDsByFormLike.length,
- "Check the correct number of different formLikes were returned");
-
- let formLikeIndex = -1;
- for (let formLikeFromInput of mapRootElementToFormLike.values()) {
- formLikeIndex++;
- let pwFields = LoginManagerContent._getPasswordFields(formLikeFromInput,
- testcase.skipEmptyFields);
-
- if (formLikeFromInput.rootElement instanceof Ci.nsIDOMHTMLFormElement) {
- let formLikeFromForm = LoginFormFactory.createFromForm(formLikeFromInput.rootElement);
- do_print("Checking that the FormLike created for the <form> matches" +
- " the one from a password field");
- formLikeEqual(formLikeFromInput, formLikeFromForm);
- }
-
-
- if (testcase.returnedFieldIDsByFormLike[formLikeIndex].length === 0) {
- Assert.strictEqual(pwFields, null,
- "If no password fields were found null should be returned");
- } else {
- Assert.strictEqual(pwFields.length,
- testcase.returnedFieldIDsByFormLike[formLikeIndex].length,
- "Check the # of password fields for formLike #" + formLikeIndex);
- }
-
- for (let i = 0; i < testcase.returnedFieldIDsByFormLike[formLikeIndex].length; i++) {
- let expectedID = testcase.returnedFieldIDsByFormLike[formLikeIndex][i];
- Assert.strictEqual(pwFields[i].element.id, expectedID,
- "Check password field " + i + " ID");
- }
- }
- });
- })();
-}
diff --git a/toolkit/components/passwordmgr/test/unit/test_getPasswordOrigin.js b/toolkit/components/passwordmgr/test/unit/test_getPasswordOrigin.js
deleted file mode 100644
index f2773ec62..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_getPasswordOrigin.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Test for LoginUtils._getPasswordOrigin
- */
-
-"use strict";
-
-const LMCBackstagePass = Cu.import("resource://gre/modules/LoginManagerContent.jsm");
-const TESTCASES = [
- ["javascript:void(0);", null],
- ["javascript:void(0);", "javascript:", true],
- ["chrome://MyAccount", null],
- ["data:text/html,example", null],
- ["http://username:password@example.com:80/foo?bar=baz#fragment", "http://example.com", true],
- ["http://127.0.0.1:80/foo", "http://127.0.0.1"],
- ["http://[::1]:80/foo", "http://[::1]"],
- ["http://example.com:8080/foo", "http://example.com:8080"],
- ["http://127.0.0.1:8080/foo", "http://127.0.0.1:8080", true],
- ["http://[::1]:8080/foo", "http://[::1]:8080"],
- ["https://example.com:443/foo", "https://example.com"],
- ["https://[::1]:443/foo", "https://[::1]"],
- ["https://[::1]:8443/foo", "https://[::1]:8443"],
- ["ftp://username:password@[::1]:2121/foo", "ftp://[::1]:2121"],
-];
-
-for (let [input, expected, allowJS] of TESTCASES) {
- let actual = LMCBackstagePass.LoginUtils._getPasswordOrigin(input, allowJS);
- Assert.strictEqual(actual, expected, "Checking: " + input);
-}
diff --git a/toolkit/components/passwordmgr/test/unit/test_isOriginMatching.js b/toolkit/components/passwordmgr/test/unit/test_isOriginMatching.js
deleted file mode 100644
index 660910dff..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_isOriginMatching.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Test LoginHelper.isOriginMatching
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/LoginHelper.jsm");
-
-add_task(function test_isOriginMatching() {
- let testcases = [
- // Index 0 holds the expected return value followed by arguments to isOriginMatching.
- [true, "http://example.com", "http://example.com"],
- [true, "http://example.com:8080", "http://example.com:8080"],
- [true, "https://example.com", "https://example.com"],
- [true, "https://example.com:8443", "https://example.com:8443"],
- [false, "http://example.com", "http://mozilla.org"],
- [false, "http://example.com", "http://example.com:8080"],
- [false, "https://example.com", "http://example.com"],
- [false, "https://example.com", "https://mozilla.org"],
- [false, "http://example.com", "http://sub.example.com"],
- [false, "https://example.com", "https://sub.example.com"],
- [false, "http://example.com", "https://example.com:8443"],
- [false, "http://example.com:8080", "http://example.com:8081"],
- [false, "http://example.com", ""],
- [false, "", "http://example.com"],
- [true, "http://example.com", "https://example.com", { schemeUpgrades: true }],
- [true, "https://example.com", "https://example.com", { schemeUpgrades: true }],
- [true, "http://example.com:8080", "http://example.com:8080", { schemeUpgrades: true }],
- [true, "https://example.com:8443", "https://example.com:8443", { schemeUpgrades: true }],
- [false, "https://example.com", "http://example.com", { schemeUpgrades: true }], // downgrade
- [false, "http://example.com:8080", "https://example.com", { schemeUpgrades: true }], // port mismatch
- [false, "http://example.com", "https://example.com:8443", { schemeUpgrades: true }], // port mismatch
- [false, "http://sub.example.com", "http://example.com", { schemeUpgrades: true }],
- ];
- for (let tc of testcases) {
- let expected = tc.shift();
- Assert.strictEqual(LoginHelper.isOriginMatching(...tc), expected,
- "Check " + JSON.stringify(tc));
- }
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_legacy_empty_formSubmitURL.js b/toolkit/components/passwordmgr/test/unit/test_legacy_empty_formSubmitURL.js
deleted file mode 100644
index 4e16aa267..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_legacy_empty_formSubmitURL.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the legacy case of a login store containing entries that have an empty
- * string in the formSubmitURL field.
- *
- * In normal conditions, for the purpose of login autocomplete, HTML forms are
- * identified using both the prePath of the URI on which they are located, and
- * the prePath of the URI where the data will be submitted. This is represented
- * by the hostname and formSubmitURL properties of the stored nsILoginInfo.
- *
- * When a new login for use in forms is saved (after the user replies to the
- * password prompt), it is always stored with both the hostname and the
- * formSubmitURL (that will be equal to the hostname when the form has no
- * "action" attribute).
- *
- * When the same form is displayed again, the password is autocompleted. If
- * there is another form on the same site that submits to a different site, it
- * is considered a different form, so the password is not autocompleted, but a
- * new password can be stored for the other form.
- *
- * However, the login database might contain data for an nsILoginInfo that has a
- * valid hostname, but an empty formSubmitURL. This means that the login
- * applies to all forms on the site, regardless of where they submit data to.
- *
- * A site can have at most one such login, and in case it is present, then it is
- * not possible to store separate logins for forms on the same site that submit
- * data to different sites.
- *
- * The only way to have such condition is to be using logins that were initially
- * saved by a very old version of the browser, or because of data manually added
- * by an extension in an old version.
- */
-
-"use strict";
-
-// Tests
-
-/**
- * Adds a login with an empty formSubmitURL, then it verifies that no other
- * form logins can be added for the same host.
- */
-add_task(function test_addLogin_wildcard()
-{
- let loginInfo = TestData.formLogin({ hostname: "http://any.example.com",
- formSubmitURL: "" });
- Services.logins.addLogin(loginInfo);
-
- // Normal form logins cannot be added anymore.
- loginInfo = TestData.formLogin({ hostname: "http://any.example.com" });
- Assert.throws(() => Services.logins.addLogin(loginInfo), /already exists/);
-
- // Authentication logins can still be added.
- loginInfo = TestData.authLogin({ hostname: "http://any.example.com" });
- Services.logins.addLogin(loginInfo);
-
- // Form logins can be added for other hosts.
- loginInfo = TestData.formLogin({ hostname: "http://other.example.com" });
- Services.logins.addLogin(loginInfo);
-});
-
-/**
- * Verifies that findLogins, searchLogins, and countLogins include all logins
- * that have an empty formSubmitURL in the store, even when a formSubmitURL is
- * specified.
- */
-add_task(function test_search_all_wildcard()
-{
- // Search a given formSubmitURL on any host.
- let matchData = newPropertyBag({ formSubmitURL: "http://www.example.com" });
- do_check_eq(Services.logins.searchLogins({}, matchData).length, 2);
-
- do_check_eq(Services.logins.findLogins({}, "", "http://www.example.com",
- null).length, 2);
-
- do_check_eq(Services.logins.countLogins("", "http://www.example.com",
- null), 2);
-
- // Restrict the search to one host.
- matchData.setProperty("hostname", "http://any.example.com");
- do_check_eq(Services.logins.searchLogins({}, matchData).length, 1);
-
- do_check_eq(Services.logins.findLogins({}, "http://any.example.com",
- "http://www.example.com",
- null).length, 1);
-
- do_check_eq(Services.logins.countLogins("http://any.example.com",
- "http://www.example.com",
- null), 1);
-});
-
-/**
- * Verifies that specifying an empty string for formSubmitURL in searchLogins
- * includes only logins that have an empty formSubmitURL in the store.
- */
-add_task(function test_searchLogins_wildcard()
-{
- let logins = Services.logins.searchLogins({},
- newPropertyBag({ formSubmitURL: "" }));
-
- let loginInfo = TestData.formLogin({ hostname: "http://any.example.com",
- formSubmitURL: "" });
- LoginTestUtils.assertLoginListsEqual(logins, [loginInfo]);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_legacy_validation.js b/toolkit/components/passwordmgr/test/unit/test_legacy_validation.js
deleted file mode 100644
index 709bc9818..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_legacy_validation.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the legacy validation made when storing nsILoginInfo or disabled hosts.
- *
- * These rules exist because of limitations of the "signons.txt" storage file,
- * that is not used anymore. They are still enforced by the Login Manager
- * service, despite these values can now be safely stored in the back-end.
- */
-
-"use strict";
-
-// Tests
-
-/**
- * Tests legacy validation with addLogin.
- */
-add_task(function test_addLogin_invalid_characters_legacy()
-{
- // Test newlines and carriage returns in properties that contain URLs.
- for (let testValue of ["http://newline\n.example.com",
- "http://carriagereturn.example.com\r"]) {
- let loginInfo = TestData.formLogin({ hostname: testValue });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /login values can't contain newlines/);
-
- loginInfo = TestData.formLogin({ formSubmitURL: testValue });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /login values can't contain newlines/);
-
- loginInfo = TestData.authLogin({ httpRealm: testValue });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /login values can't contain newlines/);
- }
-
- // Test newlines and carriage returns in form field names.
- for (let testValue of ["newline_field\n", "carriagereturn\r_field"]) {
- let loginInfo = TestData.formLogin({ usernameField: testValue });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /login values can't contain newlines/);
-
- loginInfo = TestData.formLogin({ passwordField: testValue });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /login values can't contain newlines/);
- }
-
- // Test a single dot as the value of usernameField and formSubmitURL.
- let loginInfo = TestData.formLogin({ usernameField: "." });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /login values can't be periods/);
-
- loginInfo = TestData.formLogin({ formSubmitURL: "." });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /login values can't be periods/);
-
- // Test the sequence " (" inside the value of the "hostname" property.
- loginInfo = TestData.formLogin({ hostname: "http://parens (.example.com" });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /bad parens in hostname/);
-});
-
-/**
- * Tests legacy validation with setLoginSavingEnabled.
- */
-add_task(function test_setLoginSavingEnabled_invalid_characters_legacy()
-{
- for (let hostname of ["http://newline\n.example.com",
- "http://carriagereturn.example.com\r",
- "."]) {
- Assert.throws(() => Services.logins.setLoginSavingEnabled(hostname, false),
- /Invalid hostname/);
- }
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_logins_change.js b/toolkit/components/passwordmgr/test/unit/test_logins_change.js
deleted file mode 100644
index 79c6d2f54..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_logins_change.js
+++ /dev/null
@@ -1,384 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests methods that add, remove, and modify logins.
- */
-
-"use strict";
-
-// Globals
-
-/**
- * Verifies that the specified login is considered invalid by addLogin and by
- * modifyLogin with both nsILoginInfo and nsIPropertyBag arguments.
- *
- * This test requires that the login store is empty.
- *
- * @param aLoginInfo
- * nsILoginInfo corresponding to an invalid login.
- * @param aExpectedError
- * This argument is passed to the "Assert.throws" test to determine which
- * error is expected from the modification functions.
- */
-function checkLoginInvalid(aLoginInfo, aExpectedError)
-{
- // Try to add the new login, and verify that no data is stored.
- Assert.throws(() => Services.logins.addLogin(aLoginInfo), aExpectedError);
- LoginTestUtils.checkLogins([]);
-
- // Add a login for the modification tests.
- let testLogin = TestData.formLogin({ hostname: "http://modify.example.com" });
- Services.logins.addLogin(testLogin);
-
- // Try to modify the existing login using nsILoginInfo and nsIPropertyBag.
- Assert.throws(() => Services.logins.modifyLogin(testLogin, aLoginInfo),
- aExpectedError);
- Assert.throws(() => Services.logins.modifyLogin(testLogin, newPropertyBag({
- hostname: aLoginInfo.hostname,
- formSubmitURL: aLoginInfo.formSubmitURL,
- httpRealm: aLoginInfo.httpRealm,
- username: aLoginInfo.username,
- password: aLoginInfo.password,
- usernameField: aLoginInfo.usernameField,
- passwordField: aLoginInfo.passwordField,
- })), aExpectedError);
-
- // Verify that no data was stored by the previous calls.
- LoginTestUtils.checkLogins([testLogin]);
- Services.logins.removeLogin(testLogin);
-}
-
-/**
- * Verifies that two objects are not the same instance
- * but have equal attributes.
- *
- * @param {Object} objectA
- * An object to compare.
- *
- * @param {Object} objectB
- * Another object to compare.
- *
- * @param {string[]} attributes
- * Attributes to compare.
- *
- * @return true if all passed attributes are equal for both objects, false otherwise.
- */
-function compareAttributes(objectA, objectB, attributes) {
- // If it's the same object, we want to return false.
- if (objectA == objectB) {
- return false;
- }
- return attributes.every(attr => objectA[attr] == objectB[attr]);
-}
-
-// Tests
-
-/**
- * Tests that adding logins to the database works.
- */
-add_task(function test_addLogin_removeLogin()
-{
- // Each login from the test data should be valid and added to the list.
- for (let loginInfo of TestData.loginList()) {
- Services.logins.addLogin(loginInfo);
- }
- LoginTestUtils.checkLogins(TestData.loginList());
-
- // Trying to add each login again should result in an error.
- for (let loginInfo of TestData.loginList()) {
- Assert.throws(() => Services.logins.addLogin(loginInfo), /already exists/);
- }
-
- // Removing each login should succeed.
- for (let loginInfo of TestData.loginList()) {
- Services.logins.removeLogin(loginInfo);
- }
-
- LoginTestUtils.checkLogins([]);
-});
-
-/**
- * Tests invalid combinations of httpRealm and formSubmitURL.
- *
- * For an nsILoginInfo to be valid for storage, one of the two properties should
- * be strictly equal to null, and the other must not be null or an empty string.
- *
- * The legacy case of an empty string in formSubmitURL and a null value in
- * httpRealm is also supported for storage at the moment.
- */
-add_task(function test_invalid_httpRealm_formSubmitURL()
-{
- // httpRealm === null, formSubmitURL === null
- checkLoginInvalid(TestData.formLogin({ formSubmitURL: null }),
- /without a httpRealm or formSubmitURL/);
-
- // httpRealm === "", formSubmitURL === null
- checkLoginInvalid(TestData.authLogin({ httpRealm: "" }),
- /without a httpRealm or formSubmitURL/);
-
- // httpRealm === null, formSubmitURL === ""
- // This is not enforced for now.
- // checkLoginInvalid(TestData.formLogin({ formSubmitURL: "" }),
- // /without a httpRealm or formSubmitURL/);
-
- // httpRealm === "", formSubmitURL === ""
- checkLoginInvalid(TestData.formLogin({ formSubmitURL: "", httpRealm: "" }),
- /both a httpRealm and formSubmitURL/);
-
- // !!httpRealm, !!formSubmitURL
- checkLoginInvalid(TestData.formLogin({ httpRealm: "The HTTP Realm" }),
- /both a httpRealm and formSubmitURL/);
-
- // httpRealm === "", !!formSubmitURL
- checkLoginInvalid(TestData.formLogin({ httpRealm: "" }),
- /both a httpRealm and formSubmitURL/);
-
- // !!httpRealm, formSubmitURL === ""
- checkLoginInvalid(TestData.authLogin({ formSubmitURL: "" }),
- /both a httpRealm and formSubmitURL/);
-});
-
-/**
- * Tests null or empty values in required login properties.
- */
-add_task(function test_missing_properties()
-{
- checkLoginInvalid(TestData.formLogin({ hostname: null }),
- /null or empty hostname/);
-
- checkLoginInvalid(TestData.formLogin({ hostname: "" }),
- /null or empty hostname/);
-
- checkLoginInvalid(TestData.formLogin({ username: null }),
- /null username/);
-
- checkLoginInvalid(TestData.formLogin({ password: null }),
- /null or empty password/);
-
- checkLoginInvalid(TestData.formLogin({ password: "" }),
- /null or empty password/);
-});
-
-/**
- * Tests invalid NUL characters in nsILoginInfo properties.
- */
-add_task(function test_invalid_characters()
-{
- let loginList = [
- TestData.authLogin({ hostname: "http://null\0X.example.com" }),
- TestData.authLogin({ httpRealm: "realm\0" }),
- TestData.formLogin({ formSubmitURL: "http://null\0X.example.com" }),
- TestData.formLogin({ usernameField: "field\0_null" }),
- TestData.formLogin({ usernameField: ".\0" }), // Special single dot case
- TestData.formLogin({ passwordField: "field\0_null" }),
- TestData.formLogin({ username: "user\0name" }),
- TestData.formLogin({ password: "pass\0word" }),
- ];
- for (let loginInfo of loginList) {
- checkLoginInvalid(loginInfo, /login values can't contain nulls/);
- }
-});
-
-/**
- * Tests removing a login that does not exists.
- */
-add_task(function test_removeLogin_nonexisting()
-{
- Assert.throws(() => Services.logins.removeLogin(TestData.formLogin()),
- /No matching logins/);
-});
-
-/**
- * Tests removing all logins at once.
- */
-add_task(function test_removeAllLogins()
-{
- for (let loginInfo of TestData.loginList()) {
- Services.logins.addLogin(loginInfo);
- }
- Services.logins.removeAllLogins();
- LoginTestUtils.checkLogins([]);
-
- // The function should also work when there are no logins to delete.
- Services.logins.removeAllLogins();
-});
-
-/**
- * Tests the modifyLogin function with an nsILoginInfo argument.
- */
-add_task(function test_modifyLogin_nsILoginInfo()
-{
- let loginInfo = TestData.formLogin();
- let updatedLoginInfo = TestData.formLogin({
- username: "new username",
- password: "new password",
- usernameField: "new_form_field_username",
- passwordField: "new_form_field_password",
- });
- let differentLoginInfo = TestData.authLogin();
-
- // Trying to modify a login that does not exist should throw.
- Assert.throws(() => Services.logins.modifyLogin(loginInfo, updatedLoginInfo),
- /No matching logins/);
-
- // Add the first form login, then modify it to match the second.
- Services.logins.addLogin(loginInfo);
- Services.logins.modifyLogin(loginInfo, updatedLoginInfo);
-
- // The data should now match the second login.
- LoginTestUtils.checkLogins([updatedLoginInfo]);
- Assert.throws(() => Services.logins.modifyLogin(loginInfo, updatedLoginInfo),
- /No matching logins/);
-
- // The login can be changed to have a different type and hostname.
- Services.logins.modifyLogin(updatedLoginInfo, differentLoginInfo);
- LoginTestUtils.checkLogins([differentLoginInfo]);
-
- // It is now possible to add a login with the old type and hostname.
- Services.logins.addLogin(loginInfo);
- LoginTestUtils.checkLogins([loginInfo, differentLoginInfo]);
-
- // Modifying a login to match an existing one should not be possible.
- Assert.throws(
- () => Services.logins.modifyLogin(loginInfo, differentLoginInfo),
- /already exists/);
- LoginTestUtils.checkLogins([loginInfo, differentLoginInfo]);
-
- LoginTestUtils.clearData();
-});
-
-/**
- * Tests the modifyLogin function with an nsIPropertyBag argument.
- */
-add_task(function test_modifyLogin_nsIProperyBag()
-{
- let loginInfo = TestData.formLogin();
- let updatedLoginInfo = TestData.formLogin({
- username: "new username",
- password: "new password",
- usernameField: "",
- passwordField: "new_form_field_password",
- });
- let differentLoginInfo = TestData.authLogin();
- let differentLoginProperties = newPropertyBag({
- hostname: differentLoginInfo.hostname,
- formSubmitURL: differentLoginInfo.formSubmitURL,
- httpRealm: differentLoginInfo.httpRealm,
- username: differentLoginInfo.username,
- password: differentLoginInfo.password,
- usernameField: differentLoginInfo.usernameField,
- passwordField: differentLoginInfo.passwordField,
- });
-
- // Trying to modify a login that does not exist should throw.
- Assert.throws(() => Services.logins.modifyLogin(loginInfo, newPropertyBag()),
- /No matching logins/);
-
- // Add the first form login, then modify it to match the second, changing
- // only some of its properties and checking the behavior with an empty string.
- Services.logins.addLogin(loginInfo);
- Services.logins.modifyLogin(loginInfo, newPropertyBag({
- username: "new username",
- password: "new password",
- usernameField: "",
- passwordField: "new_form_field_password",
- }));
-
- // The data should now match the second login.
- LoginTestUtils.checkLogins([updatedLoginInfo]);
- Assert.throws(() => Services.logins.modifyLogin(loginInfo, newPropertyBag()),
- /No matching logins/);
-
- // It is also possible to provide no properties to be modified.
- Services.logins.modifyLogin(updatedLoginInfo, newPropertyBag());
-
- // Specifying a null property for a required value should throw.
- Assert.throws(() => Services.logins.modifyLogin(loginInfo, newPropertyBag({
- usernameField: null,
- })));
-
- // The login can be changed to have a different type and hostname.
- Services.logins.modifyLogin(updatedLoginInfo, differentLoginProperties);
- LoginTestUtils.checkLogins([differentLoginInfo]);
-
- // It is now possible to add a login with the old type and hostname.
- Services.logins.addLogin(loginInfo);
- LoginTestUtils.checkLogins([loginInfo, differentLoginInfo]);
-
- // Modifying a login to match an existing one should not be possible.
- Assert.throws(
- () => Services.logins.modifyLogin(loginInfo, differentLoginProperties),
- /already exists/);
- LoginTestUtils.checkLogins([loginInfo, differentLoginInfo]);
-
- LoginTestUtils.clearData();
-});
-
-/**
- * Tests the login deduplication function.
- */
-add_task(function test_deduplicate_logins() {
- // Different key attributes combinations and the amount of unique
- // results expected for the TestData login list.
- let keyCombinations = [
- {
- keyset: ["username", "password"],
- results: 13,
- },
- {
- keyset: ["hostname", "username"],
- results: 17,
- },
- {
- keyset: ["hostname", "username", "password"],
- results: 18,
- },
- {
- keyset: ["hostname", "username", "password", "formSubmitURL"],
- results: 23,
- },
- ];
-
- let logins = TestData.loginList();
-
- for (let testCase of keyCombinations) {
- // Deduplicate the logins using the current testcase keyset.
- let deduped = LoginHelper.dedupeLogins(logins, testCase.keyset);
- Assert.equal(deduped.length, testCase.results, "Correct amount of results.");
-
- // Checks that every login after deduping is unique.
- Assert.ok(deduped.every(loginA =>
- deduped.every(loginB => !compareAttributes(loginA, loginB, testCase.keyset))
- ), "Every login is unique.");
- }
-});
-
-/**
- * Ensure that the login deduplication function keeps the most recent login.
- */
-add_task(function test_deduplicate_keeps_most_recent() {
- // Logins to deduplicate.
- let logins = [
- TestData.formLogin({timeLastUsed: Date.UTC(2004, 11, 4, 0, 0, 0)}),
- TestData.formLogin({formSubmitURL: "http://example.com", timeLastUsed: Date.UTC(2015, 11, 4, 0, 0, 0)}),
- ];
-
- // Deduplicate the logins.
- let deduped = LoginHelper.dedupeLogins(logins);
- Assert.equal(deduped.length, 1, "Deduplicated the logins array.");
-
- // Verify that the remaining login have the most recent date.
- let loginTimeLastUsed = deduped[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
- Assert.equal(loginTimeLastUsed, Date.UTC(2015, 11, 4, 0, 0, 0), "Most recent login was kept.");
-
- // Deduplicate the reverse logins array.
- deduped = LoginHelper.dedupeLogins(logins.reverse());
- Assert.equal(deduped.length, 1, "Deduplicated the reversed logins array.");
-
- // Verify that the remaining login have the most recent date.
- loginTimeLastUsed = deduped[0].QueryInterface(Ci.nsILoginMetaInfo).timeLastUsed;
- Assert.equal(loginTimeLastUsed, Date.UTC(2015, 11, 4, 0, 0, 0), "Most recent login was kept.");
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_logins_decrypt_failure.js b/toolkit/components/passwordmgr/test/unit/test_logins_decrypt_failure.js
deleted file mode 100644
index ffbedb4de..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_logins_decrypt_failure.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the case where there are logins that cannot be decrypted.
- */
-
-"use strict";
-
-// Globals
-
-/**
- * Resets the token used to decrypt logins. This is equivalent to resetting the
- * master password when it is not known.
- */
-function resetMasterPassword()
-{
- let token = Cc["@mozilla.org/security/pk11tokendb;1"]
- .getService(Ci.nsIPK11TokenDB).getInternalKeyToken();
- token.reset();
- token.changePassword("", "");
-}
-
-// Tests
-
-/**
- * Resets the master password after some logins were added to the database.
- */
-add_task(function test_logins_decrypt_failure()
-{
- let logins = TestData.loginList();
- for (let loginInfo of logins) {
- Services.logins.addLogin(loginInfo);
- }
-
- // This makes the existing logins non-decryptable.
- resetMasterPassword();
-
- // These functions don't see the non-decryptable entries anymore.
- do_check_eq(Services.logins.getAllLogins().length, 0);
- do_check_eq(Services.logins.findLogins({}, "", "", "").length, 0);
- do_check_eq(Services.logins.searchLogins({}, newPropertyBag()).length, 0);
- Assert.throws(() => Services.logins.modifyLogin(logins[0], newPropertyBag()),
- /No matching logins/);
- Assert.throws(() => Services.logins.removeLogin(logins[0]),
- /No matching logins/);
-
- // The function that counts logins sees the non-decryptable entries also.
- do_check_eq(Services.logins.countLogins("", "", ""), logins.length);
-
- // Equivalent logins can be added.
- for (let loginInfo of logins) {
- Services.logins.addLogin(loginInfo);
- }
- LoginTestUtils.checkLogins(logins);
- do_check_eq(Services.logins.countLogins("", "", ""), logins.length * 2);
-
- // Finding logins doesn't return the non-decryptable duplicates.
- do_check_eq(Services.logins.findLogins({}, "http://www.example.com",
- "", "").length, 1);
- let matchData = newPropertyBag({ hostname: "http://www.example.com" });
- do_check_eq(Services.logins.searchLogins({}, matchData).length, 1);
-
- // Removing single logins does not remove non-decryptable logins.
- for (let loginInfo of TestData.loginList()) {
- Services.logins.removeLogin(loginInfo);
- }
- do_check_eq(Services.logins.getAllLogins().length, 0);
- do_check_eq(Services.logins.countLogins("", "", ""), logins.length);
-
- // Removing all logins removes the non-decryptable entries also.
- Services.logins.removeAllLogins();
- do_check_eq(Services.logins.getAllLogins().length, 0);
- do_check_eq(Services.logins.countLogins("", "", ""), 0);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_logins_metainfo.js b/toolkit/components/passwordmgr/test/unit/test_logins_metainfo.js
deleted file mode 100644
index 38344aa7d..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_logins_metainfo.js
+++ /dev/null
@@ -1,284 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the handling of nsILoginMetaInfo by methods that add, remove, modify,
- * and find logins.
- */
-
-"use strict";
-
-// Globals
-
-XPCOMUtils.defineLazyServiceGetter(this, "gUUIDGenerator",
- "@mozilla.org/uuid-generator;1",
- "nsIUUIDGenerator");
-
-var gLooksLikeUUIDRegex = /^\{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}\}$/;
-
-/**
- * Retrieves the only login among the current data that matches the hostname of
- * the given nsILoginInfo. In case there is more than one login for the
- * hostname, the test fails.
- */
-function retrieveLoginMatching(aLoginInfo)
-{
- let logins = Services.logins.findLogins({}, aLoginInfo.hostname, "", "");
- do_check_eq(logins.length, 1);
- return logins[0].QueryInterface(Ci.nsILoginMetaInfo);
-}
-
-/**
- * Checks that the nsILoginInfo and nsILoginMetaInfo properties of two different
- * login instances are equal.
- */
-function assertMetaInfoEqual(aActual, aExpected)
-{
- do_check_neq(aActual, aExpected);
-
- // Check the nsILoginInfo properties.
- do_check_true(aActual.equals(aExpected));
-
- // Check the nsILoginMetaInfo properties.
- do_check_eq(aActual.guid, aExpected.guid);
- do_check_eq(aActual.timeCreated, aExpected.timeCreated);
- do_check_eq(aActual.timeLastUsed, aExpected.timeLastUsed);
- do_check_eq(aActual.timePasswordChanged, aExpected.timePasswordChanged);
- do_check_eq(aActual.timesUsed, aExpected.timesUsed);
-}
-
-/**
- * nsILoginInfo instances with or without nsILoginMetaInfo properties.
- */
-var gLoginInfo1;
-var gLoginInfo2;
-var gLoginInfo3;
-
-/**
- * nsILoginInfo instances reloaded with all the nsILoginMetaInfo properties.
- * These are often used to provide the reference values to test against.
- */
-var gLoginMetaInfo1;
-var gLoginMetaInfo2;
-var gLoginMetaInfo3;
-
-// Tests
-
-/**
- * Prepare the test objects that will be used by the following tests.
- */
-add_task(function test_initialize()
-{
- // Use a reference time from ten minutes ago to initialize one instance of
- // nsILoginMetaInfo, to test that reference times are updated when needed.
- let baseTimeMs = Date.now() - 600000;
-
- gLoginInfo1 = TestData.formLogin();
- gLoginInfo2 = TestData.formLogin({
- hostname: "http://other.example.com",
- guid: gUUIDGenerator.generateUUID().toString(),
- timeCreated: baseTimeMs,
- timeLastUsed: baseTimeMs + 2,
- timePasswordChanged: baseTimeMs + 1,
- timesUsed: 2,
- });
- gLoginInfo3 = TestData.authLogin();
-});
-
-/**
- * Tests the behavior of addLogin with regard to metadata. The logins added
- * here are also used by the following tests.
- */
-add_task(function test_addLogin_metainfo()
-{
- // Add a login without metadata to the database.
- Services.logins.addLogin(gLoginInfo1);
-
- // The object provided to addLogin should not have been modified.
- do_check_eq(gLoginInfo1.guid, null);
- do_check_eq(gLoginInfo1.timeCreated, 0);
- do_check_eq(gLoginInfo1.timeLastUsed, 0);
- do_check_eq(gLoginInfo1.timePasswordChanged, 0);
- do_check_eq(gLoginInfo1.timesUsed, 0);
-
- // A login with valid metadata should have been stored.
- gLoginMetaInfo1 = retrieveLoginMatching(gLoginInfo1);
- do_check_true(gLooksLikeUUIDRegex.test(gLoginMetaInfo1.guid));
- let creationTime = gLoginMetaInfo1.timeCreated;
- LoginTestUtils.assertTimeIsAboutNow(creationTime);
- do_check_eq(gLoginMetaInfo1.timeLastUsed, creationTime);
- do_check_eq(gLoginMetaInfo1.timePasswordChanged, creationTime);
- do_check_eq(gLoginMetaInfo1.timesUsed, 1);
-
- // Add a login without metadata to the database.
- let originalLogin = gLoginInfo2.clone().QueryInterface(Ci.nsILoginMetaInfo);
- Services.logins.addLogin(gLoginInfo2);
-
- // The object provided to addLogin should not have been modified.
- assertMetaInfoEqual(gLoginInfo2, originalLogin);
-
- // A login with the provided metadata should have been stored.
- gLoginMetaInfo2 = retrieveLoginMatching(gLoginInfo2);
- assertMetaInfoEqual(gLoginMetaInfo2, gLoginInfo2);
-
- // Add an authentication login to the database before continuing.
- Services.logins.addLogin(gLoginInfo3);
- gLoginMetaInfo3 = retrieveLoginMatching(gLoginInfo3);
- LoginTestUtils.checkLogins([gLoginInfo1, gLoginInfo2, gLoginInfo3]);
-});
-
-/**
- * Tests that adding a login with a duplicate GUID throws an exception.
- */
-add_task(function test_addLogin_metainfo_duplicate()
-{
- let loginInfo = TestData.formLogin({
- hostname: "http://duplicate.example.com",
- guid: gLoginMetaInfo2.guid,
- });
- Assert.throws(() => Services.logins.addLogin(loginInfo),
- /specified GUID already exists/);
-
- // Verify that no data was stored by the previous call.
- LoginTestUtils.checkLogins([gLoginInfo1, gLoginInfo2, gLoginInfo3]);
-});
-
-/**
- * Tests that the existing metadata is not changed when modifyLogin is called
- * with an nsILoginInfo argument.
- */
-add_task(function test_modifyLogin_nsILoginInfo_metainfo_ignored()
-{
- let newLoginInfo = gLoginInfo1.clone().QueryInterface(Ci.nsILoginMetaInfo);
- newLoginInfo.guid = gUUIDGenerator.generateUUID().toString();
- newLoginInfo.timeCreated = Date.now();
- newLoginInfo.timeLastUsed = Date.now();
- newLoginInfo.timePasswordChanged = Date.now();
- newLoginInfo.timesUsed = 12;
- Services.logins.modifyLogin(gLoginInfo1, newLoginInfo);
-
- newLoginInfo = retrieveLoginMatching(gLoginInfo1);
- assertMetaInfoEqual(newLoginInfo, gLoginMetaInfo1);
-});
-
-/**
- * Tests the modifyLogin function with an nsIProperyBag argument.
- */
-add_task(function test_modifyLogin_nsIProperyBag_metainfo()
-{
- // Use a new reference time that is two minutes from now.
- let newTimeMs = Date.now() + 120000;
- let newUUIDValue = gUUIDGenerator.generateUUID().toString();
-
- // Check that properties are changed as requested.
- Services.logins.modifyLogin(gLoginInfo1, newPropertyBag({
- guid: newUUIDValue,
- timeCreated: newTimeMs,
- timeLastUsed: newTimeMs + 2,
- timePasswordChanged: newTimeMs + 1,
- timesUsed: 2,
- }));
-
- gLoginMetaInfo1 = retrieveLoginMatching(gLoginInfo1);
- do_check_eq(gLoginMetaInfo1.guid, newUUIDValue);
- do_check_eq(gLoginMetaInfo1.timeCreated, newTimeMs);
- do_check_eq(gLoginMetaInfo1.timeLastUsed, newTimeMs + 2);
- do_check_eq(gLoginMetaInfo1.timePasswordChanged, newTimeMs + 1);
- do_check_eq(gLoginMetaInfo1.timesUsed, 2);
-
- // Check that timePasswordChanged is updated when changing the password.
- let originalLogin = gLoginInfo2.clone().QueryInterface(Ci.nsILoginMetaInfo);
- Services.logins.modifyLogin(gLoginInfo2, newPropertyBag({
- password: "new password",
- }));
- gLoginInfo2.password = "new password";
-
- gLoginMetaInfo2 = retrieveLoginMatching(gLoginInfo2);
- do_check_eq(gLoginMetaInfo2.password, gLoginInfo2.password);
- do_check_eq(gLoginMetaInfo2.timeCreated, originalLogin.timeCreated);
- do_check_eq(gLoginMetaInfo2.timeLastUsed, originalLogin.timeLastUsed);
- LoginTestUtils.assertTimeIsAboutNow(gLoginMetaInfo2.timePasswordChanged);
-
- // Check that timePasswordChanged is not set to the current time when changing
- // the password and specifying a new value for the property at the same time.
- Services.logins.modifyLogin(gLoginInfo2, newPropertyBag({
- password: "other password",
- timePasswordChanged: newTimeMs,
- }));
- gLoginInfo2.password = "other password";
-
- gLoginMetaInfo2 = retrieveLoginMatching(gLoginInfo2);
- do_check_eq(gLoginMetaInfo2.password, gLoginInfo2.password);
- do_check_eq(gLoginMetaInfo2.timeCreated, originalLogin.timeCreated);
- do_check_eq(gLoginMetaInfo2.timeLastUsed, originalLogin.timeLastUsed);
- do_check_eq(gLoginMetaInfo2.timePasswordChanged, newTimeMs);
-
- // Check the special timesUsedIncrement property.
- Services.logins.modifyLogin(gLoginInfo2, newPropertyBag({
- timesUsedIncrement: 2,
- }));
-
- gLoginMetaInfo2 = retrieveLoginMatching(gLoginInfo2);
- do_check_eq(gLoginMetaInfo2.timeCreated, originalLogin.timeCreated);
- do_check_eq(gLoginMetaInfo2.timeLastUsed, originalLogin.timeLastUsed);
- do_check_eq(gLoginMetaInfo2.timePasswordChanged, newTimeMs);
- do_check_eq(gLoginMetaInfo2.timesUsed, 4);
-});
-
-/**
- * Tests that modifying a login to a duplicate GUID throws an exception.
- */
-add_task(function test_modifyLogin_nsIProperyBag_metainfo_duplicate()
-{
- Assert.throws(() => Services.logins.modifyLogin(gLoginInfo1, newPropertyBag({
- guid: gLoginInfo2.guid,
- })), /specified GUID already exists/);
- LoginTestUtils.checkLogins([gLoginInfo1, gLoginInfo2, gLoginInfo3]);
-});
-
-/**
- * Tests searching logins using nsILoginMetaInfo properties.
- */
-add_task(function test_searchLogins_metainfo()
-{
- // Find by GUID.
- let logins = Services.logins.searchLogins({}, newPropertyBag({
- guid: gLoginMetaInfo1.guid,
- }));
- do_check_eq(logins.length, 1);
- let foundLogin = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- assertMetaInfoEqual(foundLogin, gLoginMetaInfo1);
-
- // Find by timestamp.
- logins = Services.logins.searchLogins({}, newPropertyBag({
- timePasswordChanged: gLoginMetaInfo2.timePasswordChanged,
- }));
- do_check_eq(logins.length, 1);
- foundLogin = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- assertMetaInfoEqual(foundLogin, gLoginMetaInfo2);
-
- // Find using two properties at the same time.
- logins = Services.logins.searchLogins({}, newPropertyBag({
- guid: gLoginMetaInfo3.guid,
- timePasswordChanged: gLoginMetaInfo3.timePasswordChanged,
- }));
- do_check_eq(logins.length, 1);
- foundLogin = logins[0].QueryInterface(Ci.nsILoginMetaInfo);
- assertMetaInfoEqual(foundLogin, gLoginMetaInfo3);
-});
-
-/**
- * Tests that the default nsILoginManagerStorage module attached to the Login
- * Manager service is able to save and reload nsILoginMetaInfo properties.
- */
-add_task(function* test_storage_metainfo()
-{
- yield* LoginTestUtils.reloadData();
- LoginTestUtils.checkLogins([gLoginInfo1, gLoginInfo2, gLoginInfo3]);
-
- assertMetaInfoEqual(retrieveLoginMatching(gLoginInfo1), gLoginMetaInfo1);
- assertMetaInfoEqual(retrieveLoginMatching(gLoginInfo2), gLoginMetaInfo2);
- assertMetaInfoEqual(retrieveLoginMatching(gLoginInfo3), gLoginMetaInfo3);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_logins_search.js b/toolkit/components/passwordmgr/test/unit/test_logins_search.js
deleted file mode 100644
index 730771981..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_logins_search.js
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Tests methods that find specific logins in the store (findLogins,
- * searchLogins, and countLogins).
- *
- * The getAllLogins method is not tested explicitly here, because it is used by
- * all tests to verify additions, removals and modifications to the login store.
- */
-
-"use strict";
-
-// Globals
-
-/**
- * Returns a list of new nsILoginInfo objects that are a subset of the test
- * data, built to match the specified query.
- *
- * @param aQuery
- * Each property and value of this object restricts the search to those
- * entries from the test data that match the property exactly.
- */
-function buildExpectedLogins(aQuery)
-{
- return TestData.loginList().filter(
- entry => Object.keys(aQuery).every(name => entry[name] === aQuery[name]));
-}
-
-/**
- * Tests the searchLogins function.
- *
- * @param aQuery
- * Each property and value of this object is translated to an entry in
- * the nsIPropertyBag parameter of searchLogins.
- * @param aExpectedCount
- * Number of logins from the test data that should be found. The actual
- * list of logins is obtained using the buildExpectedLogins helper, and
- * this value is just used to verify that modifications to the test data
- * don't make the current test meaningless.
- */
-function checkSearchLogins(aQuery, aExpectedCount)
-{
- do_print("Testing searchLogins for " + JSON.stringify(aQuery));
-
- let expectedLogins = buildExpectedLogins(aQuery);
- do_check_eq(expectedLogins.length, aExpectedCount);
-
- let outCount = {};
- let logins = Services.logins.searchLogins(outCount, newPropertyBag(aQuery));
- do_check_eq(outCount.value, expectedLogins.length);
- LoginTestUtils.assertLoginListsEqual(logins, expectedLogins);
-}
-
-/**
- * Tests findLogins, searchLogins, and countLogins with the same query.
- *
- * @param aQuery
- * The "hostname", "formSubmitURL", and "httpRealm" properties of this
- * object are passed as parameters to findLogins and countLogins. The
- * same object is then passed to the checkSearchLogins function.
- * @param aExpectedCount
- * Number of logins from the test data that should be found. The actual
- * list of logins is obtained using the buildExpectedLogins helper, and
- * this value is just used to verify that modifications to the test data
- * don't make the current test meaningless.
- */
-function checkAllSearches(aQuery, aExpectedCount)
-{
- do_print("Testing all search functions for " + JSON.stringify(aQuery));
-
- let expectedLogins = buildExpectedLogins(aQuery);
- do_check_eq(expectedLogins.length, aExpectedCount);
-
- // The findLogins and countLogins functions support wildcard matches by
- // specifying empty strings as parameters, while searchLogins requires
- // omitting the property entirely.
- let hostname = ("hostname" in aQuery) ? aQuery.hostname : "";
- let formSubmitURL = ("formSubmitURL" in aQuery) ? aQuery.formSubmitURL : "";
- let httpRealm = ("httpRealm" in aQuery) ? aQuery.httpRealm : "";
-
- // Test findLogins.
- let outCount = {};
- let logins = Services.logins.findLogins(outCount, hostname, formSubmitURL,
- httpRealm);
- do_check_eq(outCount.value, expectedLogins.length);
- LoginTestUtils.assertLoginListsEqual(logins, expectedLogins);
-
- // Test countLogins.
- let count = Services.logins.countLogins(hostname, formSubmitURL, httpRealm);
- do_check_eq(count, expectedLogins.length);
-
- // Test searchLogins.
- checkSearchLogins(aQuery, aExpectedCount);
-}
-
-// Tests
-
-/**
- * Prepare data for the following tests.
- */
-add_task(function test_initialize()
-{
- for (let login of TestData.loginList()) {
- Services.logins.addLogin(login);
- }
-});
-
-/**
- * Tests findLogins, searchLogins, and countLogins with basic queries.
- */
-add_task(function test_search_all_basic()
-{
- // Find all logins, using no filters in the search functions.
- checkAllSearches({}, 23);
-
- // Find all form logins, then all authentication logins.
- checkAllSearches({ httpRealm: null }, 14);
- checkAllSearches({ formSubmitURL: null }, 9);
-
- // Find all form logins on one host, then all authentication logins.
- checkAllSearches({ hostname: "http://www4.example.com",
- httpRealm: null }, 3);
- checkAllSearches({ hostname: "http://www2.example.org",
- formSubmitURL: null }, 2);
-
- // Verify that scheme and subdomain are distinct in the hostname.
- checkAllSearches({ hostname: "http://www.example.com" }, 1);
- checkAllSearches({ hostname: "https://www.example.com" }, 1);
- checkAllSearches({ hostname: "https://example.com" }, 1);
- checkAllSearches({ hostname: "http://www3.example.com" }, 3);
-
- // Verify that scheme and subdomain are distinct in formSubmitURL.
- checkAllSearches({ formSubmitURL: "http://www.example.com" }, 2);
- checkAllSearches({ formSubmitURL: "https://www.example.com" }, 2);
- checkAllSearches({ formSubmitURL: "http://example.com" }, 1);
-
- // Find by formSubmitURL on a single host.
- checkAllSearches({ hostname: "http://www3.example.com",
- formSubmitURL: "http://www.example.com" }, 1);
- checkAllSearches({ hostname: "http://www3.example.com",
- formSubmitURL: "https://www.example.com" }, 1);
- checkAllSearches({ hostname: "http://www3.example.com",
- formSubmitURL: "http://example.com" }, 1);
-
- // Find by httpRealm on all hosts.
- checkAllSearches({ httpRealm: "The HTTP Realm" }, 3);
- checkAllSearches({ httpRealm: "ftp://ftp.example.org" }, 1);
- checkAllSearches({ httpRealm: "The HTTP Realm Other" }, 2);
-
- // Find by httpRealm on a single host.
- checkAllSearches({ hostname: "http://example.net",
- httpRealm: "The HTTP Realm" }, 1);
- checkAllSearches({ hostname: "http://example.net",
- httpRealm: "The HTTP Realm Other" }, 1);
- checkAllSearches({ hostname: "ftp://example.net",
- httpRealm: "ftp://example.net" }, 1);
-});
-
-/**
- * Tests searchLogins with advanced queries.
- */
-add_task(function test_searchLogins()
-{
- checkSearchLogins({ usernameField: "form_field_username" }, 12);
- checkSearchLogins({ passwordField: "form_field_password" }, 13);
-
- // Find all logins with an empty usernameField, including for authentication.
- checkSearchLogins({ usernameField: "" }, 11);
-
- // Find form logins with an empty usernameField.
- checkSearchLogins({ httpRealm: null,
- usernameField: "" }, 2);
-
- // Find logins with an empty usernameField on one host.
- checkSearchLogins({ hostname: "http://www6.example.com",
- usernameField: "" }, 1);
-});
-
-/**
- * Tests searchLogins with invalid arguments.
- */
-add_task(function test_searchLogins_invalid()
-{
- Assert.throws(() => Services.logins.searchLogins({},
- newPropertyBag({ username: "value" })),
- /Unexpected field/);
-});
-
-/**
- * Tests that matches are case-sensitive, compare the full field value, and are
- * strict when interpreting the prePath of URIs.
- */
-add_task(function test_search_all_full_case_sensitive()
-{
- checkAllSearches({ hostname: "http://www.example.com" }, 1);
- checkAllSearches({ hostname: "http://www.example.com/" }, 0);
- checkAllSearches({ hostname: "example.com" }, 0);
-
- checkAllSearches({ formSubmitURL: "http://www.example.com" }, 2);
- checkAllSearches({ formSubmitURL: "http://www.example.com/" }, 0);
- checkAllSearches({ formSubmitURL: "http://" }, 0);
- checkAllSearches({ formSubmitURL: "example.com" }, 0);
-
- checkAllSearches({ httpRealm: "The HTTP Realm" }, 3);
- checkAllSearches({ httpRealm: "The http Realm" }, 0);
- checkAllSearches({ httpRealm: "The HTTP" }, 0);
- checkAllSearches({ httpRealm: "Realm" }, 0);
-});
-
-/**
- * Tests findLogins, searchLogins, and countLogins with queries that should
- * return no values.
- */
-add_task(function test_search_all_empty()
-{
- checkAllSearches({ hostname: "http://nonexistent.example.com" }, 0);
- checkAllSearches({ formSubmitURL: "http://www.example.com",
- httpRealm: "The HTTP Realm" }, 0);
-
- checkSearchLogins({ hostname: "" }, 0);
- checkSearchLogins({ id: "1000" }, 0);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_maybeImportLogin.js b/toolkit/components/passwordmgr/test/unit/test_maybeImportLogin.js
deleted file mode 100644
index 19175df59..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_maybeImportLogin.js
+++ /dev/null
@@ -1,169 +0,0 @@
-"use strict";
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/LoginHelper.jsm");
-
-const HOST1 = "https://www.example.com/";
-const HOST2 = "https://www.mozilla.org/";
-
-const USER1 = "myuser";
-const USER2 = "anotheruser";
-
-const PASS1 = "mypass";
-const PASS2 = "anotherpass";
-const PASS3 = "yetanotherpass";
-
-add_task(function test_new_logins() {
- let importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- formSubmitURL: HOST1,
- });
- Assert.ok(importedLogin, "Return value should indicate imported login.");
- let matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should be 1 login for ${HOST1}`);
-
- importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST2,
- formSubmitURL: HOST2,
- });
-
- Assert.ok(importedLogin, "Return value should indicate another imported login.");
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should still be 1 login for ${HOST1}`);
-
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST2});
- Assert.equal(matchingLogins.length, 1, `There should also be 1 login for ${HOST2}`);
- Assert.equal(Services.logins.getAllLogins().length, 2, "There should be 2 logins in total");
- Services.logins.removeAllLogins();
-});
-
-add_task(function test_duplicate_logins() {
- let importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- formSubmitURL: HOST1,
- });
- Assert.ok(importedLogin, "Return value should indicate imported login.");
- let matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should be 1 login for ${HOST1}`);
-
- importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- formSubmitURL: HOST1,
- });
- Assert.ok(!importedLogin, "Return value should indicate no new login was imported.");
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should still be 1 login for ${HOST1}`);
- Services.logins.removeAllLogins();
-});
-
-add_task(function test_different_passwords() {
- let importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- formSubmitURL: HOST1,
- timeCreated: new Date(Date.now() - 1000),
- });
- Assert.ok(importedLogin, "Return value should indicate imported login.");
- let matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should be 1 login for ${HOST1}`);
-
- // This item will be newer, so its password should take precedence.
- importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS2,
- hostname: HOST1,
- formSubmitURL: HOST1,
- timeCreated: new Date(),
- });
- Assert.ok(!importedLogin, "Return value should not indicate imported login (as we updated an existing one).");
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should still be 1 login for ${HOST1}`);
- Assert.equal(matchingLogins[0].password, PASS2, "We should have updated the password for this login.");
-
- // Now try to update with an older password:
- importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS3,
- hostname: HOST1,
- formSubmitURL: HOST1,
- timeCreated: new Date(Date.now() - 1000000),
- });
- Assert.ok(!importedLogin, "Return value should not indicate imported login (as we didn't update anything).");
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should still be 1 login for ${HOST1}`);
- Assert.equal(matchingLogins[0].password, PASS2, "We should NOT have updated the password for this login.");
-
- Services.logins.removeAllLogins();
-});
-
-add_task(function test_different_usernames() {
- let importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- formSubmitURL: HOST1,
- });
- Assert.ok(importedLogin, "Return value should indicate imported login.");
- let matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should be 1 login for ${HOST1}`);
-
- importedLogin = LoginHelper.maybeImportLogin({
- username: USER2,
- password: PASS1,
- hostname: HOST1,
- formSubmitURL: HOST1,
- });
- Assert.ok(importedLogin, "Return value should indicate another imported login.");
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 2, `There should now be 2 logins for ${HOST1}`);
-
- Services.logins.removeAllLogins();
-});
-
-add_task(function test_different_targets() {
- let importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- formSubmitURL: HOST1,
- });
- Assert.ok(importedLogin, "Return value should indicate imported login.");
- let matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should be 1 login for ${HOST1}`);
-
- // Not passing either a formSubmitURL or a httpRealm should be treated as
- // the same as the previous login
- importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- });
- Assert.ok(!importedLogin, "Return value should NOT indicate imported login " +
- "(because a missing formSubmitURL and httpRealm should be duped to the existing login).");
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 1, `There should still be 1 login for ${HOST1}`);
- Assert.equal(matchingLogins[0].formSubmitURL, HOST1, "The form submission URL should have been kept.");
-
- importedLogin = LoginHelper.maybeImportLogin({
- username: USER1,
- password: PASS1,
- hostname: HOST1,
- httpRealm: HOST1,
- });
- Assert.ok(importedLogin, "Return value should indicate another imported login " +
- "as an httpRealm login shouldn't be duped.");
- matchingLogins = LoginHelper.searchLoginsWithObject({hostname: HOST1});
- Assert.equal(matchingLogins.length, 2, `There should now be 2 logins for ${HOST1}`);
-
- Services.logins.removeAllLogins();
-});
-
diff --git a/toolkit/components/passwordmgr/test/unit/test_module_LoginImport.js b/toolkit/components/passwordmgr/test/unit/test_module_LoginImport.js
deleted file mode 100644
index b8793e1bd..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_module_LoginImport.js
+++ /dev/null
@@ -1,243 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the LoginImport object.
- */
-
-"use strict";
-
-// Globals
-
-Cu.import("resource://gre/modules/Task.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper",
- "resource://gre/modules/LoginHelper.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "LoginImport",
- "resource://gre/modules/LoginImport.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "LoginStore",
- "resource://gre/modules/LoginStore.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Sqlite",
- "resource://gre/modules/Sqlite.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gLoginManagerCrypto",
- "@mozilla.org/login-manager/crypto/SDR;1",
- "nsILoginManagerCrypto");
-XPCOMUtils.defineLazyServiceGetter(this, "gUUIDGenerator",
- "@mozilla.org/uuid-generator;1",
- "nsIUUIDGenerator");
-
-/**
- * Creates empty login data tables in the given SQLite connection, resembling
- * the most recent schema version (excluding indices).
- */
-function promiseCreateDatabaseSchema(aConnection)
-{
- return Task.spawn(function* () {
- yield aConnection.setSchemaVersion(5);
- yield aConnection.execute("CREATE TABLE moz_logins (" +
- "id INTEGER PRIMARY KEY," +
- "hostname TEXT NOT NULL," +
- "httpRealm TEXT," +
- "formSubmitURL TEXT," +
- "usernameField TEXT NOT NULL," +
- "passwordField TEXT NOT NULL," +
- "encryptedUsername TEXT NOT NULL," +
- "encryptedPassword TEXT NOT NULL," +
- "guid TEXT," +
- "encType INTEGER," +
- "timeCreated INTEGER," +
- "timeLastUsed INTEGER," +
- "timePasswordChanged INTEGER," +
- "timesUsed INTEGER)");
- yield aConnection.execute("CREATE TABLE moz_disabledHosts (" +
- "id INTEGER PRIMARY KEY," +
- "hostname TEXT UNIQUE)");
- yield aConnection.execute("CREATE TABLE moz_deleted_logins (" +
- "id INTEGER PRIMARY KEY," +
- "guid TEXT," +
- "timeDeleted INTEGER)");
- });
-}
-
-/**
- * Inserts a new entry in the database resembling the given nsILoginInfo object.
- */
-function promiseInsertLoginInfo(aConnection, aLoginInfo)
-{
- aLoginInfo.QueryInterface(Ci.nsILoginMetaInfo);
-
- // We can't use the aLoginInfo object directly in the execute statement
- // because the bind code in Sqlite.jsm doesn't allow objects with extra
- // properties beyond those being binded. So we might as well use an array as
- // it is simpler.
- let values = [
- aLoginInfo.hostname,
- aLoginInfo.httpRealm,
- aLoginInfo.formSubmitURL,
- aLoginInfo.usernameField,
- aLoginInfo.passwordField,
- gLoginManagerCrypto.encrypt(aLoginInfo.username),
- gLoginManagerCrypto.encrypt(aLoginInfo.password),
- aLoginInfo.guid,
- aLoginInfo.encType,
- aLoginInfo.timeCreated,
- aLoginInfo.timeLastUsed,
- aLoginInfo.timePasswordChanged,
- aLoginInfo.timesUsed,
- ];
-
- return aConnection.execute("INSERT INTO moz_logins (hostname, " +
- "httpRealm, formSubmitURL, usernameField, " +
- "passwordField, encryptedUsername, " +
- "encryptedPassword, guid, encType, timeCreated, " +
- "timeLastUsed, timePasswordChanged, timesUsed) " +
- "VALUES (?" + ",?".repeat(12) + ")", values);
-}
-
-/**
- * Inserts a new disabled host entry in the database.
- */
-function promiseInsertDisabledHost(aConnection, aHostname)
-{
- return aConnection.execute("INSERT INTO moz_disabledHosts (hostname) " +
- "VALUES (?)", [aHostname]);
-}
-
-// Tests
-
-/**
- * Imports login data from a SQLite file constructed using the test data.
- */
-add_task(function* test_import()
-{
- let store = new LoginStore(getTempFile("test-import.json").path);
- let loginsSqlite = getTempFile("test-logins.sqlite").path;
-
- // Prepare the logins to be imported, including the nsILoginMetaInfo data.
- let loginList = TestData.loginList();
- for (let loginInfo of loginList) {
- loginInfo.QueryInterface(Ci.nsILoginMetaInfo);
- loginInfo.guid = gUUIDGenerator.generateUUID().toString();
- loginInfo.timeCreated = Date.now();
- loginInfo.timeLastUsed = Date.now();
- loginInfo.timePasswordChanged = Date.now();
- loginInfo.timesUsed = 1;
- }
-
- // Create and populate the SQLite database first.
- let connection = yield Sqlite.openConnection({ path: loginsSqlite });
- try {
- yield promiseCreateDatabaseSchema(connection);
- for (let loginInfo of loginList) {
- yield promiseInsertLoginInfo(connection, loginInfo);
- }
- yield promiseInsertDisabledHost(connection, "http://www.example.com");
- yield promiseInsertDisabledHost(connection, "https://www.example.org");
- } finally {
- yield connection.close();
- }
-
- // The "load" method must be called before importing data.
- yield store.load();
- yield new LoginImport(store, loginsSqlite).import();
-
- // Verify that every login in the test data has a matching imported row.
- do_check_eq(loginList.length, store.data.logins.length);
- do_check_true(loginList.every(function (loginInfo) {
- return store.data.logins.some(function (loginDataItem) {
- let username = gLoginManagerCrypto.decrypt(loginDataItem.encryptedUsername);
- let password = gLoginManagerCrypto.decrypt(loginDataItem.encryptedPassword);
- return loginDataItem.hostname == loginInfo.hostname &&
- loginDataItem.httpRealm == loginInfo.httpRealm &&
- loginDataItem.formSubmitURL == loginInfo.formSubmitURL &&
- loginDataItem.usernameField == loginInfo.usernameField &&
- loginDataItem.passwordField == loginInfo.passwordField &&
- username == loginInfo.username &&
- password == loginInfo.password &&
- loginDataItem.guid == loginInfo.guid &&
- loginDataItem.encType == loginInfo.encType &&
- loginDataItem.timeCreated == loginInfo.timeCreated &&
- loginDataItem.timeLastUsed == loginInfo.timeLastUsed &&
- loginDataItem.timePasswordChanged == loginInfo.timePasswordChanged &&
- loginDataItem.timesUsed == loginInfo.timesUsed;
- });
- }));
-
- // Verify that disabled hosts have been imported.
- do_check_eq(store.data.disabledHosts.length, 2);
- do_check_true(store.data.disabledHosts.indexOf("http://www.example.com") != -1);
- do_check_true(store.data.disabledHosts.indexOf("https://www.example.org") != -1);
-});
-
-/**
- * Tests imports of NULL values due to a downgraded database.
- */
-add_task(function* test_import_downgraded()
-{
- let store = new LoginStore(getTempFile("test-import-downgraded.json").path);
- let loginsSqlite = getTempFile("test-logins-downgraded.sqlite").path;
-
- // Create and populate the SQLite database first.
- let connection = yield Sqlite.openConnection({ path: loginsSqlite });
- try {
- yield promiseCreateDatabaseSchema(connection);
- yield connection.setSchemaVersion(3);
- yield promiseInsertLoginInfo(connection, TestData.formLogin({
- guid: gUUIDGenerator.generateUUID().toString(),
- timeCreated: null,
- timeLastUsed: null,
- timePasswordChanged: null,
- timesUsed: 0,
- }));
- } finally {
- yield connection.close();
- }
-
- // The "load" method must be called before importing data.
- yield store.load();
- yield new LoginImport(store, loginsSqlite).import();
-
- // Verify that the missing metadata was generated correctly.
- let loginItem = store.data.logins[0];
- let creationTime = loginItem.timeCreated;
- LoginTestUtils.assertTimeIsAboutNow(creationTime);
- do_check_eq(loginItem.timeLastUsed, creationTime);
- do_check_eq(loginItem.timePasswordChanged, creationTime);
- do_check_eq(loginItem.timesUsed, 1);
-});
-
-/**
- * Verifies that importing from a SQLite file with database version 2 fails.
- */
-add_task(function* test_import_v2()
-{
- let store = new LoginStore(getTempFile("test-import-v2.json").path);
- let loginsSqlite = do_get_file("data/signons-v2.sqlite").path;
-
- // The "load" method must be called before importing data.
- yield store.load();
- try {
- yield new LoginImport(store, loginsSqlite).import();
- do_throw("The operation should have failed.");
- } catch (ex) { }
-});
-
-/**
- * Imports login data from a SQLite file, with database version 3.
- */
-add_task(function* test_import_v3()
-{
- let store = new LoginStore(getTempFile("test-import-v3.json").path);
- let loginsSqlite = do_get_file("data/signons-v3.sqlite").path;
-
- // The "load" method must be called before importing data.
- yield store.load();
- yield new LoginImport(store, loginsSqlite).import();
-
- // We only execute basic integrity checks.
- do_check_eq(store.data.logins[0].usernameField, "u1");
- do_check_eq(store.data.disabledHosts.length, 0);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_module_LoginStore.js b/toolkit/components/passwordmgr/test/unit/test_module_LoginStore.js
deleted file mode 100644
index 335eb601b..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_module_LoginStore.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the LoginStore object.
- */
-
-"use strict";
-
-// Globals
-
-XPCOMUtils.defineLazyModuleGetter(this, "LoginStore",
- "resource://gre/modules/LoginStore.jsm");
-
-const TEST_STORE_FILE_NAME = "test-logins.json";
-
-// Tests
-
-/**
- * Saves login data to a file, then reloads it.
- */
-add_task(function* test_save_reload()
-{
- let storeForSave = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);
-
- // The "load" method must be called before preparing the data to be saved.
- yield storeForSave.load();
-
- let rawLoginData = {
- id: storeForSave.data.nextId++,
- hostname: "http://www.example.com",
- httpRealm: null,
- formSubmitURL: "http://www.example.com/submit-url",
- usernameField: "field_" + String.fromCharCode(533, 537, 7570, 345),
- passwordField: "field_" + String.fromCharCode(421, 259, 349, 537),
- encryptedUsername: "(test)",
- encryptedPassword: "(test)",
- guid: "(test)",
- encType: Ci.nsILoginManagerCrypto.ENCTYPE_SDR,
- timeCreated: Date.now(),
- timeLastUsed: Date.now(),
- timePasswordChanged: Date.now(),
- timesUsed: 1,
- };
- storeForSave.data.logins.push(rawLoginData);
-
- storeForSave.data.disabledHosts.push("http://www.example.org");
-
- yield storeForSave._save();
-
- // Test the asynchronous initialization path.
- let storeForLoad = new LoginStore(storeForSave.path);
- yield storeForLoad.load();
-
- do_check_eq(storeForLoad.data.logins.length, 1);
- do_check_matches(storeForLoad.data.logins[0], rawLoginData);
- do_check_eq(storeForLoad.data.disabledHosts.length, 1);
- do_check_eq(storeForLoad.data.disabledHosts[0], "http://www.example.org");
-
- // Test the synchronous initialization path.
- storeForLoad = new LoginStore(storeForSave.path);
- storeForLoad.ensureDataReady();
-
- do_check_eq(storeForLoad.data.logins.length, 1);
- do_check_matches(storeForLoad.data.logins[0], rawLoginData);
- do_check_eq(storeForLoad.data.disabledHosts.length, 1);
- do_check_eq(storeForLoad.data.disabledHosts[0], "http://www.example.org");
-});
-
-/**
- * Checks that loading from a missing file results in empty arrays.
- */
-add_task(function* test_load_empty()
-{
- let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);
-
- do_check_false(yield OS.File.exists(store.path));
-
- yield store.load();
-
- do_check_false(yield OS.File.exists(store.path));
-
- do_check_eq(store.data.logins.length, 0);
- do_check_eq(store.data.disabledHosts.length, 0);
-});
-
-/**
- * Checks that saving empty data still overwrites any existing file.
- */
-add_task(function* test_save_empty()
-{
- let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);
-
- yield store.load();
-
- let createdFile = yield OS.File.open(store.path, { create: true });
- yield createdFile.close();
-
- yield store._save();
-
- do_check_true(yield OS.File.exists(store.path));
-});
-
-/**
- * Loads data from a string in a predefined format. The purpose of this test is
- * to verify that the JSON format used in previous versions can be loaded.
- */
-add_task(function* test_load_string_predefined()
-{
- let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);
-
- let string = "{\"logins\":[{" +
- "\"id\":1," +
- "\"hostname\":\"http://www.example.com\"," +
- "\"httpRealm\":null," +
- "\"formSubmitURL\":\"http://www.example.com/submit-url\"," +
- "\"usernameField\":\"usernameField\"," +
- "\"passwordField\":\"passwordField\"," +
- "\"encryptedUsername\":\"(test)\"," +
- "\"encryptedPassword\":\"(test)\"," +
- "\"guid\":\"(test)\"," +
- "\"encType\":1," +
- "\"timeCreated\":1262304000000," +
- "\"timeLastUsed\":1262390400000," +
- "\"timePasswordChanged\":1262476800000," +
- "\"timesUsed\":1}],\"disabledHosts\":[" +
- "\"http://www.example.org\"]}";
-
- yield OS.File.writeAtomic(store.path,
- new TextEncoder().encode(string),
- { tmpPath: store.path + ".tmp" });
-
- yield store.load();
-
- do_check_eq(store.data.logins.length, 1);
- do_check_matches(store.data.logins[0], {
- id: 1,
- hostname: "http://www.example.com",
- httpRealm: null,
- formSubmitURL: "http://www.example.com/submit-url",
- usernameField: "usernameField",
- passwordField: "passwordField",
- encryptedUsername: "(test)",
- encryptedPassword: "(test)",
- guid: "(test)",
- encType: Ci.nsILoginManagerCrypto.ENCTYPE_SDR,
- timeCreated: 1262304000000,
- timeLastUsed: 1262390400000,
- timePasswordChanged: 1262476800000,
- timesUsed: 1,
- });
-
- do_check_eq(store.data.disabledHosts.length, 1);
- do_check_eq(store.data.disabledHosts[0], "http://www.example.org");
-});
-
-/**
- * Loads login data from a malformed JSON string.
- */
-add_task(function* test_load_string_malformed()
-{
- let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);
-
- let string = "{\"logins\":[{\"hostname\":\"http://www.example.com\"," +
- "\"id\":1,";
-
- yield OS.File.writeAtomic(store.path, new TextEncoder().encode(string),
- { tmpPath: store.path + ".tmp" });
-
- yield store.load();
-
- // A backup file should have been created.
- do_check_true(yield OS.File.exists(store.path + ".corrupt"));
- yield OS.File.remove(store.path + ".corrupt");
-
- // The store should be ready to accept new data.
- do_check_eq(store.data.logins.length, 0);
- do_check_eq(store.data.disabledHosts.length, 0);
-});
-
-/**
- * Loads login data from a malformed JSON string, using the synchronous
- * initialization path.
- */
-add_task(function* test_load_string_malformed_sync()
-{
- let store = new LoginStore(getTempFile(TEST_STORE_FILE_NAME).path);
-
- let string = "{\"logins\":[{\"hostname\":\"http://www.example.com\"," +
- "\"id\":1,";
-
- yield OS.File.writeAtomic(store.path, new TextEncoder().encode(string),
- { tmpPath: store.path + ".tmp" });
-
- store.ensureDataReady();
-
- // A backup file should have been created.
- do_check_true(yield OS.File.exists(store.path + ".corrupt"));
- yield OS.File.remove(store.path + ".corrupt");
-
- // The store should be ready to accept new data.
- do_check_eq(store.data.logins.length, 0);
- do_check_eq(store.data.disabledHosts.length, 0);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_notifications.js b/toolkit/components/passwordmgr/test/unit/test_notifications.js
deleted file mode 100644
index 41caa2c1b..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_notifications.js
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Tests notifications dispatched when modifying stored logins.
- */
-
-var expectedNotification;
-var expectedData;
-
-var TestObserver = {
- QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
-
- observe : function (subject, topic, data) {
- do_check_eq(topic, "passwordmgr-storage-changed");
- do_check_eq(data, expectedNotification);
-
- switch (data) {
- case "addLogin":
- do_check_true(subject instanceof Ci.nsILoginInfo);
- do_check_true(subject instanceof Ci.nsILoginMetaInfo);
- do_check_true(expectedData.equals(subject)); // nsILoginInfo.equals()
- break;
- case "modifyLogin":
- do_check_true(subject instanceof Ci.nsIArray);
- do_check_eq(subject.length, 2);
- var oldLogin = subject.queryElementAt(0, Ci.nsILoginInfo);
- var newLogin = subject.queryElementAt(1, Ci.nsILoginInfo);
- do_check_true(expectedData[0].equals(oldLogin)); // nsILoginInfo.equals()
- do_check_true(expectedData[1].equals(newLogin));
- break;
- case "removeLogin":
- do_check_true(subject instanceof Ci.nsILoginInfo);
- do_check_true(subject instanceof Ci.nsILoginMetaInfo);
- do_check_true(expectedData.equals(subject)); // nsILoginInfo.equals()
- break;
- case "removeAllLogins":
- do_check_eq(subject, null);
- break;
- case "hostSavingEnabled":
- case "hostSavingDisabled":
- do_check_true(subject instanceof Ci.nsISupportsString);
- do_check_eq(subject.data, expectedData);
- break;
- default:
- do_throw("Unhandled notification: " + data + " / " + topic);
- }
-
- expectedNotification = null; // ensure a duplicate is flagged as unexpected.
- expectedData = null;
- }
-};
-
-add_task(function test_notifications()
-{
-
-try {
-
-var testnum = 0;
-var testdesc = "Setup of nsLoginInfo test-users";
-
-var testuser1 = new LoginInfo("http://testhost1", "", null,
- "dummydude", "itsasecret", "put_user_here", "put_pw_here");
-
-var testuser2 = new LoginInfo("http://testhost2", "", null,
- "dummydude2", "itsasecret2", "put_user2_here", "put_pw2_here");
-
-Services.obs.addObserver(TestObserver, "passwordmgr-storage-changed", false);
-
-
-/* ========== 1 ========== */
-testnum = 1;
-testdesc = "Initial connection to storage module";
-
-/* ========== 2 ========== */
-testnum++;
-testdesc = "addLogin";
-
-expectedNotification = "addLogin";
-expectedData = testuser1;
-Services.logins.addLogin(testuser1);
-LoginTestUtils.checkLogins([testuser1]);
-do_check_eq(expectedNotification, null); // check that observer got a notification
-
-/* ========== 3 ========== */
-testnum++;
-testdesc = "modifyLogin";
-
-expectedNotification = "modifyLogin";
-expectedData = [testuser1, testuser2];
-Services.logins.modifyLogin(testuser1, testuser2);
-do_check_eq(expectedNotification, null);
-LoginTestUtils.checkLogins([testuser2]);
-
-/* ========== 4 ========== */
-testnum++;
-testdesc = "removeLogin";
-
-expectedNotification = "removeLogin";
-expectedData = testuser2;
-Services.logins.removeLogin(testuser2);
-do_check_eq(expectedNotification, null);
-LoginTestUtils.checkLogins([]);
-
-/* ========== 5 ========== */
-testnum++;
-testdesc = "removeAllLogins";
-
-expectedNotification = "removeAllLogins";
-expectedData = null;
-Services.logins.removeAllLogins();
-do_check_eq(expectedNotification, null);
-LoginTestUtils.checkLogins([]);
-
-/* ========== 6 ========== */
-testnum++;
-testdesc = "removeAllLogins (again)";
-
-expectedNotification = "removeAllLogins";
-expectedData = null;
-Services.logins.removeAllLogins();
-do_check_eq(expectedNotification, null);
-LoginTestUtils.checkLogins([]);
-
-/* ========== 7 ========== */
-testnum++;
-testdesc = "setLoginSavingEnabled / false";
-
-expectedNotification = "hostSavingDisabled";
-expectedData = "http://site.com";
-Services.logins.setLoginSavingEnabled("http://site.com", false);
-do_check_eq(expectedNotification, null);
-LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- ["http://site.com"]);
-
-/* ========== 8 ========== */
-testnum++;
-testdesc = "setLoginSavingEnabled / false (again)";
-
-expectedNotification = "hostSavingDisabled";
-expectedData = "http://site.com";
-Services.logins.setLoginSavingEnabled("http://site.com", false);
-do_check_eq(expectedNotification, null);
-LoginTestUtils.assertDisabledHostsEqual(Services.logins.getAllDisabledHosts(),
- ["http://site.com"]);
-
-/* ========== 9 ========== */
-testnum++;
-testdesc = "setLoginSavingEnabled / true";
-
-expectedNotification = "hostSavingEnabled";
-expectedData = "http://site.com";
-Services.logins.setLoginSavingEnabled("http://site.com", true);
-do_check_eq(expectedNotification, null);
-LoginTestUtils.checkLogins([]);
-
-/* ========== 10 ========== */
-testnum++;
-testdesc = "setLoginSavingEnabled / true (again)";
-
-expectedNotification = "hostSavingEnabled";
-expectedData = "http://site.com";
-Services.logins.setLoginSavingEnabled("http://site.com", true);
-do_check_eq(expectedNotification, null);
-LoginTestUtils.checkLogins([]);
-
-Services.obs.removeObserver(TestObserver, "passwordmgr-storage-changed");
-
-LoginTestUtils.clearData();
-
-} catch (e) {
- throw new Error("FAILED in test #" + testnum + " -- " + testdesc + ": " + e);
-}
-
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_recipes_add.js b/toolkit/components/passwordmgr/test/unit/test_recipes_add.js
deleted file mode 100644
index ef5086c3b..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_recipes_add.js
+++ /dev/null
@@ -1,177 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests adding and retrieving LoginRecipes in the parent process.
- */
-
-"use strict";
-
-add_task(function* test_init() {
- let parent = new LoginRecipesParent({ defaults: null });
- let initPromise1 = parent.initializationPromise;
- let initPromise2 = parent.initializationPromise;
- Assert.strictEqual(initPromise1, initPromise2, "Check that the same promise is returned");
-
- let recipesParent = yield initPromise1;
- Assert.ok(recipesParent instanceof LoginRecipesParent, "Check init return value");
- Assert.strictEqual(recipesParent._recipesByHost.size, 0, "Initially 0 recipes");
-});
-
-add_task(function* test_get_missing_host() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- let exampleRecipes = recipesParent.getRecipesForHost("example.invalid");
- Assert.strictEqual(exampleRecipes.size, 0, "Check recipe count for example.invalid");
-
-});
-
-add_task(function* test_add_get_simple_host() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.strictEqual(recipesParent._recipesByHost.size, 0, "Initially 0 recipes");
- recipesParent.add({
- hosts: ["example.com"],
- });
- Assert.strictEqual(recipesParent._recipesByHost.size, 1,
- "Check number of hosts after the addition");
-
- let exampleRecipes = recipesParent.getRecipesForHost("example.com");
- Assert.strictEqual(exampleRecipes.size, 1, "Check recipe count for example.com");
- let recipe = [...exampleRecipes][0];
- Assert.strictEqual(typeof(recipe), "object", "Check recipe type");
- Assert.strictEqual(recipe.hosts.length, 1, "Check that one host is present");
- Assert.strictEqual(recipe.hosts[0], "example.com", "Check the one host");
-});
-
-add_task(function* test_add_get_non_standard_port_host() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- recipesParent.add({
- hosts: ["example.com:8080"],
- });
- Assert.strictEqual(recipesParent._recipesByHost.size, 1,
- "Check number of hosts after the addition");
-
- let exampleRecipes = recipesParent.getRecipesForHost("example.com:8080");
- Assert.strictEqual(exampleRecipes.size, 1, "Check recipe count for example.com:8080");
- let recipe = [...exampleRecipes][0];
- Assert.strictEqual(typeof(recipe), "object", "Check recipe type");
- Assert.strictEqual(recipe.hosts.length, 1, "Check that one host is present");
- Assert.strictEqual(recipe.hosts[0], "example.com:8080", "Check the one host");
-});
-
-add_task(function* test_add_multiple_hosts() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- recipesParent.add({
- hosts: ["example.com", "foo.invalid"],
- });
- Assert.strictEqual(recipesParent._recipesByHost.size, 2,
- "Check number of hosts after the addition");
-
- let exampleRecipes = recipesParent.getRecipesForHost("example.com");
- Assert.strictEqual(exampleRecipes.size, 1, "Check recipe count for example.com");
- let recipe = [...exampleRecipes][0];
- Assert.strictEqual(typeof(recipe), "object", "Check recipe type");
- Assert.strictEqual(recipe.hosts.length, 2, "Check that two hosts are present");
- Assert.strictEqual(recipe.hosts[0], "example.com", "Check the first host");
- Assert.strictEqual(recipe.hosts[1], "foo.invalid", "Check the second host");
-
- let fooRecipes = recipesParent.getRecipesForHost("foo.invalid");
- Assert.strictEqual(fooRecipes.size, 1, "Check recipe count for foo.invalid");
- let fooRecipe = [...fooRecipes][0];
- Assert.strictEqual(fooRecipe, recipe, "Check that the recipe is shared");
- Assert.strictEqual(typeof(fooRecipe), "object", "Check recipe type");
- Assert.strictEqual(fooRecipe.hosts.length, 2, "Check that two hosts are present");
- Assert.strictEqual(fooRecipe.hosts[0], "example.com", "Check the first host");
- Assert.strictEqual(fooRecipe.hosts[1], "foo.invalid", "Check the second host");
-});
-
-add_task(function* test_add_pathRegex() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- recipesParent.add({
- hosts: ["example.com"],
- pathRegex: /^\/mypath\//,
- });
- Assert.strictEqual(recipesParent._recipesByHost.size, 1,
- "Check number of hosts after the addition");
-
- let exampleRecipes = recipesParent.getRecipesForHost("example.com");
- Assert.strictEqual(exampleRecipes.size, 1, "Check recipe count for example.com");
- let recipe = [...exampleRecipes][0];
- Assert.strictEqual(typeof(recipe), "object", "Check recipe type");
- Assert.strictEqual(recipe.hosts.length, 1, "Check that one host is present");
- Assert.strictEqual(recipe.hosts[0], "example.com", "Check the one host");
- Assert.strictEqual(recipe.pathRegex.toString(), "/^\\/mypath\\//", "Check the pathRegex");
-});
-
-add_task(function* test_add_selectors() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- recipesParent.add({
- hosts: ["example.com"],
- usernameSelector: "#my-username",
- passwordSelector: "#my-form > input.password",
- });
- Assert.strictEqual(recipesParent._recipesByHost.size, 1,
- "Check number of hosts after the addition");
-
- let exampleRecipes = recipesParent.getRecipesForHost("example.com");
- Assert.strictEqual(exampleRecipes.size, 1, "Check recipe count for example.com");
- let recipe = [...exampleRecipes][0];
- Assert.strictEqual(typeof(recipe), "object", "Check recipe type");
- Assert.strictEqual(recipe.hosts.length, 1, "Check that one host is present");
- Assert.strictEqual(recipe.hosts[0], "example.com", "Check the one host");
- Assert.strictEqual(recipe.usernameSelector, "#my-username", "Check the usernameSelector");
- Assert.strictEqual(recipe.passwordSelector, "#my-form > input.password", "Check the passwordSelector");
-});
-
-/* Begin checking errors with add */
-
-add_task(function* test_add_missing_prop() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.throws(() => recipesParent.add({}), /required/, "Some properties are required");
-});
-
-add_task(function* test_add_unknown_prop() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.throws(() => recipesParent.add({
- unknownProp: true,
- }), /supported/, "Unknown properties should cause an error to help with typos");
-});
-
-add_task(function* test_add_invalid_hosts() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.throws(() => recipesParent.add({
- hosts: 404,
- }), /array/, "hosts should be an array");
-});
-
-add_task(function* test_add_empty_host_array() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.throws(() => recipesParent.add({
- hosts: [],
- }), /array/, "hosts should be a non-empty array");
-});
-
-add_task(function* test_add_pathRegex_non_regexp() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.throws(() => recipesParent.add({
- hosts: ["example.com"],
- pathRegex: "foo",
- }), /regular expression/, "pathRegex should be a RegExp");
-});
-
-add_task(function* test_add_usernameSelector_non_string() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.throws(() => recipesParent.add({
- hosts: ["example.com"],
- usernameSelector: 404,
- }), /string/, "usernameSelector should be a string");
-});
-
-add_task(function* test_add_passwordSelector_non_string() {
- let recipesParent = yield RecipeHelpers.initNewParent();
- Assert.throws(() => recipesParent.add({
- hosts: ["example.com"],
- passwordSelector: 404,
- }), /string/, "passwordSelector should be a string");
-});
-
-/* End checking errors with add */
diff --git a/toolkit/components/passwordmgr/test/unit/test_recipes_content.js b/toolkit/components/passwordmgr/test/unit/test_recipes_content.js
deleted file mode 100644
index 3d3751452..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_recipes_content.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Test filtering recipes in LoginRecipesContent.
- */
-
-"use strict";
-
-Cu.importGlobalProperties(["URL"]);
-
-add_task(function* test_getFieldOverrides() {
- let recipes = new Set([
- { // path doesn't match but otherwise good
- hosts: ["example.com:8080"],
- passwordSelector: "#password",
- pathRegex: /^\/$/,
- usernameSelector: ".username",
- },
- { // match with no field overrides
- hosts: ["example.com:8080"],
- },
- { // best match (field selectors + path match)
- description: "best match",
- hosts: ["a.invalid", "example.com:8080", "other.invalid"],
- passwordSelector: "#password",
- pathRegex: /^\/first\/second\/$/,
- usernameSelector: ".username",
- },
- ]);
-
- let form = MockDocument.createTestDocument("http://localhost:8080/first/second/", "<form>").
- forms[0];
- let override = LoginRecipesContent.getFieldOverrides(recipes, form);
- Assert.strictEqual(override.description, "best match",
- "Check the best field override recipe was returned");
- Assert.strictEqual(override.usernameSelector, ".username", "Check usernameSelector");
- Assert.strictEqual(override.passwordSelector, "#password", "Check passwordSelector");
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_removeLegacySignonFiles.js b/toolkit/components/passwordmgr/test/unit/test_removeLegacySignonFiles.js
deleted file mode 100644
index 51a107170..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_removeLegacySignonFiles.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * Tests the LoginHelper object.
- */
-
-"use strict";
-
-
-Cu.import("resource://gre/modules/Task.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper",
- "resource://gre/modules/LoginHelper.jsm");
-
-
-function* createSignonFile(singon) {
- let {file, pref} = singon;
-
- if (pref) {
- Services.prefs.setCharPref(pref, file);
- }
-
- yield OS.File.writeAtomic(
- OS.Path.join(OS.Constants.Path.profileDir, file), new Uint8Array(1));
-}
-
-function* isSignonClear(singon) {
- const {file, pref} = singon;
- const fileExists = yield OS.File.exists(
- OS.Path.join(OS.Constants.Path.profileDir, file));
-
- if (pref) {
- try {
- Services.prefs.getCharPref(pref);
- return false;
- } catch (e) {}
- }
-
- return !fileExists;
-}
-
-add_task(function* test_remove_lagecy_signonfile() {
- // In the last test case, signons3.txt being deleted even when
- // it doesn't exist.
- const signonsSettings = [[
- { file: "signons.txt" },
- { file: "signons2.txt" },
- { file: "signons3.txt" }
- ], [
- { file: "signons.txt", pref: "signon.SignonFileName" },
- { file: "signons2.txt", pref: "signon.SignonFileName2" },
- { file: "signons3.txt", pref: "signon.SignonFileName3" }
- ], [
- { file: "signons2.txt" },
- { file: "singons.txt", pref: "signon.SignonFileName" },
- { file: "customized2.txt", pref: "signon.SignonFileName2" },
- { file: "customized3.txt", pref: "signon.SignonFileName3" }
- ]];
-
- for (let setting of signonsSettings) {
- for (let singon of setting) {
- yield createSignonFile(singon);
- }
-
- LoginHelper.removeLegacySignonFiles();
-
- for (let singon of setting) {
- equal(yield isSignonClear(singon), true);
- }
- }
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_search_schemeUpgrades.js b/toolkit/components/passwordmgr/test/unit/test_search_schemeUpgrades.js
deleted file mode 100644
index 3406becff..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_search_schemeUpgrades.js
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Test Services.logins.searchLogins with the `schemeUpgrades` property.
- */
-
-const HTTP3_ORIGIN = "http://www3.example.com";
-const HTTPS_ORIGIN = "https://www.example.com";
-const HTTP_ORIGIN = "http://www.example.com";
-
-/**
- * Returns a list of new nsILoginInfo objects that are a subset of the test
- * data, built to match the specified query.
- *
- * @param {Object} aQuery
- * Each property and value of this object restricts the search to those
- * entries from the test data that match the property exactly.
- */
-function buildExpectedLogins(aQuery) {
- return TestData.loginList().filter(
- entry => Object.keys(aQuery).every(name => {
- if (name == "schemeUpgrades") {
- return true;
- }
- if (["hostname", "formSubmitURL"].includes(name)) {
- return LoginHelper.isOriginMatching(entry[name], aQuery[name], {
- schemeUpgrades: aQuery.schemeUpgrades,
- });
- }
- return entry[name] === aQuery[name];
- }));
-}
-
-/**
- * Tests the searchLogins function.
- *
- * @param {Object} aQuery
- * Each property and value of this object is translated to an entry in
- * the nsIPropertyBag parameter of searchLogins.
- * @param {Number} aExpectedCount
- * Number of logins from the test data that should be found. The actual
- * list of logins is obtained using the buildExpectedLogins helper, and
- * this value is just used to verify that modifications to the test data
- * don't make the current test meaningless.
- */
-function checkSearch(aQuery, aExpectedCount) {
- do_print("Testing searchLogins for " + JSON.stringify(aQuery));
-
- let expectedLogins = buildExpectedLogins(aQuery);
- do_check_eq(expectedLogins.length, aExpectedCount);
-
- let outCount = {};
- let logins = Services.logins.searchLogins(outCount, newPropertyBag(aQuery));
- do_check_eq(outCount.value, expectedLogins.length);
- LoginTestUtils.assertLoginListsEqual(logins, expectedLogins);
-}
-
-/**
- * Prepare data for the following tests.
- */
-add_task(function test_initialize() {
- for (let login of TestData.loginList()) {
- Services.logins.addLogin(login);
- }
-});
-
-/**
- * Tests searchLogins with the `schemeUpgrades` property
- */
-add_task(function test_search_schemeUpgrades_hostname() {
- // Hostname-only
- checkSearch({
- hostname: HTTPS_ORIGIN,
- }, 1);
- checkSearch({
- hostname: HTTPS_ORIGIN,
- schemeUpgrades: false,
- }, 1);
- checkSearch({
- hostname: HTTPS_ORIGIN,
- schemeUpgrades: undefined,
- }, 1);
- checkSearch({
- hostname: HTTPS_ORIGIN,
- schemeUpgrades: true,
- }, 2);
-});
-
-/**
- * Same as above but replacing hostname with formSubmitURL.
- */
-add_task(function test_search_schemeUpgrades_formSubmitURL() {
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- }, 2);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- schemeUpgrades: false,
- }, 2);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- schemeUpgrades: undefined,
- }, 2);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- schemeUpgrades: true,
- }, 4);
-});
-
-
-add_task(function test_search_schemeUpgrades_hostname_formSubmitURL() {
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTPS_ORIGIN,
- }, 1);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTPS_ORIGIN,
- schemeUpgrades: false,
- }, 1);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTPS_ORIGIN,
- schemeUpgrades: undefined,
- }, 1);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTPS_ORIGIN,
- schemeUpgrades: true,
- }, 2);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTPS_ORIGIN,
- schemeUpgrades: true,
- usernameField: "form_field_username",
- }, 2);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTPS_ORIGIN,
- passwordField: "form_field_password",
- schemeUpgrades: true,
- usernameField: "form_field_username",
- }, 2);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTPS_ORIGIN,
- httpRealm: null,
- passwordField: "form_field_password",
- schemeUpgrades: true,
- usernameField: "form_field_username",
- }, 2);
-});
-
-/**
- * HTTP submitting to HTTPS
- */
-add_task(function test_http_to_https() {
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTP3_ORIGIN,
- httpRealm: null,
- schemeUpgrades: false,
- }, 1);
- checkSearch({
- formSubmitURL: HTTPS_ORIGIN,
- hostname: HTTP3_ORIGIN,
- httpRealm: null,
- schemeUpgrades: true,
- }, 2);
-});
-
-/**
- * schemeUpgrades shouldn't cause downgrades
- */
-add_task(function test_search_schemeUpgrades_downgrade() {
- checkSearch({
- formSubmitURL: HTTP_ORIGIN,
- hostname: HTTP_ORIGIN,
- }, 1);
- do_print("The same number should be found with schemeUpgrades since we're searching for HTTP");
- checkSearch({
- formSubmitURL: HTTP_ORIGIN,
- hostname: HTTP_ORIGIN,
- schemeUpgrades: true,
- }, 1);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_storage.js b/toolkit/components/passwordmgr/test/unit/test_storage.js
deleted file mode 100644
index d65516d9b..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_storage.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests that the default nsILoginManagerStorage module attached to the Login
- * Manager service is able to save and reload nsILoginInfo properties correctly,
- * even when they include special characters.
- */
-
-"use strict";
-
-// Globals
-
-function* reloadAndCheckLoginsGen(aExpectedLogins)
-{
- yield LoginTestUtils.reloadData();
- LoginTestUtils.checkLogins(aExpectedLogins);
- LoginTestUtils.clearData();
-}
-
-// Tests
-
-/**
- * Tests addLogin with valid non-ASCII characters.
- */
-add_task(function* test_storage_addLogin_nonascii()
-{
- let hostname = "http://" + String.fromCharCode(355) + ".example.com";
-
- // Store the strings "user" and "pass" using similarly looking glyphs.
- let loginInfo = TestData.formLogin({
- hostname: hostname,
- formSubmitURL: hostname,
- username: String.fromCharCode(533, 537, 7570, 345),
- password: String.fromCharCode(421, 259, 349, 537),
- usernameField: "field_" + String.fromCharCode(533, 537, 7570, 345),
- passwordField: "field_" + String.fromCharCode(421, 259, 349, 537),
- });
- Services.logins.addLogin(loginInfo);
- yield* reloadAndCheckLoginsGen([loginInfo]);
-
- // Store the string "test" using similarly looking glyphs.
- loginInfo = TestData.authLogin({
- httpRealm: String.fromCharCode(355, 277, 349, 357),
- });
- Services.logins.addLogin(loginInfo);
- yield* reloadAndCheckLoginsGen([loginInfo]);
-});
-
-/**
- * Tests addLogin with newline characters in the username and password.
- */
-add_task(function* test_storage_addLogin_newlines()
-{
- let loginInfo = TestData.formLogin({
- username: "user\r\nname",
- password: "password\r\n",
- });
- Services.logins.addLogin(loginInfo);
- yield* reloadAndCheckLoginsGen([loginInfo]);
-});
-
-/**
- * Tests addLogin with a single dot in fields where it is allowed.
- *
- * These tests exist to verify the legacy "signons.txt" storage format.
- */
-add_task(function* test_storage_addLogin_dot()
-{
- let loginInfo = TestData.formLogin({ hostname: ".", passwordField: "." });
- Services.logins.addLogin(loginInfo);
- yield* reloadAndCheckLoginsGen([loginInfo]);
-
- loginInfo = TestData.authLogin({ httpRealm: "." });
- Services.logins.addLogin(loginInfo);
- yield* reloadAndCheckLoginsGen([loginInfo]);
-});
-
-/**
- * Tests addLogin with parentheses in hostnames.
- *
- * These tests exist to verify the legacy "signons.txt" storage format.
- */
-add_task(function* test_storage_addLogin_parentheses()
-{
- let loginList = [
- TestData.authLogin({ httpRealm: "(realm" }),
- TestData.authLogin({ httpRealm: "realm)" }),
- TestData.authLogin({ httpRealm: "(realm)" }),
- TestData.authLogin({ httpRealm: ")realm(" }),
- TestData.authLogin({ hostname: "http://parens(.example.com" }),
- TestData.authLogin({ hostname: "http://parens).example.com" }),
- TestData.authLogin({ hostname: "http://parens(example).example.com" }),
- TestData.authLogin({ hostname: "http://parens)example(.example.com" }),
- ];
- for (let loginInfo of loginList) {
- Services.logins.addLogin(loginInfo);
- }
- yield* reloadAndCheckLoginsGen(loginList);
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_storage_mozStorage.js b/toolkit/components/passwordmgr/test/unit/test_storage_mozStorage.js
deleted file mode 100644
index 8eab6efe5..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_storage_mozStorage.js
+++ /dev/null
@@ -1,507 +0,0 @@
-/*
- * This test interfaces directly with the mozStorage password storage module,
- * bypassing the normal password manager usage.
- */
-
-
-const ENCTYPE_BASE64 = 0;
-const ENCTYPE_SDR = 1;
-const PERMISSION_SAVE_LOGINS = "login-saving";
-
-// Current schema version used by storage-mozStorage.js. This will need to be
-// kept in sync with the version there (or else the tests fail).
-const CURRENT_SCHEMA = 6;
-
-function* copyFile(aLeafName)
-{
- yield OS.File.copy(OS.Path.join(do_get_file("data").path, aLeafName),
- OS.Path.join(OS.Constants.Path.profileDir, aLeafName));
-}
-
-function openDB(aLeafName)
-{
- var dbFile = new FileUtils.File(OS.Constants.Path.profileDir);
- dbFile.append(aLeafName);
-
- return Services.storage.openDatabase(dbFile);
-}
-
-function deleteFile(pathname, filename)
-{
- var file = new FileUtils.File(pathname);
- file.append(filename);
-
- // Suppress failures, this happens in the mozstorage tests on Windows
- // because the module may still be holding onto the DB. (We don't
- // have a way to explicitly shutdown/GC the module).
- try {
- if (file.exists())
- file.remove(false);
- } catch (e) {}
-}
-
-function reloadStorage(aInputPathName, aInputFileName)
-{
- var inputFile = null;
- if (aInputFileName) {
- inputFile = Cc["@mozilla.org/file/local;1"].
- createInstance(Ci.nsILocalFile);
- inputFile.initWithPath(aInputPathName);
- inputFile.append(aInputFileName);
- }
-
- let storage = Cc["@mozilla.org/login-manager/storage/mozStorage;1"]
- .createInstance(Ci.nsILoginManagerStorage);
- storage.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIVariant)
- .initWithFile(inputFile);
-
- return storage;
-}
-
-function checkStorageData(storage, ref_disabledHosts, ref_logins)
-{
- LoginTestUtils.assertLoginListsEqual(storage.getAllLogins(), ref_logins);
- LoginTestUtils.assertDisabledHostsEqual(getAllDisabledHostsFromPermissionManager(),
- ref_disabledHosts);
-}
-
-function getAllDisabledHostsFromPermissionManager() {
- let disabledHosts = [];
- let enumerator = Services.perms.enumerator;
-
- while (enumerator.hasMoreElements()) {
- let perm = enumerator.getNext();
- if (perm.type == PERMISSION_SAVE_LOGINS && perm.capability == Services.perms.DENY_ACTION) {
- disabledHosts.push(perm.principal.URI.prePath);
- }
- }
-
- return disabledHosts;
-}
-
-function setLoginSavingEnabled(origin, enabled) {
- let uri = Services.io.newURI(origin, null, null);
-
- if (enabled) {
- Services.perms.remove(uri, PERMISSION_SAVE_LOGINS);
- } else {
- Services.perms.add(uri, PERMISSION_SAVE_LOGINS, Services.perms.DENY_ACTION);
- }
-}
-
-add_task(function* test_execute()
-{
-
-const OUTDIR = OS.Constants.Path.profileDir;
-
-try {
-
-var isGUID = /^\{[0-9a-f\d]{8}-[0-9a-f\d]{4}-[0-9a-f\d]{4}-[0-9a-f\d]{4}-[0-9a-f\d]{12}\}$/;
-function getGUIDforID(conn, id) {
- var stmt = conn.createStatement("SELECT guid from moz_logins WHERE id = " + id);
- stmt.executeStep();
- var guid = stmt.getString(0);
- stmt.finalize();
- return guid;
-}
-
-function getEncTypeForID(conn, id) {
- var stmt = conn.createStatement("SELECT encType from moz_logins WHERE id = " + id);
- stmt.executeStep();
- var encType = stmt.row.encType;
- stmt.finalize();
- return encType;
-}
-
-function getAllDisabledHostsFromMozStorage(conn) {
- let disabledHosts = [];
- let stmt = conn.createStatement("SELECT hostname from moz_disabledHosts");
-
- while (stmt.executeStep()) {
- disabledHosts.push(stmt.row.hostname);
- }
-
- return disabledHosts;
-}
-
-var storage;
-var dbConnection;
-var testnum = 0;
-var testdesc = "Setup of nsLoginInfo test-users";
-var nsLoginInfo = new Components.Constructor(
- "@mozilla.org/login-manager/loginInfo;1",
- Components.interfaces.nsILoginInfo);
-do_check_true(nsLoginInfo != null);
-
-var testuser1 = new nsLoginInfo;
-testuser1.init("http://test.com", "http://test.com", null,
- "testuser1", "testpass1", "u1", "p1");
-var testuser1B = new nsLoginInfo;
-testuser1B.init("http://test.com", "http://test.com", null,
- "testuser1B", "testpass1B", "u1", "p1");
-var testuser2 = new nsLoginInfo;
-testuser2.init("http://test.org", "http://test.org", null,
- "testuser2", "testpass2", "u2", "p2");
-var testuser3 = new nsLoginInfo;
-testuser3.init("http://test.gov", "http://test.gov", null,
- "testuser3", "testpass3", "u3", "p3");
-var testuser4 = new nsLoginInfo;
-testuser4.init("http://test.gov", "http://test.gov", null,
- "testuser1", "testpass2", "u4", "p4");
-var testuser5 = new nsLoginInfo;
-testuser5.init("http://test.gov", "http://test.gov", null,
- "testuser2", "testpass1", "u5", "p5");
-
-
-/* ========== 1 ========== */
-testnum++;
-testdesc = "Test downgrade from v999 storage";
-
-yield* copyFile("signons-v999.sqlite");
-// Verify the schema version in the test file.
-dbConnection = openDB("signons-v999.sqlite");
-do_check_eq(999, dbConnection.schemaVersion);
-dbConnection.close();
-
-storage = reloadStorage(OUTDIR, "signons-v999.sqlite");
-setLoginSavingEnabled("https://disabled.net", false);
-checkStorageData(storage, ["https://disabled.net"], [testuser1]);
-
-// Check to make sure we downgraded the schema version.
-dbConnection = openDB("signons-v999.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-dbConnection.close();
-
-deleteFile(OUTDIR, "signons-v999.sqlite");
-
-/* ========== 2 ========== */
-testnum++;
-testdesc = "Test downgrade from incompat v999 storage";
-// This file has a testuser999/testpass999, but is missing an expected column
-
-var origFile = OS.Path.join(OUTDIR, "signons-v999-2.sqlite");
-var failFile = OS.Path.join(OUTDIR, "signons-v999-2.sqlite.corrupt");
-
-// Make sure we always start clean in a clean state.
-yield* copyFile("signons-v999-2.sqlite");
-yield OS.File.remove(failFile);
-
-Assert.throws(() => reloadStorage(OUTDIR, "signons-v999-2.sqlite"),
- /Initialization failed/);
-
-// Check to ensure the DB file was renamed to .corrupt.
-do_check_false(yield OS.File.exists(origFile));
-do_check_true(yield OS.File.exists(failFile));
-
-yield OS.File.remove(failFile);
-
-/* ========== 3 ========== */
-testnum++;
-testdesc = "Test upgrade from v1->v2 storage";
-
-yield* copyFile("signons-v1.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v1.sqlite");
-do_check_eq(1, dbConnection.schemaVersion);
-dbConnection.close();
-
-storage = reloadStorage(OUTDIR, "signons-v1.sqlite");
-checkStorageData(storage, ["https://disabled.net"], [testuser1, testuser2]);
-
-// Check to see that we added a GUIDs to the logins.
-dbConnection = openDB("signons-v1.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-var guid = getGUIDforID(dbConnection, 1);
-do_check_true(isGUID.test(guid));
-guid = getGUIDforID(dbConnection, 2);
-do_check_true(isGUID.test(guid));
-dbConnection.close();
-
-deleteFile(OUTDIR, "signons-v1.sqlite");
-
-/* ========== 4 ========== */
-testnum++;
-testdesc = "Test upgrade v2->v1 storage";
-// This is the case where a v2 DB has been accessed with v1 code, and now we
-// are upgrading it again. Any logins added by the v1 code must be properly
-// upgraded.
-
-yield* copyFile("signons-v1v2.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v1v2.sqlite");
-do_check_eq(1, dbConnection.schemaVersion);
-dbConnection.close();
-
-storage = reloadStorage(OUTDIR, "signons-v1v2.sqlite");
-checkStorageData(storage, ["https://disabled.net"], [testuser1, testuser2, testuser3]);
-
-// While we're here, try modifying a login, to ensure that doing so doesn't
-// change the existing GUID.
-storage.modifyLogin(testuser1, testuser1B);
-checkStorageData(storage, ["https://disabled.net"], [testuser1B, testuser2, testuser3]);
-
-// Check the GUIDs. Logins 1 and 2 should retain their original GUID, login 3
-// should have one created (because it didn't have one previously).
-dbConnection = openDB("signons-v1v2.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-guid = getGUIDforID(dbConnection, 1);
-do_check_eq("{655c7358-f1d6-6446-adab-53f98ac5d80f}", guid);
-guid = getGUIDforID(dbConnection, 2);
-do_check_eq("{13d9bfdc-572a-4d4e-9436-68e9803e84c1}", guid);
-guid = getGUIDforID(dbConnection, 3);
-do_check_true(isGUID.test(guid));
-dbConnection.close();
-
-deleteFile(OUTDIR, "signons-v1v2.sqlite");
-
-/* ========== 5 ========== */
-testnum++;
-testdesc = "Test upgrade from v2->v3 storage";
-
-yield* copyFile("signons-v2.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v2.sqlite");
-do_check_eq(2, dbConnection.schemaVersion);
-
-storage = reloadStorage(OUTDIR, "signons-v2.sqlite");
-
-// Check to see that we added the correct encType to the logins.
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-var encTypes = [ENCTYPE_BASE64, ENCTYPE_SDR, ENCTYPE_BASE64, ENCTYPE_BASE64];
-for (let i = 0; i < encTypes.length; i++)
- do_check_eq(encTypes[i], getEncTypeForID(dbConnection, i + 1));
-dbConnection.close();
-
-// There are 4 logins, but 3 will be invalid because we can no longer decrypt
-// base64-encoded items. (testuser1/4/5)
-checkStorageData(storage, ["https://disabled.net"],
- [testuser2]);
-
-deleteFile(OUTDIR, "signons-v2.sqlite");
-
-/* ========== 6 ========== */
-testnum++;
-testdesc = "Test upgrade v3->v2 storage";
-// This is the case where a v3 DB has been accessed with v2 code, and now we
-// are upgrading it again. Any logins added by the v2 code must be properly
-// upgraded.
-
-yield* copyFile("signons-v2v3.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v2v3.sqlite");
-do_check_eq(2, dbConnection.schemaVersion);
-encTypes = [ENCTYPE_BASE64, ENCTYPE_SDR, ENCTYPE_BASE64, ENCTYPE_BASE64, null];
-for (let i = 0; i < encTypes.length; i++)
- do_check_eq(encTypes[i], getEncTypeForID(dbConnection, i + 1));
-
-// Reload storage, check that the new login now has encType=1, others untouched
-storage = reloadStorage(OUTDIR, "signons-v2v3.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-
-encTypes = [ENCTYPE_BASE64, ENCTYPE_SDR, ENCTYPE_BASE64, ENCTYPE_BASE64, ENCTYPE_SDR];
-for (let i = 0; i < encTypes.length; i++)
- do_check_eq(encTypes[i], getEncTypeForID(dbConnection, i + 1));
-
-// Sanity check that the data gets migrated
-// There are 5 logins, but 3 will be invalid because we can no longer decrypt
-// base64-encoded items. (testuser1/4/5). We no longer reencrypt with SDR.
-checkStorageData(storage, ["https://disabled.net"], [testuser2, testuser3]);
-encTypes = [ENCTYPE_BASE64, ENCTYPE_SDR, ENCTYPE_BASE64, ENCTYPE_BASE64, ENCTYPE_SDR];
-for (let i = 0; i < encTypes.length; i++)
- do_check_eq(encTypes[i], getEncTypeForID(dbConnection, i + 1));
-dbConnection.close();
-
-deleteFile(OUTDIR, "signons-v2v3.sqlite");
-
-
-/* ========== 7 ========== */
-testnum++;
-testdesc = "Test upgrade from v3->v4 storage";
-
-yield* copyFile("signons-v3.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v3.sqlite");
-do_check_eq(3, dbConnection.schemaVersion);
-
-storage = reloadStorage(OUTDIR, "signons-v3.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-
-// Remove old entry from permission manager.
-setLoginSavingEnabled("https://disabled.net", true);
-
-// Check that timestamps and counts were initialized correctly
-checkStorageData(storage, [], [testuser1, testuser2]);
-
-var logins = storage.getAllLogins();
-for (var i = 0; i < 2; i++) {
- do_check_true(logins[i] instanceof Ci.nsILoginMetaInfo);
- do_check_eq(1, logins[i].timesUsed);
- LoginTestUtils.assertTimeIsAboutNow(logins[i].timeCreated);
- LoginTestUtils.assertTimeIsAboutNow(logins[i].timeLastUsed);
- LoginTestUtils.assertTimeIsAboutNow(logins[i].timePasswordChanged);
-}
-
-/* ========== 8 ========== */
-testnum++;
-testdesc = "Test upgrade from v3->v4->v3 storage";
-
-yield* copyFile("signons-v3v4.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v3v4.sqlite");
-do_check_eq(3, dbConnection.schemaVersion);
-
-storage = reloadStorage(OUTDIR, "signons-v3v4.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-
-// testuser1 already has timestamps, testuser2 does not.
-checkStorageData(storage, [], [testuser1, testuser2]);
-
-logins = storage.getAllLogins();
-
-var t1, t2;
-if (logins[0].username == "testuser1") {
- t1 = logins[0];
- t2 = logins[1];
-} else {
- t1 = logins[1];
- t2 = logins[0];
-}
-
-do_check_true(t1 instanceof Ci.nsILoginMetaInfo);
-do_check_true(t2 instanceof Ci.nsILoginMetaInfo);
-
-do_check_eq(9, t1.timesUsed);
-do_check_eq(1262049951275, t1.timeCreated);
-do_check_eq(1262049951275, t1.timeLastUsed);
-do_check_eq(1262049951275, t1.timePasswordChanged);
-
-do_check_eq(1, t2.timesUsed);
-LoginTestUtils.assertTimeIsAboutNow(t2.timeCreated);
-LoginTestUtils.assertTimeIsAboutNow(t2.timeLastUsed);
-LoginTestUtils.assertTimeIsAboutNow(t2.timePasswordChanged);
-
-
-/* ========== 9 ========== */
-testnum++;
-testdesc = "Test upgrade from v4 storage";
-
-yield* copyFile("signons-v4.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v4.sqlite");
-do_check_eq(4, dbConnection.schemaVersion);
-do_check_false(dbConnection.tableExists("moz_deleted_logins"));
-
-storage = reloadStorage(OUTDIR, "signons-v4.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-do_check_true(dbConnection.tableExists("moz_deleted_logins"));
-
-
-/* ========== 10 ========== */
-testnum++;
-testdesc = "Test upgrade from v4->v5->v4 storage";
-
-yield copyFile("signons-v4v5.sqlite");
-// Sanity check the test file.
-dbConnection = openDB("signons-v4v5.sqlite");
-do_check_eq(4, dbConnection.schemaVersion);
-do_check_true(dbConnection.tableExists("moz_deleted_logins"));
-
-storage = reloadStorage(OUTDIR, "signons-v4v5.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-do_check_true(dbConnection.tableExists("moz_deleted_logins"));
-
-/* ========== 11 ========== */
-testnum++;
-testdesc = "Test upgrade from v5->v6 storage";
-
-yield* copyFile("signons-v5v6.sqlite");
-
-// Sanity check the test file.
-dbConnection = openDB("signons-v5v6.sqlite");
-do_check_eq(5, dbConnection.schemaVersion);
-do_check_true(dbConnection.tableExists("moz_disabledHosts"));
-
-// Initial disabled hosts inside signons-v5v6.sqlite
-var disabledHosts = [
- "http://disabled1.example.com",
- "http://大.net",
- "http://xn--19g.com"
-];
-
-LoginTestUtils.assertDisabledHostsEqual(disabledHosts, getAllDisabledHostsFromMozStorage(dbConnection));
-
-// Reload storage
-storage = reloadStorage(OUTDIR, "signons-v5v6.sqlite");
-do_check_eq(CURRENT_SCHEMA, dbConnection.schemaVersion);
-
-// moz_disabledHosts should now be empty after migration.
-LoginTestUtils.assertDisabledHostsEqual([], getAllDisabledHostsFromMozStorage(dbConnection));
-
-// Get all the other hosts currently saved in the permission manager.
-let hostsInPermissionManager = getAllDisabledHostsFromPermissionManager();
-
-// All disabledHosts should have migrated to the permission manager
-LoginTestUtils.assertDisabledHostsEqual(disabledHosts, hostsInPermissionManager);
-
-// Remove all disabled hosts from the permission manager before test ends
-for (let host of disabledHosts) {
- setLoginSavingEnabled(host, true);
-}
-
-/* ========== 12 ========== */
-testnum++;
-testdesc = "Create nsILoginInfo instances for testing with";
-
-testuser1 = new nsLoginInfo;
-testuser1.init("http://dummyhost.mozilla.org", "", null,
- "dummydude", "itsasecret", "put_user_here", "put_pw_here");
-
-
-/*
- * ---------------------- DB Corruption ----------------------
- * Try to initialize with a corrupt database file. This should create a backup
- * file, then upon next use create a new database file.
- */
-
-/* ========== 13 ========== */
-testnum++;
-testdesc = "Corrupt database and backup";
-
-const filename = "signons-c.sqlite";
-const filepath = OS.Path.join(OS.Constants.Path.profileDir, filename);
-
-yield OS.File.copy(do_get_file("data/corruptDB.sqlite").path, filepath);
-
-// will init mozStorage module with corrupt database, init should fail
-Assert.throws(
- () => reloadStorage(OS.Constants.Path.profileDir, filename),
- /Initialization failed/);
-
-// check that the backup file exists
-do_check_true(yield OS.File.exists(filepath + ".corrupt"));
-
-// check that the original corrupt file has been deleted
-do_check_false(yield OS.File.exists(filepath));
-
-// initialize the storage module again
-storage = reloadStorage(OS.Constants.Path.profileDir, filename);
-
-// use the storage module again, should work now
-storage.addLogin(testuser1);
-checkStorageData(storage, [], [testuser1]);
-
-// check the file exists
-var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
-file.initWithPath(OS.Constants.Path.profileDir);
-file.append(filename);
-do_check_true(file.exists());
-
-deleteFile(OS.Constants.Path.profileDir, filename + ".corrupt");
-deleteFile(OS.Constants.Path.profileDir, filename);
-
-} catch (e) {
- throw new Error("FAILED in test #" + testnum + " -- " + testdesc + ": " + e);
-}
-
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_telemetry.js b/toolkit/components/passwordmgr/test/unit/test_telemetry.js
deleted file mode 100644
index 1d8f80226..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_telemetry.js
+++ /dev/null
@@ -1,187 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Tests the statistics and other counters reported through telemetry.
- */
-
-"use strict";
-
-// Globals
-
-const MS_PER_DAY = 24 * 60 * 60 * 1000;
-
-// To prevent intermittent failures when the test is executed at a time that is
-// very close to a day boundary, we make it deterministic by using a static
-// reference date for all the time-based statistics.
-const gReferenceTimeMs = new Date("2000-01-01T00:00:00").getTime();
-
-// Returns a milliseconds value to use with nsILoginMetaInfo properties, falling
-// approximately in the middle of the specified number of days before the
-// reference time, where zero days indicates a time within the past 24 hours.
-var daysBeforeMs = days => gReferenceTimeMs - (days + 0.5) * MS_PER_DAY;
-
-/**
- * Contains metadata that will be attached to test logins in order to verify
- * that the statistics collection is working properly. Most properties of the
- * logins are initialized to the default test values already.
- *
- * If you update this data or any of the telemetry histograms it checks, you'll
- * probably need to update the expected statistics in the test below.
- */
-const StatisticsTestData = [
- {
- timeLastUsed: daysBeforeMs(0),
- },
- {
- timeLastUsed: daysBeforeMs(1),
- },
- {
- timeLastUsed: daysBeforeMs(7),
- formSubmitURL: null,
- httpRealm: "The HTTP Realm",
- },
- {
- username: "",
- timeLastUsed: daysBeforeMs(7),
- },
- {
- username: "",
- timeLastUsed: daysBeforeMs(30),
- },
- {
- username: "",
- timeLastUsed: daysBeforeMs(31),
- },
- {
- timeLastUsed: daysBeforeMs(365),
- },
- {
- username: "",
- timeLastUsed: daysBeforeMs(366),
- },
- {
- // If the login was saved in the future, it is ignored for statistiscs.
- timeLastUsed: daysBeforeMs(-1),
- },
- {
- timeLastUsed: daysBeforeMs(1000),
- },
-];
-
-/**
- * Triggers the collection of those statistics that are not accumulated each
- * time an action is taken, but are a static snapshot of the current state.
- */
-function triggerStatisticsCollection() {
- Services.obs.notifyObservers(null, "gather-telemetry", "" + gReferenceTimeMs);
-}
-
-/**
- * Tests the telemetry histogram with the given ID contains only the specified
- * non-zero ranges, expressed in the format { range1: value1, range2: value2 }.
- */
-function testHistogram(histogramId, expectedNonZeroRanges) {
- let snapshot = Services.telemetry.getHistogramById(histogramId).snapshot();
-
- // Compute the actual ranges in the format { range1: value1, range2: value2 }.
- let actualNonZeroRanges = {};
- for (let [index, range] of snapshot.ranges.entries()) {
- let value = snapshot.counts[index];
- if (value > 0) {
- actualNonZeroRanges[range] = value;
- }
- }
-
- // These are stringified to visualize the differences between the values.
- do_print("Testing histogram: " + histogramId);
- do_check_eq(JSON.stringify(actualNonZeroRanges),
- JSON.stringify(expectedNonZeroRanges));
-}
-
-// Tests
-
-/**
- * Enable local telemetry recording for the duration of the tests, and prepare
- * the test data that will be used by the following tests.
- */
-add_task(function test_initialize() {
- let oldCanRecord = Services.telemetry.canRecordExtended;
- Services.telemetry.canRecordExtended = true;
- do_register_cleanup(function () {
- Services.telemetry.canRecordExtended = oldCanRecord;
- });
-
- let uniqueNumber = 1;
- for (let loginModifications of StatisticsTestData) {
- loginModifications.hostname = `http://${uniqueNumber++}.example.com`;
- Services.logins.addLogin(TestData.formLogin(loginModifications));
- }
-});
-
-/**
- * Tests the collection of statistics related to login metadata.
- */
-add_task(function test_logins_statistics() {
- // Repeat the operation twice to test that histograms are not accumulated.
- for (let repeating of [false, true]) {
- triggerStatisticsCollection();
-
- // Should record 1 in the bucket corresponding to the number of passwords.
- testHistogram("PWMGR_NUM_SAVED_PASSWORDS",
- { 10: 1 });
-
- // Should record 1 in the bucket corresponding to the number of passwords.
- testHistogram("PWMGR_NUM_HTTPAUTH_PASSWORDS",
- { 1: 1 });
-
- // For each saved login, should record 1 in the bucket corresponding to the
- // age in days since the login was last used.
- testHistogram("PWMGR_LOGIN_LAST_USED_DAYS",
- { 0: 1, 1: 1, 7: 2, 29: 2, 356: 2, 750: 1 });
-
- // Should record the number of logins without a username in bucket 0, and
- // the number of logins with a username in bucket 1.
- testHistogram("PWMGR_USERNAME_PRESENT",
- { 0: 4, 1: 6 });
- }
-});
-
-/**
- * Tests the collection of statistics related to hosts for which passowrd saving
- * has been explicitly disabled.
- */
-add_task(function test_disabledHosts_statistics() {
- // Should record 1 in the bucket corresponding to the number of sites for
- // which password saving is disabled.
- Services.logins.setLoginSavingEnabled("http://www.example.com", false);
- triggerStatisticsCollection();
- testHistogram("PWMGR_BLOCKLIST_NUM_SITES", { 1: 1 });
-
- Services.logins.setLoginSavingEnabled("http://www.example.com", true);
- triggerStatisticsCollection();
- testHistogram("PWMGR_BLOCKLIST_NUM_SITES", { 0: 1 });
-});
-
-/**
- * Tests the collection of statistics related to general settings.
- */
-add_task(function test_settings_statistics() {
- let oldRememberSignons = Services.prefs.getBoolPref("signon.rememberSignons");
- do_register_cleanup(function () {
- Services.prefs.setBoolPref("signon.rememberSignons", oldRememberSignons);
- });
-
- // Repeat the operation twice per value to test that histograms are reset.
- for (let remember of [false, true, false, true]) {
- // This change should be observed immediately by the login service.
- Services.prefs.setBoolPref("signon.rememberSignons", remember);
-
- triggerStatisticsCollection();
-
- // Should record 1 in either bucket 0 or bucket 1 based on the preference.
- testHistogram("PWMGR_SAVING_ENABLED", remember ? { 1: 1 } : { 0: 1 });
- }
-});
diff --git a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js b/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js
deleted file mode 100644
index e1d250a76..000000000
--- a/toolkit/components/passwordmgr/test/unit/test_user_autocomplete_result.js
+++ /dev/null
@@ -1,488 +0,0 @@
-XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper",
- "resource://gre/modules/LoginHelper.jsm");
-Cu.import("resource://gre/modules/LoginManagerContent.jsm");
-var nsLoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
- Ci.nsILoginInfo, "init");
-
-const PREF_INSECURE_FIELD_WARNING_ENABLED = "security.insecure_field_warning.contextual.enabled";
-const PREF_INSECURE_AUTOFILLFORMS_ENABLED = "signon.autofillForms.http";
-
-let matchingLogins = [];
-matchingLogins.push(new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "", "emptypass1", "uname", "pword"));
-
-matchingLogins.push(new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "tempuser1", "temppass1", "uname", "pword"));
-
-matchingLogins.push(new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser2", "testpass2", "uname", "pword"));
-
-matchingLogins.push(new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "testuser3", "testpass3", "uname", "pword"));
-
-matchingLogins.push(new nsLoginInfo("http://mochi.test:8888", "http://autocomplete:8888", null,
- "zzzuser4", "zzzpass4", "uname", "pword"));
-
-let meta = matchingLogins[0].QueryInterface(Ci.nsILoginMetaInfo);
-let dateAndTimeFormatter = new Intl.DateTimeFormat(undefined,
- { day: "numeric", month: "short", year: "numeric" });
-let time = dateAndTimeFormatter.format(new Date(meta.timePasswordChanged));
-const LABEL_NO_USERNAME = "No username (" + time + ")";
-
-let expectedResults = [
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: true,
- isSecure: true,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "tempuser1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testuser2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testuser3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzuser4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: true,
- isSecure: false,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: "This connection is not secure. Logins entered here could be compromised. Learn More",
- style: "insecureWarning"
- }, {
- value: "",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "tempuser1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testuser2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testuser3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzuser4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: true,
- isSecure: true,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: [{
- value: "emptypass1",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "temppass1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testpass2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testpass3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzpass4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: true,
- isSecure: false,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: "This connection is not secure. Logins entered here could be compromised. Learn More",
- style: "insecureWarning"
- }, {
- value: "emptypass1",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "temppass1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testpass2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testpass3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzpass4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: true,
- isSecure: true,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "tempuser1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testuser2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testuser3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzuser4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: true,
- isSecure: false,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "tempuser1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testuser2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testuser3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzuser4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: true,
- isSecure: true,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: [{
- value: "emptypass1",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "temppass1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testpass2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testpass3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzpass4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: true,
- isSecure: false,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: [{
- value: "emptypass1",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "temppass1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testpass2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testpass3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzpass4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: false,
- isSecure: true,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "tempuser1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testuser2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testuser3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzuser4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: false,
- isSecure: false,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: "This connection is not secure. Logins entered here could be compromised. Learn More",
- style: "insecureWarning"
- }, {
- value: "",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "tempuser1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testuser2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testuser3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzuser4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: false,
- isSecure: true,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: [{
- value: "emptypass1",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "temppass1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testpass2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testpass3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzpass4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: true,
- insecureAutoFillFormsEnabled: false,
- isSecure: false,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: "This connection is not secure. Logins entered here could be compromised. Learn More",
- style: "insecureWarning"
- }, {
- value: "emptypass1",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "temppass1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testpass2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testpass3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzpass4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: false,
- isSecure: true,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: [{
- value: "",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "tempuser1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testuser2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testuser3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzuser4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: false,
- isSecure: false,
- isPasswordField: false,
- matchingLogins: matchingLogins,
- items: []
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: false,
- isSecure: true,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: [{
- value: "emptypass1",
- label: LABEL_NO_USERNAME,
- style: "login",
- }, {
- value: "temppass1",
- label: "tempuser1",
- style: "login",
- }, {
- value: "testpass2",
- label: "testuser2",
- style: "login",
- }, {
- value: "testpass3",
- label: "testuser3",
- style: "login",
- }, {
- value: "zzzpass4",
- label: "zzzuser4",
- style: "login",
- }]
- },
- {
- insecureFieldWarningEnabled: false,
- insecureAutoFillFormsEnabled: false,
- isSecure: false,
- isPasswordField: true,
- matchingLogins: matchingLogins,
- items: []
- },
-];
-
-add_task(function* test_all_patterns() {
- LoginHelper.createLogger("UserAutoCompleteResult");
- expectedResults.forEach(pattern => {
- Services.prefs.setBoolPref(PREF_INSECURE_FIELD_WARNING_ENABLED,
- pattern.insecureFieldWarningEnabled);
- Services.prefs.setBoolPref(PREF_INSECURE_AUTOFILLFORMS_ENABLED,
- pattern.insecureAutoFillFormsEnabled);
- let actual = new UserAutoCompleteResult("", pattern.matchingLogins,
- {
- isSecure: pattern.isSecure,
- isPasswordField: pattern.isPasswordField
- });
- pattern.items.forEach((item, index) => {
- equal(actual.getValueAt(index), item.value);
- equal(actual.getLabelAt(index), item.label);
- equal(actual.getStyleAt(index), item.style);
- });
-
- if (pattern.items.length != 0) {
- Assert.throws(() => actual.getValueAt(pattern.items.length),
- /Index out of range\./);
-
- Assert.throws(() => actual.getLabelAt(pattern.items.length),
- /Index out of range\./);
-
- Assert.throws(() => actual.removeValueAt(pattern.items.length, true),
- /Index out of range\./);
- }
- });
-});
diff --git a/toolkit/components/passwordmgr/test/unit/xpcshell.ini b/toolkit/components/passwordmgr/test/unit/xpcshell.ini
deleted file mode 100644
index 8f8c92a28..000000000
--- a/toolkit/components/passwordmgr/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,46 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-support-files = data/**
-
-# Test JSON file access and import from SQLite, not applicable to Android.
-[test_module_LoginImport.js]
-skip-if = os == "android"
-[test_module_LoginStore.js]
-skip-if = os == "android"
-[test_removeLegacySignonFiles.js]
-skip-if = os == "android"
-
-# Test SQLite database backup and migration, applicable to Android only.
-[test_storage_mozStorage.js]
-skip-if = true || os != "android" # Bug 1171687: Needs fixing on Android
-
-# The following tests apply to any storage back-end.
-[test_context_menu.js]
-skip-if = os == "android" # The context menu isn't used on Android.
-# LoginManagerContextMenu is only included for MOZ_BUILD_APP == 'browser'.
-run-if = buildapp == "browser"
-[test_dedupeLogins.js]
-[test_disabled_hosts.js]
-[test_getFormFields.js]
-[test_getPasswordFields.js]
-[test_getPasswordOrigin.js]
-[test_isOriginMatching.js]
-[test_legacy_empty_formSubmitURL.js]
-[test_legacy_validation.js]
-[test_logins_change.js]
-[test_logins_decrypt_failure.js]
-skip-if = os == "android" # Bug 1171687: Needs fixing on Android
-[test_user_autocomplete_result.js]
-skip-if = os == "android"
-[test_logins_metainfo.js]
-[test_logins_search.js]
-[test_maybeImportLogin.js]
-[test_notifications.js]
-[test_OSCrypto_win.js]
-skip-if = os != "win"
-[test_recipes_add.js]
-[test_recipes_content.js]
-[test_search_schemeUpgrades.js]
-[test_storage.js]
-[test_telemetry.js]
diff --git a/toolkit/components/perf/chrome.ini b/toolkit/components/perf/chrome.ini
deleted file mode 100644
index eaa3c2401..000000000
--- a/toolkit/components/perf/chrome.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[test_pm.xul]
diff --git a/toolkit/components/perf/moz.build b/toolkit/components/perf/moz.build
index d153244c5..378d18feb 100644
--- a/toolkit/components/perf/moz.build
+++ b/toolkit/components/perf/moz.build
@@ -17,5 +17,3 @@ FINAL_LIBRARY = 'xul'
LOCAL_INCLUDES += [
'/js/xpconnect/loader',
]
-
-MOCHITEST_CHROME_MANIFESTS += ['chrome.ini']
diff --git a/toolkit/components/perf/test_pm.xul b/toolkit/components/perf/test_pm.xul
deleted file mode 100644
index 7dbf27b92..000000000
--- a/toolkit/components/perf/test_pm.xul
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
- - License, v. 2.0. If a copy of the MPL was not distributed with this
- - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<window title="Performance measurement tests"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test()">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
-
- <script type="application/javascript"><![CDATA[
-function test()
-{
- SimpleTest.waitForExplicitFinish();
-
- Components.utils.import("resource://gre/modules/PerfMeasurement.jsm");
- let pm = new PerfMeasurement(PerfMeasurement.ALL);
- if (pm.eventsMeasured == 0) {
- todo(false, "stub, skipping test");
- } else {
- pm.start();
- for (let i = 0; i < 10000; i++) ;
- pm.stop();
-
- events = ["cpu_cycles", "instructions", "cache_references", "cache_misses",
- "branch_instructions", "branch_misses", "bus_cycles", "page_faults",
- "major_page_faults", "context_switches", "cpu_migrations"];
-
- for (var i = 0; i < events.length; i++) {
- var e = events[i];
- ((pm.eventsMeasured & PerfMeasurement[e.toUpperCase()]) ? isnot : todo_is)(pm[e], -1, e);
- }
- }
- SimpleTest.finish();
-}
-]]></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
- <label id="test-result"/>
-</window>
diff --git a/toolkit/components/perfmonitoring/moz.build b/toolkit/components/perfmonitoring/moz.build
index 1effe5f00..53c73803e 100644
--- a/toolkit/components/perfmonitoring/moz.build
+++ b/toolkit/components/perfmonitoring/moz.build
@@ -4,10 +4,16 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-BROWSER_CHROME_MANIFESTS += ['tests/browser/browser.ini']
-
XPIDL_MODULE = 'toolkit_perfmonitoring'
+XPIDL_SOURCES += ['nsIPerformanceStats.idl']
+
+EXPORTS += ['nsPerformanceStats.h']
+
+LOCAL_INCLUDES += ['/dom/base']
+
+UNIFIED_SOURCES += ['nsPerformanceStats.cpp']
+
EXTRA_JS_MODULES += [
'AddonWatcher.jsm',
'PerformanceStats-content.js',
@@ -16,20 +22,4 @@ EXTRA_JS_MODULES += [
'PerformanceWatcher.jsm',
]
-XPIDL_SOURCES += [
- 'nsIPerformanceStats.idl',
-]
-
-UNIFIED_SOURCES += [
- 'nsPerformanceStats.cpp'
-]
-
-EXPORTS += [
- 'nsPerformanceStats.h'
-]
-
-LOCAL_INCLUDES += [
- '/dom/base',
-]
-
FINAL_LIBRARY = 'xul'
diff --git a/toolkit/components/perfmonitoring/tests/browser/.eslintrc.js b/toolkit/components/perfmonitoring/tests/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser.ini b/toolkit/components/perfmonitoring/tests/browser/browser.ini
deleted file mode 100644
index 7f4ac8514..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-head = head.js
-tags = addons
-support-files =
- browser_Addons_sample.xpi
- browser_compartments.html
- browser_compartments_frame.html
- browser_compartments_script.js
-
-[browser_AddonWatcher.js]
-[browser_compartments.js]
-skip-if = os == "linux" && !debug && e10s # Bug 1230018
-[browser_addonPerformanceAlerts.js]
-[browser_addonPerformanceAlerts_2.js]
-[browser_webpagePerformanceAlerts.js]
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_AddonWatcher.js b/toolkit/components/perfmonitoring/tests/browser/browser_AddonWatcher.js
deleted file mode 100644
index b4e80faa7..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_AddonWatcher.js
+++ /dev/null
@@ -1,151 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests for AddonWatcher.jsm
-
-"use strict";
-
-requestLongerTimeout(2);
-
-Cu.import("resource://gre/modules/Promise.jsm", this);
-Cu.import("resource://gre/modules/AddonManager.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-const ADDON_URL = "http://example.com/browser/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample.xpi";
-const ADDON_ID = "addonwatcher-test@mozilla.com";
-
-add_task(function* init() {
- info("Installing test add-on");
- let installer = yield new Promise(resolve => AddonManager.getInstallForURL(ADDON_URL, resolve, "application/x-xpinstall"));
- if (installer.error) {
- throw installer.error;
- }
- let installed = new Promise((resolve, reject) => installer.addListener({
- onInstallEnded: (_, addon) => resolve(addon),
- onInstallFailed: reject,
- onDownloadFailed: reject
- }));
-
- // We also need to wait for the add-on to report that it's ready
- // to be used in the test.
- let ready = TestUtils.topicObserved("test-addonwatcher-ready");
- installer.install();
-
- info("Waiting for installation to terminate");
- let addon = yield installed;
-
- yield ready;
-
- registerCleanupFunction(() => {
- info("Uninstalling test add-on");
- addon.uninstall()
- });
-
- Preferences.set("browser.addon-watch.warmup-ms", 0);
- Preferences.set("browser.addon-watch.freeze-threshold-micros", 0);
- Preferences.set("browser.addon-watch.jank-threshold-micros", 0);
- Preferences.set("browser.addon-watch.occurrences-between-alerts", 0);
- Preferences.set("browser.addon-watch.delay-between-alerts-ms", 0);
- Preferences.set("browser.addon-watch.delay-between-freeze-alerts-ms", 0);
- Preferences.set("browser.addon-watch.max-simultaneous-reports", 10000);
- Preferences.set("browser.addon-watch.deactivate-after-idle-ms", 100000000);
- registerCleanupFunction(() => {
- for (let k of [
- "browser.addon-watch.warmup-ms",
- "browser.addon-watch.freeze-threshold-micros",
- "browser.addon-watch.jank-threshold-micros",
- "browser.addon-watch.occurrences-between-alerts",
- "browser.addon-watch.delay-between-alerts-ms",
- "browser.addon-watch.delay-between-freeze-alerts-ms",
- "browser.addon-watch.max-simultaneous-reports",
- "browser.addon-watch.deactivate-after-idle-ms"
- ]) {
- Preferences.reset(k);
- }
- });
-
- let oldCanRecord = Services.telemetry.canRecordExtended;
- Services.telemetry.canRecordExtended = true;
- AddonWatcher.init();
-
- registerCleanupFunction(function () {
- AddonWatcher.paused = true;
- Services.telemetry.canRecordExtended = oldCanRecord;
- });
-});
-
-// Utility function to burn some resource, trigger a reaction of the add-on watcher
-// and check both its notification and telemetry.
-let burn_rubber = Task.async(function*({histogramName, topic, expectedMinSum}) {
- let detected = false;
- let observer = (_, topic, id) => {
- Assert.equal(id, ADDON_ID, "The add-on watcher has detected the misbehaving addon");
- detected = true;
- };
-
- try {
- info("Preparing add-on watcher");
-
- Services.obs.addObserver(observer, AddonWatcher.TOPIC_SLOW_ADDON_DETECTED, false);
-
- let histogram = Services.telemetry.getKeyedHistogramById(histogramName);
- histogram.clear();
- let snap1 = histogram.snapshot(ADDON_ID);
- Assert.equal(snap1.sum, 0, `Histogram ${histogramName} is initially empty for the add-on`);
-
- let histogramUpdated = false;
- do {
- info(`Burning some CPU with ${topic}. This should cause an add-on watcher notification`);
- yield new Promise(resolve => setTimeout(resolve, 100));
- Services.obs.notifyObservers(null, topic, "");
- yield new Promise(resolve => setTimeout(resolve, 100));
-
- let snap2 = histogram.snapshot(ADDON_ID);
- histogramUpdated = snap2.sum > 0;
- info(`For the moment, histogram ${histogramName} shows ${snap2.sum} => ${histogramUpdated}`);
- info(`For the moment, we have ${detected?"":"NOT "}detected the slow add-on`);
- } while (!histogramUpdated || !detected);
-
- let snap3 = histogram.snapshot(ADDON_ID);
- Assert.ok(snap3.sum >= expectedMinSum, `Histogram ${histogramName} recorded a gravity of ${snap3.sum}, expecting at least ${expectedMinSum}.`);
- } finally {
- Services.obs.removeObserver(observer, AddonWatcher.TOPIC_SLOW_ADDON_DETECTED);
- }
-});
-
-// Test that burning CPU will cause the add-on watcher to notice that
-// the add-on is misbehaving.
-add_task(function* test_burn_CPU() {
- yield burn_rubber({
- histogramName: "PERF_MONITORING_SLOW_ADDON_JANK_US",
- topic: "test-addonwatcher-burn-some-cpu",
- expectedMinSum: 7,
- });
-});
-
-// Test that burning content CPU will cause the add-on watcher to notice that
-// the add-on is misbehaving.
-/*
-Blocked by bug 1227283.
-add_task(function* test_burn_content_CPU() {
- yield burn_rubber({
- histogramName: "PERF_MONITORING_SLOW_ADDON_JANK_US",
- topic: "test-addonwatcher-burn-some-content-cpu",
- expectedMinSum: 7,
- });
-});
-*/
-
-// Test that burning CPOW will cause the add-on watcher to notice that
-// the add-on is misbehaving.
-add_task(function* test_burn_CPOW() {
- if (!gMultiProcessBrowser) {
- info("This is a single-process Firefox, we can't test for CPOW");
- return;
- }
- yield burn_rubber({
- histogramName: "PERF_MONITORING_SLOW_ADDON_CPOW_US",
- topic: "test-addonwatcher-burn-some-cpow",
- expectedMinSum: 400,
- });
-});
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample.xpi b/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample.xpi
deleted file mode 100644
index ae5bcc5ff..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample.xpi
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/bootstrap.js b/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/bootstrap.js
deleted file mode 100644
index 9a5575827..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/bootstrap.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Sample for browser_AddonWatcher.js
-
-"use strict";
-
-const {utils: Cu, classes: Cc, interfaces: Ci} = Components;
-
-const TOPIC_BURNCPU = "test-addonwatcher-burn-some-cpu";
-const TOPIC_BURNCPOW = "test-addonwatcher-burn-some-cpow";
-const TOPIC_BURNCONTENTCPU = "test-addonwatcher-burn-some-content-cpu";
-const TOPIC_READY = "test-addonwatcher-ready";
-
-const MESSAGE_BURNCPOW = "test-addonwatcher-cpow:init";
-const URL_FRAMESCRIPT = "chrome://addonwatcher-test/content/framescript.js";
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-const { setTimeout } = Cu.import("resource://gre/modules/Timer.jsm", {});
-Cu.import("resource://gre/modules/Task.jsm", this);
-
-let globalMM = Cc["@mozilla.org/globalmessagemanager;1"]
- .getService(Ci.nsIMessageListenerManager);
-
-/**
- * Spend some time using CPU.
- */
-function burnCPU() {
- let ignored = [];
- let start = Date.now();
- let i = 0;
- while (Date.now() - start < 1000) {
- ignored[i++ % 2] = i;
- }
-}
-
-/**
- * Spend some time in CPOW.
- */
-function burnCPOW() {
- gBurnCPOW();
-}
-let gBurnCPOW = null;
-
-function burnContentCPU() {
- setTimeout(() => { try {
- gBurnContentCPU()
- } catch (ex) {
- dump(`test-addon error: ${ex}\n`);
- } }, 0);
-}
-let gBurnContentCPU = null;
-
-let gTab = null;
-let gTabBrowser = null;
-
-function startup() {
- Services.obs.addObserver(burnCPU, TOPIC_BURNCPU, false);
- Services.obs.addObserver(burnCPOW, TOPIC_BURNCPOW, false);
- Services.obs.addObserver(burnContentCPU, TOPIC_BURNCONTENTCPU, false);
-
- let windows = Services.wm.getEnumerator("navigator:browser");
- let win = windows.getNext();
- gTabBrowser = win.gBrowser;
- gTab = gTabBrowser.addTab("about:robots");
- gBurnContentCPU = function() {
- gTab.linkedBrowser.messageManager.sendAsyncMessage("test-addonwatcher-burn-some-content-cpu", {});
- }
-
- gTab.linkedBrowser.messageManager.loadFrameScript(URL_FRAMESCRIPT, false);
- globalMM.loadFrameScript(URL_FRAMESCRIPT, false);
-
- if (Services.appinfo.browserTabsRemoteAutostart) {
- // This profile has e10s enabled, which means we'll want to
- // test CPOW traffic.
- globalMM.addMessageListener("test-addonwatcher-cpow:init", function waitForCPOW(msg) {
- if (Components.utils.isCrossProcessWrapper(msg.objects.burnCPOW)) {
- gBurnCPOW = msg.objects.burnCPOW;
- globalMM.removeMessageListener("test-addonwatcher-cpow:init", waitForCPOW);
- Services.obs.notifyObservers(null, TOPIC_READY, null);
- } else {
- Cu.reportError("test-addonwatcher-cpow:init didn't give us a CPOW! Expect timeouts.");
- }
- });
- } else {
- // e10s is not enabled, so a CPOW is not necessary - we can report ready
- // right away.
- Services.obs.notifyObservers(null, TOPIC_READY, null);
- }
-}
-
-function shutdown() {
- Services.obs.removeObserver(burnCPU, TOPIC_BURNCPU);
- Services.obs.removeObserver(burnCPOW, TOPIC_BURNCPOW);
- Services.obs.removeObserver(burnContentCPU, TOPIC_BURNCONTENTCPU);
- gTabBrowser.removeTab(gTab);
-}
-
-function install() {
- // Nothing to do
-}
-
-function uninstall() {
- // Nothing to do
-}
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/build.sh b/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/build.sh
deleted file mode 100644
index 28d52ea3a..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/build.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-echo "Rebuilding browser_Addons_sample.xpi..."
-zip -r ../browser_Addons_sample.xpi .
-echo "
-Done! Don't forget to sign it: https://wiki.mozilla.org/EngineeringProductivity/HowTo/SignExtensions" \ No newline at end of file
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/chrome.manifest b/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/chrome.manifest
deleted file mode 100644
index 9f53da861..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/chrome.manifest
+++ /dev/null
@@ -1 +0,0 @@
-content addonwatcher-test content/
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/content/framescript.js b/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/content/framescript.js
deleted file mode 100644
index e7ebc2a61..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/content/framescript.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-function burnCPOW(msg) {
- dump(`Addon: content burnCPU start ${Math.sin(Math.random())}\n`);
- let start = content.performance.now();
- let ignored = [];
- while (content.performance.now() - start < 5000) {
- ignored[ignored.length % 2] = ignored.length;
- }
- dump(`Addon: content burnCPU done: ${content.performance.now() - start}\n`);
-}
-
-if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
- sendAsyncMessage("test-addonwatcher-cpow:init", {}, {burnCPOW});
-}
-
-addMessageListener("test-addonwatcher-burn-some-content-cpu", burnCPOW);
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/install.rdf b/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/install.rdf
deleted file mode 100644
index cae10ace6..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_Addons_sample/install.rdf
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
- <Description about="urn:mozilla:install-manifest">
- <em:id>addonwatcher-test@mozilla.com</em:id>
- <em:version>1.1</em:version>
-
- <em:targetApplication>
- <Description>
- <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
- <em:minVersion>0.3</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>1</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <em:bootstrap>true</em:bootstrap>
-
- <em:name>Sample for browser_AddonWatcher.js</em:name>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts.js b/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts.js
deleted file mode 100644
index af78f0074..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts.js
+++ /dev/null
@@ -1,91 +0,0 @@
-"use strict";
-
-/**
- * Tests for PerformanceWatcher watching slow addons.
- */
-
-add_task(function* init() {
- // Get rid of buffering.
- let service = Cc["@mozilla.org/toolkit/performance-stats-service;1"].getService(
- Ci.nsIPerformanceStatsService);
- let oldDelay = service.jankAlertBufferingDelay;
-
- service.jankAlertBufferingDelay = 0 /* ms */;
- registerCleanupFunction(() => {
- info("Cleanup");
- service.jankAlertBufferingDelay = oldDelay;
- });
-});
-
-add_task(function* test_install_addon_then_watch_it() {
- for (let topic of ["burnCPU", "promiseBurnContentCPU", "promiseBurnCPOW"]) {
- info(`Starting subtest ${topic}`);
- info("Spawning fake add-on, making sure that the compartment is initialized");
- let addon = new AddonBurner();
- yield addon.promiseInitialized;
- addon.burnCPU();
-
- info(`Check that burning CPU triggers the real listener, but not the fake listener ${topic}`);
- let realListener = new AddonListener(addon.addonId, (group, details) => {
- if (group.addonId == addon.addonId) {
- return details.highestJank;
- }
- throw new Error(`I shouldn't have been called with addon ${group.addonId}`);
- });
- let fakeListener = new AddonListener(addon.addonId + "-fake-" + Math.random(), group => true); // This listener should never be triggered.
- let universalListener = new AddonListener("*", alerts => {
- info(`AddonListener: received alerts ${JSON.stringify(alerts)}`);
- let alert = alerts.find(({source}) => {
- return source.addonId == addon.addonId;
- });
- if (alert) {
- info(`AddonListener: I found an alert for ${addon.addonId}`);
- return alert.details.highestJank;
- }
- info(`AddonListener: I didn't find any alert for ${addon.addonId}`);
- return null;
- });
-
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
- yield addon.run(topic, 10, realListener);
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
-
- Assert.ok(realListener.triggered, `1. The real listener was triggered ${topic}`);
- Assert.ok(universalListener.triggered, `1. The universal listener was triggered ${topic}`);
- Assert.ok(!fakeListener.triggered, `1. The fake listener was not triggered ${topic}`);
- Assert.ok(realListener.result >= addon.jankThreshold, `1. jank is at least ${addon.jankThreshold/1000}ms (${realListener.result/1000}ms) ${topic}`);
-
- info(`Attempting to remove a performance listener incorrectly, check that this does not hurt our real listener ${topic}`);
- Assert.throws(() => PerformanceWatcher.removePerformanceListener({addonId: addon.addonId}, () => {}));
- Assert.throws(() => PerformanceWatcher.removePerformanceListener({addonId: addon.addonId + "-unbound-id-" + Math.random()}, realListener.listener));
-
- yield addon.run(topic, 10, realListener);
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 300));
-
- Assert.ok(realListener.triggered, `2. The real listener was triggered ${topic}`);
- Assert.ok(universalListener.triggered, `2. The universal listener was triggered ${topic}`);
- Assert.ok(!fakeListener.triggered, `2. The fake listener was not triggered ${topic}`);
- Assert.ok(realListener.result >= 200000, `2. jank is at least 300ms (${realListener.result/1000}ms) ${topic}`);
-
- info(`Attempting to remove correctly, check if the listener is still triggered ${topic}`);
- realListener.unregister();
- yield addon.run(topic, 3, realListener);
- Assert.ok(!realListener.triggered, `3. After being unregistered, the real listener was not triggered ${topic}`);
- Assert.ok(universalListener.triggered, `3. The universal listener is still triggered ${topic}`);
-
- info("Unregistering universal listener");
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
- universalListener.unregister();
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
- yield addon.run(topic, 3, realListener);
- Assert.ok(!universalListener.triggered, `4. After being unregistered, the universal listener is not triggered ${topic}`);
-
- fakeListener.unregister();
- addon.dispose();
- }
-});
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts_2.js b/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts_2.js
deleted file mode 100644
index d39c38b1f..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_addonPerformanceAlerts_2.js
+++ /dev/null
@@ -1,25 +0,0 @@
-"use strict";
-
-/**
- * Tests for PerformanceWatcher watching slow addons.
- */
-
-add_task(function* test_watch_addon_then_install_it() {
- for (let topic of ["burnCPU", "promiseBurnContentCPU", "promiseBurnCPOW"]) {
- let addonId = "addon:test_watch_addons_before_installing" + Math.random();
- let realListener = new AddonListener(addonId, (group, details) => {
- if (group.addonId == addonId) {
- return details.highestJank;
- }
- throw new Error(`I shouldn't have been called with addon ${group.addonId}`);
- });
-
- info("Now install the add-on, *after* having installed the listener");
- let addon = new AddonBurner(addonId);
-
- Assert.ok((yield addon.run(topic, 10, realListener)), `5. The real listener was triggered ${topic}`);
- Assert.ok(realListener.result >= addon.jankThreshold, `5. jank is at least ${addon.jankThreshold/1000}ms (${realListener.result}µs) ${topic}`);
- realListener.unregister();
- addon.dispose();
- }
-});
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.html b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.html
deleted file mode 100644
index d7ee6c418..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>
- Main frame for test browser_compartments.js
- </title>
-</head>
-<body>
-Main frame.
-
-<iframe src="browser_compartments_frame.html?frame=1">
- Subframe 1
-</iframe>
-
-<iframe src="browser_compartments_frame.html?frame=2">
- Subframe 2.
-</iframe>
-
-</body>
-</html>
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js b/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js
deleted file mode 100644
index f04fefb33..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_compartments.js
+++ /dev/null
@@ -1,312 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-/**
- * Test that we see jank that takes place in a webpage,
- * and that jank from several iframes are actually charged
- * to the top window.
- */
-Cu.import("resource://gre/modules/PerformanceStats.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://testing-common/ContentTask.jsm", this);
-
-
-const URL = "http://example.com/browser/toolkit/components/perfmonitoring/tests/browser/browser_compartments.html?test=" + Math.random();
-const PARENT_TITLE = `Main frame for test browser_compartments.js ${Math.random()}`;
-const FRAME_TITLE = `Subframe for test browser_compartments.js ${Math.random()}`;
-
-const PARENT_PID = Services.appinfo.processID;
-
-// This function is injected as source as a frameScript
-function frameScript() {
- try {
- "use strict";
-
- const { utils: Cu, classes: Cc, interfaces: Ci } = Components;
- Cu.import("resource://gre/modules/PerformanceStats.jsm");
- Cu.import("resource://gre/modules/Services.jsm");
-
- // Make sure that the stopwatch is now active.
- let monitor = PerformanceStats.getMonitor(["jank", "cpow", "ticks", "compartments"]);
-
- addMessageListener("compartments-test:getStatistics", () => {
- try {
- monitor.promiseSnapshot().then(snapshot => {
- sendAsyncMessage("compartments-test:getStatistics", {snapshot, pid: Services.appinfo.processID});
- });
- } catch (ex) {
- Cu.reportError("Error in content (getStatistics): " + ex);
- Cu.reportError(ex.stack);
- }
- });
-
- addMessageListener("compartments-test:setTitles", titles => {
- try {
- content.document.title = titles.data.parent;
- for (let i = 0; i < content.frames.length; ++i) {
- content.frames[i].postMessage({title: titles.data.frames}, "*");
- }
- console.log("content", "Done setting titles", content.document.title);
- sendAsyncMessage("compartments-test:setTitles");
- } catch (ex) {
- Cu.reportError("Error in content (setTitles): " + ex);
- Cu.reportError(ex.stack);
- }
- });
- } catch (ex) {
- Cu.reportError("Error in content (setup): " + ex);
- Cu.reportError(ex.stack);
- }
-}
-
-// A variant of `Assert` that doesn't spam the logs
-// in case of success.
-var SilentAssert = {
- equal: function(a, b, msg) {
- if (a == b) {
- return;
- }
- Assert.equal(a, b, msg);
- },
- notEqual: function(a, b, msg) {
- if (a != b) {
- return;
- }
- Assert.notEqual(a, b, msg);
- },
- ok: function(a, msg) {
- if (a) {
- return;
- }
- Assert.ok(a, msg);
- },
- leq: function(a, b, msg) {
- this.ok(a <= b, `${msg}: ${a} <= ${b}`);
- }
-};
-
-var isShuttingDown = false;
-function monotinicity_tester(source, testName) {
- // In the background, check invariants:
- // - numeric data can only ever increase;
- // - the name, addonId, isSystem of a component never changes;
- // - the name, addonId, isSystem of the process data;
- // - there is at most one component with a combination of `name` and `addonId`;
- // - types, etc.
- let previous = {
- processData: null,
- componentsMap: new Map(),
- };
-
- let sanityCheck = function(prev, next) {
- if (prev == null) {
- return;
- }
- for (let k of ["groupId", "addonId", "isSystem"]) {
- SilentAssert.equal(prev[k], next[k], `Sanity check (${testName}): ${k} hasn't changed (${prev.name}).`);
- }
- for (let [probe, k] of [
- ["jank", "totalUserTime"],
- ["jank", "totalSystemTime"],
- ["cpow", "totalCPOWTime"],
- ["ticks", "ticks"]
- ]) {
- SilentAssert.equal(typeof next[probe][k], "number", `Sanity check (${testName}): ${k} is a number.`);
- SilentAssert.leq(prev[probe][k], next[probe][k], `Sanity check (${testName}): ${k} is monotonic.`);
- SilentAssert.leq(0, next[probe][k], `Sanity check (${testName}): ${k} is >= 0.`)
- }
- SilentAssert.equal(prev.jank.durations.length, next.jank.durations.length);
- for (let i = 0; i < next.jank.durations.length; ++i) {
- SilentAssert.ok(typeof next.jank.durations[i] == "number" && next.jank.durations[i] >= 0,
- `Sanity check (${testName}): durations[${i}] is a non-negative number.`);
- SilentAssert.leq(prev.jank.durations[i], next.jank.durations[i],
- `Sanity check (${testName}): durations[${i}] is monotonic.`);
- }
- for (let i = 0; i < next.jank.durations.length - 1; ++i) {
- SilentAssert.leq(next.jank.durations[i + 1], next.jank.durations[i],
- `Sanity check (${testName}): durations[${i}] >= durations[${i + 1}].`)
- }
- };
- let iteration = 0;
- let frameCheck = Task.async(function*() {
- if (isShuttingDown) {
- window.clearInterval(interval);
- return;
- }
- let name = `${testName}: ${iteration++}`;
- let result = yield source();
- if (!result) {
- // This can happen at the end of the test when we attempt
- // to communicate too late with the content process.
- window.clearInterval(interval);
- return;
- }
- let {pid, snapshot} = result;
-
- // Sanity check on the process data.
- sanityCheck(previous.processData, snapshot.processData);
- SilentAssert.equal(snapshot.processData.isSystem, true);
- SilentAssert.equal(snapshot.processData.name, "<process>");
- SilentAssert.equal(snapshot.processData.addonId, "");
- SilentAssert.equal(snapshot.processData.processId, pid);
- previous.procesData = snapshot.processData;
-
- // Sanity check on components data.
- let map = new Map();
- for (let item of snapshot.componentsData) {
- for (let [probe, k] of [
- ["jank", "totalUserTime"],
- ["jank", "totalSystemTime"],
- ["cpow", "totalCPOWTime"]
- ]) {
- // Note that we cannot expect components data to be always smaller
- // than process data, as `getrusage` & co are not monotonic.
- SilentAssert.leq(item[probe][k], 3 * snapshot.processData[probe][k],
- `Sanity check (${name}): ${k} of component is not impossibly larger than that of process`);
- }
-
- let isCorrectPid = (item.processId == pid && !item.isChildProcess)
- || (item.processId != pid && item.isChildProcess);
- SilentAssert.ok(isCorrectPid, `Pid check (${name}): the item comes from the right process`);
-
- let key = item.groupId;
- if (map.has(key)) {
- let old = map.get(key);
- Assert.ok(false, `Component ${key} has already been seen. Latest: ${item.addonId||item.name}, previous: ${old.addonId||old.name}`);
- }
- map.set(key, item);
- }
- for (let item of snapshot.componentsData) {
- if (!item.parentId) {
- continue;
- }
- let parent = map.get(item.parentId);
- SilentAssert.ok(parent, `The parent exists ${item.parentId}`);
-
- for (let [probe, k] of [
- ["jank", "totalUserTime"],
- ["jank", "totalSystemTime"],
- ["cpow", "totalCPOWTime"]
- ]) {
- // Note that we cannot expect components data to be always smaller
- // than parent data, as `getrusage` & co are not monotonic.
- SilentAssert.leq(item[probe][k], 2 * parent[probe][k],
- `Sanity check (${testName}): ${k} of component is not impossibly larger than that of parent`);
- }
- }
- for (let [key, item] of map) {
- sanityCheck(previous.componentsMap.get(key), item);
- previous.componentsMap.set(key, item);
- }
- });
- let interval = window.setInterval(frameCheck, 300);
- registerCleanupFunction(() => {
- window.clearInterval(interval);
- });
-}
-
-add_task(function* test() {
- let monitor = PerformanceStats.getMonitor(["jank", "cpow", "ticks"]);
-
- info("Extracting initial state");
- let stats0 = yield monitor.promiseSnapshot();
- Assert.notEqual(stats0.componentsData.length, 0, "There is more than one component");
- Assert.ok(!stats0.componentsData.find(stat => stat.name.indexOf(URL) != -1),
- "The url doesn't appear yet");
-
- let newTab = gBrowser.addTab();
- let browser = newTab.linkedBrowser;
- // Setup monitoring in the tab
- info("Setting up monitoring in the tab");
- yield ContentTask.spawn(newTab.linkedBrowser, null, frameScript);
-
- info("Opening URL");
- newTab.linkedBrowser.loadURI(URL);
-
- if (Services.sysinfo.getPropertyAsAString("name") == "Windows_NT") {
- info("Deactivating sanity checks under Windows (bug 1151240)");
- } else {
- info("Setting up sanity checks");
- monotinicity_tester(() => monitor.promiseSnapshot().then(snapshot => ({snapshot, pid: PARENT_PID})), "parent process");
- monotinicity_tester(() => promiseContentResponseOrNull(browser, "compartments-test:getStatistics", null), "content process" );
- }
-
- let skipTotalUserTime = hasLowPrecision();
-
-
- while (true) {
- yield new Promise(resolve => setTimeout(resolve, 100));
-
- // We may have race conditions with DOM loading.
- // Don't waste too much brainpower here, let's just ask
- // repeatedly for the title to be changed, until this works.
- info("Setting titles");
- yield promiseContentResponse(browser, "compartments-test:setTitles", {
- parent: PARENT_TITLE,
- frames: FRAME_TITLE
- });
- info("Titles set");
-
- let {snapshot: stats} = (yield promiseContentResponse(browser, "compartments-test:getStatistics", null));
-
- // Attach titles to components.
- let titles = [];
- let map = new Map();
- let windows = Services.wm.getEnumerator("navigator:browser");
- while (windows.hasMoreElements()) {
- let window = windows.getNext();
- let tabbrowser = window.gBrowser;
- for (let browser of tabbrowser.browsers) {
- let id = browser.outerWindowID; // May be `null` if the browser isn't loaded yet
- if (id != null) {
- map.set(id, browser);
- }
- }
- }
- for (let stat of stats.componentsData) {
- if (!stat.windowId) {
- continue;
- }
- let browser = map.get(stat.windowId);
- if (!browser) {
- continue;
- }
- let title = browser.contentTitle;
- if (title) {
- stat.title = title;
- titles.push(title);
- }
- }
-
- // While the webpage consists in three compartments, we should see only
- // one `PerformanceData` in `componentsData`. Its `name` is undefined
- // (could be either the main frame or one of its subframes), but its
- // `title` should be the title of the main frame.
- info(`Searching for frame title '${FRAME_TITLE}' in ${JSON.stringify(titles)} (I hope not to find it)`);
- Assert.ok(!titles.includes(FRAME_TITLE), "Searching by title, the frames don't show up in the list of components");
-
- info(`Searching for window title '${PARENT_TITLE}' in ${JSON.stringify(titles)} (I hope to find it)`);
- let parent = stats.componentsData.find(x => x.title == PARENT_TITLE);
- if (!parent) {
- info("Searching by title, we didn't find the main frame");
- continue;
- }
- info("Found the main frame");
-
- if (skipTotalUserTime) {
- info("Not looking for total user time on this platform, we're done");
- break;
- } else if (parent.jank.totalUserTime > 1000) {
- info("Enough CPU time detected, we're done");
- break;
- } else {
- info(`Not enough CPU time detected: ${parent.jank.totalUserTime}`);
- }
- }
- isShuttingDown = true;
-
- // Cleanup
- gBrowser.removeTab(newTab, {skipPermitUnload: true});
-});
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_compartments_frame.html b/toolkit/components/perfmonitoring/tests/browser/browser_compartments_frame.html
deleted file mode 100644
index 69edfe871..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_compartments_frame.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>
- Subframe for test browser_compartments.html (do not change this title)
- </title>
- <script src="browser_compartments_script.js"></script>
-</head>
-<body>
-Subframe loaded.
-</body>
-</html>
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_compartments_script.js b/toolkit/components/perfmonitoring/tests/browser/browser_compartments_script.js
deleted file mode 100644
index 3d5f7114f..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_compartments_script.js
+++ /dev/null
@@ -1,29 +0,0 @@
-
-var carryOn = true;
-
-window.addEventListener("message", e => {
- console.log("frame content", "message", e);
- if ("title" in e.data) {
- document.title = e.data.title;
- }
- if ("stop" in e.data) {
- carryOn = false;
- }
-});
-
-// Use some CPU.
-var interval = window.setInterval(() => {
- if (!carryOn) {
- window.clearInterval(interval);
- return;
- }
-
- // Compute an arbitrary value, print it out to make sure that the JS
- // engine doesn't discard all our computation.
- var date = Date.now();
- var array = [];
- var i = 0;
- while (Date.now() - date <= 100) {
- array[i%2] = i++;
- }
-}, 300);
diff --git a/toolkit/components/perfmonitoring/tests/browser/browser_webpagePerformanceAlerts.js b/toolkit/components/perfmonitoring/tests/browser/browser_webpagePerformanceAlerts.js
deleted file mode 100644
index eb908c8db..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/browser_webpagePerformanceAlerts.js
+++ /dev/null
@@ -1,111 +0,0 @@
-"use strict";
-
-/**
- * Tests for PerformanceWatcher watching slow web pages.
- */
-
- /**
- * Simulate a slow webpage.
- */
-function WebpageBurner() {
- CPUBurner.call(this, "http://example.com/browser/toolkit/components/perfmonitoring/tests/browser/browser_compartments.html?test=" + Math.random(), 300000);
-}
-WebpageBurner.prototype = Object.create(CPUBurner.prototype);
-WebpageBurner.prototype.promiseBurnContentCPU = function() {
- return promiseContentResponse(this._browser, "test-performance-watcher:burn-content-cpu", {});
-};
-
-function WebpageListener(windowId, accept) {
- info(`Creating WebpageListener for ${windowId}`);
- AlertListener.call(this, accept, {
- register: () => PerformanceWatcher.addPerformanceListener({windowId}, this.listener),
- unregister: () => PerformanceWatcher.removePerformanceListener({windowId}, this.listener)
- });
-}
-WebpageListener.prototype = Object.create(AlertListener.prototype);
-
-add_task(function* init() {
- // Get rid of buffering.
- let service = Cc["@mozilla.org/toolkit/performance-stats-service;1"].getService(
- Ci.nsIPerformanceStatsService);
- let oldDelay = service.jankAlertBufferingDelay;
-
- service.jankAlertBufferingDelay = 0 /* ms */;
- registerCleanupFunction(() => {
- info("Cleanup");
- service.jankAlertBufferingDelay = oldDelay;
- });
-});
-
-add_task(function* test_open_window_then_watch_it() {
- let burner = new WebpageBurner();
- yield burner.promiseInitialized;
- yield burner.promiseBurnContentCPU();
-
- info(`Check that burning CPU triggers the real listener, but not the fake listener`);
- let realListener = new WebpageListener(burner.windowId, (group, details) => {
- info(`test: realListener for ${burner.tab.linkedBrowser.outerWindowID}: ${group}, ${details}\n`);
- Assert.equal(group.windowId, burner.windowId, "We should not receive data meant for another group");
- return details;
- }); // This listener should be triggered.
-
- info(`Creating fake burner`);
- let otherTab = gBrowser.addTab();
- yield BrowserTestUtils.browserLoaded(otherTab.linkedBrowser);
- info(`Check that burning CPU triggers the real listener, but not the fake listener`);
- let fakeListener = new WebpageListener(otherTab.linkedBrowser.outerWindowID, group => group.windowId == burner.windowId); // This listener should never be triggered.
- let universalListener = new WebpageListener(0, alerts =>
- alerts.find(alert => alert.source.windowId == burner.windowId)
- );
-
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
-
- yield burner.run("promiseBurnContentCPU", 20, realListener);
- Assert.ok(realListener.triggered, `1. The real listener was triggered`);
- Assert.ok(universalListener.triggered, `1. The universal listener was triggered`);
- Assert.ok(!fakeListener.triggered, `1. The fake listener was not triggered`);
-
- if (realListener.result) {
- Assert.ok(realListener.result.highestJank >= 300, `1. jank is at least 300ms (${realListener.result.highestJank}ms)`);
- }
-
- info(`Attempting to remove a performance listener incorrectly, check that this does not hurt our real listener`);
- Assert.throws(() => PerformanceWatcher.removePerformanceListener({addonId: addon.addonId}, () => {}));
- Assert.throws(() => PerformanceWatcher.removePerformanceListener({addonId: addon.addonId + "-unbound-id-" + Math.random()}, realListener.listener));
-
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
- yield burner.run("promiseBurnContentCPU", 20, realListener);
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
-
- Assert.ok(realListener.triggered, `2. The real listener was triggered`);
- Assert.ok(universalListener.triggered, `2. The universal listener was triggered`);
- Assert.ok(!fakeListener.triggered, `2. The fake listener was not triggered`);
- if (realListener.result) {
- Assert.ok(realListener.result.highestJank >= 300, `2. jank is at least 300ms (${realListener.jank}ms)`);
- }
-
- info(`Attempting to remove correctly, check if the listener is still triggered`);
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
- realListener.unregister();
-
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
- yield burner.run("promiseBurnContentCPU", 3, realListener);
- Assert.ok(!realListener.triggered, `3. After being unregistered, the real listener was not triggered`);
- Assert.ok(universalListener.triggered, `3. The universal listener is still triggered`);
-
- universalListener.unregister();
-
- // Waiting a little – listeners are buffered.
- yield new Promise(resolve => setTimeout(resolve, 100));
- yield burner.run("promiseBurnContentCPU", 3, realListener);
- Assert.ok(!universalListener.triggered, `4. After being unregistered, the universal listener is not triggered`);
-
- fakeListener.unregister();
- burner.dispose();
- gBrowser.removeTab(otherTab);
-});
diff --git a/toolkit/components/perfmonitoring/tests/browser/head.js b/toolkit/components/perfmonitoring/tests/browser/head.js
deleted file mode 100644
index 92258fd1b..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/head.js
+++ /dev/null
@@ -1,287 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var { utils: Cu, interfaces: Ci, classes: Cc } = Components;
-
-Cu.import("resource://gre/modules/Promise.jsm", this);
-Cu.import("resource://gre/modules/AddonManager.jsm", this);
-Cu.import("resource://gre/modules/AddonWatcher.jsm", this);
-Cu.import("resource://gre/modules/PerformanceWatcher.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://testing-common/ContentTaskUtils.jsm", this);
-
-/**
- * Base class for simulating slow addons/webpages.
- */
-function CPUBurner(url, jankThreshold) {
- info(`CPUBurner: Opening tab for ${url}\n`);
- this.url = url;
- this.tab = gBrowser.addTab(url);
- this.jankThreshold = jankThreshold;
- let browser = this.tab.linkedBrowser;
- this._browser = browser;
- ContentTask.spawn(this._browser, null, CPUBurner.frameScript);
- this.promiseInitialized = BrowserTestUtils.browserLoaded(browser);
-}
-CPUBurner.prototype = {
- get windowId() {
- return this._browser.outerWindowID;
- },
- /**
- * Burn CPU until it triggers a listener with the specified jank threshold.
- */
- run: Task.async(function*(burner, max, listener) {
- listener.reset();
- for (let i = 0; i < max; ++i) {
- yield new Promise(resolve => setTimeout(resolve, 50));
- try {
- yield this[burner]();
- } catch (ex) {
- return false;
- }
- if (listener.triggered && listener.result >= this.jankThreshold) {
- return true;
- }
- }
- return false;
- }),
- dispose: function() {
- info(`CPUBurner: Closing tab for ${this.url}\n`);
- gBrowser.removeTab(this.tab);
- }
-};
-// This function is injected in all frames
-CPUBurner.frameScript = function() {
- try {
- "use strict";
-
- const { utils: Cu, classes: Cc, interfaces: Ci } = Components;
- let sandboxes = new Map();
- let getSandbox = function(addonId) {
- let sandbox = sandboxes.get(addonId);
- if (!sandbox) {
- sandbox = Components.utils.Sandbox(Services.scriptSecurityManager.getSystemPrincipal(), { addonId });
- sandboxes.set(addonId, sandbox);
- }
- return sandbox;
- };
-
- let burnCPU = function() {
- var start = Date.now();
- var ignored = [];
- while (Date.now() - start < 500) {
- ignored[ignored.length % 2] = ignored.length;
- }
- };
- let burnCPUInSandbox = function(addonId) {
- let sandbox = getSandbox(addonId);
- Cu.evalInSandbox(burnCPU.toSource() + "()", sandbox);
- };
-
- {
- let topic = "test-performance-watcher:burn-content-cpu";
- addMessageListener(topic, function(msg) {
- try {
- if (msg.data && msg.data.addonId) {
- burnCPUInSandbox(msg.data.addonId);
- } else {
- burnCPU();
- }
- sendAsyncMessage(topic, {});
- } catch (ex) {
- dump(`This is the content attempting to burn CPU: error ${ex}\n`);
- dump(`${ex.stack}\n`);
- }
- });
- }
-
- // Bind the function to the global context or it might be GC'd during test
- // causing failures (bug 1230027)
- this.burnCPOWInSandbox = function(addonId) {
- try {
- burnCPUInSandbox(addonId);
- } catch (ex) {
- dump(`This is the addon attempting to burn CPOW: error ${ex}\n`);
- dump(`${ex.stack}\n`);
- }
- }
-
- sendAsyncMessage("test-performance-watcher:cpow-init", {}, {
- burnCPOWInSandbox: this.burnCPOWInSandbox
- });
-
- } catch (ex) {
- Cu.reportError("This is the addon: error " + ex);
- Cu.reportError(ex.stack);
- }
-};
-
-/**
- * Base class for listening to slow group alerts
- */
-function AlertListener(accept, {register, unregister}) {
- this.listener = (...args) => {
- if (this._unregistered) {
- throw new Error("Listener was unregistered");
- }
- let result = accept(...args);
- if (!result) {
- return;
- }
- this.result = result;
- this.triggered = true;
- return;
- };
- this.triggered = false;
- this.result = null;
- this._unregistered = false;
- this._unregister = unregister;
- registerCleanupFunction(() => {
- this.unregister();
- });
- register();
-}
-AlertListener.prototype = {
- unregister: function() {
- this.reset();
- if (this._unregistered) {
- info(`head.js: No need to unregister, we're already unregistered.\n`);
- return;
- }
- info(`head.js: Unregistering listener.\n`);
- this._unregistered = true;
- this._unregister();
- info(`head.js: Unregistration complete.\n`);
- },
- reset: function() {
- this.triggered = false;
- this.result = null;
- },
-};
-
-/**
- * Simulate a slow add-on.
- */
-function AddonBurner(addonId = "fake add-on id: " + Math.random()) {
- this.jankThreshold = 200000;
- CPUBurner.call(this, `http://example.com/?uri=${addonId}`, this.jankThreshold);
- this._addonId = addonId;
- this._sandbox = Components.utils.Sandbox(Services.scriptSecurityManager.getSystemPrincipal(), { addonId: this._addonId });
- this._CPOWBurner = null;
-
- this._promiseCPOWBurner = new Promise(resolve => {
- this._browser.messageManager.addMessageListener("test-performance-watcher:cpow-init", msg => {
- // Note that we cannot resolve Promises with CPOWs now that they
- // have been outlawed in bug 1233497, so we stash it in the
- // AddonBurner instance instead.
- this._CPOWBurner = msg.objects.burnCPOWInSandbox;
- resolve();
- });
- });
-}
-AddonBurner.prototype = Object.create(CPUBurner.prototype);
-Object.defineProperty(AddonBurner.prototype, "addonId", {
- get: function() {
- return this._addonId;
- }
-});
-
-/**
- * Simulate slow code being executed by the add-on in the chrome.
- */
-AddonBurner.prototype.burnCPU = function() {
- Cu.evalInSandbox(AddonBurner.burnCPU.toSource() + "()", this._sandbox);
-};
-
-/**
- * Simulate slow code being executed by the add-on in a CPOW.
- */
-AddonBurner.prototype.promiseBurnCPOW = Task.async(function*() {
- yield this._promiseCPOWBurner;
- ok(this._CPOWBurner, "Got the CPOW burner");
- let burner = this._CPOWBurner;
- info("Parent: Preparing to burn CPOW");
- try {
- yield burner(this._addonId);
- info("Parent: Done burning CPOW");
- } catch (ex) {
- info(`Parent: Error burning CPOW: ${ex}\n`);
- info(ex.stack + "\n");
- }
-});
-
-/**
- * Simulate slow code being executed by the add-on in the content.
- */
-AddonBurner.prototype.promiseBurnContentCPU = function() {
- return promiseContentResponse(this._browser, "test-performance-watcher:burn-content-cpu", {addonId: this._addonId});
-};
-AddonBurner.burnCPU = function() {
- var start = Date.now();
- var ignored = [];
- while (Date.now() - start < 500) {
- ignored[ignored.length % 2] = ignored.length;
- }
-};
-
-
-function AddonListener(addonId, accept) {
- let target = {addonId};
- AlertListener.call(this, accept, {
- register: () => {
- info(`AddonListener: registering ${JSON.stringify(target, null, "\t")}`);
- PerformanceWatcher.addPerformanceListener({addonId}, this.listener);
- },
- unregister: () => {
- info(`AddonListener: unregistering ${JSON.stringify(target, null, "\t")}`);
- PerformanceWatcher.removePerformanceListener({addonId}, this.listener);
- }
- });
-}
-AddonListener.prototype = Object.create(AlertListener.prototype);
-
-function promiseContentResponse(browser, name, message) {
- let mm = browser.messageManager;
- let promise = new Promise(resolve => {
- function removeListener() {
- mm.removeMessageListener(name, listener);
- }
-
- function listener(msg) {
- removeListener();
- resolve(msg.data);
- }
-
- mm.addMessageListener(name, listener);
- registerCleanupFunction(removeListener);
- });
- mm.sendAsyncMessage(name, message);
- return promise;
-}
-function promiseContentResponseOrNull(browser, name, message) {
- if (!browser.messageManager) {
- return null;
- }
- return promiseContentResponse(browser, name, message);
-}
-
-/**
- * `true` if we are running an OS in which the OS performance
- * clock has a low precision and might unpredictably
- * never be updated during the execution of the test.
- */
-function hasLowPrecision() {
- let [sysName, sysVersion] = [Services.sysinfo.getPropertyAsAString("name"), Services.sysinfo.getPropertyAsDouble("version")];
- info(`Running ${sysName} version ${sysVersion}`);
-
- if (sysName == "Windows_NT" && sysVersion < 6) {
- info("Running old Windows, need to deactivate tests due to bad precision.");
- return true;
- }
- if (sysName == "Linux" && sysVersion <= 2.6) {
- info("Running old Linux, need to deactivate tests due to bad precision.");
- return true;
- }
- info("This platform has good precision.")
- return false;
-}
diff --git a/toolkit/components/perfmonitoring/tests/browser/install.rdf b/toolkit/components/perfmonitoring/tests/browser/install.rdf
deleted file mode 100644
index 65add014f..000000000
--- a/toolkit/components/perfmonitoring/tests/browser/install.rdf
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
- <Description about="urn:mozilla:install-manifest">
- <em:id>addonwatcher-test@mozilla.com</em:id>
- <em:version>1.0</em:version>
-
- <em:targetApplication>
- <Description>
- <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
- <em:minVersion>0.3</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>1</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <em:bootstrap>true</em:bootstrap>
-
- <em:name>Sample for browser_AddonWatcher.js</em:name>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/places/moz.build b/toolkit/components/places/moz.build
index 478b18e02..0d0ea7768 100644
--- a/toolkit/components/places/moz.build
+++ b/toolkit/components/places/moz.build
@@ -4,9 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-if CONFIG['MOZ_PLACES']:
- TEST_DIRS += ['tests']
-
XPIDL_SOURCES += [
'nsINavHistoryService.idl',
]
@@ -93,8 +90,5 @@ if CONFIG['MOZ_PLACES']:
include('/ipc/chromium/chromium-config.mozbuild')
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Places')
-
if CONFIG['GNU_CXX']:
CXXFLAGS += ['-Wno-error=shadow']
diff --git a/toolkit/components/places/tests/.eslintrc.js b/toolkit/components/places/tests/.eslintrc.js
deleted file mode 100644
index d5283c966..000000000
--- a/toolkit/components/places/tests/.eslintrc.js
+++ /dev/null
@@ -1,9 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/mochitest.eslintrc.js",
- "../../../../testing/mochitest/chrome.eslintrc.js",
- "../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/PlacesTestUtils.jsm b/toolkit/components/places/tests/PlacesTestUtils.jsm
deleted file mode 100644
index 36e425cae..000000000
--- a/toolkit/components/places/tests/PlacesTestUtils.jsm
+++ /dev/null
@@ -1,163 +0,0 @@
-"use strict";
-
-this.EXPORTED_SYMBOLS = [
- "PlacesTestUtils",
-];
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.importGlobalProperties(["URL"]);
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
- "resource://gre/modules/PlacesUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-
-this.PlacesTestUtils = Object.freeze({
- /**
- * Asynchronously adds visits to a page.
- *
- * @param aPlaceInfo
- * Can be an nsIURI, in such a case a single LINK visit will be added.
- * Otherwise can be an object describing the visit to add, or an array
- * of these objects:
- * { uri: nsIURI of the page,
- * [optional] transition: one of the TRANSITION_* from nsINavHistoryService,
- * [optional] title: title of the page,
- * [optional] visitDate: visit date, either in microseconds from the epoch or as a date object
- * [optional] referrer: nsIURI of the referrer for this visit
- * }
- *
- * @return {Promise}
- * @resolves When all visits have been added successfully.
- * @rejects JavaScript exception.
- */
- addVisits: Task.async(function* (placeInfo) {
- let places = [];
- let infos = [];
-
- if (placeInfo instanceof Ci.nsIURI ||
- placeInfo instanceof URL ||
- typeof placeInfo == "string") {
- places.push({ uri: placeInfo });
- }
- else if (Array.isArray(placeInfo)) {
- places = places.concat(placeInfo);
- } else if (typeof placeInfo == "object" && placeInfo.uri) {
- places.push(placeInfo)
- } else {
- throw new Error("Unsupported type passed to addVisits");
- }
-
- // Create a PageInfo for each entry.
- for (let place of places) {
- let info = {url: place.uri};
- info.title = (typeof place.title === "string") ? place.title : "test visit for " + info.url.spec ;
- if (typeof place.referrer == "string") {
- place.referrer = NetUtil.newURI(place.referrer);
- } else if (place.referrer && place.referrer instanceof URL) {
- place.referrer = NetUtil.newURI(place.referrer.href);
- }
- let visitDate = place.visitDate;
- if (visitDate) {
- if (!(visitDate instanceof Date)) {
- visitDate = PlacesUtils.toDate(visitDate);
- }
- } else {
- visitDate = new Date();
- }
- info.visits = [{
- transition: place.transition,
- date: visitDate,
- referrer: place.referrer
- }];
- infos.push(info);
- }
- return PlacesUtils.history.insertMany(infos);
- }),
-
- /**
- * Clear all history.
- *
- * @return {Promise}
- * @resolves When history was cleared successfully.
- * @rejects JavaScript exception.
- */
- clearHistory() {
- let expirationFinished = new Promise(resolve => {
- Services.obs.addObserver(function observe(subj, topic, data) {
- Services.obs.removeObserver(observe, topic);
- resolve();
- }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
- });
-
- return Promise.all([expirationFinished, PlacesUtils.history.clear()]);
- },
-
- /**
- * Waits for all pending async statements on the default connection.
- *
- * @return {Promise}
- * @resolves When all pending async statements finished.
- * @rejects Never.
- *
- * @note The result is achieved by asynchronously executing a query requiring
- * a write lock. Since all statements on the same connection are
- * serialized, the end of this write operation means that all writes are
- * complete. Note that WAL makes so that writers don't block readers, but
- * this is a problem only across different connections.
- */
- promiseAsyncUpdates() {
- return PlacesUtils.withConnectionWrapper("promiseAsyncUpdates", Task.async(function* (db) {
- try {
- yield db.executeCached("BEGIN EXCLUSIVE");
- yield db.executeCached("COMMIT");
- } catch (ex) {
- // If we fail to start a transaction, it's because there is already one.
- // In such a case we should not try to commit the existing transaction.
- }
- }));
- },
-
- /**
- * Asynchronously checks if an address is found in the database.
- * @param aURI
- * nsIURI or address to look for.
- *
- * @return {Promise}
- * @resolves Returns true if the page is found.
- * @rejects JavaScript exception.
- */
- isPageInDB: Task.async(function* (aURI) {
- let url = aURI instanceof Ci.nsIURI ? aURI.spec : aURI;
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.executeCached(
- "SELECT id FROM moz_places WHERE url_hash = hash(:url) AND url = :url",
- { url });
- return rows.length > 0;
- }),
-
- /**
- * Asynchronously checks how many visits exist for a specified page.
- * @param aURI
- * nsIURI or address to look for.
- *
- * @return {Promise}
- * @resolves Returns the number of visits found.
- * @rejects JavaScript exception.
- */
- visitsInDB: Task.async(function* (aURI) {
- let url = aURI instanceof Ci.nsIURI ? aURI.spec : aURI;
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.executeCached(
- `SELECT count(*) FROM moz_historyvisits v
- JOIN moz_places h ON h.id = v.place_id
- WHERE url_hash = hash(:url) AND url = :url`,
- { url });
- return rows[0].getResultByIndex(0);
- })
-});
diff --git a/toolkit/components/places/tests/bookmarks/.eslintrc.js b/toolkit/components/places/tests/bookmarks/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/bookmarks/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/bookmarks/head_bookmarks.js b/toolkit/components/places/tests/bookmarks/head_bookmarks.js
deleted file mode 100644
index 842a66b31..000000000
--- a/toolkit/components/places/tests/bookmarks/head_bookmarks.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
diff --git a/toolkit/components/places/tests/bookmarks/test_1016953-renaming-uncompressed.js b/toolkit/components/places/tests/bookmarks/test_1016953-renaming-uncompressed.js
deleted file mode 100644
index b6982987b..000000000
--- a/toolkit/components/places/tests/bookmarks/test_1016953-renaming-uncompressed.js
+++ /dev/null
@@ -1,103 +0,0 @@
-function run_test() {
- run_next_test();
-}
-
-/* Bug 1016953 - When a previous bookmark backup exists with the same hash
-regardless of date, an automatic backup should attempt to either rename it to
-today's date if the backup was for an old date or leave it alone if it was for
-the same date. However if the file ext was json it will accidentally rename it
-to jsonlz4 while keeping the json contents
-*/
-
-add_task(function* test_same_date_same_hash() {
- // If old file has been created on the same date and has the same hash
- // the file should be left alone
- let backupFolder = yield PlacesBackups.getBackupFolder();
- // Save to profile dir to obtain hash and nodeCount to append to filename
- let tempPath = OS.Path.join(OS.Constants.Path.profileDir,
- "bug10169583_bookmarks.json");
- let {count, hash} = yield BookmarkJSONUtils.exportToFile(tempPath);
-
- // Save JSON file in backup folder with hash appended
- let dateObj = new Date();
- let filename = "bookmarks-" + PlacesBackups.toISODateString(dateObj) + "_" +
- count + "_" + hash + ".json";
- let backupFile = OS.Path.join(backupFolder, filename);
- yield OS.File.move(tempPath, backupFile);
-
- // Force a compressed backup which fallbacks to rename
- yield PlacesBackups.create();
- let mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup();
- // check to ensure not renamed to jsonlz4
- Assert.equal(mostRecentBackupFile, backupFile);
- // inspect contents and check if valid json
- let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
- createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- let result = yield OS.File.read(mostRecentBackupFile);
- let jsonString = converter.convertFromByteArray(result, result.length);
- do_print("Check is valid JSON");
- JSON.parse(jsonString);
-
- // Cleanup
- yield OS.File.remove(backupFile);
- yield OS.File.remove(tempPath);
- PlacesBackups._backupFiles = null; // To force re-cache of backupFiles
-});
-
-add_task(function* test_same_date_diff_hash() {
- // If the old file has been created on the same date, but has a different hash
- // the existing file should be overwritten with the newer compressed version
- let backupFolder = yield PlacesBackups.getBackupFolder();
- let tempPath = OS.Path.join(OS.Constants.Path.profileDir,
- "bug10169583_bookmarks.json");
- let {count} = yield BookmarkJSONUtils.exportToFile(tempPath);
- let dateObj = new Date();
- let filename = "bookmarks-" + PlacesBackups.toISODateString(dateObj) + "_" +
- count + "_" + "differentHash==" + ".json";
- let backupFile = OS.Path.join(backupFolder, filename);
- yield OS.File.move(tempPath, backupFile);
- yield PlacesBackups.create(); // Force compressed backup
- mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup();
-
- // Decode lz4 compressed file to json and check if json is valid
- let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
- createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- let result = yield OS.File.read(mostRecentBackupFile, { compression: "lz4" });
- let jsonString = converter.convertFromByteArray(result, result.length);
- do_print("Check is valid JSON");
- JSON.parse(jsonString);
-
- // Cleanup
- yield OS.File.remove(mostRecentBackupFile);
- yield OS.File.remove(tempPath);
- PlacesBackups._backupFiles = null; // To force re-cache of backupFiles
-});
-
-add_task(function* test_diff_date_same_hash() {
- // If the old file has been created on an older day but has the same hash
- // it should be renamed with today's date without altering the contents.
- let backupFolder = yield PlacesBackups.getBackupFolder();
- let tempPath = OS.Path.join(OS.Constants.Path.profileDir,
- "bug10169583_bookmarks.json");
- let {count, hash} = yield BookmarkJSONUtils.exportToFile(tempPath);
- let oldDate = new Date(2014, 1, 1);
- let curDate = new Date();
- let oldFilename = "bookmarks-" + PlacesBackups.toISODateString(oldDate) + "_" +
- count + "_" + hash + ".json";
- let newFilename = "bookmarks-" + PlacesBackups.toISODateString(curDate) + "_" +
- count + "_" + hash + ".json";
- let backupFile = OS.Path.join(backupFolder, oldFilename);
- let newBackupFile = OS.Path.join(backupFolder, newFilename);
- yield OS.File.move(tempPath, backupFile);
-
- // Ensure file has been renamed correctly
- yield PlacesBackups.create();
- let mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup();
- Assert.equal(mostRecentBackupFile, newBackupFile);
-
- // Cleanup
- yield OS.File.remove(mostRecentBackupFile);
- yield OS.File.remove(tempPath);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_1017502-bookmarks_foreign_count.js b/toolkit/components/places/tests/bookmarks/test_1017502-bookmarks_foreign_count.js
deleted file mode 100644
index 13755e576..000000000
--- a/toolkit/components/places/tests/bookmarks/test_1017502-bookmarks_foreign_count.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Bug 1017502 - Add a foreign_count column to moz_places
-This tests, tests the triggers that adjust the foreign_count when a bookmark is
-added or removed and also the maintenance task to fix wrong counts.
-*/
-
-const T_URI = NetUtil.newURI("https://www.mozilla.org/firefox/nightly/firstrun/");
-
-function* getForeignCountForURL(conn, url) {
- yield PlacesTestUtils.promiseAsyncUpdates();
- url = url instanceof Ci.nsIURI ? url.spec : url;
- let rows = yield conn.executeCached(
- `SELECT foreign_count FROM moz_places WHERE url_hash = hash(:t_url)
- AND url = :t_url`, { t_url: url });
- return rows[0].getResultByName("foreign_count");
-}
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* add_remove_change_bookmark_test() {
- let conn = yield PlacesUtils.promiseDBConnection();
-
- // Simulate a visit to the url
- yield PlacesTestUtils.addVisits(T_URI);
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 0);
-
- // Add 1st bookmark which should increment foreign_count by 1
- let id1 = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- T_URI, PlacesUtils.bookmarks.DEFAULT_INDEX, "First Run");
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 1);
-
- // Add 2nd bookmark
- let id2 = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
- T_URI, PlacesUtils.bookmarks.DEFAULT_INDEX, "First Run");
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 2);
-
- // Remove 2nd bookmark which should decrement foreign_count by 1
- PlacesUtils.bookmarks.removeItem(id2);
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 1);
-
- // Change first bookmark's URI
- const URI2 = NetUtil.newURI("http://www.mozilla.org");
- PlacesUtils.bookmarks.changeBookmarkURI(id1, URI2);
- // Check foreign count for original URI
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 0);
- // Check foreign count for new URI
- Assert.equal((yield getForeignCountForURL(conn, URI2)), 1);
-
- // Cleanup - Remove changed bookmark
- let id = PlacesUtils.bookmarks.getBookmarkIdsForURI(URI2);
- PlacesUtils.bookmarks.removeItem(id);
- Assert.equal((yield getForeignCountForURL(conn, URI2)), 0);
-
-});
-
-add_task(function* maintenance_foreign_count_test() {
- let conn = yield PlacesUtils.promiseDBConnection();
-
- // Simulate a visit to the url
- yield PlacesTestUtils.addVisits(T_URI);
-
- // Adjust the foreign_count for the added entry to an incorrect value
- let deferred = Promise.defer();
- let stmt = DBConn().createAsyncStatement(
- `UPDATE moz_places SET foreign_count = 10 WHERE url_hash = hash(:t_url)
- AND url = :t_url `);
- stmt.params.t_url = T_URI.spec;
- stmt.executeAsync({
- handleCompletion: function() {
- deferred.resolve();
- }
- });
- stmt.finalize();
- yield deferred.promise;
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 10);
-
- // Run maintenance
- Components.utils.import("resource://gre/modules/PlacesDBUtils.jsm");
- let promiseMaintenanceFinished =
- promiseTopicObserved("places-maintenance-finished");
- PlacesDBUtils.maintenanceOnIdle();
- yield promiseMaintenanceFinished;
-
- // Check if the foreign_count has been adjusted to the correct value
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 0);
-});
-
-add_task(function* add_remove_tags_test() {
- let conn = yield PlacesUtils.promiseDBConnection();
-
- yield PlacesTestUtils.addVisits(T_URI);
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 0);
-
- // Check foreign count incremented by 1 for a single tag
- PlacesUtils.tagging.tagURI(T_URI, ["test tag"]);
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 1);
-
- // Check foreign count is incremented by 2 for two tags
- PlacesUtils.tagging.tagURI(T_URI, ["one", "two"]);
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 3);
-
- // Check foreign count is set to 0 when all tags are removed
- PlacesUtils.tagging.untagURI(T_URI, ["test tag", "one", "two"]);
- Assert.equal((yield getForeignCountForURL(conn, T_URI)), 0);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_1129529.js b/toolkit/components/places/tests/bookmarks/test_1129529.js
deleted file mode 100644
index da1ff708f..000000000
--- a/toolkit/components/places/tests/bookmarks/test_1129529.js
+++ /dev/null
@@ -1,76 +0,0 @@
-var now = Date.now() * 1000;
-
-// Test that importing bookmark data where a bookmark has a tag longer than 100
-// chars imports everything except the tags for that bookmark.
-add_task(function* () {
- let aData = {
- guid: "root________",
- index: 0,
- id: 1,
- type: "text/x-moz-place-container",
- dateAdded: now,
- lastModified: now,
- root: "placesRoot",
- children: [{
- guid: "unfiled_____",
- index: 0,
- id: 2,
- type: "text/x-moz-place-container",
- dateAdded: now,
- lastModified: now,
- root: "unfiledBookmarksFolder",
- children: [
- {
- guid: "___guid1____",
- index: 0,
- id: 3,
- charset: "UTF-8",
- tags: "tag0",
- type: "text/x-moz-place",
- dateAdded: now,
- lastModified: now,
- uri: "http://test0.com/"
- },
- {
- guid: "___guid2____",
- index: 1,
- id: 4,
- charset: "UTF-8",
- tags: "tag1," + "a" + "0123456789".repeat(10), // 101 chars
- type: "text/x-moz-place",
- dateAdded: now,
- lastModified: now,
- uri: "http://test1.com/"
- },
- {
- guid: "___guid3____",
- index: 2,
- id: 5,
- charset: "UTF-8",
- tags: "tag2",
- type: "text/x-moz-place",
- dateAdded: now,
- lastModified: now,
- uri: "http://test2.com/"
- }
- ]
- }]
- };
-
- let contentType = "application/json";
- let uri = "data:" + contentType + "," + JSON.stringify(aData);
- yield BookmarkJSONUtils.importFromURL(uri, false);
-
- let [bookmarks] = yield PlacesBackups.getBookmarksTree();
- let unsortedBookmarks = bookmarks.children[2].children;
- Assert.equal(unsortedBookmarks.length, 3);
-
- for (let i = 0; i < unsortedBookmarks.length; ++i) {
- let bookmark = unsortedBookmarks[i];
- Assert.equal(bookmark.charset, "UTF-8");
- Assert.equal(bookmark.dateAdded, now);
- Assert.equal(bookmark.lastModified, now);
- Assert.equal(bookmark.uri, "http://test" + i + ".com/");
- Assert.equal(bookmark.tags, "tag" + i);
- }
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_384228.js b/toolkit/components/places/tests/bookmarks/test_384228.js
deleted file mode 100644
index 9a52c9746..000000000
--- a/toolkit/components/places/tests/bookmarks/test_384228.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * test querying for bookmarks in multiple folders.
- */
-add_task(function* search_bookmark_in_folder() {
- let testFolder1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "bug 384228 test folder 1"
- });
- Assert.equal(testFolder1.index, 0);
-
- let testFolder2 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "bug 384228 test folder 2"
- });
- Assert.equal(testFolder2.index, 1);
-
- let testFolder3 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "bug 384228 test folder 3"
- });
- Assert.equal(testFolder3.index, 2);
-
- let b1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: testFolder1.guid,
- url: "http://foo.tld/",
- title: "title b1 (folder 1)"
- });
- Assert.equal(b1.index, 0);
-
- let b2 = yield PlacesUtils.bookmarks.insert({
- parentGuid: testFolder1.guid,
- url: "http://foo.tld/",
- title: "title b2 (folder 1)"
- });
- Assert.equal(b2.index, 1);
-
- let b3 = yield PlacesUtils.bookmarks.insert({
- parentGuid: testFolder2.guid,
- url: "http://foo.tld/",
- title: "title b3 (folder 2)"
- });
- Assert.equal(b3.index, 0);
-
- let b4 = yield PlacesUtils.bookmarks.insert({
- parentGuid: testFolder3.guid,
- url: "http://foo.tld/",
- title: "title b4 (folder 3)"
- });
- Assert.equal(b4.index, 0);
-
- // also test recursive search
- let testFolder1_1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: testFolder1.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "bug 384228 test folder 1.1"
- });
- Assert.equal(testFolder1_1.index, 2);
-
- let b5 = yield PlacesUtils.bookmarks.insert({
- parentGuid: testFolder1_1.guid,
- url: "http://foo.tld/",
- title: "title b5 (folder 1.1)"
- });
- Assert.equal(b5.index, 0);
-
-
- // query folder 1, folder 2 and get 4 bookmarks
- let folderIds = [];
- folderIds.push(yield PlacesUtils.promiseItemId(testFolder1.guid));
- folderIds.push(yield PlacesUtils.promiseItemId(testFolder2.guid));
-
- let hs = PlacesUtils.history;
- let options = hs.getNewQueryOptions();
- let query = hs.getNewQuery();
- query.searchTerms = "title";
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- query.setFolders(folderIds, folderIds.length);
- let rootNode = hs.executeQuery(query, options).root;
- rootNode.containerOpen = true;
-
- // should not match item from folder 3
- Assert.equal(rootNode.childCount, 4);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b1.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b2.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b3.guid);
- Assert.equal(rootNode.getChild(3).bookmarkGuid, b5.guid);
-
- rootNode.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_385829.js b/toolkit/components/places/tests/bookmarks/test_385829.js
deleted file mode 100644
index 63beee5f3..000000000
--- a/toolkit/components/places/tests/bookmarks/test_385829.js
+++ /dev/null
@@ -1,182 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* search_bookmark_by_lastModified_dateDated() {
- // test search on folder with various sorts and max results
- // see bug #385829 for more details
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "bug 385829 test"
- });
-
- let now = new Date();
- // ensure some unique values for date added and last modified
- // for date added: b1 < b2 < b3 < b4
- // for last modified: b1 > b2 > b3 > b4
- let b1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder.guid,
- url: "http://a1.com/",
- title: "1 title",
- dateAdded: new Date(now.getTime() + 1000)
- });
- let b2 = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder.guid,
- url: "http://a2.com/",
- title: "2 title",
- dateAdded: new Date(now.getTime() + 2000)
- });
- let b3 = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder.guid,
- url: "http://a3.com/",
- title: "3 title",
- dateAdded: new Date(now.getTime() + 3000)
- });
- let b4 = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder.guid,
- url: "http://a4.com/",
- title: "4 title",
- dateAdded: new Date(now.getTime() + 4000)
- });
-
- // make sure lastModified is larger than dateAdded
- let modifiedTime = new Date(now.getTime() + 5000);
- yield PlacesUtils.bookmarks.update({
- guid: b1.guid,
- lastModified: new Date(modifiedTime.getTime() + 4000)
- });
- yield PlacesUtils.bookmarks.update({
- guid: b2.guid,
- lastModified: new Date(modifiedTime.getTime() + 3000)
- });
- yield PlacesUtils.bookmarks.update({
- guid: b3.guid,
- lastModified: new Date(modifiedTime.getTime() + 2000)
- });
- yield PlacesUtils.bookmarks.update({
- guid: b4.guid,
- lastModified: new Date(modifiedTime.getTime() + 1000)
- });
-
- let hs = PlacesUtils.history;
- let options = hs.getNewQueryOptions();
- let query = hs.getNewQuery();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- options.maxResults = 3;
- let folderIds = [];
- folderIds.push(yield PlacesUtils.promiseItemId(folder.guid));
- query.setFolders(folderIds, 1);
-
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
-
- // test SORT_BY_DATEADDED_ASCENDING (live update)
- result.sortingMode = options.SORT_BY_DATEADDED_ASCENDING;
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b1.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b2.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b3.guid);
- Assert.ok(rootNode.getChild(0).dateAdded <
- rootNode.getChild(1).dateAdded);
- Assert.ok(rootNode.getChild(1).dateAdded <
- rootNode.getChild(2).dateAdded);
-
- // test SORT_BY_DATEADDED_DESCENDING (live update)
- result.sortingMode = options.SORT_BY_DATEADDED_DESCENDING;
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b3.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b2.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b1.guid);
- Assert.ok(rootNode.getChild(0).dateAdded >
- rootNode.getChild(1).dateAdded);
- Assert.ok(rootNode.getChild(1).dateAdded >
- rootNode.getChild(2).dateAdded);
-
- // test SORT_BY_LASTMODIFIED_ASCENDING (live update)
- result.sortingMode = options.SORT_BY_LASTMODIFIED_ASCENDING;
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b3.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b2.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b1.guid);
- Assert.ok(rootNode.getChild(0).lastModified <
- rootNode.getChild(1).lastModified);
- Assert.ok(rootNode.getChild(1).lastModified <
- rootNode.getChild(2).lastModified);
-
- // test SORT_BY_LASTMODIFIED_DESCENDING (live update)
- result.sortingMode = options.SORT_BY_LASTMODIFIED_DESCENDING;
-
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b1.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b2.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b3.guid);
- Assert.ok(rootNode.getChild(0).lastModified >
- rootNode.getChild(1).lastModified);
- Assert.ok(rootNode.getChild(1).lastModified >
- rootNode.getChild(2).lastModified);
- rootNode.containerOpen = false;
-
- // test SORT_BY_DATEADDED_ASCENDING
- options.sortingMode = options.SORT_BY_DATEADDED_ASCENDING;
- result = hs.executeQuery(query, options);
- rootNode = result.root;
- rootNode.containerOpen = true;
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b1.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b2.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b3.guid);
- Assert.ok(rootNode.getChild(0).dateAdded <
- rootNode.getChild(1).dateAdded);
- Assert.ok(rootNode.getChild(1).dateAdded <
- rootNode.getChild(2).dateAdded);
- rootNode.containerOpen = false;
-
- // test SORT_BY_DATEADDED_DESCENDING
- options.sortingMode = options.SORT_BY_DATEADDED_DESCENDING;
- result = hs.executeQuery(query, options);
- rootNode = result.root;
- rootNode.containerOpen = true;
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b4.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b3.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b2.guid);
- Assert.ok(rootNode.getChild(0).dateAdded >
- rootNode.getChild(1).dateAdded);
- Assert.ok(rootNode.getChild(1).dateAdded >
- rootNode.getChild(2).dateAdded);
- rootNode.containerOpen = false;
-
- // test SORT_BY_LASTMODIFIED_ASCENDING
- options.sortingMode = options.SORT_BY_LASTMODIFIED_ASCENDING;
- result = hs.executeQuery(query, options);
- rootNode = result.root;
- rootNode.containerOpen = true;
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b4.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b3.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b2.guid);
- Assert.ok(rootNode.getChild(0).lastModified <
- rootNode.getChild(1).lastModified);
- Assert.ok(rootNode.getChild(1).lastModified <
- rootNode.getChild(2).lastModified);
- rootNode.containerOpen = false;
-
- // test SORT_BY_LASTMODIFIED_DESCENDING
- options.sortingMode = options.SORT_BY_LASTMODIFIED_DESCENDING;
- result = hs.executeQuery(query, options);
- rootNode = result.root;
- rootNode.containerOpen = true;
- Assert.equal(rootNode.childCount, 3);
- Assert.equal(rootNode.getChild(0).bookmarkGuid, b1.guid);
- Assert.equal(rootNode.getChild(1).bookmarkGuid, b2.guid);
- Assert.equal(rootNode.getChild(2).bookmarkGuid, b3.guid);
- Assert.ok(rootNode.getChild(0).lastModified >
- rootNode.getChild(1).lastModified);
- Assert.ok(rootNode.getChild(1).lastModified >
- rootNode.getChild(2).lastModified);
- rootNode.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_388695.js b/toolkit/components/places/tests/bookmarks/test_388695.js
deleted file mode 100644
index 4e313c52f..000000000
--- a/toolkit/components/places/tests/bookmarks/test_388695.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get bookmark service
-try {
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-} catch (ex) {
- do_throw("Could not get nav-bookmarks-service\n");
-}
-
-var gTestRoot;
-var gURI;
-var gItemId1;
-var gItemId2;
-
-// main
-function run_test() {
- gURI = uri("http://foo.tld.com/");
- gTestRoot = bmsvc.createFolder(bmsvc.placesRoot, "test folder",
- bmsvc.DEFAULT_INDEX);
-
- // test getBookmarkIdsForURI
- // getBookmarkIdsForURI sorts by the most recently added/modified (descending)
- //
- // we cannot rely on dateAdded growing when doing so in a simple iteration,
- // see PR_Now() documentation
- do_test_pending();
-
- gItemId1 = bmsvc.insertBookmark(gTestRoot, gURI, bmsvc.DEFAULT_INDEX, "");
- do_timeout(100, phase2);
-}
-
-function phase2() {
- gItemId2 = bmsvc.insertBookmark(gTestRoot, gURI, bmsvc.DEFAULT_INDEX, "");
- var b = bmsvc.getBookmarkIdsForURI(gURI);
- do_check_eq(b[0], gItemId2);
- do_check_eq(b[1], gItemId1);
- do_timeout(100, phase3);
-}
-
-function phase3() {
- // trigger last modified change
- bmsvc.setItemTitle(gItemId1, "");
- var b = bmsvc.getBookmarkIdsForURI(gURI);
- do_check_eq(b[0], gItemId1);
- do_check_eq(b[1], gItemId2);
- do_test_finished();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_393498.js b/toolkit/components/places/tests/bookmarks/test_393498.js
deleted file mode 100644
index 601f77a0a..000000000
--- a/toolkit/components/places/tests/bookmarks/test_393498.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var observer = {
- __proto__: NavBookmarkObserver.prototype,
-
- onItemAdded: function (id, folder, index) {
- this._itemAddedId = id;
- this._itemAddedParent = folder;
- this._itemAddedIndex = index;
- },
- onItemChanged: function (id, property, isAnnotationProperty, value) {
- this._itemChangedId = id;
- this._itemChangedProperty = property;
- this._itemChanged_isAnnotationProperty = isAnnotationProperty;
- this._itemChangedValue = value;
- }
-};
-PlacesUtils.bookmarks.addObserver(observer, false);
-
-do_register_cleanup(function () {
- PlacesUtils.bookmarks.removeObserver(observer);
-});
-
-function run_test() {
- // We set times in the past to workaround a timing bug due to virtual
- // machines and the skew between PR_Now() and Date.now(), see bug 427142 and
- // bug 858377 for details.
- const PAST_PRTIME = (Date.now() - 86400000) * 1000;
-
- // Insert a new bookmark.
- let testFolder = PlacesUtils.bookmarks.createFolder(
- PlacesUtils.placesRootId, "test Folder",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- let bookmarkId = PlacesUtils.bookmarks.insertBookmark(
- testFolder, uri("http://google.com/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, "");
-
- // Sanity check.
- do_check_true(observer.itemChangedProperty === undefined);
-
- // Set dateAdded in the past and verify the bookmarks cache.
- PlacesUtils.bookmarks.setItemDateAdded(bookmarkId, PAST_PRTIME);
- do_check_eq(observer._itemChangedProperty, "dateAdded");
- do_check_eq(observer._itemChangedValue, PAST_PRTIME);
- let dateAdded = PlacesUtils.bookmarks.getItemDateAdded(bookmarkId);
- do_check_eq(dateAdded, PAST_PRTIME);
-
- // After just inserting, modified should be the same as dateAdded.
- do_check_eq(PlacesUtils.bookmarks.getItemLastModified(bookmarkId), dateAdded);
-
- // Set lastModified in the past and verify the bookmarks cache.
- PlacesUtils.bookmarks.setItemLastModified(bookmarkId, PAST_PRTIME);
- do_check_eq(observer._itemChangedProperty, "lastModified");
- do_check_eq(observer._itemChangedValue, PAST_PRTIME);
- do_check_eq(PlacesUtils.bookmarks.getItemLastModified(bookmarkId),
- PAST_PRTIME);
-
- // Set bookmark title
- PlacesUtils.bookmarks.setItemTitle(bookmarkId, "Google");
-
- // Test notifications.
- do_check_eq(observer._itemChangedId, bookmarkId);
- do_check_eq(observer._itemChangedProperty, "title");
- do_check_eq(observer._itemChangedValue, "Google");
-
- // Check lastModified has been updated.
- is_time_ordered(PAST_PRTIME,
- PlacesUtils.bookmarks.getItemLastModified(bookmarkId));
-
- // Check that node properties are updated.
- let root = PlacesUtils.getFolderContents(testFolder).root;
- do_check_eq(root.childCount, 1);
- let childNode = root.getChild(0);
-
- // confirm current dates match node properties
- do_check_eq(PlacesUtils.bookmarks.getItemDateAdded(bookmarkId),
- childNode.dateAdded);
- do_check_eq(PlacesUtils.bookmarks.getItemLastModified(bookmarkId),
- childNode.lastModified);
-
- // Test live update of lastModified when setting title.
- PlacesUtils.bookmarks.setItemLastModified(bookmarkId, PAST_PRTIME);
- PlacesUtils.bookmarks.setItemTitle(bookmarkId, "Google");
-
- // Check lastModified has been updated.
- is_time_ordered(PAST_PRTIME, childNode.lastModified);
- // Test that node value matches db value.
- do_check_eq(PlacesUtils.bookmarks.getItemLastModified(bookmarkId),
- childNode.lastModified);
-
- // Test live update of the exposed date apis.
- PlacesUtils.bookmarks.setItemDateAdded(bookmarkId, PAST_PRTIME);
- do_check_eq(childNode.dateAdded, PAST_PRTIME);
- PlacesUtils.bookmarks.setItemLastModified(bookmarkId, PAST_PRTIME);
- do_check_eq(childNode.lastModified, PAST_PRTIME);
-
- root.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_395101.js b/toolkit/components/places/tests/bookmarks/test_395101.js
deleted file mode 100644
index a507e7361..000000000
--- a/toolkit/components/places/tests/bookmarks/test_395101.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get bookmark service
-try {
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Ci.nsINavBookmarksService);
-} catch (ex) {
- do_throw("Could not get nav-bookmarks-service\n");
-}
-
-// Get history service
-try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsINavHistoryService);
-} catch (ex) {
- do_throw("Could not get history service\n");
-}
-
-// Get tagging service
-try {
- var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-} catch (ex) {
- do_throw("Could not get tagging service\n");
-}
-
-// get bookmarks root id
-var root = bmsvc.bookmarksMenuFolder;
-
-// main
-function run_test() {
- // test searching for tagged bookmarks
-
- // test folder
- var folder = bmsvc.createFolder(root, "bug 395101 test", bmsvc.DEFAULT_INDEX);
-
- // create a bookmark
- var testURI = uri("http://a1.com");
- var b1 = bmsvc.insertBookmark(folder, testURI,
- bmsvc.DEFAULT_INDEX, "1 title");
-
- // tag the bookmarked URI
- tagssvc.tagURI(testURI, ["elephant", "walrus", "giraffe", "turkey", "hiPPo", "BABOON", "alf"]);
-
- // search for the bookmark, using a tag
- var query = histsvc.getNewQuery();
- query.searchTerms = "elephant";
- var options = histsvc.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- query.setFolders([folder], 1);
-
- var result = histsvc.executeQuery(query, options);
- var rootNode = result.root;
- rootNode.containerOpen = true;
-
- do_check_eq(rootNode.childCount, 1);
- do_check_eq(rootNode.getChild(0).itemId, b1);
- rootNode.containerOpen = false;
-
- // partial matches are okay
- query.searchTerms = "wal";
- result = histsvc.executeQuery(query, options);
- rootNode = result.root;
- rootNode.containerOpen = true;
- do_check_eq(rootNode.childCount, 1);
- rootNode.containerOpen = false;
-
- // case insensitive search term
- query.searchTerms = "WALRUS";
- result = histsvc.executeQuery(query, options);
- rootNode = result.root;
- rootNode.containerOpen = true;
- do_check_eq(rootNode.childCount, 1);
- do_check_eq(rootNode.getChild(0).itemId, b1);
- rootNode.containerOpen = false;
-
- // case insensitive tag
- query.searchTerms = "baboon";
- result = histsvc.executeQuery(query, options);
- rootNode = result.root;
- rootNode.containerOpen = true;
- do_check_eq(rootNode.childCount, 1);
- do_check_eq(rootNode.getChild(0).itemId, b1);
- rootNode.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_395593.js b/toolkit/components/places/tests/bookmarks/test_395593.js
deleted file mode 100644
index 46d8f5b80..000000000
--- a/toolkit/components/places/tests/bookmarks/test_395593.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-
-var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-function check_queries_results(aQueries, aOptions, aExpectedItemIds) {
- var result = hs.executeQueries(aQueries, aQueries.length, aOptions);
- var root = result.root;
- root.containerOpen = true;
-
- // Dump found nodes.
- for (let i = 0; i < root.childCount; i++) {
- dump("nodes[" + i + "]: " + root.getChild(0).title + "\n");
- }
-
- do_check_eq(root.childCount, aExpectedItemIds.length);
- for (let i = 0; i < root.childCount; i++) {
- do_check_eq(root.getChild(i).itemId, aExpectedItemIds[i]);
- }
-
- root.containerOpen = false;
-}
-
-// main
-function run_test() {
- var id1 = bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://foo.tld"),
- bs.DEFAULT_INDEX, "123 0");
- var id2 = bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://foo.tld"),
- bs.DEFAULT_INDEX, "456");
- var id3 = bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://foo.tld"),
- bs.DEFAULT_INDEX, "123 456");
- var id4 = bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://foo.tld"),
- bs.DEFAULT_INDEX, "789 456");
-
- /**
- * All of the query objects are ORed together. Within a query, all the terms
- * are ANDed together. See nsINavHistory.idl.
- */
- var queries = [];
- queries.push(hs.getNewQuery());
- queries.push(hs.getNewQuery());
- var options = hs.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
-
- // Test 1
- dump("Test searching for 123 OR 789\n");
- queries[0].searchTerms = "123";
- queries[1].searchTerms = "789";
- check_queries_results(queries, options, [id1, id3, id4]);
-
- // Test 2
- dump("Test searching for 123 OR 456\n");
- queries[0].searchTerms = "123";
- queries[1].searchTerms = "456";
- check_queries_results(queries, options, [id1, id2, id3, id4]);
-
- // Test 3
- dump("Test searching for 00 OR 789\n");
- queries[0].searchTerms = "00";
- queries[1].searchTerms = "789";
- check_queries_results(queries, options, [id4]);
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_405938_restore_queries.js b/toolkit/components/places/tests/bookmarks/test_405938_restore_queries.js
deleted file mode 100644
index e317cc2e9..000000000
--- a/toolkit/components/places/tests/bookmarks/test_405938_restore_queries.js
+++ /dev/null
@@ -1,221 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [];
-
-/*
-
-Backup/restore tests example:
-
-var myTest = {
- populate: function () { ... add bookmarks ... },
- validate: function () { ... query for your bookmarks ... }
-}
-
-this.push(myTest);
-
-*/
-
-/*
-
-test summary:
-- create folders with content
-- create a query bookmark for those folders
-- backs up bookmarks
-- restores bookmarks
-- confirms that the query has the new ids for the same folders
-
-scenarios:
-- 1 folder (folder shortcut)
-- n folders (single query)
-- n folders (multiple queries)
-
-*/
-
-const DEFAULT_INDEX = PlacesUtils.bookmarks.DEFAULT_INDEX;
-
-var test = {
- _testRootId: null,
- _testRootTitle: "test root",
- _folderIds: [],
- _bookmarkURIs: [],
- _count: 3,
-
- populate: function populate() {
- // folder to hold this test
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.toolbarFolderId);
- this._testRootId =
- PlacesUtils.bookmarks.createFolder(PlacesUtils.toolbarFolderId,
- this._testRootTitle, DEFAULT_INDEX);
-
- // create test folders each with a bookmark
- for (var i = 0; i < this._count; i++) {
- var folderId =
- PlacesUtils.bookmarks.createFolder(this._testRootId, "folder" + i, DEFAULT_INDEX);
- this._folderIds.push(folderId)
-
- var bookmarkURI = uri("http://" + i);
- PlacesUtils.bookmarks.insertBookmark(folderId, bookmarkURI,
- DEFAULT_INDEX, "bookmark" + i);
- this._bookmarkURIs.push(bookmarkURI);
- }
-
- // create a query URI with 1 folder (ie: folder shortcut)
- this._queryURI1 = uri("place:folder=" + this._folderIds[0] + "&queryType=1");
- this._queryTitle1 = "query1";
- PlacesUtils.bookmarks.insertBookmark(this._testRootId, this._queryURI1,
- DEFAULT_INDEX, this._queryTitle1);
-
- // create a query URI with _count folders
- this._queryURI2 = uri("place:folder=" + this._folderIds.join("&folder=") + "&queryType=1");
- this._queryTitle2 = "query2";
- PlacesUtils.bookmarks.insertBookmark(this._testRootId, this._queryURI2,
- DEFAULT_INDEX, this._queryTitle2);
-
- // create a query URI with _count queries (each with a folder)
- // first get a query object for each folder
- var queries = this._folderIds.map(function(aFolderId) {
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([aFolderId], 1);
- return query;
- });
- var options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- this._queryURI3 =
- uri(PlacesUtils.history.queriesToQueryString(queries, queries.length, options));
- this._queryTitle3 = "query3";
- PlacesUtils.bookmarks.insertBookmark(this._testRootId, this._queryURI3,
- DEFAULT_INDEX, this._queryTitle3);
- },
-
- clean: function () {},
-
- validate: function validate() {
- // Throw a wrench in the works by inserting some new bookmarks,
- // ensuring folder ids won't be the same, when restoring.
- for (let i = 0; i < 10; i++) {
- PlacesUtils.bookmarks.
- insertBookmark(PlacesUtils.bookmarksMenuFolderId, uri("http://aaaa"+i), DEFAULT_INDEX, "");
- }
-
- var toolbar =
- PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId,
- false, true).root;
- do_check_true(toolbar.childCount, 1);
-
- var folderNode = toolbar.getChild(0);
- do_check_eq(folderNode.type, folderNode.RESULT_TYPE_FOLDER);
- do_check_eq(folderNode.title, this._testRootTitle);
- folderNode.QueryInterface(Ci.nsINavHistoryQueryResultNode);
- folderNode.containerOpen = true;
-
- // |_count| folders + the query node
- do_check_eq(folderNode.childCount, this._count+3);
-
- for (let i = 0; i < this._count; i++) {
- var subFolder = folderNode.getChild(i);
- do_check_eq(subFolder.title, "folder"+i);
- subFolder.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- subFolder.containerOpen = true;
- do_check_eq(subFolder.childCount, 1);
- var child = subFolder.getChild(0);
- do_check_eq(child.title, "bookmark"+i);
- do_check_true(uri(child.uri).equals(uri("http://" + i)))
- }
-
- // validate folder shortcut
- this.validateQueryNode1(folderNode.getChild(this._count));
-
- // validate folders query
- this.validateQueryNode2(folderNode.getChild(this._count + 1));
-
- // validate multiple queries query
- this.validateQueryNode3(folderNode.getChild(this._count + 2));
-
- // clean up
- folderNode.containerOpen = false;
- toolbar.containerOpen = false;
- },
-
- validateQueryNode1: function validateQueryNode1(aNode) {
- do_check_eq(aNode.title, this._queryTitle1);
- do_check_true(PlacesUtils.nodeIsFolder(aNode));
-
- aNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- aNode.containerOpen = true;
- do_check_eq(aNode.childCount, 1);
- var child = aNode.getChild(0);
- do_check_true(uri(child.uri).equals(uri("http://0")))
- do_check_eq(child.title, "bookmark0")
- aNode.containerOpen = false;
- },
-
- validateQueryNode2: function validateQueryNode2(aNode) {
- do_check_eq(aNode.title, this._queryTitle2);
- do_check_true(PlacesUtils.nodeIsQuery(aNode));
-
- aNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- aNode.containerOpen = true;
- do_check_eq(aNode.childCount, this._count);
- for (var i = 0; i < aNode.childCount; i++) {
- var child = aNode.getChild(i);
- do_check_true(uri(child.uri).equals(uri("http://" + i)))
- do_check_eq(child.title, "bookmark" + i)
- }
- aNode.containerOpen = false;
- },
-
- validateQueryNode3: function validateQueryNode3(aNode) {
- do_check_eq(aNode.title, this._queryTitle3);
- do_check_true(PlacesUtils.nodeIsQuery(aNode));
-
- aNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- aNode.containerOpen = true;
- do_check_eq(aNode.childCount, this._count);
- for (var i = 0; i < aNode.childCount; i++) {
- var child = aNode.getChild(i);
- do_check_true(uri(child.uri).equals(uri("http://" + i)))
- do_check_eq(child.title, "bookmark" + i)
- }
- aNode.containerOpen = false;
- }
-}
-tests.push(test);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* () {
- // make json file
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.json");
-
- // populate db
- tests.forEach(function(aTest) {
- aTest.populate();
- // sanity
- aTest.validate();
- });
-
- // export json to file
- yield BookmarkJSONUtils.exportToFile(jsonFile);
-
- // clean
- tests.forEach(function(aTest) {
- aTest.clean();
- });
-
- // restore json file
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
-
- // validate
- tests.forEach(function(aTest) {
- aTest.validate();
- });
-
- // clean up
- yield OS.File.remove(jsonFile);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_417228-exclude-from-backup.js b/toolkit/components/places/tests/bookmarks/test_417228-exclude-from-backup.js
deleted file mode 100644
index 858496856..000000000
--- a/toolkit/components/places/tests/bookmarks/test_417228-exclude-from-backup.js
+++ /dev/null
@@ -1,141 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const EXCLUDE_FROM_BACKUP_ANNO = "places/excludeFromBackup";
-// Menu, Toolbar, Unsorted, Tags, Mobile
-const PLACES_ROOTS_COUNT = 5;
-var tests = [];
-
-/*
-
-Backup/restore tests example:
-
-var myTest = {
- populate: function () { ... add bookmarks ... },
- validate: function () { ... query for your bookmarks ... }
-}
-
-this.push(myTest);
-
-*/
-
-var test = {
- populate: function populate() {
- // check initial size
- var rootNode = PlacesUtils.getFolderContents(PlacesUtils.placesRootId,
- false, false).root;
- do_check_eq(rootNode.childCount, PLACES_ROOTS_COUNT );
- rootNode.containerOpen = false;
-
- var idx = PlacesUtils.bookmarks.DEFAULT_INDEX;
-
- // create a root to be restore
- this._restoreRootTitle = "restore root";
- var restoreRootId = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.placesRootId,
- this._restoreRootTitle, idx);
- // add a test bookmark
- this._restoreRootURI = uri("http://restore.uri");
- PlacesUtils.bookmarks.insertBookmark(restoreRootId, this._restoreRootURI,
- idx, "restore uri");
- // add a test bookmark to be exclude
- this._restoreRootExcludeURI = uri("http://exclude.uri");
- var exItemId = PlacesUtils.bookmarks
- .insertBookmark(restoreRootId,
- this._restoreRootExcludeURI,
- idx, "exclude uri");
- // Annotate the bookmark for exclusion.
- PlacesUtils.annotations.setItemAnnotation(exItemId,
- EXCLUDE_FROM_BACKUP_ANNO, 1, 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-
- // create a root to be exclude
- this._excludeRootTitle = "exclude root";
- this._excludeRootId = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.placesRootId,
- this._excludeRootTitle, idx);
- // Annotate the root for exclusion.
- PlacesUtils.annotations.setItemAnnotation(this._excludeRootId,
- EXCLUDE_FROM_BACKUP_ANNO, 1, 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- // add a test bookmark exclude by exclusion of its parent
- PlacesUtils.bookmarks.insertBookmark(this._excludeRootId,
- this._restoreRootExcludeURI,
- idx, "exclude uri");
- },
-
- validate: function validate(aEmptyBookmarks) {
- var rootNode = PlacesUtils.getFolderContents(PlacesUtils.placesRootId,
- false, false).root;
-
- if (!aEmptyBookmarks) {
- // since restore does not remove backup exclude items both
- // roots should still exist.
- do_check_eq(rootNode.childCount, PLACES_ROOTS_COUNT + 2);
- // open exclude root and check it still contains one item
- var restoreRootIndex = PLACES_ROOTS_COUNT;
- var excludeRootIndex = PLACES_ROOTS_COUNT+1;
- var excludeRootNode = rootNode.getChild(excludeRootIndex);
- do_check_eq(this._excludeRootTitle, excludeRootNode.title);
- excludeRootNode.QueryInterface(Ci.nsINavHistoryQueryResultNode);
- excludeRootNode.containerOpen = true;
- do_check_eq(excludeRootNode.childCount, 1);
- var excludeRootChildNode = excludeRootNode.getChild(0);
- do_check_eq(excludeRootChildNode.uri, this._restoreRootExcludeURI.spec);
- excludeRootNode.containerOpen = false;
- }
- else {
- // exclude root should not exist anymore
- do_check_eq(rootNode.childCount, PLACES_ROOTS_COUNT + 1);
- restoreRootIndex = PLACES_ROOTS_COUNT;
- }
-
- var restoreRootNode = rootNode.getChild(restoreRootIndex);
- do_check_eq(this._restoreRootTitle, restoreRootNode.title);
- restoreRootNode.QueryInterface(Ci.nsINavHistoryQueryResultNode);
- restoreRootNode.containerOpen = true;
- do_check_eq(restoreRootNode.childCount, 1);
- var restoreRootChildNode = restoreRootNode.getChild(0);
- do_check_eq(restoreRootChildNode.uri, this._restoreRootURI.spec);
- restoreRootNode.containerOpen = false;
-
- rootNode.containerOpen = false;
- }
-}
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function*() {
- // make json file
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.json");
-
- // populate db
- test.populate();
-
- yield BookmarkJSONUtils.exportToFile(jsonFile);
-
- // restore json file
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
-
- // validate without removing all bookmarks
- // restore do not remove backup exclude entries
- test.validate(false);
-
- // cleanup
- yield PlacesUtils.bookmarks.eraseEverything();
- // manually remove the excluded root
- PlacesUtils.bookmarks.removeItem(test._excludeRootId);
- // restore json file
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
-
- // validate after a complete bookmarks cleanup
- test.validate(true);
-
- // clean up
- yield OS.File.remove(jsonFile);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_417228-other-roots.js b/toolkit/components/places/tests/bookmarks/test_417228-other-roots.js
deleted file mode 100644
index 1def75d2d..000000000
--- a/toolkit/components/places/tests/bookmarks/test_417228-other-roots.js
+++ /dev/null
@@ -1,158 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [];
-
-/*
-
-Backup/restore tests example:
-
-var myTest = {
- populate: function () { ... add bookmarks ... },
- validate: function () { ... query for your bookmarks ... }
-}
-
-this.push(myTest);
-
-*/
-
-tests.push({
- excludeItemsFromRestore: [],
- populate: function populate() {
- // check initial size
- var rootNode = PlacesUtils.getFolderContents(PlacesUtils.placesRootId,
- false, false).root;
- do_check_eq(rootNode.childCount, 5);
-
- // create a test root
- this._folderTitle = "test folder";
- this._folderId =
- PlacesUtils.bookmarks.createFolder(PlacesUtils.placesRootId,
- this._folderTitle,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- do_check_eq(rootNode.childCount, 6);
-
- // add a tag
- this._testURI = PlacesUtils._uri("http://test");
- this._tags = ["a", "b"];
- PlacesUtils.tagging.tagURI(this._testURI, this._tags);
-
- // add a child to each root, including our test root
- this._roots = [PlacesUtils.bookmarksMenuFolderId, PlacesUtils.toolbarFolderId,
- PlacesUtils.unfiledBookmarksFolderId, PlacesUtils.mobileFolderId,
- this._folderId];
- this._roots.forEach(function(aRootId) {
- // clean slate
- PlacesUtils.bookmarks.removeFolderChildren(aRootId);
- // add a test bookmark
- PlacesUtils.bookmarks.insertBookmark(aRootId, this._testURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX, "test");
- }, this);
-
- // add a folder to exclude from replacing during restore
- // this will still be present post-restore
- var excludedFolderId =
- PlacesUtils.bookmarks.createFolder(PlacesUtils.placesRootId,
- "excluded",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- do_check_eq(rootNode.childCount, 7);
- this.excludeItemsFromRestore.push(excludedFolderId);
-
- // add a test bookmark to it
- PlacesUtils.bookmarks.insertBookmark(excludedFolderId, this._testURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX, "test");
- },
-
- inbetween: function inbetween() {
- // add some items that should be removed by the restore
-
- // add a folder
- this._litterTitle = "otter";
- PlacesUtils.bookmarks.createFolder(PlacesUtils.placesRootId,
- this._litterTitle, 0);
-
- // add some tags
- PlacesUtils.tagging.tagURI(this._testURI, ["c", "d"]);
- },
-
- validate: function validate() {
- // validate tags restored
- var tags = PlacesUtils.tagging.getTagsForURI(this._testURI);
- // also validates that litter tags are gone
- do_check_eq(this._tags.toString(), tags.toString());
-
- var rootNode = PlacesUtils.getFolderContents(PlacesUtils.placesRootId,
- false, false).root;
-
- // validate litter is gone
- do_check_neq(rootNode.getChild(0).title, this._litterTitle);
-
- // test root count is the same
- do_check_eq(rootNode.childCount, 7);
-
- var foundTestFolder = 0;
- for (var i = 0; i < rootNode.childCount; i++) {
- var node = rootNode.getChild(i);
-
- do_print("validating " + node.title);
- if (node.itemId != PlacesUtils.tagsFolderId) {
- if (node.title == this._folderTitle) {
- // check the test folder's properties
- do_check_eq(node.type, node.RESULT_TYPE_FOLDER);
- do_check_eq(node.title, this._folderTitle);
- foundTestFolder++;
- }
-
- // test contents
- node.QueryInterface(Ci.nsINavHistoryContainerResultNode).containerOpen = true;
- do_check_eq(node.childCount, 1);
- var child = node.getChild(0);
- do_check_true(PlacesUtils._uri(child.uri).equals(this._testURI));
-
- // clean up
- node.containerOpen = false;
- }
- }
- do_check_eq(foundTestFolder, 1);
- rootNode.containerOpen = false;
- }
-});
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* () {
- // make json file
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.json");
-
- // populate db
- tests.forEach(function(aTest) {
- aTest.populate();
- // sanity
- aTest.validate();
-
- if (aTest.excludedItemsFromRestore)
- excludedItemsFromRestore = excludedItems.concat(aTest.excludedItemsFromRestore);
- });
-
- yield BookmarkJSONUtils.exportToFile(jsonFile);
-
- tests.forEach(function(aTest) {
- aTest.inbetween();
- });
-
- // restore json file
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
-
- // validate
- tests.forEach(function(aTest) {
- aTest.validate();
- });
-
- // clean up
- yield OS.File.remove(jsonFile);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js b/toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js
deleted file mode 100644
index 7da1146cf..000000000
--- a/toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [];
-
-/*
-
-Backup/restore tests example:
-
-var myTest = {
- populate: function () { ... add bookmarks ... },
- validate: function () { ... query for your bookmarks ... }
-}
-
-this.push(myTest);
-
-*/
-
-var quotesTest = {
- _folderTitle: '"quoted folder"',
- _folderId: null,
-
- populate: function () {
- this._folderId =
- PlacesUtils.bookmarks.createFolder(PlacesUtils.toolbarFolderId,
- this._folderTitle,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- },
-
- clean: function () {
- PlacesUtils.bookmarks.removeItem(this._folderId);
- },
-
- validate: function () {
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- var result = PlacesUtils.history.executeQuery(query, PlacesUtils.history.getNewQueryOptions());
-
- var toolbar = result.root;
- toolbar.containerOpen = true;
-
- // test for our quoted folder
- do_check_true(toolbar.childCount, 1);
- var folderNode = toolbar.getChild(0);
- do_check_eq(folderNode.type, folderNode.RESULT_TYPE_FOLDER);
- do_check_eq(folderNode.title, this._folderTitle);
-
- // clean up
- toolbar.containerOpen = false;
- }
-}
-tests.push(quotesTest);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* () {
- // make json file
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.json");
-
- // populate db
- tests.forEach(function(aTest) {
- aTest.populate();
- // sanity
- aTest.validate();
- });
-
- // export json to file
- yield BookmarkJSONUtils.exportToFile(jsonFile);
-
- // clean
- tests.forEach(function(aTest) {
- aTest.clean();
- });
-
- // restore json file
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
-
- // validate
- tests.forEach(function(aTest) {
- aTest.validate();
- });
-
- // clean up
- yield OS.File.remove(jsonFile);
-
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_448584.js b/toolkit/components/places/tests/bookmarks/test_448584.js
deleted file mode 100644
index 6e58bd83a..000000000
--- a/toolkit/components/places/tests/bookmarks/test_448584.js
+++ /dev/null
@@ -1,113 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [];
-
-// Get database connection
-try {
- var mDBConn = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .DBConnection;
-}
-catch (ex) {
- do_throw("Could not get database connection\n");
-}
-
-/*
- This test is:
- - don't try to add invalid uri nodes to a JSON backup
-*/
-
-var invalidURITest = {
- _itemTitle: "invalid uri",
- _itemUrl: "http://test.mozilla.org/",
- _itemId: null,
-
- populate: function () {
- // add a valid bookmark
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.toolbarFolderId,
- PlacesUtils._uri(this._itemUrl),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- this._itemTitle);
- // this bookmark will go corrupt
- this._itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.toolbarFolderId,
- PlacesUtils._uri(this._itemUrl),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- this._itemTitle);
- },
-
- clean: function () {
- PlacesUtils.bookmarks.removeItem(this._itemId);
- },
-
- validate: function (aExpectValidItemsCount) {
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- var options = PlacesUtils.history.getNewQueryOptions();
- var result = PlacesUtils.history.executeQuery(query, options);
-
- var toolbar = result.root;
- toolbar.containerOpen = true;
-
- // test for our bookmark
- do_check_eq(toolbar.childCount, aExpectValidItemsCount);
- for (var i = 0; i < toolbar.childCount; i++) {
- var folderNode = toolbar.getChild(0);
- do_check_eq(folderNode.type, folderNode.RESULT_TYPE_URI);
- do_check_eq(folderNode.title, this._itemTitle);
- }
-
- // clean up
- toolbar.containerOpen = false;
- }
-}
-tests.push(invalidURITest);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function*() {
- // make json file
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.json");
-
- // populate db
- tests.forEach(function(aTest) {
- aTest.populate();
- // sanity
- aTest.validate(2);
- // Something in the code went wrong and we finish up losing the place, so
- // the bookmark uri becomes null.
- var sql = "UPDATE moz_bookmarks SET fk = 1337 WHERE id = ?1";
- var stmt = mDBConn.createStatement(sql);
- stmt.bindByIndex(0, aTest._itemId);
- try {
- stmt.execute();
- } finally {
- stmt.finalize();
- }
- });
-
- yield BookmarkJSONUtils.exportToFile(jsonFile);
-
- // clean
- tests.forEach(function(aTest) {
- aTest.clean();
- });
-
- // restore json file
- try {
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
- } catch (ex) { do_throw("couldn't import the exported file: " + ex); }
-
- // validate
- tests.forEach(function(aTest) {
- aTest.validate(1);
- });
-
- // clean up
- yield OS.File.remove(jsonFile);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_458683.js b/toolkit/components/places/tests/bookmarks/test_458683.js
deleted file mode 100644
index c3722aab5..000000000
--- a/toolkit/components/places/tests/bookmarks/test_458683.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [];
-
-// Get database connection
-try {
- var mDBConn = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .DBConnection;
-}
-catch (ex) {
- do_throw("Could not get database connection\n");
-}
-
-/*
- This test is:
- - don't block while doing backup and restore if tag containers contain
- bogus items (separators, folders)
-*/
-
-var invalidTagChildTest = {
- _itemTitle: "invalid uri",
- _itemUrl: "http://test.mozilla.org/",
- _itemId: -1,
- _tag: "testTag",
- _tagItemId: -1,
-
- populate: function () {
- // add a valid bookmark
- this._itemId = PlacesUtils.bookmarks
- .insertBookmark(PlacesUtils.toolbarFolderId,
- PlacesUtils._uri(this._itemUrl),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- this._itemTitle);
-
- // create a tag
- PlacesUtils.tagging.tagURI(PlacesUtils._uri(this._itemUrl), [this._tag]);
- // get tag folder id
- var options = PlacesUtils.history.getNewQueryOptions();
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.tagsFolder], 1);
- var result = PlacesUtils.history.executeQuery(query, options);
- var tagRoot = result.root;
- tagRoot.containerOpen = true;
- do_check_eq(tagRoot.childCount, 1);
- var tagNode = tagRoot.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- this._tagItemId = tagNode.itemId;
- tagRoot.containerOpen = false;
-
- // add a separator and a folder inside tag folder
- PlacesUtils.bookmarks.insertSeparator(this._tagItemId,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.createFolder(this._tagItemId,
- "test folder",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
-
- // add a separator and a folder inside tag root
- PlacesUtils.bookmarks.insertSeparator(PlacesUtils.bookmarks.tagsFolder,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.createFolder(PlacesUtils.bookmarks.tagsFolder,
- "test tags root folder",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- },
-
- clean: function () {
- PlacesUtils.tagging.untagURI(PlacesUtils._uri(this._itemUrl), [this._tag]);
- PlacesUtils.bookmarks.removeItem(this._itemId);
- },
-
- validate: function () {
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- var options = PlacesUtils.history.getNewQueryOptions();
- var result = PlacesUtils.history.executeQuery(query, options);
-
- var toolbar = result.root;
- toolbar.containerOpen = true;
-
- // test for our bookmark
- do_check_eq(toolbar.childCount, 1);
- for (var i = 0; i < toolbar.childCount; i++) {
- var folderNode = toolbar.getChild(0);
- do_check_eq(folderNode.type, folderNode.RESULT_TYPE_URI);
- do_check_eq(folderNode.title, this._itemTitle);
- }
- toolbar.containerOpen = false;
-
- // test for our tag
- var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(this._itemUrl));
- do_check_eq(tags.length, 1);
- do_check_eq(tags[0], this._tag);
- }
-}
-tests.push(invalidTagChildTest);
-
-function run_test() {
- run_next_test()
-}
-
-add_task(function* () {
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.json");
-
- // populate db
- tests.forEach(function(aTest) {
- aTest.populate();
- // sanity
- aTest.validate();
- });
-
- yield BookmarkJSONUtils.exportToFile(jsonFile);
-
- // clean
- tests.forEach(function(aTest) {
- aTest.clean();
- });
-
- // restore json file
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
-
- // validate
- tests.forEach(function(aTest) {
- aTest.validate();
- });
-
- // clean up
- yield OS.File.remove(jsonFile);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js b/toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js
deleted file mode 100644
index 3ce0e6ad7..000000000
--- a/toolkit/components/places/tests/bookmarks/test_466303-json-remove-backups.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Since PlacesBackups.getbackupFiles() is a lazy getter, these tests must
-// run in the given order, to avoid making it out-of-sync.
-
-add_task(function* check_max_backups_is_respected() {
- // Get bookmarkBackups directory
- let backupFolder = yield PlacesBackups.getBackupFolder();
-
- // Create 2 json dummy backups in the past.
- let oldJsonPath = OS.Path.join(backupFolder, "bookmarks-2008-01-01.json");
- let oldJsonFile = yield OS.File.open(oldJsonPath, { truncate: true });
- oldJsonFile.close();
- do_check_true(yield OS.File.exists(oldJsonPath));
-
- let jsonPath = OS.Path.join(backupFolder, "bookmarks-2008-01-31.json");
- let jsonFile = yield OS.File.open(jsonPath, { truncate: true });
- jsonFile.close();
- do_check_true(yield OS.File.exists(jsonPath));
-
- // Export bookmarks to JSON.
- // Allow 2 backups, the older one should be removed.
- yield PlacesBackups.create(2);
-
- let count = 0;
- let lastBackupPath = null;
- let iterator = new OS.File.DirectoryIterator(backupFolder);
- try {
- yield iterator.forEach(aEntry => {
- count++;
- if (PlacesBackups.filenamesRegex.test(aEntry.name))
- lastBackupPath = aEntry.path;
- });
- } finally {
- iterator.close();
- }
-
- do_check_eq(count, 2);
- do_check_neq(lastBackupPath, null);
- do_check_false(yield OS.File.exists(oldJsonPath));
- do_check_true(yield OS.File.exists(jsonPath));
-});
-
-add_task(function* check_max_backups_greater_than_backups() {
- // Get bookmarkBackups directory
- let backupFolder = yield PlacesBackups.getBackupFolder();
-
- // Export bookmarks to JSON.
- // Allow 3 backups, none should be removed.
- yield PlacesBackups.create(3);
-
- let count = 0;
- let lastBackupPath = null;
- let iterator = new OS.File.DirectoryIterator(backupFolder);
- try {
- yield iterator.forEach(aEntry => {
- count++;
- if (PlacesBackups.filenamesRegex.test(aEntry.name))
- lastBackupPath = aEntry.path;
- });
- } finally {
- iterator.close();
- }
- do_check_eq(count, 2);
- do_check_neq(lastBackupPath, null);
-});
-
-add_task(function* check_max_backups_null() {
- // Get bookmarkBackups directory
- let backupFolder = yield PlacesBackups.getBackupFolder();
-
- // Export bookmarks to JSON.
- // Allow infinite backups, none should be removed, a new one is not created
- // since one for today already exists.
- yield PlacesBackups.create(null);
-
- let count = 0;
- let lastBackupPath = null;
- let iterator = new OS.File.DirectoryIterator(backupFolder);
- try {
- yield iterator.forEach(aEntry => {
- count++;
- if (PlacesBackups.filenamesRegex.test(aEntry.name))
- lastBackupPath = aEntry.path;
- });
- } finally {
- iterator.close();
- }
- do_check_eq(count, 2);
- do_check_neq(lastBackupPath, null);
-});
-
-add_task(function* check_max_backups_undefined() {
- // Get bookmarkBackups directory
- let backupFolder = yield PlacesBackups.getBackupFolder();
-
- // Export bookmarks to JSON.
- // Allow infinite backups, none should be removed, a new one is not created
- // since one for today already exists.
- yield PlacesBackups.create();
-
- let count = 0;
- let lastBackupPath = null;
- let iterator = new OS.File.DirectoryIterator(backupFolder);
- try {
- yield iterator.forEach(aEntry => {
- count++;
- if (PlacesBackups.filenamesRegex.test(aEntry.name))
- lastBackupPath = aEntry.path;
- });
- } finally {
- iterator.close();
- }
- do_check_eq(count, 2);
- do_check_neq(lastBackupPath, null);
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js b/toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js
deleted file mode 100644
index 116352666..000000000
--- a/toolkit/components/places/tests/bookmarks/test_477583_json-backup-in-future.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- do_test_pending();
-
- Task.spawn(function*() {
- let backupFolder = yield PlacesBackups.getBackupFolder();
- let bookmarksBackupDir = new FileUtils.File(backupFolder);
- // Remove all files from backups folder.
- let files = bookmarksBackupDir.directoryEntries;
- while (files.hasMoreElements()) {
- let entry = files.getNext().QueryInterface(Ci.nsIFile);
- entry.remove(false);
- }
-
- // Create a json dummy backup in the future.
- let dateObj = new Date();
- dateObj.setYear(dateObj.getFullYear() + 1);
- let name = PlacesBackups.getFilenameForDate(dateObj);
- do_check_eq(name, "bookmarks-" + PlacesBackups.toISODateString(dateObj) + ".json");
- files = bookmarksBackupDir.directoryEntries;
- while (files.hasMoreElements()) {
- let entry = files.getNext().QueryInterface(Ci.nsIFile);
- if (PlacesBackups.filenamesRegex.test(entry.leafName))
- entry.remove(false);
- }
-
- let futureBackupFile = bookmarksBackupDir.clone();
- futureBackupFile.append(name);
- futureBackupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0o600);
- do_check_true(futureBackupFile.exists());
-
- do_check_eq((yield PlacesBackups.getBackupFiles()).length, 0);
-
- yield PlacesBackups.create();
- // Check that a backup for today has been created.
- do_check_eq((yield PlacesBackups.getBackupFiles()).length, 1);
- let mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup();
- do_check_neq(mostRecentBackupFile, null);
- do_check_true(PlacesBackups.filenamesRegex.test(OS.Path.basename(mostRecentBackupFile)));
-
- // Check that future backup has been removed.
- do_check_false(futureBackupFile.exists());
-
- // Cleanup.
- mostRecentBackupFile = new FileUtils.File(mostRecentBackupFile);
- mostRecentBackupFile.remove(false);
- do_check_false(mostRecentBackupFile.exists());
-
- do_test_finished()
- });
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_675416.js b/toolkit/components/places/tests/bookmarks/test_675416.js
deleted file mode 100644
index 08b1c3620..000000000
--- a/toolkit/components/places/tests/bookmarks/test_675416.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test() {
- /**
- * Requests information to the service, so that bookmark's data is cached.
- * @param aItemId
- * Id of the bookmark to be cached.
- */
- function forceBookmarkCaching(aItemId) {
- PlacesUtils.bookmarks.getFolderIdForItem(aItemId);
- }
-
- let observer = {
- onBeginUpdateBatch: () => forceBookmarkCaching(itemId1),
- onEndUpdateBatch: () => forceBookmarkCaching(itemId1),
- onItemAdded: forceBookmarkCaching,
- onItemChanged: forceBookmarkCaching,
- onItemMoved: forceBookmarkCaching,
- onItemRemoved: function(id) {
- try {
- forceBookmarkCaching(id);
- do_throw("trying to fetch a removed bookmark should throw");
- } catch (ex) {}
- },
- onItemVisited: forceBookmarkCaching,
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
- };
- PlacesUtils.bookmarks.addObserver(observer, false);
-
- let folderId1 = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.bookmarksMenuFolderId,
- "Bookmarks",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- let itemId1 = PlacesUtils.bookmarks
- .insertBookmark(folderId1,
- NetUtil.newURI("http:/www.wired.com/wiredscience"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "Wired Science");
-
- PlacesUtils.bookmarks.removeItem(folderId1);
-
- let folderId2 = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.bookmarksMenuFolderId,
- "Science",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- let folderId3 = PlacesUtils.bookmarks
- .createFolder(folderId2,
- "Blogs",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- // Check title is correctly reported.
- do_check_eq(PlacesUtils.bookmarks.getItemTitle(folderId3), "Blogs");
- do_check_eq(PlacesUtils.bookmarks.getItemTitle(folderId2), "Science");
-
- PlacesUtils.bookmarks.removeObserver(observer, false);
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_711914.js b/toolkit/components/places/tests/bookmarks/test_711914.js
deleted file mode 100644
index 3712c8a77..000000000
--- a/toolkit/components/places/tests/bookmarks/test_711914.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- /**
- * Requests information to the service, so that bookmark's data is cached.
- * @param aItemId
- * Id of the bookmark to be cached.
- */
- function forceBookmarkCaching(aItemId) {
- let parent = PlacesUtils.bookmarks.getFolderIdForItem(aItemId);
- PlacesUtils.bookmarks.getFolderIdForItem(parent);
- }
-
- let observer = {
- onBeginUpdateBatch: () => forceBookmarkCaching(itemId1),
- onEndUpdateBatch: () => forceBookmarkCaching(itemId1),
- onItemAdded: forceBookmarkCaching,
- onItemChanged: forceBookmarkCaching,
- onItemMoved: forceBookmarkCaching,
- onItemRemoved: function (id) {
- try {
- forceBookmarkCaching(id);
- do_throw("trying to fetch a removed bookmark should throw");
- } catch (ex) {}
- },
- onItemVisited: forceBookmarkCaching,
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
- };
- PlacesUtils.bookmarks.addObserver(observer, false);
-
- let folder1 = PlacesUtils.bookmarks
- .createFolder(PlacesUtils.bookmarksMenuFolderId,
- "Folder1",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- let folder2 = PlacesUtils.bookmarks
- .createFolder(folder1,
- "Folder2",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.insertBookmark(folder2,
- NetUtil.newURI("http://mozilla.org/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "Mozilla");
-
- PlacesUtils.bookmarks.removeFolderChildren(folder1);
-
- // Check title is correctly reported.
- do_check_eq(PlacesUtils.bookmarks.getItemTitle(folder1), "Folder1");
- try {
- PlacesUtils.bookmarks.getItemTitle(folder2);
- do_throw("trying to fetch a removed bookmark should throw");
- } catch (ex) {}
-
- PlacesUtils.bookmarks.removeObserver(observer, false);
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_818584-discard-duplicate-backups.js b/toolkit/components/places/tests/bookmarks/test_818584-discard-duplicate-backups.js
deleted file mode 100644
index c88323478..000000000
--- a/toolkit/components/places/tests/bookmarks/test_818584-discard-duplicate-backups.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/. */
-
-/**
- * Checks that automatically created bookmark backups are discarded if they are
- * duplicate of an existing ones.
- */
-function run_test() {
- run_next_test();
-}
-
-add_task(function*() {
- // Create a backup for yesterday in the backups folder.
- let backupFolder = yield PlacesBackups.getBackupFolder();
- let dateObj = new Date();
- dateObj.setDate(dateObj.getDate() - 1);
- let oldBackupName = PlacesBackups.getFilenameForDate(dateObj);
- let oldBackup = OS.Path.join(backupFolder, oldBackupName);
- let {count: count, hash: hash} = yield BookmarkJSONUtils.exportToFile(oldBackup);
- do_check_true(count > 0);
- do_check_eq(hash.length, 24);
- oldBackupName = oldBackupName.replace(/\.json/, "_" + count + "_" + hash + ".json");
- yield OS.File.move(oldBackup, OS.Path.join(backupFolder, oldBackupName));
-
- // Create a backup.
- // This should just rename the existing backup, so in the end there should be
- // only one backup with today's date.
- yield PlacesBackups.create();
-
- // Get the hash of the generated backup
- let backupFiles = yield PlacesBackups.getBackupFiles();
- do_check_eq(backupFiles.length, 1);
-
- let matches = OS.Path.basename(backupFiles[0]).match(PlacesBackups.filenamesRegex);
- do_check_eq(matches[1], PlacesBackups.toISODateString(new Date()));
- do_check_eq(matches[2], count);
- do_check_eq(matches[3], hash);
-
- // Add a bookmark and create another backup.
- let bookmarkId = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarks.bookmarksMenuFolder,
- uri("http://foo.com"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "foo");
- // We must enforce a backup since one for today already exists. The forced
- // backup will replace the existing one.
- yield PlacesBackups.create(undefined, true);
- do_check_eq(backupFiles.length, 1);
- recentBackup = yield PlacesBackups.getMostRecentBackup();
- do_check_neq(recentBackup, OS.Path.join(backupFolder, oldBackupName));
- matches = OS.Path.basename(recentBackup).match(PlacesBackups.filenamesRegex);
- do_check_eq(matches[1], PlacesBackups.toISODateString(new Date()));
- do_check_eq(matches[2], count + 1);
- do_check_neq(matches[3], hash);
-
- // Clean up
- PlacesUtils.bookmarks.removeItem(bookmarkId);
- yield PlacesBackups.create(0);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_818587_compress-bookmarks-backups.js b/toolkit/components/places/tests/bookmarks/test_818587_compress-bookmarks-backups.js
deleted file mode 100644
index 2c84990b3..000000000
--- a/toolkit/components/places/tests/bookmarks/test_818587_compress-bookmarks-backups.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* compress_bookmark_backups_test() {
- // Check for jsonlz4 extension
- let todayFilename = PlacesBackups.getFilenameForDate(new Date(2014, 4, 15), true);
- do_check_eq(todayFilename, "bookmarks-2014-05-15.jsonlz4");
-
- yield PlacesBackups.create();
-
- // Check that a backup for today has been created and the regex works fine for lz4.
- do_check_eq((yield PlacesBackups.getBackupFiles()).length, 1);
- let mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup();
- do_check_neq(mostRecentBackupFile, null);
- do_check_true(PlacesBackups.filenamesRegex.test(OS.Path.basename(mostRecentBackupFile)));
-
- // The most recent backup file has to be removed since saveBookmarksToJSONFile
- // will otherwise over-write the current backup, since it will be made on the
- // same date
- yield OS.File.remove(mostRecentBackupFile);
- do_check_false((yield OS.File.exists(mostRecentBackupFile)));
-
- // Check that, if the user created a custom backup out of the default
- // backups folder, it gets copied (compressed) into it.
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.json");
- yield PlacesBackups.saveBookmarksToJSONFile(jsonFile);
- do_check_eq((yield PlacesBackups.getBackupFiles()).length, 1);
-
- // Check if import works from lz4 compressed json
- let uri = NetUtil.newURI("http://www.mozilla.org/en-US/");
- let bm = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark");
-
- // Force create a compressed backup, Remove the bookmark, the restore the backup
- yield PlacesBackups.create(undefined, true);
- let recentBackup = yield PlacesBackups.getMostRecentBackup();
- PlacesUtils.bookmarks.removeItem(bm);
- yield BookmarkJSONUtils.importFromFile(recentBackup, true);
- let root = PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- let node = root.getChild(0);
- do_check_eq(node.uri, uri.spec);
-
- root.containerOpen = false;
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
-
- // Cleanup.
- yield OS.File.remove(jsonFile);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js b/toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js
deleted file mode 100644
index 4ea07fb39..000000000
--- a/toolkit/components/places/tests/bookmarks/test_818593-store-backup-metadata.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * To confirm that metadata i.e. bookmark count is set and retrieved for
- * automatic backups.
- */
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_saveBookmarksToJSONFile_and_create()
-{
- // Add a bookmark
- let uri = NetUtil.newURI("http://getfirefox.com/");
- let bookmarkId =
- PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX, "Get Firefox!");
-
- // Test saveBookmarksToJSONFile()
- let backupFile = FileUtils.getFile("TmpD", ["bookmarks.json"]);
- backupFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, parseInt("0600", 8));
-
- let nodeCount = yield PlacesBackups.saveBookmarksToJSONFile(backupFile, true);
- do_check_true(nodeCount > 0);
- do_check_true(backupFile.exists());
- do_check_eq(backupFile.leafName, "bookmarks.json");
-
- // Ensure the backup would be copied to our backups folder when the original
- // backup is saved somewhere else.
- let recentBackup = yield PlacesBackups.getMostRecentBackup();
- let matches = OS.Path.basename(recentBackup).match(PlacesBackups.filenamesRegex);
- do_check_eq(matches[2], nodeCount);
- do_check_eq(matches[3].length, 24);
-
- // Clear all backups in our backups folder.
- yield PlacesBackups.create(0);
- do_check_eq((yield PlacesBackups.getBackupFiles()).length, 0);
-
- // Test create() which saves bookmarks with metadata on the filename.
- yield PlacesBackups.create();
- do_check_eq((yield PlacesBackups.getBackupFiles()).length, 1);
-
- mostRecentBackupFile = yield PlacesBackups.getMostRecentBackup();
- do_check_neq(mostRecentBackupFile, null);
- matches = OS.Path.basename(recentBackup).match(PlacesBackups.filenamesRegex);
- do_check_eq(matches[2], nodeCount);
- do_check_eq(matches[3].length, 24);
-
- // Cleanup
- backupFile.remove(false);
- yield PlacesBackups.create(0);
- PlacesUtils.bookmarks.removeItem(bookmarkId);
-});
-
diff --git a/toolkit/components/places/tests/bookmarks/test_992901-backup-unsorted-hierarchy.js b/toolkit/components/places/tests/bookmarks/test_992901-backup-unsorted-hierarchy.js
deleted file mode 100644
index f5e9f8187..000000000
--- a/toolkit/components/places/tests/bookmarks/test_992901-backup-unsorted-hierarchy.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Checks that backups properly include all of the bookmarks if the hierarchy
- * in the database is unordered so that a hierarchy is defined before its
- * ancestor in the bookmarks table.
- */
-function run_test() {
- run_next_test();
-}
-
-add_task(function*() {
- let bm = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- NetUtil.newURI("http://mozilla.org/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark");
- let f2 = PlacesUtils.bookmarks.createFolder(PlacesUtils.unfiledBookmarksFolderId, "f2",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.moveItem(bm, f2, PlacesUtils.bookmarks.DEFAULT_INDEX);
- let f1 = PlacesUtils.bookmarks.createFolder(PlacesUtils.unfiledBookmarksFolderId, "f1",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.moveItem(f2, f1, PlacesUtils.bookmarks.DEFAULT_INDEX);
-
- // Create a backup.
- yield PlacesBackups.create();
-
- // Remove the bookmarks, then restore the backup.
- PlacesUtils.bookmarks.removeItem(f1);
- yield BookmarkJSONUtils.importFromFile((yield PlacesBackups.getMostRecentBackup()), true);
-
- do_print("Checking first level");
- let root = PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- let level1 = root.getChild(0);
- do_check_eq(level1.title, "f1");
- do_print("Checking second level");
- PlacesUtils.asContainer(level1).containerOpen = true
- let level2 = level1.getChild(0);
- do_check_eq(level2.title, "f2");
- do_print("Checking bookmark");
- PlacesUtils.asContainer(level2).containerOpen = true
- let bookmark = level2.getChild(0);
- do_check_eq(bookmark.title, "bookmark");
- level2.containerOpen = false;
- level1.containerOpen = false;
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_997030-bookmarks-html-encode.js b/toolkit/components/places/tests/bookmarks/test_997030-bookmarks-html-encode.js
deleted file mode 100644
index b900887b5..000000000
--- a/toolkit/components/places/tests/bookmarks/test_997030-bookmarks-html-encode.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Checks that we don't encodeURI twice when creating bookmarks.html.
- */
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* () {
- let uri = NetUtil.newURI("http://bt.ktxp.com/search.php?keyword=%E5%A6%84%E6%83%B3%E5%AD%A6%E7%94%9F%E4%BC%9A");
- let bm = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark");
-
- let file = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.exported.997030.html");
- if ((yield OS.File.exists(file))) {
- yield OS.File.remove(file);
- }
- yield BookmarkHTMLUtils.exportToFile(file);
-
- // Remove the bookmarks, then restore the backup.
- PlacesUtils.bookmarks.removeItem(bm);
- yield BookmarkHTMLUtils.importFromFile(file, true);
-
- do_print("Checking first level");
- let root = PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- let node = root.getChild(0);
- do_check_eq(node.uri, uri.spec);
-
- root.containerOpen = false;
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_async_observers.js b/toolkit/components/places/tests/bookmarks/test_async_observers.js
deleted file mode 100644
index 86d48ac24..000000000
--- a/toolkit/components/places/tests/bookmarks/test_async_observers.js
+++ /dev/null
@@ -1,177 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* This test checks that bookmarks service is correctly forwarding async
- * events like visit or favicon additions. */
-
-const NOW = Date.now() * 1000;
-
-var observer = {
- bookmarks: [],
- observedBookmarks: 0,
- observedVisitId: 0,
- deferred: null,
-
- /**
- * Returns a promise that is resolved when the observer determines that the
- * test can continue. This is required rather than calling run_next_test
- * directly in the observer because there are cases where we must wait for
- * other asynchronous events to be completed in addition to this.
- */
- setupCompletionPromise: function ()
- {
- this.observedBookmarks = 0;
- this.deferred = Promise.defer();
- return this.deferred.promise;
- },
-
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemAdded: function () {},
- onItemRemoved: function () {},
- onItemMoved: function () {},
- onItemChanged: function(aItemId, aProperty, aIsAnnotation, aNewValue,
- aLastModified, aItemType)
- {
- do_print("Check that we got the correct change information.");
- do_check_neq(this.bookmarks.indexOf(aItemId), -1);
- if (aProperty == "favicon") {
- do_check_false(aIsAnnotation);
- do_check_eq(aNewValue, SMALLPNG_DATA_URI.spec);
- do_check_eq(aLastModified, 0);
- do_check_eq(aItemType, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- }
- else if (aProperty == "cleartime") {
- do_check_false(aIsAnnotation);
- do_check_eq(aNewValue, "");
- do_check_eq(aLastModified, 0);
- do_check_eq(aItemType, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- }
- else {
- do_throw("Unexpected property change " + aProperty);
- }
-
- if (++this.observedBookmarks == this.bookmarks.length) {
- this.deferred.resolve();
- }
- },
- onItemVisited: function(aItemId, aVisitId, aTime)
- {
- do_print("Check that we got the correct visit information.");
- do_check_neq(this.bookmarks.indexOf(aItemId), -1);
- this.observedVisitId = aVisitId;
- do_check_eq(aTime, NOW);
- if (++this.observedBookmarks == this.bookmarks.length) {
- this.deferred.resolve();
- }
- },
-
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver,
- ])
-};
-PlacesUtils.bookmarks.addObserver(observer, false);
-
-add_task(function* test_add_visit()
-{
- let observerPromise = observer.setupCompletionPromise();
-
- // Add a visit to the bookmark and wait for the observer.
- let visitId;
- let deferUpdatePlaces = Promise.defer();
- PlacesUtils.asyncHistory.updatePlaces({
- uri: NetUtil.newURI("http://book.ma.rk/"),
- visits: [{ transitionType: TRANSITION_TYPED, visitDate: NOW }]
- }, {
- handleError: function TAV_handleError() {
- deferUpdatePlaces.reject(new Error("Unexpected error in adding visit."));
- },
- handleResult: function (aPlaceInfo) {
- visitId = aPlaceInfo.visits[0].visitId;
- },
- handleCompletion: function TAV_handleCompletion() {
- deferUpdatePlaces.resolve();
- }
- });
-
- // Wait for both the observer and the asynchronous update, in any order.
- yield deferUpdatePlaces.promise;
- yield observerPromise;
-
- // Check that both asynchronous results are consistent.
- do_check_eq(observer.observedVisitId, visitId);
-});
-
-add_task(function* test_add_icon()
-{
- let observerPromise = observer.setupCompletionPromise();
- PlacesUtils.favicons.setAndFetchFaviconForPage(NetUtil.newURI("http://book.ma.rk/"),
- SMALLPNG_DATA_URI, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null,
- Services.scriptSecurityManager.getSystemPrincipal());
- yield observerPromise;
-});
-
-add_task(function* test_remove_page()
-{
- let observerPromise = observer.setupCompletionPromise();
- PlacesUtils.history.removePage(NetUtil.newURI("http://book.ma.rk/"));
- yield observerPromise;
-});
-
-add_task(function cleanup()
-{
- PlacesUtils.bookmarks.removeObserver(observer, false);
-});
-
-add_task(function* shutdown()
-{
- // Check that async observers don't try to create async statements after
- // shutdown. That would cause assertions, since the async thread is gone
- // already. Note that in such a case the notifications are not fired, so we
- // cannot test for them.
- // Put an history notification that triggers AsyncGetBookmarksForURI between
- // asyncClose() and the actual connection closing. Enqueuing a main-thread
- // event just after places-will-close-connection should ensure it runs before
- // places-connection-closed.
- // Notice this code is not using helpers cause it depends on a very specific
- // order, a change in the helpers code could make this test useless.
- let deferred = Promise.defer();
-
- Services.obs.addObserver(function onNotification() {
- Services.obs.removeObserver(onNotification, "places-will-close-connection");
- do_check_true(true, "Observed fake places shutdown");
-
- Services.tm.mainThread.dispatch(() => {
- // WARNING: this is very bad, never use out of testing code.
- PlacesUtils.bookmarks.QueryInterface(Ci.nsINavHistoryObserver)
- .onPageChanged(NetUtil.newURI("http://book.ma.rk/"),
- Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON,
- "test", "test");
- deferred.resolve(promiseTopicObserved("places-connection-closed"));
- }, Ci.nsIThread.DISPATCH_NORMAL);
- }, "places-will-close-connection", false);
- shutdownPlaces();
-
- yield deferred.promise;
-});
-
-function run_test()
-{
- // Add multiple bookmarks to the same uri.
- observer.bookmarks.push(
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- NetUtil.newURI("http://book.ma.rk/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "Bookmark")
- );
- observer.bookmarks.push(
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.toolbarFolderId,
- NetUtil.newURI("http://book.ma.rk/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "Bookmark")
- );
-
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bmindex.js b/toolkit/components/places/tests/bookmarks/test_bmindex.js
deleted file mode 100644
index c764e4310..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bmindex.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const NUM_BOOKMARKS = 20;
-const NUM_SEPARATORS = 5;
-const NUM_FOLDERS = 10;
-const NUM_ITEMS = NUM_BOOKMARKS + NUM_SEPARATORS + NUM_FOLDERS;
-const MIN_RAND = -5;
-const MAX_RAND = 40;
-
-var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-function check_contiguous_indexes(aBookmarks) {
- var indexes = [];
- aBookmarks.forEach(function(aBookmarkId) {
- let bmIndex = bs.getItemIndex(aBookmarkId);
- dump("Index: " + bmIndex + "\n");
- dump("Checking duplicates\n");
- do_check_eq(indexes.indexOf(bmIndex), -1);
- dump("Checking out of range, found " + aBookmarks.length + " items\n");
- do_check_true(bmIndex >= 0 && bmIndex < aBookmarks.length);
- indexes.push(bmIndex);
- });
- dump("Checking all valid indexes have been used\n");
- do_check_eq(indexes.length, aBookmarks.length);
-}
-
-// main
-function run_test() {
- var bookmarks = [];
- // Insert bookmarks with random indexes.
- for (let i = 0; bookmarks.length < NUM_BOOKMARKS; i++) {
- let randIndex = Math.round(MIN_RAND + (Math.random() * (MAX_RAND - MIN_RAND)));
- try {
- let id = bs.insertBookmark(bs.unfiledBookmarksFolder,
- uri("http://" + i + ".mozilla.org/"),
- randIndex, "Test bookmark " + i);
- if (randIndex < -1)
- do_throw("Creating a bookmark at an invalid index should throw");
- bookmarks.push(id);
- }
- catch (ex) {
- if (randIndex >= -1)
- do_throw("Creating a bookmark at a valid index should not throw");
- }
- }
- check_contiguous_indexes(bookmarks);
-
- // Insert separators with random indexes.
- for (let i = 0; bookmarks.length < NUM_BOOKMARKS + NUM_SEPARATORS; i++) {
- let randIndex = Math.round(MIN_RAND + (Math.random() * (MAX_RAND - MIN_RAND)));
- try {
- let id = bs.insertSeparator(bs.unfiledBookmarksFolder, randIndex);
- if (randIndex < -1)
- do_throw("Creating a separator at an invalid index should throw");
- bookmarks.push(id);
- }
- catch (ex) {
- if (randIndex >= -1)
- do_throw("Creating a separator at a valid index should not throw");
- }
- }
- check_contiguous_indexes(bookmarks);
-
- // Insert folders with random indexes.
- for (let i = 0; bookmarks.length < NUM_ITEMS; i++) {
- let randIndex = Math.round(MIN_RAND + (Math.random() * (MAX_RAND - MIN_RAND)));
- try {
- let id = bs.createFolder(bs.unfiledBookmarksFolder,
- "Test folder " + i, randIndex);
- if (randIndex < -1)
- do_throw("Creating a folder at an invalid index should throw");
- bookmarks.push(id);
- }
- catch (ex) {
- if (randIndex >= -1)
- do_throw("Creating a folder at a valid index should not throw");
- }
- }
- check_contiguous_indexes(bookmarks);
-
- // Execute some random bookmark delete.
- for (let i = 0; i < Math.ceil(NUM_ITEMS / 4); i++) {
- let id = bookmarks.splice(Math.floor(Math.random() * bookmarks.length), 1);
- dump("Removing item with id " + id + "\n");
- bs.removeItem(id);
- }
- check_contiguous_indexes(bookmarks);
-
- // Execute some random bookmark move. This will also try to move it to
- // invalid index values.
- for (let i = 0; i < Math.ceil(NUM_ITEMS / 4); i++) {
- let randIndex = Math.floor(Math.random() * bookmarks.length);
- let id = bookmarks[randIndex];
- let newIndex = Math.round(MIN_RAND + (Math.random() * (MAX_RAND - MIN_RAND)));
- dump("Moving item with id " + id + " to index " + newIndex + "\n");
- try {
- bs.moveItem(id, bs.unfiledBookmarksFolder, newIndex);
- if (newIndex < -1)
- do_throw("Moving an item to a negative index should throw\n");
- }
- catch (ex) {
- if (newIndex >= -1)
- do_throw("Moving an item to a valid index should not throw\n");
- }
-
- }
- check_contiguous_indexes(bookmarks);
-
- // Ensure setItemIndex throws if we pass it a negative index.
- try {
- bs.setItemIndex(bookmarks[0], -1);
- do_throw("setItemIndex should throw for a negative index");
- } catch (ex) {}
- // Ensure setItemIndex throws if we pass it a bad itemId.
- try {
- bs.setItemIndex(0, 5);
- do_throw("setItemIndex should throw for a bad itemId");
- } catch (ex) {}
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks.js b/toolkit/components/places/tests/bookmarks/test_bookmarks.js
deleted file mode 100644
index b67482223..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks.js
+++ /dev/null
@@ -1,718 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var bs = PlacesUtils.bookmarks;
-var hs = PlacesUtils.history;
-var anno = PlacesUtils.annotations;
-
-
-var bookmarksObserver = {
- onBeginUpdateBatch: function() {
- this._beginUpdateBatch = true;
- },
- onEndUpdateBatch: function() {
- this._endUpdateBatch = true;
- },
- onItemAdded: function(id, folder, index, itemType, uri, title, dateAdded,
- guid) {
- this._itemAddedId = id;
- this._itemAddedParent = folder;
- this._itemAddedIndex = index;
- this._itemAddedURI = uri;
- this._itemAddedTitle = title;
-
- // Ensure that we've created a guid for this item.
- let stmt = DBConn().createStatement(
- `SELECT guid
- FROM moz_bookmarks
- WHERE id = :item_id`
- );
- stmt.params.item_id = id;
- do_check_true(stmt.executeStep());
- do_check_false(stmt.getIsNull(0));
- do_check_valid_places_guid(stmt.row.guid);
- do_check_eq(stmt.row.guid, guid);
- stmt.finalize();
- },
- onItemRemoved: function(id, folder, index, itemType) {
- this._itemRemovedId = id;
- this._itemRemovedFolder = folder;
- this._itemRemovedIndex = index;
- },
- onItemChanged: function(id, property, isAnnotationProperty, value,
- lastModified, itemType, parentId, guid, parentGuid,
- oldValue) {
- this._itemChangedId = id;
- this._itemChangedProperty = property;
- this._itemChanged_isAnnotationProperty = isAnnotationProperty;
- this._itemChangedValue = value;
- this._itemChangedOldValue = oldValue;
- },
- onItemVisited: function(id, visitID, time) {
- this._itemVisitedId = id;
- this._itemVisitedVistId = visitID;
- this._itemVisitedTime = time;
- },
- onItemMoved: function(id, oldParent, oldIndex, newParent, newIndex,
- itemType) {
- this._itemMovedId = id
- this._itemMovedOldParent = oldParent;
- this._itemMovedOldIndex = oldIndex;
- this._itemMovedNewParent = newParent;
- this._itemMovedNewIndex = newIndex;
- },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver,
- ])
-};
-
-
-// Get bookmarks menu folder id.
-var root = bs.bookmarksMenuFolder;
-// Index at which items should begin.
-var bmStartIndex = 0;
-
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_bookmarks() {
- bs.addObserver(bookmarksObserver, false);
-
- // test special folders
- do_check_true(bs.placesRoot > 0);
- do_check_true(bs.bookmarksMenuFolder > 0);
- do_check_true(bs.tagsFolder > 0);
- do_check_true(bs.toolbarFolder > 0);
- do_check_true(bs.unfiledBookmarksFolder > 0);
-
- // test getFolderIdForItem() with bogus item id will throw
- try {
- bs.getFolderIdForItem(0);
- do_throw("getFolderIdForItem accepted bad input");
- } catch (ex) {}
-
- // test getFolderIdForItem() with bogus item id will throw
- try {
- bs.getFolderIdForItem(-1);
- do_throw("getFolderIdForItem accepted bad input");
- } catch (ex) {}
-
- // test root parentage
- do_check_eq(bs.getFolderIdForItem(bs.bookmarksMenuFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.tagsFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.toolbarFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.unfiledBookmarksFolder), bs.placesRoot);
-
- // create a folder to hold all the tests
- // this makes the tests more tolerant of changes to default_places.html
- let testRoot = bs.createFolder(root, "places bookmarks xpcshell tests",
- bs.DEFAULT_INDEX);
- do_check_eq(bookmarksObserver._itemAddedId, testRoot);
- do_check_eq(bookmarksObserver._itemAddedParent, root);
- do_check_eq(bookmarksObserver._itemAddedIndex, bmStartIndex);
- do_check_eq(bookmarksObserver._itemAddedURI, null);
- let testStartIndex = 0;
-
- // test getItemIndex for folders
- do_check_eq(bs.getItemIndex(testRoot), bmStartIndex);
-
- // test getItemType for folders
- do_check_eq(bs.getItemType(testRoot), bs.TYPE_FOLDER);
-
- // insert a bookmark.
- // the time before we insert, in microseconds
- let beforeInsert = Date.now() * 1000;
- do_check_true(beforeInsert > 0);
-
- let newId = bs.insertBookmark(testRoot, uri("http://google.com/"),
- bs.DEFAULT_INDEX, "");
- do_check_eq(bookmarksObserver._itemAddedId, newId);
- do_check_eq(bookmarksObserver._itemAddedParent, testRoot);
- do_check_eq(bookmarksObserver._itemAddedIndex, testStartIndex);
- do_check_true(bookmarksObserver._itemAddedURI.equals(uri("http://google.com/")));
- do_check_eq(bs.getBookmarkURI(newId).spec, "http://google.com/");
-
- let dateAdded = bs.getItemDateAdded(newId);
- // dateAdded can equal beforeInsert
- do_check_true(is_time_ordered(beforeInsert, dateAdded));
-
- // after just inserting, modified should not be set
- let lastModified = bs.getItemLastModified(newId);
- do_check_eq(lastModified, dateAdded);
-
- // The time before we set the title, in microseconds.
- let beforeSetTitle = Date.now() * 1000;
- do_check_true(beforeSetTitle >= beforeInsert);
-
- // Workaround possible VM timers issues moving lastModified and dateAdded
- // to the past.
- lastModified -= 1000;
- bs.setItemLastModified(newId, lastModified);
- dateAdded -= 1000;
- bs.setItemDateAdded(newId, dateAdded);
-
- // set bookmark title
- bs.setItemTitle(newId, "Google");
- do_check_eq(bookmarksObserver._itemChangedId, newId);
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
- do_check_eq(bookmarksObserver._itemChangedValue, "Google");
-
- // check that dateAdded hasn't changed
- let dateAdded2 = bs.getItemDateAdded(newId);
- do_check_eq(dateAdded2, dateAdded);
-
- // check lastModified after we set the title
- let lastModified2 = bs.getItemLastModified(newId);
- do_print("test setItemTitle");
- do_print("dateAdded = " + dateAdded);
- do_print("beforeSetTitle = " + beforeSetTitle);
- do_print("lastModified = " + lastModified);
- do_print("lastModified2 = " + lastModified2);
- do_check_true(is_time_ordered(lastModified, lastModified2));
- do_check_true(is_time_ordered(dateAdded, lastModified2));
-
- // get item title
- let title = bs.getItemTitle(newId);
- do_check_eq(title, "Google");
-
- // test getItemType for bookmarks
- do_check_eq(bs.getItemType(newId), bs.TYPE_BOOKMARK);
-
- // get item title bad input
- try {
- bs.getItemTitle(-3);
- do_throw("getItemTitle accepted bad input");
- } catch (ex) {}
-
- // get the folder that the bookmark is in
- let folderId = bs.getFolderIdForItem(newId);
- do_check_eq(folderId, testRoot);
-
- // test getItemIndex for bookmarks
- do_check_eq(bs.getItemIndex(newId), testStartIndex);
-
- // create a folder at a specific index
- let workFolder = bs.createFolder(testRoot, "Work", 0);
- do_check_eq(bookmarksObserver._itemAddedId, workFolder);
- do_check_eq(bookmarksObserver._itemAddedParent, testRoot);
- do_check_eq(bookmarksObserver._itemAddedIndex, 0);
- do_check_eq(bookmarksObserver._itemAddedURI, null);
-
- do_check_eq(bs.getItemTitle(workFolder), "Work");
- bs.setItemTitle(workFolder, "Work #");
- do_check_eq(bs.getItemTitle(workFolder), "Work #");
-
- // add item into subfolder, specifying index
- let newId2 = bs.insertBookmark(workFolder,
- uri("http://developer.mozilla.org/"),
- 0, "");
- do_check_eq(bookmarksObserver._itemAddedId, newId2);
- do_check_eq(bookmarksObserver._itemAddedParent, workFolder);
- do_check_eq(bookmarksObserver._itemAddedIndex, 0);
-
- // change item
- bs.setItemTitle(newId2, "DevMo");
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
-
- // insert item into subfolder
- let newId3 = bs.insertBookmark(workFolder,
- uri("http://msdn.microsoft.com/"),
- bs.DEFAULT_INDEX, "");
- do_check_eq(bookmarksObserver._itemAddedId, newId3);
- do_check_eq(bookmarksObserver._itemAddedParent, workFolder);
- do_check_eq(bookmarksObserver._itemAddedIndex, 1);
-
- // change item
- bs.setItemTitle(newId3, "MSDN");
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
-
- // remove item
- bs.removeItem(newId2);
- do_check_eq(bookmarksObserver._itemRemovedId, newId2);
- do_check_eq(bookmarksObserver._itemRemovedFolder, workFolder);
- do_check_eq(bookmarksObserver._itemRemovedIndex, 0);
-
- // insert item into subfolder
- let newId4 = bs.insertBookmark(workFolder,
- uri("http://developer.mozilla.org/"),
- bs.DEFAULT_INDEX, "");
- do_check_eq(bookmarksObserver._itemAddedId, newId4);
- do_check_eq(bookmarksObserver._itemAddedParent, workFolder);
- do_check_eq(bookmarksObserver._itemAddedIndex, 1);
-
- // create folder
- let homeFolder = bs.createFolder(testRoot, "Home", bs.DEFAULT_INDEX);
- do_check_eq(bookmarksObserver._itemAddedId, homeFolder);
- do_check_eq(bookmarksObserver._itemAddedParent, testRoot);
- do_check_eq(bookmarksObserver._itemAddedIndex, 2);
-
- // insert item
- let newId5 = bs.insertBookmark(homeFolder, uri("http://espn.com/"),
- bs.DEFAULT_INDEX, "");
- do_check_eq(bookmarksObserver._itemAddedId, newId5);
- do_check_eq(bookmarksObserver._itemAddedParent, homeFolder);
- do_check_eq(bookmarksObserver._itemAddedIndex, 0);
-
- // change item
- bs.setItemTitle(newId5, "ESPN");
- do_check_eq(bookmarksObserver._itemChangedId, newId5);
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
-
- // insert query item
- let uri6 = uri("place:domain=google.com&type="+
- Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY);
- let newId6 = bs.insertBookmark(testRoot, uri6, bs.DEFAULT_INDEX, "");
- do_check_eq(bookmarksObserver._itemAddedParent, testRoot);
- do_check_eq(bookmarksObserver._itemAddedIndex, 3);
-
- // change item
- bs.setItemTitle(newId6, "Google Sites");
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
-
- // test getIdForItemAt
- do_check_eq(bs.getIdForItemAt(testRoot, 0), workFolder);
- // wrong parent, should return -1
- do_check_eq(bs.getIdForItemAt(1337, 0), -1);
- // wrong index, should return -1
- do_check_eq(bs.getIdForItemAt(testRoot, 1337), -1);
- // wrong parent and index, should return -1
- do_check_eq(bs.getIdForItemAt(1337, 1337), -1);
-
- // move folder, appending, to different folder
- let oldParentCC = getChildCount(testRoot);
- bs.moveItem(workFolder, homeFolder, bs.DEFAULT_INDEX);
- do_check_eq(bookmarksObserver._itemMovedId, workFolder);
- do_check_eq(bookmarksObserver._itemMovedOldParent, testRoot);
- do_check_eq(bookmarksObserver._itemMovedOldIndex, 0);
- do_check_eq(bookmarksObserver._itemMovedNewParent, homeFolder);
- do_check_eq(bookmarksObserver._itemMovedNewIndex, 1);
-
- // test that the new index is properly stored
- do_check_eq(bs.getItemIndex(workFolder), 1);
- do_check_eq(bs.getFolderIdForItem(workFolder), homeFolder);
-
- // try to get index of the item from within the old parent folder
- // check that it has been really removed from there
- do_check_neq(bs.getIdForItemAt(testRoot, 0), workFolder);
- // check the last item from within the old parent folder
- do_check_neq(bs.getIdForItemAt(testRoot, -1), workFolder);
- // check the index of the item within the new parent folder
- do_check_eq(bs.getIdForItemAt(homeFolder, 1), workFolder);
- // try to get index of the last item within the new parent folder
- do_check_eq(bs.getIdForItemAt(homeFolder, -1), workFolder);
- // XXX expose FolderCount, and check that the old parent has one less child?
- do_check_eq(getChildCount(testRoot), oldParentCC-1);
-
- // move item, appending, to different folder
- bs.moveItem(newId5, testRoot, bs.DEFAULT_INDEX);
- do_check_eq(bookmarksObserver._itemMovedId, newId5);
- do_check_eq(bookmarksObserver._itemMovedOldParent, homeFolder);
- do_check_eq(bookmarksObserver._itemMovedOldIndex, 0);
- do_check_eq(bookmarksObserver._itemMovedNewParent, testRoot);
- do_check_eq(bookmarksObserver._itemMovedNewIndex, 3);
-
- // test get folder's index
- let tmpFolder = bs.createFolder(testRoot, "tmp", 2);
- do_check_eq(bs.getItemIndex(tmpFolder), 2);
-
- // test setKeywordForBookmark
- let kwTestItemId = bs.insertBookmark(testRoot, uri("http://keywordtest.com"),
- bs.DEFAULT_INDEX, "");
- bs.setKeywordForBookmark(kwTestItemId, "bar");
-
- // test getKeywordForBookmark
- let k = bs.getKeywordForBookmark(kwTestItemId);
- do_check_eq("bar", k);
-
- // test getURIForKeyword
- let u = bs.getURIForKeyword("bar");
- do_check_eq("http://keywordtest.com/", u.spec);
-
- // test removeFolderChildren
- // 1) add/remove each child type (bookmark, separator, folder)
- tmpFolder = bs.createFolder(testRoot, "removeFolderChildren",
- bs.DEFAULT_INDEX);
- bs.insertBookmark(tmpFolder, uri("http://foo9.com/"), bs.DEFAULT_INDEX, "");
- bs.createFolder(tmpFolder, "subfolder", bs.DEFAULT_INDEX);
- bs.insertSeparator(tmpFolder, bs.DEFAULT_INDEX);
- // 2) confirm that folder has 3 children
- let options = hs.getNewQueryOptions();
- let query = hs.getNewQuery();
- query.setFolders([tmpFolder], 1);
- try {
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- do_check_eq(rootNode.childCount, 3);
- rootNode.containerOpen = false;
- } catch (ex) {
- do_throw("test removeFolderChildren() - querying for children failed: " + ex);
- }
- // 3) remove all children
- bs.removeFolderChildren(tmpFolder);
- // 4) confirm that folder has 0 children
- try {
- result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- do_check_eq(rootNode.childCount, 0);
- rootNode.containerOpen = false;
- } catch (ex) {
- do_throw("removeFolderChildren(): " + ex);
- }
-
- // XXX - test folderReadOnly
-
- // test bookmark id in query output
- try {
- options = hs.getNewQueryOptions();
- query = hs.getNewQuery();
- query.setFolders([testRoot], 1);
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- let cc = rootNode.childCount;
- do_print("bookmark itemId test: CC = " + cc);
- do_check_true(cc > 0);
- for (let i=0; i < cc; ++i) {
- let node = rootNode.getChild(i);
- if (node.type == node.RESULT_TYPE_FOLDER ||
- node.type == node.RESULT_TYPE_URI ||
- node.type == node.RESULT_TYPE_SEPARATOR ||
- node.type == node.RESULT_TYPE_QUERY) {
- do_check_true(node.itemId > 0);
- }
- else {
- do_check_eq(node.itemId, -1);
- }
- }
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("bookmarks query: " + ex);
- }
-
- // test that multiple bookmarks with same URI show up right in bookmark
- // folder queries, todo: also to do for complex folder queries
- try {
- // test uri
- let mURI = uri("http://multiple.uris.in.query");
-
- let testFolder = bs.createFolder(testRoot, "test Folder", bs.DEFAULT_INDEX);
- // add 2 bookmarks
- bs.insertBookmark(testFolder, mURI, bs.DEFAULT_INDEX, "title 1");
- bs.insertBookmark(testFolder, mURI, bs.DEFAULT_INDEX, "title 2");
-
- // query
- options = hs.getNewQueryOptions();
- query = hs.getNewQuery();
- query.setFolders([testFolder], 1);
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- let cc = rootNode.childCount;
- do_check_eq(cc, 2);
- do_check_eq(rootNode.getChild(0).title, "title 1");
- do_check_eq(rootNode.getChild(1).title, "title 2");
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("bookmarks query: " + ex);
- }
-
- // test change bookmark uri
- let newId10 = bs.insertBookmark(testRoot, uri("http://foo10.com/"),
- bs.DEFAULT_INDEX, "");
- dateAdded = bs.getItemDateAdded(newId10);
- // after just inserting, modified should not be set
- lastModified = bs.getItemLastModified(newId10);
- do_check_eq(lastModified, dateAdded);
-
- // Workaround possible VM timers issues moving lastModified and dateAdded
- // to the past.
- lastModified -= 1000;
- bs.setItemLastModified(newId10, lastModified);
- dateAdded -= 1000;
- bs.setItemDateAdded(newId10, dateAdded);
-
- bs.changeBookmarkURI(newId10, uri("http://foo11.com/"));
-
- // check that lastModified is set after we change the bookmark uri
- lastModified2 = bs.getItemLastModified(newId10);
- do_print("test changeBookmarkURI");
- do_print("dateAdded = " + dateAdded);
- do_print("lastModified = " + lastModified);
- do_print("lastModified2 = " + lastModified2);
- do_check_true(is_time_ordered(lastModified, lastModified2));
- do_check_true(is_time_ordered(dateAdded, lastModified2));
-
- do_check_eq(bookmarksObserver._itemChangedId, newId10);
- do_check_eq(bookmarksObserver._itemChangedProperty, "uri");
- do_check_eq(bookmarksObserver._itemChangedValue, "http://foo11.com/");
- do_check_eq(bookmarksObserver._itemChangedOldValue, "http://foo10.com/");
-
- // test getBookmarkURI
- let newId11 = bs.insertBookmark(testRoot, uri("http://foo11.com/"),
- bs.DEFAULT_INDEX, "");
- let bmURI = bs.getBookmarkURI(newId11);
- do_check_eq("http://foo11.com/", bmURI.spec);
-
- // test getBookmarkURI with non-bookmark items
- try {
- bs.getBookmarkURI(testRoot);
- do_throw("getBookmarkURI() should throw for non-bookmark items!");
- } catch (ex) {}
-
- // test getItemIndex
- let newId12 = bs.insertBookmark(testRoot, uri("http://foo11.com/"), 1, "");
- let bmIndex = bs.getItemIndex(newId12);
- do_check_eq(1, bmIndex);
-
- // insert a bookmark with title ZZZXXXYYY and then search for it.
- // this test confirms that we can find bookmarks that we haven't visited
- // (which are "hidden") and that we can find by title.
- // see bug #369887 for more details
- let newId13 = bs.insertBookmark(testRoot, uri("http://foobarcheese.com/"),
- bs.DEFAULT_INDEX, "");
- do_check_eq(bookmarksObserver._itemAddedId, newId13);
- do_check_eq(bookmarksObserver._itemAddedParent, testRoot);
- do_check_eq(bookmarksObserver._itemAddedIndex, 11);
-
- // set bookmark title
- bs.setItemTitle(newId13, "ZZZXXXYYY");
- do_check_eq(bookmarksObserver._itemChangedId, newId13);
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
- do_check_eq(bookmarksObserver._itemChangedValue, "ZZZXXXYYY");
-
- // check if setting an item annotation triggers onItemChanged
- bookmarksObserver._itemChangedId = -1;
- anno.setItemAnnotation(newId3, "test-annotation", "foo", 0, 0);
- do_check_eq(bookmarksObserver._itemChangedId, newId3);
- do_check_eq(bookmarksObserver._itemChangedProperty, "test-annotation");
- do_check_true(bookmarksObserver._itemChanged_isAnnotationProperty);
- do_check_eq(bookmarksObserver._itemChangedValue, "");
-
- // test search on bookmark title ZZZXXXYYY
- try {
- options = hs.getNewQueryOptions();
- options.excludeQueries = 1;
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- query = hs.getNewQuery();
- query.searchTerms = "ZZZXXXYYY";
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- let cc = rootNode.childCount;
- do_check_eq(cc, 1);
- let node = rootNode.getChild(0);
- do_check_eq(node.title, "ZZZXXXYYY");
- do_check_true(node.itemId > 0);
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("bookmarks query: " + ex);
- }
-
- // test dateAdded and lastModified properties
- // for a search query
- try {
- options = hs.getNewQueryOptions();
- options.excludeQueries = 1;
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- query = hs.getNewQuery();
- query.searchTerms = "ZZZXXXYYY";
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- let cc = rootNode.childCount;
- do_check_eq(cc, 1);
- let node = rootNode.getChild(0);
-
- do_check_eq(typeof node.dateAdded, "number");
- do_check_true(node.dateAdded > 0);
-
- do_check_eq(typeof node.lastModified, "number");
- do_check_true(node.lastModified > 0);
-
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("bookmarks query: " + ex);
- }
-
- // test dateAdded and lastModified properties
- // for a folder query
- try {
- options = hs.getNewQueryOptions();
- query = hs.getNewQuery();
- query.setFolders([testRoot], 1);
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- let cc = rootNode.childCount;
- do_check_true(cc > 0);
- for (let i = 0; i < cc; i++) {
- let node = rootNode.getChild(i);
-
- if (node.type == node.RESULT_TYPE_URI) {
- do_check_eq(typeof node.dateAdded, "number");
- do_check_true(node.dateAdded > 0);
-
- do_check_eq(typeof node.lastModified, "number");
- do_check_true(node.lastModified > 0);
- break;
- }
- }
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("bookmarks query: " + ex);
- }
-
- // check setItemLastModified() and setItemDateAdded()
- let newId14 = bs.insertBookmark(testRoot, uri("http://bar.tld/"),
- bs.DEFAULT_INDEX, "");
- dateAdded = bs.getItemDateAdded(newId14);
- lastModified = bs.getItemLastModified(newId14);
- do_check_eq(lastModified, dateAdded);
- bs.setItemLastModified(newId14, 1234000000000000);
- let fakeLastModified = bs.getItemLastModified(newId14);
- do_check_eq(fakeLastModified, 1234000000000000);
- bs.setItemDateAdded(newId14, 4321000000000000);
- let fakeDateAdded = bs.getItemDateAdded(newId14);
- do_check_eq(fakeDateAdded, 4321000000000000);
-
- // ensure that removing an item removes its annotations
- do_check_true(anno.itemHasAnnotation(newId3, "test-annotation"));
- bs.removeItem(newId3);
- do_check_false(anno.itemHasAnnotation(newId3, "test-annotation"));
-
- // bug 378820
- let uri1 = uri("http://foo.tld/a");
- bs.insertBookmark(testRoot, uri1, bs.DEFAULT_INDEX, "");
- yield PlacesTestUtils.addVisits(uri1);
-
- // bug 646993 - test bookmark titles longer than the maximum allowed length
- let title15 = Array(TITLE_LENGTH_MAX + 5).join("X");
- let title15expected = title15.substring(0, TITLE_LENGTH_MAX);
- let newId15 = bs.insertBookmark(testRoot, uri("http://evil.com/"),
- bs.DEFAULT_INDEX, title15);
-
- do_check_eq(bs.getItemTitle(newId15).length,
- title15expected.length);
- do_check_eq(bookmarksObserver._itemAddedTitle, title15expected);
- // test title length after updates
- bs.setItemTitle(newId15, title15 + " updated");
- do_check_eq(bs.getItemTitle(newId15).length,
- title15expected.length);
- do_check_eq(bookmarksObserver._itemChangedId, newId15);
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
- do_check_eq(bookmarksObserver._itemChangedValue, title15expected);
-
- testSimpleFolderResult();
-});
-
-function testSimpleFolderResult() {
- // the time before we create a folder, in microseconds
- // Workaround possible VM timers issues subtracting 1us.
- let beforeCreate = Date.now() * 1000 - 1;
- do_check_true(beforeCreate > 0);
-
- // create a folder
- let parent = bs.createFolder(root, "test", bs.DEFAULT_INDEX);
-
- let dateCreated = bs.getItemDateAdded(parent);
- do_print("check that the folder was created with a valid dateAdded");
- do_print("beforeCreate = " + beforeCreate);
- do_print("dateCreated = " + dateCreated);
- do_check_true(is_time_ordered(beforeCreate, dateCreated));
-
- // the time before we insert, in microseconds
- // Workaround possible VM timers issues subtracting 1ms.
- let beforeInsert = Date.now() * 1000 - 1;
- do_check_true(beforeInsert > 0);
-
- // insert a separator
- let sep = bs.insertSeparator(parent, bs.DEFAULT_INDEX);
-
- let dateAdded = bs.getItemDateAdded(sep);
- do_print("check that the separator was created with a valid dateAdded");
- do_print("beforeInsert = " + beforeInsert);
- do_print("dateAdded = " + dateAdded);
- do_check_true(is_time_ordered(beforeInsert, dateAdded));
-
- // re-set item title separately so can test nodes' last modified
- let item = bs.insertBookmark(parent, uri("about:blank"),
- bs.DEFAULT_INDEX, "");
- bs.setItemTitle(item, "test bookmark");
-
- // see above
- let folder = bs.createFolder(parent, "test folder", bs.DEFAULT_INDEX);
- bs.setItemTitle(folder, "test folder");
-
- let longName = Array(TITLE_LENGTH_MAX + 5).join("A");
- let folderLongName = bs.createFolder(parent, longName, bs.DEFAULT_INDEX);
- do_check_eq(bookmarksObserver._itemAddedTitle, longName.substring(0, TITLE_LENGTH_MAX));
-
- let options = hs.getNewQueryOptions();
- let query = hs.getNewQuery();
- query.setFolders([parent], 1);
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- do_check_eq(rootNode.childCount, 4);
-
- let node = rootNode.getChild(0);
- do_check_true(node.dateAdded > 0);
- do_check_eq(node.lastModified, node.dateAdded);
- do_check_eq(node.itemId, sep);
- do_check_eq(node.title, "");
- node = rootNode.getChild(1);
- do_check_eq(node.itemId, item);
- do_check_true(node.dateAdded > 0);
- do_check_true(node.lastModified > 0);
- do_check_eq(node.title, "test bookmark");
- node = rootNode.getChild(2);
- do_check_eq(node.itemId, folder);
- do_check_eq(node.title, "test folder");
- do_check_true(node.dateAdded > 0);
- do_check_true(node.lastModified > 0);
- node = rootNode.getChild(3);
- do_check_eq(node.itemId, folderLongName);
- do_check_eq(node.title, longName.substring(0, TITLE_LENGTH_MAX));
- do_check_true(node.dateAdded > 0);
- do_check_true(node.lastModified > 0);
-
- // update with another long title
- bs.setItemTitle(folderLongName, longName + " updated");
- do_check_eq(bookmarksObserver._itemChangedId, folderLongName);
- do_check_eq(bookmarksObserver._itemChangedProperty, "title");
- do_check_eq(bookmarksObserver._itemChangedValue, longName.substring(0, TITLE_LENGTH_MAX));
-
- node = rootNode.getChild(3);
- do_check_eq(node.title, longName.substring(0, TITLE_LENGTH_MAX));
-
- rootNode.containerOpen = false;
-}
-
-function getChildCount(aFolderId) {
- let cc = -1;
- try {
- let options = hs.getNewQueryOptions();
- let query = hs.getNewQuery();
- query.setFolders([aFolderId], 1);
- let result = hs.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- cc = rootNode.childCount;
- rootNode.containerOpen = false;
- } catch (ex) {
- do_throw("getChildCount failed: " + ex);
- }
- return cc;
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_eraseEverything.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_eraseEverything.js
deleted file mode 100644
index e8414359b..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_eraseEverything.js
+++ /dev/null
@@ -1,116 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* test_eraseEverything() {
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("http://example.com/") });
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("http://mozilla.org/") });
- let frecencyForExample = frecencyForUrl("http://example.com/");
- let frecencyForMozilla = frecencyForUrl("http://example.com/");
- Assert.ok(frecencyForExample > 0);
- Assert.ok(frecencyForMozilla > 0);
- let unfiledFolder = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- checkBookmarkObject(unfiledFolder);
- let unfiledBookmark = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/" });
- checkBookmarkObject(unfiledBookmark);
- let unfiledBookmarkInFolder =
- yield PlacesUtils.bookmarks.insert({ parentGuid: unfiledFolder.guid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://mozilla.org/" });
- checkBookmarkObject(unfiledBookmarkInFolder);
- PlacesUtils.annotations.setItemAnnotation((yield PlacesUtils.promiseItemId(unfiledBookmarkInFolder.guid)),
- "testanno1", "testvalue1", 0, 0);
-
- let menuFolder = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.menuGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- checkBookmarkObject(menuFolder);
- let menuBookmark = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.menuGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/" });
- checkBookmarkObject(menuBookmark);
- let menuBookmarkInFolder =
- yield PlacesUtils.bookmarks.insert({ parentGuid: menuFolder.guid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://mozilla.org/" });
- checkBookmarkObject(menuBookmarkInFolder);
- PlacesUtils.annotations.setItemAnnotation((yield PlacesUtils.promiseItemId(menuBookmarkInFolder.guid)),
- "testanno1", "testvalue1", 0, 0);
-
- let toolbarFolder = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- checkBookmarkObject(toolbarFolder);
- let toolbarBookmark = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/" });
- checkBookmarkObject(toolbarBookmark);
- let toolbarBookmarkInFolder =
- yield PlacesUtils.bookmarks.insert({ parentGuid: toolbarFolder.guid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://mozilla.org/" });
- checkBookmarkObject(toolbarBookmarkInFolder);
- PlacesUtils.annotations.setItemAnnotation((yield PlacesUtils.promiseItemId(toolbarBookmarkInFolder.guid)),
- "testanno1", "testvalue1", 0, 0);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- Assert.ok(frecencyForUrl("http://example.com/") > frecencyForExample);
- Assert.ok(frecencyForUrl("http://example.com/") > frecencyForMozilla);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- Assert.equal(frecencyForUrl("http://example.com/"), frecencyForExample);
- Assert.equal(frecencyForUrl("http://example.com/"), frecencyForMozilla);
-
- // Check there are no orphan annotations.
- let conn = yield PlacesUtils.promiseDBConnection();
- let annoAttrs = yield conn.execute(`SELECT id, name FROM moz_anno_attributes`);
- // Bug 1306445 will eventually remove the mobile root anno.
- Assert.equal(annoAttrs.length, 1);
- Assert.equal(annoAttrs[0].getResultByName("name"), PlacesUtils.MOBILE_ROOT_ANNO);
- let annos = rows = yield conn.execute(`SELECT item_id, anno_attribute_id FROM moz_items_annos`);
- Assert.equal(annos.length, 1);
- Assert.equal(annos[0].getResultByName("item_id"), PlacesUtils.mobileFolderId);
- Assert.equal(annos[0].getResultByName("anno_attribute_id"), annoAttrs[0].getResultByName("id"));
-});
-
-add_task(function* test_eraseEverything_roots() {
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Ensure the roots have not been removed.
- Assert.ok(yield PlacesUtils.bookmarks.fetch(PlacesUtils.bookmarks.unfiledGuid));
- Assert.ok(yield PlacesUtils.bookmarks.fetch(PlacesUtils.bookmarks.toolbarGuid));
- Assert.ok(yield PlacesUtils.bookmarks.fetch(PlacesUtils.bookmarks.menuGuid));
- Assert.ok(yield PlacesUtils.bookmarks.fetch(PlacesUtils.bookmarks.tagsGuid));
- Assert.ok(yield PlacesUtils.bookmarks.fetch(PlacesUtils.bookmarks.rootGuid));
-});
-
-add_task(function* test_eraseEverything_reparented() {
- // Create a folder with 1 bookmark in it...
- let folder1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER
- });
- let bookmark1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder1.guid,
- url: "http://example.com/"
- });
- // ...and a second folder.
- let folder2 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER
- });
-
- // Reparent the bookmark to the 2nd folder.
- bookmark1.parentGuid = folder2.guid;
- yield PlacesUtils.bookmarks.update(bookmark1);
-
- // Erase everything.
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // All the above items should no longer be in the GUIDHelper cache.
- for (let guid of [folder1.guid, bookmark1.guid, folder2.guid]) {
- yield Assert.rejects(PlacesUtils.promiseItemId(guid),
- /no item found for the given GUID/);
- }
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_fetch.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_fetch.js
deleted file mode 100644
index 9527f02e6..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_fetch.js
+++ /dev/null
@@ -1,310 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var gAccumulator = {
- get callback() {
- this.results = [];
- return result => this.results.push(result);
- }
-};
-
-add_task(function* invalid_input_throws() {
- Assert.throws(() => PlacesUtils.bookmarks.fetch(),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch(null),
- /Input should be a valid object/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ guid: "123456789012",
- parentGuid: "012345678901" }),
- /The following properties were expected: index/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ guid: "123456789012",
- index: 0 }),
- /The following properties were expected: parentGuid/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch({}),
- /Unexpected number of conditions provided: 0/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ guid: "123456789012",
- parentGuid: "012345678901",
- index: 0 }),
- /Unexpected number of conditions provided: 2/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ guid: "123456789012",
- url: "http://example.com"}),
- /Unexpected number of conditions provided: 2/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch("test"),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch(123),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ guid: "test" }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ guid: null }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ guid: 123 }),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ parentGuid: "test",
- index: 0 }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ parentGuid: null,
- index: 0 }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ parentGuid: 123,
- index: 0 }),
- /Invalid value for property 'parentGuid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ parentGuid: "123456789012",
- index: "0" }),
- /Invalid value for property 'index'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ parentGuid: "123456789012",
- index: null }),
- /Invalid value for property 'index'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ parentGuid: "123456789012",
- index: -10 }),
- /Invalid value for property 'index'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ url: "http://te st/" }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ url: null }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch({ url: -10 }),
- /Invalid value for property 'url'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.fetch("123456789012", "test"),
- /onResult callback must be a valid function/);
- Assert.throws(() => PlacesUtils.bookmarks.fetch("123456789012", {}),
- /onResult callback must be a valid function/);
-});
-
-add_task(function* fetch_nonexistent_guid() {
- let bm = yield PlacesUtils.bookmarks.fetch({ guid: "123456789012" },
- gAccumulator.callback);
- Assert.equal(bm, null);
- Assert.equal(gAccumulator.results.length, 0);
-});
-
-add_task(function* fetch_bookmark() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch(bm1.guid,
- gAccumulator.callback);
- checkBookmarkObject(bm2);
- Assert.equal(gAccumulator.results.length, 1);
- checkBookmarkObject(gAccumulator.results[0]);
- Assert.deepEqual(gAccumulator.results[0], bm1);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 0);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm2.url.href, "http://example.com/");
- Assert.equal(bm2.title, "a bookmark");
-
- yield PlacesUtils.bookmarks.remove(bm1.guid);
-});
-
-add_task(function* fetch_bookmar_empty_title() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.index, 0);
- Assert.ok(!("title" in bm2));
-
- yield PlacesUtils.bookmarks.remove(bm1.guid);
-});
-
-add_task(function* fetch_folder() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a folder" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 0);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- Assert.equal(bm2.title, "a folder");
- Assert.ok(!("url" in bm2));
-
- yield PlacesUtils.bookmarks.remove(bm1.guid);
-});
-
-add_task(function* fetch_folder_empty_title() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.index, 0);
- Assert.ok(!("title" in bm2));
-
- yield PlacesUtils.bookmarks.remove(bm1.guid);
-});
-
-add_task(function* fetch_separator() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 0);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- Assert.ok(!("url" in bm2));
- Assert.ok(!("title" in bm2));
-
- yield PlacesUtils.bookmarks.remove(bm1.guid);
-});
-
-add_task(function* fetch_byposition_nonexisting_parentGuid() {
- let bm = yield PlacesUtils.bookmarks.fetch({ parentGuid: "123456789012",
- index: 0 },
- gAccumulator.callback);
- Assert.equal(bm, null);
- Assert.equal(gAccumulator.results.length, 0);
-});
-
-add_task(function* fetch_byposition_nonexisting_index() {
- let bm = yield PlacesUtils.bookmarks.fetch({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: 100 },
- gAccumulator.callback);
- Assert.equal(bm, null);
- Assert.equal(gAccumulator.results.length, 0);
-});
-
-add_task(function* fetch_byposition() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch({ parentGuid: bm1.parentGuid,
- index: bm1.index },
- gAccumulator.callback);
- checkBookmarkObject(bm2);
- Assert.equal(gAccumulator.results.length, 1);
- checkBookmarkObject(gAccumulator.results[0]);
- Assert.deepEqual(gAccumulator.results[0], bm1);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 0);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm2.url.href, "http://example.com/");
- Assert.equal(bm2.title, "a bookmark");
-});
-
-add_task(function* fetch_byposition_default_index() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/last",
- title: "last child" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch({ parentGuid: bm1.parentGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX },
- gAccumulator.callback);
- checkBookmarkObject(bm2);
- Assert.equal(gAccumulator.results.length, 1);
- checkBookmarkObject(gAccumulator.results[0]);
- Assert.deepEqual(gAccumulator.results[0], bm1);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 1);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm2.url.href, "http://example.com/last");
- Assert.equal(bm2.title, "last child");
-
- yield PlacesUtils.bookmarks.remove(bm1.guid);
-});
-
-add_task(function* fetch_byurl_nonexisting() {
- let bm = yield PlacesUtils.bookmarks.fetch({ url: "http://nonexisting.com/" },
- gAccumulator.callback);
- Assert.equal(bm, null);
- Assert.equal(gAccumulator.results.length, 0);
-});
-
-add_task(function* fetch_byurl() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://byurl.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm1);
-
- // Also ensure that fecth-by-url excludes the tags folder.
- PlacesUtils.tagging.tagURI(uri(bm1.url.href), ["Test Tag"]);
-
- let bm2 = yield PlacesUtils.bookmarks.fetch({ url: bm1.url },
- gAccumulator.callback);
- checkBookmarkObject(bm2);
- Assert.equal(gAccumulator.results.length, 1);
- checkBookmarkObject(gAccumulator.results[0]);
- Assert.deepEqual(gAccumulator.results[0], bm1);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm2.url.href, "http://byurl.com/");
- Assert.equal(bm2.title, "a bookmark");
-
- let bm3 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://byurl.com/",
- title: "a bookmark" });
- let bm4 = yield PlacesUtils.bookmarks.fetch({ url: bm1.url },
- gAccumulator.callback);
- checkBookmarkObject(bm4);
- Assert.deepEqual(bm3, bm4);
- Assert.equal(gAccumulator.results.length, 2);
- gAccumulator.results.forEach(checkBookmarkObject);
- Assert.deepEqual(gAccumulator.results[0], bm4);
-
- // After an update the returned bookmark should change.
- yield PlacesUtils.bookmarks.update({ guid: bm1.guid, title: "new title" });
- let bm5 = yield PlacesUtils.bookmarks.fetch({ url: bm1.url },
- gAccumulator.callback);
- checkBookmarkObject(bm5);
- // Cannot use deepEqual cause lastModified changed.
- Assert.equal(bm1.guid, bm5.guid);
- Assert.ok(bm5.lastModified > bm1.lastModified);
- Assert.equal(gAccumulator.results.length, 2);
- gAccumulator.results.forEach(checkBookmarkObject);
- Assert.deepEqual(gAccumulator.results[0], bm5);
-
- // cleanup
- PlacesUtils.tagging.untagURI(uri(bm1.url.href), ["Test Tag"]);
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_getRecent.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_getRecent.js
deleted file mode 100644
index 35166bd95..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_getRecent.js
+++ /dev/null
@@ -1,44 +0,0 @@
-add_task(function* invalid_input_throws() {
- Assert.throws(() => PlacesUtils.bookmarks.getRecent(),
- /numberOfItems argument is required/);
- Assert.throws(() => PlacesUtils.bookmarks.getRecent("abc"),
- /numberOfItems argument must be an integer/);
- Assert.throws(() => PlacesUtils.bookmarks.getRecent(1.2),
- /numberOfItems argument must be an integer/);
- Assert.throws(() => PlacesUtils.bookmarks.getRecent(0),
- /numberOfItems argument must be greater than zero/);
- Assert.throws(() => PlacesUtils.bookmarks.getRecent(-1),
- /numberOfItems argument must be greater than zero/);
-});
-
-add_task(function* getRecent_returns_recent_bookmarks() {
- yield PlacesUtils.bookmarks.eraseEverything();
-
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- title: "a bookmark" });
- let bm2 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.org/path",
- title: "another bookmark" });
- let bm3 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.net/",
- title: "another bookmark" });
- let bm4 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.net/path",
- title: "yet another bookmark" });
- checkBookmarkObject(bm1);
- checkBookmarkObject(bm2);
- checkBookmarkObject(bm3);
- checkBookmarkObject(bm4);
-
- let results = yield PlacesUtils.bookmarks.getRecent(3);
- Assert.equal(results.length, 3);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm4, results[0]);
- checkBookmarkObject(results[1]);
- Assert.deepEqual(bm3, results[1]);
- checkBookmarkObject(results[2]);
- Assert.deepEqual(bm2, results[2]);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_insert.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_insert.js
deleted file mode 100644
index 0f772a92f..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_insert.js
+++ /dev/null
@@ -1,264 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* invalid_input_throws() {
- Assert.throws(() => PlacesUtils.bookmarks.insert(),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.bookmarks.insert(null),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({}),
- /The following properties were expected/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ guid: "test" }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ guid: null }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ guid: 123 }),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ parentGuid: "test" }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ parentGuid: null }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ parentGuid: 123 }),
- /Invalid value for property 'parentGuid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ index: "1" }),
- /Invalid value for property 'index'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ index: -10 }),
- /Invalid value for property 'index'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ dateAdded: -10 }),
- /Invalid value for property 'dateAdded'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ dateAdded: "today" }),
- /Invalid value for property 'dateAdded'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ dateAdded: Date.now() }),
- /Invalid value for property 'dateAdded'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ lastModified: -10 }),
- /Invalid value for property 'lastModified'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ lastModified: "today" }),
- /Invalid value for property 'lastModified'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ lastModified: Date.now() }),
- /Invalid value for property 'lastModified'/);
- let time = new Date();
- let future = new Date(time + 86400000);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ dateAdded: future,
- lastModified: time }),
- /Invalid value for property 'dateAdded'/);
- let past = new Date(time - 86400000);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ lastModified: past }),
- /Invalid value for property 'lastModified'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: -1 }),
- /Invalid value for property 'type'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: 100 }),
- /Invalid value for property 'type'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: "bookmark" }),
- /Invalid value for property 'type'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- title: -1 }),
- /Invalid value for property 'title'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: 10 }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://te st" }),
- /Invalid value for property 'url'/);
- let longurl = "http://www.example.com/";
- for (let i = 0; i < 65536; i++) {
- longurl += "a";
- }
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: longurl }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: NetUtil.newURI(longurl) }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "te st" }),
- /Invalid value for property 'url'/);
-});
-
-add_task(function* invalid_properties_for_bookmark_type() {
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- url: "http://www.moz.com/" }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- url: "http://www.moz.com/" }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- title: "test" }),
- /Invalid value for property 'title'/);
-});
-
-add_task(function* long_title_trim() {
- let longtitle = "a";
- for (let i = 0; i < 4096; i++) {
- longtitle += "a";
- }
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: longtitle });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm.index, 0);
- Assert.equal(bm.dateAdded, bm.lastModified);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- Assert.equal(bm.title.length, 4096, "title should have been trimmed");
- Assert.ok(!("url" in bm), "url should not be set");
-});
-
-add_task(function* create_separator() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm.index, 1);
- Assert.equal(bm.dateAdded, bm.lastModified);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- Assert.ok(!("title" in bm), "title should not be set");
-});
-
-add_task(function* create_separator_w_title_fail() {
- try {
- yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- title: "a separator" });
- Assert.ok(false, "Trying to set title for a separator should reject");
- } catch (ex) {}
-});
-
-add_task(function* create_separator_invalid_parent_fail() {
- try {
- yield PlacesUtils.bookmarks.insert({ parentGuid: "123456789012",
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- title: "a separator" });
- Assert.ok(false, "Trying to create an item in a non existing parent reject");
- } catch (ex) {}
-});
-
-add_task(function* create_separator_given_guid() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- guid: "123456789012" });
- checkBookmarkObject(bm);
- Assert.equal(bm.guid, "123456789012");
- Assert.equal(bm.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm.index, 2);
- Assert.equal(bm.dateAdded, bm.lastModified);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- Assert.ok(!("title" in bm), "title should not be set");
-});
-
-add_task(function* create_item_given_guid_no_type_fail() {
- try {
- yield PlacesUtils.bookmarks.insert({ parentGuid: "123456789012" });
- Assert.ok(false, "Trying to create an item with a given guid but no type should reject");
- } catch (ex) {}
-});
-
-add_task(function* create_separator_big_index() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- index: 9999 });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm.index, 3);
- Assert.equal(bm.dateAdded, bm.lastModified);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- Assert.ok(!("title" in bm), "title should not be set");
-});
-
-add_task(function* create_separator_given_dateAdded() {
- let time = new Date();
- let past = new Date(time - 86400000);
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- dateAdded: past });
- checkBookmarkObject(bm);
- Assert.equal(bm.dateAdded, past);
- Assert.equal(bm.lastModified, past);
-});
-
-add_task(function* create_folder() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm.dateAdded, bm.lastModified);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- Assert.ok(!("title" in bm), "title should not be set");
-
- // And then create a nested folder.
- let parentGuid = bm.guid;
- bm = yield PlacesUtils.bookmarks.insert({ parentGuid: parentGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a folder" });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, parentGuid);
- Assert.equal(bm.index, 0);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- Assert.strictEqual(bm.title, "a folder");
-});
-
-add_task(function* create_bookmark() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- let parentGuid = bm.guid;
-
- bm = yield PlacesUtils.bookmarks.insert({ parentGuid: parentGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, parentGuid);
- Assert.equal(bm.index, 0);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm.url.href, "http://example.com/");
- Assert.equal(bm.title, "a bookmark");
-
- // Check parent lastModified.
- let parent = yield PlacesUtils.bookmarks.fetch({ guid: bm.parentGuid });
- Assert.deepEqual(parent.lastModified, bm.dateAdded);
-
- bm = yield PlacesUtils.bookmarks.insert({ parentGuid: parentGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: new URL("http://example.com/") });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, parentGuid);
- Assert.equal(bm.index, 1);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm.url.href, "http://example.com/");
- Assert.ok(!("title" in bm), "title should not be set");
-});
-
-add_task(function* create_bookmark_frecency() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- Assert.ok(frecencyForUrl(bm.url) > 0, "Check frecency has been updated")
-});
-
-add_task(function* create_bookmark_without_type() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm.url.href, "http://example.com/");
- Assert.equal(bm.title, "a bookmark");
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_notifications.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_notifications.js
deleted file mode 100644
index 02787425d..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_notifications.js
+++ /dev/null
@@ -1,527 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* insert_separator_notification() {
- let observer = expectNotifications();
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid});
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
- observer.check([ { name: "onItemAdded",
- arguments: [ itemId, parentId, bm.index, bm.type,
- null, null, bm.dateAdded,
- bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* insert_folder_notification() {
- let observer = expectNotifications();
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "a folder" });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
- observer.check([ { name: "onItemAdded",
- arguments: [ itemId, parentId, bm.index, bm.type,
- null, bm.title, bm.dateAdded,
- bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* insert_folder_notitle_notification() {
- let observer = expectNotifications();
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
- observer.check([ { name: "onItemAdded",
- arguments: [ itemId, parentId, bm.index, bm.type,
- null, null, bm.dateAdded,
- bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* insert_bookmark_notification() {
- let observer = expectNotifications();
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://example.com/"),
- title: "a bookmark" });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
- observer.check([ { name: "onItemAdded",
- arguments: [ itemId, parentId, bm.index, bm.type,
- bm.url, bm.title, bm.dateAdded,
- bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* insert_bookmark_notitle_notification() {
- let observer = expectNotifications();
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://example.com/") });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
- observer.check([ { name: "onItemAdded",
- arguments: [ itemId, parentId, bm.index, bm.type,
- bm.url, null, bm.dateAdded,
- bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* insert_bookmark_tag_notification() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://tag.example.com/") });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- let tagFolder = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.tagsGuid,
- title: "tag" });
- let observer = expectNotifications();
- let tag = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: tagFolder.guid,
- url: new URL("http://tag.example.com/") });
- let tagId = yield PlacesUtils.promiseItemId(tag.guid);
- let tagParentId = yield PlacesUtils.promiseItemId(tag.parentGuid);
-
- observer.check([ { name: "onItemAdded",
- arguments: [ tagId, tagParentId, tag.index, tag.type,
- tag.url, null, tag.dateAdded,
- tag.guid, tag.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ itemId, "tags", false, "",
- bm.lastModified, bm.type, parentId,
- bm.guid, bm.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* update_bookmark_lastModified() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://lastmod.example.com/") });
- let observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- lastModified: new Date() });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- observer.check([ { name: "onItemChanged",
- arguments: [ itemId, "lastModified", false,
- `${bm.lastModified * 1000}`, bm.lastModified,
- bm.type, parentId, bm.guid, bm.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* update_bookmark_title() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://title.example.com/") });
- let observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- title: "new title" });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- observer.check([ { name: "onItemChanged",
- arguments: [ itemId, "title", false, bm.title,
- bm.lastModified, bm.type, parentId, bm.guid,
- bm.parentGuid, "", Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* update_bookmark_uri() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://url.example.com/") });
- let observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- url: "http://mozilla.org/" });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- observer.check([ { name: "onItemChanged",
- arguments: [ itemId, "uri", false, bm.url.href,
- bm.lastModified, bm.type, parentId, bm.guid,
- bm.parentGuid, "http://url.example.com/",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* update_move_same_folder() {
- // Ensure there are at least two items in place (others test do so for us,
- // but we don't have to depend on that).
- yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://move.example.com/") });
- let bmItemId = yield PlacesUtils.promiseItemId(bm.guid);
- let bmParentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
- let bmOldIndex = bm.index;
-
- let observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: 0 });
- Assert.equal(bm.index, 0);
- observer.check([ { name: "onItemMoved",
- arguments: [ bmItemId, bmParentId, bmOldIndex, bmParentId, bm.index,
- bm.type, bm.guid, bm.parentGuid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-
- // Test that we get the right index for DEFAULT_INDEX input.
- bmOldIndex = 0;
- observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX });
- Assert.ok(bm.index > 0);
- observer.check([ { name: "onItemMoved",
- arguments: [ bmItemId, bmParentId, bmOldIndex, bmParentId, bm.index,
- bm.type, bm.guid, bm.parentGuid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* update_move_different_folder() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://move.example.com/") });
- let folder = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let bmItemId = yield PlacesUtils.promiseItemId(bm.guid);
- let bmOldParentId = PlacesUtils.unfiledBookmarksFolderId;
- let bmOldIndex = bm.index;
-
- let observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- parentGuid: folder.guid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX });
- Assert.equal(bm.index, 0);
- let bmNewParentId = yield PlacesUtils.promiseItemId(folder.guid);
- observer.check([ { name: "onItemMoved",
- arguments: [ bmItemId, bmOldParentId, bmOldIndex, bmNewParentId,
- bm.index, bm.type, bm.guid,
- PlacesUtils.bookmarks.unfiledGuid,
- bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* remove_bookmark() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://remove.example.com/") });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- let observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.remove(bm.guid);
- // TODO (Bug 653910): onItemAnnotationRemoved notified even if there were no
- // annotations.
- observer.check([ { name: "onItemRemoved",
- arguments: [ itemId, parentId, bm.index, bm.type, bm.url,
- bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* remove_folder() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- let observer = expectNotifications();
- bm = yield PlacesUtils.bookmarks.remove(bm.guid);
- observer.check([ { name: "onItemRemoved",
- arguments: [ itemId, parentId, bm.index, bm.type, null,
- bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* remove_bookmark_tag_notification() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: new URL("http://untag.example.com/") });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- let tagFolder = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.tagsGuid,
- title: "tag" });
- let tag = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: tagFolder.guid,
- url: new URL("http://untag.example.com/") });
- let tagId = yield PlacesUtils.promiseItemId(tag.guid);
- let tagParentId = yield PlacesUtils.promiseItemId(tag.parentGuid);
-
- let observer = expectNotifications();
- yield PlacesUtils.bookmarks.remove(tag.guid);
-
- observer.check([ { name: "onItemRemoved",
- arguments: [ tagId, tagParentId, tag.index, tag.type,
- tag.url, tag.guid, tag.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ itemId, "tags", false, "",
- bm.lastModified, bm.type, parentId,
- bm.guid, bm.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* remove_folder_notification() {
- let folder1 = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let folder1Id = yield PlacesUtils.promiseItemId(folder1.guid);
- let folder1ParentId = yield PlacesUtils.promiseItemId(folder1.parentGuid);
-
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: folder1.guid,
- url: new URL("http://example.com/") });
- let bmItemId = yield PlacesUtils.promiseItemId(bm.guid);
-
- let folder2 = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: folder1.guid });
- let folder2Id = yield PlacesUtils.promiseItemId(folder2.guid);
-
- let bm2 = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: folder2.guid,
- url: new URL("http://example.com/") });
- let bm2ItemId = yield PlacesUtils.promiseItemId(bm2.guid);
-
- let observer = expectNotifications();
- yield PlacesUtils.bookmarks.remove(folder1.guid);
-
- observer.check([ { name: "onItemRemoved",
- arguments: [ bm2ItemId, folder2Id, bm2.index, bm2.type,
- bm2.url, bm2.guid, bm2.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ folder2Id, folder1Id, folder2.index,
- folder2.type, null, folder2.guid,
- folder2.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ bmItemId, folder1Id, bm.index, bm.type,
- bm.url, bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ folder1Id, folder1ParentId, folder1.index,
- folder1.type, null, folder1.guid,
- folder1.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-});
-
-add_task(function* eraseEverything_notification() {
- // Let's start from a clean situation.
- yield PlacesUtils.bookmarks.eraseEverything();
-
- let folder1 = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let folder1Id = yield PlacesUtils.promiseItemId(folder1.guid);
- let folder1ParentId = yield PlacesUtils.promiseItemId(folder1.parentGuid);
-
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: folder1.guid,
- url: new URL("http://example.com/") });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- let folder2 = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let folder2Id = yield PlacesUtils.promiseItemId(folder2.guid);
- let folder2ParentId = yield PlacesUtils.promiseItemId(folder2.parentGuid);
-
- let toolbarBm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: new URL("http://example.com/") });
- let toolbarBmId = yield PlacesUtils.promiseItemId(toolbarBm.guid);
- let toolbarBmParentId = yield PlacesUtils.promiseItemId(toolbarBm.parentGuid);
-
- let menuBm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- url: new URL("http://example.com/") });
- let menuBmId = yield PlacesUtils.promiseItemId(menuBm.guid);
- let menuBmParentId = yield PlacesUtils.promiseItemId(menuBm.parentGuid);
-
- let observer = expectNotifications();
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Bookmarks should always be notified before their parents.
- observer.check([ { name: "onItemRemoved",
- arguments: [ itemId, parentId, bm.index, bm.type,
- bm.url, bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ folder2Id, folder2ParentId, folder2.index,
- folder2.type, null, folder2.guid,
- folder2.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ folder1Id, folder1ParentId, folder1.index,
- folder1.type, null, folder1.guid,
- folder1.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ menuBmId, menuBmParentId,
- menuBm.index, menuBm.type,
- menuBm.url, menuBm.guid,
- menuBm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ toolbarBmId, toolbarBmParentId,
- toolbarBm.index, toolbarBm.type,
- toolbarBm.url, toolbarBm.guid,
- toolbarBm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- ]);
-});
-
-add_task(function* eraseEverything_reparented_notification() {
- // Let's start from a clean situation.
- yield PlacesUtils.bookmarks.eraseEverything();
-
- let folder1 = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let folder1Id = yield PlacesUtils.promiseItemId(folder1.guid);
- let folder1ParentId = yield PlacesUtils.promiseItemId(folder1.parentGuid);
-
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: folder1.guid,
- url: new URL("http://example.com/") });
- let itemId = yield PlacesUtils.promiseItemId(bm.guid);
-
- let folder2 = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let folder2Id = yield PlacesUtils.promiseItemId(folder2.guid);
- let folder2ParentId = yield PlacesUtils.promiseItemId(folder2.parentGuid);
-
- bm.parentGuid = folder2.guid;
- bm = yield PlacesUtils.bookmarks.update(bm);
- let parentId = yield PlacesUtils.promiseItemId(bm.parentGuid);
-
- let observer = expectNotifications();
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Bookmarks should always be notified before their parents.
- observer.check([ { name: "onItemRemoved",
- arguments: [ itemId, parentId, bm.index, bm.type,
- bm.url, bm.guid, bm.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ folder2Id, folder2ParentId, folder2.index,
- folder2.type, null, folder2.guid,
- folder2.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemRemoved",
- arguments: [ folder1Id, folder1ParentId, folder1.index,
- folder1.type, null, folder1.guid,
- folder1.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- ]);
-});
-
-add_task(function* reorder_notification() {
- let bookmarks = [
- { type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example1.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example2.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example3.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- ];
- let sorted = [];
- for (let bm of bookmarks) {
- sorted.push(yield PlacesUtils.bookmarks.insert(bm));
- }
-
- // Randomly reorder the array.
- sorted.sort(() => 0.5 - Math.random());
-
- let observer = expectNotifications();
- yield PlacesUtils.bookmarks.reorder(PlacesUtils.bookmarks.unfiledGuid,
- sorted.map(bm => bm.guid));
-
- let expectedNotifications = [];
- for (let i = 0; i < sorted.length; ++i) {
- let child = sorted[i];
- let childId = yield PlacesUtils.promiseItemId(child.guid);
- expectedNotifications.push({ name: "onItemMoved",
- arguments: [ childId,
- PlacesUtils.unfiledBookmarksFolderId,
- child.index,
- PlacesUtils.unfiledBookmarksFolderId,
- i,
- child.type,
- child.guid,
- child.parentGuid,
- child.parentGuid,
- Ci.nsINavBookmarksService.SOURCE_DEFAULT
- ] });
- }
- observer.check(expectedNotifications);
-});
-
-function expectNotifications() {
- let notifications = [];
- let observer = new Proxy(NavBookmarkObserver, {
- get(target, name) {
- if (name == "check") {
- PlacesUtils.bookmarks.removeObserver(observer);
- return expectedNotifications =>
- Assert.deepEqual(notifications, expectedNotifications);
- }
-
- if (name.startsWith("onItem")) {
- return (...origArgs) => {
- let args = Array.from(origArgs, arg => {
- if (arg && arg instanceof Ci.nsIURI)
- return new URL(arg.spec);
- if (arg && typeof(arg) == "number" && arg >= Date.now() * 1000)
- return new Date(parseInt(arg/1000));
- return arg;
- });
- notifications.push({ name: name, arguments: args });
- }
- }
-
- if (name in target)
- return target[name];
- return undefined;
- }
- });
- PlacesUtils.bookmarks.addObserver(observer, false);
- return observer;
-}
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_remove.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_remove.js
deleted file mode 100644
index 19085a282..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_remove.js
+++ /dev/null
@@ -1,204 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* invalid_input_throws() {
- Assert.throws(() => PlacesUtils.bookmarks.remove(),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.bookmarks.remove(null),
- /Input should be a valid object/);
-
- Assert.throws(() => PlacesUtils.bookmarks.remove("test"),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.remove(123),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.remove({ guid: "test" }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.remove({ guid: null }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.remove({ guid: 123 }),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.remove({ parentGuid: "test" }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.remove({ parentGuid: null }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.remove({ parentGuid: 123 }),
- /Invalid value for property 'parentGuid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.remove({ url: "http://te st/" }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.remove({ url: null }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.remove({ url: -10 }),
- /Invalid value for property 'url'/);
-});
-
-add_task(function* remove_nonexistent_guid() {
- try {
- yield PlacesUtils.bookmarks.remove({ guid: "123456789012"});
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/No bookmarks found for the provided GUID/.test(ex));
- }
-});
-
-add_task(function* remove_roots_fail() {
- let guids = [PlacesUtils.bookmarks.rootGuid,
- PlacesUtils.bookmarks.unfiledGuid,
- PlacesUtils.bookmarks.menuGuid,
- PlacesUtils.bookmarks.toolbarGuid,
- PlacesUtils.bookmarks.tagsGuid,
- PlacesUtils.bookmarks.mobileGuid];
- for (let guid of guids) {
- Assert.throws(() => PlacesUtils.bookmarks.remove(guid),
- /It's not possible to remove Places root folders/);
- }
-});
-
-add_task(function* remove_normal_folder_under_root_succeeds() {
- let folder = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.rootGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- checkBookmarkObject(folder);
- let removed_folder = yield PlacesUtils.bookmarks.remove(folder);
- Assert.deepEqual(folder, removed_folder);
- Assert.strictEqual((yield PlacesUtils.bookmarks.fetch(folder.guid)), null);
-});
-
-add_task(function* remove_bookmark() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.remove(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 0);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_BOOKMARK);
- Assert.equal(bm2.url.href, "http://example.com/");
- Assert.equal(bm2.title, "a bookmark");
-});
-
-
-add_task(function* remove_bookmark_orphans() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(bm1);
- PlacesUtils.annotations.setItemAnnotation((yield PlacesUtils.promiseItemId(bm1.guid)),
- "testanno", "testvalue", 0, 0);
-
- let bm2 = yield PlacesUtils.bookmarks.remove(bm1.guid);
- checkBookmarkObject(bm2);
-
- // Check there are no orphan annotations.
- let conn = yield PlacesUtils.promiseDBConnection();
- let annoAttrs = yield conn.execute(`SELECT id, name FROM moz_anno_attributes`);
- // Bug 1306445 will eventually remove the mobile root anno.
- Assert.equal(annoAttrs.length, 1);
- Assert.equal(annoAttrs[0].getResultByName("name"), PlacesUtils.MOBILE_ROOT_ANNO);
- let annos = rows = yield conn.execute(`SELECT item_id, anno_attribute_id FROM moz_items_annos`);
- Assert.equal(annos.length, 1);
- Assert.equal(annos[0].getResultByName("item_id"), PlacesUtils.mobileFolderId);
- Assert.equal(annos[0].getResultByName("anno_attribute_id"), annoAttrs[0].getResultByName("id"));
-});
-
-add_task(function* remove_bookmark_empty_title() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.remove(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.index, 0);
- Assert.ok(!("title" in bm2));
-});
-
-add_task(function* remove_folder() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a folder" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.remove(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 0);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_FOLDER);
- Assert.equal(bm2.title, "a folder");
- Assert.ok(!("url" in bm2));
-});
-
-add_task(function* test_nested_contents_removed() {
- let folder1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a folder" });
- let folder2 = yield PlacesUtils.bookmarks.insert({ parentGuid: folder1.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a folder" });
- let sep = yield PlacesUtils.bookmarks.insert({ parentGuid: folder2.guid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR });
- yield PlacesUtils.bookmarks.remove(folder1);
- Assert.strictEqual((yield PlacesUtils.bookmarks.fetch(folder1.guid)), null);
- Assert.strictEqual((yield PlacesUtils.bookmarks.fetch(folder2.guid)), null);
- Assert.strictEqual((yield PlacesUtils.bookmarks.fetch(sep.guid)), null);
-});
-
-add_task(function* remove_folder_empty_title() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "" });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.remove(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.index, 0);
- Assert.ok(!("title" in bm2));
-});
-
-add_task(function* remove_separator() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR });
- checkBookmarkObject(bm1);
-
- let bm2 = yield PlacesUtils.bookmarks.remove(bm1.guid);
- checkBookmarkObject(bm2);
-
- Assert.deepEqual(bm1, bm2);
- Assert.equal(bm2.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- Assert.equal(bm2.index, 0);
- Assert.deepEqual(bm2.dateAdded, bm2.lastModified);
- Assert.equal(bm2.type, PlacesUtils.bookmarks.TYPE_SEPARATOR);
- Assert.ok(!("url" in bm2));
- Assert.ok(!("title" in bm2));
-});
-
-add_task(function* test_nested_content_fails_when_not_allowed() {
- let folder1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a folder" });
- yield PlacesUtils.bookmarks.insert({ parentGuid: folder1.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a folder" });
- yield Assert.rejects(PlacesUtils.bookmarks.remove(folder1, {preventRemovalOfNonEmptyFolders: true}),
- /Cannot remove a non-empty folder./);
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_reorder.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_reorder.js
deleted file mode 100644
index 4f6617280..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_reorder.js
+++ /dev/null
@@ -1,177 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* invalid_input_throws() {
- Assert.throws(() => PlacesUtils.bookmarks.reorder(),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.reorder(null),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.reorder("test"),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.reorder(123),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.reorder({ guid: "test" }),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012"),
- /Must provide a sorted array of children GUIDs./);
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012", {}),
- /Must provide a sorted array of children GUIDs./);
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012", null),
- /Must provide a sorted array of children GUIDs./);
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012", []),
- /Must provide a sorted array of children GUIDs./);
-
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012", [ null ]),
- /Invalid GUID found in the sorted children array/);
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012", [ "" ]),
- /Invalid GUID found in the sorted children array/);
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012", [ {} ]),
- /Invalid GUID found in the sorted children array/);
- Assert.throws(() => PlacesUtils.bookmarks.reorder("123456789012", [ "012345678901", null ]),
- /Invalid GUID found in the sorted children array/);
-});
-
-add_task(function* reorder_nonexistent_guid() {
- yield Assert.rejects(PlacesUtils.bookmarks.reorder("123456789012", [ "012345678901" ]),
- /No folder found for the provided GUID/,
- "Should throw for nonexisting guid");
-});
-
-add_task(function* reorder() {
- let bookmarks = [
- { url: "http://example1.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { url: "http://example2.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- },
- { url: "http://example3.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- }
- ];
-
- let sorted = [];
- for (let bm of bookmarks) {
- sorted.push(yield PlacesUtils.bookmarks.insert(bm));
- }
-
- // Check the initial append sorting.
- Assert.ok(sorted.every((bm, i) => bm.index == i),
- "Initial bookmarks sorting is correct");
-
- // Apply random sorting and run multiple tests.
- for (let t = 0; t < 4; t++) {
- sorted.sort(() => 0.5 - Math.random());
- let sortedGuids = sorted.map(child => child.guid);
- dump("Expected order: " + sortedGuids.join() + "\n");
- // Add a nonexisting guid to the array, to ensure nothing will break.
- sortedGuids.push("123456789012");
- yield PlacesUtils.bookmarks.reorder(PlacesUtils.bookmarks.unfiledGuid,
- sortedGuids);
- for (let i = 0; i < sorted.length; ++i) {
- let item = yield PlacesUtils.bookmarks.fetch(sorted[i].guid);
- Assert.equal(item.index, i);
- }
- }
-
- do_print("Test partial sorting");
- // Try a partial sorting by passing only 2 entries.
- // The unspecified entries should retain the original order.
- sorted = [ sorted[1], sorted[0] ].concat(sorted.slice(2));
- let sortedGuids = [ sorted[0].guid, sorted[1].guid ];
- dump("Expected order: " + sorted.map(b => b.guid).join() + "\n");
- yield PlacesUtils.bookmarks.reorder(PlacesUtils.bookmarks.unfiledGuid,
- sortedGuids);
- for (let i = 0; i < sorted.length; ++i) {
- let item = yield PlacesUtils.bookmarks.fetch(sorted[i].guid);
- Assert.equal(item.index, i);
- }
-
- // Use triangular numbers to detect skipped position.
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(
- `SELECT parent
- FROM moz_bookmarks
- GROUP BY parent
- HAVING (SUM(DISTINCT position + 1) - (count(*) * (count(*) + 1) / 2)) <> 0`);
- Assert.equal(rows.length, 0, "All the bookmarks should have consistent positions");
-});
-
-add_task(function* move_and_reorder() {
- // Start clean.
- yield PlacesUtils.bookmarks.eraseEverything();
-
- let bm1 = yield PlacesUtils.bookmarks.insert({
- url: "http://example1.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- });
- let f1 = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- });
- let bm2 = yield PlacesUtils.bookmarks.insert({
- url: "http://example2.com/",
- parentGuid: f1.guid
- });
- let f2 = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- });
- let bm3 = yield PlacesUtils.bookmarks.insert({
- url: "http://example3.com/",
- parentGuid: f2.guid
- });
- let bm4 = yield PlacesUtils.bookmarks.insert({
- url: "http://example4.com/",
- parentGuid: f2.guid
- });
- let bm5 = yield PlacesUtils.bookmarks.insert({
- url: "http://example5.com/",
- parentGuid: f2.guid
- });
-
- // Invert f2 children.
- // This is critical to reproduce the bug, cause it inverts the position
- // compared to the natural insertion order.
- yield PlacesUtils.bookmarks.reorder(f2.guid, [bm5.guid, bm4.guid, bm3.guid]);
-
- bm1.parentGuid = f1.guid;
- bm1.index = 0;
- yield PlacesUtils.bookmarks.update(bm1);
-
- bm1 = yield PlacesUtils.bookmarks.fetch(bm1.guid);
- Assert.equal(bm1.index, 0);
- bm2 = yield PlacesUtils.bookmarks.fetch(bm2.guid);
- Assert.equal(bm2.index, 1);
- bm3 = yield PlacesUtils.bookmarks.fetch(bm3.guid);
- Assert.equal(bm3.index, 2);
- bm4 = yield PlacesUtils.bookmarks.fetch(bm4.guid);
- Assert.equal(bm4.index, 1);
- bm5 = yield PlacesUtils.bookmarks.fetch(bm5.guid);
- Assert.equal(bm5.index, 0);
-
- // No-op reorder on f1 children.
- // Nothing should change. Though, due to bug 1293365 this was causing children
- // of other folders to get messed up.
- yield PlacesUtils.bookmarks.reorder(f1.guid, [bm1.guid, bm2.guid]);
-
- bm1 = yield PlacesUtils.bookmarks.fetch(bm1.guid);
- Assert.equal(bm1.index, 0);
- bm2 = yield PlacesUtils.bookmarks.fetch(bm2.guid);
- Assert.equal(bm2.index, 1);
- bm3 = yield PlacesUtils.bookmarks.fetch(bm3.guid);
- Assert.equal(bm3.index, 2);
- bm4 = yield PlacesUtils.bookmarks.fetch(bm4.guid);
- Assert.equal(bm4.index, 1);
- bm5 = yield PlacesUtils.bookmarks.fetch(bm5.guid);
- Assert.equal(bm5.index, 0);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_search.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_search.js
deleted file mode 100644
index 02f7c5460..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_search.js
+++ /dev/null
@@ -1,223 +0,0 @@
-add_task(function* invalid_input_throws() {
- Assert.throws(() => PlacesUtils.bookmarks.search(),
- /Query object is required/);
- Assert.throws(() => PlacesUtils.bookmarks.search(null),
- /Query object is required/);
- Assert.throws(() => PlacesUtils.bookmarks.search({title: 50}),
- /Title option must be a string/);
- Assert.throws(() => PlacesUtils.bookmarks.search({url: {url: "wombat"}}),
- /Url option must be a string or a URL object/);
- Assert.throws(() => PlacesUtils.bookmarks.search(50),
- /Query must be an object or a string/);
- Assert.throws(() => PlacesUtils.bookmarks.search(true),
- /Query must be an object or a string/);
-});
-
-add_task(function* search_bookmark() {
- yield PlacesUtils.bookmarks.eraseEverything();
-
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- title: "a bookmark" });
- let bm2 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.org/",
- title: "another bookmark" });
- let bm3 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.menuGuid,
- url: "http://menu.org/",
- title: "an on-menu bookmark" });
- let bm4 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: "http://toolbar.org/",
- title: "an on-toolbar bookmark" });
- checkBookmarkObject(bm1);
- checkBookmarkObject(bm2);
- checkBookmarkObject(bm3);
- checkBookmarkObject(bm4);
-
- // finds a result by query
- let results = yield PlacesUtils.bookmarks.search("example.com");
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm1, results[0]);
-
- // finds multiple results
- results = yield PlacesUtils.bookmarks.search("example");
- Assert.equal(results.length, 2);
- checkBookmarkObject(results[0]);
- checkBookmarkObject(results[1]);
-
- // finds menu bookmarks
- results = yield PlacesUtils.bookmarks.search("an on-menu bookmark");
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm3, results[0]);
-
- // finds toolbar bookmarks
- results = yield PlacesUtils.bookmarks.search("an on-toolbar bookmark");
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm4, results[0]);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* search_bookmark_by_query_object() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- title: "a bookmark" });
- let bm2 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.org/",
- title: "another bookmark" });
- checkBookmarkObject(bm1);
- checkBookmarkObject(bm2);
-
- let results = yield PlacesUtils.bookmarks.search({query: "example.com"});
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
-
- Assert.deepEqual(bm1, results[0]);
-
- results = yield PlacesUtils.bookmarks.search({query: "example"});
- Assert.equal(results.length, 2);
- checkBookmarkObject(results[0]);
- checkBookmarkObject(results[1]);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* search_bookmark_by_url() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- title: "a bookmark" });
- let bm2 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.org/path",
- title: "another bookmark" });
- let bm3 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.org/path",
- title: "third bookmark" });
- checkBookmarkObject(bm1);
- checkBookmarkObject(bm2);
- checkBookmarkObject(bm3);
-
- // finds the correct result by url
- let results = yield PlacesUtils.bookmarks.search({url: "http://example.com/"});
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm1, results[0]);
-
- // normalizes the url
- results = yield PlacesUtils.bookmarks.search({url: "http:/example.com"});
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm1, results[0]);
-
- // returns multiple matches
- results = yield PlacesUtils.bookmarks.search({url: "http://example.org/path"});
- Assert.equal(results.length, 2);
-
- // requires exact match
- results = yield PlacesUtils.bookmarks.search({url: "http://example.org/"});
- Assert.equal(results.length, 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* search_bookmark_by_title() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- title: "a bookmark" });
- let bm2 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.org/path",
- title: "another bookmark" });
- let bm3 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.net/",
- title: "another bookmark" });
- checkBookmarkObject(bm1);
- checkBookmarkObject(bm2);
- checkBookmarkObject(bm3);
-
- // finds the correct result by title
- let results = yield PlacesUtils.bookmarks.search({title: "a bookmark"});
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm1, results[0]);
-
- // returns multiple matches
- results = yield PlacesUtils.bookmarks.search({title: "another bookmark"});
- Assert.equal(results.length, 2);
-
- // requires exact match
- results = yield PlacesUtils.bookmarks.search({title: "bookmark"});
- Assert.equal(results.length, 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* search_bookmark_combinations() {
- let bm1 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/",
- title: "a bookmark" });
- let bm2 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.org/path",
- title: "another bookmark" });
- let bm3 = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.net/",
- title: "third bookmark" });
- checkBookmarkObject(bm1);
- checkBookmarkObject(bm2);
- checkBookmarkObject(bm3);
-
- // finds the correct result if title and url match
- let results = yield PlacesUtils.bookmarks.search({url: "http://example.com/", title: "a bookmark"});
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm1, results[0]);
-
- // does not match if query is not matching but url and title match
- results = yield PlacesUtils.bookmarks.search({url: "http://example.com/", title: "a bookmark", query: "nonexistent"});
- Assert.equal(results.length, 0);
-
- // does not match if one parameter is not matching
- results = yield PlacesUtils.bookmarks.search({url: "http://what.ever", title: "a bookmark"});
- Assert.equal(results.length, 0);
-
- // query only matches if other fields match as well
- results = yield PlacesUtils.bookmarks.search({query: "bookmark", url: "http://example.net/"});
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm3, results[0]);
-
- // non-matching query will also return no results
- results = yield PlacesUtils.bookmarks.search({query: "nonexistent", url: "http://example.net/"});
- Assert.equal(results.length, 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* search_folder() {
- let folder = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.menuGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "a test folder" });
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: folder.guid,
- url: "http://example.com/",
- title: "a bookmark" });
- checkBookmarkObject(folder);
- checkBookmarkObject(bm);
-
- // also finds folders
- let results = yield PlacesUtils.bookmarks.search("a test folder");
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.equal(folder.title, results[0].title);
- Assert.equal(folder.type, results[0].type);
- Assert.equal(folder.parentGuid, results[0].parentGuid);
-
- // finds elements in folders
- results = yield PlacesUtils.bookmarks.search("example.com");
- Assert.equal(results.length, 1);
- checkBookmarkObject(results[0]);
- Assert.deepEqual(bm, results[0]);
- Assert.equal(folder.guid, results[0].parentGuid);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarks_update.js b/toolkit/components/places/tests/bookmarks/test_bookmarks_update.js
deleted file mode 100644
index d077fd6f3..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarks_update.js
+++ /dev/null
@@ -1,414 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* invalid_input_throws() {
- Assert.throws(() => PlacesUtils.bookmarks.update(),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.bookmarks.update(null),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.bookmarks.update({}),
- /The following properties were expected/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ guid: "test" }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ guid: null }),
- /Invalid value for property 'guid'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ guid: 123 }),
- /Invalid value for property 'guid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ parentGuid: "test" }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ parentGuid: null }),
- /Invalid value for property 'parentGuid'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ parentGuid: 123 }),
- /Invalid value for property 'parentGuid'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ index: "1" }),
- /Invalid value for property 'index'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ index: -10 }),
- /Invalid value for property 'index'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ dateAdded: -10 }),
- /Invalid value for property 'dateAdded'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ dateAdded: "today" }),
- /Invalid value for property 'dateAdded'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ dateAdded: Date.now() }),
- /Invalid value for property 'dateAdded'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ lastModified: -10 }),
- /Invalid value for property 'lastModified'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ lastModified: "today" }),
- /Invalid value for property 'lastModified'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ lastModified: Date.now() }),
- /Invalid value for property 'lastModified'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ type: -1 }),
- /Invalid value for property 'type'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ type: 100 }),
- /Invalid value for property 'type'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ type: "bookmark" }),
- /Invalid value for property 'type'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ url: 10 }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ url: "http://te st" }),
- /Invalid value for property 'url'/);
- let longurl = "http://www.example.com/";
- for (let i = 0; i < 65536; i++) {
- longurl += "a";
- }
- Assert.throws(() => PlacesUtils.bookmarks.update({ url: longurl }),
- /Invalid value for property 'url'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ url: NetUtil.newURI(longurl) }),
- /Invalid value for property 'url'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ url: "te st" }),
- /Invalid value for property 'url'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ title: -1 }),
- /Invalid value for property 'title'/);
- Assert.throws(() => PlacesUtils.bookmarks.update({ title: {} }),
- /Invalid value for property 'title'/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ guid: "123456789012" }),
- /Not enough properties to update/);
-
- Assert.throws(() => PlacesUtils.bookmarks.update({ guid: "123456789012",
- parentGuid: "012345678901" }),
- /The following properties were expected: index/);
-});
-
-add_task(function* nonexisting_bookmark_throws() {
- try {
- yield PlacesUtils.bookmarks.update({ guid: "123456789012",
- title: "test" });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/No bookmarks found for the provided GUID/.test(ex));
- }
-});
-
-add_task(function* invalid_properties_for_existing_bookmark() {
- let bm = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://example.com/" });
-
- try {
- yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/The bookmark type cannot be changed/.test(ex));
- }
-
- try {
- yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- dateAdded: new Date() });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/The bookmark dateAdded cannot be changed/.test(ex));
- }
-
- try {
- yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- dateAdded: new Date() });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/The bookmark dateAdded cannot be changed/.test(ex));
- }
-
- try {
- yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- parentGuid: "123456789012",
- index: 1 });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/No bookmarks found for the provided parentGuid/.test(ex));
- }
-
- let past = new Date(Date.now() - 86400000);
- try {
- yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- lastModified: past });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/Invalid value for property 'lastModified'/.test(ex));
- }
-
- let folder = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- try {
- yield PlacesUtils.bookmarks.update({ guid: folder.guid,
- url: "http://example.com/" });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/Invalid value for property 'url'/.test(ex));
- }
-
- let separator = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- try {
- yield PlacesUtils.bookmarks.update({ guid: separator.guid,
- url: "http://example.com/" });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/Invalid value for property 'url'/.test(ex));
- }
- try {
- yield PlacesUtils.bookmarks.update({ guid: separator.guid,
- title: "test" });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/Invalid value for property 'title'/.test(ex));
- }
-});
-
-add_task(function* long_title_trim() {
- let longtitle = "a";
- for (let i = 0; i < 4096; i++) {
- longtitle += "a";
- }
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "title" });
- checkBookmarkObject(bm);
-
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- title: longtitle });
- let newTitle = bm.title;
- Assert.equal(newTitle.length, 4096, "title should have been trimmed");
-
- bm = yield PlacesUtils.bookmarks.fetch(bm.guid);
- Assert.equal(bm.title, newTitle);
-});
-
-add_task(function* update_lastModified() {
- let yesterday = new Date(Date.now() - 86400000);
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "title",
- dateAdded: yesterday });
- checkBookmarkObject(bm);
- Assert.deepEqual(bm.lastModified, yesterday);
-
- let time = new Date();
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- lastModified: time });
- checkBookmarkObject(bm);
- Assert.deepEqual(bm.lastModified, time);
-
- bm = yield PlacesUtils.bookmarks.fetch(bm.guid);
- Assert.deepEqual(bm.lastModified, time);
-
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- lastModified: yesterday });
- Assert.deepEqual(bm.lastModified, yesterday);
-
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- title: "title2" });
- Assert.ok(bm.lastModified >= time);
-
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- title: "" });
- Assert.ok(!("title" in bm));
-
- bm = yield PlacesUtils.bookmarks.fetch(bm.guid);
- Assert.ok(!("title" in bm));
-});
-
-add_task(function* update_url() {
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/",
- title: "title" });
- checkBookmarkObject(bm);
- let lastModified = bm.lastModified;
- let frecency = frecencyForUrl(bm.url);
- Assert.ok(frecency > 0, "Check frecency has been updated");
-
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- url: "http://mozilla.org/" });
- checkBookmarkObject(bm);
- Assert.ok(bm.lastModified >= lastModified);
- Assert.equal(bm.url.href, "http://mozilla.org/");
-
- bm = yield PlacesUtils.bookmarks.fetch(bm.guid);
- Assert.equal(bm.url.href, "http://mozilla.org/");
- Assert.ok(bm.lastModified >= lastModified);
-
- Assert.equal(frecencyForUrl("http://example.com/"), frecency, "Check frecency for example.com");
- Assert.equal(frecencyForUrl("http://mozilla.org/"), frecency, "Check frecency for mozilla.org");
-});
-
-add_task(function* update_index() {
- let parent = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER }) ;
- let f1 = yield PlacesUtils.bookmarks.insert({ parentGuid: parent.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- Assert.equal(f1.index, 0);
- let f2 = yield PlacesUtils.bookmarks.insert({ parentGuid: parent.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- Assert.equal(f2.index, 1);
- let f3 = yield PlacesUtils.bookmarks.insert({ parentGuid: parent.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- Assert.equal(f3.index, 2);
- let lastModified = f1.lastModified;
-
- f1 = yield PlacesUtils.bookmarks.update({ guid: f1.guid,
- parentGuid: f1.parentGuid,
- index: 1});
- checkBookmarkObject(f1);
- Assert.equal(f1.index, 1);
- Assert.ok(f1.lastModified >= lastModified);
-
- parent = yield PlacesUtils.bookmarks.fetch(f1.parentGuid);
- Assert.deepEqual(parent.lastModified, f1.lastModified);
-
- f2 = yield PlacesUtils.bookmarks.fetch(f2.guid);
- Assert.equal(f2.index, 0);
-
- f3 = yield PlacesUtils.bookmarks.fetch(f3.guid);
- Assert.equal(f3.index, 2);
-
- f3 = yield PlacesUtils.bookmarks.update({ guid: f3.guid,
- index: 0 });
- f1 = yield PlacesUtils.bookmarks.fetch(f1.guid);
- Assert.equal(f1.index, 2);
-
- f2 = yield PlacesUtils.bookmarks.fetch(f2.guid);
- Assert.equal(f2.index, 1);
-});
-
-add_task(function* update_move_folder_into_descendant_throws() {
- let parent = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER }) ;
- let descendant = yield PlacesUtils.bookmarks.insert({ parentGuid: parent.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
-
- try {
- yield PlacesUtils.bookmarks.update({ guid: parent.guid,
- parentGuid: parent.guid,
- index: 0 });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/Cannot insert a folder into itself or one of its descendants/.test(ex));
- }
-
- try {
- yield PlacesUtils.bookmarks.update({ guid: parent.guid,
- parentGuid: descendant.guid,
- index: 0 });
- Assert.ok(false, "Should have thrown");
- } catch (ex) {
- Assert.ok(/Cannot insert a folder into itself or one of its descendants/.test(ex));
- }
-});
-
-add_task(function* update_move() {
- let parent = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER }) ;
- let bm = yield PlacesUtils.bookmarks.insert({ parentGuid: parent.guid,
- url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK }) ;
- let descendant = yield PlacesUtils.bookmarks.insert({ parentGuid: parent.guid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- Assert.equal(descendant.index, 1);
- let lastModified = bm.lastModified;
-
- // This is moving to a nonexisting index by purpose, it will be appended.
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- parentGuid: descendant.guid,
- index: 1 });
- checkBookmarkObject(bm);
- Assert.equal(bm.parentGuid, descendant.guid);
- Assert.equal(bm.index, 0);
- Assert.ok(bm.lastModified >= lastModified);
-
- parent = yield PlacesUtils.bookmarks.fetch(parent.guid);
- descendant = yield PlacesUtils.bookmarks.fetch(descendant.guid);
- Assert.deepEqual(parent.lastModified, bm.lastModified);
- Assert.deepEqual(descendant.lastModified, bm.lastModified);
- Assert.equal(descendant.index, 0);
-
- bm = yield PlacesUtils.bookmarks.fetch(bm.guid);
- Assert.equal(bm.parentGuid, descendant.guid);
- Assert.equal(bm.index, 0);
-
- bm = yield PlacesUtils.bookmarks.update({ guid: bm.guid,
- parentGuid: parent.guid,
- index: 0 });
- Assert.equal(bm.parentGuid, parent.guid);
- Assert.equal(bm.index, 0);
-
- descendant = yield PlacesUtils.bookmarks.fetch(descendant.guid);
- Assert.equal(descendant.index, 1);
-});
-
-add_task(function* update_move_append() {
- let folder_a =
- yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- checkBookmarkObject(folder_a);
- let folder_b =
- yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER });
- checkBookmarkObject(folder_b);
-
- /* folder_a: [sep_1, sep_2, sep_3], folder_b: [] */
- let sep_1 = yield PlacesUtils.bookmarks.insert({ parentGuid: folder_a.guid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR });
- checkBookmarkObject(sep_1);
- let sep_2 = yield PlacesUtils.bookmarks.insert({ parentGuid: folder_a.guid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR });
- checkBookmarkObject(sep_2);
- let sep_3 = yield PlacesUtils.bookmarks.insert({ parentGuid: folder_a.guid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR });
- checkBookmarkObject(sep_3);
-
- function ensurePosition(info, parentGuid, index) {
- checkBookmarkObject(info);
- Assert.equal(info.parentGuid, parentGuid);
- Assert.equal(info.index, index);
- }
-
- // folder_a: [sep_2, sep_3, sep_1], folder_b: []
- sep_1.index = PlacesUtils.bookmarks.DEFAULT_INDEX;
- // Note sep_1 includes parentGuid even though we're not moving the item to
- // another folder
- sep_1 = yield PlacesUtils.bookmarks.update(sep_1);
- ensurePosition(sep_1, folder_a.guid, 2);
- sep_2 = yield PlacesUtils.bookmarks.fetch(sep_2.guid);
- ensurePosition(sep_2, folder_a.guid, 0);
- sep_3 = yield PlacesUtils.bookmarks.fetch(sep_3.guid);
- ensurePosition(sep_3, folder_a.guid, 1);
- sep_1 = yield PlacesUtils.bookmarks.fetch(sep_1.guid);
- ensurePosition(sep_1, folder_a.guid, 2);
-
- // folder_a: [sep_2, sep_1], folder_b: [sep_3]
- sep_3.index = PlacesUtils.bookmarks.DEFAULT_INDEX;
- sep_3.parentGuid = folder_b.guid;
- sep_3 = yield PlacesUtils.bookmarks.update(sep_3);
- ensurePosition(sep_3, folder_b.guid, 0);
- sep_2 = yield PlacesUtils.bookmarks.fetch(sep_2.guid);
- ensurePosition(sep_2, folder_a.guid, 0);
- sep_1 = yield PlacesUtils.bookmarks.fetch(sep_1.guid);
- ensurePosition(sep_1, folder_a.guid, 1);
- sep_3 = yield PlacesUtils.bookmarks.fetch(sep_3.guid);
- ensurePosition(sep_3, folder_b.guid, 0);
-
- // folder_a: [sep_1], folder_b: [sep_3, sep_2]
- sep_2.index = Number.MAX_SAFE_INTEGER;
- sep_2.parentGuid = folder_b.guid;
- sep_2 = yield PlacesUtils.bookmarks.update(sep_2);
- ensurePosition(sep_2, folder_b.guid, 1);
- sep_1 = yield PlacesUtils.bookmarks.fetch(sep_1.guid);
- ensurePosition(sep_1, folder_a.guid, 0);
- sep_3 = yield PlacesUtils.bookmarks.fetch(sep_3.guid);
- ensurePosition(sep_3, folder_b.guid, 0);
- sep_2 = yield PlacesUtils.bookmarks.fetch(sep_2.guid);
- ensurePosition(sep_2, folder_b.guid, 1);
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_bookmarkstree_cache.js b/toolkit/components/places/tests/bookmarks/test_bookmarkstree_cache.js
deleted file mode 100644
index f5cf34641..000000000
--- a/toolkit/components/places/tests/bookmarks/test_bookmarkstree_cache.js
+++ /dev/null
@@ -1,18 +0,0 @@
-
-// Bug 1192692 - promiseBookmarksTree caches items without adding observers to
-// invalidate the cache.
-add_task(function* boookmarks_tree_cache() {
- // Note that for this test to be effective, it needs to use the "old" sync
- // bookmarks methods - using, eg, PlacesUtils.bookmarks.insert() doesn't
- // demonstrate the problem as it indirectly arranges for the observers to
- // be added.
- let id = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri("http://example.com"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "A title");
- yield PlacesUtils.promiseBookmarksTree();
-
- PlacesUtils.bookmarks.removeItem(id);
-
- yield Assert.rejects(PlacesUtils.promiseItemGuid(id));
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_changeBookmarkURI.js b/toolkit/components/places/tests/bookmarks/test_changeBookmarkURI.js
deleted file mode 100644
index 55ffecf2f..000000000
--- a/toolkit/components/places/tests/bookmarks/test_changeBookmarkURI.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get bookmark service
-var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-/**
- * Ensures that the Places APIs recognize that aBookmarkedUri is bookmarked
- * via aBookmarkId and that aUnbookmarkedUri is not bookmarked at all.
- *
- * @param aBookmarkId
- * an item ID whose corresponding URI is aBookmarkedUri
- * @param aBookmarkedUri
- * a bookmarked URI that has a corresponding item ID aBookmarkId
- * @param aUnbookmarkedUri
- * a URI that is not currently bookmarked at all
- */
-function checkUris(aBookmarkId, aBookmarkedUri, aUnbookmarkedUri)
-{
- // Ensure that aBookmarkedUri equals some URI that is bookmarked
- var uri = bmsvc.getBookmarkedURIFor(aBookmarkedUri);
- do_check_neq(uri, null);
- do_check_true(uri.equals(aBookmarkedUri));
-
- // Ensure that aBookmarkedUri is considered bookmarked
- do_check_true(bmsvc.isBookmarked(aBookmarkedUri));
-
- // Ensure that the URI corresponding to aBookmarkId equals aBookmarkedUri
- do_check_true(bmsvc.getBookmarkURI(aBookmarkId).equals(aBookmarkedUri));
-
- // Ensure that aUnbookmarkedUri does not equal any URI that is bookmarked
- uri = bmsvc.getBookmarkedURIFor(aUnbookmarkedUri);
- do_check_eq(uri, null);
-
- // Ensure that aUnbookmarkedUri is not considered bookmarked
- do_check_false(bmsvc.isBookmarked(aUnbookmarkedUri));
-}
-
-// main
-function run_test() {
- // Create a folder
- var folderId = bmsvc.createFolder(bmsvc.toolbarFolder,
- "test",
- bmsvc.DEFAULT_INDEX);
-
- // Create 2 URIs
- var uri1 = uri("http://www.dogs.com");
- var uri2 = uri("http://www.cats.com");
-
- // Bookmark the first one
- var bookmarkId = bmsvc.insertBookmark(folderId,
- uri1,
- bmsvc.DEFAULT_INDEX,
- "Dogs");
-
- // uri1 is bookmarked via bookmarkId, uri2 is not
- checkUris(bookmarkId, uri1, uri2);
-
- // Change the URI of the bookmark to uri2
- bmsvc.changeBookmarkURI(bookmarkId, uri2);
-
- // uri2 is now bookmarked via bookmarkId, uri1 is not
- checkUris(bookmarkId, uri2, uri1);
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_getBookmarkedURIFor.js b/toolkit/components/places/tests/bookmarks/test_getBookmarkedURIFor.js
deleted file mode 100644
index c43e8e283..000000000
--- a/toolkit/components/places/tests/bookmarks/test_getBookmarkedURIFor.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Test bookmarksService.getBookmarkedURIFor(aURI);
- */
-
-var hs = PlacesUtils.history;
-var bs = PlacesUtils.bookmarks;
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_getBookmarkedURIFor() {
- let now = Date.now() * 1000;
- const sourceURI = uri("http://test.mozilla.org/");
- // Add a visit and a bookmark.
- yield PlacesTestUtils.addVisits({ uri: sourceURI, visitDate: now });
- do_check_eq(bs.getBookmarkedURIFor(sourceURI), null);
-
- let sourceItemId = bs.insertBookmark(bs.unfiledBookmarksFolder,
- sourceURI,
- bs.DEFAULT_INDEX,
- "bookmark");
- do_check_true(bs.getBookmarkedURIFor(sourceURI).equals(sourceURI));
-
- // Add a redirected visit.
- const permaURI = uri("http://perma.mozilla.org/");
- yield PlacesTestUtils.addVisits({
- uri: permaURI,
- transition: TRANSITION_REDIRECT_PERMANENT,
- visitDate: now++,
- referrer: sourceURI
- });
- do_check_true(bs.getBookmarkedURIFor(sourceURI).equals(sourceURI));
- do_check_true(bs.getBookmarkedURIFor(permaURI).equals(sourceURI));
- // Add a bookmark to the destination.
- let permaItemId = bs.insertBookmark(bs.unfiledBookmarksFolder,
- permaURI,
- bs.DEFAULT_INDEX,
- "bookmark");
- do_check_true(bs.getBookmarkedURIFor(sourceURI).equals(sourceURI));
- do_check_true(bs.getBookmarkedURIFor(permaURI).equals(permaURI));
- // Now remove the bookmark on the destination.
- bs.removeItem(permaItemId);
- // We should see the source as bookmark.
- do_check_true(bs.getBookmarkedURIFor(permaURI).equals(sourceURI));
-
- // Add another redirected visit.
- const tempURI = uri("http://perma.mozilla.org/");
- yield PlacesTestUtils.addVisits({
- uri: tempURI,
- transition: TRANSITION_REDIRECT_TEMPORARY,
- visitDate: now++,
- referrer: permaURI
- });
-
- do_check_true(bs.getBookmarkedURIFor(sourceURI).equals(sourceURI));
- do_check_true(bs.getBookmarkedURIFor(tempURI).equals(sourceURI));
- // Add a bookmark to the destination.
- let tempItemId = bs.insertBookmark(bs.unfiledBookmarksFolder,
- tempURI,
- bs.DEFAULT_INDEX,
- "bookmark");
- do_check_true(bs.getBookmarkedURIFor(sourceURI).equals(sourceURI));
- do_check_true(bs.getBookmarkedURIFor(tempURI).equals(tempURI));
-
- // Now remove the bookmark on the destination.
- bs.removeItem(tempItemId);
- // We should see the source as bookmark.
- do_check_true(bs.getBookmarkedURIFor(tempURI).equals(sourceURI));
- // Remove the source bookmark as well.
- bs.removeItem(sourceItemId);
- do_check_eq(bs.getBookmarkedURIFor(tempURI), null);
-
- // Try to pass in a never seen URI, should return null and a new entry should
- // not be added to the database.
- do_check_eq(bs.getBookmarkedURIFor(uri("http://does.not.exist/")), null);
- do_check_false(page_in_database("http://does.not.exist/"));
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_keywords.js b/toolkit/components/places/tests/bookmarks/test_keywords.js
deleted file mode 100644
index 149d6d0b0..000000000
--- a/toolkit/components/places/tests/bookmarks/test_keywords.js
+++ /dev/null
@@ -1,310 +0,0 @@
-const URI1 = NetUtil.newURI("http://test1.mozilla.org/");
-const URI2 = NetUtil.newURI("http://test2.mozilla.org/");
-const URI3 = NetUtil.newURI("http://test3.mozilla.org/");
-
-function check_keyword(aURI, aKeyword) {
- if (aKeyword)
- aKeyword = aKeyword.toLowerCase();
-
- for (let bm of PlacesUtils.getBookmarksForURI(aURI)) {
- let keyword = PlacesUtils.bookmarks.getKeywordForBookmark(bm);
- if (keyword && !aKeyword) {
- throw (`${aURI.spec} should not have a keyword`);
- } else if (aKeyword && keyword == aKeyword) {
- Assert.equal(keyword, aKeyword);
- }
- }
-
- if (aKeyword) {
- let uri = PlacesUtils.bookmarks.getURIForKeyword(aKeyword);
- Assert.equal(uri.spec, aURI.spec);
- // Check case insensitivity.
- uri = PlacesUtils.bookmarks.getURIForKeyword(aKeyword.toUpperCase());
- Assert.equal(uri.spec, aURI.spec);
- }
-}
-
-function* check_orphans() {
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.executeCached(
- `SELECT id FROM moz_keywords k
- WHERE NOT EXISTS (SELECT 1 FROM moz_places WHERE id = k.place_id)
- `);
- Assert.equal(rows.length, 0);
-}
-
-function expectNotifications() {
- let notifications = [];
- let observer = new Proxy(NavBookmarkObserver, {
- get(target, name) {
- if (name == "check") {
- PlacesUtils.bookmarks.removeObserver(observer);
- return expectedNotifications =>
- Assert.deepEqual(notifications, expectedNotifications);
- }
-
- if (name.startsWith("onItemChanged")) {
- return function(id, prop, isAnno, val, lastMod, itemType, parentId, guid, parentGuid, oldVal) {
- if (prop != "keyword")
- return;
- let args = Array.from(arguments, arg => {
- if (arg && arg instanceof Ci.nsIURI)
- return new URL(arg.spec);
- if (arg && typeof(arg) == "number" && arg >= Date.now() * 1000)
- return new Date(parseInt(arg/1000));
- return arg;
- });
- notifications.push({ name: name, arguments: args });
- }
- }
-
- return target[name];
- }
- });
- PlacesUtils.bookmarks.addObserver(observer, false);
- return observer;
-}
-
-add_task(function test_invalid_input() {
- Assert.throws(() => PlacesUtils.bookmarks.getURIForKeyword(null),
- /NS_ERROR_ILLEGAL_VALUE/);
- Assert.throws(() => PlacesUtils.bookmarks.getURIForKeyword(""),
- /NS_ERROR_ILLEGAL_VALUE/);
- Assert.throws(() => PlacesUtils.bookmarks.getKeywordForBookmark(null),
- /NS_ERROR_ILLEGAL_VALUE/);
- Assert.throws(() => PlacesUtils.bookmarks.getKeywordForBookmark(0),
- /NS_ERROR_ILLEGAL_VALUE/);
- Assert.throws(() => PlacesUtils.bookmarks.setKeywordForBookmark(null, "k"),
- /NS_ERROR_ILLEGAL_VALUE/);
- Assert.throws(() => PlacesUtils.bookmarks.setKeywordForBookmark(0, "k"),
- /NS_ERROR_ILLEGAL_VALUE/);
-});
-
-add_task(function* test_addBookmarkAndKeyword() {
- check_keyword(URI1, null);
- let fc = yield foreign_count(URI1);
- let observer = expectNotifications();
-
- let itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- URI1,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test");
-
- PlacesUtils.bookmarks.setKeywordForBookmark(itemId, "keyword");
- let bookmark = yield PlacesUtils.bookmarks.fetch({ url: URI1 });
- observer.check([ { name: "onItemChanged",
- arguments: [ itemId, "keyword", false, "keyword",
- bookmark.lastModified, bookmark.type,
- (yield PlacesUtils.promiseItemId(bookmark.parentGuid)),
- bookmark.guid, bookmark.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- check_keyword(URI1, "keyword");
- Assert.equal((yield foreign_count(URI1)), fc + 2); // + 1 bookmark + 1 keyword
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield check_orphans();
-});
-
-add_task(function* test_addBookmarkToURIHavingKeyword() {
- // The uri has already a keyword.
- check_keyword(URI1, "keyword");
- let fc = yield foreign_count(URI1);
-
- let itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- URI1,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test");
- check_keyword(URI1, "keyword");
- Assert.equal((yield foreign_count(URI1)), fc + 1); // + 1 bookmark
-
- PlacesUtils.bookmarks.removeItem(itemId);
- yield PlacesTestUtils.promiseAsyncUpdates();
- check_orphans();
-});
-
-add_task(function* test_sameKeywordDifferentURI() {
- let fc1 = yield foreign_count(URI1);
- let fc2 = yield foreign_count(URI2);
- let observer = expectNotifications();
-
- let itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- URI2,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test2");
- check_keyword(URI1, "keyword");
- check_keyword(URI2, null);
-
- PlacesUtils.bookmarks.setKeywordForBookmark(itemId, "kEyWoRd");
-
- let bookmark1 = yield PlacesUtils.bookmarks.fetch({ url: URI1 });
- let bookmark2 = yield PlacesUtils.bookmarks.fetch({ url: URI2 });
- observer.check([ { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark1.guid)),
- "keyword", false, "",
- bookmark1.lastModified, bookmark1.type,
- (yield PlacesUtils.promiseItemId(bookmark1.parentGuid)),
- bookmark1.guid, bookmark1.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ itemId, "keyword", false, "keyword",
- bookmark2.lastModified, bookmark2.type,
- (yield PlacesUtils.promiseItemId(bookmark2.parentGuid)),
- bookmark2.guid, bookmark2.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- // The keyword should have been "moved" to the new URI.
- check_keyword(URI1, null);
- Assert.equal((yield foreign_count(URI1)), fc1 - 1); // - 1 keyword
- check_keyword(URI2, "keyword");
- Assert.equal((yield foreign_count(URI2)), fc2 + 2); // + 1 bookmark + 1 keyword
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- check_orphans();
-});
-
-add_task(function* test_sameURIDifferentKeyword() {
- let fc = yield foreign_count(URI2);
- let observer = expectNotifications();
-
- let itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- URI2,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test2");
- check_keyword(URI2, "keyword");
-
- PlacesUtils.bookmarks.setKeywordForBookmark(itemId, "keyword2");
-
- let bookmarks = [];
- yield PlacesUtils.bookmarks.fetch({ url: URI2 }, bookmark => bookmarks.push(bookmark));
- observer.check([ { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmarks[0].guid)),
- "keyword", false, "keyword2",
- bookmarks[0].lastModified, bookmarks[0].type,
- (yield PlacesUtils.promiseItemId(bookmarks[0].parentGuid)),
- bookmarks[0].guid, bookmarks[0].parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmarks[1].guid)),
- "keyword", false, "keyword2",
- bookmarks[1].lastModified, bookmarks[1].type,
- (yield PlacesUtils.promiseItemId(bookmarks[1].parentGuid)),
- bookmarks[1].guid, bookmarks[1].parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- check_keyword(URI2, "keyword2");
- Assert.equal((yield foreign_count(URI2)), fc + 2); // + 1 bookmark + 1 keyword
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- check_orphans();
-});
-
-add_task(function* test_removeBookmarkWithKeyword() {
- let fc = yield foreign_count(URI2);
- let itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- URI2,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test");
-
- // The keyword should not be removed, since there are other bookmarks yet.
- PlacesUtils.bookmarks.removeItem(itemId);
-
- check_keyword(URI2, "keyword2");
- Assert.equal((yield foreign_count(URI2)), fc); // + 1 bookmark - 1 bookmark
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- check_orphans();
-});
-
-add_task(function* test_unsetKeyword() {
- let fc = yield foreign_count(URI2);
- let observer = expectNotifications();
-
- let itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- URI2,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test");
-
- // The keyword should be removed from any bookmark.
- PlacesUtils.bookmarks.setKeywordForBookmark(itemId, null);
-
- let bookmarks = [];
- yield PlacesUtils.bookmarks.fetch({ url: URI2 }, bookmark => bookmarks.push(bookmark));
- do_print(bookmarks.length);
- observer.check([ { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmarks[0].guid)),
- "keyword", false, "",
- bookmarks[0].lastModified, bookmarks[0].type,
- (yield PlacesUtils.promiseItemId(bookmarks[0].parentGuid)),
- bookmarks[0].guid, bookmarks[0].parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmarks[1].guid)),
- "keyword", false, "",
- bookmarks[1].lastModified, bookmarks[1].type,
- (yield PlacesUtils.promiseItemId(bookmarks[1].parentGuid)),
- bookmarks[1].guid, bookmarks[1].parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmarks[2].guid)),
- "keyword", false, "",
- bookmarks[2].lastModified, bookmarks[2].type,
- (yield PlacesUtils.promiseItemId(bookmarks[2].parentGuid)),
- bookmarks[2].guid, bookmarks[2].parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-
- check_keyword(URI1, null);
- check_keyword(URI2, null);
- Assert.equal((yield foreign_count(URI2)), fc - 1); // + 1 bookmark - 2 keyword
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- check_orphans();
-});
-
-add_task(function* test_addRemoveBookmark() {
- let observer = expectNotifications();
-
- let itemId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- URI3,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test3");
-
- PlacesUtils.bookmarks.setKeywordForBookmark(itemId, "keyword");
- let bookmark = yield PlacesUtils.bookmarks.fetch({ url: URI3 });
- let parentId = yield PlacesUtils.promiseItemId(bookmark.parentGuid);
- PlacesUtils.bookmarks.removeItem(itemId);
-
- observer.check([ { name: "onItemChanged",
- arguments: [ itemId,
- "keyword", false, "keyword",
- bookmark.lastModified, bookmark.type,
- parentId,
- bookmark.guid, bookmark.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] }
- ]);
-
- check_keyword(URI3, null);
- // Don't check the foreign count since the process is async.
- // The new test_keywords.js in unit is checking this though.
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- check_orphans();
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_nsINavBookmarkObserver.js b/toolkit/components/places/tests/bookmarks/test_nsINavBookmarkObserver.js
deleted file mode 100644
index 06f45b18e..000000000
--- a/toolkit/components/places/tests/bookmarks/test_nsINavBookmarkObserver.js
+++ /dev/null
@@ -1,640 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests that each nsINavBookmarksObserver method gets the correct input.
-Cu.import("resource://gre/modules/PromiseUtils.jsm");
-
-const GUID_RE = /^[a-zA-Z0-9\-_]{12}$/;
-
-var gBookmarksObserver = {
- expected: [],
- setup(expected) {
- this.expected = expected;
- this.deferred = PromiseUtils.defer();
- return this.deferred.promise;
- },
- validate: function (aMethodName, aArguments) {
- do_check_eq(this.expected[0].name, aMethodName);
-
- let args = this.expected.shift().args;
- do_check_eq(aArguments.length, args.length);
- for (let i = 0; i < aArguments.length; i++) {
- do_check_true(args[i].check(aArguments[i]), aMethodName + "(args[" + i + "]: " + args[i].name + ")");
- }
-
- if (this.expected.length === 0) {
- this.deferred.resolve();
- }
- },
-
- // nsINavBookmarkObserver
- onBeginUpdateBatch() {
- return this.validate("onBeginUpdateBatch", arguments);
- },
- onEndUpdateBatch() {
- return this.validate("onEndUpdateBatch", arguments);
- },
- onItemAdded() {
- return this.validate("onItemAdded", arguments);
- },
- onItemRemoved() {
- return this.validate("onItemRemoved", arguments);
- },
- onItemChanged() {
- return this.validate("onItemChanged", arguments);
- },
- onItemVisited() {
- return this.validate("onItemVisited", arguments);
- },
- onItemMoved() {
- return this.validate("onItemMoved", arguments);
- },
-
- // nsISupports
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver]),
-};
-
-var gBookmarkSkipObserver = {
- skipTags: true,
- skipDescendantsOnItemRemoval: true,
-
- expected: null,
- setup(expected) {
- this.expected = expected;
- this.deferred = PromiseUtils.defer();
- return this.deferred.promise;
- },
- validate: function (aMethodName) {
- do_check_eq(this.expected.shift(), aMethodName);
- if (this.expected.length === 0) {
- this.deferred.resolve();
- }
- },
-
- // nsINavBookmarkObserver
- onBeginUpdateBatch() {
- return this.validate("onBeginUpdateBatch", arguments);
- },
- onEndUpdateBatch() {
- return this.validate("onEndUpdateBatch", arguments);
- },
- onItemAdded() {
- return this.validate("onItemAdded", arguments);
- },
- onItemRemoved() {
- return this.validate("onItemRemoved", arguments);
- },
- onItemChanged() {
- return this.validate("onItemChanged", arguments);
- },
- onItemVisited() {
- return this.validate("onItemVisited", arguments);
- },
- onItemMoved() {
- return this.validate("onItemMoved", arguments);
- },
-
- // nsISupports
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver]),
-};
-
-
-add_task(function setup() {
- PlacesUtils.bookmarks.addObserver(gBookmarksObserver, false);
- PlacesUtils.bookmarks.addObserver(gBookmarkSkipObserver, false);
-});
-
-add_task(function* batch() {
- let promise = Promise.all([
- gBookmarksObserver.setup([
- { name: "onBeginUpdateBatch",
- args: [] },
- { name: "onEndUpdateBatch",
- args: [] },
- ]),
- gBookmarkSkipObserver.setup([
- "onBeginUpdateBatch", "onEndUpdateBatch"
- ])]);
- PlacesUtils.bookmarks.runInBatchMode({
- runBatched: function () {
- // Nothing.
- }
- }, null);
- yield promise;
-});
-
-add_task(function* onItemAdded_bookmark() {
- const TITLE = "Bookmark 1";
- let uri = NetUtil.newURI("http://1.mozilla.org/");
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemAdded"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemAdded",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "title", check: v => v === TITLE },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri, PlacesUtils.bookmarks.DEFAULT_INDEX,
- TITLE);
- yield promise;
-});
-
-add_task(function* onItemAdded_separator() {
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemAdded"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemAdded",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "index", check: v => v === 1 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_SEPARATOR },
- { name: "uri", check: v => v === null },
- { name: "title", check: v => v === null },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.insertSeparator(PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- yield promise;
-});
-
-add_task(function* onItemAdded_folder() {
- const TITLE = "Folder 1";
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemAdded"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemAdded",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "index", check: v => v === 2 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "title", check: v => v === TITLE },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.createFolder(PlacesUtils.unfiledBookmarksFolderId,
- TITLE,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- yield promise;
-});
-
-add_task(function* onItemChanged_title_bookmark() {
- let id = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- const TITLE = "New title";
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemChanged"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemChanged", // This is an unfortunate effect of bug 653910.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "property", check: v => v === "title" },
- { name: "isAnno", check: v => v === false },
- { name: "newValue", check: v => v === TITLE },
- { name: "lastModified", check: v => typeof(v) == "number" && v > 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldValue", check: v => typeof(v) == "string" },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.setItemTitle(id, TITLE);
- yield promise;
-});
-
-add_task(function* onItemChanged_tags_bookmark() {
- let id = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- let uri = PlacesUtils.bookmarks.getBookmarkURI(id);
- const TAG = "tag";
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemChanged", "onItemChanged"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemAdded", // This is the tag folder.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.tagsFolderId },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "title", check: v => v === TAG },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemAdded", // This is the tag.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "title", check: v => v === null },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemChanged",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "property", check: v => v === "tags" },
- { name: "isAnno", check: v => v === false },
- { name: "newValue", check: v => v === "" },
- { name: "lastModified", check: v => typeof(v) == "number" && v > 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldValue", check: v => typeof(v) == "string" },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved", // This is the tag.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved", // This is the tag folder.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.tagsFolderId },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemChanged",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "property", check: v => v === "tags" },
- { name: "isAnno", check: v => v === false },
- { name: "newValue", check: v => v === "" },
- { name: "lastModified", check: v => typeof(v) == "number" && v > 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldValue", check: v => typeof(v) == "string" },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.tagging.tagURI(uri, [TAG]);
- PlacesUtils.tagging.untagURI(uri, [TAG]);
- yield promise;
-});
-
-add_task(function* onItemMoved_bookmark() {
- let id = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemMoved", "onItemMoved"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemMoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "oldParentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "oldIndex", check: v => v === 0 },
- { name: "newParentId", check: v => v === PlacesUtils.toolbarFolderId },
- { name: "newIndex", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldParentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "newParentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemMoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "oldParentId", check: v => v === PlacesUtils.toolbarFolderId },
- { name: "oldIndex", check: v => v === 0 },
- { name: "newParentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "newIndex", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldParentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "newParentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.moveItem(id, PlacesUtils.toolbarFolderId, 0);
- PlacesUtils.bookmarks.moveItem(id, PlacesUtils.unfiledBookmarksFolderId, 0);
- yield promise;
-});
-
-add_task(function* onItemMoved_bookmark() {
- let id = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- let uri = PlacesUtils.bookmarks.getBookmarkURI(id);
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemVisited"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemVisited",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "visitId", check: v => typeof(v) == "number" && v > 0 },
- { name: "time", check: v => typeof(v) == "number" && v > 0 },
- { name: "transitionType", check: v => v === PlacesUtils.history.TRANSITION_TYPED },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- ] },
- ])]);
- PlacesTestUtils.addVisits({ uri: uri, transition: TRANSITION_TYPED });
- yield promise;
-});
-
-add_task(function* onItemRemoved_bookmark() {
- let id = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- let uri = PlacesUtils.bookmarks.getBookmarkURI(id);
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemChanged", "onItemRemoved"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemChanged", // This is an unfortunate effect of bug 653910.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "property", check: v => v === "" },
- { name: "isAnno", check: v => v === true },
- { name: "newValue", check: v => v === "" },
- { name: "lastModified", check: v => typeof(v) == "number" && v > 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldValue", check: v => typeof(v) == "string" },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.removeItem(id);
- yield promise;
-});
-
-add_task(function* onItemRemoved_separator() {
- let id = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemChanged", "onItemRemoved"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemChanged", // This is an unfortunate effect of bug 653910.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "property", check: v => v === "" },
- { name: "isAnno", check: v => v === true },
- { name: "newValue", check: v => v === "" },
- { name: "lastModified", check: v => typeof(v) == "number" && v > 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_SEPARATOR },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldValue", check: v => typeof(v) == "string" },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_SEPARATOR },
- { name: "uri", check: v => v === null },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.removeItem(id);
- yield promise;
-});
-
-add_task(function* onItemRemoved_folder() {
- let id = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemChanged", "onItemRemoved"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemChanged", // This is an unfortunate effect of bug 653910.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "property", check: v => v === "" },
- { name: "isAnno", check: v => v === true },
- { name: "newValue", check: v => v === "" },
- { name: "lastModified", check: v => typeof(v) == "number" && v > 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldValue", check: v => typeof(v) == "string" },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- PlacesUtils.bookmarks.removeItem(id);
- yield promise;
-});
-
-add_task(function* onItemRemoved_folder_recursive() {
- const TITLE = "Folder 3";
- const BMTITLE = "Bookmark 1";
- let uri = NetUtil.newURI("http://1.mozilla.org/");
- let promise = Promise.all([
- gBookmarkSkipObserver.setup([
- "onItemAdded", "onItemAdded", "onItemAdded", "onItemAdded",
- "onItemChanged", "onItemRemoved"
- ]),
- gBookmarksObserver.setup([
- { name: "onItemAdded",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.unfiledBookmarksFolderId },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "title", check: v => v === TITLE },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemAdded",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0) },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "title", check: v => v === BMTITLE },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemAdded",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0) },
- { name: "index", check: v => v === 1 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "title", check: v => v === TITLE },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemAdded",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => v === PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0), 1) },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "title", check: v => v === BMTITLE },
- { name: "dateAdded", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemChanged", // This is an unfortunate effect of bug 653910.
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "property", check: v => v === "" },
- { name: "isAnno", check: v => v === true },
- { name: "newValue", check: v => v === "" },
- { name: "lastModified", check: v => typeof(v) == "number" && v > 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "oldValue", check: v => typeof(v) == "string" },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 1 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_BOOKMARK },
- { name: "uri", check: v => v instanceof Ci.nsIURI && v.equals(uri) },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- { name: "onItemRemoved",
- args: [
- { name: "itemId", check: v => typeof(v) == "number" && v > 0 },
- { name: "parentId", check: v => typeof(v) == "number" && v > 0 },
- { name: "index", check: v => v === 0 },
- { name: "itemType", check: v => v === PlacesUtils.bookmarks.TYPE_FOLDER },
- { name: "uri", check: v => v === null },
- { name: "guid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "parentGuid", check: v => typeof(v) == "string" && GUID_RE.test(v) },
- { name: "source", check: v => Object.values(PlacesUtils.bookmarks.SOURCES).includes(v) },
- ] },
- ])]);
- let folder = PlacesUtils.bookmarks.createFolder(PlacesUtils.unfiledBookmarksFolderId,
- TITLE,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.insertBookmark(folder,
- uri, PlacesUtils.bookmarks.DEFAULT_INDEX,
- BMTITLE);
- let folder2 = PlacesUtils.bookmarks.createFolder(folder, TITLE,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.insertBookmark(folder2,
- uri, PlacesUtils.bookmarks.DEFAULT_INDEX,
- BMTITLE);
-
- PlacesUtils.bookmarks.removeItem(folder);
- yield promise;
-});
-
-add_task(function cleanup()
-{
- PlacesUtils.bookmarks.removeObserver(gBookmarksObserver);
- PlacesUtils.bookmarks.removeObserver(gBookmarkSkipObserver);
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_protectRoots.js b/toolkit/components/places/tests/bookmarks/test_protectRoots.js
deleted file mode 100644
index 0a59f1653..000000000
--- a/toolkit/components/places/tests/bookmarks/test_protectRoots.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test()
-{
- const ROOTS = [
- PlacesUtils.bookmarksMenuFolderId,
- PlacesUtils.toolbarFolderId,
- PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.tagsFolderId,
- PlacesUtils.placesRootId,
- PlacesUtils.mobileFolderId,
- ];
-
- for (let root of ROOTS) {
- do_check_true(PlacesUtils.isRootItem(root));
-
- try {
- PlacesUtils.bookmarks.removeItem(root);
- do_throw("Trying to remove a root should throw");
- } catch (ex) {}
-
- try {
- PlacesUtils.bookmarks.moveItem(root, PlacesUtils.placesRootId, 0);
- do_throw("Trying to move a root should throw");
- } catch (ex) {}
-
- try {
- PlacesUtils.bookmarks.removeFolderChildren(root);
- if (root == PlacesUtils.placesRootId)
- do_throw("Trying to remove children of the main root should throw");
- } catch (ex) {
- if (root != PlacesUtils.placesRootId)
- do_throw("Trying to remove children of other roots should not throw");
- }
- }
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_removeFolderTransaction_reinsert.js b/toolkit/components/places/tests/bookmarks/test_removeFolderTransaction_reinsert.js
deleted file mode 100644
index 537974b38..000000000
--- a/toolkit/components/places/tests/bookmarks/test_removeFolderTransaction_reinsert.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * This test ensures that reinserting a folder within a transaction gives it
- * a different GUID, and passes the GUID to the observers.
- */
-
-add_task(function* test_removeFolderTransaction_reinsert() {
- let folder = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- title: "Test folder",
- });
- let folderId = yield PlacesUtils.promiseItemId(folder.guid);
- let fx = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder.guid,
- title: "Get Firefox!",
- url: "http://getfirefox.com",
- });
- let fxId = yield PlacesUtils.promiseItemId(fx.guid);
- let tb = yield PlacesUtils.bookmarks.insert({
- parentGuid: folder.guid,
- title: "Get Thunderbird!",
- url: "http://getthunderbird.com",
- });
- let tbId = yield PlacesUtils.promiseItemId(tb.guid);
-
- let notifications = [];
- function checkNotifications(expected, message) {
- deepEqual(notifications, expected, message);
- notifications.length = 0;
- }
-
- let observer = {
- onItemAdded(itemId, parentId, index, type, uri, title, dateAdded, guid,
- parentGuid) {
- notifications.push(["onItemAdded", itemId, parentId, guid, parentGuid]);
- },
- onItemRemoved(itemId, parentId, index, type, uri, guid, parentGuid) {
- notifications.push(["onItemRemoved", itemId, parentId, guid, parentGuid]);
- },
- };
- PlacesUtils.bookmarks.addObserver(observer, false);
- PlacesUtils.registerShutdownFunction(function() {
- PlacesUtils.bookmarks.removeObserver(observer);
- });
-
- let transaction = PlacesUtils.bookmarks.getRemoveFolderTransaction(folderId);
- deepEqual(notifications, [], "We haven't executed the transaction yet");
-
- transaction.doTransaction();
- checkNotifications([
- ["onItemRemoved", tbId, folderId, tb.guid, folder.guid],
- ["onItemRemoved", fxId, folderId, fx.guid, folder.guid],
- ["onItemRemoved", folderId, PlacesUtils.bookmarksMenuFolderId, folder.guid,
- PlacesUtils.bookmarks.menuGuid],
- ], "Executing transaction should remove folder and its descendants");
-
- transaction.undoTransaction();
- // At this point, the restored folder has the same ID, but a different GUID.
- let newFolderGuid = yield PlacesUtils.promiseItemGuid(folderId);
- checkNotifications([
- ["onItemAdded", folderId, PlacesUtils.bookmarksMenuFolderId, newFolderGuid,
- PlacesUtils.bookmarks.menuGuid],
- ], "Undo should reinsert folder with same ID and different GUID");
-
- transaction.redoTransaction();
- checkNotifications([
- ["onItemRemoved", folderId, PlacesUtils.bookmarksMenuFolderId,
- newFolderGuid, PlacesUtils.bookmarks.menuGuid],
- ], "Redo should forward new GUID to observer");
-});
diff --git a/toolkit/components/places/tests/bookmarks/test_removeItem.js b/toolkit/components/places/tests/bookmarks/test_removeItem.js
deleted file mode 100644
index ec846b28e..000000000
--- a/toolkit/components/places/tests/bookmarks/test_removeItem.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [];
-
-
-const DEFAULT_INDEX = PlacesUtils.bookmarks.DEFAULT_INDEX;
-
-function run_test() {
- // folder to hold this test
- var folderId =
- PlacesUtils.bookmarks.createFolder(PlacesUtils.toolbarFolderId,
- "", DEFAULT_INDEX);
-
- // add a bookmark to the new folder
- var bookmarkURI = uri("http://iasdjkf");
- do_check_false(PlacesUtils.bookmarks.isBookmarked(bookmarkURI));
- var bookmarkId = PlacesUtils.bookmarks.insertBookmark(folderId, bookmarkURI,
- DEFAULT_INDEX, "");
- do_check_eq(PlacesUtils.bookmarks.getItemTitle(bookmarkId), "");
-
- // remove the folder using removeItem
- PlacesUtils.bookmarks.removeItem(folderId);
- do_check_eq(PlacesUtils.bookmarks.getBookmarkIdsForURI(bookmarkURI).length, 0);
- do_check_false(PlacesUtils.bookmarks.isBookmarked(bookmarkURI));
- do_check_eq(PlacesUtils.bookmarks.getItemIndex(bookmarkId), -1);
-}
diff --git a/toolkit/components/places/tests/bookmarks/test_savedsearches.js b/toolkit/components/places/tests/bookmarks/test_savedsearches.js
deleted file mode 100644
index eee2c4489..000000000
--- a/toolkit/components/places/tests/bookmarks/test_savedsearches.js
+++ /dev/null
@@ -1,209 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// get bookmarks root id
-var root = PlacesUtils.bookmarksMenuFolderId;
-
-// a search term that matches a default bookmark
-const searchTerm = "about";
-
-var testRoot;
-
-// main
-function run_test() {
- // create a folder to hold all the tests
- // this makes the tests more tolerant of changes to the default bookmarks set
- // also, name it using the search term, for testing that containers that match don't show up in query results
- testRoot = PlacesUtils.bookmarks.createFolder(
- root, searchTerm, PlacesUtils.bookmarks.DEFAULT_INDEX);
-
- run_next_test();
-}
-
-add_test(function test_savedsearches_bookmarks() {
- // add a bookmark that matches the search term
- var bookmarkId = PlacesUtils.bookmarks.insertBookmark(
- root, uri("http://foo.com"), PlacesUtils.bookmarks.DEFAULT_INDEX,
- searchTerm);
-
- // create a saved-search that matches a default bookmark
- var searchId = PlacesUtils.bookmarks.insertBookmark(
- testRoot, uri("place:terms=" + searchTerm + "&excludeQueries=1&expandQueries=1&queryType=1"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, searchTerm);
-
- // query for the test root, expandQueries=0
- // the query should show up as a regular bookmark
- try {
- let options = PlacesUtils.history.getNewQueryOptions();
- options.expandQueries = 0;
- let query = PlacesUtils.history.getNewQuery();
- query.setFolders([testRoot], 1);
- let result = PlacesUtils.history.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- let cc = rootNode.childCount;
- do_check_eq(cc, 1);
- for (let i = 0; i < cc; i++) {
- let node = rootNode.getChild(i);
- // test that queries have valid itemId
- do_check_true(node.itemId > 0);
- // test that the container is closed
- node.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(node.containerOpen, false);
- }
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("expandQueries=0 query error: " + ex);
- }
-
- // bookmark saved search
- // query for the test root, expandQueries=1
- // the query should show up as a query container, with 1 child
- try {
- let options = PlacesUtils.history.getNewQueryOptions();
- options.expandQueries = 1;
- let query = PlacesUtils.history.getNewQuery();
- query.setFolders([testRoot], 1);
- let result = PlacesUtils.history.executeQuery(query, options);
- let rootNode = result.root;
- rootNode.containerOpen = true;
- let cc = rootNode.childCount;
- do_check_eq(cc, 1);
- for (let i = 0; i < cc; i++) {
- let node = rootNode.getChild(i);
- // test that query node type is container when expandQueries=1
- do_check_eq(node.type, node.RESULT_TYPE_QUERY);
- // test that queries (as containers) have valid itemId
- do_check_true(node.itemId > 0);
- node.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- node.containerOpen = true;
-
- // test that queries have children when excludeItems=1
- // test that query nodes don't show containers (shouldn't have our folder that matches)
- // test that queries don't show themselves in query results (shouldn't have our saved search)
- do_check_eq(node.childCount, 1);
-
- // test that bookmark shows in query results
- var item = node.getChild(0);
- do_check_eq(item.itemId, bookmarkId);
-
- // XXX - FAILING - test live-update of query results - add a bookmark that matches the query
- // var tmpBmId = PlacesUtils.bookmarks.insertBookmark(
- // root, uri("http://" + searchTerm + ".com"),
- // PlacesUtils.bookmarks.DEFAULT_INDEX, searchTerm + "blah");
- // do_check_eq(query.childCount, 2);
-
- // XXX - test live-update of query results - delete a bookmark that matches the query
- // PlacesUtils.bookmarks.removeItem(tmpBMId);
- // do_check_eq(query.childCount, 1);
-
- // test live-update of query results - add a folder that matches the query
- PlacesUtils.bookmarks.createFolder(
- root, searchTerm + "zaa", PlacesUtils.bookmarks.DEFAULT_INDEX);
- do_check_eq(node.childCount, 1);
- // test live-update of query results - add a query that matches the query
- PlacesUtils.bookmarks.insertBookmark(
- root, uri("place:terms=foo&excludeQueries=1&expandQueries=1&queryType=1"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, searchTerm + "blah");
- do_check_eq(node.childCount, 1);
- }
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("expandQueries=1 bookmarks query: " + ex);
- }
-
- // delete the bookmark search
- PlacesUtils.bookmarks.removeItem(searchId);
-
- run_next_test();
-});
-
-add_task(function* test_savedsearches_history() {
- // add a visit that matches the search term
- var testURI = uri("http://" + searchTerm + ".com");
- yield PlacesTestUtils.addVisits({ uri: testURI, title: searchTerm });
-
- // create a saved-search that matches the visit we added
- var searchId = PlacesUtils.bookmarks.insertBookmark(testRoot,
- uri("place:terms=" + searchTerm + "&excludeQueries=1&expandQueries=1&queryType=0"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, searchTerm);
-
- // query for the test root, expandQueries=1
- // the query should show up as a query container, with 1 child
- try {
- var options = PlacesUtils.history.getNewQueryOptions();
- options.expandQueries = 1;
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([testRoot], 1);
- var result = PlacesUtils.history.executeQuery(query, options);
- var rootNode = result.root;
- rootNode.containerOpen = true;
- var cc = rootNode.childCount;
- do_check_eq(cc, 1);
- for (var i = 0; i < cc; i++) {
- var node = rootNode.getChild(i);
- // test that query node type is container when expandQueries=1
- do_check_eq(node.type, node.RESULT_TYPE_QUERY);
- // test that queries (as containers) have valid itemId
- do_check_eq(node.itemId, searchId);
- node.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- node.containerOpen = true;
-
- // test that queries have children when excludeItems=1
- // test that query nodes don't show containers (shouldn't have our folder that matches)
- // test that queries don't show themselves in query results (shouldn't have our saved search)
- do_check_eq(node.childCount, 1);
-
- // test that history visit shows in query results
- var item = node.getChild(0);
- do_check_eq(item.type, item.RESULT_TYPE_URI);
- do_check_eq(item.itemId, -1); // history visit
- do_check_eq(item.uri, testURI.spec); // history visit
-
- // test live-update of query results - add a history visit that matches the query
- yield PlacesTestUtils.addVisits({
- uri: uri("http://foo.com"),
- title: searchTerm + "blah"
- });
- do_check_eq(node.childCount, 2);
-
- // test live-update of query results - delete a history visit that matches the query
- PlacesUtils.history.removePage(uri("http://foo.com"));
- do_check_eq(node.childCount, 1);
- node.containerOpen = false;
- }
-
- // test live-update of moved queries
- var tmpFolderId = PlacesUtils.bookmarks.createFolder(
- testRoot, "foo", PlacesUtils.bookmarks.DEFAULT_INDEX);
- PlacesUtils.bookmarks.moveItem(
- searchId, tmpFolderId, PlacesUtils.bookmarks.DEFAULT_INDEX);
- var tmpFolderNode = rootNode.getChild(0);
- do_check_eq(tmpFolderNode.itemId, tmpFolderId);
- tmpFolderNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- tmpFolderNode.containerOpen = true;
- do_check_eq(tmpFolderNode.childCount, 1);
-
- // test live-update of renamed queries
- PlacesUtils.bookmarks.setItemTitle(searchId, "foo");
- do_check_eq(tmpFolderNode.title, "foo");
-
- // test live-update of deleted queries
- PlacesUtils.bookmarks.removeItem(searchId);
- try {
- tmpFolderNode = root.getChild(1);
- do_throw("query was not removed");
- } catch (ex) {}
-
- tmpFolderNode.containerOpen = false;
- rootNode.containerOpen = false;
- }
- catch (ex) {
- do_throw("expandQueries=1 bookmarks query: " + ex);
- }
-});
diff --git a/toolkit/components/places/tests/bookmarks/xpcshell.ini b/toolkit/components/places/tests/bookmarks/xpcshell.ini
deleted file mode 100644
index c290fd693..000000000
--- a/toolkit/components/places/tests/bookmarks/xpcshell.ini
+++ /dev/null
@@ -1,50 +0,0 @@
-[DEFAULT]
-head = head_bookmarks.js
-tail =
-skip-if = toolkit == 'android'
-
-[test_1016953-renaming-uncompressed.js]
-[test_1017502-bookmarks_foreign_count.js]
-[test_384228.js]
-[test_385829.js]
-[test_388695.js]
-[test_393498.js]
-[test_395101.js]
-[test_395593.js]
-[test_405938_restore_queries.js]
-[test_417228-exclude-from-backup.js]
-[test_417228-other-roots.js]
-[test_424958-json-quoted-folders.js]
-[test_448584.js]
-[test_458683.js]
-[test_466303-json-remove-backups.js]
-[test_477583_json-backup-in-future.js]
-[test_675416.js]
-[test_711914.js]
-[test_818584-discard-duplicate-backups.js]
-[test_818587_compress-bookmarks-backups.js]
-[test_818593-store-backup-metadata.js]
-[test_992901-backup-unsorted-hierarchy.js]
-[test_997030-bookmarks-html-encode.js]
-[test_1129529.js]
-[test_async_observers.js]
-[test_bmindex.js]
-[test_bookmarkstree_cache.js]
-[test_bookmarks.js]
-[test_bookmarks_eraseEverything.js]
-[test_bookmarks_fetch.js]
-[test_bookmarks_getRecent.js]
-[test_bookmarks_insert.js]
-[test_bookmarks_notifications.js]
-[test_bookmarks_remove.js]
-[test_bookmarks_reorder.js]
-[test_bookmarks_search.js]
-[test_bookmarks_update.js]
-[test_changeBookmarkURI.js]
-[test_getBookmarkedURIFor.js]
-[test_keywords.js]
-[test_nsINavBookmarkObserver.js]
-[test_protectRoots.js]
-[test_removeFolderTransaction_reinsert.js]
-[test_removeItem.js]
-[test_savedsearches.js]
diff --git a/toolkit/components/places/tests/browser/.eslintrc.js b/toolkit/components/places/tests/browser/.eslintrc.js
deleted file mode 100644
index 7a41a9cde..000000000
--- a/toolkit/components/places/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,8 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js",
- "../../../../../testing/mochitest/mochitest.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/browser/399606-history.go-0.html b/toolkit/components/places/tests/browser/399606-history.go-0.html
deleted file mode 100644
index 039708ed7..000000000
--- a/toolkit/components/places/tests/browser/399606-history.go-0.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
-<head>
-<title>history.go(0)</title>
-<script>
-setTimeout('history.go(0)', 1000);
-</script>
-</head>
-<body>
-Testing history.go(0)
-</body>
-</html>
diff --git a/toolkit/components/places/tests/browser/399606-httprefresh.html b/toolkit/components/places/tests/browser/399606-httprefresh.html
deleted file mode 100644
index e43455ee0..000000000
--- a/toolkit/components/places/tests/browser/399606-httprefresh.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html><head>
-<meta http-equiv="content-type" content="text/html; charset=UTF-8">
-
-<meta http-equiv="refresh" content="1">
-<title>httprefresh</title>
-</head><body>
-Testing httprefresh
-</body></html>
diff --git a/toolkit/components/places/tests/browser/399606-location.reload.html b/toolkit/components/places/tests/browser/399606-location.reload.html
deleted file mode 100644
index 0f46538cd..000000000
--- a/toolkit/components/places/tests/browser/399606-location.reload.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
-<head>
-<title>location.reload()</title>
-<script>
-setTimeout('location.reload();', 100);
-</script>
-</head>
-<body>
-Testing location.reload();
-</body>
-</html>
diff --git a/toolkit/components/places/tests/browser/399606-location.replace.html b/toolkit/components/places/tests/browser/399606-location.replace.html
deleted file mode 100644
index 36705402c..000000000
--- a/toolkit/components/places/tests/browser/399606-location.replace.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
-<head>
-<title>location.replace</title>
-<script>
-setTimeout('location.replace(window.location.href)', 1000);
-</script>
-</head>
-<body>
-Testing location.replace
-</body>
-</html>
diff --git a/toolkit/components/places/tests/browser/399606-window.location.href.html b/toolkit/components/places/tests/browser/399606-window.location.href.html
deleted file mode 100644
index 61a2c8ba0..000000000
--- a/toolkit/components/places/tests/browser/399606-window.location.href.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
-<head>
-<title>window.location.href</title>
-<script>
-setTimeout('window.location.href = window.location.href', 1000);
-</script>
-</head>
-<body>
-Testing window.location.href
-</body>
-</html>
diff --git a/toolkit/components/places/tests/browser/399606-window.location.html b/toolkit/components/places/tests/browser/399606-window.location.html
deleted file mode 100644
index e77f73071..000000000
--- a/toolkit/components/places/tests/browser/399606-window.location.html
+++ /dev/null
@@ -1,11 +0,0 @@
-<html>
-<head>
-<title>window.location</title>
-<script>
-setTimeout('window.location = window.location', 1000);
-</script>
-</head>
-<body>
-Testing window.location
-</body>
-</html>
diff --git a/toolkit/components/places/tests/browser/461710_iframe.html b/toolkit/components/places/tests/browser/461710_iframe.html
deleted file mode 100644
index 7480fe58f..000000000
--- a/toolkit/components/places/tests/browser/461710_iframe.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- </head>
- <body>
- <iframe id="iframe"></iframe>
- </body>
-</html>
diff --git a/toolkit/components/places/tests/browser/461710_link_page-2.html b/toolkit/components/places/tests/browser/461710_link_page-2.html
deleted file mode 100644
index 1fc3e0959..000000000
--- a/toolkit/components/places/tests/browser/461710_link_page-2.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <title>Link page 2</title>
- <style type="text/css">
- a:link { color: #0000ff; }
- a:visited { color: #ff0000; }
- </style>
- </head>
- <body>
- <p><a href="461710_visited_page.html" id="link">Link to the second visited page</a></p>
- </body>
-</html> \ No newline at end of file
diff --git a/toolkit/components/places/tests/browser/461710_link_page-3.html b/toolkit/components/places/tests/browser/461710_link_page-3.html
deleted file mode 100644
index 596661803..000000000
--- a/toolkit/components/places/tests/browser/461710_link_page-3.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <title>Link page 3</title>
- <style type="text/css">
- a:link { color: #0000ff; }
- a:visited { color: #ff0000; }
- </style>
- </head>
- <body>
- <p><a href="461710_visited_page.html" id="link">Link to the third visited page</a></p>
- </body>
-</html> \ No newline at end of file
diff --git a/toolkit/components/places/tests/browser/461710_link_page.html b/toolkit/components/places/tests/browser/461710_link_page.html
deleted file mode 100644
index 6bea50628..000000000
--- a/toolkit/components/places/tests/browser/461710_link_page.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <title>Link page</title>
- <style type="text/css">
- a:link { color: #0000ff; }
- a:visited { color: #ff0000; }
- </style>
- </head>
- <body>
- <p><a href="461710_visited_page.html" id="link">Link to the visited page</a></p>
- </body>
-</html> \ No newline at end of file
diff --git a/toolkit/components/places/tests/browser/461710_visited_page.html b/toolkit/components/places/tests/browser/461710_visited_page.html
deleted file mode 100644
index 90e65116b..000000000
--- a/toolkit/components/places/tests/browser/461710_visited_page.html
+++ /dev/null
@@ -1,9 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <title>Visited page</title>
- </head>
- <body>
- <p>This page is marked as visited</p>
- </body>
-</html> \ No newline at end of file
diff --git a/toolkit/components/places/tests/browser/begin.html b/toolkit/components/places/tests/browser/begin.html
deleted file mode 100644
index da4c16dd2..000000000
--- a/toolkit/components/places/tests/browser/begin.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-
-<html>
- <body>
- <a id="clickme" href="redirect_twice.sjs">Redirect twice</a>
- </body>
-</html>
diff --git a/toolkit/components/places/tests/browser/browser.ini b/toolkit/components/places/tests/browser/browser.ini
deleted file mode 100644
index e6abe987f..000000000
--- a/toolkit/components/places/tests/browser/browser.ini
+++ /dev/null
@@ -1,26 +0,0 @@
-[DEFAULT]
-support-files =
- colorAnalyzer/category-discover.png
- colorAnalyzer/dictionaryGeneric-16.png
- colorAnalyzer/extensionGeneric-16.png
- colorAnalyzer/localeGeneric.png
- head.js
-
-[browser_bug248970.js]
-[browser_bug399606.js]
-[browser_bug461710.js]
-[browser_bug646422.js]
-[browser_bug680727.js]
-[browser_colorAnalyzer.js]
-[browser_double_redirect.js]
-[browser_favicon_privatebrowsing_perwindowpb.js]
-[browser_favicon_setAndFetchFaviconForPage.js]
-[browser_favicon_setAndFetchFaviconForPage_failures.js]
-[browser_history_post.js]
-[browser_notfound.js]
-[browser_redirect.js]
-[browser_settitle.js]
-[browser_visited_notfound.js]
-[browser_visituri.js]
-[browser_visituri_nohistory.js]
-[browser_visituri_privatebrowsing_perwindowpb.js] \ No newline at end of file
diff --git a/toolkit/components/places/tests/browser/browser_bug248970.js b/toolkit/components/places/tests/browser/browser_bug248970.js
deleted file mode 100644
index 5850a3038..000000000
--- a/toolkit/components/places/tests/browser/browser_bug248970.js
+++ /dev/null
@@ -1,152 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This test performs checks on the history testing area as outlined
-// https://wiki.mozilla.org/Firefox3.1/PrivateBrowsing/TestPlan#History
-// http://developer.mozilla.org/en/Using_the_Places_history_service
-
-var visitedURIs = [
- "http://www.test-link.com/",
- "http://www.test-typed.com/",
- "http://www.test-bookmark.com/",
- "http://www.test-redirect-permanent.com/",
- "http://www.test-redirect-temporary.com/",
- "http://www.test-embed.com/",
- "http://www.test-framed.com/",
- "http://www.test-download.com/"
-].map(NetUtil.newURI.bind(NetUtil));
-
-add_task(function* () {
- let windowsToClose = [];
- let placeItemsCount = 0;
-
- registerCleanupFunction(function() {
- windowsToClose.forEach(function(win) {
- win.close();
- });
- });
-
- yield PlacesTestUtils.clearHistory();
-
- // Ensure we wait for the default bookmarks import.
- yield new Promise(resolve => {
- waitForCondition(() => {
- placeItemsCount = getPlacesItemsCount();
- return placeItemsCount > 0
- }, resolve, "Should have default bookmarks")
- });
-
- // Create a handful of history items with various visit types
- yield PlacesTestUtils.addVisits([
- { uri: visitedURIs[0], transition: TRANSITION_LINK },
- { uri: visitedURIs[1], transition: TRANSITION_TYPED },
- { uri: visitedURIs[2], transition: TRANSITION_BOOKMARK },
- { uri: visitedURIs[3], transition: TRANSITION_REDIRECT_PERMANENT },
- { uri: visitedURIs[4], transition: TRANSITION_REDIRECT_TEMPORARY },
- { uri: visitedURIs[5], transition: TRANSITION_EMBED },
- { uri: visitedURIs[6], transition: TRANSITION_FRAMED_LINK },
- { uri: visitedURIs[7], transition: TRANSITION_DOWNLOAD }
- ]);
-
- placeItemsCount += 7;
- // We added 7 new items to history.
- is(getPlacesItemsCount(), placeItemsCount,
- "Check the total items count");
-
- function* testOnWindow(aIsPrivate, aCount) {
- let win = yield new Promise(resolve => {
- whenNewWindowLoaded({ private: aIsPrivate }, resolve);
- });
- windowsToClose.push(win);
-
- // History items should be retrievable by query
- yield checkHistoryItems();
-
- // Updates the place items count
- let count = getPlacesItemsCount();
-
- // Create Bookmark
- let title = "title " + windowsToClose.length;
- let keyword = "keyword " + windowsToClose.length;
- let url = "http://test-a-" + windowsToClose.length + ".com/";
-
- yield PlacesUtils.bookmarks.insert({ url, title,
- parentGuid: PlacesUtils.bookmarks.menuGuid });
- yield PlacesUtils.keywords.insert({ url, keyword });
- count++;
-
- ok((yield PlacesUtils.bookmarks.fetch({ url })),
- "Bookmark should be bookmarked, data should be retrievable");
- is(getPlacesItemsCount(), count,
- "Check the new bookmark items count");
- is(isBookmarkAltered(), false, "Check if bookmark has been visited");
- }
-
- // Test on windows.
- yield testOnWindow(false);
- yield testOnWindow(true);
- yield testOnWindow(false);
-});
-
-/**
- * Function performs a really simple query on our places entries,
- * and makes sure that the number of entries equal num_places_entries.
- */
-function getPlacesItemsCount() {
- // Get bookmarks count
- let options = PlacesUtils.history.getNewQueryOptions();
- options.includeHidden = true;
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- let root = PlacesUtils.history.executeQuery(
- PlacesUtils.history.getNewQuery(), options).root;
- root.containerOpen = true;
- let cc = root.childCount;
- root.containerOpen = false;
-
- // Get history item count
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY;
- root = PlacesUtils.history.executeQuery(
- PlacesUtils.history.getNewQuery(), options).root;
- root.containerOpen = true;
- cc += root.childCount;
- root.containerOpen = false;
-
- return cc;
-}
-
-function* checkHistoryItems() {
- for (let i = 0; i < visitedURIs.length; i++) {
- let visitedUri = visitedURIs[i];
- ok((yield promiseIsURIVisited(visitedUri)), "");
- if (/embed/.test(visitedUri.spec)) {
- is((yield PlacesTestUtils.isPageInDB(visitedUri)), false, "Check if URI is in database");
- } else {
- ok((yield PlacesTestUtils.isPageInDB(visitedUri)), "Check if URI is in database");
- }
- }
-}
-
-/**
- * Function attempts to check if Bookmark-A has been visited
- * during private browsing mode, function should return false
- *
- * @returns false if the accessCount has not changed
- * true if the accessCount has changed
- */
-function isBookmarkAltered() {
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- options.maxResults = 1; // should only expect a new bookmark
-
- let query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.bookmarksMenuFolder], 1);
-
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- is(root.childCount, options.maxResults, "Check new bookmarks results");
- let node = root.getChild(0);
- root.containerOpen = false;
-
- return (node.accessCount != 0);
-}
diff --git a/toolkit/components/places/tests/browser/browser_bug399606.js b/toolkit/components/places/tests/browser/browser_bug399606.js
deleted file mode 100644
index b5eee0f92..000000000
--- a/toolkit/components/places/tests/browser/browser_bug399606.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-gBrowser.selectedTab = gBrowser.addTab();
-
-function test() {
- waitForExplicitFinish();
-
- var URIs = [
- "http://example.com/tests/toolkit/components/places/tests/browser/399606-window.location.href.html",
- "http://example.com/tests/toolkit/components/places/tests/browser/399606-history.go-0.html",
- "http://example.com/tests/toolkit/components/places/tests/browser/399606-location.replace.html",
- "http://example.com/tests/toolkit/components/places/tests/browser/399606-location.reload.html",
- "http://example.com/tests/toolkit/components/places/tests/browser/399606-httprefresh.html",
- "http://example.com/tests/toolkit/components/places/tests/browser/399606-window.location.html",
- ];
- var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
- // Create and add history observer.
- var historyObserver = {
- visitCount: Array(),
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType) {
- info("Received onVisit: " + aURI.spec);
- if (aURI.spec in this.visitCount)
- this.visitCount[aURI.spec]++;
- else
- this.visitCount[aURI.spec] = 1;
- },
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
- };
- hs.addObserver(historyObserver, false);
-
- function confirm_results() {
- gBrowser.removeCurrentTab();
- hs.removeObserver(historyObserver, false);
- for (let aURI in historyObserver.visitCount) {
- is(historyObserver.visitCount[aURI], 1,
- "onVisit has been received right number of times for " + aURI);
- }
- PlacesTestUtils.clearHistory().then(finish);
- }
-
- var loadCount = 0;
- function handleLoad(aEvent) {
- loadCount++;
- info("new load count is " + loadCount);
-
- if (loadCount == 3) {
- gBrowser.removeEventListener("DOMContentLoaded", handleLoad, true);
- gBrowser.loadURI("about:blank");
- executeSoon(check_next_uri);
- }
- }
-
- function check_next_uri() {
- if (URIs.length) {
- let uri = URIs.shift();
- loadCount = 0;
- gBrowser.addEventListener("DOMContentLoaded", handleLoad, true);
- gBrowser.loadURI(uri);
- }
- else {
- confirm_results();
- }
- }
- executeSoon(check_next_uri);
-}
diff --git a/toolkit/components/places/tests/browser/browser_bug461710.js b/toolkit/components/places/tests/browser/browser_bug461710.js
deleted file mode 100644
index 12af87a06..000000000
--- a/toolkit/components/places/tests/browser/browser_bug461710.js
+++ /dev/null
@@ -1,82 +0,0 @@
-const kRed = "rgb(255, 0, 0)";
-const kBlue = "rgb(0, 0, 255)";
-
-const prefix = "http://example.com/tests/toolkit/components/places/tests/browser/461710_";
-
-add_task(function* () {
- let contentPage = prefix + "iframe.html";
- let normalWindow = yield BrowserTestUtils.openNewBrowserWindow();
-
- let browser = normalWindow.gBrowser.selectedBrowser;
- BrowserTestUtils.loadURI(browser, contentPage);
- yield BrowserTestUtils.browserLoaded(browser, contentPage);
-
- let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({private: true});
-
- browser = privateWindow.gBrowser.selectedBrowser;
- BrowserTestUtils.loadURI(browser, contentPage);
- yield BrowserTestUtils.browserLoaded(browser, contentPage);
-
- let tests = [{
- win: normalWindow,
- topic: "uri-visit-saved",
- subtest: "visited_page.html"
- }, {
- win: normalWindow,
- topic: "visited-status-resolution",
- subtest: "link_page.html",
- color: kRed,
- message: "Visited link coloring should work outside of private mode"
- }, {
- win: privateWindow,
- topic: "visited-status-resolution",
- subtest: "link_page-2.html",
- color: kBlue,
- message: "Visited link coloring should not work inside of private mode"
- }, {
- win: normalWindow,
- topic: "visited-status-resolution",
- subtest: "link_page-3.html",
- color: kRed,
- message: "Visited link coloring should work outside of private mode"
- }];
-
- let visited_page_url = prefix + tests[0].subtest;
- for (let test of tests) {
- let promise = new Promise(resolve => {
- let uri = NetUtil.newURI(visited_page_url);
- Services.obs.addObserver(function observe(aSubject) {
- if (uri.equals(aSubject.QueryInterface(Ci.nsIURI))) {
- Services.obs.removeObserver(observe, test.topic);
- resolve();
- }
- }, test.topic, false);
- });
- ContentTask.spawn(test.win.gBrowser.selectedBrowser, prefix + test.subtest, function* (aSrc) {
- content.document.getElementById("iframe").src = aSrc;
- });
- yield promise;
-
- if (test.color) {
- // In e10s waiting for visited-status-resolution is not enough to ensure links
- // have been updated, because it only tells us that messages to update links
- // have been dispatched. We must still wait for the actual links to update.
- yield BrowserTestUtils.waitForCondition(function* () {
- let color = yield ContentTask.spawn(test.win.gBrowser.selectedBrowser, null, function* () {
- let iframe = content.document.getElementById("iframe");
- let elem = iframe.contentDocument.getElementById("link");
- return content.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindowUtils)
- .getVisitedDependentComputedStyle(elem, "", "color");
- });
- return (color == test.color);
- }, test.message);
- // The harness will consider the test as failed overall if there were no
- // passes or failures, so record it as a pass.
- ok(true, test.message);
- }
- }
-
- yield BrowserTestUtils.closeWindow(normalWindow);
- yield BrowserTestUtils.closeWindow(privateWindow);
-});
diff --git a/toolkit/components/places/tests/browser/browser_bug646422.js b/toolkit/components/places/tests/browser/browser_bug646422.js
deleted file mode 100644
index 1a81de4e1..000000000
--- a/toolkit/components/places/tests/browser/browser_bug646422.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for Bug 646224. Make sure that after changing the URI via
- * history.pushState, the history service has a title stored for the new URI.
- **/
-
-add_task(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, 'http://example.com');
-
- let newTitlePromise = new Promise(resolve => {
- let observer = {
- onTitleChanged: function(uri, title) {
- // If the uri of the page whose title is changing ends with 'new_page',
- // then it's the result of our pushState.
- if (/new_page$/.test(uri.spec)) {
- resolve(title);
- PlacesUtils.history.removeObserver(observer);
- }
- },
-
- onBeginUpdateBatch: function() { },
- onEndUpdateBatch: function() { },
- onVisit: function() { },
- onDeleteURI: function() { },
- onClearHistory: function() { },
- onPageChanged: function() { },
- onDeleteVisits: function() { },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
- };
-
- PlacesUtils.history.addObserver(observer, false);
- });
-
- yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
- let title = content.document.title;
- content.history.pushState('', '', 'new_page');
- Assert.ok(title, "Content window should initially have a title.");
- });
-
- let newtitle = yield newTitlePromise;
-
- yield ContentTask.spawn(tab.linkedBrowser, { newtitle }, function* (args) {
- Assert.equal(args.newtitle, content.document.title, "Title after pushstate.");
- });
-
- yield PlacesTestUtils.clearHistory();
- gBrowser.removeTab(tab);
-});
diff --git a/toolkit/components/places/tests/browser/browser_bug680727.js b/toolkit/components/places/tests/browser/browser_bug680727.js
deleted file mode 100644
index 560cbfe6c..000000000
--- a/toolkit/components/places/tests/browser/browser_bug680727.js
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/* Ensure that clicking the button in the Offline mode neterror page updates
- global history. See bug 680727. */
-/* TEST_PATH=toolkit/components/places/tests/browser/browser_bug680727.js make -C $(OBJDIR) mochitest-browser-chrome */
-
-
-const kUniqueURI = Services.io.newURI("http://mochi.test:8888/#bug_680727",
- null, null);
-var gAsyncHistory =
- Cc["@mozilla.org/browser/history;1"].getService(Ci.mozIAsyncHistory);
-
-var proxyPrefValue;
-var ourTab;
-
-function test() {
- waitForExplicitFinish();
-
- // Tests always connect to localhost, and per bug 87717, localhost is now
- // reachable in offline mode. To avoid this, disable any proxy.
- proxyPrefValue = Services.prefs.getIntPref("network.proxy.type");
- Services.prefs.setIntPref("network.proxy.type", 0);
-
- // Clear network cache.
- Components.classes["@mozilla.org/netwerk/cache-storage-service;1"]
- .getService(Components.interfaces.nsICacheStorageService)
- .clear();
-
- // Go offline, expecting the error page.
- Services.io.offline = true;
-
- BrowserTestUtils.openNewForegroundTab(gBrowser).then(tab => {
- ourTab = tab;
- BrowserTestUtils.waitForContentEvent(ourTab.linkedBrowser, "DOMContentLoaded")
- .then(errorListener);
- BrowserTestUtils.loadURI(ourTab.linkedBrowser, kUniqueURI.spec);
- });
-}
-
-// ------------------------------------------------------------------------------
-// listen to loading the neterror page. (offline mode)
-function errorListener() {
- ok(Services.io.offline, "Services.io.offline is true.");
-
- // This is an error page.
- ContentTask.spawn(ourTab.linkedBrowser, kUniqueURI.spec, function(uri) {
- Assert.equal(content.document.documentURI.substring(0, 27),
- "about:neterror?e=netOffline", "Document URI is the error page.");
-
- // But location bar should show the original request.
- Assert.equal(content.location.href, uri, "Docshell URI is the original URI.");
- }).then(() => {
- // Global history does not record URI of a failed request.
- return PlacesTestUtils.promiseAsyncUpdates().then(() => {
- gAsyncHistory.isURIVisited(kUniqueURI, errorAsyncListener);
- });
- });
-}
-
-function errorAsyncListener(aURI, aIsVisited) {
- ok(kUniqueURI.equals(aURI) && !aIsVisited,
- "The neterror page is not listed in global history.");
-
- Services.prefs.setIntPref("network.proxy.type", proxyPrefValue);
-
- // Now press the "Try Again" button, with offline mode off.
- Services.io.offline = false;
-
- BrowserTestUtils.waitForContentEvent(ourTab.linkedBrowser, "DOMContentLoaded")
- .then(reloadListener);
-
- ContentTask.spawn(ourTab.linkedBrowser, null, function() {
- Assert.ok(content.document.getElementById("errorTryAgain"),
- "The error page has got a #errorTryAgain element");
- content.document.getElementById("errorTryAgain").click();
- });
-}
-
-// ------------------------------------------------------------------------------
-// listen to reload of neterror.
-function reloadListener() {
- // This listener catches "DOMContentLoaded" on being called
- // nsIWPL::onLocationChange(...). That is right *AFTER*
- // IHistory::VisitURI(...) is called.
- ok(!Services.io.offline, "Services.io.offline is false.");
-
- ContentTask.spawn(ourTab.linkedBrowser, kUniqueURI.spec, function(uri) {
- // This is not an error page.
- Assert.equal(content.document.documentURI, uri,
- "Document URI is not the offline-error page, but the original URI.");
- }).then(() => {
- // Check if global history remembers the successfully-requested URI.
- PlacesTestUtils.promiseAsyncUpdates().then(() => {
- gAsyncHistory.isURIVisited(kUniqueURI, reloadAsyncListener);
- });
- });
-}
-
-function reloadAsyncListener(aURI, aIsVisited) {
- ok(kUniqueURI.equals(aURI) && aIsVisited, "We have visited the URI.");
- PlacesTestUtils.clearHistory().then(finish);
-}
-
-registerCleanupFunction(function* () {
- Services.prefs.setIntPref("network.proxy.type", proxyPrefValue);
- Services.io.offline = false;
- yield BrowserTestUtils.removeTab(ourTab);
-});
diff --git a/toolkit/components/places/tests/browser/browser_colorAnalyzer.js b/toolkit/components/places/tests/browser/browser_colorAnalyzer.js
deleted file mode 100644
index 7b7fe6ec5..000000000
--- a/toolkit/components/places/tests/browser/browser_colorAnalyzer.js
+++ /dev/null
@@ -1,259 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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";
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-const CA = Cc["@mozilla.org/places/colorAnalyzer;1"].
- getService(Ci.mozIColorAnalyzer);
-
-const hiddenWindowDoc = Cc["@mozilla.org/appshell/appShellService;1"].
- getService(Ci.nsIAppShellService).
- hiddenDOMWindow.document;
-
-const XHTML_NS = "http://www.w3.org/1999/xhtml";
-
-/**
- * Passes the given uri to findRepresentativeColor.
- * If expected is null, you expect it to fail.
- * If expected is a function, it will call that function.
- * If expected is a color, you expect that color to be returned.
- * Message is used in the calls to is().
- */
-function frcTest(uri, expected, message) {
- return new Promise(resolve => {
- CA.findRepresentativeColor(Services.io.newURI(uri, "", null),
- function(success, color) {
- if (expected == null) {
- ok(!success, message);
- } else if (typeof expected == "function") {
- expected(color, message);
- } else {
- ok(success, "success: " + message);
- is(color, expected, message);
- }
- resolve();
- });
- });
-}
-
-/**
- * Handy function for getting an image into findRepresentativeColor and testing it.
- * Makes a canvas with the given dimensions, calls paintCanvasFunc with the 2d
- * context of the canvas, sticks the generated canvas into findRepresentativeColor.
- * See frcTest.
- */
-function canvasTest(width, height, paintCanvasFunc, expected, message) {
- let canvas = hiddenWindowDoc.createElementNS(XHTML_NS, "canvas");
- canvas.width = width;
- canvas.height = height;
- paintCanvasFunc(canvas.getContext("2d"));
- let uri = canvas.toDataURL();
- return frcTest(uri, expected, message);
-}
-
-// simple test - draw a red box in the center, make sure we get red back
-add_task(function* test_redSquare() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "red";
- ctx.fillRect(2, 2, 12, 12);
- }, 0xFF0000, "redSquare analysis returns red");
-});
-
-
-// draw a blue square in one corner, red in the other, such that blue overlaps
-// red by one pixel, making it the dominant color
-add_task(function* test_blueOverlappingRed() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "red";
- ctx.fillRect(0, 0, 8, 8);
- ctx.fillStyle = "blue";
- ctx.fillRect(7, 7, 8, 8);
- }, 0x0000FF, "blueOverlappingRed analysis returns blue");
-});
-
-// draw a red gradient next to a solid blue rectangle to ensure that a large
-// block of similar colors beats out a smaller block of one color
-add_task(function* test_redGradientBlueSolid() {
- yield canvasTest(16, 16, function(ctx) {
- let gradient = ctx.createLinearGradient(0, 0, 1, 15);
- gradient.addColorStop(0, "#FF0000");
- gradient.addColorStop(1, "#FF0808");
-
- ctx.fillStyle = gradient;
- ctx.fillRect(0, 0, 16, 16);
- ctx.fillStyle = "blue";
- ctx.fillRect(9, 0, 7, 16);
- }, function(actual, message) {
- ok(actual >= 0xFF0000 && actual <= 0xFF0808, message);
- }, "redGradientBlueSolid analysis returns redish");
-});
-
-// try a transparent image, should fail
-add_task(function* test_transparent() {
- yield canvasTest(16, 16, function(ctx) {
- // do nothing!
- }, null, "transparent analysis fails");
-});
-
-add_task(function* test_invalidURI() {
- yield frcTest("data:blah,Imnotavaliddatauri", null, "invalid URI analysis fails");
-});
-
-add_task(function* test_malformedPNGURI() {
- yield frcTest("data:image/png;base64,iVBORblahblahblah", null,
- "malformed PNG URI analysis fails");
-});
-
-add_task(function* test_unresolvableURI() {
- yield frcTest("http://www.example.com/blah/idontexist.png", null,
- "unresolvable URI analysis fails");
-});
-
-// draw a small blue box on a red background to make sure the algorithm avoids
-// using the background color
-add_task(function* test_blueOnRedBackground() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "red";
- ctx.fillRect(0, 0, 16, 16);
- ctx.fillStyle = "blue";
- ctx.fillRect(4, 4, 8, 8);
- }, 0x0000FF, "blueOnRedBackground analysis returns blue");
-});
-
-// draw a slightly different color in the corners to make sure the corner colors
-// don't have to be exactly equal to be considered the background color
-add_task(function* test_variableBackground() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "white";
- ctx.fillRect(0, 0, 16, 16);
- ctx.fillStyle = "#FEFEFE";
- ctx.fillRect(15, 0, 1, 1);
- ctx.fillStyle = "#FDFDFD";
- ctx.fillRect(15, 15, 1, 1);
- ctx.fillStyle = "#FCFCFC";
- ctx.fillRect(0, 15, 1, 1);
- ctx.fillStyle = "black";
- ctx.fillRect(4, 4, 8, 8);
- }, 0x000000, "variableBackground analysis returns black");
-});
-
-// like the above test, but make the colors different enough that they aren't
-// considered the background color
-add_task(function* test_tooVariableBackground() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "white";
- ctx.fillRect(0, 0, 16, 16);
- ctx.fillStyle = "#EEDDCC";
- ctx.fillRect(15, 0, 1, 1);
- ctx.fillStyle = "#DDDDDD";
- ctx.fillRect(15, 15, 1, 1);
- ctx.fillStyle = "#CCCCCC";
- ctx.fillRect(0, 15, 1, 1);
- ctx.fillStyle = "black";
- ctx.fillRect(4, 4, 8, 8);
- }, function(actual, message) {
- isnot(actual, 0x000000, message);
- }, "tooVariableBackground analysis doesn't return black");
-});
-
-// draw a small black/white box over transparent background to make sure the
-// algorithm doesn't think rgb(0,0,0) == rgba(0,0,0,0)
-add_task(function* test_transparentBackgroundConflation() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "black";
- ctx.fillRect(2, 2, 12, 12);
- ctx.fillStyle = "white";
- ctx.fillRect(5, 5, 6, 6);
- }, 0x000000, "transparentBackgroundConflation analysis returns black");
-});
-
-
-// make sure we fall back to the background color if we have no other choice
-// (instead of failing as if there were no colors)
-add_task(function* test_backgroundFallback() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "black";
- ctx.fillRect(0, 0, 16, 16);
- }, 0x000000, "backgroundFallback analysis returns black");
-});
-
-// draw red rectangle next to a pink one to make sure the algorithm picks the
-// more interesting color
-add_task(function* test_interestingColorPreference() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "#FFDDDD";
- ctx.fillRect(0, 0, 16, 16);
- ctx.fillStyle = "red";
- ctx.fillRect(0, 0, 3, 16);
- }, 0xFF0000, "interestingColorPreference analysis returns red");
-});
-
-// draw high saturation but dark red next to slightly less saturated color but
-// much lighter, to make sure the algorithm doesn't pick colors that are
-// nearly black just because of high saturation (in HSL terms)
-add_task(function* test_saturationDependence() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "hsl(0, 100%, 5%)";
- ctx.fillRect(0, 0, 16, 16);
- ctx.fillStyle = "hsl(0, 90%, 35%)";
- ctx.fillRect(0, 0, 8, 16);
- }, 0xA90808, "saturationDependence analysis returns lighter red");
-});
-
-// make sure the preference for interesting colors won't stupidly pick 1 pixel
-// of red over 169 black pixels
-add_task(function* test_interestingColorPreferenceLenient() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "black";
- ctx.fillRect(1, 1, 13, 13);
- ctx.fillStyle = "red";
- ctx.fillRect(3, 3, 1, 1);
- }, 0x000000, "interestingColorPreferenceLenient analysis returns black");
-});
-
-// ...but 6 pixels of red is more reasonable
-add_task(function* test_interestingColorPreferenceNotTooLenient() {
- yield canvasTest(16, 16, function(ctx) {
- ctx.fillStyle = "black";
- ctx.fillRect(1, 1, 13, 13);
- ctx.fillStyle = "red";
- ctx.fillRect(3, 3, 3, 2);
- }, 0xFF0000, "interestingColorPreferenceNotTooLenient analysis returns red");
-});
-
-var maxPixels = 144; // see ColorAnalyzer MAXIMUM_PIXELS const
-
-// make sure that images larger than maxPixels*maxPixels fail
-add_task(function* test_imageTooLarge() {
- yield canvasTest(1+maxPixels, 1+maxPixels, function(ctx) {
- ctx.fillStyle = "red";
- ctx.fillRect(0, 0, 1+maxPixels, 1+maxPixels);
- }, null, "imageTooLarge analysis fails");
-});
-
-// the rest of the tests are for coverage of "real" favicons
-// exact color isn't terribly important, just make sure it's reasonable
-const filePrefix = getRootDirectory(gTestPath) + "colorAnalyzer/";
-
-add_task(function* test_categoryDiscover() {
- yield frcTest(filePrefix + "category-discover.png", 0xB28D3A,
- "category-discover analysis returns red");
-});
-
-add_task(function* test_localeGeneric() {
- yield frcTest(filePrefix + "localeGeneric.png", 0x3EC23E,
- "localeGeneric analysis returns green");
-});
-
-add_task(function* test_dictionaryGeneric() {
- yield frcTest(filePrefix + "dictionaryGeneric-16.png", 0x854C30,
- "dictionaryGeneric-16 analysis returns brown");
-});
-
-add_task(function* test_extensionGeneric() {
- yield frcTest(filePrefix + "extensionGeneric-16.png", 0x53BA3F,
- "extensionGeneric-16 analysis returns green");
-});
diff --git a/toolkit/components/places/tests/browser/browser_double_redirect.js b/toolkit/components/places/tests/browser/browser_double_redirect.js
deleted file mode 100644
index 1e5dc9c16..000000000
--- a/toolkit/components/places/tests/browser/browser_double_redirect.js
+++ /dev/null
@@ -1,63 +0,0 @@
-// Test for bug 411966.
-// When a page redirects multiple times, from_visit should point to the
-// previous visit in the chain, not to the first visit in the chain.
-
-add_task(function* () {
- yield PlacesTestUtils.clearHistory();
-
- const BASE_URL = "http://example.com/tests/toolkit/components/places/tests/browser/";
- const TEST_URI = NetUtil.newURI(BASE_URL + "begin.html");
- const FIRST_REDIRECTING_URI = NetUtil.newURI(BASE_URL + "redirect_twice.sjs");
- const FINAL_URI = NetUtil.newURI(BASE_URL + "final.html");
-
- let promiseVisits = new Promise(resolve => {
- PlacesUtils.history.addObserver({
- __proto__: NavHistoryObserver.prototype,
- _notified: [],
- onVisit: function (uri, id, time, sessionId, referrerId, transition) {
- info("Received onVisit: " + uri.spec);
- this._notified.push(uri);
-
- if (!uri.equals(FINAL_URI)) {
- return;
- }
-
- is(this._notified.length, 4);
- PlacesUtils.history.removeObserver(this);
-
- Task.spawn(function* () {
- // Get all pages visited from the original typed one
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(
- `SELECT url FROM moz_historyvisits
- JOIN moz_places h ON h.id = place_id
- WHERE from_visit IN
- (SELECT v.id FROM moz_historyvisits v
- JOIN moz_places p ON p.id = v.place_id
- WHERE p.url_hash = hash(:url) AND p.url = :url)
- `, { url: TEST_URI.spec });
-
- is(rows.length, 1, "Found right number of visits");
- let visitedUrl = rows[0].getResultByName("url");
- // Check that redirect from_visit is not from the original typed one
- is(visitedUrl, FIRST_REDIRECTING_URI.spec, "Check referrer for " + visitedUrl);
-
- resolve();
- });
- }
- }, false);
- });
-
- PlacesUtils.history.markPageAsTyped(TEST_URI);
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: TEST_URI.spec,
- }, function* (browser) {
- // Load begin page, click link on page to record visits.
- yield BrowserTestUtils.synthesizeMouseAtCenter("#clickme", {}, browser);
-
- yield promiseVisits;
- });
-
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/browser/browser_favicon_privatebrowsing_perwindowpb.js b/toolkit/components/places/tests/browser/browser_favicon_privatebrowsing_perwindowpb.js
deleted file mode 100644
index 51d82adc6..000000000
--- a/toolkit/components/places/tests/browser/browser_favicon_privatebrowsing_perwindowpb.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
- waitForExplicitFinish();
-
- const pageURI =
- "http://example.org/tests/toolkit/components/places/tests/browser/favicon.html";
- let windowsToClose = [];
-
- registerCleanupFunction(function() {
- windowsToClose.forEach(function(aWin) {
- aWin.close();
- });
- });
-
- function testOnWindow(aIsPrivate, aCallback) {
- whenNewWindowLoaded({private: aIsPrivate}, function(aWin) {
- windowsToClose.push(aWin);
- executeSoon(() => aCallback(aWin));
- });
- }
-
- function waitForTabLoad(aWin, aCallback) {
- aWin.gBrowser.selectedBrowser.addEventListener("load", function onLoad() {
- aWin.gBrowser.selectedBrowser.removeEventListener("load", onLoad, true);
- aCallback();
- }, true);
- aWin.gBrowser.selectedBrowser.loadURI(pageURI);
- }
-
- testOnWindow(true, function(win) {
- waitForTabLoad(win, function() {
- PlacesUtils.favicons.getFaviconURLForPage(NetUtil.newURI(pageURI),
- function(uri, dataLen, data, mimeType) {
- is(uri, null, "No result should be found");
- finish();
- }
- );
- });
- });
-}
diff --git a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js b/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js
deleted file mode 100644
index 60df8ebd7..000000000
--- a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage.js
+++ /dev/null
@@ -1,152 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// This file tests the normal operation of setAndFetchFaviconForPage.
-function test() {
- // Initialization
- waitForExplicitFinish();
- let windowsToClose = [];
- let favIconLocation =
- "http://example.org/tests/toolkit/components/places/tests/browser/favicon-normal32.png";
- let favIconURI = NetUtil.newURI(favIconLocation);
- let favIconMimeType= "image/png";
- let pageURI;
- let favIconData;
-
- function testOnWindow(aOptions, aCallback) {
- whenNewWindowLoaded(aOptions, function(aWin) {
- windowsToClose.push(aWin);
- executeSoon(() => aCallback(aWin));
- });
- }
-
- // This function is called after calling finish() on the test.
- registerCleanupFunction(function() {
- windowsToClose.forEach(function(aWin) {
- aWin.close();
- });
- });
-
- function getIconFile(aCallback) {
- NetUtil.asyncFetch({
- uri: favIconLocation,
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_FAVICON
- }, function(inputStream, status) {
- if (!Components.isSuccessCode(status)) {
- ok(false, "Could not get the icon file");
- // Handle error.
- return;
- }
-
- // Check the returned size versus the expected size.
- let size = inputStream.available();
- favIconData = NetUtil.readInputStreamToString(inputStream, size);
- is(size, favIconData.length, "Check correct icon size");
- // Check that the favicon loaded correctly before starting the actual tests.
- is(favIconData.length, 344, "Check correct icon length (344)");
-
- if (aCallback) {
- aCallback();
- } else {
- finish();
- }
- });
- }
-
- function testNormal(aWindow, aCallback) {
- pageURI = NetUtil.newURI("http://example.com/normal");
- waitForFaviconChanged(pageURI, favIconURI, aWindow,
- function testNormalCallback() {
- checkFaviconDataForPage(pageURI, favIconMimeType, favIconData, aWindow,
- aCallback);
- }
- );
-
- addVisits({uri: pageURI, transition: TRANSITION_TYPED}, aWindow,
- function () {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, favIconURI,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
- }
- );
- }
-
- function testAboutURIBookmarked(aWindow, aCallback) {
- pageURI = NetUtil.newURI("about:testAboutURI_bookmarked");
- waitForFaviconChanged(pageURI, favIconURI, aWindow,
- function testAboutURIBookmarkedCallback() {
- checkFaviconDataForPage(pageURI, favIconMimeType, favIconData, aWindow,
- aCallback);
- }
- );
-
- aWindow.PlacesUtils.bookmarks.insertBookmark(
- aWindow.PlacesUtils.unfiledBookmarksFolderId, pageURI,
- aWindow.PlacesUtils.bookmarks.DEFAULT_INDEX, pageURI.spec);
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, favIconURI,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
- }
-
- function testPrivateBrowsingBookmarked(aWindow, aCallback) {
- pageURI = NetUtil.newURI("http://example.com/privateBrowsing_bookmarked");
- waitForFaviconChanged(pageURI, favIconURI, aWindow,
- function testPrivateBrowsingBookmarkedCallback() {
- checkFaviconDataForPage(pageURI, favIconMimeType, favIconData, aWindow,
- aCallback);
- }
- );
-
- aWindow.PlacesUtils.bookmarks.insertBookmark(
- aWindow.PlacesUtils.unfiledBookmarksFolderId, pageURI,
- aWindow.PlacesUtils.bookmarks.DEFAULT_INDEX, pageURI.spec);
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, favIconURI,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
- }
-
- function testDisabledHistoryBookmarked(aWindow, aCallback) {
- pageURI = NetUtil.newURI("http://example.com/disabledHistory_bookmarked");
- waitForFaviconChanged(pageURI, favIconURI, aWindow,
- function testDisabledHistoryBookmarkedCallback() {
- checkFaviconDataForPage(pageURI, favIconMimeType, favIconData, aWindow,
- aCallback);
- }
- );
-
- // Disable history while changing the favicon.
- aWindow.Services.prefs.setBoolPref("places.history.enabled", false);
-
- aWindow.PlacesUtils.bookmarks.insertBookmark(
- aWindow.PlacesUtils.unfiledBookmarksFolderId, pageURI,
- aWindow.PlacesUtils.bookmarks.DEFAULT_INDEX, pageURI.spec);
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, favIconURI,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- // The setAndFetchFaviconForPage function calls CanAddURI synchronously, thus
- // we can set the preference back to true immediately. We don't clear the
- // preference because not all products enable Places by default.
- aWindow.Services.prefs.setBoolPref("places.history.enabled", true);
- }
-
- getIconFile(function () {
- testOnWindow({}, function(aWin) {
- testNormal(aWin, function () {
- testOnWindow({}, function(aWin2) {
- testAboutURIBookmarked(aWin2, function () {
- testOnWindow({private: true}, function(aWin3) {
- testPrivateBrowsingBookmarked(aWin3, function () {
- testOnWindow({}, function(aWin4) {
- testDisabledHistoryBookmarked(aWin4, finish);
- });
- });
- });
- });
- });
- });
- });
- });
-}
diff --git a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js b/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js
deleted file mode 100644
index bd73af441..000000000
--- a/toolkit/components/places/tests/browser/browser_favicon_setAndFetchFaviconForPage_failures.js
+++ /dev/null
@@ -1,261 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * This file tests setAndFetchFaviconForPage when it is called with invalid
- * arguments, and when no favicon is stored for the given arguments.
- */
-function test() {
- // Initialization
- waitForExplicitFinish();
- let windowsToClose = [];
- let favIcon16Location =
- "http://example.org/tests/toolkit/components/places/tests/browser/favicon-normal16.png";
- let favIcon32Location =
- "http://example.org/tests/toolkit/components/places/tests/browser/favicon-normal32.png";
- let favIcon16URI = NetUtil.newURI(favIcon16Location);
- let favIcon32URI = NetUtil.newURI(favIcon32Location);
- let lastPageURI = NetUtil.newURI("http://example.com/verification");
- // This error icon must stay in sync with FAVICON_ERRORPAGE_URL in
- // nsIFaviconService.idl, aboutCertError.xhtml and netError.xhtml.
- let favIconErrorPageURI =
- NetUtil.newURI("chrome://global/skin/icons/warning-16.png");
- let favIconsResultCount = 0;
-
- function testOnWindow(aOptions, aCallback) {
- whenNewWindowLoaded(aOptions, function(aWin) {
- windowsToClose.push(aWin);
- executeSoon(() => aCallback(aWin));
- });
- }
-
- // This function is called after calling finish() on the test.
- registerCleanupFunction(function() {
- windowsToClose.forEach(function(aWin) {
- aWin.close();
- });
- });
-
- function checkFavIconsDBCount(aCallback) {
- let stmt = DBConn().createAsyncStatement("SELECT url FROM moz_favicons");
- stmt.executeAsync({
- handleResult: function final_handleResult(aResultSet) {
- while (aResultSet.getNextRow()) {
- favIconsResultCount++;
- }
- },
- handleError: function final_handleError(aError) {
- throw ("Unexpected error (" + aError.result + "): " + aError.message);
- },
- handleCompletion: function final_handleCompletion(aReason) {
- // begin testing
- info("Previous records in moz_favicons: " + favIconsResultCount);
- if (aCallback) {
- aCallback();
- }
- }
- });
- stmt.finalize();
- }
-
- function testNullPageURI(aWindow, aCallback) {
- try {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(null, favIcon16URI,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
- throw ("Exception expected because aPageURI is null.");
- } catch (ex) {
- // We expected an exception.
- ok(true, "Exception expected because aPageURI is null");
- }
-
- if (aCallback) {
- aCallback();
- }
- }
-
- function testNullFavIconURI(aWindow, aCallback) {
- try {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(
- NetUtil.newURI("http://example.com/null_faviconURI"), null,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null, Services.scriptSecurityManager.getSystemPrincipal());
- throw ("Exception expected because aFaviconURI is null.");
- } catch (ex) {
- // We expected an exception.
- ok(true, "Exception expected because aFaviconURI is null.");
- }
-
- if (aCallback) {
- aCallback();
- }
- }
-
- function testAboutURI(aWindow, aCallback) {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(
- NetUtil.newURI("about:testAboutURI"), favIcon16URI,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null, Services.scriptSecurityManager.getSystemPrincipal());
-
- if (aCallback) {
- aCallback();
- }
- }
-
- function testPrivateBrowsingNonBookmarkedURI(aWindow, aCallback) {
- let pageURI = NetUtil.newURI("http://example.com/privateBrowsing");
- addVisits({ uri: pageURI, transitionType: TRANSITION_TYPED }, aWindow,
- function () {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI,
- favIcon16URI, true,
- aWindow.PlacesUtils.favicons.FAVICON_LOAD_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- if (aCallback) {
- aCallback();
- }
- });
- }
-
- function testDisabledHistory(aWindow, aCallback) {
- let pageURI = NetUtil.newURI("http://example.com/disabledHistory");
- addVisits({ uri: pageURI, transition: TRANSITION_TYPED }, aWindow,
- function () {
- aWindow.Services.prefs.setBoolPref("places.history.enabled", false);
-
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI,
- favIcon16URI, true,
- aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- // The setAndFetchFaviconForPage function calls CanAddURI synchronously, thus
- // we can set the preference back to true immediately . We don't clear the
- // preference because not all products enable Places by default.
- aWindow.Services.prefs.setBoolPref("places.history.enabled", true);
-
- if (aCallback) {
- aCallback();
- }
- });
- }
-
- function testErrorIcon(aWindow, aCallback) {
- let pageURI = NetUtil.newURI("http://example.com/errorIcon");
- addVisits({ uri: pageURI, transition: TRANSITION_TYPED }, aWindow,
- function () {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI,
- favIconErrorPageURI, true,
- aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- if (aCallback) {
- aCallback();
- }
- });
- }
-
- function testNonExistingPage(aWindow, aCallback) {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(
- NetUtil.newURI("http://example.com/nonexistingPage"), favIcon16URI,
- true, aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- if (aCallback) {
- aCallback();
- }
- }
-
- function testFinalVerification(aWindow, aCallback) {
- // Only the last test should raise the onPageChanged notification,
- // executing the waitForFaviconChanged callback.
- waitForFaviconChanged(lastPageURI, favIcon32URI, aWindow,
- function final_callback() {
- // Check that only one record corresponding to the last favicon is present.
- let resultCount = 0;
- let stmt = DBConn().createAsyncStatement("SELECT url FROM moz_favicons");
- stmt.executeAsync({
- handleResult: function final_handleResult(aResultSet) {
-
- // If the moz_favicons DB had been previously loaded (before our
- // test began), we should focus only in the URI we are testing and
- // skip the URIs not related to our test.
- if (favIconsResultCount > 0) {
- for (let row; (row = aResultSet.getNextRow()); ) {
- if (favIcon32URI.spec === row.getResultByIndex(0)) {
- is(favIcon32URI.spec, row.getResultByIndex(0),
- "Check equal favicons");
- resultCount++;
- }
- }
- } else {
- for (let row; (row = aResultSet.getNextRow()); ) {
- is(favIcon32URI.spec, row.getResultByIndex(0),
- "Check equal favicons");
- resultCount++;
- }
- }
- },
- handleError: function final_handleError(aError) {
- throw ("Unexpected error (" + aError.result + "): " + aError.message);
- },
- handleCompletion: function final_handleCompletion(aReason) {
- is(Ci.mozIStorageStatementCallback.REASON_FINISHED, aReason,
- "Check reasons are equal");
- is(1, resultCount, "Check result count");
- if (aCallback) {
- aCallback();
- }
- }
- });
- stmt.finalize();
- });
-
- // This is the only test that should cause the waitForFaviconChanged
- // callback to be invoked. In turn, the callback will invoke
- // finish() causing the tests to finish.
- addVisits({ uri: lastPageURI, transition: TRANSITION_TYPED }, aWindow,
- function () {
- aWindow.PlacesUtils.favicons.setAndFetchFaviconForPage(lastPageURI,
- favIcon32URI, true,
- aWindow.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null,
- Services.scriptSecurityManager.getSystemPrincipal());
- });
- }
-
- checkFavIconsDBCount(function () {
- testOnWindow({}, function(aWin) {
- testNullPageURI(aWin, function () {
- testOnWindow({}, function(aWin2) {
- testNullFavIconURI(aWin2, function() {
- testOnWindow({}, function(aWin3) {
- testAboutURI(aWin3, function() {
- testOnWindow({private: true}, function(aWin4) {
- testPrivateBrowsingNonBookmarkedURI(aWin4, function () {
- testOnWindow({}, function(aWin5) {
- testDisabledHistory(aWin5, function () {
- testOnWindow({}, function(aWin6) {
- testErrorIcon(aWin6, function() {
- testOnWindow({}, function(aWin7) {
- testNonExistingPage(aWin7, function() {
- testOnWindow({}, function(aWin8) {
- testFinalVerification(aWin8, function() {
- finish();
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
- });
-}
diff --git a/toolkit/components/places/tests/browser/browser_history_post.js b/toolkit/components/places/tests/browser/browser_history_post.js
deleted file mode 100644
index c85e720f8..000000000
--- a/toolkit/components/places/tests/browser/browser_history_post.js
+++ /dev/null
@@ -1,23 +0,0 @@
-const PAGE_URI = "http://example.com/tests/toolkit/components/places/tests/browser/history_post.html";
-const SJS_URI = NetUtil.newURI("http://example.com/tests/toolkit/components/places/tests/browser/history_post.sjs");
-
-add_task(function* () {
- yield BrowserTestUtils.withNewTab({gBrowser, url: PAGE_URI}, Task.async(function* (aBrowser) {
- yield ContentTask.spawn(aBrowser, null, function* () {
- let doc = content.document;
- let submit = doc.getElementById("submit");
- let iframe = doc.getElementById("post_iframe");
- let p = new Promise((resolve, reject) => {
- iframe.addEventListener("load", function onLoad() {
- iframe.removeEventListener("load", onLoad);
- resolve();
- });
- });
- submit.click();
- yield p;
- });
- let visited = yield promiseIsURIVisited(SJS_URI);
- ok(!visited, "The POST page should not be added to history");
- ok(!(yield PlacesTestUtils.isPageInDB(SJS_URI.spec)), "The page should not be in the database");
- }));
-});
diff --git a/toolkit/components/places/tests/browser/browser_notfound.js b/toolkit/components/places/tests/browser/browser_notfound.js
deleted file mode 100644
index 20467eef4..000000000
--- a/toolkit/components/places/tests/browser/browser_notfound.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/. */
-
-add_task(function* () {
- const TEST_URL = "http://mochi.test:8888/notFoundPage.html";
-
- // Used to verify errors are not marked as typed.
- PlacesUtils.history.markPageAsTyped(NetUtil.newURI(TEST_URL));
-
- // Create and add history observer.
- let visitedPromise = new Promise(resolve => {
- let historyObserver = {
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType) {
- PlacesUtils.history.removeObserver(historyObserver);
- info("Received onVisit: " + aURI.spec);
- fieldForUrl(aURI, "frecency", function (aFrecency) {
- is(aFrecency, 0, "Frecency should be 0");
- fieldForUrl(aURI, "hidden", function (aHidden) {
- is(aHidden, 0, "Page should not be hidden");
- fieldForUrl(aURI, "typed", function (aTyped) {
- is(aTyped, 0, "page should not be marked as typed");
- resolve();
- });
- });
- });
- },
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
- };
- PlacesUtils.history.addObserver(historyObserver, false);
- });
-
- let newTabPromise = BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
- yield Promise.all([visitedPromise, newTabPromise]);
-
- yield PlacesTestUtils.clearHistory();
- gBrowser.removeCurrentTab();
-});
diff --git a/toolkit/components/places/tests/browser/browser_redirect.js b/toolkit/components/places/tests/browser/browser_redirect.js
deleted file mode 100644
index d8a19731a..000000000
--- a/toolkit/components/places/tests/browser/browser_redirect.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* () {
- const REDIRECT_URI = NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/browser/redirect.sjs");
- const TARGET_URI = NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/browser/redirect-target.html");
-
- // Create and add history observer.
- let visitedPromise = new Promise(resolve => {
- let historyObserver = {
- _redirectNotified: false,
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType) {
- info("Received onVisit: " + aURI.spec);
-
- if (aURI.equals(REDIRECT_URI)) {
- this._redirectNotified = true;
- // Wait for the target page notification.
- return;
- }
-
- PlacesUtils.history.removeObserver(historyObserver);
-
- ok(this._redirectNotified, "The redirect should have been notified");
-
- fieldForUrl(REDIRECT_URI, "frecency", function (aFrecency) {
- ok(aFrecency != 0, "Frecency or the redirecting page should not be 0");
-
- fieldForUrl(REDIRECT_URI, "hidden", function (aHidden) {
- is(aHidden, 1, "The redirecting page should be hidden");
-
- fieldForUrl(TARGET_URI, "frecency", function (aFrecency2) {
- ok(aFrecency2 != 0, "Frecency of the target page should not be 0");
-
- fieldForUrl(TARGET_URI, "hidden", function (aHidden2) {
- is(aHidden2, 0, "The target page should not be hidden");
- resolve();
- });
- });
- });
- });
- },
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
- };
- PlacesUtils.history.addObserver(historyObserver, false);
- });
-
- let newTabPromise = BrowserTestUtils.openNewForegroundTab(gBrowser, REDIRECT_URI.spec);
- yield Promise.all([visitedPromise, newTabPromise]);
-
- yield PlacesTestUtils.clearHistory();
- gBrowser.removeCurrentTab();
-});
diff --git a/toolkit/components/places/tests/browser/browser_settitle.js b/toolkit/components/places/tests/browser/browser_settitle.js
deleted file mode 100644
index 68c8deda7..000000000
--- a/toolkit/components/places/tests/browser/browser_settitle.js
+++ /dev/null
@@ -1,76 +0,0 @@
-var conn = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
-
-/**
- * Gets a single column value from either the places or historyvisits table.
- */
-function getColumn(table, column, url)
-{
- var stmt = conn.createStatement(
- `SELECT ${column} FROM ${table} WHERE url_hash = hash(:val) AND url = :val`);
- try {
- stmt.params.val = url;
- stmt.executeStep();
- return stmt.row[column];
- }
- finally {
- stmt.finalize();
- }
-}
-
-add_task(function* ()
-{
- // Make sure titles are correctly saved for a URI with the proper
- // notifications.
-
- // Create and add history observer.
- let titleChangedPromise = new Promise(resolve => {
- var historyObserver = {
- data: [],
- onBeginUpdateBatch: function() {},
- onEndUpdateBatch: function() {},
- onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType) {
- },
- onTitleChanged: function(aURI, aPageTitle, aGUID) {
- this.data.push({ uri: aURI, title: aPageTitle, guid: aGUID });
-
- // We only expect one title change.
- //
- // Although we are loading two different pages, the first page does not
- // have a title. Since the title starts out as empty and then is set
- // to empty, there is no title change notification.
-
- PlacesUtils.history.removeObserver(this);
- resolve(this.data);
- },
- onDeleteURI: function() {},
- onClearHistory: function() {},
- onPageChanged: function() {},
- onDeleteVisits: function() {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
- };
- PlacesUtils.history.addObserver(historyObserver, false);
- });
-
- const url1 = "http://example.com/tests/toolkit/components/places/tests/browser/title1.html";
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, url1);
-
- const url2 = "http://example.com/tests/toolkit/components/places/tests/browser/title2.html";
- let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- BrowserTestUtils.loadURI(gBrowser.selectedBrowser, url2);
- yield loadPromise;
-
- let data = yield titleChangedPromise;
- is(data[0].uri.spec, "http://example.com/tests/toolkit/components/places/tests/browser/title2.html");
- is(data[0].title, "Some title");
- is(data[0].guid, getColumn("moz_places", "guid", data[0].uri.spec));
-
- data.forEach(function(item) {
- var title = getColumn("moz_places", "title", data[0].uri.spec);
- is(title, item.title);
- });
-
- gBrowser.removeCurrentTab();
- yield PlacesTestUtils.clearHistory();
-});
-
diff --git a/toolkit/components/places/tests/browser/browser_visited_notfound.js b/toolkit/components/places/tests/browser/browser_visited_notfound.js
deleted file mode 100644
index b2b4f25b8..000000000
--- a/toolkit/components/places/tests/browser/browser_visited_notfound.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const TEST_URI = NetUtil.newURI("http://mochi.test:8888/notFoundPage.html");
-
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab();
- registerCleanupFunction(function() {
- gBrowser.removeCurrentTab();
- });
-
- // First add a visit to the page, this will ensure that later we skip
- // updating the frecency for a newly not-found page.
- addVisits({ uri: TEST_URI }, window, () => {
- info("Added visit");
- fieldForUrl(TEST_URI, "frecency", aFrecency => {
- ok(aFrecency > 0, "Frecency should be > 0");
- continueTest(aFrecency);
- });
- });
-}
-
-function continueTest(aOldFrecency) {
- // Used to verify errors are not marked as typed.
- PlacesUtils.history.markPageAsTyped(TEST_URI);
- gBrowser.selectedBrowser.loadURI(TEST_URI.spec);
-
- // Create and add history observer.
- let historyObserver = {
- __proto__: NavHistoryObserver.prototype,
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType) {
- PlacesUtils.history.removeObserver(historyObserver);
- info("Received onVisit: " + aURI.spec);
- fieldForUrl(aURI, "frecency", function (aFrecency) {
- is(aFrecency, aOldFrecency, "Frecency should be unchanged");
- fieldForUrl(aURI, "hidden", function (aHidden) {
- is(aHidden, 0, "Page should not be hidden");
- fieldForUrl(aURI, "typed", function (aTyped) {
- is(aTyped, 0, "page should not be marked as typed");
- PlacesTestUtils.clearHistory().then(finish);
- });
- });
- });
- }
- };
- PlacesUtils.history.addObserver(historyObserver, false);
-}
diff --git a/toolkit/components/places/tests/browser/browser_visituri.js b/toolkit/components/places/tests/browser/browser_visituri.js
deleted file mode 100644
index 8ba2b7272..000000000
--- a/toolkit/components/places/tests/browser/browser_visituri.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * One-time observer callback.
- */
-function promiseObserve(name, checkFn) {
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(subject) {
- if (checkFn(subject)) {
- Services.obs.removeObserver(observer, name);
- resolve();
- }
- }, name, false);
- });
-}
-
-var conn = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
-
-/**
- * Gets a single column value from either the places or historyvisits table.
- */
-function getColumn(table, column, fromColumnName, fromColumnValue) {
- let sql = `SELECT ${column}
- FROM ${table}
- WHERE ${fromColumnName} = :val
- ${fromColumnName == "url" ? "AND url_hash = hash(:val)" : ""}
- LIMIT 1`;
- let stmt = conn.createStatement(sql);
- try {
- stmt.params.val = fromColumnValue;
- ok(stmt.executeStep(), "Expect to get a row");
- return stmt.row[column];
- }
- finally {
- stmt.reset();
- }
-}
-
-add_task(function* () {
- // Make sure places visit chains are saved correctly with a redirect
- // transitions.
-
- // Part 1: observe history events that fire when a visit occurs.
- // Make sure visits appear in order, and that the visit chain is correct.
- var expectedUrls = [
- "http://example.com/tests/toolkit/components/places/tests/browser/begin.html",
- "http://example.com/tests/toolkit/components/places/tests/browser/redirect_twice.sjs",
- "http://example.com/tests/toolkit/components/places/tests/browser/redirect_once.sjs",
- "http://example.com/tests/toolkit/components/places/tests/browser/final.html"
- ];
- var currentIndex = 0;
-
- function checkObserver(subject) {
- var uri = subject.QueryInterface(Ci.nsIURI);
- var expected = expectedUrls[currentIndex];
- is(uri.spec, expected, "Saved URL visit " + uri.spec);
-
- var placeId = getColumn("moz_places", "id", "url", uri.spec);
- var fromVisitId = getColumn("moz_historyvisits", "from_visit", "place_id", placeId);
-
- if (currentIndex == 0) {
- is(fromVisitId, 0, "First visit has no from visit");
- }
- else {
- var lastVisitId = getColumn("moz_historyvisits", "place_id", "id", fromVisitId);
- var fromVisitUrl = getColumn("moz_places", "url", "id", lastVisitId);
- is(fromVisitUrl, expectedUrls[currentIndex - 1],
- "From visit was " + expectedUrls[currentIndex - 1]);
- }
-
- currentIndex++;
- return (currentIndex >= expectedUrls.length);
- }
- let visitUriPromise = promiseObserve("uri-visit-saved", checkObserver);
-
- const testUrl = "http://example.com/tests/toolkit/components/places/tests/browser/begin.html";
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, testUrl);
-
- // Load begin page, click link on page to record visits.
- yield BrowserTestUtils.synthesizeMouseAtCenter("#clickme", { }, gBrowser.selectedBrowser);
- yield visitUriPromise;
-
- yield PlacesTestUtils.clearHistory();
-
- gBrowser.removeCurrentTab();
-});
diff --git a/toolkit/components/places/tests/browser/browser_visituri_nohistory.js b/toolkit/components/places/tests/browser/browser_visituri_nohistory.js
deleted file mode 100644
index a3a8e7626..000000000
--- a/toolkit/components/places/tests/browser/browser_visituri_nohistory.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const INITIAL_URL = "http://example.com/tests/toolkit/components/places/tests/browser/begin.html";
-const FINAL_URL = "http://example.com/tests/toolkit/components/places/tests/browser/final.html";
-
-/**
- * One-time observer callback.
- */
-function promiseObserve(name)
-{
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(subject) {
- Services.obs.removeObserver(observer, name);
- resolve(subject);
- }, name, false);
- });
-}
-
-add_task(function* ()
-{
- yield new Promise(resolve => SpecialPowers.pushPrefEnv({"set": [["places.history.enabled", false]]}, resolve));
-
- let visitUriPromise = promiseObserve("uri-visit-saved");
-
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, INITIAL_URL);
-
- yield new Promise(resolve => SpecialPowers.popPrefEnv(resolve));
-
- let browserLoadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
- gBrowser.loadURI(FINAL_URL);
- yield browserLoadedPromise;
-
- let subject = yield visitUriPromise;
- let uri = subject.QueryInterface(Ci.nsIURI);
- is(uri.spec, FINAL_URL, "received expected visit");
-
- yield PlacesTestUtils.clearHistory();
- gBrowser.removeCurrentTab();
-});
diff --git a/toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js b/toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js
deleted file mode 100644
index abde69a7d..000000000
--- a/toolkit/components/places/tests/browser/browser_visituri_privatebrowsing_perwindowpb.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function test() {
- // initialization
- waitForExplicitFinish();
- let windowsToClose = [];
- let initialURL =
- "http://example.com/tests/toolkit/components/places/tests/browser/begin.html";
- let finalURL =
- "http://example.com/tests/toolkit/components/places/tests/browser/final.html";
- let observer = null;
- let enumerator = null;
- let currentObserver = null;
- let uri = null;
-
- function doTest(aIsPrivateMode, aWindow, aTestURI, aCallback) {
- observer = {
- observe: function(aSubject, aTopic, aData) {
- // The uri-visit-saved topic should only work when on normal mode.
- if (aTopic == "uri-visit-saved") {
- // Remove the observers set on per window private mode and normal
- // mode.
- enumerator = aWindow.Services.obs.enumerateObservers("uri-visit-saved");
- while (enumerator.hasMoreElements()) {
- currentObserver = enumerator.getNext();
- aWindow.Services.obs.removeObserver(currentObserver, "uri-visit-saved");
- }
-
- // The expected visit should be the finalURL because private mode
- // should not register a visit with the initialURL.
- uri = aSubject.QueryInterface(Ci.nsIURI);
- is(uri.spec, finalURL, "Check received expected visit");
- }
- }
- };
-
- aWindow.Services.obs.addObserver(observer, "uri-visit-saved", false);
-
- BrowserTestUtils.browserLoaded(aWindow.gBrowser.selectedBrowser).then(aCallback);
- aWindow.gBrowser.selectedBrowser.loadURI(aTestURI);
- }
-
- function testOnWindow(aOptions, aCallback) {
- whenNewWindowLoaded(aOptions, function(aWin) {
- windowsToClose.push(aWin);
- // execute should only be called when need, like when you are opening
- // web pages on the test. If calling executeSoon() is not necesary, then
- // call whenNewWindowLoaded() instead of testOnWindow() on your test.
- executeSoon(() => aCallback(aWin));
- });
- }
-
- // This function is called after calling finish() on the test.
- registerCleanupFunction(function() {
- windowsToClose.forEach(function(aWin) {
- aWin.close();
- });
- });
-
- // test first when on private mode
- testOnWindow({private: true}, function(aWin) {
- doTest(true, aWin, initialURL, function() {
- // then test when not on private mode
- testOnWindow({}, function(aWin2) {
- doTest(false, aWin2, finalURL, function () {
- PlacesTestUtils.clearHistory().then(finish);
- });
- });
- });
- });
-}
diff --git a/toolkit/components/places/tests/browser/colorAnalyzer/category-discover.png b/toolkit/components/places/tests/browser/colorAnalyzer/category-discover.png
deleted file mode 100644
index a6f5b49b3..000000000
--- a/toolkit/components/places/tests/browser/colorAnalyzer/category-discover.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/browser/colorAnalyzer/dictionaryGeneric-16.png b/toolkit/components/places/tests/browser/colorAnalyzer/dictionaryGeneric-16.png
deleted file mode 100644
index 4ad1a1a82..000000000
--- a/toolkit/components/places/tests/browser/colorAnalyzer/dictionaryGeneric-16.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/browser/colorAnalyzer/extensionGeneric-16.png b/toolkit/components/places/tests/browser/colorAnalyzer/extensionGeneric-16.png
deleted file mode 100644
index fc6c8a258..000000000
--- a/toolkit/components/places/tests/browser/colorAnalyzer/extensionGeneric-16.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/browser/colorAnalyzer/localeGeneric.png b/toolkit/components/places/tests/browser/colorAnalyzer/localeGeneric.png
deleted file mode 100644
index 4d9ac5ad8..000000000
--- a/toolkit/components/places/tests/browser/colorAnalyzer/localeGeneric.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/browser/favicon-normal16.png b/toolkit/components/places/tests/browser/favicon-normal16.png
deleted file mode 100644
index 62b69a3d0..000000000
--- a/toolkit/components/places/tests/browser/favicon-normal16.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/browser/favicon-normal32.png b/toolkit/components/places/tests/browser/favicon-normal32.png
deleted file mode 100644
index 5535363c9..000000000
--- a/toolkit/components/places/tests/browser/favicon-normal32.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/browser/favicon.html b/toolkit/components/places/tests/browser/favicon.html
deleted file mode 100644
index a0f5ea959..000000000
--- a/toolkit/components/places/tests/browser/favicon.html
+++ /dev/null
@@ -1,13 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-
-<html>
- <head>
- <link rel="shortcut icon" href="http://example.org/tests/toolkit/components/places/tests/browser/favicon-normal32.png">
- </head>
- <body>
- OK we're done!
- </body>
-</html>
diff --git a/toolkit/components/places/tests/browser/final.html b/toolkit/components/places/tests/browser/final.html
deleted file mode 100644
index ccd581918..000000000
--- a/toolkit/components/places/tests/browser/final.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-
-<html>
- <body>
- OK we're done!
- </body>
-</html>
diff --git a/toolkit/components/places/tests/browser/head.js b/toolkit/components/places/tests/browser/head.js
deleted file mode 100644
index 897585a81..000000000
--- a/toolkit/components/places/tests/browser/head.js
+++ /dev/null
@@ -1,319 +0,0 @@
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "BrowserTestUtils",
- "resource://testing-common/BrowserTestUtils.jsm");
-
-const TRANSITION_LINK = PlacesUtils.history.TRANSITION_LINK;
-const TRANSITION_TYPED = PlacesUtils.history.TRANSITION_TYPED;
-const TRANSITION_BOOKMARK = PlacesUtils.history.TRANSITION_BOOKMARK;
-const TRANSITION_REDIRECT_PERMANENT = PlacesUtils.history.TRANSITION_REDIRECT_PERMANENT;
-const TRANSITION_REDIRECT_TEMPORARY = PlacesUtils.history.TRANSITION_REDIRECT_TEMPORARY;
-const TRANSITION_EMBED = PlacesUtils.history.TRANSITION_EMBED;
-const TRANSITION_FRAMED_LINK = PlacesUtils.history.TRANSITION_FRAMED_LINK;
-const TRANSITION_DOWNLOAD = PlacesUtils.history.TRANSITION_DOWNLOAD;
-
-/**
- * Returns a moz_places field value for a url.
- *
- * @param aURI
- * The URI or spec to get field for.
- * param aCallback
- * Callback function that will get the property value.
- */
-function fieldForUrl(aURI, aFieldName, aCallback)
-{
- let url = aURI instanceof Ci.nsIURI ? aURI.spec : aURI;
- let stmt = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .DBConnection.createAsyncStatement(
- `SELECT ${aFieldName} FROM moz_places WHERE url_hash = hash(:page_url) AND url = :page_url`
- );
- stmt.params.page_url = url;
- stmt.executeAsync({
- _value: -1,
- handleResult: function(aResultSet) {
- let row = aResultSet.getNextRow();
- if (!row)
- ok(false, "The page should exist in the database");
- this._value = row.getResultByName(aFieldName);
- },
- handleError: function() {},
- handleCompletion: function(aReason) {
- if (aReason != Ci.mozIStorageStatementCallback.REASON_FINISHED)
- ok(false, "The statement should properly succeed");
- aCallback(this._value);
- }
- });
- stmt.finalize();
-}
-
-/**
- * Generic nsINavHistoryObserver that doesn't implement anything, but provides
- * dummy methods to prevent errors about an object not having a certain method.
- */
-function NavHistoryObserver() {}
-
-NavHistoryObserver.prototype = {
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavHistoryObserver,
- ])
-};
-
-/**
- * Waits for the first OnPageChanged notification for ATTRIBUTE_FAVICON, and
- * verifies that it matches the expected page URI and associated favicon URI.
- *
- * This function also double-checks the GUID parameter of the notification.
- *
- * @param aExpectedPageURI
- * nsIURI object of the page whose favicon should change.
- * @param aExpectedFaviconURI
- * nsIURI object of the newly associated favicon.
- * @param aCallback
- * This function is called after the check finished.
- */
-function waitForFaviconChanged(aExpectedPageURI, aExpectedFaviconURI, aWindow,
- aCallback) {
- let historyObserver = {
- __proto__: NavHistoryObserver.prototype,
- onPageChanged: function WFFC_onPageChanged(aURI, aWhat, aValue, aGUID) {
- if (aWhat != Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON) {
- return;
- }
- aWindow.PlacesUtils.history.removeObserver(this);
-
- ok(aURI.equals(aExpectedPageURI),
- "Check URIs are equal for the page which favicon changed");
- is(aValue, aExpectedFaviconURI.spec,
- "Check changed favicon URI is the expected");
- checkGuidForURI(aURI, aGUID);
-
- if (aCallback) {
- aCallback();
- }
- }
- };
- aWindow.PlacesUtils.history.addObserver(historyObserver, false);
-}
-
-/**
- * Asynchronously adds visits to a page, invoking a callback function when done.
- *
- * @param aPlaceInfo
- * Either an nsIURI, in such a case a single LINK visit will be added.
- * Or can be an object describing the visit to add, or an array
- * of these objects:
- * { uri: nsIURI of the page,
- * transition: one of the TRANSITION_* from nsINavHistoryService,
- * [optional] title: title of the page,
- * [optional] visitDate: visit date in microseconds from the epoch
- * [optional] referrer: nsIURI of the referrer for this visit
- * }
- * @param [optional] aCallback
- * Function to be invoked on completion.
- * @param [optional] aStack
- * The stack frame used to report errors.
- */
-function addVisits(aPlaceInfo, aWindow, aCallback, aStack) {
- let places = [];
- if (aPlaceInfo instanceof Ci.nsIURI) {
- places.push({ uri: aPlaceInfo });
- }
- else if (Array.isArray(aPlaceInfo)) {
- places = places.concat(aPlaceInfo);
- } else {
- places.push(aPlaceInfo)
- }
-
- // Create mozIVisitInfo for each entry.
- let now = Date.now();
- for (let place of places) {
- if (!place.title) {
- place.title = "test visit for " + place.uri.spec;
- }
- place.visits = [{
- transitionType: place.transition === undefined ? TRANSITION_LINK
- : place.transition,
- visitDate: place.visitDate || (now++) * 1000,
- referrerURI: place.referrer
- }];
- }
-
- aWindow.PlacesUtils.asyncHistory.updatePlaces(
- places,
- {
- handleError: function AAV_handleError() {
- throw ("Unexpected error in adding visit.");
- },
- handleResult: function () {},
- handleCompletion: function UP_handleCompletion() {
- if (aCallback)
- aCallback();
- }
- }
- );
-}
-
-/**
- * Checks that the favicon for the given page matches the provided data.
- *
- * @param aPageURI
- * nsIURI object for the page to check.
- * @param aExpectedMimeType
- * Expected MIME type of the icon, for example "image/png".
- * @param aExpectedData
- * Expected icon data, expressed as an array of byte values.
- * @param aCallback
- * This function is called after the check finished.
- */
-function checkFaviconDataForPage(aPageURI, aExpectedMimeType, aExpectedData,
- aWindow, aCallback) {
- aWindow.PlacesUtils.favicons.getFaviconDataForPage(aPageURI,
- function (aURI, aDataLen, aData, aMimeType) {
- is(aExpectedMimeType, aMimeType, "Check expected MimeType");
- is(aExpectedData.length, aData.length,
- "Check favicon data for the given page matches the provided data");
- checkGuidForURI(aPageURI);
- aCallback();
- });
-}
-
-/**
- * Tests that a guid was set in moz_places for a given uri.
- *
- * @param aURI
- * The uri to check.
- * @param [optional] aGUID
- * The expected guid in the database.
- */
-function checkGuidForURI(aURI, aGUID) {
- let guid = doGetGuidForURI(aURI);
- if (aGUID) {
- doCheckValidPlacesGuid(aGUID);
- is(guid, aGUID, "Check equal guid for URIs");
- }
-}
-
-/**
- * Retrieves the guid for a given uri.
- *
- * @param aURI
- * The uri to check.
- * @return the associated the guid.
- */
-function doGetGuidForURI(aURI) {
- let stmt = DBConn().createStatement(
- `SELECT guid
- FROM moz_places
- WHERE url_hash = hash(:url) AND url = :url`
- );
- stmt.params.url = aURI.spec;
- ok(stmt.executeStep(), "Check get guid for uri from moz_places");
- let guid = stmt.row.guid;
- stmt.finalize();
- doCheckValidPlacesGuid(guid);
- return guid;
-}
-
-/**
- * Tests if a given guid is valid for use in Places or not.
- *
- * @param aGuid
- * The guid to test.
- */
-function doCheckValidPlacesGuid(aGuid) {
- ok(/^[a-zA-Z0-9\-_]{12}$/.test(aGuid), "Check guid for valid places");
-}
-
-/**
- * Gets the database connection. If the Places connection is invalid it will
- * try to create a new connection.
- *
- * @param [optional] aForceNewConnection
- * Forces creation of a new connection to the database. When a
- * connection is asyncClosed it cannot anymore schedule async statements,
- * though connectionReady will keep returning true (Bug 726990).
- *
- * @return The database connection or null if unable to get one.
- */
-function DBConn(aForceNewConnection) {
- let gDBConn;
- if (!aForceNewConnection) {
- let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .DBConnection;
- if (db.connectionReady)
- return db;
- }
-
- // If the Places database connection has been closed, create a new connection.
- if (!gDBConn || aForceNewConnection) {
- let file = Services.dirsvc.get('ProfD', Ci.nsIFile);
- file.append("places.sqlite");
- let dbConn = gDBConn = Services.storage.openDatabase(file);
-
- // Be sure to cleanly close this connection.
- Services.obs.addObserver(function DBCloseCallback(aSubject, aTopic, aData) {
- Services.obs.removeObserver(DBCloseCallback, aTopic);
- dbConn.asyncClose();
- }, "profile-before-change", false);
- }
-
- return gDBConn.connectionReady ? gDBConn : null;
-}
-
-function whenNewWindowLoaded(aOptions, aCallback) {
- BrowserTestUtils.waitForNewWindow().then(aCallback);
- OpenBrowserWindow(aOptions);
-}
-
-/**
- * Asynchronously check a url is visited.
- *
- * @param aURI The URI.
- * @param aExpectedValue The expected value.
- * @return {Promise}
- * @resolves When the check has been added successfully.
- * @rejects JavaScript exception.
- */
-function promiseIsURIVisited(aURI, aExpectedValue) {
- return new Promise(resolve => {
- PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
- resolve(aIsVisited);
- });
- });
-}
-
-function waitForCondition(condition, nextTest, errorMsg) {
- let tries = 0;
- let interval = setInterval(function() {
- if (tries >= 30) {
- ok(false, errorMsg);
- moveOn();
- }
- let conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- ok(false, e + "\n" + e.stack);
- conditionPassed = false;
- }
- if (conditionPassed) {
- moveOn();
- }
- tries++;
- }, 200);
- function moveOn() {
- clearInterval(interval);
- nextTest();
- }
-}
diff --git a/toolkit/components/places/tests/browser/history_post.html b/toolkit/components/places/tests/browser/history_post.html
deleted file mode 100644
index a579a9b8a..000000000
--- a/toolkit/components/places/tests/browser/history_post.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!DOCTYPE HTML>
-<html>
- <head>
- <title>Test post pages are not added to history</title>
- </head>
- <body>
- <iframe name="post_iframe" id="post_iframe"></iframe>
- <form method="post" action="http://example.com/tests/toolkit/components/places/tests/browser/history_post.sjs" target="post_iframe">
- <input type="submit" id="submit"/>
- </form>
- </body>
-</html>
diff --git a/toolkit/components/places/tests/browser/history_post.sjs b/toolkit/components/places/tests/browser/history_post.sjs
deleted file mode 100644
index 3c86aad7b..000000000
--- a/toolkit/components/places/tests/browser/history_post.sjs
+++ /dev/null
@@ -1,6 +0,0 @@
-function handleRequest(request, response)
-{
- response.setStatusLine("1.0", 200, "OK");
- response.setHeader("Content-Type", "text/plain; charset=utf-8", false);
- response.write("Ciao");
-}
diff --git a/toolkit/components/places/tests/browser/redirect-target.html b/toolkit/components/places/tests/browser/redirect-target.html
deleted file mode 100644
index 370026338..000000000
--- a/toolkit/components/places/tests/browser/redirect-target.html
+++ /dev/null
@@ -1 +0,0 @@
-<!DOCTYPE html><html><body><p>Ciao!</p></body></html>
diff --git a/toolkit/components/places/tests/browser/redirect.sjs b/toolkit/components/places/tests/browser/redirect.sjs
deleted file mode 100644
index f55e78eb1..000000000
--- a/toolkit/components/places/tests/browser/redirect.sjs
+++ /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/. */
-
-function handleRequest(request, response)
-{
- let page = "<!DOCTYPE html><html><body><p>Redirecting...</p></body></html>";
-
- response.setStatusLine(request.httpVersion, "301", "Moved Permanently");
- response.setHeader("Content-Type", "text/html", false);
- response.setHeader("Content-Length", page.length + "", false);
- response.setHeader("Location", "redirect-target.html", false);
- response.write(page);
-}
diff --git a/toolkit/components/places/tests/browser/redirect_once.sjs b/toolkit/components/places/tests/browser/redirect_once.sjs
deleted file mode 100644
index 8b2a8aa55..000000000
--- a/toolkit/components/places/tests/browser/redirect_once.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function handleRequest(request, response) {
- response.setStatusLine("1.1", 301, "Found");
- response.setHeader("Location", "final.html", false);
-}
diff --git a/toolkit/components/places/tests/browser/redirect_twice.sjs b/toolkit/components/places/tests/browser/redirect_twice.sjs
deleted file mode 100644
index 099d20022..000000000
--- a/toolkit/components/places/tests/browser/redirect_twice.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function handleRequest(request, response) {
- response.setStatusLine("1.1", 302, "Found");
- response.setHeader("Location", "redirect_once.sjs", false);
-}
diff --git a/toolkit/components/places/tests/browser/title1.html b/toolkit/components/places/tests/browser/title1.html
deleted file mode 100644
index 3c98d693e..000000000
--- a/toolkit/components/places/tests/browser/title1.html
+++ /dev/null
@@ -1,12 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-
-<html>
- <head>
- </head>
- <body>
- title1.html
- </body>
-</html>
diff --git a/toolkit/components/places/tests/browser/title2.html b/toolkit/components/places/tests/browser/title2.html
deleted file mode 100644
index 28a6b69b5..000000000
--- a/toolkit/components/places/tests/browser/title2.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-
-<html>
- <head>
- <title>Some title</title>
- </head>
- <body>
- title2.html
- </body>
-</html>
-
diff --git a/toolkit/components/places/tests/chrome/.eslintrc.js b/toolkit/components/places/tests/chrome/.eslintrc.js
deleted file mode 100644
index bf379df8d..000000000
--- a/toolkit/components/places/tests/chrome/.eslintrc.js
+++ /dev/null
@@ -1,8 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js",
- "../../../../../testing/mochitest/mochitest.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/chrome/bad_links.atom b/toolkit/components/places/tests/chrome/bad_links.atom
deleted file mode 100644
index 446927252..000000000
--- a/toolkit/components/places/tests/chrome/bad_links.atom
+++ /dev/null
@@ -1,74 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
-
- <title>First good item</title>
- <link href="http://example.org/first"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>data: link</title>
- <link href="data:text/plain,Hi"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6b</id>
- <updated>2003-12-13T18:30:03Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>javascript: link</title>
- <link href="javascript:alert('Hi')"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6c</id>
- <updated>2003-12-13T18:30:04Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>file: link</title>
- <link href="file:///var/"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6d</id>
- <updated>2003-12-13T18:30:05Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>chrome: link</title>
- <link href="chrome://browser/content/browser.js"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6e</id>
- <updated>2003-12-13T18:30:06Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
- <entry>
-
- <title>Last good item</title>
- <link href="http://example.org/last"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6b</id>
- <updated>2003-12-13T18:30:07Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-
-</feed>
diff --git a/toolkit/components/places/tests/chrome/browser_disableglobalhistory.xul b/toolkit/components/places/tests/chrome/browser_disableglobalhistory.xul
deleted file mode 100644
index d7bbfda67..000000000
--- a/toolkit/components/places/tests/chrome/browser_disableglobalhistory.xul
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-
-<window title="Test disableglobalhistory attribute on remote browsers"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="run_test();">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
-
- <browser id="inprocess_disabled" src="about:blank" type="content" disableglobalhistory="true" />
- <browser id="inprocess_enabled" src="about:blank" type="content" />
-
- <browser id="remote_disabled" src="about:blank" type="content" disableglobalhistory="true" />
- <browser id="remote_enabled" src="about:blank" type="content" />
-
- <script type="text/javascript;version=1.7">
- const {interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components;
-
- Cu.import("resource://testing-common/ContentTask.jsm");
- ContentTask.setTestScope(window.opener.wrappedJSObject);
-
- function expectUseGlobalHistory(id, expected) {
- let browser = document.getElementById(id);
- return ContentTask.spawn(browser, {id, expected}, function*({id, expected}) {
- Assert.equal(docShell.useGlobalHistory, expected,
- "Got the right useGlobalHistory state in the docShell of " + id);
- });
- }
-
- function run_test() {
- spawn_task(function*() {
- yield expectUseGlobalHistory("inprocess_disabled", false);
- yield expectUseGlobalHistory("inprocess_enabled", true);
-
- yield expectUseGlobalHistory("remote_disabled", false);
- yield expectUseGlobalHistory("remote_enabled", true);
- window.opener.done();
- });
- };
-
- </script>
-</window> \ No newline at end of file
diff --git a/toolkit/components/places/tests/chrome/chrome.ini b/toolkit/components/places/tests/chrome/chrome.ini
deleted file mode 100644
index 5ac753e73..000000000
--- a/toolkit/components/places/tests/chrome/chrome.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-
-[test_303567.xul]
-[test_341972a.xul]
-[test_341972b.xul]
-[test_342484.xul]
-[test_371798.xul]
-[test_381357.xul]
-[test_favicon_annotations.xul]
-[test_reloadLivemarks.xul]
-[test_browser_disableglobalhistory.xul]
-support-files = browser_disableglobalhistory.xul \ No newline at end of file
diff --git a/toolkit/components/places/tests/chrome/link-less-items-no-site-uri.rss b/toolkit/components/places/tests/chrome/link-less-items-no-site-uri.rss
deleted file mode 100644
index 612b0a5c2..000000000
--- a/toolkit/components/places/tests/chrome/link-less-items-no-site-uri.rss
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<rss version="2.0">
- <channel>
- <title>feed title</title>
- <ttl>180</ttl>
- <item>
- <title>linked feed item</title>
- <link>http://feed-item-link.com</link>
- </item>
- <item>
- <title>link-less feed item</title>
- </item>
- <item>
- <title>linked feed item</title>
- <link>http://feed-item-link.com</link>
- </item>
- </channel>
-</rss>
diff --git a/toolkit/components/places/tests/chrome/link-less-items.rss b/toolkit/components/places/tests/chrome/link-less-items.rss
deleted file mode 100644
index a30d4a353..000000000
--- a/toolkit/components/places/tests/chrome/link-less-items.rss
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="iso-8859-1"?>
-<rss version="2.0">
- <channel>
- <title>feed title</title>
- <link>http://feed-link.com</link>
- <ttl>180</ttl>
- <item>
- <title>linked feed item</title>
- <link>http://feed-item-link.com</link>
- </item>
- <item>
- <title>link-less feed item</title>
- </item>
- <item>
- <title>linked feed item</title>
- <link>http://feed-item-link.com</link>
- </item>
- </channel>
-</rss>
diff --git a/toolkit/components/places/tests/chrome/rss_as_html.rss b/toolkit/components/places/tests/chrome/rss_as_html.rss
deleted file mode 100644
index e82305035..000000000
--- a/toolkit/components/places/tests/chrome/rss_as_html.rss
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
-<channel>
-<title>sadfasdfasdfasfasdf</title>
-<link>http://www.example.com</link>
-<description>asdfasdfasdf.example.com</description>
-<language>de</language>
-<copyright>asdfasdfasdfasdf</copyright>
-<lastBuildDate>Tue, 11 Mar 2008 18:52:52 +0100</lastBuildDate>
-<docs>http://blogs.law.harvard.edu/tech/rss</docs>
-<ttl>10</ttl>
-<item>
-<title>The First Title</title>
-<link>http://www.example.com/index.html</link>
-<pubDate>Tue, 11 Mar 2008 18:24:43 +0100</pubDate>
-<content:encoded>
-<![CDATA[
-<p>
-askdlfjas;dfkjas;fkdj
-</p>
-]]>
-</content:encoded>
-<description>aklsjdhfasdjfahasdfhj</description>
-<guid>http://foo.example.com/asdfasdf</guid>
-</item>
-</channel>
-</rss>
diff --git a/toolkit/components/places/tests/chrome/rss_as_html.rss^headers^ b/toolkit/components/places/tests/chrome/rss_as_html.rss^headers^
deleted file mode 100644
index 04fbaa08f..000000000
--- a/toolkit/components/places/tests/chrome/rss_as_html.rss^headers^
+++ /dev/null
@@ -1,2 +0,0 @@
-HTTP 200 OK
-Content-Type: text/html
diff --git a/toolkit/components/places/tests/chrome/sample_feed.atom b/toolkit/components/places/tests/chrome/sample_feed.atom
deleted file mode 100644
index add75efb4..000000000
--- a/toolkit/components/places/tests/chrome/sample_feed.atom
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
-
- <title>Example Feed</title>
- <link href="http://example.org/"/>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
-
- <entry>
-
- <title>Atom-Powered Robots Run Amok</title>
- <link href="http://example.org/2003/12/13/atom03"/>
- <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
- <updated>2003-12-13T18:30:02Z</updated>
-
- <summary>Some text.</summary>
- </entry>
-
-</feed>
diff --git a/toolkit/components/places/tests/chrome/test_303567.xul b/toolkit/components/places/tests/chrome/test_303567.xul
deleted file mode 100644
index 37ae77cbb..000000000
--- a/toolkit/components/places/tests/chrome/test_303567.xul
+++ /dev/null
@@ -1,122 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Add Bad Livemarks"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="runTest()">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
-<script type="application/javascript">
-<![CDATA[
-// Test that for feeds with items that have no link:
-// * the link-less items are present in the database.
-// * the feed's site URI is substituted for each item's link.
-SimpleTest.waitForExplicitFinish();
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-
-const LIVEMARKS = [
- { feedURI: NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/link-less-items.rss"),
- siteURI: NetUtil.newURI("http://mochi.test:8888/"),
- urls: [
- "http://feed-item-link.com/",
- "http://feed-link.com/",
- "http://feed-item-link.com/",
- ],
- message: "Ensure link-less livemark item picked up site uri.",
- },
- { feedURI: NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/link-less-items-no-site-uri.rss"),
- siteURI: null,
- urls: [
- "http://feed-item-link.com/",
- "http://feed-item-link.com/",
- ],
- message: "Ensure livemark item links did not inherit site uri."
- },
-];
-
-function runTest()
-{
- let loadCount = 0;
-
- function testLivemark(aLivemarkData) {
- PlacesUtils.livemarks.addLivemark(
- { title: "foo"
- , parentGuid: PlacesUtils.bookmarks.toolbarGuid
- , feedURI: aLivemarkData.feedURI
- , siteURI: aLivemarkData.siteURI
- })
- .then(function (aLivemark) {
- is (aLivemark.feedURI.spec, aLivemarkData.feedURI.spec,
- "Get correct feedURI");
- if (aLivemarkData.siteURI) {
- is (aLivemark.siteURI.spec, aLivemarkData.siteURI.spec,
- "Get correct siteURI");
- }
- else {
- is (aLivemark.siteURI, null, "Get correct siteURI");
- }
-
- waitForLivemarkLoad(aLivemark, function (aLivemark) {
- let nodes = aLivemark.getNodesForContainer({});
- is(nodes.length, aLivemarkData.urls.length,
- "Ensure all the livemark items were created.");
- aLivemarkData.urls.forEach(function (aUrl, aIndex) {
- let node = nodes[aIndex];
- is(node.uri, aUrl, aLivemarkData.message);
- });
-
- PlacesUtils.livemarks.removeLivemark(aLivemark).then(() => {
- if (++loadCount == LIVEMARKS.length)
- SimpleTest.finish();
- });
- });
- }, function () {
- is(true, false, "Should not fail adding a livemark");
- }
- );
- }
-
- LIVEMARKS.forEach(testLivemark);
-}
-
-function waitForLivemarkLoad(aLivemark, aCallback) {
- // Don't need a real node here.
- let node = {};
- let resultObserver = {
- nodeInserted: function() {},
- nodeRemoved: function() {},
- nodeAnnotationChanged: function() {},
- nodeTitleChanged: function() {},
- nodeHistoryDetailsChanged: function() {},
- nodeMoved: function() {},
- ontainerStateChanged: function () {},
- sortingChanged: function() {},
- batching: function() {},
- invalidateContainer: function(node) {
- isnot(aLivemark.status, Ci.mozILivemark.STATUS_FAILED,
- "Loading livemark should success");
- if (aLivemark.status == Ci.mozILivemark.STATUS_READY) {
- aLivemark.unregisterForUpdates(node, resultObserver);
- aCallback(aLivemark);
- }
- }
- };
- aLivemark.registerForUpdates(node, resultObserver);
- aLivemark.reload();
-}
-
-]]>
-</script>
-</window>
diff --git a/toolkit/components/places/tests/chrome/test_341972a.xul b/toolkit/components/places/tests/chrome/test_341972a.xul
deleted file mode 100644
index 7c78136a9..000000000
--- a/toolkit/components/places/tests/chrome/test_341972a.xul
+++ /dev/null
@@ -1,87 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Update Livemark SiteURI"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="runTest()">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
-<script type="application/javascript">
-<![CDATA[
-/*
- Test updating livemark siteURI to the value from the feed
- */
-SimpleTest.waitForExplicitFinish();
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-
-function runTest() {
- const FEEDSPEC = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/sample_feed.atom";
- const INITIALSITESPEC = "http://mochi.test:8888/";
- const FEEDSITESPEC = "http://example.org/";
-
- PlacesUtils.livemarks.addLivemark(
- { title: "foo"
- , parentGuid: PlacesUtils.bookmarks.toolbarGuid
- , feedURI: NetUtil.newURI(FEEDSPEC)
- , siteURI: NetUtil.newURI(INITIALSITESPEC)
- })
- .then(function (aLivemark) {
- is(aLivemark.siteURI.spec, INITIALSITESPEC,
- "Has correct initial livemark site URI");
-
- waitForLivemarkLoad(aLivemark, function (aLivemark) {
- is(aLivemark.siteURI.spec, FEEDSITESPEC,
- "livemark site URI set to value in feed");
-
- PlacesUtils.livemarks.removeLivemark(aLivemark).then(() => {
- SimpleTest.finish();
- });
- });
- }, function () {
- is(true, false, "Should not fail adding a livemark");
- }
- );
-}
-
-function waitForLivemarkLoad(aLivemark, aCallback) {
- // Don't need a real node here.
- let node = {};
- let resultObserver = {
- nodeInserted: function() {},
- nodeRemoved: function() {},
- nodeAnnotationChanged: function() {},
- nodeTitleChanged: function() {},
- nodeHistoryDetailsChanged: function() {},
- nodeMoved: function() {},
- ontainerStateChanged: function () {},
- sortingChanged: function() {},
- batching: function() {},
- invalidateContainer: function(node) {
- isnot(aLivemark.status, Ci.mozILivemark.STATUS_FAILED,
- "Loading livemark should success");
- if (aLivemark.status == Ci.mozILivemark.STATUS_READY) {
- aLivemark.unregisterForUpdates(node, resultObserver);
- aCallback(aLivemark);
- }
- }
- };
- aLivemark.registerForUpdates(node, resultObserver);
- aLivemark.reload();
-}
-
-]]>
-</script>
-
-</window>
diff --git a/toolkit/components/places/tests/chrome/test_341972b.xul b/toolkit/components/places/tests/chrome/test_341972b.xul
deleted file mode 100644
index 86cdc75f3..000000000
--- a/toolkit/components/places/tests/chrome/test_341972b.xul
+++ /dev/null
@@ -1,84 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Update Livemark SiteURI, null to start"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="runTest()">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
-<script type="application/javascript">
-<![CDATA[
-/*
- Test updating livemark siteURI to the value from the feed, when it's null
- */
-SimpleTest.waitForExplicitFinish();
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-
-function runTest() {
- const FEEDSPEC = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/sample_feed.atom";
- const FEEDSITESPEC = "http://example.org/";
-
- PlacesUtils.livemarks.addLivemark(
- { title: "foo"
- , parentGuid: PlacesUtils.bookmarks.toolbarGuid
- , feedURI: NetUtil.newURI(FEEDSPEC)
- })
- .then(function (aLivemark) {
- is(aLivemark.siteURI, null, "Has null livemark site URI");
-
- waitForLivemarkLoad(aLivemark, function (aLivemark) {
- is(aLivemark.siteURI.spec, FEEDSITESPEC,
- "livemark site URI set to value in feed");
-
- PlacesUtils.livemarks.removeLivemark(aLivemark).then(() => {
- SimpleTest.finish();
- });
- });
- }, function () {
- is(true, false, "Should not fail adding a livemark");
- }
- );
-}
-
-function waitForLivemarkLoad(aLivemark, aCallback) {
- // Don't need a real node here.
- let node = {};
- let resultObserver = {
- nodeInserted: function() {},
- nodeRemoved: function() {},
- nodeAnnotationChanged: function() {},
- nodeTitleChanged: function() {},
- nodeHistoryDetailsChanged: function() {},
- nodeMoved: function() {},
- ontainerStateChanged: function () {},
- sortingChanged: function() {},
- batching: function() {},
- invalidateContainer: function(node) {
- isnot(aLivemark.status, Ci.mozILivemark.STATUS_FAILED,
- "Loading livemark should success");
- if (aLivemark.status == Ci.mozILivemark.STATUS_READY) {
- aLivemark.unregisterForUpdates(node, resultObserver);
- aCallback(aLivemark);
- }
- }
- };
- aLivemark.registerForUpdates(node, resultObserver);
- aLivemark.reload();
-}
-
-]]>
-</script>
-
-</window>
diff --git a/toolkit/components/places/tests/chrome/test_342484.xul b/toolkit/components/places/tests/chrome/test_342484.xul
deleted file mode 100644
index 353313abb..000000000
--- a/toolkit/components/places/tests/chrome/test_342484.xul
+++ /dev/null
@@ -1,88 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Add Bad Livemarks"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="runTest()">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
-<script type="application/javascript">
-<![CDATA[
-/*
- Test loading feeds with items that aren't allowed
- */
-SimpleTest.waitForExplicitFinish();
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-
-function runTest() {
- const FEEDSPEC = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/bad_links.atom";
- const GOOD_URLS = ["http://example.org/first", "http://example.org/last"];
-
- PlacesUtils.livemarks.addLivemark(
- { title: "foo"
- , parentGuid: PlacesUtils.bookmarks.toolbarGuid
- , feedURI: NetUtil.newURI(FEEDSPEC)
- , siteURI: NetUtil.newURI("http:/mochi.test/")
- })
- .then(function (aLivemark) {
- waitForLivemarkLoad(aLivemark, function (aLivemark) {
- let nodes = aLivemark.getNodesForContainer({});
-
- is(nodes.length, 2, "Created the two good livemark items");
- for (let i = 0; i < nodes.length; ++i) {
- let node = nodes[i];
- ok(GOOD_URLS.includes(node.uri), "livemark item created with bad uri " + node.uri);
- }
-
- PlacesUtils.livemarks.removeLivemark(aLivemark).then(() => {
- SimpleTest.finish();
- });
- });
- }, function () {
- is(true, false, "Should not fail adding a livemark");
- }
- );
-}
-
-function waitForLivemarkLoad(aLivemark, aCallback) {
- // Don't need a real node here.
- let node = {};
- let resultObserver = {
- nodeInserted: function() {},
- nodeRemoved: function() {},
- nodeAnnotationChanged: function() {},
- nodeTitleChanged: function() {},
- nodeHistoryDetailsChanged: function() {},
- nodeMoved: function() {},
- ontainerStateChanged: function () {},
- sortingChanged: function() {},
- batching: function() {},
- invalidateContainer: function(node) {
- isnot(aLivemark.status, Ci.mozILivemark.STATUS_FAILED,
- "Loading livemark should success");
- if (aLivemark.status == Ci.mozILivemark.STATUS_READY) {
- aLivemark.unregisterForUpdates(node, resultObserver);
- aCallback(aLivemark);
- }
- }
- };
- aLivemark.registerForUpdates(node, resultObserver);
- aLivemark.reload();
-}
-
-]]>
-</script>
-
-</window>
diff --git a/toolkit/components/places/tests/chrome/test_371798.xul b/toolkit/components/places/tests/chrome/test_371798.xul
deleted file mode 100644
index 241db75c3..000000000
--- a/toolkit/components/places/tests/chrome/test_371798.xul
+++ /dev/null
@@ -1,101 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Bug 371798"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
-<script type="application/javascript">
-<![CDATA[
-// Test the asynchronous live-updating of bookmarks query results
-SimpleTest.waitForExplicitFinish();
-
-var {utils: Cu, interfaces: Ci} = Components;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/NetUtil.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-
-const TEST_URI = NetUtil.newURI("http://foo.com");
-
-function promiseOnItemChanged() {
- return new Promise(resolve => {
- PlacesUtils.bookmarks.addObserver({
- onBeginUpdateBatch() {},
- onEndUpdateBatch() {},
- onItemAdded() {},
- onItemRemoved() {},
- onItemVisited() {},
- onItemMoved() {},
-
- onItemChanged() {
- PlacesUtils.bookmarks.removeObserver(this);
- resolve();
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver])
- }, false);
- });
-}
-
-Task.spawn(function* () {
- // add 2 bookmarks to the toolbar, same URI, different titles (set later)
- let bm1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: TEST_URI
- });
-
- let bm2 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: TEST_URI
- });
-
- // query for bookmarks
- let rootNode = PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId).root;
-
- // set up observer
- let promiseObserved = promiseOnItemChanged();
-
- // modify the bookmark's title
- yield PlacesUtils.bookmarks.update({
- guid: bm2.guid, title: "foo"
- });
-
- // wait for notification
- yield promiseObserved;
-
- // Continue after our observer gets notified of onItemChanged
- // which is triggered by updating the item's title.
- // After receiving the notification, our original query should also
- // have been live-updated, so we can iterate through its children,
- // to check that only the modified bookmark has changed.
-
- // result node should be updated
- let cc = rootNode.childCount;
- for (let i = 0; i < cc; ++i) {
- let node = rootNode.getChild(i);
- // test that bm1 does not have new title
- if (node.bookmarkGuid == bm1.guid)
- ok(node.title != "foo",
- "Changing a bookmark's title did not affect the title of other bookmarks with the same URI");
- }
- rootNode.containerOpen = false;
-
- // clean up
- yield PlacesUtils.bookmarks.remove(bm1);
- yield PlacesUtils.bookmarks.remove(bm2);
-}).catch(err => {
- ok(false, `uncaught error: ${err}`);
-}).then(() => {
- SimpleTest.finish();
-});
-]]>
-</script>
-
-</window>
diff --git a/toolkit/components/places/tests/chrome/test_381357.xul b/toolkit/components/places/tests/chrome/test_381357.xul
deleted file mode 100644
index 6bd6cb024..000000000
--- a/toolkit/components/places/tests/chrome/test_381357.xul
+++ /dev/null
@@ -1,85 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Add Livemarks from RSS feed served as text/html"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="runTest()">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
-<script type="application/javascript">
-<![CDATA[
-/*
- Test loading feeds with text/html
- */
-SimpleTest.waitForExplicitFinish();
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-
-function runTest() {
- const FEEDSPEC = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/rss_as_html.rss";
-
- PlacesUtils.livemarks.addLivemark(
- { title: "foo"
- , parentGuid: PlacesUtils.bookmarks.toolbarGuid
- , feedURI: NetUtil.newURI(FEEDSPEC)
- , siteURI: NetUtil.newURI("http:/mochi.test/")
- })
- .then(function (aLivemark) {
- waitForLivemarkLoad(aLivemark, function (aLivemark) {
- let nodes = aLivemark.getNodesForContainer({});
-
- is(nodes[0].title, "The First Title",
- "livemark site URI set to value in feed");
-
- PlacesUtils.livemarks.removeLivemark(aLivemark).then(() => {
- SimpleTest.finish();
- });
- });
- }, function () {
- is(true, false, "Should not fail adding a livemark");
- SimpleTest.finish();
- }
- );
-}
-
-function waitForLivemarkLoad(aLivemark, aCallback) {
- // Don't need a real node here.
- let node = {};
- let resultObserver = {
- nodeInserted: function() {},
- nodeRemoved: function() {},
- nodeAnnotationChanged: function() {},
- nodeTitleChanged: function() {},
- nodeHistoryDetailsChanged: function() {},
- nodeMoved: function() {},
- ontainerStateChanged: function () {},
- sortingChanged: function() {},
- batching: function() {},
- invalidateContainer: function(node) {
- isnot(aLivemark.status, Ci.mozILivemark.STATUS_FAILED,
- "Loading livemark should success");
- if (aLivemark.status == Ci.mozILivemark.STATUS_READY) {
- aLivemark.unregisterForUpdates(node, resultObserver);
- aCallback(aLivemark);
- }
- }
- };
- aLivemark.registerForUpdates(node, resultObserver);
- aLivemark.reload();
-}
-
-]]>
-</script>
-
-</window>
diff --git a/toolkit/components/places/tests/chrome/test_browser_disableglobalhistory.xul b/toolkit/components/places/tests/chrome/test_browser_disableglobalhistory.xul
deleted file mode 100644
index 3a84f3030..000000000
--- a/toolkit/components/places/tests/chrome/test_browser_disableglobalhistory.xul
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css"
- type="text/css"?>
-
-<window title="Test disableglobalhistory attribute on remote browsers"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- </body>
-
- <script type="text/javascript;version=1.7">
- SimpleTest.waitForExplicitFinish();
-
- let w = window.open('browser_disableglobalhistory.xul', '_blank', 'chrome,resizable=yes,width=400,height=600');
-
- function done() {
- w.close();
- SimpleTest.finish();
- }
- </script>
-
-</window> \ No newline at end of file
diff --git a/toolkit/components/places/tests/chrome/test_favicon_annotations.xul b/toolkit/components/places/tests/chrome/test_favicon_annotations.xul
deleted file mode 100644
index b7647cbc6..000000000
--- a/toolkit/components/places/tests/chrome/test_favicon_annotations.xul
+++ /dev/null
@@ -1,168 +0,0 @@
-<?xml version="1.0"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
- - License, v. 2.0. If a copy of the MPL was not distributed with this
- - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-<!--
- * This file tests the moz-anno protocol, which was added in Bug 316077 and how
- * it loads favicons.
--->
-
-<window title="Favicon Annotation Protocol Test"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/WindowSnapshot.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
-
- <script type="application/javascript">
- <![CDATA[
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-let fs = Cc["@mozilla.org/browser/favicon-service;1"].
- getService(Ci.nsIFaviconService);
-
-// Test descriptions that will be printed in the case of failure.
-let testDescriptions = [
- "moz-anno URI with no data in the database loads default icon",
- "URI added to the database is properly loaded",
-];
-
-// URIs to load (will be compared with expectedURIs of the same index).
-let testURIs = [
- "http://mozilla.org/2009/made-up-favicon/places-rocks/",
- "http://mozilla.org/should-be-barney/",
-];
-
-// URIs to load for expected results.
-let expectedURIs = [
- fs.defaultFavicon.spec,
- "data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%10%00%00%00%10%08%06%00%00%00%1F%F3%FFa%00%00%00%04gAMA%00%00%AF%C87%05%8A%E9%00%00%00%19tEXtSoftware%00Adobe%20ImageReadyq%C9e%3C%00%00%01%D6IDATx%DAb%FC%FF%FF%3F%03%25%00%20%80%98%909%EF%DF%BFg%EF%EC%EC%FC%AD%AC%AC%FC%DF%95%91%F1%BF%89%89%C9%7F%20%FF%D7%EA%D5%AB%B7%DF%BBwO%16%9B%01%00%01%C4%00r%01%08%9F9s%C6%CD%D8%D8%F8%BF%0B%03%C3%FF3%40%BC%0A%88%EF%02q%1A%10%BB%40%F1%AAU%ABv%C1%D4%C30%40%00%81%89%993g%3E%06%1A%F6%3F%14%AA%11D%97%03%F1%7Fc%08%0D%E2%2B))%FD%17%04%89%A1%19%00%10%40%0C%D00%F8%0F3%00%C8%F8%BF%1B%E4%0Ac%88a%E5%60%17%19%FF%0F%0D%0D%05%1B%02v%D9%DD%BB%0A0%03%00%02%08%AC%B9%A3%A3%E3%17%03%D4v%90%01%EF%18%106%C3%0Cz%07%C5%BB%A1%DE%82y%07%20%80%A0%A6%08B%FCn%0C1%60%26%D4%20d%C3VA%C3%06%26%BE%0A%EA-%80%00%82%B9%E0%F7L4%0D%EF%90%F8%C6%60%2F%0A%82%BD%01%13%07%0700%D0%01%02%88%11%E4%02P%B41%DC%BB%C7%D0%014%0D%E8l%06W%20%06%BA%88%A1%1C%1AS%15%40%7C%16%CA6.%2Fgx%BFg%0F%83%CB%D9%B3%0C%7B%80%7C%80%00%02%BB%00%E8%9F%ED%20%1B%3A%A0%A6%9F%81%DA%DC%01%C5%B0%80%ED%80%FA%BF%BC%BC%FC%3F%83%12%90%9D%96%F6%1F%20%80%18%DE%BD%7B%C7%0E%8E%05AD%20%FEGr%A6%A0%A0%E0%7F%25P%80%02%9D%0F%D28%13%18%23%C6%C0%B0%02E%3D%C8%F5%00%01%04%8F%05P%A8%BA%40my%87%E4%12c%A8%8D%20%8B%D0%D3%00%08%03%04%10%9C%01R%E4%82d%3B%C8%A0%99%C6%90%90%C6%A5%19%84%01%02%08%9E%17%80%C9x%F7%7B%A0%DBVC%F9%A0%C0%5C%7D%16%2C%CE%00%F4%C6O%5C%99%09%20%800L%04y%A5%03%1A%95%A0%80%05%05%14.%DBA%18%20%80%18)%CD%CE%00%01%06%00%0C'%94%C7%C0k%C9%2C%00%00%00%00IEND%AEB%60%82",
-];
-
-
-/**
- * The event listener placed on our test windows used to determine when it is
- * safe to compare the two windows.
- */
-let _results = [];
-function loadEventHandler()
-{
- _results.push(snapshotWindow(window));
-
- loadNextTest();
-}
-
-/**
- * This runs the comparison.
- */
-function compareResults(aIndex, aImage1, aImage2)
-{
- let [correct, data1, data2] = compareSnapshots(aImage1, aImage2, true);
- SimpleTest.ok(correct,
- "Test '" + testDescriptions[aIndex] + "' matches expectations. " +
- "Data from window 1 is '" + data1 + "'. " +
- "Data from window 2 is '" + data2 + "'");
-}
-
-/**
- * Loads the next set of URIs to compare against.
- */
-let _counter = -1;
-function loadNextTest()
-{
- _counter++;
- // If we have no more tests, finish.
- if (_counter / 2 == testDescriptions.length) {
- for (let i = 0; i < _results.length; i = i + 2)
- compareResults(i / 2, _results[i], _results[i + 1]);
-
- SimpleTest.finish();
- return;
- }
-
- let nextURI = function() {
- let index = Math.floor(_counter / 2);
- if ((_counter % 2) == 0)
- return "moz-anno:favicon:" + testURIs[index];
- return expectedURIs[index];
- }
-
- let img = document.getElementById("favicon");
- img.setAttribute("src", nextURI());
-}
-
-function test()
-{
- SimpleTest.waitForExplicitFinish();
- let db = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsPIPlacesDatabase).
- DBConnection;
-
- // Empty any old favicons
- db.executeSimpleSQL("DELETE FROM moz_favicons");
-
- let ios = Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService);
- let uri = function(aSpec) {
- return ios.newURI(aSpec, null, null);
- };
-
- let pageURI = uri("http://example.com/favicon_annotations");
- let history = Cc["@mozilla.org/browser/history;1"]
- .getService(Ci.mozIAsyncHistory);
- history.updatePlaces(
- {
- uri: pageURI,
- visits: [{ transitionType: Ci.nsINavHistoryService.TRANSITION_TYPED,
- visitDate: Date.now() * 1000
- }],
- },
- {
- handleError: function UP_handleError() {
- ok(false, "Unexpected error in adding visit.");
- },
- handleResult: function () {},
- handleCompletion: function UP_handleCompletion() {
- // Set the favicon data. Note that the "moz-anno:" protocol requires
- // the favicon to be stored in the database, but the
- // replaceFaviconDataFromDataURL function will not save the favicon
- // unless it is associated with a page. Thus, we must associate the
- // icon with a page explicitly in order for it to be visible through
- // the protocol.
- var systemPrincipal = Cc["@mozilla.org/systemprincipal;1"]
- .createInstance(Ci.nsIPrincipal);
-
- fs.replaceFaviconDataFromDataURL(uri(testURIs[1]), expectedURIs[1],
- (Date.now() + 60 * 60 * 24 * 1000) * 1000,
- systemPrincipal);
-
- fs.setAndFetchFaviconForPage(pageURI, uri(testURIs[1]), true,
- fs.FAVICON_LOAD_NON_PRIVATE,
- null, systemPrincipal);
-
- // And start our test process.
- loadNextTest();
- }
- }
- );
-
-
-}
-
- ]]>
- </script>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <img id="favicon" onload="loadEventHandler();"/>
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
-</window>
diff --git a/toolkit/components/places/tests/chrome/test_reloadLivemarks.xul b/toolkit/components/places/tests/chrome/test_reloadLivemarks.xul
deleted file mode 100644
index 43772d09f..000000000
--- a/toolkit/components/places/tests/chrome/test_reloadLivemarks.xul
+++ /dev/null
@@ -1,155 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet
- href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-<window title="Reload Livemarks"
- xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="runTest()" onunload="cleanup()">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <body xmlns="http://www.w3.org/1999/xhtml" />
-
-<script type="application/javascript">
-<![CDATA[
-// Test that for concurrent reload of livemarks.
-
-SimpleTest.waitForExplicitFinish();
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/NetUtil.jsm");
-Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
-
-let gLivemarks = [
- { id: -1,
- title: "foo",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- feedURI: NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/link-less-items.rss")
- },
- { id: -1,
- title: "bar",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- feedURI: NetUtil.newURI("http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/link-less-items-no-site-uri.rss")
- },
-];
-
-function runTest()
-{
- addLivemarks(function () {
- reloadLivemarks(false, function () {
- reloadLivemarks(true, function () {
- removeLivemarks(SimpleTest.finish);
- });
- });
- // Ensure this normal reload doesn't overwrite the forced one.
- PlacesUtils.livemarks.reloadLivemarks();
- });
-}
-
-function addLivemarks(aCallback) {
- info("Adding livemarks");
- let count = gLivemarks.length;
- gLivemarks.forEach(function(aLivemarkData) {
- PlacesUtils.livemarks.addLivemark(aLivemarkData)
- .then(function (aLivemark) {
- ok(aLivemark.feedURI.equals(aLivemarkData.feedURI), "Livemark added");
- aLivemarkData.id = aLivemark.id;
- if (--count == 0) {
- aCallback();
- }
- },
- function () {
- is(true, false, "Should not fail adding a livemark.");
- aCallback();
- });
- });
-}
-
-function reloadLivemarks(aForceUpdate, aCallback) {
- info("Reloading livemarks with forceUpdate: " + aForceUpdate);
- let count = gLivemarks.length;
- gLivemarks.forEach(function(aLivemarkData) {
- PlacesUtils.livemarks.getLivemark(aLivemarkData)
- .then(aLivemark => {
- ok(aLivemark.feedURI.equals(aLivemarkData.feedURI), "Livemark found");
- aLivemarkData._observer = new resultObserver(aLivemark, function() {
- if (++count == gLivemarks.length) {
- aCallback();
- }
- });
- if (--count == 0) {
- PlacesUtils.livemarks.reloadLivemarks(aForceUpdate);
- }
- },
- function() {
- is(true, false, "Should not fail getting a livemark.");
- aCallback();
- }
- );
- });
-}
-
-function removeLivemarks(aCallback) {
- info("Removing livemarks");
- let count = gLivemarks.length;
- gLivemarks.forEach(function(aLivemarkData) {
- PlacesUtils.livemarks.removeLivemark(aLivemarkData).then(
- function (aLivemark) {
- if (--count == 0) {
- aCallback();
- }
- },
- function() {
- is(true, false, "Should not fail adding a livemark.");
- aCallback();
- }
- );
- });
-}
-
-function resultObserver(aLivemark, aCallback) {
- this._node = {};
- this._livemark = aLivemark;
- this._callback = aCallback;
- this._livemark.registerForUpdates(this._node, this);
-}
-resultObserver.prototype = {
- nodeInserted: function() {},
- nodeRemoved: function() {},
- nodeAnnotationChanged: function() {},
- nodeTitleChanged: function() {},
- nodeHistoryDetailsChanged: function() {},
- nodeMoved: function() {},
- ontainerStateChanged: function () {},
- sortingChanged: function() {},
- batching: function() {},
- invalidateContainer: function(aContainer) {
- // Wait for load finish.
- if (this._livemark.status == Ci.mozILivemark.STATUS_LOADING)
- return;
-
- this._terminate();
- this._callback();
- },
- _terminate: function () {
- if (!this._terminated) {
- this._livemark.unregisterForUpdates(this._node);
- this._terminated = true;
- }
- }
-};
-
-function cleanup() {
- gLivemarks.forEach(function(aLivemarkData) {
- if (aLivemarkData._observer)
- aLivemarkData._observer._terminate();
- });
-}
-]]>
-</script>
-</window>
diff --git a/toolkit/components/places/tests/cpp/mock_Link.h b/toolkit/components/places/tests/cpp/mock_Link.h
deleted file mode 100644
index 92ef25d6a..000000000
--- a/toolkit/components/places/tests/cpp/mock_Link.h
+++ /dev/null
@@ -1,229 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * This is a mock Link object which can be used in tests.
- */
-
-#ifndef mock_Link_h__
-#define mock_Link_h__
-
-#include "mozilla/MemoryReporting.h"
-#include "mozilla/dom/Link.h"
-#include "mozilla/dom/URLSearchParams.h"
-
-class mock_Link : public mozilla::dom::Link
-{
-public:
- NS_DECL_ISUPPORTS
-
- explicit mock_Link(void (*aHandlerFunction)(nsLinkState),
- bool aRunNextTest = true)
- : mozilla::dom::Link(nullptr)
- , mHandler(aHandlerFunction)
- , mRunNextTest(aRunNextTest)
- {
- // Create a cyclic ownership, so that the link will be released only
- // after its status has been updated. This will ensure that, when it should
- // run the next test, it will happen at the end of the test function, if
- // the link status has already been set before. Indeed the link status is
- // updated on a separate connection, thus may happen at any time.
- mDeathGrip = this;
- }
-
- virtual void SetLinkState(nsLinkState aState) override
- {
- // Notify our callback function.
- mHandler(aState);
-
- // Break the cycle so the object can be destroyed.
- mDeathGrip = nullptr;
- }
-
- virtual size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const override
- {
- return 0; // the value shouldn't matter
- }
-
-protected:
- ~mock_Link() {
- // Run the next test if we are supposed to.
- if (mRunNextTest) {
- run_next_test();
- }
- }
-
-private:
- void (*mHandler)(nsLinkState);
- bool mRunNextTest;
- RefPtr<Link> mDeathGrip;
-};
-
-NS_IMPL_ISUPPORTS(
- mock_Link,
- mozilla::dom::Link
-)
-
-////////////////////////////////////////////////////////////////////////////////
-//// Needed Link Methods
-
-namespace mozilla {
-namespace dom {
-
-Link::Link(Element* aElement)
-: mElement(aElement)
-, mLinkState(eLinkState_NotLink)
-, mRegistered(false)
-{
-}
-
-Link::~Link()
-{
-}
-
-bool
-Link::ElementHasHref() const
-{
- NS_NOTREACHED("Unexpected call to Link::ElementHasHref");
- return false; // suppress compiler warning
-}
-
-void
-Link::SetLinkState(nsLinkState aState)
-{
- NS_NOTREACHED("Unexpected call to Link::SetLinkState");
-}
-
-void
-Link::ResetLinkState(bool aNotify, bool aHasHref)
-{
- NS_NOTREACHED("Unexpected call to Link::ResetLinkState");
-}
-
-nsIURI*
-Link::GetURI() const
-{
- NS_NOTREACHED("Unexpected call to Link::GetURI");
- return nullptr; // suppress compiler warning
-}
-
-size_t
-Link::SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
-{
- NS_NOTREACHED("Unexpected call to Link::SizeOfExcludingThis");
- return 0;
-}
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(URLSearchParams)
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(URLSearchParams)
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(URLSearchParams)
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(URLSearchParams)
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(URLSearchParams)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(URLSearchParams)
-
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(URLSearchParams)
- NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
- NS_INTERFACE_MAP_ENTRY(nsISupports)
-NS_INTERFACE_MAP_END
-
-
-URLSearchParams::URLSearchParams(nsISupports* aParent,
- URLSearchParamsObserver* aObserver)
-{
-}
-
-URLSearchParams::~URLSearchParams()
-{
-}
-
-JSObject*
-URLSearchParams::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
- return nullptr;
-}
-
-void
-URLSearchParams::ParseInput(const nsACString& aInput)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::ParseInput");
-}
-
-void
-URLSearchParams::Serialize(nsAString& aValue) const
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::Serialize");
-}
-
-void
-URLSearchParams::Get(const nsAString& aName, nsString& aRetval)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::Get");
-}
-
-void
-URLSearchParams::GetAll(const nsAString& aName, nsTArray<nsString >& aRetval)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::GetAll");
-}
-
-void
-URLSearchParams::Set(const nsAString& aName, const nsAString& aValue)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::Set");
-}
-
-void
-URLSearchParams::Append(const nsAString& aName, const nsAString& aValue)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::Append");
-}
-
-void
-URLSearchParams::AppendInternal(const nsAString& aName, const nsAString& aValue)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::AppendInternal");
-}
-
-bool
-URLSearchParams::Has(const nsAString& aName)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::Has");
- return false;
-}
-
-void
-URLSearchParams::Delete(const nsAString& aName)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::Delete");
-}
-
-void
-URLSearchParams::DeleteAll()
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::DeleteAll");
-}
-
-void
-URLSearchParams::NotifyObserver()
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::NotifyObserver");
-}
-
-NS_IMETHODIMP
-URLSearchParams::GetSendInfo(nsIInputStream** aBody, uint64_t* aContentLength,
- nsACString& aContentType, nsACString& aCharset)
-{
- NS_NOTREACHED("Unexpected call to URLSearchParams::GetSendInfo");
- return NS_OK;
-}
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mock_Link_h__
diff --git a/toolkit/components/places/tests/cpp/moz.build b/toolkit/components/places/tests/cpp/moz.build
deleted file mode 100644
index f6bd91bd7..000000000
--- a/toolkit/components/places/tests/cpp/moz.build
+++ /dev/null
@@ -1,14 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-GeckoCppUnitTests([
- 'test_IHistory',
-])
-
-if CONFIG['JS_SHARED_LIBRARY']:
- USE_LIBS += [
- 'js',
- ]
diff --git a/toolkit/components/places/tests/cpp/places_test_harness.h b/toolkit/components/places/tests/cpp/places_test_harness.h
deleted file mode 100644
index 557a25f90..000000000
--- a/toolkit/components/places/tests/cpp/places_test_harness.h
+++ /dev/null
@@ -1,413 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "TestHarness.h"
-#include "nsMemory.h"
-#include "nsThreadUtils.h"
-#include "nsDocShellCID.h"
-
-#include "nsToolkitCompsCID.h"
-#include "nsINavHistoryService.h"
-#include "nsIObserverService.h"
-#include "nsIURI.h"
-#include "mozilla/IHistory.h"
-#include "mozIStorageConnection.h"
-#include "mozIStorageStatement.h"
-#include "mozIStorageAsyncStatement.h"
-#include "mozIStorageStatementCallback.h"
-#include "mozIStoragePendingStatement.h"
-#include "nsPIPlacesDatabase.h"
-#include "nsIObserver.h"
-#include "prinrval.h"
-#include "prtime.h"
-#include "mozilla/Attributes.h"
-
-#define WAITFORTOPIC_TIMEOUT_SECONDS 5
-
-
-static size_t gTotalTests = 0;
-static size_t gPassedTests = 0;
-
-#define do_check_true(aCondition) \
- PR_BEGIN_MACRO \
- gTotalTests++; \
- if (aCondition) { \
- gPassedTests++; \
- } else { \
- fail("%s | Expected true, got false at line %d", __FILE__, __LINE__); \
- } \
- PR_END_MACRO
-
-#define do_check_false(aCondition) \
- PR_BEGIN_MACRO \
- gTotalTests++; \
- if (!aCondition) { \
- gPassedTests++; \
- } else { \
- fail("%s | Expected false, got true at line %d", __FILE__, __LINE__); \
- } \
- PR_END_MACRO
-
-#define do_check_success(aResult) \
- do_check_true(NS_SUCCEEDED(aResult))
-
-#ifdef LINUX
-// XXX Linux opt builds on tinderbox are orange due to linking with stdlib.
-// This is sad and annoying, but it's a workaround that works.
-#define do_check_eq(aExpected, aActual) \
- do_check_true(aExpected == aActual)
-#else
-#include <sstream>
-
-#define do_check_eq(aActual, aExpected) \
- PR_BEGIN_MACRO \
- gTotalTests++; \
- if (aExpected == aActual) { \
- gPassedTests++; \
- } else { \
- std::ostringstream temp; \
- temp << __FILE__ << " | Expected '" << aExpected << "', got '"; \
- temp << aActual <<"' at line " << __LINE__; \
- fail(temp.str().c_str()); \
- } \
- PR_END_MACRO
-#endif
-
-struct Test
-{
- void (*func)(void);
- const char* const name;
-};
-#define TEST(aName) \
- {aName, #aName}
-
-/**
- * Runs the next text.
- */
-void run_next_test();
-
-/**
- * To be used around asynchronous work.
- */
-void do_test_pending();
-void do_test_finished();
-
-/**
- * Spins current thread until a topic is received.
- */
-class WaitForTopicSpinner final : public nsIObserver
-{
-public:
- NS_DECL_ISUPPORTS
-
- explicit WaitForTopicSpinner(const char* const aTopic)
- : mTopicReceived(false)
- , mStartTime(PR_IntervalNow())
- {
- nsCOMPtr<nsIObserverService> observerService =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- do_check_true(observerService);
- (void)observerService->AddObserver(this, aTopic, false);
- }
-
- void Spin() {
- while (!mTopicReceived) {
- if ((PR_IntervalNow() - mStartTime) > (WAITFORTOPIC_TIMEOUT_SECONDS * PR_USEC_PER_SEC)) {
- // Timed out waiting for the topic.
- do_check_true(false);
- break;
- }
- (void)NS_ProcessNextEvent();
- }
- }
-
- NS_IMETHOD Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData) override
- {
- mTopicReceived = true;
- nsCOMPtr<nsIObserverService> observerService =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- do_check_true(observerService);
- (void)observerService->RemoveObserver(this, aTopic);
- return NS_OK;
- }
-
-private:
- ~WaitForTopicSpinner() {}
-
- bool mTopicReceived;
- PRIntervalTime mStartTime;
-};
-NS_IMPL_ISUPPORTS(
- WaitForTopicSpinner,
- nsIObserver
-)
-
-/**
- * Spins current thread until an async statement is executed.
- */
-class AsyncStatementSpinner final : public mozIStorageStatementCallback
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_MOZISTORAGESTATEMENTCALLBACK
-
- AsyncStatementSpinner();
- void SpinUntilCompleted();
- uint16_t completionReason;
-
-protected:
- ~AsyncStatementSpinner() {}
-
- volatile bool mCompleted;
-};
-
-NS_IMPL_ISUPPORTS(AsyncStatementSpinner,
- mozIStorageStatementCallback)
-
-AsyncStatementSpinner::AsyncStatementSpinner()
-: completionReason(0)
-, mCompleted(false)
-{
-}
-
-NS_IMETHODIMP
-AsyncStatementSpinner::HandleResult(mozIStorageResultSet *aResultSet)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP
-AsyncStatementSpinner::HandleError(mozIStorageError *aError)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP
-AsyncStatementSpinner::HandleCompletion(uint16_t aReason)
-{
- completionReason = aReason;
- mCompleted = true;
- return NS_OK;
-}
-
-void AsyncStatementSpinner::SpinUntilCompleted()
-{
- nsCOMPtr<nsIThread> thread(::do_GetCurrentThread());
- nsresult rv = NS_OK;
- bool processed = true;
- while (!mCompleted && NS_SUCCEEDED(rv)) {
- rv = thread->ProcessNextEvent(true, &processed);
- }
-}
-
-struct PlaceRecord
-{
- int64_t id;
- int32_t hidden;
- int32_t typed;
- int32_t visitCount;
- nsCString guid;
-};
-
-struct VisitRecord
-{
- int64_t id;
- int64_t lastVisitId;
- int32_t transitionType;
-};
-
-already_AddRefed<mozilla::IHistory>
-do_get_IHistory()
-{
- nsCOMPtr<mozilla::IHistory> history = do_GetService(NS_IHISTORY_CONTRACTID);
- do_check_true(history);
- return history.forget();
-}
-
-already_AddRefed<nsINavHistoryService>
-do_get_NavHistory()
-{
- nsCOMPtr<nsINavHistoryService> serv =
- do_GetService(NS_NAVHISTORYSERVICE_CONTRACTID);
- do_check_true(serv);
- return serv.forget();
-}
-
-already_AddRefed<mozIStorageConnection>
-do_get_db()
-{
- nsCOMPtr<nsINavHistoryService> history = do_get_NavHistory();
- nsCOMPtr<nsPIPlacesDatabase> database = do_QueryInterface(history);
- do_check_true(database);
-
- nsCOMPtr<mozIStorageConnection> dbConn;
- nsresult rv = database->GetDBConnection(getter_AddRefs(dbConn));
- do_check_success(rv);
- return dbConn.forget();
-}
-
-/**
- * Get the place record from the database.
- *
- * @param aURI The unique URI of the place we are looking up
- * @param result Out parameter where the result is stored
- */
-void
-do_get_place(nsIURI* aURI, PlaceRecord& result)
-{
- nsCOMPtr<mozIStorageConnection> dbConn = do_get_db();
- nsCOMPtr<mozIStorageStatement> stmt;
-
- nsCString spec;
- nsresult rv = aURI->GetSpec(spec);
- do_check_success(rv);
-
- rv = dbConn->CreateStatement(NS_LITERAL_CSTRING(
- "SELECT id, hidden, typed, visit_count, guid FROM moz_places "
- "WHERE url_hash = hash(?1) AND url = ?1"
- ), getter_AddRefs(stmt));
- do_check_success(rv);
-
- rv = stmt->BindUTF8StringByIndex(0, spec);
- do_check_success(rv);
-
- bool hasResults;
- rv = stmt->ExecuteStep(&hasResults);
- do_check_success(rv);
- if (!hasResults) {
- result.id = 0;
- return;
- }
-
- rv = stmt->GetInt64(0, &result.id);
- do_check_success(rv);
- rv = stmt->GetInt32(1, &result.hidden);
- do_check_success(rv);
- rv = stmt->GetInt32(2, &result.typed);
- do_check_success(rv);
- rv = stmt->GetInt32(3, &result.visitCount);
- do_check_success(rv);
- rv = stmt->GetUTF8String(4, result.guid);
- do_check_success(rv);
-}
-
-/**
- * Gets the most recent visit to a place.
- *
- * @param placeID ID from the moz_places table
- * @param result Out parameter where visit is stored
- */
-void
-do_get_lastVisit(int64_t placeId, VisitRecord& result)
-{
- nsCOMPtr<mozIStorageConnection> dbConn = do_get_db();
- nsCOMPtr<mozIStorageStatement> stmt;
-
- nsresult rv = dbConn->CreateStatement(NS_LITERAL_CSTRING(
- "SELECT id, from_visit, visit_type FROM moz_historyvisits "
- "WHERE place_id=?1 "
- "LIMIT 1"
- ), getter_AddRefs(stmt));
- do_check_success(rv);
-
- rv = stmt->BindInt64ByIndex(0, placeId);
- do_check_success(rv);
-
- bool hasResults;
- rv = stmt->ExecuteStep(&hasResults);
- do_check_success(rv);
-
- if (!hasResults) {
- result.id = 0;
- return;
- }
-
- rv = stmt->GetInt64(0, &result.id);
- do_check_success(rv);
- rv = stmt->GetInt64(1, &result.lastVisitId);
- do_check_success(rv);
- rv = stmt->GetInt32(2, &result.transitionType);
- do_check_success(rv);
-}
-
-void
-do_wait_async_updates() {
- nsCOMPtr<mozIStorageConnection> db = do_get_db();
- nsCOMPtr<mozIStorageAsyncStatement> stmt;
-
- db->CreateAsyncStatement(NS_LITERAL_CSTRING("BEGIN EXCLUSIVE"),
- getter_AddRefs(stmt));
- nsCOMPtr<mozIStoragePendingStatement> pending;
- (void)stmt->ExecuteAsync(nullptr, getter_AddRefs(pending));
-
- db->CreateAsyncStatement(NS_LITERAL_CSTRING("COMMIT"),
- getter_AddRefs(stmt));
- RefPtr<AsyncStatementSpinner> spinner = new AsyncStatementSpinner();
- (void)stmt->ExecuteAsync(spinner, getter_AddRefs(pending));
-
- spinner->SpinUntilCompleted();
-}
-
-/**
- * Adds a URI to the database.
- *
- * @param aURI
- * The URI to add to the database.
- */
-void
-addURI(nsIURI* aURI)
-{
- nsCOMPtr<mozilla::IHistory> history = do_GetService(NS_IHISTORY_CONTRACTID);
- do_check_true(history);
- nsresult rv = history->VisitURI(aURI, nullptr, mozilla::IHistory::TOP_LEVEL);
- do_check_success(rv);
-
- do_wait_async_updates();
-}
-
-static const char TOPIC_PROFILE_CHANGE[] = "profile-before-change";
-static const char TOPIC_PLACES_CONNECTION_CLOSED[] = "places-connection-closed";
-
-class WaitForConnectionClosed final : public nsIObserver
-{
- RefPtr<WaitForTopicSpinner> mSpinner;
-
- ~WaitForConnectionClosed() {}
-
-public:
- NS_DECL_ISUPPORTS
-
- WaitForConnectionClosed()
- {
- nsCOMPtr<nsIObserverService> os =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- MOZ_ASSERT(os);
- if (os) {
- MOZ_ALWAYS_SUCCEEDS(os->AddObserver(this, TOPIC_PROFILE_CHANGE, false));
- }
- mSpinner = new WaitForTopicSpinner(TOPIC_PLACES_CONNECTION_CLOSED);
- }
-
- NS_IMETHOD Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData) override
- {
- nsCOMPtr<nsIObserverService> os =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- MOZ_ASSERT(os);
- if (os) {
- MOZ_ALWAYS_SUCCEEDS(os->RemoveObserver(this, aTopic));
- }
-
- mSpinner->Spin();
-
- return NS_OK;
- }
-};
-
-NS_IMPL_ISUPPORTS(WaitForConnectionClosed, nsIObserver)
diff --git a/toolkit/components/places/tests/cpp/places_test_harness_tail.h b/toolkit/components/places/tests/cpp/places_test_harness_tail.h
deleted file mode 100644
index 9e57c3724..000000000
--- a/toolkit/components/places/tests/cpp/places_test_harness_tail.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsWidgetsCID.h"
-#include "nsIComponentRegistrar.h"
-
-#ifndef TEST_NAME
-#error "Must #define TEST_NAME before including places_test_harness_tail.h"
-#endif
-
-#ifndef TEST_FILE
-#error "Must #define TEST_FILE before include places_test_harness_tail.h"
-#endif
-
-int gTestsIndex = 0;
-
-#define TEST_INFO_STR "TEST-INFO | (%s) | "
-
-class RunNextTest : public mozilla::Runnable
-{
-public:
- NS_IMETHOD Run() override
- {
- NS_ASSERTION(NS_IsMainThread(), "Not running on the main thread?");
- if (gTestsIndex < int(mozilla::ArrayLength(gTests))) {
- do_test_pending();
- Test &test = gTests[gTestsIndex++];
- (void)fprintf(stderr, TEST_INFO_STR "Running %s.\n", TEST_FILE,
- test.name);
- test.func();
- }
-
- do_test_finished();
- return NS_OK;
- }
-};
-
-void
-run_next_test()
-{
- nsCOMPtr<nsIRunnable> event = new RunNextTest();
- do_check_success(NS_DispatchToCurrentThread(event));
-}
-
-int gPendingTests = 0;
-
-void
-do_test_pending()
-{
- NS_ASSERTION(NS_IsMainThread(), "Not running on the main thread?");
- gPendingTests++;
-}
-
-void
-do_test_finished()
-{
- NS_ASSERTION(NS_IsMainThread(), "Not running on the main thread?");
- NS_ASSERTION(gPendingTests > 0, "Invalid pending test count!");
- gPendingTests--;
-}
-
-void
-disable_idle_service()
-{
- (void)fprintf(stderr, TEST_INFO_STR "Disabling Idle Service.\n", TEST_FILE);
- static NS_DEFINE_IID(kIdleCID, NS_IDLE_SERVICE_CID);
- nsresult rv;
- nsCOMPtr<nsIFactory> idleFactory = do_GetClassObject(kIdleCID, &rv);
- do_check_success(rv);
- nsCOMPtr<nsIComponentRegistrar> registrar;
- rv = NS_GetComponentRegistrar(getter_AddRefs(registrar));
- do_check_success(rv);
- rv = registrar->UnregisterFactory(kIdleCID, idleFactory);
- do_check_success(rv);
-}
-
-int
-main(int aArgc,
- char** aArgv)
-{
- ScopedXPCOM xpcom(TEST_NAME);
- if (xpcom.failed())
- return -1;
- // Initialize a profile folder to ensure a clean shutdown.
- nsCOMPtr<nsIFile> profile = xpcom.GetProfileDirectory();
- if (!profile) {
- fail("Couldn't get the profile directory.");
- return -1;
- }
-
- RefPtr<WaitForConnectionClosed> spinClose = new WaitForConnectionClosed();
-
- // Tinderboxes are constantly on idle. Since idle tasks can interact with
- // tests, causing random failures, disable the idle service.
- disable_idle_service();
-
- do_test_pending();
- run_next_test();
-
- // Spin the event loop until we've run out of tests to run.
- while (gPendingTests) {
- (void)NS_ProcessNextEvent();
- }
-
- // And let any other events finish before we quit.
- (void)NS_ProcessPendingEvents(nullptr);
-
- // Check that we have passed all of our tests, and output accordingly.
- if (gPassedTests == gTotalTests) {
- passed(TEST_FILE);
- }
-
- (void)fprintf(stderr, TEST_INFO_STR "%u of %u tests passed\n",
- TEST_FILE, unsigned(gPassedTests), unsigned(gTotalTests));
-
- return gPassedTests == gTotalTests ? 0 : -1;
-}
diff --git a/toolkit/components/places/tests/cpp/test_IHistory.cpp b/toolkit/components/places/tests/cpp/test_IHistory.cpp
deleted file mode 100644
index 90998ce8c..000000000
--- a/toolkit/components/places/tests/cpp/test_IHistory.cpp
+++ /dev/null
@@ -1,639 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "places_test_harness.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch.h"
-#include "mozilla/Attributes.h"
-#include "nsNetUtil.h"
-
-#include "mock_Link.h"
-using namespace mozilla;
-using namespace mozilla::dom;
-
-/**
- * This file tests the IHistory interface.
- */
-
-////////////////////////////////////////////////////////////////////////////////
-//// Helper Methods
-
-void
-expect_visit(nsLinkState aState)
-{
- do_check_true(aState == eLinkState_Visited);
-}
-
-void
-expect_no_visit(nsLinkState aState)
-{
- do_check_true(aState == eLinkState_Unvisited);
-}
-
-already_AddRefed<nsIURI>
-new_test_uri()
-{
- // Create a unique spec.
- static int32_t specNumber = 0;
- nsAutoCString spec = NS_LITERAL_CSTRING("http://mozilla.org/");
- spec.AppendInt(specNumber++);
-
- // Create the URI for the spec.
- nsCOMPtr<nsIURI> testURI;
- nsresult rv = NS_NewURI(getter_AddRefs(testURI), spec);
- do_check_success(rv);
- return testURI.forget();
-}
-
-class VisitURIObserver final : public nsIObserver
-{
- ~VisitURIObserver() {}
-
-public:
- NS_DECL_ISUPPORTS
-
- explicit VisitURIObserver(int aExpectedVisits = 1) :
- mVisits(0),
- mExpectedVisits(aExpectedVisits)
- {
- nsCOMPtr<nsIObserverService> observerService =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- do_check_true(observerService);
- (void)observerService->AddObserver(this,
- "uri-visit-saved",
- false);
- }
-
- void WaitForNotification()
- {
- while (mVisits < mExpectedVisits) {
- (void)NS_ProcessNextEvent();
- }
- }
-
- NS_IMETHOD Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData) override
- {
- mVisits++;
-
- if (mVisits == mExpectedVisits) {
- nsCOMPtr<nsIObserverService> observerService =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- (void)observerService->RemoveObserver(this, "uri-visit-saved");
- }
-
- return NS_OK;
- }
-private:
- int mVisits;
- int mExpectedVisits;
-};
-NS_IMPL_ISUPPORTS(
- VisitURIObserver,
- nsIObserver
-)
-
-////////////////////////////////////////////////////////////////////////////////
-//// Test Functions
-
-void
-test_set_places_enabled()
-{
- // Ensure places is enabled for everyone.
- nsresult rv;
- nsCOMPtr<nsIPrefBranch> prefBranch =
- do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
- do_check_success(rv);
-
- rv = prefBranch->SetBoolPref("places.history.enabled", true);
- do_check_success(rv);
-
- // Run the next test.
- run_next_test();
-}
-
-
-void
-test_wait_checkpoint()
-{
- // This "fake" test is here to wait for the initial WAL checkpoint we force
- // after creating the database schema, since that may happen at any time,
- // and cause concurrent readers to access an older checkpoint.
- nsCOMPtr<mozIStorageConnection> db = do_get_db();
- nsCOMPtr<mozIStorageAsyncStatement> stmt;
- db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT 1"),
- getter_AddRefs(stmt));
- RefPtr<AsyncStatementSpinner> spinner = new AsyncStatementSpinner();
- nsCOMPtr<mozIStoragePendingStatement> pending;
- (void)stmt->ExecuteAsync(spinner, getter_AddRefs(pending));
- spinner->SpinUntilCompleted();
-
- // Run the next test.
- run_next_test();
-}
-
-// These variables are shared between part 1 and part 2 of the test. Part 2
-// sets the nsCOMPtr's to nullptr, freeing the reference.
-namespace test_unvisited_does_not_notify {
- nsCOMPtr<nsIURI> testURI;
- RefPtr<Link> testLink;
-} // namespace test_unvisited_does_not_notify
-void
-test_unvisited_does_not_notify_part1()
-{
- using namespace test_unvisited_does_not_notify;
-
- // This test is done in two parts. The first part registers for a URI that
- // should not be visited. We then run another test that will also do a
- // lookup and will be notified. Since requests are answered in the order they
- // are requested (at least as long as the same URI isn't asked for later), we
- // will know that the Link was not notified.
-
- // First, we need a test URI.
- testURI = new_test_uri();
-
- // Create our test Link.
- testLink = new mock_Link(expect_no_visit);
-
- // Now, register our Link to be notified.
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->RegisterVisitedCallback(testURI, testLink);
- do_check_success(rv);
-
- // Run the next test.
- run_next_test();
-}
-
-void
-test_visited_notifies()
-{
- // First, we add our test URI to history.
- nsCOMPtr<nsIURI> testURI = new_test_uri();
- addURI(testURI);
-
- // Create our test Link. The callback function will release the reference we
- // have on the Link.
- RefPtr<Link> link = new mock_Link(expect_visit);
-
- // Now, register our Link to be notified.
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->RegisterVisitedCallback(testURI, link);
- do_check_success(rv);
-
- // Note: test will continue upon notification.
-}
-
-void
-test_unvisited_does_not_notify_part2()
-{
- using namespace test_unvisited_does_not_notify;
-
- // We would have had a failure at this point had the content node been told it
- // was visited. Therefore, it is safe to unregister our content node.
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->UnregisterVisitedCallback(testURI, testLink);
- do_check_success(rv);
-
- // Clear the stored variables now.
- testURI = nullptr;
- testLink = nullptr;
-
- // Run the next test.
- run_next_test();
-}
-
-void
-test_same_uri_notifies_both()
-{
- // First, we add our test URI to history.
- nsCOMPtr<nsIURI> testURI = new_test_uri();
- addURI(testURI);
-
- // Create our two test Links. The callback function will release the
- // reference we have on the Links. Only the second Link should run the next
- // test!
- RefPtr<Link> link1 = new mock_Link(expect_visit, false);
- RefPtr<Link> link2 = new mock_Link(expect_visit);
-
- // Now, register our Link to be notified.
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->RegisterVisitedCallback(testURI, link1);
- do_check_success(rv);
- rv = history->RegisterVisitedCallback(testURI, link2);
- do_check_success(rv);
-
- // Note: test will continue upon notification.
-}
-
-void
-test_unregistered_visited_does_not_notify()
-{
- // This test must have a test that has a successful notification after it.
- // The Link would have been notified by now if we were buggy and notified
- // unregistered Links (due to request serialization).
-
- nsCOMPtr<nsIURI> testURI = new_test_uri();
- RefPtr<Link> link = new mock_Link(expect_no_visit);
-
- // Now, register our Link to be notified.
- nsCOMPtr<IHistory> history(do_get_IHistory());
- nsresult rv = history->RegisterVisitedCallback(testURI, link);
- do_check_success(rv);
-
- // Unregister the Link.
- rv = history->UnregisterVisitedCallback(testURI, link);
- do_check_success(rv);
-
- // And finally add a visit for the URI.
- addURI(testURI);
-
- // If history tries to notify us, we'll either crash because the Link will
- // have been deleted (we are the only thing holding a reference to it), or our
- // expect_no_visit call back will produce a failure. Either way, the test
- // will be reported as a failure.
-
- // Run the next test.
- run_next_test();
-}
-
-void
-test_new_visit_notifies_waiting_Link()
-{
- // Create our test Link. The callback function will release the reference we
- // have on the link.
- RefPtr<Link> link = new mock_Link(expect_visit);
-
- // Now, register our content node to be notified.
- nsCOMPtr<nsIURI> testURI = new_test_uri();
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->RegisterVisitedCallback(testURI, link);
- do_check_success(rv);
-
- // Add ourselves to history.
- addURI(testURI);
-
- // Note: test will continue upon notification.
-}
-
-void
-test_RegisterVisitedCallback_returns_before_notifying()
-{
- // Add a URI so that it's already in history.
- nsCOMPtr<nsIURI> testURI = new_test_uri();
- addURI(testURI);
-
- // Create our test Link.
- RefPtr<Link> link = new mock_Link(expect_no_visit);
-
- // Now, register our content node to be notified. It should not be notified.
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->RegisterVisitedCallback(testURI, link);
- do_check_success(rv);
-
- // Remove ourselves as an observer. We would have failed if we had been
- // notified.
- rv = history->UnregisterVisitedCallback(testURI, link);
- do_check_success(rv);
-
- run_next_test();
-}
-
-namespace test_observer_topic_dispatched_helpers {
- #define URI_VISITED "visited"
- #define URI_NOT_VISITED "not visited"
- #define URI_VISITED_RESOLUTION_TOPIC "visited-status-resolution"
- class statusObserver final : public nsIObserver
- {
- ~statusObserver() {}
-
- public:
- NS_DECL_ISUPPORTS
-
- statusObserver(nsIURI* aURI,
- const bool aExpectVisit,
- bool& _notified)
- : mURI(aURI)
- , mExpectVisit(aExpectVisit)
- , mNotified(_notified)
- {
- nsCOMPtr<nsIObserverService> observerService =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- do_check_true(observerService);
- (void)observerService->AddObserver(this,
- URI_VISITED_RESOLUTION_TOPIC,
- false);
- }
-
- NS_IMETHOD Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData) override
- {
- // Make sure we got notified of the right topic.
- do_check_false(strcmp(aTopic, URI_VISITED_RESOLUTION_TOPIC));
-
- // If this isn't for our URI, do not do anything.
- nsCOMPtr<nsIURI> notifiedURI = do_QueryInterface(aSubject);
- do_check_true(notifiedURI);
-
- bool isOurURI;
- nsresult rv = notifiedURI->Equals(mURI, &isOurURI);
- do_check_success(rv);
- if (!isOurURI) {
- return NS_OK;
- }
-
- // Check that we have either the visited or not visited string.
- bool visited = !!NS_LITERAL_STRING(URI_VISITED).Equals(aData);
- bool notVisited = !!NS_LITERAL_STRING(URI_NOT_VISITED).Equals(aData);
- do_check_true(visited || notVisited);
-
- // Check to make sure we got the state we expected.
- do_check_eq(visited, mExpectVisit);
-
- // Indicate that we've been notified.
- mNotified = true;
-
- // Remove ourselves as an observer.
- nsCOMPtr<nsIObserverService> observerService =
- do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
- (void)observerService->RemoveObserver(this,
- URI_VISITED_RESOLUTION_TOPIC);
- return NS_OK;
- }
- private:
- nsCOMPtr<nsIURI> mURI;
- const bool mExpectVisit;
- bool& mNotified;
- };
- NS_IMPL_ISUPPORTS(
- statusObserver,
- nsIObserver
- )
-} // namespace test_observer_topic_dispatched_helpers
-void
-test_observer_topic_dispatched()
-{
- using namespace test_observer_topic_dispatched_helpers;
-
- // Create two URIs, making sure only one is in history.
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
- nsCOMPtr<nsIURI> notVisitedURI = new_test_uri();
- bool urisEqual;
- nsresult rv = visitedURI->Equals(notVisitedURI, &urisEqual);
- do_check_success(rv);
- do_check_false(urisEqual);
- addURI(visitedURI);
-
- // Need two Link objects as well - one for each URI.
- RefPtr<Link> visitedLink = new mock_Link(expect_visit, false);
- RefPtr<Link> visitedLinkCopy = visitedLink;
- RefPtr<Link> notVisitedLink = new mock_Link(expect_no_visit);
-
- // Add the right observers for the URIs to check results.
- bool visitedNotified = false;
- nsCOMPtr<nsIObserver> visitedObs =
- new statusObserver(visitedURI, true, visitedNotified);
- bool notVisitedNotified = false;
- nsCOMPtr<nsIObserver> unvisitedObs =
- new statusObserver(notVisitedURI, false, notVisitedNotified);
-
- // Register our Links to be notified.
- nsCOMPtr<IHistory> history = do_get_IHistory();
- rv = history->RegisterVisitedCallback(visitedURI, visitedLink);
- do_check_success(rv);
- rv = history->RegisterVisitedCallback(notVisitedURI, notVisitedLink);
- do_check_success(rv);
-
- // Spin the event loop as long as we have not been properly notified.
- while (!visitedNotified || !notVisitedNotified) {
- (void)NS_ProcessNextEvent();
- }
-
- // Unregister our observer that would not have been released.
- rv = history->UnregisterVisitedCallback(notVisitedURI, notVisitedLink);
- do_check_success(rv);
-
- run_next_test();
-}
-
-void
-test_visituri_inserts()
-{
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsCOMPtr<nsIURI> lastURI = new_test_uri();
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
-
- history->VisitURI(visitedURI, lastURI, mozilla::IHistory::TOP_LEVEL);
-
- RefPtr<VisitURIObserver> finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- PlaceRecord place;
- do_get_place(visitedURI, place);
-
- do_check_true(place.id > 0);
- do_check_false(place.hidden);
- do_check_false(place.typed);
- do_check_eq(place.visitCount, 1);
-
- run_next_test();
-}
-
-void
-test_visituri_updates()
-{
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsCOMPtr<nsIURI> lastURI = new_test_uri();
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
- RefPtr<VisitURIObserver> finisher;
-
- history->VisitURI(visitedURI, lastURI, mozilla::IHistory::TOP_LEVEL);
- finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- history->VisitURI(visitedURI, lastURI, mozilla::IHistory::TOP_LEVEL);
- finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- PlaceRecord place;
- do_get_place(visitedURI, place);
-
- do_check_eq(place.visitCount, 2);
-
- run_next_test();
-}
-
-void
-test_visituri_preserves_shown_and_typed()
-{
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsCOMPtr<nsIURI> lastURI = new_test_uri();
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
-
- history->VisitURI(visitedURI, lastURI, mozilla::IHistory::TOP_LEVEL);
- // this simulates the uri visit happening in a frame. Normally frame
- // transitions would be hidden unless it was previously loaded top-level
- history->VisitURI(visitedURI, lastURI, 0);
-
- RefPtr<VisitURIObserver> finisher = new VisitURIObserver(2);
- finisher->WaitForNotification();
-
- PlaceRecord place;
- do_get_place(visitedURI, place);
- do_check_false(place.hidden);
-
- run_next_test();
-}
-
-void
-test_visituri_creates_visit()
-{
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsCOMPtr<nsIURI> lastURI = new_test_uri();
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
-
- history->VisitURI(visitedURI, lastURI, mozilla::IHistory::TOP_LEVEL);
- RefPtr<VisitURIObserver> finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- PlaceRecord place;
- VisitRecord visit;
- do_get_place(visitedURI, place);
- do_get_lastVisit(place.id, visit);
-
- do_check_true(visit.id > 0);
- do_check_eq(visit.lastVisitId, 0);
- do_check_eq(visit.transitionType, nsINavHistoryService::TRANSITION_LINK);
-
- run_next_test();
-}
-
-void
-test_visituri_transition_typed()
-{
- nsCOMPtr<nsINavHistoryService> navHistory = do_get_NavHistory();
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsCOMPtr<nsIURI> lastURI = new_test_uri();
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
-
- navHistory->MarkPageAsTyped(visitedURI);
- history->VisitURI(visitedURI, lastURI, mozilla::IHistory::TOP_LEVEL);
- RefPtr<VisitURIObserver> finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- PlaceRecord place;
- VisitRecord visit;
- do_get_place(visitedURI, place);
- do_get_lastVisit(place.id, visit);
-
- do_check_true(visit.transitionType == nsINavHistoryService::TRANSITION_TYPED);
-
- run_next_test();
-}
-
-void
-test_visituri_transition_embed()
-{
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsCOMPtr<nsIURI> lastURI = new_test_uri();
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
-
- history->VisitURI(visitedURI, lastURI, 0);
- RefPtr<VisitURIObserver> finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- PlaceRecord place;
- VisitRecord visit;
- do_get_place(visitedURI, place);
- do_get_lastVisit(place.id, visit);
-
- do_check_eq(place.id, 0);
- do_check_eq(visit.id, 0);
-
- run_next_test();
-}
-
-void
-test_new_visit_adds_place_guid()
-{
- // First, add a visit and wait. This will also add a place.
- nsCOMPtr<nsIURI> visitedURI = new_test_uri();
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->VisitURI(visitedURI, nullptr,
- mozilla::IHistory::TOP_LEVEL);
- do_check_success(rv);
- RefPtr<VisitURIObserver> finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- // Check that we have a guid for our visit.
- PlaceRecord place;
- do_get_place(visitedURI, place);
- do_check_eq(place.visitCount, 1);
- do_check_eq(place.guid.Length(), 12);
-
- run_next_test();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//// IPC-only Tests
-
-void
-test_two_null_links_same_uri()
-{
- // Tests that we do not crash when we have had two nullptr Links passed to
- // RegisterVisitedCallback and then the visit occurs (bug 607469). This only
- // happens in IPC builds.
- nsCOMPtr<nsIURI> testURI = new_test_uri();
-
- nsCOMPtr<IHistory> history = do_get_IHistory();
- nsresult rv = history->RegisterVisitedCallback(testURI, nullptr);
- do_check_success(rv);
- rv = history->RegisterVisitedCallback(testURI, nullptr);
- do_check_success(rv);
-
- rv = history->VisitURI(testURI, nullptr, mozilla::IHistory::TOP_LEVEL);
- do_check_success(rv);
-
- RefPtr<VisitURIObserver> finisher = new VisitURIObserver();
- finisher->WaitForNotification();
-
- run_next_test();
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//// Test Harness
-
-/**
- * Note: for tests marked "Order Important!", please see the test for details.
- */
-Test gTests[] = {
- TEST(test_set_places_enabled), // Must come first!
- TEST(test_wait_checkpoint), // Must come second!
- TEST(test_unvisited_does_not_notify_part1), // Order Important!
- TEST(test_visited_notifies),
- TEST(test_unvisited_does_not_notify_part2), // Order Important!
- TEST(test_same_uri_notifies_both),
- TEST(test_unregistered_visited_does_not_notify), // Order Important!
- TEST(test_new_visit_notifies_waiting_Link),
- TEST(test_RegisterVisitedCallback_returns_before_notifying),
- TEST(test_observer_topic_dispatched),
- TEST(test_visituri_inserts),
- TEST(test_visituri_updates),
- TEST(test_visituri_preserves_shown_and_typed),
- TEST(test_visituri_creates_visit),
- TEST(test_visituri_transition_typed),
- TEST(test_visituri_transition_embed),
- TEST(test_new_visit_adds_place_guid),
-
- // The rest of these tests are tests that are only run in IPC builds.
- TEST(test_two_null_links_same_uri),
-};
-
-const char* file = __FILE__;
-#define TEST_NAME "IHistory"
-#define TEST_FILE file
-#include "places_test_harness_tail.h"
diff --git a/toolkit/components/places/tests/expiration/.eslintrc.js b/toolkit/components/places/tests/expiration/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/expiration/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/expiration/head_expiration.js b/toolkit/components/places/tests/expiration/head_expiration.js
deleted file mode 100644
index 2be4af307..000000000
--- a/toolkit/components/places/tests/expiration/head_expiration.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
-
-
-// Simulates an expiration at shutdown.
-function shutdownExpiration()
-{
- let expire = Cc["@mozilla.org/places/expiration;1"].getService(Ci.nsIObserver);
- expire.observe(null, "places-will-close-connection", null);
-}
-
-
-/**
- * Causes expiration component to start, otherwise it would wait for the first
- * history notification.
- */
-function force_expiration_start() {
- Cc["@mozilla.org/places/expiration;1"]
- .getService(Ci.nsIObserver)
- .observe(null, "testing-mode", null);
-}
-
-
-/**
- * Forces an expiration run.
- *
- * @param [optional] aLimit
- * Limit for the expiration. Pass -1 for unlimited.
- * Any other non-positive value will just expire orphans.
- *
- * @return {Promise}
- * @resolves When expiration finishes.
- * @rejects Never.
- */
-function promiseForceExpirationStep(aLimit) {
- let promise = promiseTopicObserved(PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- let expire = Cc["@mozilla.org/places/expiration;1"].getService(Ci.nsIObserver);
- expire.observe(null, "places-debug-start-expiration", aLimit);
- return promise;
-}
-
-
-/**
- * Expiration preferences helpers.
- */
-
-function setInterval(aNewInterval) {
- Services.prefs.setIntPref("places.history.expiration.interval_seconds", aNewInterval);
-}
-function getInterval() {
- return Services.prefs.getIntPref("places.history.expiration.interval_seconds");
-}
-function clearInterval() {
- try {
- Services.prefs.clearUserPref("places.history.expiration.interval_seconds");
- }
- catch (ex) {}
-}
-
-
-function setMaxPages(aNewMaxPages) {
- Services.prefs.setIntPref("places.history.expiration.max_pages", aNewMaxPages);
-}
-function getMaxPages() {
- return Services.prefs.getIntPref("places.history.expiration.max_pages");
-}
-function clearMaxPages() {
- try {
- Services.prefs.clearUserPref("places.history.expiration.max_pages");
- }
- catch (ex) {}
-}
-
-
-function setHistoryEnabled(aHistoryEnabled) {
- Services.prefs.setBoolPref("places.history.enabled", aHistoryEnabled);
-}
-function getHistoryEnabled() {
- return Services.prefs.getBoolPref("places.history.enabled");
-}
-function clearHistoryEnabled() {
- try {
- Services.prefs.clearUserPref("places.history.enabled");
- }
- catch (ex) {}
-}
-
-/**
- * Returns a PRTime in the past usable to add expirable visits.
- *
- * param [optional] daysAgo
- * Expiration ignores any visit added in the last 7 days, so by default
- * this will be set to 7.
- * @note to be safe against DST issues we go back one day more.
- */
-function getExpirablePRTime(daysAgo = 7) {
- let dateObj = new Date();
- // Normalize to midnight
- dateObj.setHours(0);
- dateObj.setMinutes(0);
- dateObj.setSeconds(0);
- dateObj.setMilliseconds(0);
- dateObj = new Date(dateObj.getTime() - (daysAgo + 1) * 86400000);
- return dateObj.getTime() * 1000;
-}
diff --git a/toolkit/components/places/tests/expiration/test_analyze_runs.js b/toolkit/components/places/tests/expiration/test_analyze_runs.js
deleted file mode 100644
index 1a84e1b38..000000000
--- a/toolkit/components/places/tests/expiration/test_analyze_runs.js
+++ /dev/null
@@ -1,118 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Constants
-
-const TOPIC_AUTOCOMPLETE_FEEDBACK_INCOMING = "autocomplete-will-enter-text";
-
-// Helpers
-
-/**
- * Ensures that we have no data in the tables created by ANALYZE.
- */
-function clearAnalyzeData() {
- let db = DBConn();
- if (!db.tableExists("sqlite_stat1")) {
- return;
- }
- db.executeSimpleSQL("DELETE FROM sqlite_stat1");
-}
-
-/**
- * Checks that we ran ANALYZE on the specified table.
- *
- * @param aTableName
- * The table to check if ANALYZE was ran.
- * @param aRan
- * True if it was expected to run, false otherwise
- */
-function do_check_analyze_ran(aTableName, aRan) {
- let db = DBConn();
- do_check_true(db.tableExists("sqlite_stat1"));
- let stmt = db.createStatement("SELECT idx FROM sqlite_stat1 WHERE tbl = :table");
- stmt.params.table = aTableName;
- try {
- if (aRan) {
- do_check_true(stmt.executeStep());
- do_check_neq(stmt.row.idx, null);
- }
- else {
- do_check_false(stmt.executeStep());
- }
- }
- finally {
- stmt.finalize();
- }
-}
-
-// Tests
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* init_tests() {
- const TEST_URI = NetUtil.newURI("http://mozilla.org/");
- const TEST_TITLE = "This is a test";
-
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: TEST_TITLE,
- url: TEST_URI
- });
- yield PlacesTestUtils.addVisits(TEST_URI);
- let thing = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput,
- Ci.nsIAutoCompletePopup,
- Ci.nsIAutoCompleteController]),
- get popup() { return thing; },
- get controller() { return thing; },
- popupOpen: true,
- selectedIndex: 0,
- getValueAt: function() { return TEST_URI.spec; },
- searchString: TEST_TITLE,
- };
- Services.obs.notifyObservers(thing, TOPIC_AUTOCOMPLETE_FEEDBACK_INCOMING,
- null);
-});
-
-add_task(function* test_timed() {
- clearAnalyzeData();
-
- // Set a low interval and wait for the timed expiration to start.
- let promise = promiseTopicObserved(PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- setInterval(3);
- yield promise;
- setInterval(3600);
-
- do_check_analyze_ran("moz_places", false);
- do_check_analyze_ran("moz_bookmarks", false);
- do_check_analyze_ran("moz_historyvisits", false);
- do_check_analyze_ran("moz_inputhistory", true);
-});
-
-add_task(function* test_debug() {
- clearAnalyzeData();
-
- yield promiseForceExpirationStep(1);
-
- do_check_analyze_ran("moz_places", true);
- do_check_analyze_ran("moz_bookmarks", true);
- do_check_analyze_ran("moz_historyvisits", true);
- do_check_analyze_ran("moz_inputhistory", true);
-});
-
-add_task(function* test_clear_history() {
- clearAnalyzeData();
-
- let promise = promiseTopicObserved(PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- let listener = Cc["@mozilla.org/places/expiration;1"]
- .getService(Ci.nsINavHistoryObserver);
- listener.onClearHistory();
- yield promise;
-
- do_check_analyze_ran("moz_places", true);
- do_check_analyze_ran("moz_bookmarks", false);
- do_check_analyze_ran("moz_historyvisits", true);
- do_check_analyze_ran("moz_inputhistory", true);
-});
diff --git a/toolkit/components/places/tests/expiration/test_annos_expire_history.js b/toolkit/components/places/tests/expiration/test_annos_expire_history.js
deleted file mode 100644
index f9568a769..000000000
--- a/toolkit/components/places/tests/expiration/test_annos_expire_history.js
+++ /dev/null
@@ -1,93 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * EXPIRE_WITH_HISTORY annotations should be expired when a page has no more
- * visits, even if the page still exists in the database.
- * This expiration policy is only valid for page annotations.
- */
-
-var as = Cc["@mozilla.org/browser/annotation-service;1"].
- getService(Ci.nsIAnnotationService);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_annos_expire_history() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- // Expire all expirable pages.
- setMaxPages(0);
-
- // Add some visited page and a couple expire with history annotations for each.
- let now = getExpirablePRTime();
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://page_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
- as.setPageAnnotation(pageURI, "page_expire1", "test", 0, as.EXPIRE_WITH_HISTORY);
- as.setPageAnnotation(pageURI, "page_expire2", "test", 0, as.EXPIRE_WITH_HISTORY);
- }
-
- let pages = as.getPagesWithAnnotation("page_expire1");
- do_check_eq(pages.length, 5);
- pages = as.getPagesWithAnnotation("page_expire2");
- do_check_eq(pages.length, 5);
-
- // Add some bookmarked page and a couple session annotations for each.
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://item_anno." + i + ".mozilla.org/");
- // We also add a visit before bookmarking.
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: pageURI,
- title: null
- });
- // Notice we use page annotations here, items annotations can't use this
- // kind of expiration policy.
- as.setPageAnnotation(pageURI, "item_persist1", "test", 0, as.EXPIRE_WITH_HISTORY);
- as.setPageAnnotation(pageURI, "item_persist2", "test", 0, as.EXPIRE_WITH_HISTORY);
- }
-
- let items = as.getPagesWithAnnotation("item_persist1");
- do_check_eq(items.length, 5);
- items = as.getPagesWithAnnotation("item_persist2");
- do_check_eq(items.length, 5);
-
- // Add other visited page and a couple expire with history annotations for each.
- // We won't expire these visits, so the annotations should survive.
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://persist_page_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
- as.setPageAnnotation(pageURI, "page_persist1", "test", 0, as.EXPIRE_WITH_HISTORY);
- as.setPageAnnotation(pageURI, "page_persist2", "test", 0, as.EXPIRE_WITH_HISTORY);
- }
-
- pages = as.getPagesWithAnnotation("page_persist1");
- do_check_eq(pages.length, 5);
- pages = as.getPagesWithAnnotation("page_persist2");
- do_check_eq(pages.length, 5);
-
- // Expire all visits for the first 5 pages and the bookmarks.
- yield promiseForceExpirationStep(10);
-
- pages = as.getPagesWithAnnotation("page_expire1");
- do_check_eq(pages.length, 0);
- pages = as.getPagesWithAnnotation("page_expire2");
- do_check_eq(pages.length, 0);
- items = as.getItemsWithAnnotation("item_persist1");
- do_check_eq(items.length, 0);
- items = as.getItemsWithAnnotation("item_persist2");
- do_check_eq(items.length, 0);
- pages = as.getPagesWithAnnotation("page_persist1");
- do_check_eq(pages.length, 5);
- pages = as.getPagesWithAnnotation("page_persist2");
- do_check_eq(pages.length, 5);
-});
diff --git a/toolkit/components/places/tests/expiration/test_annos_expire_never.js b/toolkit/components/places/tests/expiration/test_annos_expire_never.js
deleted file mode 100644
index f146f25b5..000000000
--- a/toolkit/components/places/tests/expiration/test_annos_expire_never.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * EXPIRE_NEVER annotations should be expired when a page is removed from the
- * database.
- * If the annotation is a page annotation this will happen when the page is
- * expired, namely when the page has no visits and is not bookmarked.
- * Otherwise if it's an item annotation the annotation will be expired when
- * the item is removed, thus expiration won't handle this case at all.
- */
-
-var as = Cc["@mozilla.org/browser/annotation-service;1"].
- getService(Ci.nsIAnnotationService);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_annos_expire_never() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- // Expire all expirable pages.
- setMaxPages(0);
-
- // Add some visited page and a couple expire never annotations for each.
- let now = getExpirablePRTime();
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://page_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
- as.setPageAnnotation(pageURI, "page_expire1", "test", 0, as.EXPIRE_NEVER);
- as.setPageAnnotation(pageURI, "page_expire2", "test", 0, as.EXPIRE_NEVER);
- }
-
- let pages = as.getPagesWithAnnotation("page_expire1");
- do_check_eq(pages.length, 5);
- pages = as.getPagesWithAnnotation("page_expire2");
- do_check_eq(pages.length, 5);
-
- // Add some bookmarked page and a couple expire never annotations for each.
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://item_anno." + i + ".mozilla.org/");
- // We also add a visit before bookmarking.
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: pageURI,
- title: null
- });
- let id = yield PlacesUtils.promiseItemId(bm.guid);
- as.setItemAnnotation(id, "item_persist1", "test", 0, as.EXPIRE_NEVER);
- as.setItemAnnotation(id, "item_persist2", "test", 0, as.EXPIRE_NEVER);
- }
-
- let items = as.getItemsWithAnnotation("item_persist1");
- do_check_eq(items.length, 5);
- items = as.getItemsWithAnnotation("item_persist2");
- do_check_eq(items.length, 5);
-
- // Add other visited page and a couple expire never annotations for each.
- // We won't expire these visits, so the annotations should survive.
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://persist_page_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
- as.setPageAnnotation(pageURI, "page_persist1", "test", 0, as.EXPIRE_NEVER);
- as.setPageAnnotation(pageURI, "page_persist2", "test", 0, as.EXPIRE_NEVER);
- }
-
- pages = as.getPagesWithAnnotation("page_persist1");
- do_check_eq(pages.length, 5);
- pages = as.getPagesWithAnnotation("page_persist2");
- do_check_eq(pages.length, 5);
-
- // Expire all visits for the first 5 pages and the bookmarks.
- yield promiseForceExpirationStep(10);
-
- pages = as.getPagesWithAnnotation("page_expire1");
- do_check_eq(pages.length, 0);
- pages = as.getPagesWithAnnotation("page_expire2");
- do_check_eq(pages.length, 0);
- items = as.getItemsWithAnnotation("item_persist1");
- do_check_eq(items.length, 5);
- items = as.getItemsWithAnnotation("item_persist2");
- do_check_eq(items.length, 5);
- pages = as.getPagesWithAnnotation("page_persist1");
- do_check_eq(pages.length, 5);
- pages = as.getPagesWithAnnotation("page_persist2");
- do_check_eq(pages.length, 5);
-});
diff --git a/toolkit/components/places/tests/expiration/test_annos_expire_policy.js b/toolkit/components/places/tests/expiration/test_annos_expire_policy.js
deleted file mode 100644
index 2fe50e13e..000000000
--- a/toolkit/components/places/tests/expiration/test_annos_expire_policy.js
+++ /dev/null
@@ -1,189 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * Annotations can be set with a timed expiration policy.
- * Supported policies are:
- * - EXPIRE_DAYS: annotation would be expired after 7 days
- * - EXPIRE_WEEKS: annotation would be expired after 30 days
- * - EXPIRE_MONTHS: annotation would be expired after 180 days
- */
-
-var as = Cc["@mozilla.org/browser/annotation-service;1"].
- getService(Ci.nsIAnnotationService);
-
-/**
- * Creates an aged annotation.
- *
- * @param aIdentifier Either a page url or an item id.
- * @param aIdentifier Name of the annotation.
- * @param aValue Value for the annotation.
- * @param aExpirePolicy Expiration policy of the annotation.
- * @param aAgeInDays Age in days of the annotation.
- * @param [optional] aLastModifiedAgeInDays Age in days of the annotation, for lastModified.
- */
-var now = Date.now();
-function add_old_anno(aIdentifier, aName, aValue, aExpirePolicy,
- aAgeInDays, aLastModifiedAgeInDays) {
- let expireDate = (now - (aAgeInDays * 86400 * 1000)) * 1000;
- let lastModifiedDate = 0;
- if (aLastModifiedAgeInDays)
- lastModifiedDate = (now - (aLastModifiedAgeInDays * 86400 * 1000)) * 1000;
-
- let sql;
- if (typeof(aIdentifier) == "number") {
- // Item annotation.
- as.setItemAnnotation(aIdentifier, aName, aValue, 0, aExpirePolicy);
- // Update dateAdded for the last added annotation.
- sql = "UPDATE moz_items_annos SET dateAdded = :expire_date, lastModified = :last_modified " +
- "WHERE id = (SELECT id FROM moz_items_annos " +
- "WHERE item_id = :id " +
- "ORDER BY dateAdded DESC LIMIT 1)";
- }
- else if (aIdentifier instanceof Ci.nsIURI) {
- // Page annotation.
- as.setPageAnnotation(aIdentifier, aName, aValue, 0, aExpirePolicy);
- // Update dateAdded for the last added annotation.
- sql = "UPDATE moz_annos SET dateAdded = :expire_date, lastModified = :last_modified " +
- "WHERE id = (SELECT a.id FROM moz_annos a " +
- "LEFT JOIN moz_places h on h.id = a.place_id " +
- "WHERE h.url_hash = hash(:id) AND h.url = :id " +
- "ORDER BY a.dateAdded DESC LIMIT 1)";
- }
- else
- do_throw("Wrong identifier type");
-
- let stmt = DBConn().createStatement(sql);
- stmt.params.id = (typeof(aIdentifier) == "number") ? aIdentifier
- : aIdentifier.spec;
- stmt.params.expire_date = expireDate;
- stmt.params.last_modified = lastModifiedDate;
- try {
- stmt.executeStep();
- }
- finally {
- stmt.finalize();
- }
-}
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_annos_expire_policy() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- // Expire all expirable pages.
- setMaxPages(0);
-
- let now_specific_to_test = getExpirablePRTime();
- // Add some bookmarked page and timed annotations for each.
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://item_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now_specific_to_test++ });
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: pageURI,
- title: null
- });
- let id = yield PlacesUtils.promiseItemId(bm.guid);
- // Add a 6 days old anno.
- add_old_anno(id, "persist_days", "test", as.EXPIRE_DAYS, 6);
- // Add a 8 days old anno, modified 5 days ago.
- add_old_anno(id, "persist_lm_days", "test", as.EXPIRE_DAYS, 8, 6);
- // Add a 8 days old anno.
- add_old_anno(id, "expire_days", "test", as.EXPIRE_DAYS, 8);
-
- // Add a 29 days old anno.
- add_old_anno(id, "persist_weeks", "test", as.EXPIRE_WEEKS, 29);
- // Add a 31 days old anno, modified 29 days ago.
- add_old_anno(id, "persist_lm_weeks", "test", as.EXPIRE_WEEKS, 31, 29);
- // Add a 31 days old anno.
- add_old_anno(id, "expire_weeks", "test", as.EXPIRE_WEEKS, 31);
-
- // Add a 179 days old anno.
- add_old_anno(id, "persist_months", "test", as.EXPIRE_MONTHS, 179);
- // Add a 181 days old anno, modified 179 days ago.
- add_old_anno(id, "persist_lm_months", "test", as.EXPIRE_MONTHS, 181, 179);
- // Add a 181 days old anno.
- add_old_anno(id, "expire_months", "test", as.EXPIRE_MONTHS, 181);
-
- // Add a 6 days old anno.
- add_old_anno(pageURI, "persist_days", "test", as.EXPIRE_DAYS, 6);
- // Add a 8 days old anno, modified 5 days ago.
- add_old_anno(pageURI, "persist_lm_days", "test", as.EXPIRE_DAYS, 8, 6);
- // Add a 8 days old anno.
- add_old_anno(pageURI, "expire_days", "test", as.EXPIRE_DAYS, 8);
-
- // Add a 29 days old anno.
- add_old_anno(pageURI, "persist_weeks", "test", as.EXPIRE_WEEKS, 29);
- // Add a 31 days old anno, modified 29 days ago.
- add_old_anno(pageURI, "persist_lm_weeks", "test", as.EXPIRE_WEEKS, 31, 29);
- // Add a 31 days old anno.
- add_old_anno(pageURI, "expire_weeks", "test", as.EXPIRE_WEEKS, 31);
-
- // Add a 179 days old anno.
- add_old_anno(pageURI, "persist_months", "test", as.EXPIRE_MONTHS, 179);
- // Add a 181 days old anno, modified 179 days ago.
- add_old_anno(pageURI, "persist_lm_months", "test", as.EXPIRE_MONTHS, 181, 179);
- // Add a 181 days old anno.
- add_old_anno(pageURI, "expire_months", "test", as.EXPIRE_MONTHS, 181);
- }
-
- // Add some visited page and timed annotations for each.
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://page_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now_specific_to_test++ });
- // Add a 6 days old anno.
- add_old_anno(pageURI, "persist_days", "test", as.EXPIRE_DAYS, 6);
- // Add a 8 days old anno, modified 5 days ago.
- add_old_anno(pageURI, "persist_lm_days", "test", as.EXPIRE_DAYS, 8, 6);
- // Add a 8 days old anno.
- add_old_anno(pageURI, "expire_days", "test", as.EXPIRE_DAYS, 8);
-
- // Add a 29 days old anno.
- add_old_anno(pageURI, "persist_weeks", "test", as.EXPIRE_WEEKS, 29);
- // Add a 31 days old anno, modified 29 days ago.
- add_old_anno(pageURI, "persist_lm_weeks", "test", as.EXPIRE_WEEKS, 31, 29);
- // Add a 31 days old anno.
- add_old_anno(pageURI, "expire_weeks", "test", as.EXPIRE_WEEKS, 31);
-
- // Add a 179 days old anno.
- add_old_anno(pageURI, "persist_months", "test", as.EXPIRE_MONTHS, 179);
- // Add a 181 days old anno, modified 179 days ago.
- add_old_anno(pageURI, "persist_lm_months", "test", as.EXPIRE_MONTHS, 181, 179);
- // Add a 181 days old anno.
- add_old_anno(pageURI, "expire_months", "test", as.EXPIRE_MONTHS, 181);
- }
-
- // Expire all visits for the bookmarks.
- yield promiseForceExpirationStep(5);
-
- ["expire_days", "expire_weeks", "expire_months"].forEach(function(aAnno) {
- let pages = as.getPagesWithAnnotation(aAnno);
- do_check_eq(pages.length, 0);
- });
-
- ["expire_days", "expire_weeks", "expire_months"].forEach(function(aAnno) {
- let items = as.getItemsWithAnnotation(aAnno);
- do_check_eq(items.length, 0);
- });
-
- ["persist_days", "persist_lm_days", "persist_weeks", "persist_lm_weeks",
- "persist_months", "persist_lm_months"].forEach(function(aAnno) {
- let pages = as.getPagesWithAnnotation(aAnno);
- do_check_eq(pages.length, 10);
- });
-
- ["persist_days", "persist_lm_days", "persist_weeks", "persist_lm_weeks",
- "persist_months", "persist_lm_months"].forEach(function(aAnno) {
- let items = as.getItemsWithAnnotation(aAnno);
- do_check_eq(items.length, 5);
- });
-});
diff --git a/toolkit/components/places/tests/expiration/test_annos_expire_session.js b/toolkit/components/places/tests/expiration/test_annos_expire_session.js
deleted file mode 100644
index 68c995f80..000000000
--- a/toolkit/components/places/tests/expiration/test_annos_expire_session.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * Session annotations should be expired when browsing session ends.
- */
-
-var as = Cc["@mozilla.org/browser/annotation-service;1"].
- getService(Ci.nsIAnnotationService);
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_annos_expire_session() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- // Add some visited page and a couple session annotations for each.
- let now = Date.now() * 1000;
- for (let i = 0; i < 10; i++) {
- let pageURI = uri("http://session_page_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI, visitDate: now++ });
- as.setPageAnnotation(pageURI, "test1", "test", 0, as.EXPIRE_SESSION);
- as.setPageAnnotation(pageURI, "test2", "test", 0, as.EXPIRE_SESSION);
- }
-
- // Add some bookmarked page and a couple session annotations for each.
- for (let i = 0; i < 10; i++) {
- let pageURI = uri("http://session_item_anno." + i + ".mozilla.org/");
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: pageURI,
- title: null
- });
- let id = yield PlacesUtils.promiseItemId(bm.guid);
- as.setItemAnnotation(id, "test1", "test", 0, as.EXPIRE_SESSION);
- as.setItemAnnotation(id, "test2", "test", 0, as.EXPIRE_SESSION);
- }
-
-
- let pages = as.getPagesWithAnnotation("test1");
- do_check_eq(pages.length, 10);
- pages = as.getPagesWithAnnotation("test2");
- do_check_eq(pages.length, 10);
- let items = as.getItemsWithAnnotation("test1");
- do_check_eq(items.length, 10);
- items = as.getItemsWithAnnotation("test2");
- do_check_eq(items.length, 10);
-
- let deferred = Promise.defer();
- waitForConnectionClosed(function() {
- let stmt = DBConn(true).createAsyncStatement(
- `SELECT id FROM moz_annos
- UNION ALL
- SELECT id FROM moz_items_annos
- WHERE expiration = :expiration`
- );
- stmt.params.expiration = as.EXPIRE_SESSION;
- stmt.executeAsync({
- handleResult: function(aResultSet) {
- dump_table("moz_annos");
- dump_table("moz_items_annos");
- do_throw("Should not find any leftover session annotations");
- },
- handleError: function(aError) {
- do_throw("Error code " + aError.result + " with message '" +
- aError.message + "' returned.");
- },
- handleCompletion: function(aReason) {
- do_check_eq(aReason, Ci.mozIStorageStatementCallback.REASON_FINISHED);
- deferred.resolve();
- }
- });
- stmt.finalize();
- });
- yield deferred.promise;
-});
diff --git a/toolkit/components/places/tests/expiration/test_clearHistory.js b/toolkit/components/places/tests/expiration/test_clearHistory.js
deleted file mode 100644
index d3879d7ad..000000000
--- a/toolkit/components/places/tests/expiration/test_clearHistory.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * History.clear() should expire everything but bookmarked pages and valid
- * annos.
- */
-
-var hs = PlacesUtils.history;
-var as = PlacesUtils.annotations;
-
-/**
- * Creates an aged annotation.
- *
- * @param aIdentifier Either a page url or an item id.
- * @param aIdentifier Name of the annotation.
- * @param aValue Value for the annotation.
- * @param aExpirePolicy Expiration policy of the annotation.
- * @param aAgeInDays Age in days of the annotation.
- * @param [optional] aLastModifiedAgeInDays Age in days of the annotation, for lastModified.
- */
-var now = Date.now();
-function add_old_anno(aIdentifier, aName, aValue, aExpirePolicy,
- aAgeInDays, aLastModifiedAgeInDays) {
- let expireDate = (now - (aAgeInDays * 86400 * 1000)) * 1000;
- let lastModifiedDate = 0;
- if (aLastModifiedAgeInDays)
- lastModifiedDate = (now - (aLastModifiedAgeInDays * 86400 * 1000)) * 1000;
-
- let sql;
- if (typeof(aIdentifier) == "number") {
- // Item annotation.
- as.setItemAnnotation(aIdentifier, aName, aValue, 0, aExpirePolicy);
- // Update dateAdded for the last added annotation.
- sql = "UPDATE moz_items_annos SET dateAdded = :expire_date, lastModified = :last_modified " +
- "WHERE id = ( " +
- "SELECT a.id FROM moz_items_annos a " +
- "JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id " +
- "WHERE a.item_id = :id " +
- "AND n.name = :anno_name " +
- "ORDER BY a.dateAdded DESC LIMIT 1 " +
- ")";
- }
- else if (aIdentifier instanceof Ci.nsIURI) {
- // Page annotation.
- as.setPageAnnotation(aIdentifier, aName, aValue, 0, aExpirePolicy);
- // Update dateAdded for the last added annotation.
- sql = "UPDATE moz_annos SET dateAdded = :expire_date, lastModified = :last_modified " +
- "WHERE id = ( " +
- "SELECT a.id FROM moz_annos a " +
- "JOIN moz_anno_attributes n ON n.id = a.anno_attribute_id " +
- "JOIN moz_places h on h.id = a.place_id " +
- "WHERE h.url_hash = hash(:id) AND h.url = :id " +
- "AND n.name = :anno_name " +
- "ORDER BY a.dateAdded DESC LIMIT 1 " +
- ")";
- }
- else
- do_throw("Wrong identifier type");
-
- let stmt = DBConn().createStatement(sql);
- stmt.params.id = (typeof(aIdentifier) == "number") ? aIdentifier
- : aIdentifier.spec;
- stmt.params.expire_date = expireDate;
- stmt.params.last_modified = lastModifiedDate;
- stmt.params.anno_name = aName;
- try {
- stmt.executeStep();
- }
- finally {
- stmt.finalize();
- }
-}
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_historyClear() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- // Expire all expirable pages.
- setMaxPages(0);
-
- // Add some bookmarked page with visit and annotations.
- for (let i = 0; i < 5; i++) {
- let pageURI = uri("http://item_anno." + i + ".mozilla.org/");
- // This visit will be expired.
- yield PlacesTestUtils.addVisits({ uri: pageURI });
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: pageURI,
- title: null
- });
- let id = yield PlacesUtils.promiseItemId(bm.guid);
- // Will persist because it's an EXPIRE_NEVER item anno.
- as.setItemAnnotation(id, "persist", "test", 0, as.EXPIRE_NEVER);
- // Will persist because the page is bookmarked.
- as.setPageAnnotation(pageURI, "persist", "test", 0, as.EXPIRE_NEVER);
- // All EXPIRE_SESSION annotations are expected to expire on clear history.
- as.setItemAnnotation(id, "expire_session", "test", 0, as.EXPIRE_SESSION);
- as.setPageAnnotation(pageURI, "expire_session", "test", 0, as.EXPIRE_SESSION);
- // Annotations with timed policy will expire regardless bookmarked status.
- add_old_anno(id, "expire_days", "test", as.EXPIRE_DAYS, 8);
- add_old_anno(id, "expire_weeks", "test", as.EXPIRE_WEEKS, 31);
- add_old_anno(id, "expire_months", "test", as.EXPIRE_MONTHS, 181);
- add_old_anno(pageURI, "expire_days", "test", as.EXPIRE_DAYS, 8);
- add_old_anno(pageURI, "expire_weeks", "test", as.EXPIRE_WEEKS, 31);
- add_old_anno(pageURI, "expire_months", "test", as.EXPIRE_MONTHS, 181);
- }
-
- // Add some visited page and annotations for each.
- for (let i = 0; i < 5; i++) {
- // All page annotations related to these expired pages are expected to
- // expire as well.
- let pageURI = uri("http://page_anno." + i + ".mozilla.org/");
- yield PlacesTestUtils.addVisits({ uri: pageURI });
- as.setPageAnnotation(pageURI, "expire", "test", 0, as.EXPIRE_NEVER);
- as.setPageAnnotation(pageURI, "expire_session", "test", 0, as.EXPIRE_SESSION);
- add_old_anno(pageURI, "expire_days", "test", as.EXPIRE_DAYS, 8);
- add_old_anno(pageURI, "expire_weeks", "test", as.EXPIRE_WEEKS, 31);
- add_old_anno(pageURI, "expire_months", "test", as.EXPIRE_MONTHS, 181);
- }
-
- // Expire all visits for the bookmarks
- yield PlacesUtils.history.clear();
-
- ["expire_days", "expire_weeks", "expire_months", "expire_session",
- "expire"].forEach(function(aAnno) {
- let pages = as.getPagesWithAnnotation(aAnno);
- do_check_eq(pages.length, 0);
- });
-
- ["expire_days", "expire_weeks", "expire_months", "expire_session",
- "expire"].forEach(function(aAnno) {
- let items = as.getItemsWithAnnotation(aAnno);
- do_check_eq(items.length, 0);
- });
-
- let pages = as.getPagesWithAnnotation("persist");
- do_check_eq(pages.length, 5);
-
- let items = as.getItemsWithAnnotation("persist");
- do_check_eq(items.length, 5);
-
- for (let itemId of items) {
- // Check item exists.
- let guid = yield PlacesUtils.promiseItemGuid(itemId);
- do_check_true((yield PlacesUtils.bookmarks.fetch({guid})), "item exists");
- }
-});
diff --git a/toolkit/components/places/tests/expiration/test_debug_expiration.js b/toolkit/components/places/tests/expiration/test_debug_expiration.js
deleted file mode 100644
index 456c03363..000000000
--- a/toolkit/components/places/tests/expiration/test_debug_expiration.js
+++ /dev/null
@@ -1,225 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * What this is aimed to test:
- *
- * Expiration can be manually triggered through a debug topic, but that should
- * only expire orphan entries, unless -1 is passed as limit.
- */
-
-var gNow = getExpirablePRTime(60);
-
-add_task(function* test_expire_orphans()
-{
- // Add visits to 2 pages and force a orphan expiration. Visits should survive.
- yield PlacesTestUtils.addVisits({
- uri: uri("http://page1.mozilla.org/"),
- visitDate: gNow++
- });
- yield PlacesTestUtils.addVisits({
- uri: uri("http://page2.mozilla.org/"),
- visitDate: gNow++
- });
- // Create a orphan place.
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://page3.mozilla.org/",
- title: ""
- });
- yield PlacesUtils.bookmarks.remove(bm);
-
- // Expire now.
- yield promiseForceExpirationStep(0);
-
- // Check that visits survived.
- do_check_eq(visits_in_database("http://page1.mozilla.org/"), 1);
- do_check_eq(visits_in_database("http://page2.mozilla.org/"), 1);
- do_check_false(page_in_database("http://page3.mozilla.org/"));
-
- // Clean up.
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_expire_orphans_optionalarg()
-{
- // Add visits to 2 pages and force a orphan expiration. Visits should survive.
- yield PlacesTestUtils.addVisits({
- uri: uri("http://page1.mozilla.org/"),
- visitDate: gNow++
- });
- yield PlacesTestUtils.addVisits({
- uri: uri("http://page2.mozilla.org/"),
- visitDate: gNow++
- });
- // Create a orphan place.
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "http://page3.mozilla.org/",
- title: ""
- });
- yield PlacesUtils.bookmarks.remove(bm);
-
- // Expire now.
- yield promiseForceExpirationStep();
-
- // Check that visits survived.
- do_check_eq(visits_in_database("http://page1.mozilla.org/"), 1);
- do_check_eq(visits_in_database("http://page2.mozilla.org/"), 1);
- do_check_false(page_in_database("http://page3.mozilla.org/"));
-
- // Clean up.
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_expire_limited()
-{
- yield PlacesTestUtils.addVisits([
- { // Should be expired cause it's the oldest visit
- uri: "http://old.mozilla.org/",
- visitDate: gNow++
- },
- { // Should not be expired cause we limit 1
- uri: "http://new.mozilla.org/",
- visitDate: gNow++
- },
- ]);
-
- // Expire now.
- yield promiseForceExpirationStep(1);
-
- // Check that newer visit survived.
- do_check_eq(visits_in_database("http://new.mozilla.org/"), 1);
- // Other visits should have been expired.
- do_check_false(page_in_database("http://old.mozilla.org/"));
-
- // Clean up.
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_expire_limited_longurl()
-{
- let longurl = "http://long.mozilla.org/" + "a".repeat(232);
- yield PlacesTestUtils.addVisits([
- { // Should be expired cause it's the oldest visit
- uri: "http://old.mozilla.org/",
- visitDate: gNow++
- },
- { // Should be expired cause it's a long url older than 60 days.
- uri: longurl,
- visitDate: gNow++
- },
- { // Should not be expired cause younger than 60 days.
- uri: longurl,
- visitDate: getExpirablePRTime(58)
- }
- ]);
-
- yield promiseForceExpirationStep(1);
-
- // Check that some visits survived.
- do_check_eq(visits_in_database(longurl), 1);
- // Other visits should have been expired.
- do_check_false(page_in_database("http://old.mozilla.org/"));
-
- // Clean up.
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_expire_limited_exoticurl()
-{
- yield PlacesTestUtils.addVisits([
- { // Should be expired cause it's the oldest visit
- uri: "http://old.mozilla.org/",
- visitDate: gNow++
- },
- { // Should be expired cause it's a long url older than 60 days.
- uri: "http://download.mozilla.org",
- visitDate: gNow++,
- transition: 7
- },
- { // Should not be expired cause younger than 60 days.
- uri: "http://nonexpirable-download.mozilla.org",
- visitDate: getExpirablePRTime(58),
- transition: 7
- }
- ]);
-
- yield promiseForceExpirationStep(1);
-
- // Check that some visits survived.
- do_check_eq(visits_in_database("http://nonexpirable-download.mozilla.org/"), 1);
- // The visits are gone, the url is not yet, cause we limited the expiration
- // to one entry, and we already removed http://old.mozilla.org/.
- // The page normally would be expired by the next expiration run.
- do_check_eq(visits_in_database("http://download.mozilla.org/"), 0);
- // Other visits should have been expired.
- do_check_false(page_in_database("http://old.mozilla.org/"));
-
- // Clean up.
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_expire_unlimited()
-{
- let longurl = "http://long.mozilla.org/" + "a".repeat(232);
- yield PlacesTestUtils.addVisits([
- {
- uri: "http://old.mozilla.org/",
- visitDate: gNow++
- },
- {
- uri: "http://new.mozilla.org/",
- visitDate: gNow++
- },
- // Add expirable visits.
- {
- uri: "http://download.mozilla.org/",
- visitDate: gNow++,
- transition: PlacesUtils.history.TRANSITION_DOWNLOAD
- },
- {
- uri: longurl,
- visitDate: gNow++
- },
-
- // Add non-expirable visits
- {
- uri: "http://nonexpirable.mozilla.org/",
- visitDate: getExpirablePRTime(5)
- },
- {
- uri: "http://nonexpirable-download.mozilla.org/",
- visitDate: getExpirablePRTime(5),
- transition: PlacesUtils.history.TRANSITION_DOWNLOAD
- },
- {
- uri: longurl,
- visitDate: getExpirablePRTime(5)
- }
- ]);
-
- yield promiseForceExpirationStep(-1);
-
- // Check that some visits survived.
- do_check_eq(visits_in_database("http://nonexpirable.mozilla.org/"), 1);
- do_check_eq(visits_in_database("http://nonexpirable-download.mozilla.org/"), 1);
- do_check_eq(visits_in_database(longurl), 1);
- // Other visits should have been expired.
- do_check_false(page_in_database("http://old.mozilla.org/"));
- do_check_false(page_in_database("http://download.mozilla.org/"));
- do_check_false(page_in_database("http://new.mozilla.org/"));
-
- // Clean up.
- yield PlacesTestUtils.clearHistory();
-});
-
-function run_test()
-{
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
- // Set maxPages to a low value, so it's easy to go over it.
- setMaxPages(1);
-
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/expiration/test_idle_daily.js b/toolkit/components/places/tests/expiration/test_idle_daily.js
deleted file mode 100644
index 05e5a8125..000000000
--- a/toolkit/components/places/tests/expiration/test_idle_daily.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test that expiration runs on idle-daily.
-
-function run_test() {
- do_test_pending();
-
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- Services.obs.addObserver(function observeExpiration(aSubject, aTopic, aData) {
- Services.obs.removeObserver(observeExpiration,
- PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- do_test_finished();
- }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
-
- let expire = Cc["@mozilla.org/places/expiration;1"].
- getService(Ci.nsIObserver);
- expire.observe(null, "idle-daily", null);
-}
diff --git a/toolkit/components/places/tests/expiration/test_notifications.js b/toolkit/components/places/tests/expiration/test_notifications.js
deleted file mode 100644
index 06e585c6c..000000000
--- a/toolkit/components/places/tests/expiration/test_notifications.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * Ensure that History (through category cache) notifies us just once.
- */
-
-var os = Cc["@mozilla.org/observer-service;1"].
- getService(Ci.nsIObserverService);
-
-var gObserver = {
- notifications: 0,
- observe: function(aSubject, aTopic, aData) {
- this.notifications++;
- }
-};
-os.addObserver(gObserver, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
-
-function run_test() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- PlacesTestUtils.clearHistory();
-
- do_timeout(2000, check_result);
- do_test_pending();
-}
-
-function check_result() {
- os.removeObserver(gObserver, PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- do_check_eq(gObserver.notifications, 1);
- do_test_finished();
-}
diff --git a/toolkit/components/places/tests/expiration/test_notifications_onDeleteURI.js b/toolkit/components/places/tests/expiration/test_notifications_onDeleteURI.js
deleted file mode 100644
index f70cd2b58..000000000
--- a/toolkit/components/places/tests/expiration/test_notifications_onDeleteURI.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * Expiring a full page should fire an onDeleteURI notification.
- */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-var tests = [
-
- { desc: "Add 1 bookmarked page.",
- addPages: 1,
- addBookmarks: 1,
- expectedNotifications: 0, // No expirable pages.
- },
-
- { desc: "Add 2 pages, 1 bookmarked.",
- addPages: 2,
- addBookmarks: 1,
- expectedNotifications: 1, // Only one expirable page.
- },
-
- { desc: "Add 10 pages, none bookmarked.",
- addPages: 10,
- addBookmarks: 0,
- expectedNotifications: 10, // Will expire everything.
- },
-
- { desc: "Add 10 pages, all bookmarked.",
- addPages: 10,
- addBookmarks: 10,
- expectedNotifications: 0, // No expirable pages.
- },
-
-];
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_notifications_onDeleteURI() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- // Expire anything that is expirable.
- setMaxPages(0);
-
- for (let testIndex = 1; testIndex <= tests.length; testIndex++) {
- let currentTest = tests[testIndex -1];
- print("\nTEST " + testIndex + ": " + currentTest.desc);
- currentTest.receivedNotifications = 0;
-
- // Setup visits.
- let now = getExpirablePRTime();
- for (let i = 0; i < currentTest.addPages; i++) {
- let page = "http://" + testIndex + "." + i + ".mozilla.org/";
- yield PlacesTestUtils.addVisits({ uri: uri(page), visitDate: now++ });
- }
-
- // Setup bookmarks.
- currentTest.bookmarks = [];
- for (let i = 0; i < currentTest.addBookmarks; i++) {
- let page = "http://" + testIndex + "." + i + ".mozilla.org/";
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: null,
- url: page
- });
- currentTest.bookmarks.push(page);
- }
-
- // Observe history.
- historyObserver = {
- onBeginUpdateBatch: function PEX_onBeginUpdateBatch() {},
- onEndUpdateBatch: function PEX_onEndUpdateBatch() {},
- onClearHistory: function() {},
- onVisit: function() {},
- onTitleChanged: function() {},
- onDeleteURI: function(aURI, aGUID, aReason) {
- currentTest.receivedNotifications++;
- // Check this uri was not bookmarked.
- do_check_eq(currentTest.bookmarks.indexOf(aURI.spec), -1);
- do_check_valid_places_guid(aGUID);
- do_check_eq(aReason, Ci.nsINavHistoryObserver.REASON_EXPIRED);
- },
- onPageChanged: function() {},
- onDeleteVisits: function(aURI, aTime) { },
- };
- hs.addObserver(historyObserver, false);
-
- // Expire now.
- yield promiseForceExpirationStep(-1);
-
- hs.removeObserver(historyObserver, false);
-
- do_check_eq(currentTest.receivedNotifications,
- currentTest.expectedNotifications);
-
- // Clean up.
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
- }
-
- clearMaxPages();
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/expiration/test_notifications_onDeleteVisits.js b/toolkit/components/places/tests/expiration/test_notifications_onDeleteVisits.js
deleted file mode 100644
index e6b99ff8b..000000000
--- a/toolkit/components/places/tests/expiration/test_notifications_onDeleteVisits.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * Expiring only visits for a page, but not the full page, should fire an
- * onDeleteVisits notification.
- */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-var tests = [
-
- { desc: "Add 1 bookmarked page.",
- addPages: 1,
- visitsPerPage: 1,
- addBookmarks: 1,
- limitExpiration: -1,
- expectedNotifications: 1, // Will expire visits for 1 page.
- },
-
- { desc: "Add 2 pages, 1 bookmarked.",
- addPages: 2,
- visitsPerPage: 1,
- addBookmarks: 1,
- limitExpiration: -1,
- expectedNotifications: 1, // Will expire visits for 1 page.
- },
-
- { desc: "Add 10 pages, none bookmarked.",
- addPages: 10,
- visitsPerPage: 1,
- addBookmarks: 0,
- limitExpiration: -1,
- expectedNotifications: 0, // Will expire only full pages.
- },
-
- { desc: "Add 10 pages, all bookmarked.",
- addPages: 10,
- visitsPerPage: 1,
- addBookmarks: 10,
- limitExpiration: -1,
- expectedNotifications: 10, // Will expire visist for all pages.
- },
-
- { desc: "Add 10 pages with lot of visits, none bookmarked.",
- addPages: 10,
- visitsPerPage: 10,
- addBookmarks: 0,
- limitExpiration: 10,
- expectedNotifications: 10, // Will expire 1 visist for each page, but won't
- }, // expire pages since they still have visits.
-
-];
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_notifications_onDeleteVisits() {
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- // Expire anything that is expirable.
- setMaxPages(0);
-
- for (let testIndex = 1; testIndex <= tests.length; testIndex++) {
- let currentTest = tests[testIndex -1];
- print("\nTEST " + testIndex + ": " + currentTest.desc);
- currentTest.receivedNotifications = 0;
-
- // Setup visits.
- let timeInMicroseconds = getExpirablePRTime(8);
-
- function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds + 1000;
- return timeInMicroseconds;
- }
-
- for (let j = 0; j < currentTest.visitsPerPage; j++) {
- for (let i = 0; i < currentTest.addPages; i++) {
- let page = "http://" + testIndex + "." + i + ".mozilla.org/";
- yield PlacesTestUtils.addVisits({ uri: uri(page), visitDate: newTimeInMicroseconds() });
- }
- }
-
- // Setup bookmarks.
- currentTest.bookmarks = [];
- for (let i = 0; i < currentTest.addBookmarks; i++) {
- let page = "http://" + testIndex + "." + i + ".mozilla.org/";
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: null,
- url: page
- });
- currentTest.bookmarks.push(page);
- }
-
- // Observe history.
- historyObserver = {
- onBeginUpdateBatch: function PEX_onBeginUpdateBatch() {},
- onEndUpdateBatch: function PEX_onEndUpdateBatch() {},
- onClearHistory: function() {},
- onVisit: function() {},
- onTitleChanged: function() {},
- onDeleteURI: function(aURI, aGUID, aReason) {
- // Check this uri was not bookmarked.
- do_check_eq(currentTest.bookmarks.indexOf(aURI.spec), -1);
- do_check_valid_places_guid(aGUID);
- do_check_eq(aReason, Ci.nsINavHistoryObserver.REASON_EXPIRED);
- },
- onPageChanged: function() {},
- onDeleteVisits: function(aURI, aTime, aGUID, aReason) {
- currentTest.receivedNotifications++;
- do_check_guid_for_uri(aURI, aGUID);
- do_check_eq(aReason, Ci.nsINavHistoryObserver.REASON_EXPIRED);
- },
- };
- hs.addObserver(historyObserver, false);
-
- // Expire now.
- yield promiseForceExpirationStep(currentTest.limitExpiration);
-
- hs.removeObserver(historyObserver, false);
-
- do_check_eq(currentTest.receivedNotifications,
- currentTest.expectedNotifications);
-
- // Clean up.
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
- }
-
- clearMaxPages();
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/expiration/test_outdated_analyze.js b/toolkit/components/places/tests/expiration/test_outdated_analyze.js
deleted file mode 100644
index 9cf61f06b..000000000
--- a/toolkit/components/places/tests/expiration/test_outdated_analyze.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test that expiration executes ANALYZE when statistics are outdated.
-
-const TEST_URL = "http://www.mozilla.org/";
-
-XPCOMUtils.defineLazyServiceGetter(this, "gHistory",
- "@mozilla.org/browser/history;1",
- "mozIAsyncHistory");
-
-/**
- * Object that represents a mozIVisitInfo object.
- *
- * @param [optional] aTransitionType
- * The transition type of the visit. Defaults to TRANSITION_LINK if not
- * provided.
- * @param [optional] aVisitTime
- * The time of the visit. Defaults to now if not provided.
- */
-function VisitInfo(aTransitionType, aVisitTime) {
- this.transitionType =
- aTransitionType === undefined ? TRANSITION_LINK : aTransitionType;
- this.visitDate = aVisitTime || Date.now() * 1000;
-}
-
-function run_test() {
- do_test_pending();
-
- // Init expiration before "importing".
- force_expiration_start();
-
- // Add a bunch of pages (at laast IMPORT_PAGES_THRESHOLD pages).
- let places = [];
- for (let i = 0; i < 100; i++) {
- places.push({
- uri: NetUtil.newURI(TEST_URL + i),
- title: "Title" + i,
- visits: [new VisitInfo]
- });
- }
- gHistory.updatePlaces(places);
-
- // Set interval to a small value to expire on it.
- setInterval(1); // 1s
-
- Services.obs.addObserver(function observeExpiration(aSubject, aTopic, aData) {
- Services.obs.removeObserver(observeExpiration,
- PlacesUtils.TOPIC_EXPIRATION_FINISHED);
-
- // Check that statistica are up-to-date.
- let stmt = DBConn().createAsyncStatement(
- "SELECT (SELECT COUNT(*) FROM moz_places) - "
- + "(SELECT SUBSTR(stat,1,LENGTH(stat)-2) FROM sqlite_stat1 "
- + "WHERE idx = 'moz_places_url_hashindex')"
- );
- stmt.executeAsync({
- handleResult: function(aResultSet) {
- let row = aResultSet.getNextRow();
- this._difference = row.getResultByIndex(0);
- },
- handleError: function(aError) {
- do_throw("Unexpected error (" + aError.result + "): " + aError.message);
- },
- handleCompletion: function(aReason) {
- do_check_true(this._difference === 0);
- do_test_finished();
- }
- });
- stmt.finalize();
- }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false);
-}
diff --git a/toolkit/components/places/tests/expiration/test_pref_interval.js b/toolkit/components/places/tests/expiration/test_pref_interval.js
deleted file mode 100644
index 44c749d7a..000000000
--- a/toolkit/components/places/tests/expiration/test_pref_interval.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * What this is aimed to test:
- *
- * Expiration relies on an interval, that is user-preffable setting
- * "places.history.expiration.interval_seconds".
- * On pref change it will stop current interval timer and fire a new one,
- * that will obey the new value.
- * If the pref is set to a number <= 0 we will use the default value.
- */
-
-// Default timer value for expiration in seconds. Must have same value as
-// PREF_INTERVAL_SECONDS_NOTSET in nsPlacesExpiration.
-const DEFAULT_TIMER_DELAY_SECONDS = 3 * 60;
-
-// Sync this with the const value in the component.
-const EXPIRE_AGGRESSIVITY_MULTIPLIER = 3;
-
-var tests = [
-
- // This test should be the first, so the interval won't be influenced by
- // status of history.
- { desc: "Set interval to 1s.",
- interval: 1,
- expectedTimerDelay: 1
- },
-
- { desc: "Set interval to a negative value.",
- interval: -1,
- expectedTimerDelay: DEFAULT_TIMER_DELAY_SECONDS
- },
-
- { desc: "Set interval to 0.",
- interval: 0,
- expectedTimerDelay: DEFAULT_TIMER_DELAY_SECONDS
- },
-
- { desc: "Set interval to a large value.",
- interval: 100,
- expectedTimerDelay: 100
- },
-
-];
-
-add_task(function* test() {
- // The pref should not exist by default.
- Assert.throws(() => getInterval());
-
- // Force the component, so it will start observing preferences.
- force_expiration_start();
-
- for (let currentTest of tests) {
- print(currentTest.desc);
- let promise = promiseTopicObserved("test-interval-changed");
- setInterval(currentTest.interval);
- let [, data] = yield promise;
- Assert.equal(data, currentTest.expectedTimerDelay * EXPIRE_AGGRESSIVITY_MULTIPLIER);
- }
-
- clearInterval();
-});
-
diff --git a/toolkit/components/places/tests/expiration/test_pref_maxpages.js b/toolkit/components/places/tests/expiration/test_pref_maxpages.js
deleted file mode 100644
index 6a237afbb..000000000
--- a/toolkit/components/places/tests/expiration/test_pref_maxpages.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * What this is aimed to test:
- *
- * Expiration will obey to hardware spec, but user can set a custom maximum
- * number of pages to retain, to restrict history, through
- * "places.history.expiration.max_pages".
- * This limit is used at next expiration run.
- * If the pref is set to a number < 0 we will use the default value.
- */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-var tests = [
-
- { desc: "Set max_pages to a negative value, with 1 page.",
- maxPages: -1,
- addPages: 1,
- expectedNotifications: 0, // Will ignore and won't expire anything.
- },
-
- { desc: "Set max_pages to 0.",
- maxPages: 0,
- addPages: 1,
- expectedNotifications: 1,
- },
-
- { desc: "Set max_pages to 0, with 2 pages.",
- maxPages: 0,
- addPages: 2,
- expectedNotifications: 2, // Will expire everything.
- },
-
- // Notice if we are over limit we do a full step of expiration. So we ensure
- // that we will expire if we are over the limit, but we don't ensure that we
- // will expire exactly up to the limit. Thus in this case we expire
- // everything.
- { desc: "Set max_pages to 1 with 2 pages.",
- maxPages: 1,
- addPages: 2,
- expectedNotifications: 2, // Will expire everything (in this case).
- },
-
- { desc: "Set max_pages to 10, with 9 pages.",
- maxPages: 10,
- addPages: 9,
- expectedNotifications: 0, // We are at the limit, won't expire anything.
- },
-
- { desc: "Set max_pages to 10 with 10 pages.",
- maxPages: 10,
- addPages: 10,
- expectedNotifications: 0, // We are below the limit, won't expire anything.
- },
-];
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_pref_maxpages() {
- // The pref should not exist by default.
- try {
- getMaxPages();
- do_throw("interval pref should not exist by default");
- }
- catch (ex) {}
-
- // Set interval to a large value so we don't expire on it.
- setInterval(3600); // 1h
-
- for (let testIndex = 1; testIndex <= tests.length; testIndex++) {
- let currentTest = tests[testIndex -1];
- print("\nTEST " + testIndex + ": " + currentTest.desc);
- currentTest.receivedNotifications = 0;
-
- // Setup visits.
- let now = getExpirablePRTime();
- for (let i = 0; i < currentTest.addPages; i++) {
- let page = "http://" + testIndex + "." + i + ".mozilla.org/";
- yield PlacesTestUtils.addVisits({ uri: uri(page), visitDate: now++ });
- }
-
- // Observe history.
- let historyObserver = {
- onBeginUpdateBatch: function PEX_onBeginUpdateBatch() {},
- onEndUpdateBatch: function PEX_onEndUpdateBatch() {},
- onClearHistory: function() {},
- onVisit: function() {},
- onTitleChanged: function() {},
- onDeleteURI: function(aURI) {
- print("onDeleteURI " + aURI.spec);
- currentTest.receivedNotifications++;
- },
- onPageChanged: function() {},
- onDeleteVisits: function(aURI, aTime) {
- print("onDeleteVisits " + aURI.spec + " " + aTime);
- },
- };
- hs.addObserver(historyObserver, false);
-
- setMaxPages(currentTest.maxPages);
-
- // Expire now.
- yield promiseForceExpirationStep(-1);
-
- hs.removeObserver(historyObserver, false);
-
- do_check_eq(currentTest.receivedNotifications,
- currentTest.expectedNotifications);
-
- // Clean up.
- yield PlacesTestUtils.clearHistory();
- }
-
- clearMaxPages();
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/expiration/xpcshell.ini b/toolkit/components/places/tests/expiration/xpcshell.ini
deleted file mode 100644
index cda7ac052..000000000
--- a/toolkit/components/places/tests/expiration/xpcshell.ini
+++ /dev/null
@@ -1,22 +0,0 @@
-[DEFAULT]
-head = head_expiration.js
-tail =
-skip-if = toolkit == 'android'
-
-[test_analyze_runs.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_annos_expire_history.js]
-[test_annos_expire_never.js]
-[test_annos_expire_policy.js]
-[test_annos_expire_session.js]
-[test_clearHistory.js]
-[test_debug_expiration.js]
-[test_idle_daily.js]
-[test_notifications.js]
-[test_notifications_onDeleteURI.js]
-[test_notifications_onDeleteVisits.js]
-[test_outdated_analyze.js]
-[test_pref_interval.js]
-[test_pref_maxpages.js]
-skip-if = os == "linux" # bug 1284083
diff --git a/toolkit/components/places/tests/favicons/.eslintrc.js b/toolkit/components/places/tests/favicons/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/favicons/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/favicons/expected-favicon-big32.jpg.png b/toolkit/components/places/tests/favicons/expected-favicon-big32.jpg.png
deleted file mode 100644
index 723008771..000000000
--- a/toolkit/components/places/tests/favicons/expected-favicon-big32.jpg.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/expected-favicon-big4.jpg.png b/toolkit/components/places/tests/favicons/expected-favicon-big4.jpg.png
deleted file mode 100644
index 9932c18fb..000000000
--- a/toolkit/components/places/tests/favicons/expected-favicon-big4.jpg.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/expected-favicon-big48.ico.png b/toolkit/components/places/tests/favicons/expected-favicon-big48.ico.png
deleted file mode 100644
index 9f16bef43..000000000
--- a/toolkit/components/places/tests/favicons/expected-favicon-big48.ico.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/expected-favicon-big64.png.png b/toolkit/components/places/tests/favicons/expected-favicon-big64.png.png
deleted file mode 100644
index ed158d161..000000000
--- a/toolkit/components/places/tests/favicons/expected-favicon-big64.png.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/expected-favicon-scale160x3.jpg.png b/toolkit/components/places/tests/favicons/expected-favicon-scale160x3.jpg.png
deleted file mode 100644
index 585c9e897..000000000
--- a/toolkit/components/places/tests/favicons/expected-favicon-scale160x3.jpg.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/expected-favicon-scale3x160.jpg.png b/toolkit/components/places/tests/favicons/expected-favicon-scale3x160.jpg.png
deleted file mode 100644
index e07dabc79..000000000
--- a/toolkit/components/places/tests/favicons/expected-favicon-scale3x160.jpg.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-big16.ico b/toolkit/components/places/tests/favicons/favicon-big16.ico
deleted file mode 100644
index d44438903..000000000
--- a/toolkit/components/places/tests/favicons/favicon-big16.ico
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-big32.jpg b/toolkit/components/places/tests/favicons/favicon-big32.jpg
deleted file mode 100644
index b2131bf0c..000000000
--- a/toolkit/components/places/tests/favicons/favicon-big32.jpg
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-big4.jpg b/toolkit/components/places/tests/favicons/favicon-big4.jpg
deleted file mode 100644
index b84fcd35a..000000000
--- a/toolkit/components/places/tests/favicons/favicon-big4.jpg
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-big48.ico b/toolkit/components/places/tests/favicons/favicon-big48.ico
deleted file mode 100644
index f22522411..000000000
--- a/toolkit/components/places/tests/favicons/favicon-big48.ico
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-big64.png b/toolkit/components/places/tests/favicons/favicon-big64.png
deleted file mode 100644
index 2756cf0cb..000000000
--- a/toolkit/components/places/tests/favicons/favicon-big64.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-normal16.png b/toolkit/components/places/tests/favicons/favicon-normal16.png
deleted file mode 100644
index 62b69a3d0..000000000
--- a/toolkit/components/places/tests/favicons/favicon-normal16.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-normal32.png b/toolkit/components/places/tests/favicons/favicon-normal32.png
deleted file mode 100644
index 5535363c9..000000000
--- a/toolkit/components/places/tests/favicons/favicon-normal32.png
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-scale160x3.jpg b/toolkit/components/places/tests/favicons/favicon-scale160x3.jpg
deleted file mode 100644
index 422ee7ea0..000000000
--- a/toolkit/components/places/tests/favicons/favicon-scale160x3.jpg
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/favicon-scale3x160.jpg b/toolkit/components/places/tests/favicons/favicon-scale3x160.jpg
deleted file mode 100644
index e8514966a..000000000
--- a/toolkit/components/places/tests/favicons/favicon-scale3x160.jpg
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/favicons/head_favicons.js b/toolkit/components/places/tests/favicons/head_favicons.js
deleted file mode 100644
index cc81791e8..000000000
--- a/toolkit/components/places/tests/favicons/head_favicons.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
-
-
-// This error icon must stay in sync with FAVICON_ERRORPAGE_URL in
-// nsIFaviconService.idl, aboutCertError.xhtml and netError.xhtml.
-const FAVICON_ERRORPAGE_URI =
- NetUtil.newURI("chrome://global/skin/icons/warning-16.png");
-
-/**
- * Waits for the first OnPageChanged notification for ATTRIBUTE_FAVICON, and
- * verifies that it matches the expected page URI and associated favicon URI.
- *
- * This function also double-checks the GUID parameter of the notification.
- *
- * @param aExpectedPageURI
- * nsIURI object of the page whose favicon should change.
- * @param aExpectedFaviconURI
- * nsIURI object of the newly associated favicon.
- * @param aCallback
- * This function is called after the check finished.
- */
-function waitForFaviconChanged(aExpectedPageURI, aExpectedFaviconURI,
- aCallback) {
- let historyObserver = {
- __proto__: NavHistoryObserver.prototype,
- onPageChanged: function WFFC_onPageChanged(aURI, aWhat, aValue, aGUID) {
- if (aWhat != Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON) {
- return;
- }
- PlacesUtils.history.removeObserver(this);
-
- do_check_true(aURI.equals(aExpectedPageURI));
- do_check_eq(aValue, aExpectedFaviconURI.spec);
- do_check_guid_for_uri(aURI, aGUID);
- aCallback();
- }
- };
- PlacesUtils.history.addObserver(historyObserver, false);
-}
-
-/**
- * Checks that the favicon for the given page matches the provided data.
- *
- * @param aPageURI
- * nsIURI object for the page to check.
- * @param aExpectedMimeType
- * Expected MIME type of the icon, for example "image/png".
- * @param aExpectedData
- * Expected icon data, expressed as an array of byte values.
- * @param aCallback
- * This function is called after the check finished.
- */
-function checkFaviconDataForPage(aPageURI, aExpectedMimeType, aExpectedData,
- aCallback) {
- PlacesUtils.favicons.getFaviconDataForPage(aPageURI,
- function (aURI, aDataLen, aData, aMimeType) {
- do_check_eq(aExpectedMimeType, aMimeType);
- do_check_true(compareArrays(aExpectedData, aData));
- do_check_guid_for_uri(aPageURI);
- aCallback();
- });
-}
-
-/**
- * Checks that the given page has no associated favicon.
- *
- * @param aPageURI
- * nsIURI object for the page to check.
- * @param aCallback
- * This function is called after the check finished.
- */
-function checkFaviconMissingForPage(aPageURI, aCallback) {
- PlacesUtils.favicons.getFaviconURLForPage(aPageURI,
- function (aURI, aDataLen, aData, aMimeType) {
- do_check_true(aURI === null);
- aCallback();
- });
-}
-
-function promiseFaviconMissingForPage(aPageURI) {
- return new Promise(resolve => checkFaviconMissingForPage(aPageURI, resolve));
-}
-
-function promiseFaviconChanged(aExpectedPageURI, aExpectedFaviconURI) {
- return new Promise(resolve => waitForFaviconChanged(aExpectedPageURI, aExpectedFaviconURI, resolve));
-}
diff --git a/toolkit/components/places/tests/favicons/test_expireAllFavicons.js b/toolkit/components/places/tests/favicons/test_expireAllFavicons.js
deleted file mode 100644
index c5d8edfdd..000000000
--- a/toolkit/components/places/tests/favicons/test_expireAllFavicons.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * This file tests that favicons are correctly expired by expireAllFavicons.
- */
-
-"use strict";
-
-const TEST_PAGE_URI = NetUtil.newURI("http://example.com/");
-const BOOKMARKED_PAGE_URI = NetUtil.newURI("http://example.com/bookmarked");
-
-add_task(function* test_expireAllFavicons() {
- // Add a visited page.
- yield PlacesTestUtils.addVisits({ uri: TEST_PAGE_URI, transition: TRANSITION_TYPED });
-
- // Set a favicon for our test page.
- yield promiseSetIconForPage(TEST_PAGE_URI, SMALLPNG_DATA_URI);
-
- // Add a page with a bookmark.
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: BOOKMARKED_PAGE_URI,
- title: "Test bookmark"
- });
-
- // Set a favicon for our bookmark.
- yield promiseSetIconForPage(BOOKMARKED_PAGE_URI, SMALLPNG_DATA_URI);
-
- // Start expiration only after data has been saved in the database.
- let promise = promiseTopicObserved(PlacesUtils.TOPIC_FAVICONS_EXPIRED);
- PlacesUtils.favicons.expireAllFavicons();
- yield promise;
-
- // Check that the favicons for the pages we added were removed.
- yield promiseFaviconMissingForPage(TEST_PAGE_URI);
- yield promiseFaviconMissingForPage(BOOKMARKED_PAGE_URI);
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/favicons/test_favicons_conversions.js b/toolkit/components/places/tests/favicons/test_favicons_conversions.js
deleted file mode 100644
index fa0d332ec..000000000
--- a/toolkit/components/places/tests/favicons/test_favicons_conversions.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests the image conversions done by the favicon service.
- */
-
-// Globals
-
-// The pixel values we get on Windows are sometimes +/- 1 value compared to
-// other platforms, so we need to skip some image content tests.
-var isWindows = ("@mozilla.org/windows-registry-key;1" in Cc);
-
-/**
- * Checks the conversion of the given test image file.
- *
- * @param aFileName
- * File that contains the favicon image, located in the test folder.
- * @param aFileMimeType
- * MIME type of the image contained in the file.
- * @param aFileLength
- * Expected length of the file.
- * @param aExpectConversion
- * If false, the icon should be stored as is. If true, the expected data
- * is loaded from a file named "expected-" + aFileName + ".png".
- * @param aVaryOnWindows
- * Indicates that the content of the converted image can be different on
- * Windows and should not be checked on that platform.
- * @param aCallback
- * This function is called after the check finished.
- */
-function checkFaviconDataConversion(aFileName, aFileMimeType, aFileLength,
- aExpectConversion, aVaryOnWindows,
- aCallback) {
- let pageURI = NetUtil.newURI("http://places.test/page/" + aFileName);
- PlacesTestUtils.addVisits({ uri: pageURI, transition: TRANSITION_TYPED }).then(
- function () {
- let faviconURI = NetUtil.newURI("http://places.test/icon/" + aFileName);
- let fileData = readFileOfLength(aFileName, aFileLength);
-
- PlacesUtils.favicons.replaceFaviconData(faviconURI, fileData, fileData.length,
- aFileMimeType);
- PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, faviconURI, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function CFDC_verify(aURI, aDataLen, aData, aMimeType) {
- if (!aExpectConversion) {
- do_check_true(compareArrays(aData, fileData));
- do_check_eq(aMimeType, aFileMimeType);
- } else {
- if (!aVaryOnWindows || !isWindows) {
- let expectedFile = do_get_file("expected-" + aFileName + ".png");
- do_check_true(compareArrays(aData, readFileData(expectedFile)));
- }
- do_check_eq(aMimeType, "image/png");
- }
-
- aCallback();
- }, Services.scriptSecurityManager.getSystemPrincipal());
- });
-}
-
-// Tests
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_storing_a_normal_16x16_icon() {
- // 16x16 png, 286 bytes.
- // optimized: no
- checkFaviconDataConversion("favicon-normal16.png", "image/png", 286,
- false, false, run_next_test);
-});
-
-add_test(function test_storing_a_normal_32x32_icon() {
- // 32x32 png, 344 bytes.
- // optimized: no
- checkFaviconDataConversion("favicon-normal32.png", "image/png", 344,
- false, false, run_next_test);
-});
-
-add_test(function test_storing_a_big_16x16_icon() {
- // in: 16x16 ico, 1406 bytes.
- // optimized: no
- checkFaviconDataConversion("favicon-big16.ico", "image/x-icon", 1406,
- false, false, run_next_test);
-});
-
-add_test(function test_storing_an_oversize_4x4_icon() {
- // in: 4x4 jpg, 4751 bytes.
- // optimized: yes
- checkFaviconDataConversion("favicon-big4.jpg", "image/jpeg", 4751,
- true, false, run_next_test);
-});
-
-add_test(function test_storing_an_oversize_32x32_icon() {
- // in: 32x32 jpg, 3494 bytes.
- // optimized: yes
- checkFaviconDataConversion("favicon-big32.jpg", "image/jpeg", 3494,
- true, true, run_next_test);
-});
-
-add_test(function test_storing_an_oversize_48x48_icon() {
- // in: 48x48 ico, 56646 bytes.
- // (howstuffworks.com icon, contains 13 icons with sizes from 16x16 to
- // 48x48 in varying depths)
- // optimized: yes
- checkFaviconDataConversion("favicon-big48.ico", "image/x-icon", 56646,
- true, false, run_next_test);
-});
-
-add_test(function test_storing_an_oversize_64x64_icon() {
- // in: 64x64 png, 10698 bytes.
- // optimized: yes
- checkFaviconDataConversion("favicon-big64.png", "image/png", 10698,
- true, false, run_next_test);
-});
-
-add_test(function test_scaling_an_oversize_160x3_icon() {
- // in: 160x3 jpg, 5095 bytes.
- // optimized: yes
- checkFaviconDataConversion("favicon-scale160x3.jpg", "image/jpeg", 5095,
- true, false, run_next_test);
-});
-
-add_test(function test_scaling_an_oversize_3x160_icon() {
- // in: 3x160 jpg, 5059 bytes.
- // optimized: yes
- checkFaviconDataConversion("favicon-scale3x160.jpg", "image/jpeg", 5059,
- true, false, run_next_test);
-});
diff --git a/toolkit/components/places/tests/favicons/test_getFaviconDataForPage.js b/toolkit/components/places/tests/favicons/test_getFaviconDataForPage.js
deleted file mode 100644
index 73eea7436..000000000
--- a/toolkit/components/places/tests/favicons/test_getFaviconDataForPage.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests getFaviconDataForPage.
- */
-
-// Globals
-
-const FAVICON_URI = NetUtil.newURI(do_get_file("favicon-normal32.png"));
-const FAVICON_DATA = readFileData(do_get_file("favicon-normal32.png"));
-const FAVICON_MIMETYPE = "image/png";
-
-// Tests
-
-function run_test()
-{
- // Check that the favicon loaded correctly before starting the actual tests.
- do_check_eq(FAVICON_DATA.length, 344);
- run_next_test();
-}
-
-add_test(function test_normal()
-{
- let pageURI = NetUtil.newURI("http://example.com/normal");
-
- PlacesTestUtils.addVisits(pageURI).then(function () {
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- pageURI, FAVICON_URI, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function () {
- PlacesUtils.favicons.getFaviconDataForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
- do_check_true(aURI.equals(FAVICON_URI));
- do_check_eq(FAVICON_DATA.length, aDataLen);
- do_check_true(compareArrays(FAVICON_DATA, aData));
- do_check_eq(FAVICON_MIMETYPE, aMimeType);
- run_next_test();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- });
-});
-
-add_test(function test_missing()
-{
- let pageURI = NetUtil.newURI("http://example.com/missing");
-
- PlacesUtils.favicons.getFaviconDataForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
- // Check also the expected data types.
- do_check_true(aURI === null);
- do_check_true(aDataLen === 0);
- do_check_true(aData.length === 0);
- do_check_true(aMimeType === "");
- run_next_test();
- });
-});
diff --git a/toolkit/components/places/tests/favicons/test_getFaviconURLForPage.js b/toolkit/components/places/tests/favicons/test_getFaviconURLForPage.js
deleted file mode 100644
index fb2e23ff9..000000000
--- a/toolkit/components/places/tests/favicons/test_getFaviconURLForPage.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests getFaviconURLForPage.
- */
-
-// Tests
-
-function run_test()
-{
- run_next_test();
-}
-
-add_test(function test_normal()
-{
- let pageURI = NetUtil.newURI("http://example.com/normal");
-
- PlacesTestUtils.addVisits(pageURI).then(function () {
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- pageURI, SMALLPNG_DATA_URI, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function () {
- PlacesUtils.favicons.getFaviconURLForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
- do_check_true(aURI.equals(SMALLPNG_DATA_URI));
-
- // Check also the expected data types.
- do_check_true(aDataLen === 0);
- do_check_true(aData.length === 0);
- do_check_true(aMimeType === "");
- run_next_test();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- });
-});
-
-add_test(function test_missing()
-{
- let pageURI = NetUtil.newURI("http://example.com/missing");
-
- PlacesUtils.favicons.getFaviconURLForPage(pageURI,
- function (aURI, aDataLen, aData, aMimeType) {
- // Check also the expected data types.
- do_check_true(aURI === null);
- do_check_true(aDataLen === 0);
- do_check_true(aData.length === 0);
- do_check_true(aMimeType === "");
- run_next_test();
- });
-});
diff --git a/toolkit/components/places/tests/favicons/test_moz-anno_favicon_mime_type.js b/toolkit/components/places/tests/favicons/test_moz-anno_favicon_mime_type.js
deleted file mode 100644
index d055d8d61..000000000
--- a/toolkit/components/places/tests/favicons/test_moz-anno_favicon_mime_type.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * This test ensures that the mime type is set for moz-anno channels of favicons
- * properly. Added with work in bug 481227.
- */
-
-// Constants
-Cu.import("resource://gre/modules/NetUtil.jsm");
-
-const testFaviconData = "data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%10%00%00%00%10%08%06%00%00%00%1F%F3%FFa%00%00%00%04gAMA%00%00%AF%C87%05%8A%E9%00%00%00%19tEXtSoftware%00Adobe%20ImageReadyq%C9e%3C%00%00%01%D6IDATx%DAb%FC%FF%FF%3F%03%25%00%20%80%98%909%EF%DF%BFg%EF%EC%EC%FC%AD%AC%AC%FC%DF%95%91%F1%BF%89%89%C9%7F%20%FF%D7%EA%D5%AB%B7%DF%BBwO%16%9B%01%00%01%C4%00r%01%08%9F9s%C6%CD%D8%D8%F8%BF%0B%03%C3%FF3%40%BC%0A%88%EF%02q%1A%10%BB%40%F1%AAU%ABv%C1%D4%C30%40%00%81%89%993g%3E%06%1A%F6%3F%14%AA%11D%97%03%F1%7Fc%08%0D%E2%2B))%FD%17%04%89%A1%19%00%10%40%0C%D00%F8%0F3%00%C8%F8%BF%1B%E4%0Ac%88a%E5%60%17%19%FF%0F%0D%0D%05%1B%02v%D9%DD%BB%0A0%03%00%02%08%AC%B9%A3%A3%E3%17%03%D4v%90%01%EF%18%106%C3%0Cz%07%C5%BB%A1%DE%82y%07%20%80%A0%A6%08B%FCn%0C1%60%26%D4%20d%C3VA%C3%06%26%BE%0A%EA-%80%00%82%B9%E0%F7L4%0D%EF%90%F8%C6%60%2F%0A%82%BD%01%13%07%0700%D0%01%02%88%11%E4%02P%B41%DC%BB%C7%D0%014%0D%E8l%06W%20%06%BA%88%A1%1C%1AS%15%40%7C%16%CA6.%2Fgx%BFg%0F%83%CB%D9%B3%0C%7B%80%7C%80%00%02%BB%00%E8%9F%ED%20%1B%3A%A0%A6%9F%81%DA%DC%01%C5%B0%80%ED%80%FA%BF%BC%BC%FC%3F%83%12%90%9D%96%F6%1F%20%80%18%DE%BD%7B%C7%0E%8E%05AD%20%FEGr%A6%A0%A0%E0%7F%25P%80%02%9D%0F%D28%13%18%23%C6%C0%B0%02E%3D%C8%F5%00%01%04%8F%05P%A8%BA%40my%87%E4%12c%A8%8D%20%8B%D0%D3%00%08%03%04%10%9C%01R%E4%82d%3B%C8%A0%99%C6%90%90%C6%A5%19%84%01%02%08%9E%17%80%C9x%F7%7B%A0%DBVC%F9%A0%C0%5C%7D%16%2C%CE%00%F4%C6O%5C%99%09%20%800L%04y%A5%03%1A%95%A0%80%05%05%14.%DBA%18%20%80%18)%CD%CE%00%01%06%00%0C'%94%C7%C0k%C9%2C%00%00%00%00IEND%AEB%60%82";
-const moz_anno_favicon_prefix = "moz-anno:favicon:";
-
-// streamListener
-
-function streamListener(aExpectedContentType)
-{
- this._expectedContentType = aExpectedContentType;
-}
-streamListener.prototype =
-{
- onStartRequest: function(aRequest, aContext)
- {
- // We have other tests that make sure the data is what we expect. We just
- // need to check the content type here.
- let channel = aRequest.QueryInterface(Ci.nsIChannel);
- dump("*** Checking " + channel.URI.spec + "\n");
- do_check_eq(channel.contentType, this._expectedContentType);
-
- // If we somehow throw before doing the above check, the test will pass, so
- // we do this for extra sanity.
- this._checked = true;
- },
- onStopRequest: function()
- {
- do_check_true(this._checked);
- do_test_finished();
- },
- onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount)
- {
- aRequest.cancel(Cr.NS_ERROR_ABORT);
- }
-};
-
-// Test Runner
-
-function run_test()
-{
- let fs = Cc["@mozilla.org/browser/favicon-service;1"].
- getService(Ci.nsIFaviconService);
-
- // Test that the default icon has the content type of image/png.
- let channel = NetUtil.newChannel({
- uri: fs.defaultFavicon,
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_FAVICON
- });
- channel.asyncOpen2(new streamListener("image/png"));
- do_test_pending();
-
- // Test URI that we don't know anything about. Will end up being the default
- // icon, so expect image/png.
- channel = NetUtil.newChannel({
- uri: moz_anno_favicon_prefix + "http://mozilla.org",
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_FAVICON
- });
- channel.asyncOpen2(new streamListener("image/png"));
- do_test_pending();
-
- // Test that the content type of a favicon we add ends up being image/png.
- let testURI = uri("http://mozilla.org/");
- // Add the data before opening
- fs.replaceFaviconDataFromDataURL(testURI, testFaviconData,
- (Date.now() + 60 * 60 * 24 * 1000) * 1000,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- // Open the channel
- channel = NetUtil.newChannel({
- uri: moz_anno_favicon_prefix + testURI.spec,
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_FAVICON
- });
- channel.asyncOpen2(new streamListener("image/png"));
- do_test_pending();
-}
diff --git a/toolkit/components/places/tests/favicons/test_page-icon_protocol.js b/toolkit/components/places/tests/favicons/test_page-icon_protocol.js
deleted file mode 100644
index 5533d5135..000000000
--- a/toolkit/components/places/tests/favicons/test_page-icon_protocol.js
+++ /dev/null
@@ -1,66 +0,0 @@
-const ICON_DATA = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==";
-const TEST_URI = NetUtil.newURI("http://mozilla.org/");
-const ICON_URI = NetUtil.newURI("http://mozilla.org/favicon.ico");
-
-function fetchIconForSpec(spec) {
- return new Promise((resolve, reject) => {
- NetUtil.asyncFetch({
- uri: NetUtil.newURI("page-icon:" + TEST_URI.spec),
- loadUsingSystemPrincipal: true,
- contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_FAVICON
- }, (input, status, request) => {
- if (!Components.isSuccessCode(status)) {
- reject(new Error("unable to load icon"));
- return;
- }
-
- try {
- let data = NetUtil.readInputStreamToString(input, input.available());
- let contentType = request.QueryInterface(Ci.nsIChannel).contentType;
- input.close();
- resolve({ data, contentType });
- } catch (ex) {
- reject(ex);
- }
- });
- });
-}
-
-var gDefaultFavicon;
-var gFavicon;
-
-add_task(function* setup() {
- yield PlacesTestUtils.addVisits({ uri: TEST_URI });
-
- PlacesUtils.favicons.replaceFaviconDataFromDataURL(
- ICON_URI, ICON_DATA, (Date.now() + 8640000) * 1000,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- yield new Promise(resolve => {
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- TEST_URI, ICON_URI, false,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- resolve, Services.scriptSecurityManager.getSystemPrincipal());
- });
-
- gDefaultFavicon = yield fetchIconForSpec(PlacesUtils.favicons.defaultFavicon);
- gFavicon = yield fetchIconForSpec(ICON_DATA);
-});
-
-add_task(function* known_url() {
- let {data, contentType} = yield fetchIconForSpec(TEST_URI.spec);
- Assert.equal(contentType, gFavicon.contentType);
- Assert.ok(data == gFavicon.data, "Got the favicon data");
-});
-
-add_task(function* unknown_url() {
- let {data, contentType} = yield fetchIconForSpec("http://www.moz.org/");
- Assert.equal(contentType, gDefaultFavicon.contentType);
- Assert.ok(data == gDefaultFavicon.data, "Got the default favicon data");
-});
-
-add_task(function* invalid_url() {
- let {data, contentType} = yield fetchIconForSpec("test");
- Assert.equal(contentType, gDefaultFavicon.contentType);
- Assert.ok(data == gDefaultFavicon.data, "Got the default favicon data");
-});
diff --git a/toolkit/components/places/tests/favicons/test_query_result_favicon_changed_on_child.js b/toolkit/components/places/tests/favicons/test_query_result_favicon_changed_on_child.js
deleted file mode 100644
index df61c22cd..000000000
--- a/toolkit/components/places/tests/favicons/test_query_result_favicon_changed_on_child.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Test for bug 451499 <https://bugzilla.mozilla.org/show_bug.cgi?id=451499>:
- * Wrong folder icon appears on smart bookmarks.
- */
-
-"use strict";
-
-const PAGE_URI = NetUtil.newURI("http://example.com/test_query_result");
-
-add_task(function* test_query_result_favicon_changed_on_child() {
- // Bookmark our test page, so it will appear in the query resultset.
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- title: "test_bookmark",
- url: PAGE_URI
- });
-
- // Get the last 10 bookmarks added to the menu or the toolbar.
- let query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarksMenuFolderId,
- PlacesUtils.toolbarFolderId], 2);
-
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- options.maxResults = 10;
- options.excludeQueries = 1;
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
-
- let result = PlacesUtils.history.executeQuery(query, options);
- let resultObserver = {
- __proto__: NavHistoryResultObserver.prototype,
- containerStateChanged(aContainerNode, aOldState, aNewState) {
- if (aNewState == Ci.nsINavHistoryContainerResultNode.STATE_OPENED) {
- // We set a favicon on PAGE_URI while the container is open. The
- // favicon for the page must have data associated with it in order for
- // the icon changed notifications to be sent, so we use a valid image
- // data URI.
- PlacesUtils.favicons.setAndFetchFaviconForPage(PAGE_URI,
- SMALLPNG_DATA_URI,
- false,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null,
- Services.scriptSecurityManager.getSystemPrincipal());
- }
- },
- nodeIconChanged(aNode) {
- do_throw("The icon should be set only for the page," +
- " not for the containing query.");
- }
- };
- result.addObserver(resultObserver, false);
-
- // Open the container and wait for containerStateChanged. We should start
- // observing before setting |containerOpen| as that's caused by the
- // setAndFetchFaviconForPage() call caused by the containerStateChanged
- // observer above.
- let promise = promiseFaviconChanged(PAGE_URI, SMALLPNG_DATA_URI);
- result.root.containerOpen = true;
- yield promise;
-
- // We must wait for the asynchronous database thread to finish the
- // operation, and then for the main thread to process any pending
- // notifications that came from the asynchronous thread, before we can be
- // sure that nodeIconChanged was not invoked in the meantime.
- yield PlacesTestUtils.promiseAsyncUpdates();
- result.removeObserver(resultObserver);
-
- // Free the resources immediately.
- result.root.containerOpen = false;
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/favicons/test_replaceFaviconData.js b/toolkit/components/places/tests/favicons/test_replaceFaviconData.js
deleted file mode 100644
index ac53e70e9..000000000
--- a/toolkit/components/places/tests/favicons/test_replaceFaviconData.js
+++ /dev/null
@@ -1,264 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests for mozIAsyncFavicons::replaceFaviconData()
- */
-
-var iconsvc = PlacesUtils.favicons;
-var histsvc = PlacesUtils.history;
-var systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
-
-var originalFavicon = {
- file: do_get_file("favicon-normal16.png"),
- uri: uri(do_get_file("favicon-normal16.png")),
- data: readFileData(do_get_file("favicon-normal16.png")),
- mimetype: "image/png"
-};
-
-var uniqueFaviconId = 0;
-function createFavicon(fileName) {
- let tempdir = Services.dirsvc.get("TmpD", Ci.nsILocalFile);
-
- // remove any existing file at the path we're about to copy to
- let outfile = tempdir.clone();
- outfile.append(fileName);
- try { outfile.remove(false); } catch (e) {}
-
- originalFavicon.file.copyToFollowingLinks(tempdir, fileName);
-
- let stream = Cc["@mozilla.org/network/file-output-stream;1"]
- .createInstance(Ci.nsIFileOutputStream);
- stream.init(outfile, 0x02 | 0x08 | 0x10, 0o600, 0);
-
- // append some data that sniffers/encoders will ignore that will distinguish
- // the different favicons we'll create
- uniqueFaviconId++;
- let uniqueStr = "uid:" + uniqueFaviconId;
- stream.write(uniqueStr, uniqueStr.length);
- stream.close();
-
- do_check_eq(outfile.leafName.substr(0, fileName.length), fileName);
-
- return {
- file: outfile,
- uri: uri(outfile),
- data: readFileData(outfile),
- mimetype: "image/png"
- };
-}
-
-function checkCallbackSucceeded(callbackMimetype, callbackData, sourceMimetype, sourceData) {
- do_check_eq(callbackMimetype, sourceMimetype);
- do_check_true(compareArrays(callbackData, sourceData));
-}
-
-function run_test() {
- // check that the favicon loaded correctly
- do_check_eq(originalFavicon.data.length, 286);
- run_next_test();
-}
-
-add_task(function* test_replaceFaviconData_validHistoryURI() {
- do_print("test replaceFaviconData for valid history uri");
-
- let pageURI = uri("http://test1.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let favicon = createFavicon("favicon1.png");
-
- iconsvc.replaceFaviconData(favicon.uri, favicon.data, favicon.data.length,
- favicon.mimetype);
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(pageURI, favicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconData_validHistoryURI_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, favicon.mimetype, favicon.data);
- checkFaviconDataForPage(
- pageURI, favicon.mimetype, favicon.data,
- function test_replaceFaviconData_validHistoryURI_callback() {
- favicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, systemPrincipal);
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconData_overrideDefaultFavicon() {
- do_print("test replaceFaviconData to override a later setAndFetchFaviconForPage");
-
- let pageURI = uri("http://test2.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon2.png");
- let secondFavicon = createFavicon("favicon3.png");
-
- iconsvc.replaceFaviconData(
- firstFavicon.uri, secondFavicon.data, secondFavicon.data.length,
- secondFavicon.mimetype);
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconData_overrideDefaultFavicon_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, secondFavicon.mimetype, secondFavicon.data);
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconData_overrideDefaultFavicon_callback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, systemPrincipal);
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconData_replaceExisting() {
- do_print("test replaceFaviconData to override a previous setAndFetchFaviconForPage");
-
- let pageURI = uri("http://test3.bar");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon4.png");
- let secondFavicon = createFavicon("favicon5.png");
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconData_replaceExisting_firstSet_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, firstFavicon.mimetype, firstFavicon.data);
- checkFaviconDataForPage(
- pageURI, firstFavicon.mimetype, firstFavicon.data,
- function test_replaceFaviconData_overrideDefaultFavicon_firstCallback() {
- iconsvc.replaceFaviconData(
- firstFavicon.uri, secondFavicon.data, secondFavicon.data.length,
- secondFavicon.mimetype);
- PlacesTestUtils.promiseAsyncUpdates().then(() => {
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconData_overrideDefaultFavicon_secondCallback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- }, systemPrincipal);
- });
- });
- }, systemPrincipal);
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconData_unrelatedReplace() {
- do_print("test replaceFaviconData to not make unrelated changes");
-
- let pageURI = uri("http://test4.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let favicon = createFavicon("favicon6.png");
- let unrelatedFavicon = createFavicon("favicon7.png");
-
- iconsvc.replaceFaviconData(
- unrelatedFavicon.uri, unrelatedFavicon.data, unrelatedFavicon.data.length,
- unrelatedFavicon.mimetype);
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, favicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconData_unrelatedReplace_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, favicon.mimetype, favicon.data);
- checkFaviconDataForPage(
- pageURI, favicon.mimetype, favicon.data,
- function test_replaceFaviconData_unrelatedReplace_callback() {
- favicon.file.remove(false);
- unrelatedFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, systemPrincipal);
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconData_badInputs() {
- do_print("test replaceFaviconData to throw on bad inputs");
-
- let favicon = createFavicon("favicon8.png");
-
- let ex = null;
- try {
- iconsvc.replaceFaviconData(
- favicon.uri, favicon.data, favicon.data.length, "");
- } catch (e) {
- ex = e;
- } finally {
- do_check_true(!!ex);
- }
-
- ex = null;
- try {
- iconsvc.replaceFaviconData(
- null, favicon.data, favicon.data.length, favicon.mimeType);
- } catch (e) {
- ex = e;
- } finally {
- do_check_true(!!ex);
- }
-
- ex = null;
- try {
- iconsvc.replaceFaviconData(
- favicon.uri, null, 0, favicon.mimeType);
- } catch (e) {
- ex = e;
- } finally {
- do_check_true(!!ex);
- }
-
- favicon.file.remove(false);
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconData_twiceReplace() {
- do_print("test replaceFaviconData on multiple replacements");
-
- let pageURI = uri("http://test5.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon9.png");
- let secondFavicon = createFavicon("favicon10.png");
-
- iconsvc.replaceFaviconData(
- firstFavicon.uri, firstFavicon.data, firstFavicon.data.length,
- firstFavicon.mimetype);
- iconsvc.replaceFaviconData(
- firstFavicon.uri, secondFavicon.data, secondFavicon.data.length,
- secondFavicon.mimetype);
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconData_twiceReplace_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, secondFavicon.mimetype, secondFavicon.data);
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconData_twiceReplace_callback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- }, systemPrincipal);
- }, systemPrincipal);
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/favicons/test_replaceFaviconDataFromDataURL.js b/toolkit/components/places/tests/favicons/test_replaceFaviconDataFromDataURL.js
deleted file mode 100644
index 69a5ba852..000000000
--- a/toolkit/components/places/tests/favicons/test_replaceFaviconDataFromDataURL.js
+++ /dev/null
@@ -1,352 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- * Tests for mozIAsyncFavicons::replaceFaviconData()
- */
-
-var iconsvc = PlacesUtils.favicons;
-var histsvc = PlacesUtils.history;
-
-var originalFavicon = {
- file: do_get_file("favicon-normal16.png"),
- uri: uri(do_get_file("favicon-normal16.png")),
- data: readFileData(do_get_file("favicon-normal16.png")),
- mimetype: "image/png"
-};
-
-var uniqueFaviconId = 0;
-function createFavicon(fileName) {
- let tempdir = Services.dirsvc.get("TmpD", Ci.nsILocalFile);
-
- // remove any existing file at the path we're about to copy to
- let outfile = tempdir.clone();
- outfile.append(fileName);
- try { outfile.remove(false); } catch (e) {}
-
- originalFavicon.file.copyToFollowingLinks(tempdir, fileName);
-
- let stream = Cc["@mozilla.org/network/file-output-stream;1"]
- .createInstance(Ci.nsIFileOutputStream);
- stream.init(outfile, 0x02 | 0x08 | 0x10, 0o600, 0);
-
- // append some data that sniffers/encoders will ignore that will distinguish
- // the different favicons we'll create
- uniqueFaviconId++;
- let uniqueStr = "uid:" + uniqueFaviconId;
- stream.write(uniqueStr, uniqueStr.length);
- stream.close();
-
- do_check_eq(outfile.leafName.substr(0, fileName.length), fileName);
-
- return {
- file: outfile,
- uri: uri(outfile),
- data: readFileData(outfile),
- mimetype: "image/png"
- };
-}
-
-function createDataURLForFavicon(favicon) {
- return "data:" + favicon.mimetype + ";base64," + toBase64(favicon.data);
-}
-
-function checkCallbackSucceeded(callbackMimetype, callbackData, sourceMimetype, sourceData) {
- do_check_eq(callbackMimetype, sourceMimetype);
- do_check_true(compareArrays(callbackData, sourceData));
-}
-
-function run_test() {
- // check that the favicon loaded correctly
- do_check_eq(originalFavicon.data.length, 286);
- run_next_test();
-}
-
-add_task(function* test_replaceFaviconDataFromDataURL_validHistoryURI() {
- do_print("test replaceFaviconDataFromDataURL for valid history uri");
-
- let pageURI = uri("http://test1.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let favicon = createFavicon("favicon1.png");
- iconsvc.replaceFaviconDataFromDataURL(favicon.uri, createDataURLForFavicon(favicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(pageURI, favicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconDataFromDataURL_validHistoryURI_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, favicon.mimetype, favicon.data);
- checkFaviconDataForPage(
- pageURI, favicon.mimetype, favicon.data,
- function test_replaceFaviconDataFromDataURL_validHistoryURI_callback() {
- favicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconDataFromDataURL_overrideDefaultFavicon() {
- do_print("test replaceFaviconDataFromDataURL to override a later setAndFetchFaviconForPage");
-
- let pageURI = uri("http://test2.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon2.png");
- let secondFavicon = createFavicon("favicon3.png");
-
- iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(secondFavicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconDataFromDataURL_overrideDefaultFavicon_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, secondFavicon.mimetype, secondFavicon.data);
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconDataFromDataURL_overrideDefaultFavicon_callback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconDataFromDataURL_replaceExisting() {
- do_print("test replaceFaviconDataFromDataURL to override a previous setAndFetchFaviconForPage");
-
- let pageURI = uri("http://test3.bar");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon4.png");
- let secondFavicon = createFavicon("favicon5.png");
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconDataFromDataURL_replaceExisting_firstSet_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, firstFavicon.mimetype, firstFavicon.data);
- checkFaviconDataForPage(
- pageURI, firstFavicon.mimetype, firstFavicon.data,
- function test_replaceFaviconDataFromDataURL_replaceExisting_firstCallback() {
- iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(secondFavicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconDataFromDataURL_replaceExisting_secondCallback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconDataFromDataURL_unrelatedReplace() {
- do_print("test replaceFaviconDataFromDataURL to not make unrelated changes");
-
- let pageURI = uri("http://test4.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let favicon = createFavicon("favicon6.png");
- let unrelatedFavicon = createFavicon("favicon7.png");
-
- iconsvc.replaceFaviconDataFromDataURL(unrelatedFavicon.uri, createDataURLForFavicon(unrelatedFavicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, favicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconDataFromDataURL_unrelatedReplace_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, favicon.mimetype, favicon.data);
- checkFaviconDataForPage(
- pageURI, favicon.mimetype, favicon.data,
- function test_replaceFaviconDataFromDataURL_unrelatedReplace_callback() {
- favicon.file.remove(false);
- unrelatedFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconDataFromDataURL_badInputs() {
- do_print("test replaceFaviconDataFromDataURL to throw on bad inputs");
-
- let favicon = createFavicon("favicon8.png");
-
- let ex = null;
- try {
- iconsvc.replaceFaviconDataFromDataURL(favicon.uri, "", 0,
- Services.scriptSecurityManager.getSystemPrincipal());
- } catch (e) {
- ex = e;
- } finally {
- do_check_true(!!ex);
- }
-
- ex = null;
- try {
- iconsvc.replaceFaviconDataFromDataURL(null, createDataURLForFavicon(favicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
- } catch (e) {
- ex = e;
- } finally {
- do_check_true(!!ex);
- }
-
- favicon.file.remove(false);
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconDataFromDataURL_twiceReplace() {
- do_print("test replaceFaviconDataFromDataURL on multiple replacements");
-
- let pageURI = uri("http://test5.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon9.png");
- let secondFavicon = createFavicon("favicon10.png");
-
- iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(firstFavicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
- iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(secondFavicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconDataFromDataURL_twiceReplace_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, secondFavicon.mimetype, secondFavicon.data);
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconDataFromDataURL_twiceReplace_callback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconDataFromDataURL_afterRegularAssign() {
- do_print("test replaceFaviconDataFromDataURL after replaceFaviconData");
-
- let pageURI = uri("http://test6.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon11.png");
- let secondFavicon = createFavicon("favicon12.png");
-
- iconsvc.replaceFaviconData(
- firstFavicon.uri, firstFavicon.data, firstFavicon.data.length,
- firstFavicon.mimetype);
- iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(secondFavicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconDataFromDataURL_afterRegularAssign_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, secondFavicon.mimetype, secondFavicon.data);
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconDataFromDataURL_afterRegularAssign_callback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_replaceFaviconDataFromDataURL_beforeRegularAssign() {
- do_print("test replaceFaviconDataFromDataURL before replaceFaviconData");
-
- let pageURI = uri("http://test7.bar/");
- yield PlacesTestUtils.addVisits(pageURI);
-
- let firstFavicon = createFavicon("favicon13.png");
- let secondFavicon = createFavicon("favicon14.png");
-
- iconsvc.replaceFaviconDataFromDataURL(firstFavicon.uri, createDataURLForFavicon(firstFavicon), 0,
- Services.scriptSecurityManager.getSystemPrincipal());
- iconsvc.replaceFaviconData(
- firstFavicon.uri, secondFavicon.data, secondFavicon.data.length,
- secondFavicon.mimetype);
-
- let deferSetAndFetchFavicon = Promise.defer();
- iconsvc.setAndFetchFaviconForPage(
- pageURI, firstFavicon.uri, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- function test_replaceFaviconDataFromDataURL_beforeRegularAssign_check(aURI, aDataLen, aData, aMimeType) {
- checkCallbackSucceeded(aMimeType, aData, secondFavicon.mimetype, secondFavicon.data);
- checkFaviconDataForPage(
- pageURI, secondFavicon.mimetype, secondFavicon.data,
- function test_replaceFaviconDataFromDataURL_beforeRegularAssign_callback() {
- firstFavicon.file.remove(false);
- secondFavicon.file.remove(false);
- deferSetAndFetchFavicon.resolve();
- });
- }, Services.scriptSecurityManager.getSystemPrincipal());
- yield deferSetAndFetchFavicon.promise;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-/* toBase64 copied from image/test/unit/test_encoder_png.js */
-
-/* Convert data (an array of integers) to a Base64 string. */
-const toBase64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +
- '0123456789+/';
-const base64Pad = '=';
-function toBase64(data) {
- let result = '';
- let length = data.length;
- let i;
- // Convert every three bytes to 4 ascii characters.
- for (i = 0; i < (length - 2); i += 3) {
- result += toBase64Table[data[i] >> 2];
- result += toBase64Table[((data[i] & 0x03) << 4) + (data[i+1] >> 4)];
- result += toBase64Table[((data[i+1] & 0x0f) << 2) + (data[i+2] >> 6)];
- result += toBase64Table[data[i+2] & 0x3f];
- }
-
- // Convert the remaining 1 or 2 bytes, pad out to 4 characters.
- if (length%3) {
- i = length - (length%3);
- result += toBase64Table[data[i] >> 2];
- if ((length%3) == 2) {
- result += toBase64Table[((data[i] & 0x03) << 4) + (data[i+1] >> 4)];
- result += toBase64Table[(data[i+1] & 0x0f) << 2];
- result += base64Pad;
- } else {
- result += toBase64Table[(data[i] & 0x03) << 4];
- result += base64Pad + base64Pad;
- }
- }
-
- return result;
-}
diff --git a/toolkit/components/places/tests/favicons/xpcshell.ini b/toolkit/components/places/tests/favicons/xpcshell.ini
deleted file mode 100644
index 851f193c7..000000000
--- a/toolkit/components/places/tests/favicons/xpcshell.ini
+++ /dev/null
@@ -1,32 +0,0 @@
-[DEFAULT]
-head = head_favicons.js
-tail =
-skip-if = toolkit == 'android'
-support-files =
- expected-favicon-big32.jpg.png
- expected-favicon-big4.jpg.png
- expected-favicon-big48.ico.png
- expected-favicon-big64.png.png
- expected-favicon-scale160x3.jpg.png
- expected-favicon-scale3x160.jpg.png
- favicon-big16.ico
- favicon-big32.jpg
- favicon-big4.jpg
- favicon-big48.ico
- favicon-big64.png
- favicon-normal16.png
- favicon-normal32.png
- favicon-scale160x3.jpg
- favicon-scale3x160.jpg
-
-[test_expireAllFavicons.js]
-[test_favicons_conversions.js]
-# Bug 676989: test fails consistently on Android
-fail-if = os == "android"
-[test_getFaviconDataForPage.js]
-[test_getFaviconURLForPage.js]
-[test_moz-anno_favicon_mime_type.js]
-[test_page-icon_protocol.js]
-[test_query_result_favicon_changed_on_child.js]
-[test_replaceFaviconData.js]
-[test_replaceFaviconDataFromDataURL.js]
diff --git a/toolkit/components/places/tests/head_common.js b/toolkit/components/places/tests/head_common.js
deleted file mode 100644
index ddb6dcbd7..000000000
--- a/toolkit/components/places/tests/head_common.js
+++ /dev/null
@@ -1,869 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const CURRENT_SCHEMA_VERSION = 35;
-const FIRST_UPGRADABLE_SCHEMA_VERSION = 11;
-
-const NS_APP_USER_PROFILE_50_DIR = "ProfD";
-const NS_APP_PROFILE_DIR_STARTUP = "ProfDS";
-
-// Shortcuts to transitions type.
-const TRANSITION_LINK = Ci.nsINavHistoryService.TRANSITION_LINK;
-const TRANSITION_TYPED = Ci.nsINavHistoryService.TRANSITION_TYPED;
-const TRANSITION_BOOKMARK = Ci.nsINavHistoryService.TRANSITION_BOOKMARK;
-const TRANSITION_EMBED = Ci.nsINavHistoryService.TRANSITION_EMBED;
-const TRANSITION_FRAMED_LINK = Ci.nsINavHistoryService.TRANSITION_FRAMED_LINK;
-const TRANSITION_REDIRECT_PERMANENT = Ci.nsINavHistoryService.TRANSITION_REDIRECT_PERMANENT;
-const TRANSITION_REDIRECT_TEMPORARY = Ci.nsINavHistoryService.TRANSITION_REDIRECT_TEMPORARY;
-const TRANSITION_DOWNLOAD = Ci.nsINavHistoryService.TRANSITION_DOWNLOAD;
-const TRANSITION_RELOAD = Ci.nsINavHistoryService.TRANSITION_RELOAD;
-
-const TITLE_LENGTH_MAX = 4096;
-
-Cu.importGlobalProperties(["URL"]);
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Services",
- "resource://gre/modules/Services.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Task",
- "resource://gre/modules/Task.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "BookmarkJSONUtils",
- "resource://gre/modules/BookmarkJSONUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "BookmarkHTMLUtils",
- "resource://gre/modules/BookmarkHTMLUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesBackups",
- "resource://gre/modules/PlacesBackups.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTransactions",
- "resource://gre/modules/PlacesTransactions.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Sqlite",
- "resource://gre/modules/Sqlite.jsm");
-
-// This imports various other objects in addition to PlacesUtils.
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "SMALLPNG_DATA_URI", function() {
- return NetUtil.newURI(
- "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAA" +
- "AAAA6fptVAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==");
-});
-XPCOMUtils.defineLazyGetter(this, "SMALLSVG_DATA_URI", function() {
- return NetUtil.newURI(
- "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy5" +
- "3My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIiBmaWxs" +
- "PSIjNDI0ZTVhIj4NCiAgPGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iN" +
- "DQiIHN0cm9rZT0iIzQyNGU1YSIgc3Ryb2tlLXdpZHRoPSIxMSIgZmlsbD" +
- "0ibm9uZSIvPg0KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjI0LjYiIHI9IjY" +
- "uNCIvPg0KICA8cmVjdCB4PSI0NSIgeT0iMzkuOSIgd2lkdGg9IjEwLjEi" +
- "IGhlaWdodD0iNDEuOCIvPg0KPC9zdmc%2BDQo%3D");
-});
-
-var gTestDir = do_get_cwd();
-
-// Initialize profile.
-var gProfD = do_get_profile(true);
-
-// Remove any old database.
-clearDB();
-
-/**
- * Shortcut to create a nsIURI.
- *
- * @param aSpec
- * URLString of the uri.
- */
-function uri(aSpec) {
- return NetUtil.newURI(aSpec);
-}
-
-
-/**
- * Gets the database connection. If the Places connection is invalid it will
- * try to create a new connection.
- *
- * @param [optional] aForceNewConnection
- * Forces creation of a new connection to the database. When a
- * connection is asyncClosed it cannot anymore schedule async statements,
- * though connectionReady will keep returning true (Bug 726990).
- *
- * @return The database connection or null if unable to get one.
- */
-var gDBConn;
-function DBConn(aForceNewConnection) {
- if (!aForceNewConnection) {
- let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .DBConnection;
- if (db.connectionReady)
- return db;
- }
-
- // If the Places database connection has been closed, create a new connection.
- if (!gDBConn || aForceNewConnection) {
- let file = Services.dirsvc.get('ProfD', Ci.nsIFile);
- file.append("places.sqlite");
- let dbConn = gDBConn = Services.storage.openDatabase(file);
-
- // Be sure to cleanly close this connection.
- promiseTopicObserved("profile-before-change").then(() => dbConn.asyncClose());
- }
-
- return gDBConn.connectionReady ? gDBConn : null;
-}
-
-/**
- * Reads data from the provided inputstream.
- *
- * @return an array of bytes.
- */
-function readInputStreamData(aStream) {
- let bistream = Cc["@mozilla.org/binaryinputstream;1"].
- createInstance(Ci.nsIBinaryInputStream);
- try {
- bistream.setInputStream(aStream);
- let expectedData = [];
- let avail;
- while ((avail = bistream.available())) {
- expectedData = expectedData.concat(bistream.readByteArray(avail));
- }
- return expectedData;
- } finally {
- bistream.close();
- }
-}
-
-/**
- * Reads the data from the specified nsIFile.
- *
- * @param aFile
- * The nsIFile to read from.
- * @return an array of bytes.
- */
-function readFileData(aFile) {
- let inputStream = Cc["@mozilla.org/network/file-input-stream;1"].
- createInstance(Ci.nsIFileInputStream);
- // init the stream as RD_ONLY, -1 == default permissions.
- inputStream.init(aFile, 0x01, -1, null);
-
- // Check the returned size versus the expected size.
- let size = inputStream.available();
- let bytes = readInputStreamData(inputStream);
- if (size != bytes.length) {
- throw "Didn't read expected number of bytes";
- }
- return bytes;
-}
-
-/**
- * Reads the data from the named file, verifying the expected file length.
- *
- * @param aFileName
- * This file should be located in the same folder as the test.
- * @param aExpectedLength
- * Expected length of the file.
- *
- * @return The array of bytes read from the file.
- */
-function readFileOfLength(aFileName, aExpectedLength) {
- let data = readFileData(do_get_file(aFileName));
- do_check_eq(data.length, aExpectedLength);
- return data;
-}
-
-
-/**
- * Returns the base64-encoded version of the given string. This function is
- * similar to window.btoa, but is available to xpcshell tests also.
- *
- * @param aString
- * Each character in this string corresponds to a byte, and must be a
- * code point in the range 0-255.
- *
- * @return The base64-encoded string.
- */
-function base64EncodeString(aString) {
- var stream = Cc["@mozilla.org/io/string-input-stream;1"]
- .createInstance(Ci.nsIStringInputStream);
- stream.setData(aString, aString.length);
- var encoder = Cc["@mozilla.org/scriptablebase64encoder;1"]
- .createInstance(Ci.nsIScriptableBase64Encoder);
- return encoder.encodeToString(stream, aString.length);
-}
-
-
-/**
- * Compares two arrays, and returns true if they are equal.
- *
- * @param aArray1
- * First array to compare.
- * @param aArray2
- * Second array to compare.
- */
-function compareArrays(aArray1, aArray2) {
- if (aArray1.length != aArray2.length) {
- print("compareArrays: array lengths differ\n");
- return false;
- }
-
- for (let i = 0; i < aArray1.length; i++) {
- if (aArray1[i] != aArray2[i]) {
- print("compareArrays: arrays differ at index " + i + ": " +
- "(" + aArray1[i] + ") != (" + aArray2[i] +")\n");
- return false;
- }
- }
-
- return true;
-}
-
-
-/**
- * Deletes a previously created sqlite file from the profile folder.
- */
-function clearDB() {
- try {
- let file = Services.dirsvc.get('ProfD', Ci.nsIFile);
- file.append("places.sqlite");
- if (file.exists())
- file.remove(false);
- } catch (ex) { dump("Exception: " + ex); }
-}
-
-
-/**
- * Dumps the rows of a table out to the console.
- *
- * @param aName
- * The name of the table or view to output.
- */
-function dump_table(aName)
-{
- let stmt = DBConn().createStatement("SELECT * FROM " + aName);
-
- print("\n*** Printing data from " + aName);
- let count = 0;
- while (stmt.executeStep()) {
- let columns = stmt.numEntries;
-
- if (count == 0) {
- // Print the column names.
- for (let i = 0; i < columns; i++)
- dump(stmt.getColumnName(i) + "\t");
- dump("\n");
- }
-
- // Print the rows.
- for (let i = 0; i < columns; i++) {
- switch (stmt.getTypeOfIndex(i)) {
- case Ci.mozIStorageValueArray.VALUE_TYPE_NULL:
- dump("NULL\t");
- break;
- case Ci.mozIStorageValueArray.VALUE_TYPE_INTEGER:
- dump(stmt.getInt64(i) + "\t");
- break;
- case Ci.mozIStorageValueArray.VALUE_TYPE_FLOAT:
- dump(stmt.getDouble(i) + "\t");
- break;
- case Ci.mozIStorageValueArray.VALUE_TYPE_TEXT:
- dump(stmt.getString(i) + "\t");
- break;
- }
- }
- dump("\n");
-
- count++;
- }
- print("*** There were a total of " + count + " rows of data.\n");
-
- stmt.finalize();
-}
-
-
-/**
- * Checks if an address is found in the database.
- * @param aURI
- * nsIURI or address to look for.
- * @return place id of the page or 0 if not found
- */
-function page_in_database(aURI)
-{
- let url = aURI instanceof Ci.nsIURI ? aURI.spec : aURI;
- let stmt = DBConn().createStatement(
- "SELECT id FROM moz_places WHERE url_hash = hash(:url) AND url = :url"
- );
- stmt.params.url = url;
- try {
- if (!stmt.executeStep())
- return 0;
- return stmt.getInt64(0);
- }
- finally {
- stmt.finalize();
- }
-}
-
-/**
- * Checks how many visits exist for a specified page.
- * @param aURI
- * nsIURI or address to look for.
- * @return number of visits found.
- */
-function visits_in_database(aURI)
-{
- let url = aURI instanceof Ci.nsIURI ? aURI.spec : aURI;
- let stmt = DBConn().createStatement(
- `SELECT count(*) FROM moz_historyvisits v
- JOIN moz_places h ON h.id = v.place_id
- WHERE url_hash = hash(:url) AND url = :url`
- );
- stmt.params.url = url;
- try {
- if (!stmt.executeStep())
- return 0;
- return stmt.getInt64(0);
- }
- finally {
- stmt.finalize();
- }
-}
-
-/**
- * Checks that we don't have any bookmark
- */
-function check_no_bookmarks() {
- let query = PlacesUtils.history.getNewQuery();
- let folders = [
- PlacesUtils.bookmarks.toolbarFolder,
- PlacesUtils.bookmarks.bookmarksMenuFolder,
- PlacesUtils.bookmarks.unfiledBookmarksFolder,
- ];
- query.setFolders(folders, 3);
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- if (root.childCount != 0)
- do_throw("Unable to remove all bookmarks");
- root.containerOpen = false;
-}
-
-/**
- * Allows waiting for an observer notification once.
- *
- * @param aTopic
- * Notification topic to observe.
- *
- * @return {Promise}
- * @resolves The array [aSubject, aData] from the observed notification.
- * @rejects Never.
- */
-function promiseTopicObserved(aTopic)
-{
- return new Promise(resolve => {
- Services.obs.addObserver(function observe(aObsSubject, aObsTopic, aObsData) {
- Services.obs.removeObserver(observe, aObsTopic);
- resolve([aObsSubject, aObsData]);
- }, aTopic, false);
- });
-}
-
-/**
- * Simulates a Places shutdown.
- */
-var shutdownPlaces = function() {
- do_print("shutdownPlaces: starting");
- let promise = new Promise(resolve => {
- Services.obs.addObserver(resolve, "places-connection-closed", false);
- });
- let hs = PlacesUtils.history.QueryInterface(Ci.nsIObserver);
- hs.observe(null, "profile-change-teardown", null);
- do_print("shutdownPlaces: sent profile-change-teardown");
- hs.observe(null, "test-simulate-places-shutdown", null);
- do_print("shutdownPlaces: sent test-simulate-places-shutdown");
- return promise.then(() => {
- do_print("shutdownPlaces: complete");
- });
-};
-
-const FILENAME_BOOKMARKS_HTML = "bookmarks.html";
-const FILENAME_BOOKMARKS_JSON = "bookmarks-" +
- (PlacesBackups.toISODateString(new Date())) + ".json";
-
-/**
- * Creates a bookmarks.html file in the profile folder from a given source file.
- *
- * @param aFilename
- * Name of the file to copy to the profile folder. This file must
- * exist in the directory that contains the test files.
- *
- * @return nsIFile object for the file.
- */
-function create_bookmarks_html(aFilename) {
- if (!aFilename)
- do_throw("you must pass a filename to create_bookmarks_html function");
- remove_bookmarks_html();
- let bookmarksHTMLFile = gTestDir.clone();
- bookmarksHTMLFile.append(aFilename);
- do_check_true(bookmarksHTMLFile.exists());
- bookmarksHTMLFile.copyTo(gProfD, FILENAME_BOOKMARKS_HTML);
- let profileBookmarksHTMLFile = gProfD.clone();
- profileBookmarksHTMLFile.append(FILENAME_BOOKMARKS_HTML);
- do_check_true(profileBookmarksHTMLFile.exists());
- return profileBookmarksHTMLFile;
-}
-
-
-/**
- * Remove bookmarks.html file from the profile folder.
- */
-function remove_bookmarks_html() {
- let profileBookmarksHTMLFile = gProfD.clone();
- profileBookmarksHTMLFile.append(FILENAME_BOOKMARKS_HTML);
- if (profileBookmarksHTMLFile.exists()) {
- profileBookmarksHTMLFile.remove(false);
- do_check_false(profileBookmarksHTMLFile.exists());
- }
-}
-
-
-/**
- * Check bookmarks.html file exists in the profile folder.
- *
- * @return nsIFile object for the file.
- */
-function check_bookmarks_html() {
- let profileBookmarksHTMLFile = gProfD.clone();
- profileBookmarksHTMLFile.append(FILENAME_BOOKMARKS_HTML);
- do_check_true(profileBookmarksHTMLFile.exists());
- return profileBookmarksHTMLFile;
-}
-
-
-/**
- * Creates a JSON backup in the profile folder folder from a given source file.
- *
- * @param aFilename
- * Name of the file to copy to the profile folder. This file must
- * exist in the directory that contains the test files.
- *
- * @return nsIFile object for the file.
- */
-function create_JSON_backup(aFilename) {
- if (!aFilename)
- do_throw("you must pass a filename to create_JSON_backup function");
- let bookmarksBackupDir = gProfD.clone();
- bookmarksBackupDir.append("bookmarkbackups");
- if (!bookmarksBackupDir.exists()) {
- bookmarksBackupDir.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8));
- do_check_true(bookmarksBackupDir.exists());
- }
- let profileBookmarksJSONFile = bookmarksBackupDir.clone();
- profileBookmarksJSONFile.append(FILENAME_BOOKMARKS_JSON);
- if (profileBookmarksJSONFile.exists()) {
- profileBookmarksJSONFile.remove();
- }
- let bookmarksJSONFile = gTestDir.clone();
- bookmarksJSONFile.append(aFilename);
- do_check_true(bookmarksJSONFile.exists());
- bookmarksJSONFile.copyTo(bookmarksBackupDir, FILENAME_BOOKMARKS_JSON);
- profileBookmarksJSONFile = bookmarksBackupDir.clone();
- profileBookmarksJSONFile.append(FILENAME_BOOKMARKS_JSON);
- do_check_true(profileBookmarksJSONFile.exists());
- return profileBookmarksJSONFile;
-}
-
-
-/**
- * Remove bookmarksbackup dir and all backups from the profile folder.
- */
-function remove_all_JSON_backups() {
- let bookmarksBackupDir = gProfD.clone();
- bookmarksBackupDir.append("bookmarkbackups");
- if (bookmarksBackupDir.exists()) {
- bookmarksBackupDir.remove(true);
- do_check_false(bookmarksBackupDir.exists());
- }
-}
-
-
-/**
- * Check a JSON backup file for today exists in the profile folder.
- *
- * @param aIsAutomaticBackup The boolean indicates whether it's an automatic
- * backup.
- * @return nsIFile object for the file.
- */
-function check_JSON_backup(aIsAutomaticBackup) {
- let profileBookmarksJSONFile;
- if (aIsAutomaticBackup) {
- let bookmarksBackupDir = gProfD.clone();
- bookmarksBackupDir.append("bookmarkbackups");
- let files = bookmarksBackupDir.directoryEntries;
- while (files.hasMoreElements()) {
- let entry = files.getNext().QueryInterface(Ci.nsIFile);
- if (PlacesBackups.filenamesRegex.test(entry.leafName)) {
- profileBookmarksJSONFile = entry;
- break;
- }
- }
- } else {
- profileBookmarksJSONFile = gProfD.clone();
- profileBookmarksJSONFile.append("bookmarkbackups");
- profileBookmarksJSONFile.append(FILENAME_BOOKMARKS_JSON);
- }
- do_check_true(profileBookmarksJSONFile.exists());
- return profileBookmarksJSONFile;
-}
-
-/**
- * Returns the frecency of a url.
- *
- * @param aURI
- * The URI or spec to get frecency for.
- * @return the frecency value.
- */
-function frecencyForUrl(aURI)
-{
- let url = aURI;
- if (aURI instanceof Ci.nsIURI) {
- url = aURI.spec;
- } else if (aURI instanceof URL) {
- url = aURI.href;
- }
- let stmt = DBConn().createStatement(
- "SELECT frecency FROM moz_places WHERE url_hash = hash(?1) AND url = ?1"
- );
- stmt.bindByIndex(0, url);
- try {
- if (!stmt.executeStep()) {
- throw new Error("No result for frecency.");
- }
- return stmt.getInt32(0);
- } finally {
- stmt.finalize();
- }
-}
-
-/**
- * Returns the hidden status of a url.
- *
- * @param aURI
- * The URI or spec to get hidden for.
- * @return @return true if the url is hidden, false otherwise.
- */
-function isUrlHidden(aURI)
-{
- let url = aURI instanceof Ci.nsIURI ? aURI.spec : aURI;
- let stmt = DBConn().createStatement(
- "SELECT hidden FROM moz_places WHERE url_hash = hash(?1) AND url = ?1"
- );
- stmt.bindByIndex(0, url);
- if (!stmt.executeStep())
- throw new Error("No result for hidden.");
- let hidden = stmt.getInt32(0);
- stmt.finalize();
-
- return !!hidden;
-}
-
-/**
- * Compares two times in usecs, considering eventual platform timers skews.
- *
- * @param aTimeBefore
- * The older time in usecs.
- * @param aTimeAfter
- * The newer time in usecs.
- * @return true if times are ordered, false otherwise.
- */
-function is_time_ordered(before, after) {
- // Windows has an estimated 16ms timers precision, since Date.now() and
- // PR_Now() use different code atm, the results can be unordered by this
- // amount of time. See bug 558745 and bug 557406.
- let isWindows = ("@mozilla.org/windows-registry-key;1" in Cc);
- // Just to be safe we consider 20ms.
- let skew = isWindows ? 20000000 : 0;
- return after - before > -skew;
-}
-
-/**
- * Shutdowns Places, invoking the callback when the connection has been closed.
- *
- * @param aCallback
- * Function to be called when done.
- */
-function waitForConnectionClosed(aCallback)
-{
- promiseTopicObserved("places-connection-closed").then(aCallback);
- shutdownPlaces();
-}
-
-/**
- * Tests if a given guid is valid for use in Places or not.
- *
- * @param aGuid
- * The guid to test.
- * @param [optional] aStack
- * The stack frame used to report the error.
- */
-function do_check_valid_places_guid(aGuid,
- aStack)
-{
- if (!aStack) {
- aStack = Components.stack.caller;
- }
- do_check_true(/^[a-zA-Z0-9\-_]{12}$/.test(aGuid), aStack);
-}
-
-/**
- * Retrieves the guid for a given uri.
- *
- * @param aURI
- * The uri to check.
- * @param [optional] aStack
- * The stack frame used to report the error.
- * @return the associated the guid.
- */
-function do_get_guid_for_uri(aURI,
- aStack)
-{
- if (!aStack) {
- aStack = Components.stack.caller;
- }
- let stmt = DBConn().createStatement(
- `SELECT guid
- FROM moz_places
- WHERE url_hash = hash(:url) AND url = :url`
- );
- stmt.params.url = aURI.spec;
- do_check_true(stmt.executeStep(), aStack);
- let guid = stmt.row.guid;
- stmt.finalize();
- do_check_valid_places_guid(guid, aStack);
- return guid;
-}
-
-/**
- * Tests that a guid was set in moz_places for a given uri.
- *
- * @param aURI
- * The uri to check.
- * @param [optional] aGUID
- * The expected guid in the database.
- */
-function do_check_guid_for_uri(aURI,
- aGUID)
-{
- let caller = Components.stack.caller;
- let guid = do_get_guid_for_uri(aURI, caller);
- if (aGUID) {
- do_check_valid_places_guid(aGUID, caller);
- do_check_eq(guid, aGUID, caller);
- }
-}
-
-/**
- * Retrieves the guid for a given bookmark.
- *
- * @param aId
- * The bookmark id to check.
- * @param [optional] aStack
- * The stack frame used to report the error.
- * @return the associated the guid.
- */
-function do_get_guid_for_bookmark(aId,
- aStack)
-{
- if (!aStack) {
- aStack = Components.stack.caller;
- }
- let stmt = DBConn().createStatement(
- `SELECT guid
- FROM moz_bookmarks
- WHERE id = :item_id`
- );
- stmt.params.item_id = aId;
- do_check_true(stmt.executeStep(), aStack);
- let guid = stmt.row.guid;
- stmt.finalize();
- do_check_valid_places_guid(guid, aStack);
- return guid;
-}
-
-/**
- * Tests that a guid was set in moz_places for a given bookmark.
- *
- * @param aId
- * The bookmark id to check.
- * @param [optional] aGUID
- * The expected guid in the database.
- */
-function do_check_guid_for_bookmark(aId,
- aGUID)
-{
- let caller = Components.stack.caller;
- let guid = do_get_guid_for_bookmark(aId, caller);
- if (aGUID) {
- do_check_valid_places_guid(aGUID, caller);
- do_check_eq(guid, aGUID, caller);
- }
-}
-
-/**
- * Compares 2 arrays returning whether they contains the same elements.
- *
- * @param a1
- * First array to compare.
- * @param a2
- * Second array to compare.
- * @param [optional] sorted
- * Whether the comparison should take in count position of the elements.
- * @return true if the arrays contain the same elements, false otherwise.
- */
-function do_compare_arrays(a1, a2, sorted)
-{
- if (a1.length != a2.length)
- return false;
-
- if (sorted) {
- return a1.every((e, i) => e == a2[i]);
- }
- return a1.filter(e => !a2.includes(e)).length == 0 &&
- a2.filter(e => !a1.includes(e)).length == 0;
-}
-
-/**
- * Generic nsINavBookmarkObserver that doesn't implement anything, but provides
- * dummy methods to prevent errors about an object not having a certain method.
- */
-function NavBookmarkObserver() {}
-
-NavBookmarkObserver.prototype = {
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemAdded: function () {},
- onItemRemoved: function () {},
- onItemChanged: function () {},
- onItemVisited: function () {},
- onItemMoved: function () {},
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver,
- ])
-};
-
-/**
- * Generic nsINavHistoryObserver that doesn't implement anything, but provides
- * dummy methods to prevent errors about an object not having a certain method.
- */
-function NavHistoryObserver() {}
-
-NavHistoryObserver.prototype = {
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function () {},
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavHistoryObserver,
- ])
-};
-
-/**
- * Generic nsINavHistoryResultObserver that doesn't implement anything, but
- * provides dummy methods to prevent errors about an object not having a certain
- * method.
- */
-function NavHistoryResultObserver() {}
-
-NavHistoryResultObserver.prototype = {
- batching: function () {},
- containerStateChanged: function () {},
- invalidateContainer: function () {},
- nodeAnnotationChanged: function () {},
- nodeDateAddedChanged: function () {},
- nodeHistoryDetailsChanged: function () {},
- nodeIconChanged: function () {},
- nodeInserted: function () {},
- nodeKeywordChanged: function () {},
- nodeLastModifiedChanged: function () {},
- nodeMoved: function () {},
- nodeRemoved: function () {},
- nodeTagsChanged: function () {},
- nodeTitleChanged: function () {},
- nodeURIChanged: function () {},
- sortingChanged: function () {},
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavHistoryResultObserver,
- ])
-};
-
-/**
- * Asynchronously check a url is visited.
- *
- * @param aURI The URI.
- * @return {Promise}
- * @resolves When the check has been added successfully.
- * @rejects JavaScript exception.
- */
-function promiseIsURIVisited(aURI) {
- let deferred = Promise.defer();
-
- PlacesUtils.asyncHistory.isURIVisited(aURI, function(unused, aIsVisited) {
- deferred.resolve(aIsVisited);
- });
-
- return deferred.promise;
-}
-
-/**
- * Asynchronously set the favicon associated with a page.
- * @param aPageURI
- * The page's URI
- * @param aIconURI
- * The URI of the favicon to be set.
- */
-function promiseSetIconForPage(aPageURI, aIconURI) {
- let deferred = Promise.defer();
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- aPageURI, aIconURI, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- () => { deferred.resolve(); },
- Services.scriptSecurityManager.getSystemPrincipal());
- return deferred.promise;
-}
-
-function checkBookmarkObject(info) {
- do_check_valid_places_guid(info.guid);
- do_check_valid_places_guid(info.parentGuid);
- Assert.ok(typeof info.index == "number", "index should be a number");
- Assert.ok(info.dateAdded.constructor.name == "Date", "dateAdded should be a Date");
- Assert.ok(info.lastModified.constructor.name == "Date", "lastModified should be a Date");
- Assert.ok(info.lastModified >= info.dateAdded, "lastModified should never be smaller than dateAdded");
- Assert.ok(typeof info.type == "number", "type should be a number");
-}
-
-/**
- * Reads foreign_count value for a given url.
- */
-function* foreign_count(url) {
- if (url instanceof Ci.nsIURI)
- url = url.spec;
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.executeCached(
- `SELECT foreign_count FROM moz_places
- WHERE url_hash = hash(:url) AND url = :url
- `, { url });
- return rows.length == 0 ? 0 : rows[0].getResultByName("foreign_count");
-}
diff --git a/toolkit/components/places/tests/history/.eslintrc.js b/toolkit/components/places/tests/history/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/history/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/history/head_history.js b/toolkit/components/places/tests/history/head_history.js
deleted file mode 100644
index 870802dc1..000000000
--- a/toolkit/components/places/tests/history/head_history.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
diff --git a/toolkit/components/places/tests/history/test_insert.js b/toolkit/components/places/tests/history/test_insert.js
deleted file mode 100644
index e2884af8c..000000000
--- a/toolkit/components/places/tests/history/test_insert.js
+++ /dev/null
@@ -1,257 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-
-// Tests for `History.insert` and `History.insertMany`, as implemented in History.jsm
-
-"use strict";
-
-add_task(function* test_insert_error_cases() {
- const TEST_URL = "http://mozilla.com";
-
- Assert.throws(
- () => PlacesUtils.history.insert(),
- /TypeError: pageInfo must be an object/,
- "passing a null into History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert(1),
- /TypeError: pageInfo must be an object/,
- "passing a non object into History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({}),
- /TypeError: PageInfo object must have a url property/,
- "passing an object without a url to History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({url: 123}),
- /TypeError: Invalid url or guid: 123/,
- "passing an object with an invalid url to History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({url: TEST_URL}),
- /TypeError: PageInfo object must have an array of visits/,
- "passing an object without a visits property to History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({url: TEST_URL, visits: 1}),
- /TypeError: PageInfo object must have an array of visits/,
- "passing an object with a non-array visits property to History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({url: TEST_URL, visits: []}),
- /TypeError: PageInfo object must have an array of visits/,
- "passing an object with an empty array as the visits property to History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({
- url: TEST_URL,
- visits: [
- {
- transition: TRANSITION_LINK,
- date: "a"
- }
- ]}),
- /TypeError: Expected a Date, got a/,
- "passing a visit object with an invalid date to History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({
- url: TEST_URL,
- visits: [
- {
- transition: TRANSITION_LINK
- },
- {
- transition: TRANSITION_LINK,
- date: "a"
- }
- ]}),
- /TypeError: Expected a Date, got a/,
- "passing a second visit object with an invalid date to History.insert should throw a TypeError"
- );
- let futureDate = new Date();
- futureDate.setDate(futureDate.getDate() + 1000);
- Assert.throws(
- () => PlacesUtils.history.insert({
- url: TEST_URL,
- visits: [
- {
- transition: TRANSITION_LINK,
- date: futureDate,
- }
- ]}),
- `TypeError: date: ${futureDate} is not a valid date`,
- "passing a visit object with a future date to History.insert should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insert({
- url: TEST_URL,
- visits: [
- {transition: "a"}
- ]}),
- /TypeError: transition: a is not a valid transition type/,
- "passing a visit object with an invalid transition to History.insert should throw a TypeError"
- );
-});
-
-add_task(function* test_history_insert() {
- const TEST_URL = "http://mozilla.com/";
-
- let inserter = Task.async(function*(name, filter, referrer, date, transition) {
- do_print(name);
- do_print(`filter: ${filter}, referrer: ${referrer}, date: ${date}, transition: ${transition}`);
-
- let uri = NetUtil.newURI(TEST_URL + Math.random());
- let title = "Visit " + Math.random();
-
- let pageInfo = {
- title,
- visits: [
- {transition: transition, referrer: referrer, date: date, }
- ]
- };
-
- pageInfo.url = yield filter(uri);
-
- let result = yield PlacesUtils.history.insert(pageInfo);
-
- Assert.ok(PlacesUtils.isValidGuid(result.guid), "guid for pageInfo object is valid");
- Assert.equal(uri.spec, result.url.href, "url is correct for pageInfo object");
- Assert.equal(title, result.title, "title is correct for pageInfo object");
- Assert.equal(TRANSITION_LINK, result.visits[0].transition, "transition is correct for pageInfo object");
- if (referrer) {
- Assert.equal(referrer, result.visits[0].referrer.href, "url of referrer for visit is correct");
- } else {
- Assert.equal(null, result.visits[0].referrer, "url of referrer for visit is correct");
- }
- if (date) {
- Assert.equal(Number(date),
- Number(result.visits[0].date),
- "date of visit is correct");
- }
-
- Assert.ok(yield PlacesTestUtils.isPageInDB(uri), "Page was added");
- Assert.ok(yield PlacesTestUtils.visitsInDB(uri), "Visit was added");
- });
-
- try {
- for (let referrer of [TEST_URL, null]) {
- for (let date of [new Date(), null]) {
- for (let transition of [TRANSITION_LINK, null]) {
- yield inserter("Testing History.insert() with an nsIURI", x => x, referrer, date, transition);
- yield inserter("Testing History.insert() with a string url", x => x.spec, referrer, date, transition);
- yield inserter("Testing History.insert() with a URL object", x => new URL(x.spec), referrer, date, transition);
- }
- }
- }
- } finally {
- yield PlacesTestUtils.clearHistory();
- }
-});
-
-add_task(function* test_insert_multiple_error_cases() {
- let validPageInfo = {
- url: "http://mozilla.com",
- visits: [
- {transition: TRANSITION_LINK}
- ]
- };
-
- Assert.throws(
- () => PlacesUtils.history.insertMany(),
- /TypeError: pageInfos must be an array/,
- "passing a null into History.insertMany should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insertMany([]),
- /TypeError: pageInfos may not be an empty array/,
- "passing an empty array into History.insertMany should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.insertMany([validPageInfo, {}]),
- /TypeError: PageInfo object must have a url property/,
- "passing a second invalid PageInfo object to History.insertMany should throw a TypeError"
- );
-});
-
-add_task(function* test_history_insertMany() {
- const BAD_URLS = ["about:config", "chrome://browser/content/browser.xul"];
- const GOOD_URLS = [1, 2, 3].map(x => { return `http://mozilla.com/${x}`; });
-
- let makePageInfos = Task.async(function*(urls, filter = x => x) {
- let pageInfos = [];
- for (let url of urls) {
- let uri = NetUtil.newURI(url);
-
- let pageInfo = {
- title: `Visit to ${url}`,
- visits: [
- {transition: TRANSITION_LINK}
- ]
- };
-
- pageInfo.url = yield filter(uri);
- pageInfos.push(pageInfo);
- }
- return pageInfos;
- });
-
- let inserter = Task.async(function*(name, filter, useCallbacks) {
- do_print(name);
- do_print(`filter: ${filter}`);
- do_print(`useCallbacks: ${useCallbacks}`);
- yield PlacesTestUtils.clearHistory();
-
- let result;
- let allUrls = GOOD_URLS.concat(BAD_URLS);
- let pageInfos = yield makePageInfos(allUrls, filter);
-
- if (useCallbacks) {
- let onResultUrls = [];
- let onErrorUrls = [];
- result = yield PlacesUtils.history.insertMany(pageInfos, pageInfo => {
- let url = pageInfo.url.href;
- Assert.ok(GOOD_URLS.includes(url), "onResult callback called for correct url");
- onResultUrls.push(url);
- Assert.equal(`Visit to ${url}`, pageInfo.title, "onResult callback provides the correct title");
- Assert.ok(PlacesUtils.isValidGuid(pageInfo.guid), "onResult callback provides a valid guid");
- }, pageInfo => {
- let url = pageInfo.url.href;
- Assert.ok(BAD_URLS.includes(url), "onError callback called for correct uri");
- onErrorUrls.push(url);
- Assert.equal(undefined, pageInfo.title, "onError callback provides the correct title");
- Assert.equal(undefined, pageInfo.guid, "onError callback provides the expected guid");
- });
- Assert.equal(GOOD_URLS.sort().toString(), onResultUrls.sort().toString(), "onResult callback was called for each good url");
- Assert.equal(BAD_URLS.sort().toString(), onErrorUrls.sort().toString(), "onError callback was called for each bad url");
- } else {
- result = yield PlacesUtils.history.insertMany(pageInfos);
- }
-
- Assert.equal(undefined, result, "insertMany returned undefined");
-
- for (let url of allUrls) {
- let expected = GOOD_URLS.includes(url);
- Assert.equal(expected, yield PlacesTestUtils.isPageInDB(url), `isPageInDB for ${url} is ${expected}`);
- Assert.equal(expected, yield PlacesTestUtils.visitsInDB(url), `visitsInDB for ${url} is ${expected}`);
- }
- });
-
- try {
- for (let useCallbacks of [false, true]) {
- yield inserter("Testing History.insertMany() with an nsIURI", x => x, useCallbacks);
- yield inserter("Testing History.insertMany() with a string url", x => x.spec, useCallbacks);
- yield inserter("Testing History.insertMany() with a URL object", x => new URL(x.spec), useCallbacks);
- }
- // Test rejection when no items added
- let pageInfos = yield makePageInfos(BAD_URLS);
- PlacesUtils.history.insertMany(pageInfos).then(() => {
- Assert.ok(false, "History.insertMany rejected promise with all bad URLs");
- }, error => {
- Assert.equal("No items were added to history.", error.message, "History.insertMany rejected promise with all bad URLs");
- });
- } finally {
- yield PlacesTestUtils.clearHistory();
- }
-});
diff --git a/toolkit/components/places/tests/history/test_remove.js b/toolkit/components/places/tests/history/test_remove.js
deleted file mode 100644
index 7423f6464..000000000
--- a/toolkit/components/places/tests/history/test_remove.js
+++ /dev/null
@@ -1,360 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-
-// Tests for `History.remove`, as implemented in History.jsm
-
-"use strict";
-
-Cu.importGlobalProperties(["URL"]);
-
-
-// Test removing a single page
-add_task(function* test_remove_single() {
- yield PlacesTestUtils.clearHistory();
- yield PlacesUtils.bookmarks.eraseEverything();
-
-
- let WITNESS_URI = NetUtil.newURI("http://mozilla.com/test_browserhistory/test_remove/" + Math.random());
- yield PlacesTestUtils.addVisits(WITNESS_URI);
- Assert.ok(page_in_database(WITNESS_URI));
-
- let remover = Task.async(function*(name, filter, options) {
- do_print(name);
- do_print(JSON.stringify(options));
- do_print("Setting up visit");
-
- let uri = NetUtil.newURI("http://mozilla.com/test_browserhistory/test_remove/" + Math.random());
- let title = "Visit " + Math.random();
- yield PlacesTestUtils.addVisits({uri: uri, title: title});
- Assert.ok(visits_in_database(uri), "History entry created");
-
- let removeArg = yield filter(uri);
-
- if (options.addBookmark) {
- PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test bookmark");
- }
-
- let shouldRemove = !options.addBookmark;
- let observer;
- let promiseObserved = new Promise((resolve, reject) => {
- observer = {
- onBeginUpdateBatch: function() {},
- onEndUpdateBatch: function() {},
- onVisit: function(aUri) {
- reject(new Error("Unexpected call to onVisit " + aUri.spec));
- },
- onTitleChanged: function(aUri) {
- reject(new Error("Unexpected call to onTitleChanged " + aUri.spec));
- },
- onClearHistory: function() {
- reject("Unexpected call to onClearHistory");
- },
- onPageChanged: function(aUri) {
- reject(new Error("Unexpected call to onPageChanged " + aUri.spec));
- },
- onFrecencyChanged: function(aURI) {
- try {
- Assert.ok(!shouldRemove, "Observing onFrecencyChanged");
- Assert.equal(aURI.spec, uri.spec, "Observing effect on the right uri");
- } finally {
- resolve();
- }
- },
- onManyFrecenciesChanged: function() {
- try {
- Assert.ok(!shouldRemove, "Observing onManyFrecenciesChanged");
- } finally {
- resolve();
- }
- },
- onDeleteURI: function(aURI) {
- try {
- Assert.ok(shouldRemove, "Observing onDeleteURI");
- Assert.equal(aURI.spec, uri.spec, "Observing effect on the right uri");
- } finally {
- resolve();
- }
- },
- onDeleteVisits: function(aURI) {
- Assert.equal(aURI.spec, uri.spec, "Observing onDeleteVisits on the right uri");
- }
- };
- });
- PlacesUtils.history.addObserver(observer, false);
-
- do_print("Performing removal");
- let removed = false;
- if (options.useCallback) {
- let onRowCalled = false;
- let guid = do_get_guid_for_uri(uri);
- removed = yield PlacesUtils.history.remove(removeArg, page => {
- Assert.equal(onRowCalled, false, "Callback has not been called yet");
- onRowCalled = true;
- Assert.equal(page.url.href, uri.spec, "Callback provides the correct url");
- Assert.equal(page.guid, guid, "Callback provides the correct guid");
- Assert.equal(page.title, title, "Callback provides the correct title");
- });
- Assert.ok(onRowCalled, "Callback has been called");
- } else {
- removed = yield PlacesUtils.history.remove(removeArg);
- }
-
- yield promiseObserved;
- PlacesUtils.history.removeObserver(observer);
-
- Assert.equal(visits_in_database(uri), 0, "History entry has disappeared");
- Assert.notEqual(visits_in_database(WITNESS_URI), 0, "Witness URI still has visits");
- Assert.notEqual(page_in_database(WITNESS_URI), 0, "Witness URI is still here");
- if (shouldRemove) {
- Assert.ok(removed, "Something was removed");
- Assert.equal(page_in_database(uri), 0, "Page has disappeared");
- } else {
- Assert.ok(!removed, "The page was not removed, as there was a bookmark");
- Assert.notEqual(page_in_database(uri), 0, "The page is still present");
- }
- });
-
- try {
- for (let useCallback of [false, true]) {
- for (let addBookmark of [false, true]) {
- let options = { useCallback: useCallback, addBookmark: addBookmark };
- yield remover("Testing History.remove() with a single URI", x => x, options);
- yield remover("Testing History.remove() with a single string url", x => x.spec, options);
- yield remover("Testing History.remove() with a single string guid", x => do_get_guid_for_uri(x), options);
- yield remover("Testing History.remove() with a single URI in an array", x => [x], options);
- yield remover("Testing History.remove() with a single string url in an array", x => [x.spec], options);
- yield remover("Testing History.remove() with a single string guid in an array", x => [do_get_guid_for_uri(x)], options);
- }
- }
- } finally {
- yield PlacesTestUtils.clearHistory();
- }
- return;
-});
-
-// Test removing a list of pages
-add_task(function* test_remove_many() {
- const SIZE = 10;
-
- yield PlacesTestUtils.clearHistory();
- yield PlacesUtils.bookmarks.eraseEverything();
-
- do_print("Adding a witness page");
- let WITNESS_URI = NetUtil.newURI("http://mozilla.com/test_browserhistory/test_remove/" + Math.random());
- yield PlacesTestUtils.addVisits(WITNESS_URI);
- Assert.ok(page_in_database(WITNESS_URI), "Witness page added");
-
- do_print("Generating samples");
- let pages = [];
- for (let i = 0; i < SIZE; ++i) {
- let uri = NetUtil.newURI("http://mozilla.com/test_browserhistory/test_remove?sample=" + i + "&salt=" + Math.random());
- let title = "Visit " + i + ", " + Math.random();
- let hasBookmark = i % 3 == 0;
- let page = {
- uri: uri,
- title: title,
- hasBookmark: hasBookmark,
- // `true` once `onResult` has been called for this page
- onResultCalled: false,
- // `true` once `onDeleteVisits` has been called for this page
- onDeleteVisitsCalled: false,
- // `true` once `onFrecencyChangedCalled` has been called for this page
- onFrecencyChangedCalled: false,
- // `true` once `onDeleteURI` has been called for this page
- onDeleteURICalled: false,
- };
- do_print("Pushing: " + uri.spec);
- pages.push(page);
-
- yield PlacesTestUtils.addVisits(page);
- page.guid = do_get_guid_for_uri(uri);
- if (hasBookmark) {
- PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test bookmark " + i);
- }
- Assert.ok(page_in_database(uri), "Page added");
- }
-
- do_print("Mixing key types and introducing dangling keys");
- let keys = [];
- for (let i = 0; i < SIZE; ++i) {
- if (i % 4 == 0) {
- keys.push(pages[i].uri);
- keys.push(NetUtil.newURI("http://example.org/dangling/nsIURI/" + i));
- } else if (i % 4 == 1) {
- keys.push(new URL(pages[i].uri.spec));
- keys.push(new URL("http://example.org/dangling/URL/" + i));
- } else if (i % 4 == 2) {
- keys.push(pages[i].uri.spec);
- keys.push("http://example.org/dangling/stringuri/" + i);
- } else {
- keys.push(pages[i].guid);
- keys.push(("guid_" + i + "_01234567890").substr(0, 12));
- }
- }
-
- let observer = {
- onBeginUpdateBatch: function() {},
- onEndUpdateBatch: function() {},
- onVisit: function(aURI) {
- Assert.ok(false, "Unexpected call to onVisit " + aURI.spec);
- },
- onTitleChanged: function(aURI) {
- Assert.ok(false, "Unexpected call to onTitleChanged " + aURI.spec);
- },
- onClearHistory: function() {
- Assert.ok(false, "Unexpected call to onClearHistory");
- },
- onPageChanged: function(aURI) {
- Assert.ok(false, "Unexpected call to onPageChanged " + aURI.spec);
- },
- onFrecencyChanged: function(aURI) {
- let origin = pages.find(x => x.uri.spec == aURI.spec);
- Assert.ok(origin);
- Assert.ok(origin.hasBookmark, "Observing onFrecencyChanged on a page with a bookmark");
- origin.onFrecencyChangedCalled = true;
- // We do not make sure that `origin.onFrecencyChangedCalled` is `false`, as
- },
- onManyFrecenciesChanged: function() {
- Assert.ok(false, "Observing onManyFrecenciesChanges, this is most likely correct but not covered by this test");
- },
- onDeleteURI: function(aURI) {
- let origin = pages.find(x => x.uri.spec == aURI.spec);
- Assert.ok(origin);
- Assert.ok(!origin.hasBookmark, "Observing onDeleteURI on a page without a bookmark");
- Assert.ok(!origin.onDeleteURICalled, "Observing onDeleteURI for the first time");
- origin.onDeleteURICalled = true;
- },
- onDeleteVisits: function(aURI) {
- let origin = pages.find(x => x.uri.spec == aURI.spec);
- Assert.ok(origin);
- Assert.ok(!origin.onDeleteVisitsCalled, "Observing onDeleteVisits for the first time");
- origin.onDeleteVisitsCalled = true;
- }
- };
- PlacesUtils.history.addObserver(observer, false);
-
- do_print("Removing the pages and checking the callbacks");
- let removed = yield PlacesUtils.history.remove(keys, page => {
- let origin = pages.find(candidate => candidate.uri.spec == page.url.href);
-
- Assert.ok(origin, "onResult has a valid page");
- Assert.ok(!origin.onResultCalled, "onResult has not seen this page yet");
- origin.onResultCalled = true;
- Assert.equal(page.guid, origin.guid, "onResult has the right guid");
- Assert.equal(page.title, origin.title, "onResult has the right title");
- });
- Assert.ok(removed, "Something was removed");
-
- PlacesUtils.history.removeObserver(observer);
-
- do_print("Checking out results");
- // By now the observers should have been called.
- for (let i = 0; i < pages.length; ++i) {
- let page = pages[i];
- do_print("Page: " + i);
- Assert.ok(page.onResultCalled, "We have reached the page from the callback");
- Assert.ok(visits_in_database(page.uri) == 0, "History entry has disappeared");
- Assert.equal(page_in_database(page.uri) != 0, page.hasBookmark, "Page is present only if it also has bookmarks");
- Assert.equal(page.onFrecencyChangedCalled, page.onDeleteVisitsCalled, "onDeleteVisits was called iff onFrecencyChanged was called");
- Assert.ok(page.onFrecencyChangedCalled ^ page.onDeleteURICalled, "Either onFrecencyChanged or onDeleteURI was called");
- }
-
- Assert.notEqual(visits_in_database(WITNESS_URI), 0, "Witness URI still has visits");
- Assert.notEqual(page_in_database(WITNESS_URI), 0, "Witness URI is still here");
-});
-
-add_task(function* cleanup() {
- yield PlacesTestUtils.clearHistory();
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-// Test the various error cases
-add_task(function* test_error_cases() {
- Assert.throws(
- () => PlacesUtils.history.remove(),
- /TypeError: Invalid url/,
- "History.remove with no argument should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove(null),
- /TypeError: Invalid url/,
- "History.remove with `null` should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove(undefined),
- /TypeError: Invalid url/,
- "History.remove with `undefined` should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove("not a guid, obviously"),
- /TypeError: .* is not a valid URL/,
- "History.remove with an ill-formed guid/url argument should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove({"not the kind of object we know how to handle": true}),
- /TypeError: Invalid url/,
- "History.remove with an unexpected object should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove([]),
- /TypeError: Expected at least one page/,
- "History.remove with an empty array should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove([null]),
- /TypeError: Invalid url or guid/,
- "History.remove with an array containing null should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove(["http://example.org", "not a guid, obviously"]),
- /TypeError: .* is not a valid URL/,
- "History.remove with an array containing an ill-formed guid/url argument should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove(["0123456789ab"/* valid guid*/, null]),
- /TypeError: Invalid url or guid: null/,
- "History.remove with an array containing a guid and a second argument that is null should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove(["http://example.org", {"not the kind of object we know how to handle": true}]),
- /TypeError: Invalid url/,
- "History.remove with an array containing an unexpected objecgt should throw a TypeError"
- );
- Assert.throws(
- () => PlacesUtils.history.remove("http://example.org", "not a function, obviously"),
- /TypeError: Invalid function/,
- "History.remove with a second argument that is not a function argument should throw a TypeError"
- );
- try {
- PlacesUtils.history.remove("http://example.org/I/have/clearly/not/been/added", null);
- Assert.ok(true, "History.remove should ignore `null` as a second argument");
- } catch (ex) {
- Assert.ok(false, "History.remove should ignore `null` as a second argument");
- }
-});
-
-add_task(function* test_orphans() {
- let uri = NetUtil.newURI("http://moz.org/");
- yield PlacesTestUtils.addVisits({ uri });
-
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- uri, SMALLPNG_DATA_URI, true, PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null, Services.scriptSecurityManager.getSystemPrincipal());
- PlacesUtils.annotations.setPageAnnotation(uri, "test", "restval", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-
- yield PlacesUtils.history.remove(uri);
- Assert.ok(!(yield PlacesTestUtils.isPageInDB(uri)), "Page should have been removed");
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(`SELECT (SELECT count(*) FROM moz_annos) +
- (SELECT count(*) FROM moz_favicons) AS count`);
- Assert.equal(rows[0].getResultByName("count"), 0, "Should not find orphans");
-});
diff --git a/toolkit/components/places/tests/history/test_removeVisits.js b/toolkit/components/places/tests/history/test_removeVisits.js
deleted file mode 100644
index 8df0c81a9..000000000
--- a/toolkit/components/places/tests/history/test_removeVisits.js
+++ /dev/null
@@ -1,316 +0,0 @@
-const JS_NOW = Date.now();
-const DB_NOW = JS_NOW * 1000;
-const TEST_URI = uri("http://example.com/");
-const PLACE_URI = uri("place:queryType=0&sort=8&maxResults=10");
-
-function* cleanup() {
- yield PlacesTestUtils.clearHistory();
- yield PlacesUtils.bookmarks.eraseEverything();
- // This is needed to remove place: entries.
- DBConn().executeSimpleSQL("DELETE FROM moz_places");
-}
-
-add_task(function* remove_visits_outside_unbookmarked_uri() {
- do_print("*** TEST: Remove some visits outside valid timeframe from an unbookmarked URI");
-
- do_print("Add 10 visits for the URI from way in the past.");
- let visits = [];
- for (let i = 0; i < 10; i++) {
- visits.push({ uri: TEST_URI, visitDate: DB_NOW - 100000 - (i * 1000) });
- }
- yield PlacesTestUtils.addVisits(visits);
-
- do_print("Remove visits using timerange outside the URI's visits.");
- let filter = {
- beginDate: new Date(JS_NOW - 10),
- endDate: new Date(JS_NOW)
- };
- yield PlacesUtils.history.removeVisitsByFilter(filter);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI should still exist in moz_places.");
- do_check_true(page_in_database(TEST_URI.spec));
-
- do_print("Run a history query and check that all visits still exist.");
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_VISIT;
- opts.sortingMode = opts.SORT_BY_DATE_DESCENDING;
- let root = PlacesUtils.history.executeQuery(query, opts).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 10);
- for (let i = 0; i < root.childCount; i++) {
- let visitTime = root.getChild(i).time;
- do_check_eq(visitTime, DB_NOW - 100000 - (i * 1000));
- }
- root.containerOpen = false;
-
- do_print("asyncHistory.isURIVisited should return true.");
- do_check_true(yield promiseIsURIVisited(TEST_URI));
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("Frecency should be positive.")
- do_check_true(frecencyForUrl(TEST_URI) > 0);
-
- yield cleanup();
-});
-
-add_task(function* remove_visits_outside_bookmarked_uri() {
- do_print("*** TEST: Remove some visits outside valid timeframe from a bookmarked URI");
-
- do_print("Add 10 visits for the URI from way in the past.");
- let visits = [];
- for (let i = 0; i < 10; i++) {
- visits.push({ uri: TEST_URI, visitDate: DB_NOW - 100000 - (i * 1000) });
- }
- yield PlacesTestUtils.addVisits(visits);
- do_print("Bookmark the URI.");
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark title");
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Remove visits using timerange outside the URI's visits.");
- let filter = {
- beginDate: new Date(JS_NOW - 10),
- endDate: new Date(JS_NOW)
- };
- yield PlacesUtils.history.removeVisitsByFilter(filter);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI should still exist in moz_places.");
- do_check_true(page_in_database(TEST_URI.spec));
-
- do_print("Run a history query and check that all visits still exist.");
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_VISIT;
- opts.sortingMode = opts.SORT_BY_DATE_DESCENDING;
- let root = PlacesUtils.history.executeQuery(query, opts).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 10);
- for (let i = 0; i < root.childCount; i++) {
- let visitTime = root.getChild(i).time;
- do_check_eq(visitTime, DB_NOW - 100000 - (i * 1000));
- }
- root.containerOpen = false;
-
- do_print("asyncHistory.isURIVisited should return true.");
- do_check_true(yield promiseIsURIVisited(TEST_URI));
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Frecency should be positive.")
- do_check_true(frecencyForUrl(TEST_URI) > 0);
-
- yield cleanup();
-});
-
-add_task(function* remove_visits_unbookmarked_uri() {
- do_print("*** TEST: Remove some visits from an unbookmarked URI");
-
- do_print("Add 10 visits for the URI from now to 9 usecs in the past.");
- let visits = [];
- for (let i = 0; i < 10; i++) {
- visits.push({ uri: TEST_URI, visitDate: DB_NOW - (i * 1000) });
- }
- yield PlacesTestUtils.addVisits(visits);
-
- do_print("Remove the 5 most recent visits.");
- let filter = {
- beginDate: new Date(JS_NOW - 4),
- endDate: new Date(JS_NOW)
- };
- yield PlacesUtils.history.removeVisitsByFilter(filter);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI should still exist in moz_places.");
- do_check_true(page_in_database(TEST_URI.spec));
-
- do_print("Run a history query and check that only the older 5 visits still exist.");
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_VISIT;
- opts.sortingMode = opts.SORT_BY_DATE_DESCENDING;
- let root = PlacesUtils.history.executeQuery(query, opts).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 5);
- for (let i = 0; i < root.childCount; i++) {
- let visitTime = root.getChild(i).time;
- do_check_eq(visitTime, DB_NOW - (i * 1000) - 5000);
- }
- root.containerOpen = false;
-
- do_print("asyncHistory.isURIVisited should return true.");
- do_check_true(yield promiseIsURIVisited(TEST_URI));
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Frecency should be positive.")
- do_check_true(frecencyForUrl(TEST_URI) > 0);
-
- yield cleanup();
-});
-
-add_task(function* remove_visits_bookmarked_uri() {
- do_print("*** TEST: Remove some visits from a bookmarked URI");
-
- do_print("Add 10 visits for the URI from now to 9 usecs in the past.");
- let visits = [];
- for (let i = 0; i < 10; i++) {
- visits.push({ uri: TEST_URI, visitDate: DB_NOW - (i * 1000) });
- }
- yield PlacesTestUtils.addVisits(visits);
- do_print("Bookmark the URI.");
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark title");
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Remove the 5 most recent visits.");
- let filter = {
- beginDate: new Date(JS_NOW - 4),
- endDate: new Date(JS_NOW)
- };
- yield PlacesUtils.history.removeVisitsByFilter(filter);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI should still exist in moz_places.");
- do_check_true(page_in_database(TEST_URI.spec));
-
- do_print("Run a history query and check that only the older 5 visits still exist.");
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_VISIT;
- opts.sortingMode = opts.SORT_BY_DATE_DESCENDING;
- let root = PlacesUtils.history.executeQuery(query, opts).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 5);
- for (let i = 0; i < root.childCount; i++) {
- let visitTime = root.getChild(i).time;
- do_check_eq(visitTime, DB_NOW - (i * 1000) - 5000);
- }
- root.containerOpen = false;
-
- do_print("asyncHistory.isURIVisited should return true.");
- do_check_true(yield promiseIsURIVisited(TEST_URI));
- yield PlacesTestUtils.promiseAsyncUpdates()
-
- do_print("Frecency should be positive.")
- do_check_true(frecencyForUrl(TEST_URI) > 0);
-
- yield cleanup();
-});
-
-add_task(function* remove_all_visits_unbookmarked_uri() {
- do_print("*** TEST: Remove all visits from an unbookmarked URI");
-
- do_print("Add some visits for the URI.");
- let visits = [];
- for (let i = 0; i < 10; i++) {
- visits.push({ uri: TEST_URI, visitDate: DB_NOW - (i * 1000) });
- }
- yield PlacesTestUtils.addVisits(visits);
-
- do_print("Remove all visits.");
- let filter = {
- beginDate: new Date(JS_NOW - 10),
- endDate: new Date(JS_NOW)
- };
- yield PlacesUtils.history.removeVisitsByFilter(filter);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI should no longer exist in moz_places.");
- do_check_false(page_in_database(TEST_URI.spec));
-
- do_print("Run a history query and check that no visits exist.");
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_VISIT;
- opts.sortingMode = opts.SORT_BY_DATE_DESCENDING;
- let root = PlacesUtils.history.executeQuery(query, opts).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 0);
- root.containerOpen = false;
-
- do_print("asyncHistory.isURIVisited should return false.");
- do_check_false(yield promiseIsURIVisited(TEST_URI));
-
- yield cleanup();
-});
-
-add_task(function* remove_all_visits_bookmarked_uri() {
- do_print("*** TEST: Remove all visits from a bookmarked URI");
-
- do_print("Add some visits for the URI.");
- let visits = [];
- for (let i = 0; i < 10; i++) {
- visits.push({ uri: TEST_URI, visitDate: DB_NOW - (i * 1000) });
- }
- yield PlacesTestUtils.addVisits(visits);
- do_print("Bookmark the URI.");
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark title");
- yield PlacesTestUtils.promiseAsyncUpdates();
- let initialFrecency = frecencyForUrl(TEST_URI);
-
- do_print("Remove all visits.");
- let filter = {
- beginDate: new Date(JS_NOW - 10),
- endDate: new Date(JS_NOW)
- };
- yield PlacesUtils.history.removeVisitsByFilter(filter);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI should still exist in moz_places.");
- do_check_true(page_in_database(TEST_URI.spec));
-
- do_print("Run a history query and check that no visits exist.");
- let query = PlacesUtils.history.getNewQuery();
- let opts = PlacesUtils.history.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_VISIT;
- opts.sortingMode = opts.SORT_BY_DATE_DESCENDING;
- let root = PlacesUtils.history.executeQuery(query, opts).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 0);
- root.containerOpen = false;
-
- do_print("asyncHistory.isURIVisited should return false.");
- do_check_false(yield promiseIsURIVisited(TEST_URI));
-
- do_print("nsINavBookmarksService.isBookmarked should return true.");
- do_check_true(PlacesUtils.bookmarks.isBookmarked(TEST_URI));
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Frecency should be smaller.")
- do_check_true(frecencyForUrl(TEST_URI) < initialFrecency);
-
- yield cleanup();
-});
-
-add_task(function* remove_all_visits_bookmarked_uri() {
- do_print("*** TEST: Remove some visits from a zero frecency URI retains zero frecency");
-
- do_print("Add some visits for the URI.");
- yield PlacesTestUtils.addVisits([
- { uri: TEST_URI, transition: TRANSITION_FRAMED_LINK, visitDate: (DB_NOW - 86400000000000) },
- { uri: TEST_URI, transition: TRANSITION_FRAMED_LINK, visitDate: DB_NOW }
- ]);
-
- do_print("Remove newer visit.");
- let filter = {
- beginDate: new Date(JS_NOW - 10),
- endDate: new Date(JS_NOW)
- };
- yield PlacesUtils.history.removeVisitsByFilter(filter);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI should still exist in moz_places.");
- do_check_true(page_in_database(TEST_URI.spec));
- do_print("Frecency should be zero.")
- do_check_eq(frecencyForUrl(TEST_URI), 0);
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/history/test_removeVisitsByFilter.js b/toolkit/components/places/tests/history/test_removeVisitsByFilter.js
deleted file mode 100644
index 699420e43..000000000
--- a/toolkit/components/places/tests/history/test_removeVisitsByFilter.js
+++ /dev/null
@@ -1,345 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-
-// Tests for `History.removeVisitsByFilter`, as implemented in History.jsm
-
-"use strict";
-
-Cu.importGlobalProperties(["URL"]);
-
-Cu.import("resource://gre/modules/PromiseUtils.jsm", this);
-
-add_task(function* test_removeVisitsByFilter() {
- let referenceDate = new Date(1999, 9, 9, 9, 9);
-
- // Populate a database with 20 entries, remove a subset of entries,
- // ensure consistency.
- let remover = Task.async(function*(options) {
- do_print("Remover with options " + JSON.stringify(options));
- let SAMPLE_SIZE = options.sampleSize;
-
- yield PlacesTestUtils.clearHistory();
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // Populate the database.
- // Create `SAMPLE_SIZE` visits, from the oldest to the newest.
-
- let bookmarkIndices = new Set(options.bookmarks);
- let visits = [];
- let frecencyChangePromises = new Map();
- let uriDeletePromises = new Map();
- let getURL = options.url ?
- i => "http://mozilla.com/test_browserhistory/test_removeVisitsByFilter/removeme/byurl/" + Math.floor(i / (SAMPLE_SIZE / 5)) + "/" :
- i => "http://mozilla.com/test_browserhistory/test_removeVisitsByFilter/removeme/" + i + "/" + Math.random();
- for (let i = 0; i < SAMPLE_SIZE; ++i) {
- let spec = getURL(i);
- let uri = NetUtil.newURI(spec);
- let jsDate = new Date(Number(referenceDate) + 3600 * 1000 * i);
- let dbDate = jsDate * 1000;
- let hasBookmark = bookmarkIndices.has(i);
- let hasOwnBookmark = hasBookmark;
- if (!hasOwnBookmark && options.url) {
- // Also mark as bookmarked if one of the earlier bookmarked items has the same URL.
- hasBookmark =
- options.bookmarks.filter(n => n < i).some(n => visits[n].uri.spec == spec && visits[n].test.hasBookmark);
- }
- do_print("Generating " + uri.spec + ", " + dbDate);
- let visit = {
- uri,
- title: "visit " + i,
- visitDate: dbDate,
- test: {
- // `visitDate`, as a Date
- jsDate: jsDate,
- // `true` if we expect that the visit will be removed
- toRemove: false,
- // `true` if `onRow` informed of the removal of this visit
- announcedByOnRow: false,
- // `true` if there is a bookmark for this URI, i.e. of the page
- // should not be entirely removed.
- hasBookmark: hasBookmark,
- onFrecencyChanged: null,
- onDeleteURI: null,
- },
- };
- visits.push(visit);
- if (hasOwnBookmark) {
- do_print("Adding a bookmark to visit " + i);
- yield PlacesUtils.bookmarks.insert({
- url: uri,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "test bookmark"
- });
- do_print("Bookmark added");
- }
- }
-
- do_print("Adding visits");
- yield PlacesTestUtils.addVisits(visits);
-
- do_print("Preparing filters");
- let filter = {
- };
- let beginIndex = 0;
- let endIndex = visits.length - 1;
- if ("begin" in options) {
- let ms = Number(visits[options.begin].test.jsDate) - 1000;
- filter.beginDate = new Date(ms);
- beginIndex = options.begin;
- }
- if ("end" in options) {
- let ms = Number(visits[options.end].test.jsDate) + 1000;
- filter.endDate = new Date(ms);
- endIndex = options.end;
- }
- if ("limit" in options) {
- endIndex = beginIndex + options.limit - 1; // -1 because the start index is inclusive.
- filter.limit = options.limit;
- }
- let removedItems = visits.slice(beginIndex);
- endIndex -= beginIndex;
- if (options.url) {
- let rawURL = "";
- switch (options.url) {
- case 1:
- filter.url = new URL(removedItems[0].uri.spec);
- rawURL = filter.url.href;
- break;
- case 2:
- filter.url = removedItems[0].uri;
- rawURL = filter.url.spec;
- break;
- case 3:
- filter.url = removedItems[0].uri.spec;
- rawURL = filter.url;
- break;
- }
- endIndex = Math.min(endIndex, removedItems.findIndex((v, index) => v.uri.spec != rawURL) - 1);
- }
- removedItems.splice(endIndex + 1);
- let remainingItems = visits.filter(v => !removedItems.includes(v));
- for (let i = 0; i < removedItems.length; i++) {
- let test = removedItems[i].test;
- do_print("Marking visit " + (beginIndex + i) + " as expecting removal");
- test.toRemove = true;
- if (test.hasBookmark ||
- (options.url && remainingItems.some(v => v.uri.spec == removedItems[i].uri.spec))) {
- frecencyChangePromises.set(removedItems[i].uri.spec, PromiseUtils.defer());
- } else if (!options.url || i == 0) {
- uriDeletePromises.set(removedItems[i].uri.spec, PromiseUtils.defer());
- }
- }
-
- let observer = {
- deferred: PromiseUtils.defer(),
- onBeginUpdateBatch: function() {},
- onEndUpdateBatch: function() {},
- onVisit: function(uri) {
- this.deferred.reject(new Error("Unexpected call to onVisit " + uri.spec));
- },
- onTitleChanged: function(uri) {
- this.deferred.reject(new Error("Unexpected call to onTitleChanged " + uri.spec));
- },
- onClearHistory: function() {
- this.deferred.reject("Unexpected call to onClearHistory");
- },
- onPageChanged: function(uri) {
- this.deferred.reject(new Error("Unexpected call to onPageChanged " + uri.spec));
- },
- onFrecencyChanged: function(aURI) {
- do_print("onFrecencyChanged " + aURI.spec);
- let deferred = frecencyChangePromises.get(aURI.spec);
- Assert.ok(!!deferred, "Observing onFrecencyChanged");
- deferred.resolve();
- },
- onManyFrecenciesChanged: function() {
- do_print("Many frecencies changed");
- for (let [, deferred] of frecencyChangePromises) {
- deferred.resolve();
- }
- },
- onDeleteURI: function(aURI) {
- do_print("onDeleteURI " + aURI.spec);
- let deferred = uriDeletePromises.get(aURI.spec);
- Assert.ok(!!deferred, "Observing onDeleteURI");
- deferred.resolve();
- },
- onDeleteVisits: function(aURI) {
- // Not sure we can test anything.
- }
- };
- PlacesUtils.history.addObserver(observer, false);
-
- let cbarg;
- if (options.useCallback) {
- do_print("Setting up callback");
- cbarg = [info => {
- for (let visit of visits) {
- do_print("Comparing " + info.date + " and " + visit.test.jsDate);
- if (Math.abs(visit.test.jsDate - info.date) < 100) { // Assume rounding errors
- Assert.ok(!visit.test.announcedByOnRow,
- "This is the first time we announce the removal of this visit");
- Assert.ok(visit.test.toRemove,
- "This is a visit we intended to remove");
- visit.test.announcedByOnRow = true;
- return;
- }
- }
- Assert.ok(false, "Could not find the visit we attempt to remove");
- }];
- } else {
- do_print("No callback");
- cbarg = [];
- }
- let result = yield PlacesUtils.history.removeVisitsByFilter(filter, ...cbarg);
-
- Assert.ok(result, "Removal succeeded");
-
- // Make sure that we have eliminated exactly the entries we expected
- // to eliminate.
- for (let i = 0; i < visits.length; ++i) {
- let visit = visits[i];
- do_print("Controlling the results on visit " + i);
- let remainingVisitsForURI = remainingItems.filter(v => visit.uri.spec == v.uri.spec).length;
- Assert.equal(
- visits_in_database(visit.uri),
- remainingVisitsForURI,
- "Visit is still present iff expected");
- if (options.useCallback) {
- Assert.equal(
- visit.test.toRemove,
- visit.test.announcedByOnRow,
- "Visit removal has been announced by onResult iff expected");
- }
- if (visit.test.hasBookmark || remainingVisitsForURI) {
- Assert.notEqual(page_in_database(visit.uri), 0, "The page should still appear in the db");
- } else {
- Assert.equal(page_in_database(visit.uri), 0, "The page should have been removed from the db");
- }
- }
-
- // Make sure that the observer has been called wherever applicable.
- do_print("Checking URI delete promises.");
- yield Promise.all(Array.from(uriDeletePromises.values()));
- do_print("Checking frecency change promises.");
- yield Promise.all(Array.from(frecencyChangePromises.values()));
- PlacesUtils.history.removeObserver(observer);
- });
-
- let size = 20;
- for (let range of [
- {begin: 0},
- {end: 19},
- {begin: 0, end: 10},
- {begin: 3, end: 4},
- {begin: 5, end: 8, limit: 2},
- {begin: 10, end: 18, limit: 5},
- ]) {
- for (let bookmarks of [[], [5, 6]]) {
- let options = {
- sampleSize: size,
- bookmarks: bookmarks,
- };
- if ("begin" in range) {
- options.begin = range.begin;
- }
- if ("end" in range) {
- options.end = range.end;
- }
- if ("limit" in range) {
- options.limit = range.limit;
- }
- yield remover(options);
- options.url = 1;
- yield remover(options);
- options.url = 2;
- yield remover(options);
- options.url = 3;
- yield remover(options);
- }
- }
- yield PlacesTestUtils.clearHistory();
-});
-
-// Test the various error cases
-add_task(function* test_error_cases() {
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter(),
- /TypeError: Expected a filter/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter("obviously, not a filter"),
- /TypeError: Expected a filter/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({}),
- /TypeError: Expected a non-empty filter/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({beginDate: "now"}),
- /TypeError: Expected a Date/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({beginDate: Date.now()}),
- /TypeError: Expected a Date/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({beginDate: new Date()}, "obviously, not a callback"),
- /TypeError: Invalid function/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({beginDate: new Date(1000), endDate: new Date(0)}),
- /TypeError: `beginDate` should be at least as old/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({limit: {}}),
- /Expected a non-zero positive integer as a limit/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({limit: -1}),
- /Expected a non-zero positive integer as a limit/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({limit: 0.1}),
- /Expected a non-zero positive integer as a limit/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({limit: Infinity}),
- /Expected a non-zero positive integer as a limit/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({url: {}}),
- /Expected a valid URL for `url`/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({url: 0}),
- /Expected a valid URL for `url`/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({beginDate: new Date(1000), endDate: new Date(0)}),
- /TypeError: `beginDate` should be at least as old/
- );
- Assert.throws(
- () => PlacesUtils.history.removeVisitsByFilter({beginDate: new Date(1000), endDate: new Date(0)}),
- /TypeError: `beginDate` should be at least as old/
- );
-});
-
-add_task(function* test_orphans() {
- let uri = NetUtil.newURI("http://moz.org/");
- yield PlacesTestUtils.addVisits({ uri });
-
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- uri, SMALLPNG_DATA_URI, true, PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null, Services.scriptSecurityManager.getSystemPrincipal());
- PlacesUtils.annotations.setPageAnnotation(uri, "test", "restval", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-
- yield PlacesUtils.history.removeVisitsByFilter({ beginDate: new Date(1999, 9, 9, 9, 9),
- endDate: new Date() });
- Assert.ok(!(yield PlacesTestUtils.isPageInDB(uri)), "Page should have been removed");
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(`SELECT (SELECT count(*) FROM moz_annos) +
- (SELECT count(*) FROM moz_favicons) AS count`);
- Assert.equal(rows[0].getResultByName("count"), 0, "Should not find orphans");
-});
diff --git a/toolkit/components/places/tests/history/test_updatePlaces_sameUri_titleChanged.js b/toolkit/components/places/tests/history/test_updatePlaces_sameUri_titleChanged.js
deleted file mode 100644
index 832df9d9a..000000000
--- a/toolkit/components/places/tests/history/test_updatePlaces_sameUri_titleChanged.js
+++ /dev/null
@@ -1,52 +0,0 @@
-// Test that repeated additions of the same URI through updatePlaces, properly
-// update from_visit and notify titleChanged.
-
-add_task(function* test() {
- let uri = "http://test.com/";
-
- let promiseTitleChangedNotifications = new Promise(resolve => {
- let historyObserver = {
- _count: 0,
- __proto__: NavHistoryObserver.prototype,
- onTitleChanged(aURI, aTitle, aGUID) {
- Assert.equal(aURI.spec, uri, "Should notify the proper url");
- if (++this._count == 2) {
- PlacesUtils.history.removeObserver(historyObserver);
- resolve();
- }
- }
- };
- PlacesUtils.history.addObserver(historyObserver, false);
- });
-
- // This repeats the url on purpose, don't merge it into a single place entry.
- yield PlacesTestUtils.addVisits([
- { uri, title: "test" },
- { uri, referrer: uri, title: "test2" },
- ]);
-
- let options = PlacesUtils.history.getNewQueryOptions();
- let query = PlacesUtils.history.getNewQuery();
- query.uri = NetUtil.newURI(uri);
- options.resultType = options.RESULTS_AS_VISIT;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- Assert.equal(root.childCount, 2);
-
- let child = root.getChild(0);
- Assert.equal(child.visitType, TRANSITION_LINK, "Visit type should be TRANSITION_LINK");
- Assert.equal(child.visitId, 1, "Visit ID should be 1");
- Assert.equal(child.fromVisitId, -1, "Should have no referrer visit ID");
- Assert.equal(child.title, "test2", "Should have the correct title");
-
- child = root.getChild(1);
- Assert.equal(child.visitType, TRANSITION_LINK, "Visit type should be TRANSITION_LINK");
- Assert.equal(child.visitId, 2, "Visit ID should be 2");
- Assert.equal(child.fromVisitId, 1, "First visit should be the referring visit");
- Assert.equal(child.title, "test2", "Should have the correct title");
-
- root.containerOpen = false;
-
- yield promiseTitleChangedNotifications;
-});
diff --git a/toolkit/components/places/tests/history/xpcshell.ini b/toolkit/components/places/tests/history/xpcshell.ini
deleted file mode 100644
index ee182e090..000000000
--- a/toolkit/components/places/tests/history/xpcshell.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[DEFAULT]
-head = head_history.js
-tail =
-
-[test_insert.js]
-[test_remove.js]
-[test_removeVisits.js]
-[test_removeVisitsByFilter.js]
-[test_updatePlaces_sameUri_titleChanged.js]
diff --git a/toolkit/components/places/tests/migration/.eslintrc.js b/toolkit/components/places/tests/migration/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/migration/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/migration/head_migration.js b/toolkit/components/places/tests/migration/head_migration.js
deleted file mode 100644
index 1ebecd4c0..000000000
--- a/toolkit/components/places/tests/migration/head_migration.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict"
-
-var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
-
-const DB_FILENAME = "places.sqlite";
-
-/**
- * Sets the database to use for the given test. This should be the very first
- * thing in the test, otherwise this database will not be used!
- *
- * @param aFileName
- * The filename of the database to use. This database must exist in
- * toolkit/components/places/tests/migration!
- * @return {Promise}
- */
-var setupPlacesDatabase = Task.async(function* (aFileName) {
- let currentDir = yield OS.File.getCurrentDirectory();
-
- let src = OS.Path.join(currentDir, aFileName);
- Assert.ok((yield OS.File.exists(src)), "Database file found");
-
- // Ensure that our database doesn't already exist.
- let dest = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- Assert.ok(!(yield OS.File.exists(dest)), "Database file should not exist yet");
-
- yield OS.File.copy(src, dest);
-});
-
-// This works provided all tests in this folder use add_task.
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/migration/places_v10.sqlite b/toolkit/components/places/tests/migration/places_v10.sqlite
deleted file mode 100644
index 80a8ecd6a..000000000
--- a/toolkit/components/places/tests/migration/places_v10.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v11.sqlite b/toolkit/components/places/tests/migration/places_v11.sqlite
deleted file mode 100644
index bef27d5f5..000000000
--- a/toolkit/components/places/tests/migration/places_v11.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v17.sqlite b/toolkit/components/places/tests/migration/places_v17.sqlite
deleted file mode 100644
index 5183cde83..000000000
--- a/toolkit/components/places/tests/migration/places_v17.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v19.sqlite b/toolkit/components/places/tests/migration/places_v19.sqlite
deleted file mode 100644
index 11e2e6247..000000000
--- a/toolkit/components/places/tests/migration/places_v19.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v21.sqlite b/toolkit/components/places/tests/migration/places_v21.sqlite
deleted file mode 100644
index f72930826..000000000
--- a/toolkit/components/places/tests/migration/places_v21.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v22.sqlite b/toolkit/components/places/tests/migration/places_v22.sqlite
deleted file mode 100644
index 30bf840b0..000000000
--- a/toolkit/components/places/tests/migration/places_v22.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v23.sqlite b/toolkit/components/places/tests/migration/places_v23.sqlite
deleted file mode 100644
index b519b97d2..000000000
--- a/toolkit/components/places/tests/migration/places_v23.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v24.sqlite b/toolkit/components/places/tests/migration/places_v24.sqlite
deleted file mode 100644
index b35f958a6..000000000
--- a/toolkit/components/places/tests/migration/places_v24.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v25.sqlite b/toolkit/components/places/tests/migration/places_v25.sqlite
deleted file mode 100644
index 2afd1da1f..000000000
--- a/toolkit/components/places/tests/migration/places_v25.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v26.sqlite b/toolkit/components/places/tests/migration/places_v26.sqlite
deleted file mode 100644
index b4b238179..000000000
--- a/toolkit/components/places/tests/migration/places_v26.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v27.sqlite b/toolkit/components/places/tests/migration/places_v27.sqlite
deleted file mode 100644
index 57dfb7562..000000000
--- a/toolkit/components/places/tests/migration/places_v27.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v28.sqlite b/toolkit/components/places/tests/migration/places_v28.sqlite
deleted file mode 100644
index 9a27db324..000000000
--- a/toolkit/components/places/tests/migration/places_v28.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v29.sqlite b/toolkit/components/places/tests/migration/places_v29.sqlite
deleted file mode 100644
index f6de0fe8a..000000000
--- a/toolkit/components/places/tests/migration/places_v29.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v30.sqlite b/toolkit/components/places/tests/migration/places_v30.sqlite
deleted file mode 100644
index 9cbabe005..000000000
--- a/toolkit/components/places/tests/migration/places_v30.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v31.sqlite b/toolkit/components/places/tests/migration/places_v31.sqlite
deleted file mode 100644
index 9d33b9eff..000000000
--- a/toolkit/components/places/tests/migration/places_v31.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v32.sqlite b/toolkit/components/places/tests/migration/places_v32.sqlite
deleted file mode 100644
index 239f6c5fe..000000000
--- a/toolkit/components/places/tests/migration/places_v32.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v33.sqlite b/toolkit/components/places/tests/migration/places_v33.sqlite
deleted file mode 100644
index 6071dc6a6..000000000
--- a/toolkit/components/places/tests/migration/places_v33.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v34.sqlite b/toolkit/components/places/tests/migration/places_v34.sqlite
deleted file mode 100644
index 474628996..000000000
--- a/toolkit/components/places/tests/migration/places_v34.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v35.sqlite b/toolkit/components/places/tests/migration/places_v35.sqlite
deleted file mode 100644
index 5e157d778..000000000
--- a/toolkit/components/places/tests/migration/places_v35.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/places_v6.sqlite b/toolkit/components/places/tests/migration/places_v6.sqlite
deleted file mode 100644
index 2852a4cf9..000000000
--- a/toolkit/components/places/tests/migration/places_v6.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/migration/test_current_from_downgraded.js b/toolkit/components/places/tests/migration/test_current_from_downgraded.js
deleted file mode 100644
index 6d36cab14..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_downgraded.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- yield setupPlacesDatabase(`places_v${CURRENT_SCHEMA_VERSION}.sqlite`);
- // Downgrade the schema version to the first supported one.
- let path = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- let db = yield Sqlite.openConnection({ path: path });
- yield db.setSchemaVersion(FIRST_UPGRADABLE_SCHEMA_VERSION);
- yield db.close();
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v11.js b/toolkit/components/places/tests/migration/test_current_from_v11.js
deleted file mode 100644
index 43b8fb1f6..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v11.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v11.sqlite");
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_moz_hosts() {
- let db = yield PlacesUtils.promiseDBConnection();
-
- // This will throw if the column does not exist.
- yield db.execute("SELECT host, frecency, typed, prefix FROM moz_hosts");
-
- // moz_hosts is populated asynchronously, so we need to wait.
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- // check the number of entries in moz_hosts equals the number of
- // unique rev_host in moz_places
- let rows = yield db.execute(
- `SELECT (SELECT COUNT(host) FROM moz_hosts),
- (SELECT COUNT(DISTINCT rev_host)
- FROM moz_places
- WHERE LENGTH(rev_host) > 1)
- `);
-
- Assert.equal(rows.length, 1);
- let mozHostsCount = rows[0].getResultByIndex(0);
- let mozPlacesCount = rows[0].getResultByIndex(1);
-
- Assert.ok(mozPlacesCount > 0, "There is some url in the database");
- Assert.equal(mozPlacesCount, mozHostsCount, "moz_hosts has the expected number of entries");
-});
-
-add_task(function* test_journal() {
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute("PRAGMA journal_mode");
- Assert.equal(rows.length, 1);
- // WAL journal mode should be set on this database.
- Assert.equal(rows[0].getResultByIndex(0), "wal");
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v19.js b/toolkit/components/places/tests/migration/test_current_from_v19.js
deleted file mode 100644
index b8d837e68..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v19.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const ANNO_LEGACYGUID = "placesInternal/GUID";
-
-var getTotalGuidAnnotationsCount = Task.async(function* (db) {
- let rows = yield db.execute(
- `SELECT count(*)
- FROM moz_items_annos a
- JOIN moz_anno_attributes b ON a.anno_attribute_id = b.id
- WHERE b.name = :attr_name
- `, { attr_name: ANNO_LEGACYGUID });
- return rows[0].getResultByIndex(0);
-});
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v19.sqlite");
-});
-
-add_task(function* initial_state() {
- let path = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- let db = yield Sqlite.openConnection({ path: path });
-
- Assert.equal((yield getTotalGuidAnnotationsCount(db)), 1,
- "There should be 1 obsolete guid annotation");
- yield db.close();
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_bookmark_guid_annotation_removed()
-{
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield getTotalGuidAnnotationsCount(db)), 0,
- "There should be no more obsolete GUID annotations.");
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v24.js b/toolkit/components/places/tests/migration/test_current_from_v24.js
deleted file mode 100644
index 0561b4922..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v24.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v24.sqlite");
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_bookmark_guid_annotation_removed()
-{
- yield PlacesUtils.bookmarks.eraseEverything();
-
- let db = yield PlacesUtils.promiseDBConnection();
- let m = new Map([
- [PlacesUtils.placesRootId, PlacesUtils.bookmarks.rootGuid],
- [PlacesUtils.bookmarksMenuFolderId, PlacesUtils.bookmarks.menuGuid],
- [PlacesUtils.toolbarFolderId, PlacesUtils.bookmarks.toolbarGuid],
- [PlacesUtils.unfiledBookmarksFolderId, PlacesUtils.bookmarks.unfiledGuid],
- [PlacesUtils.tagsFolderId, PlacesUtils.bookmarks.tagsGuid],
- [PlacesUtils.mobileFolderId, PlacesUtils.bookmarks.mobileGuid],
- ]);
-
- let rows = yield db.execute(`SELECT id, guid FROM moz_bookmarks`);
- for (let row of rows) {
- let id = row.getResultByName("id");
- let guid = row.getResultByName("guid");
- Assert.equal(m.get(id), guid, "The root folder has the correct GUID");
- }
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v25.js b/toolkit/components/places/tests/migration/test_current_from_v25.js
deleted file mode 100644
index b066975fc..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v25.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v25.sqlite");
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_dates_rounded() {
- let root = yield PlacesUtils.promiseBookmarksTree();
- function ensureDates(node) {
- // When/if promiseBookmarksTree returns these as Date objects, switch this
- // test to use getItemDateAdded and getItemLastModified. And when these
- // methods are removed, this test can be eliminated altogether.
- Assert.strictEqual(typeof(node.dateAdded), "number");
- Assert.strictEqual(typeof(node.lastModified), "number");
- Assert.strictEqual(node.dateAdded % 1000, 0);
- Assert.strictEqual(node.lastModified % 1000, 0);
- if ("children" in node)
- node.children.forEach(ensureDates);
- }
- ensureDates(root);
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v26.js b/toolkit/components/places/tests/migration/test_current_from_v26.js
deleted file mode 100644
index 7ff4bc352..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v26.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v26.sqlite");
- // Setup database contents to be migrated.
- let path = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- let db = yield Sqlite.openConnection({ path });
- // Add pages.
- yield db.execute(`INSERT INTO moz_places (url, guid)
- VALUES ("http://test1.com/", "test1_______")
- , ("http://test2.com/", "test2_______")
- , ("http://test3.com/", "test3_______")
- `);
- // Add keywords.
- yield db.execute(`INSERT INTO moz_keywords (keyword)
- VALUES ("kw1")
- , ("kw2")
- , ("kw3")
- , ("kw4")
- , ("kw5")
- `);
- // Add bookmarks.
- let now = Date.now() * 1000;
- let index = 0;
- yield db.execute(`INSERT INTO moz_bookmarks (type, fk, parent, position, dateAdded, lastModified, keyword_id, guid)
- VALUES (1, (SELECT id FROM moz_places WHERE guid = 'test1_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw1'), "bookmark1___")
- /* same uri, different keyword */
- , (1, (SELECT id FROM moz_places WHERE guid = 'test1_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw2'), "bookmark2___")
- /* different uri, same keyword as 1 */
- , (1, (SELECT id FROM moz_places WHERE guid = 'test2_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw1'), "bookmark3___")
- /* same uri, same keyword as 1 */
- , (1, (SELECT id FROM moz_places WHERE guid = 'test1_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw1'), "bookmark4___")
- /* same uri, same keyword as 2 */
- , (1, (SELECT id FROM moz_places WHERE guid = 'test2_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw2'), "bookmark5___")
- /* different uri, same keyword as 1 */
- , (1, (SELECT id FROM moz_places WHERE guid = 'test1_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw3'), "bookmark6___")
- , (1, (SELECT id FROM moz_places WHERE guid = 'test3_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw4'), "bookmark7___")
- /* same uri and post_data as bookmark7, different keyword */
- , (1, (SELECT id FROM moz_places WHERE guid = 'test3_______'), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = 'kw5'), "bookmark8___")
- `);
- // Add postData.
- yield db.execute(`INSERT INTO moz_anno_attributes (name)
- VALUES ("bookmarkProperties/POSTData")
- , ("someOtherAnno")`);
- yield db.execute(`INSERT INTO moz_items_annos(anno_attribute_id, item_id, content)
- VALUES ((SELECT id FROM moz_anno_attributes where name = "bookmarkProperties/POSTData"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark3___"), "postData1")
- , ((SELECT id FROM moz_anno_attributes where name = "bookmarkProperties/POSTData"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark5___"), "postData2")
- , ((SELECT id FROM moz_anno_attributes where name = "someOtherAnno"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark5___"), "zzzzzzzzzz")
- , ((SELECT id FROM moz_anno_attributes where name = "bookmarkProperties/POSTData"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark7___"), "postData3")
- , ((SELECT id FROM moz_anno_attributes where name = "bookmarkProperties/POSTData"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark8___"), "postData3")
- `);
- yield db.close();
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_keywords() {
- // When 2 urls have the same keyword, if one has postData it will be
- // preferred.
- let entry1 = yield PlacesUtils.keywords.fetch("kw1");
- Assert.equal(entry1.url.href, "http://test2.com/");
- Assert.equal(entry1.postData, "postData1");
- let entry2 = yield PlacesUtils.keywords.fetch("kw2");
- Assert.equal(entry2.url.href, "http://test2.com/");
- Assert.equal(entry2.postData, "postData2");
- let entry3 = yield PlacesUtils.keywords.fetch("kw3");
- Assert.equal(entry3.url.href, "http://test1.com/");
- Assert.equal(entry3.postData, null);
- let entry4 = yield PlacesUtils.keywords.fetch("kw4");
- Assert.equal(entry4, null);
- let entry5 = yield PlacesUtils.keywords.fetch("kw5");
- Assert.equal(entry5.url.href, "http://test3.com/");
- Assert.equal(entry5.postData, "postData3");
-
- Assert.equal((yield foreign_count("http://test1.com/")), 5); // 4 bookmark2 + 1 keywords
- Assert.equal((yield foreign_count("http://test2.com/")), 4); // 2 bookmark2 + 2 keywords
- Assert.equal((yield foreign_count("http://test3.com/")), 3); // 2 bookmark2 + 1 keywords
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v27.js b/toolkit/components/places/tests/migration/test_current_from_v27.js
deleted file mode 100644
index 1675901eb..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v27.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v27.sqlite");
- // Setup database contents to be migrated.
- let path = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- let db = yield Sqlite.openConnection({ path });
- // Add pages.
- yield db.execute(`INSERT INTO moz_places (url, guid)
- VALUES ("http://test1.com/", "test1_______")
- , ("http://test2.com/", "test2_______")
- `);
- // Add keywords.
- yield db.execute(`INSERT INTO moz_keywords (keyword, place_id, post_data)
- VALUES ("kw1", (SELECT id FROM moz_places WHERE guid = "test2_______"), "broken data")
- , ("kw2", (SELECT id FROM moz_places WHERE guid = "test2_______"), NULL)
- , ("kw3", (SELECT id FROM moz_places WHERE guid = "test1_______"), "zzzzzzzzzz")
- `);
- // Add bookmarks.
- let now = Date.now() * 1000;
- let index = 0;
- yield db.execute(`INSERT INTO moz_bookmarks (type, fk, parent, position, dateAdded, lastModified, keyword_id, guid)
- VALUES (1, (SELECT id FROM moz_places WHERE guid = "test1_______"), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = "kw1"), "bookmark1___")
- /* same uri, different keyword */
- , (1, (SELECT id FROM moz_places WHERE guid = "test1_______"), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = "kw2"), "bookmark2___")
- /* different uri, same keyword as 1 */
- , (1, (SELECT id FROM moz_places WHERE guid = "test2_______"), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = "kw1"), "bookmark3___")
- /* same uri, same keyword as 1 */
- , (1, (SELECT id FROM moz_places WHERE guid = "test1_______"), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = "kw1"), "bookmark4___")
- /* same uri, same keyword as 2 */
- , (1, (SELECT id FROM moz_places WHERE guid = "test2_______"), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = "kw2"), "bookmark5___")
- /* different uri, same keyword as 1 */
- , (1, (SELECT id FROM moz_places WHERE guid = "test1_______"), 3, ${index++}, ${now}, ${now},
- (SELECT id FROM moz_keywords WHERE keyword = "kw3"), "bookmark6___")
- `);
- // Add postData.
- yield db.execute(`INSERT INTO moz_anno_attributes (name)
- VALUES ("bookmarkProperties/POSTData")
- , ("someOtherAnno")`);
- yield db.execute(`INSERT INTO moz_items_annos(anno_attribute_id, item_id, content)
- VALUES ((SELECT id FROM moz_anno_attributes where name = "bookmarkProperties/POSTData"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark3___"), "postData1")
- , ((SELECT id FROM moz_anno_attributes where name = "bookmarkProperties/POSTData"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark5___"), "postData2")
- , ((SELECT id FROM moz_anno_attributes where name = "someOtherAnno"),
- (SELECT id FROM moz_bookmarks WHERE guid = "bookmark5___"), "zzzzzzzzzz")
- `);
- yield db.close();
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_keywords() {
- // When 2 urls have the same keyword, if one has postData it will be
- // preferred.
- let entry1 = yield PlacesUtils.keywords.fetch("kw1");
- Assert.equal(entry1.url.href, "http://test2.com/");
- Assert.equal(entry1.postData, "postData1");
- let entry2 = yield PlacesUtils.keywords.fetch("kw2");
- Assert.equal(entry2.url.href, "http://test2.com/");
- Assert.equal(entry2.postData, "postData2");
- let entry3 = yield PlacesUtils.keywords.fetch("kw3");
- Assert.equal(entry3.url.href, "http://test1.com/");
- Assert.equal(entry3.postData, null);
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v31.js b/toolkit/components/places/tests/migration/test_current_from_v31.js
deleted file mode 100644
index 6b9131daa..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v31.js
+++ /dev/null
@@ -1,46 +0,0 @@
-// Add pages.
-let shorturl = "http://example.com/" + "a".repeat(1981);
-let longurl = "http://example.com/" + "a".repeat(1982);
-let bmurl = "http://example.com/" + "a".repeat(1983);
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v31.sqlite");
- // Setup database contents to be migrated.
- let path = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- let db = yield Sqlite.openConnection({ path });
-
- yield db.execute(`INSERT INTO moz_places (url, guid, foreign_count)
- VALUES (:shorturl, "test1_______", 0)
- , (:longurl, "test2_______", 0)
- , (:bmurl, "test3_______", 1)
- `, { shorturl, longurl, bmurl });
- // Add visits.
- yield db.execute(`INSERT INTO moz_historyvisits (place_id)
- VALUES ((SELECT id FROM moz_places WHERE url = :shorturl))
- , ((SELECT id FROM moz_places WHERE url = :longurl))
- `, { shorturl, longurl });
- yield db.close();
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_longurls() {
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(`SELECT 1 FROM moz_places where url = :longurl`,
- { longurl });
- Assert.equal(rows.length, 0, "Long url should have been removed");
- rows = yield db.execute(`SELECT 1 FROM moz_places where url = :shorturl`,
- { shorturl });
- Assert.equal(rows.length, 1, "Short url should have been retained");
- rows = yield db.execute(`SELECT 1 FROM moz_places where url = :bmurl`,
- { bmurl });
- Assert.equal(rows.length, 1, "Bookmarked url should have been retained");
- rows = yield db.execute(`SELECT count(*) FROM moz_historyvisits`);
- Assert.equal(rows.length, 1, "Orphan visists should have been removed");
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v34.js b/toolkit/components/places/tests/migration/test_current_from_v34.js
deleted file mode 100644
index 115bcec67..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v34.js
+++ /dev/null
@@ -1,141 +0,0 @@
-Cu.importGlobalProperties(["URL", "crypto"]);
-
-const { TYPE_BOOKMARK, TYPE_FOLDER } = Ci.nsINavBookmarksService;
-const { EXPIRE_NEVER, TYPE_INT32 } = Ci.nsIAnnotationService;
-
-function makeGuid() {
- return ChromeUtils.base64URLEncode(crypto.getRandomValues(new Uint8Array(9)), {
- pad: false,
- });
-}
-
-// These queries are more or less copied directly from Bookmarks.jsm, but
-// operate on the old, pre-migration DB. We can't use any of the Places SQL
-// functions yet, because those are only registered for the main connection.
-function* insertItem(db, info) {
- let [parentInfo] = yield db.execute(`
- SELECT b.id, (SELECT count(*) FROM moz_bookmarks
- WHERE parent = b.id) AS childCount
- FROM moz_bookmarks b
- WHERE b.guid = :parentGuid`,
- { parentGuid: info.parentGuid });
-
- let guid = makeGuid();
- yield db.execute(`
- INSERT INTO moz_bookmarks (fk, type, parent, position, guid)
- VALUES ((SELECT id FROM moz_places WHERE url = :url),
- :type, :parent, :position, :guid)`,
- { url: info.url || "nonexistent", type: info.type, guid,
- // Just append items.
- position: parentInfo.getResultByName("childCount"),
- parent: parentInfo.getResultByName("id") });
-
- let id = (yield db.execute(`
- SELECT id FROM moz_bookmarks WHERE guid = :guid LIMIT 1`,
- { guid }))[0].getResultByName("id");
-
- return { id, guid };
-}
-
-function insertBookmark(db, info) {
- return db.executeTransaction(function* () {
- if (info.type == TYPE_BOOKMARK) {
- // We don't have access to the hash function here, so we omit the
- // `url_hash` column. These will be fixed up automatically during
- // migration.
- let url = new URL(info.url);
- let placeGuid = makeGuid();
- yield db.execute(`
- INSERT INTO moz_places (url, rev_host, hidden, frecency, guid)
- VALUES (:url, :rev_host, 0, -1, :guid)`,
- { url: url.href, guid: placeGuid,
- rev_host: PlacesUtils.getReversedHost(url) });
- }
- return yield* insertItem(db, info);
- });
-}
-
-function* insertAnno(db, itemId, name, value) {
- yield db.execute(`INSERT OR IGNORE INTO moz_anno_attributes (name)
- VALUES (:name)`, { name });
- yield db.execute(`
- INSERT INTO moz_items_annos
- (item_id, anno_attribute_id, content, flags,
- expiration, type, dateAdded, lastModified)
- VALUES (:itemId,
- (SELECT id FROM moz_anno_attributes
- WHERE name = :name),
- 1, 0, :expiration, :type, 0, 0)
- `, { itemId, name, expiration: EXPIRE_NEVER, type: TYPE_INT32 });
-}
-
-function insertMobileFolder(db) {
- return db.executeTransaction(function* () {
- let item = yield* insertItem(db, {
- type: TYPE_FOLDER,
- parentGuid: "root________",
- });
- yield* insertAnno(db, item.id, "mobile/bookmarksRoot", 1);
- return item;
- });
-}
-
-var mobileId, mobileGuid, fxGuid;
-var dupeMobileId, dupeMobileGuid, tbGuid;
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v34.sqlite");
- // Setup database contents to be migrated.
- let path = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- let db = yield Sqlite.openConnection({ path });
-
- do_print("Create mobile folder with bookmarks");
- ({ id: mobileId, guid: mobileGuid } = yield insertMobileFolder(db));
- ({ guid: fxGuid } = yield insertBookmark(db, {
- type: TYPE_BOOKMARK,
- url: "http://getfirefox.com",
- parentGuid: mobileGuid,
- }));
-
- // We should only have one mobile folder, but, in case an old version of Sync
- // did the wrong thing and created multiple mobile folders, we should merge
- // their contents into the new mobile root.
- do_print("Create second mobile folder with different bookmarks");
- ({ id: dupeMobileId, guid: dupeMobileGuid } = yield insertMobileFolder(db));
- ({ guid: tbGuid } = yield insertBookmark(db, {
- type: TYPE_BOOKMARK,
- url: "http://getthunderbird.com",
- parentGuid: dupeMobileGuid,
- }));
-
- yield db.close();
-});
-
-add_task(function* database_is_valid() {
- // Accessing the database for the first time triggers migration.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* test_mobile_root() {
- let fxBmk = yield PlacesUtils.bookmarks.fetch(fxGuid);
- equal(fxBmk.parentGuid, PlacesUtils.bookmarks.mobileGuid,
- "Firefox bookmark should be moved to new mobile root");
- equal(fxBmk.index, 0, "Firefox bookmark should be first child of new root");
-
- let tbBmk = yield PlacesUtils.bookmarks.fetch(tbGuid);
- equal(tbBmk.parentGuid, PlacesUtils.bookmarks.mobileGuid,
- "Thunderbird bookmark should be moved to new mobile root");
- equal(tbBmk.index, 1,
- "Thunderbird bookmark should be second child of new root");
-
- let mobileRootId = PlacesUtils.promiseItemId(
- PlacesUtils.bookmarks.mobileGuid);
- let annoItemIds = PlacesUtils.annotations.getItemsWithAnnotation(
- PlacesUtils.MOBILE_ROOT_ANNO, {});
- deepEqual(annoItemIds, [mobileRootId],
- "Only mobile root should have mobile anno");
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v34_no_roots.js b/toolkit/components/places/tests/migration/test_current_from_v34_no_roots.js
deleted file mode 100644
index 871fe8993..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v34_no_roots.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v34.sqlite");
- // Setup database contents to be migrated.
- let path = OS.Path.join(OS.Constants.Path.profileDir, DB_FILENAME);
- let db = yield Sqlite.openConnection({ path });
- // Remove all the roots.
- yield db.execute("DELETE FROM moz_bookmarks");
- yield db.close();
-});
-
-add_task(function* database_is_valid() {
- // Accessing the database for the first time triggers migration.
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_UPGRADED);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
diff --git a/toolkit/components/places/tests/migration/test_current_from_v6.js b/toolkit/components/places/tests/migration/test_current_from_v6.js
deleted file mode 100644
index a3f9dc229..000000000
--- a/toolkit/components/places/tests/migration/test_current_from_v6.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests migration from a preliminary schema version 6 that
- * lacks frecency column and moz_inputhistory table.
- */
-
-add_task(function* setup() {
- yield setupPlacesDatabase("places_v6.sqlite");
-});
-
-add_task(function* corrupt_database_not_exists() {
- let corruptPath = OS.Path.join(OS.Constants.Path.profileDir,
- "places.sqlite.corrupt");
- Assert.ok(!(yield OS.File.exists(corruptPath)), "Corrupt file should not exist");
-});
-
-add_task(function* database_is_valid() {
- Assert.equal(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CORRUPT);
-
- let db = yield PlacesUtils.promiseDBConnection();
- Assert.equal((yield db.getSchemaVersion()), CURRENT_SCHEMA_VERSION);
-});
-
-add_task(function* check_columns() {
- // Check the database has been replaced, these would throw otherwise.
- let db = yield PlacesUtils.promiseDBConnection();
- yield db.execute("SELECT frecency from moz_places");
- yield db.execute("SELECT 1 from moz_inputhistory");
-});
-
-add_task(function* corrupt_database_exists() {
- let corruptPath = OS.Path.join(OS.Constants.Path.profileDir,
- "places.sqlite.corrupt");
- Assert.ok((yield OS.File.exists(corruptPath)), "Corrupt file should exist");
-});
diff --git a/toolkit/components/places/tests/migration/xpcshell.ini b/toolkit/components/places/tests/migration/xpcshell.ini
deleted file mode 100644
index aae0f75ee..000000000
--- a/toolkit/components/places/tests/migration/xpcshell.ini
+++ /dev/null
@@ -1,36 +0,0 @@
-[DEFAULT]
-head = head_migration.js
-tail =
-
-support-files =
- places_v6.sqlite
- places_v10.sqlite
- places_v11.sqlite
- places_v17.sqlite
- places_v19.sqlite
- places_v21.sqlite
- places_v22.sqlite
- places_v23.sqlite
- places_v24.sqlite
- places_v25.sqlite
- places_v26.sqlite
- places_v27.sqlite
- places_v28.sqlite
- places_v30.sqlite
- places_v31.sqlite
- places_v32.sqlite
- places_v33.sqlite
- places_v34.sqlite
- places_v35.sqlite
-
-[test_current_from_downgraded.js]
-[test_current_from_v6.js]
-[test_current_from_v11.js]
-[test_current_from_v19.js]
-[test_current_from_v24.js]
-[test_current_from_v25.js]
-[test_current_from_v26.js]
-[test_current_from_v27.js]
-[test_current_from_v31.js]
-[test_current_from_v34.js]
-[test_current_from_v34_no_roots.js]
diff --git a/toolkit/components/places/tests/moz.build b/toolkit/components/places/tests/moz.build
deleted file mode 100644
index a40c0e93a..000000000
--- a/toolkit/components/places/tests/moz.build
+++ /dev/null
@@ -1,67 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-TEST_DIRS += ['cpp']
-
-TESTING_JS_MODULES += [
- 'PlacesTestUtils.jsm',
-]
-
-XPCSHELL_TESTS_MANIFESTS += [
- 'bookmarks/xpcshell.ini',
- 'expiration/xpcshell.ini',
- 'favicons/xpcshell.ini',
- 'history/xpcshell.ini',
- 'migration/xpcshell.ini',
- 'queries/xpcshell.ini',
- 'unifiedcomplete/xpcshell.ini',
- 'unit/xpcshell.ini',
-]
-
-BROWSER_CHROME_MANIFESTS += ['browser/browser.ini']
-MOCHITEST_CHROME_MANIFESTS += [
- 'chrome/chrome.ini',
-]
-
-TEST_HARNESS_FILES.xpcshell.toolkit.components.places.tests += [
- 'head_common.js',
-]
-
-TEST_HARNESS_FILES.testing.mochitest.tests.toolkit.components.places.tests.browser += [
- 'browser/399606-history.go-0.html',
- 'browser/399606-httprefresh.html',
- 'browser/399606-location.reload.html',
- 'browser/399606-location.replace.html',
- 'browser/399606-window.location.href.html',
- 'browser/399606-window.location.html',
- 'browser/461710_iframe.html',
- 'browser/461710_link_page-2.html',
- 'browser/461710_link_page-3.html',
- 'browser/461710_link_page.html',
- 'browser/461710_visited_page.html',
- 'browser/begin.html',
- 'browser/favicon-normal16.png',
- 'browser/favicon-normal32.png',
- 'browser/favicon.html',
- 'browser/final.html',
- 'browser/history_post.html',
- 'browser/history_post.sjs',
- 'browser/redirect-target.html',
- 'browser/redirect.sjs',
- 'browser/redirect_once.sjs',
- 'browser/redirect_twice.sjs',
- 'browser/title1.html',
- 'browser/title2.html',
-]
-
-TEST_HARNESS_FILES.testing.mochitest.tests.toolkit.components.places.tests.chrome += [
- 'chrome/bad_links.atom',
- 'chrome/link-less-items-no-site-uri.rss',
- 'chrome/link-less-items.rss',
- 'chrome/rss_as_html.rss',
- 'chrome/rss_as_html.rss^headers^',
- 'chrome/sample_feed.atom',
-]
diff --git a/toolkit/components/places/tests/queries/.eslintrc.js b/toolkit/components/places/tests/queries/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/queries/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/queries/head_queries.js b/toolkit/components/places/tests/queries/head_queries.js
deleted file mode 100644
index d37b3365f..000000000
--- a/toolkit/components/places/tests/queries/head_queries.js
+++ /dev/null
@@ -1,370 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
-
-
-// Some Useful Date constants - PRTime uses microseconds, so convert
-const DAY_MICROSEC = 86400000000;
-const today = PlacesUtils.toPRTime(Date.now());
-const yesterday = today - DAY_MICROSEC;
-const lastweek = today - (DAY_MICROSEC * 7);
-const daybefore = today - (DAY_MICROSEC * 2);
-const old = today - (DAY_MICROSEC * 3);
-const futureday = today + (DAY_MICROSEC * 3);
-const olderthansixmonths = today - (DAY_MICROSEC * 31 * 7);
-
-
-/**
- * Generalized function to pull in an array of objects of data and push it into
- * the database. It does NOT do any checking to see that the input is
- * appropriate. This function is an asynchronous task, it can be called using
- * "Task.spawn" or using the "yield" function inside another task.
- */
-function* task_populateDB(aArray)
-{
- // Iterate over aArray and execute all instructions.
- for (let arrayItem of aArray) {
- try {
- // make the data object into a query data object in order to create proper
- // default values for anything left unspecified
- var qdata = new queryData(arrayItem);
- if (qdata.isVisit) {
- // Then we should add a visit for this node
- yield PlacesTestUtils.addVisits({
- uri: uri(qdata.uri),
- transition: qdata.transType,
- visitDate: qdata.lastVisit,
- referrer: qdata.referrer ? uri(qdata.referrer) : null,
- title: qdata.title
- });
- if (qdata.visitCount && !qdata.isDetails) {
- // Set a fake visit_count, this is not a real count but can be used
- // to test sorting by visit_count.
- let stmt = DBConn().createAsyncStatement(
- "UPDATE moz_places SET visit_count = :vc WHERE url_hash = hash(:url) AND url = :url");
- stmt.params.vc = qdata.visitCount;
- stmt.params.url = qdata.uri;
- try {
- stmt.executeAsync();
- }
- catch (ex) {
- print("Error while setting visit_count.");
- }
- finally {
- stmt.finalize();
- }
- }
- }
-
- if (qdata.isRedirect) {
- // This must be async to properly enqueue after the updateFrecency call
- // done by the visit addition.
- let stmt = DBConn().createAsyncStatement(
- "UPDATE moz_places SET hidden = 1 WHERE url_hash = hash(:url) AND url = :url");
- stmt.params.url = qdata.uri;
- try {
- stmt.executeAsync();
- }
- catch (ex) {
- print("Error while setting hidden.");
- }
- finally {
- stmt.finalize();
- }
- }
-
- if (qdata.isDetails) {
- // Then we add extraneous page details for testing
- yield PlacesTestUtils.addVisits({
- uri: uri(qdata.uri),
- visitDate: qdata.lastVisit,
- title: qdata.title
- });
- }
-
- if (qdata.markPageAsTyped) {
- PlacesUtils.history.markPageAsTyped(uri(qdata.uri));
- }
-
- if (qdata.isPageAnnotation) {
- if (qdata.removeAnnotation)
- PlacesUtils.annotations.removePageAnnotation(uri(qdata.uri),
- qdata.annoName);
- else {
- PlacesUtils.annotations.setPageAnnotation(uri(qdata.uri),
- qdata.annoName,
- qdata.annoVal,
- qdata.annoFlags,
- qdata.annoExpiration);
- }
- }
-
- if (qdata.isItemAnnotation) {
- if (qdata.removeAnnotation)
- PlacesUtils.annotations.removeItemAnnotation(qdata.itemId,
- qdata.annoName);
- else {
- PlacesUtils.annotations.setItemAnnotation(qdata.itemId,
- qdata.annoName,
- qdata.annoVal,
- qdata.annoFlags,
- qdata.annoExpiration);
- }
- }
-
- if (qdata.isFolder) {
- yield PlacesUtils.bookmarks.insert({
- parentGuid: qdata.parentGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: qdata.title,
- index: qdata.index
- });
- }
-
- if (qdata.isLivemark) {
- yield PlacesUtils.livemarks.addLivemark({ title: qdata.title
- , parentId: (yield PlacesUtils.promiseItemId(qdata.parentGuid))
- , index: qdata.index
- , feedURI: uri(qdata.feedURI)
- , siteURI: uri(qdata.uri)
- });
- }
-
- if (qdata.isBookmark) {
- let data = {
- parentGuid: qdata.parentGuid,
- index: qdata.index,
- title: qdata.title,
- url: qdata.uri
- };
-
- if (qdata.dateAdded) {
- data.dateAdded = new Date(qdata.dateAdded / 1000);
- }
-
- if (qdata.lastModified) {
- data.lastModified = new Date(qdata.lastModified / 1000);
- }
-
- yield PlacesUtils.bookmarks.insert(data);
-
- if (qdata.keyword) {
- yield PlacesUtils.keywords.insert({ url: qdata.uri,
- keyword: qdata.keyword });
- }
- }
-
- if (qdata.isTag) {
- PlacesUtils.tagging.tagURI(uri(qdata.uri), qdata.tagArray);
- }
-
- if (qdata.isSeparator) {
- yield PlacesUtils.bookmarks.insert({
- parentGuid: qdata.parentGuid,
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- index: qdata.index
- });
- }
- } catch (ex) {
- // use the arrayItem object here in case instantiation of qdata failed
- do_print("Problem with this URI: " + arrayItem.uri);
- do_throw("Error creating database: " + ex + "\n");
- }
- }
-}
-
-
-/**
- * The Query Data Object - this object encapsulates data for our queries and is
- * used to parameterize our calls to the Places APIs to put data into the
- * database. It also has some interesting meta functions to determine which APIs
- * should be called, and to determine if this object should show up in the
- * resulting query.
- * Its parameter is an object specifying which attributes you want to set.
- * For ex:
- * var myobj = new queryData({isVisit: true, uri:"http://mozilla.com", title="foo"});
- * Note that it doesn't do any input checking on that object.
- */
-function queryData(obj) {
- this.isVisit = obj.isVisit ? obj.isVisit : false;
- this.isBookmark = obj.isBookmark ? obj.isBookmark: false;
- this.uri = obj.uri ? obj.uri : "";
- this.lastVisit = obj.lastVisit ? obj.lastVisit : today;
- this.referrer = obj.referrer ? obj.referrer : null;
- this.transType = obj.transType ? obj.transType : Ci.nsINavHistoryService.TRANSITION_TYPED;
- this.isRedirect = obj.isRedirect ? obj.isRedirect : false;
- this.isDetails = obj.isDetails ? obj.isDetails : false;
- this.title = obj.title ? obj.title : "";
- this.markPageAsTyped = obj.markPageAsTyped ? obj.markPageAsTyped : false;
- this.isPageAnnotation = obj.isPageAnnotation ? obj.isPageAnnotation : false;
- this.removeAnnotation= obj.removeAnnotation ? true : false;
- this.annoName = obj.annoName ? obj.annoName : "";
- this.annoVal = obj.annoVal ? obj.annoVal : "";
- this.annoFlags = obj.annoFlags ? obj.annoFlags : 0;
- this.annoExpiration = obj.annoExpiration ? obj.annoExpiration : 0;
- this.isItemAnnotation = obj.isItemAnnotation ? obj.isItemAnnotation : false;
- this.itemId = obj.itemId ? obj.itemId : 0;
- this.annoMimeType = obj.annoMimeType ? obj.annoMimeType : "";
- this.isTag = obj.isTag ? obj.isTag : false;
- this.tagArray = obj.tagArray ? obj.tagArray : null;
- this.isLivemark = obj.isLivemark ? obj.isLivemark : false;
- this.parentGuid = obj.parentGuid || PlacesUtils.bookmarks.rootGuid;
- this.feedURI = obj.feedURI ? obj.feedURI : "";
- this.index = obj.index ? obj.index : PlacesUtils.bookmarks.DEFAULT_INDEX;
- this.isFolder = obj.isFolder ? obj.isFolder : false;
- this.contractId = obj.contractId ? obj.contractId : "";
- this.lastModified = obj.lastModified ? obj.lastModified : null;
- this.dateAdded = obj.dateAdded ? obj.dateAdded : null;
- this.keyword = obj.keyword ? obj.keyword : "";
- this.visitCount = obj.visitCount ? obj.visitCount : 0;
- this.isSeparator = obj.hasOwnProperty("isSeparator") && obj.isSeparator;
-
- // And now, the attribute for whether or not this object should appear in the
- // resulting query
- this.isInQuery = obj.isInQuery ? obj.isInQuery : false;
-}
-
-// All attributes are set in the constructor above
-queryData.prototype = { }
-
-
-/**
- * Helper function to compare an array of query objects with a result set.
- * It assumes the array of query objects contains the SAME SORT as the result
- * set. It checks the the uri, title, time, and bookmarkIndex properties of
- * the results, where appropriate.
- */
-function compareArrayToResult(aArray, aRoot) {
- do_print("Comparing Array to Results");
-
- var wasOpen = aRoot.containerOpen;
- if (!wasOpen)
- aRoot.containerOpen = true;
-
- // check expected number of results against actual
- var expectedResultCount = aArray.filter(function(aEl) { return aEl.isInQuery; }).length;
- if (expectedResultCount != aRoot.childCount) {
- // Debugging code for failures.
- dump_table("moz_places");
- dump_table("moz_historyvisits");
- do_print("Found children:");
- for (let i = 0; i < aRoot.childCount; i++) {
- do_print(aRoot.getChild(i).uri);
- }
- do_print("Expected:");
- for (let i = 0; i < aArray.length; i++) {
- if (aArray[i].isInQuery)
- do_print(aArray[i].uri);
- }
- }
- do_check_eq(expectedResultCount, aRoot.childCount);
-
- var inQueryIndex = 0;
- for (var i = 0; i < aArray.length; i++) {
- if (aArray[i].isInQuery) {
- var child = aRoot.getChild(inQueryIndex);
- // do_print("testing testData[" + i + "] vs result[" + inQueryIndex + "]");
- if (!aArray[i].isFolder && !aArray[i].isSeparator) {
- do_print("testing testData[" + aArray[i].uri + "] vs result[" + child.uri + "]");
- if (aArray[i].uri != child.uri) {
- dump_table("moz_places");
- do_throw("Expected " + aArray[i].uri + " found " + child.uri);
- }
- }
- if (!aArray[i].isSeparator && aArray[i].title != child.title)
- do_throw("Expected " + aArray[i].title + " found " + child.title);
- if (aArray[i].hasOwnProperty("lastVisit") &&
- aArray[i].lastVisit != child.time)
- do_throw("Expected " + aArray[i].lastVisit + " found " + child.time);
- if (aArray[i].hasOwnProperty("index") &&
- aArray[i].index != PlacesUtils.bookmarks.DEFAULT_INDEX &&
- aArray[i].index != child.bookmarkIndex)
- do_throw("Expected " + aArray[i].index + " found " + child.bookmarkIndex);
-
- inQueryIndex++;
- }
- }
-
- if (!wasOpen)
- aRoot.containerOpen = false;
- do_print("Comparing Array to Results passes");
-}
-
-
-/**
- * Helper function to check to see if one object either is or is not in the
- * result set. It can accept either a queryData object or an array of queryData
- * objects. If it gets an array, it only compares the first object in the array
- * to see if it is in the result set.
- * Returns: True if item is in query set, and false if item is not in query set
- * If input is an array, returns True if FIRST object in array is in
- * query set. To compare entire array, use the function above.
- */
-function isInResult(aQueryData, aRoot) {
- var rv = false;
- var uri;
- var wasOpen = aRoot.containerOpen;
- if (!wasOpen)
- aRoot.containerOpen = true;
-
- // If we have an array, pluck out the first item. If an object, pluc out the
- // URI, we just compare URI's here.
- if ("uri" in aQueryData) {
- uri = aQueryData.uri;
- } else {
- uri = aQueryData[0].uri;
- }
-
- for (var i=0; i < aRoot.childCount; i++) {
- if (uri == aRoot.getChild(i).uri) {
- rv = true;
- break;
- }
- }
- if (!wasOpen)
- aRoot.containerOpen = false;
- return rv;
-}
-
-
-/**
- * A nice helper function for debugging things. It prints the contents of a
- * result set.
- */
-function displayResultSet(aRoot) {
-
- var wasOpen = aRoot.containerOpen;
- if (!wasOpen)
- aRoot.containerOpen = true;
-
- if (!aRoot.hasChildren) {
- // Something wrong? Empty result set?
- do_print("Result Set Empty");
- return;
- }
-
- for (var i=0; i < aRoot.childCount; ++i) {
- do_print("Result Set URI: " + aRoot.getChild(i).uri + " Title: " +
- aRoot.getChild(i).title + " Visit Time: " + aRoot.getChild(i).time);
- }
- if (!wasOpen)
- aRoot.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/queries/readme.txt b/toolkit/components/places/tests/queries/readme.txt
deleted file mode 100644
index 19414f96e..000000000
--- a/toolkit/components/places/tests/queries/readme.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-These are tests specific to the Places Query API.
-
-We are tracking the coverage of these tests here:
-http://wiki.mozilla.org/QA/TDAI/Projects/Places_Tests
-
-When creating one of these tests, you need to update those tables so that we
-know how well our test coverage is of this area. Furthermore, when adding tests
-ensure to cover live update (changing the query set) by performing the following
-operations on the query set you get after running the query:
-* Adding a new item to the query set
-* Updating an existing item so that it matches the query set
-* Change an existing item so that it does not match the query set
-* Do multiple of the above inside an Update Batch transaction.
-* Try these transactions in different orders.
-
-Use the stub test to help you create a test with the proper structure.
diff --git a/toolkit/components/places/tests/queries/test_415716.js b/toolkit/components/places/tests/queries/test_415716.js
deleted file mode 100644
index 754a73e7c..000000000
--- a/toolkit/components/places/tests/queries/test_415716.js
+++ /dev/null
@@ -1,108 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function modHistoryTypes(val) {
- switch (val % 8) {
- case 0:
- case 1:
- return TRANSITION_LINK;
- case 2:
- return TRANSITION_TYPED;
- case 3:
- return TRANSITION_BOOKMARK;
- case 4:
- return TRANSITION_EMBED;
- case 5:
- return TRANSITION_REDIRECT_PERMANENT;
- case 6:
- return TRANSITION_REDIRECT_TEMPORARY;
- case 7:
- return TRANSITION_DOWNLOAD;
- case 8:
- return TRANSITION_FRAMED_LINK;
- }
- return TRANSITION_TYPED;
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-/**
- * Builds a test database by hand using various times, annotations and
- * visit numbers for this test
- */
-add_task(function* test_buildTestDatabase()
-{
- // This is the set of visits that we will match - our min visit is 2 so that's
- // why we add more visits to the same URIs.
- let testURI = uri("http://www.foo.com");
- let places = [];
-
- for (let i = 0; i < 12; ++i) {
- places.push({
- uri: testURI,
- transition: modHistoryTypes(i),
- visitDate: today
- });
- }
-
- testURI = uri("http://foo.com/youdontseeme.html");
- let testAnnoName = "moz-test-places/testing123";
- let testAnnoVal = "test";
- for (let i = 0; i < 12; ++i) {
- places.push({
- uri: testURI,
- transition: modHistoryTypes(i),
- visitDate: today
- });
- }
-
- yield PlacesTestUtils.addVisits(places);
-
- PlacesUtils.annotations.setPageAnnotation(testURI, testAnnoName,
- testAnnoVal, 0, 0);
-});
-
-/**
- * This test will test Queries that use relative Time Range, minVists, maxVisits,
- * annotation.
- * The Query:
- * Annotation == "moz-test-places/testing123" &&
- * TimeRange == "now() - 2d" &&
- * minVisits == 2 &&
- * maxVisits == 10
- */
-add_task(function test_execute()
-{
- let query = PlacesUtils.history.getNewQuery();
- query.annotation = "moz-test-places/testing123";
- query.beginTime = daybefore * 1000;
- query.beginTimeReference = PlacesUtils.history.TIME_RELATIVE_NOW;
- query.endTime = today * 1000;
- query.endTimeReference = PlacesUtils.history.TIME_RELATIVE_NOW;
- query.minVisits = 2;
- query.maxVisits = 10;
-
- // Options
- let options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- options.resultType = options.RESULTS_AS_VISIT;
-
- // Results
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- let cc = root.childCount;
- dump("----> cc is: " + cc + "\n");
- for (let i = 0; i < root.childCount; ++i) {
- let resultNode = root.getChild(i);
- let accesstime = Date(resultNode.time / 1000);
- dump("----> result: " + resultNode.uri + " Date: " + accesstime.toLocaleString() + "\n");
- }
- do_check_eq(cc, 0);
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_abstime-annotation-domain.js b/toolkit/components/places/tests/queries/test_abstime-annotation-domain.js
deleted file mode 100644
index 199fc0865..000000000
--- a/toolkit/components/places/tests/queries/test_abstime-annotation-domain.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const DAY_MSEC = 86400000;
-const MIN_MSEC = 60000;
-const HOUR_MSEC = 3600000;
-// Jan 6 2008 at 8am is our begin edge of the query
-var beginTimeDate = new Date(2008, 0, 6, 8, 0, 0, 0);
-// Jan 15 2008 at 9:30pm is our ending edge of the query
-var endTimeDate = new Date(2008, 0, 15, 21, 30, 0, 0);
-
-// These as millisecond values
-var beginTime = beginTimeDate.getTime();
-var endTime = endTimeDate.getTime();
-
-// Some range dates inside our query - mult by 1000 to convert to PRTIME
-var jan7_800 = (beginTime + DAY_MSEC) * 1000;
-var jan6_815 = (beginTime + (MIN_MSEC * 15)) * 1000;
-var jan11_800 = (beginTime + (DAY_MSEC * 5)) * 1000;
-var jan14_2130 = (endTime - DAY_MSEC) * 1000;
-var jan15_2045 = (endTime - (MIN_MSEC * 45)) * 1000;
-var jan12_1730 = (endTime - (DAY_MSEC * 3) - (HOUR_MSEC*4)) * 1000;
-
-// Dates outside our query - mult by 1000 to convert to PRTIME
-var jan6_700 = (beginTime - HOUR_MSEC) * 1000;
-var jan5_800 = (beginTime - DAY_MSEC) * 1000;
-var dec27_800 = (beginTime - (DAY_MSEC * 10)) * 1000;
-var jan15_2145 = (endTime + (MIN_MSEC * 15)) * 1000;
-var jan16_2130 = (endTime + (DAY_MSEC)) * 1000;
-var jan25_2130 = (endTime + (DAY_MSEC * 10)) * 1000;
-
-// So that we can easily use these too, convert them to PRTIME
-beginTime *= 1000;
-endTime *= 1000;
-
-/**
- * Array of objects to build our test database
- */
-var goodAnnoName = "moz-test-places/testing123";
-var val = "test";
-var badAnnoName = "text/foo";
-
-// The test data for our database, note that the ordering of the results that
-// will be returned by the query (the isInQuery: true objects) is IMPORTANT.
-// see compareArrayToResult in head_queries.js for more info.
-var testData = [
- // Test ftp protocol - vary the title length
- {isInQuery: true, isVisit: true, isDetails: true,
- uri: "ftp://foo.com/ftp", lastVisit: jan12_1730,
- title: "hugelongconfmozlagurationofwordswithasearchtermsinit whoo-hoo"},
-
- // Test flat domain with annotation
- {isInQuery: true, isVisit: true, isDetails: true, isPageAnnotation: true,
- uri: "http://foo.com/", annoName: goodAnnoName, annoVal: val,
- lastVisit: jan14_2130, title: "moz"},
-
- // Test subdomain included with isRedirect=true, different transtype
- {isInQuery: true, isVisit: true, isDetails: true, title: "moz",
- isRedirect: true, uri: "http://mail.foo.com/redirect", lastVisit: jan11_800,
- transType: PlacesUtils.history.TRANSITION_LINK},
-
- // Test subdomain inclued at the leading time edge
- {isInQuery: true, isVisit: true, isDetails: true,
- uri: "http://mail.foo.com/yiihah", title: "moz", lastVisit: jan6_815},
-
- // Test www. style URI is included, with an annotation
- {isInQuery: true, isVisit: true, isDetails: true, isPageAnnotation: true,
- uri: "http://www.foo.com/yiihah", annoName: goodAnnoName, annoVal: val,
- lastVisit: jan7_800, title: "moz"},
-
- // Test https protocol
- {isInQuery: true, isVisit: true, isDetails: true, title: "moz",
- uri: "https://foo.com/", lastVisit: jan15_2045},
-
- // Test begin edge of time
- {isInQuery: true, isVisit: true, isDetails: true, title: "moz mozilla",
- uri: "https://foo.com/begin.html", lastVisit: beginTime},
-
- // Test end edge of time
- {isInQuery: true, isVisit: true, isDetails: true, title: "moz mozilla",
- uri: "https://foo.com/end.html", lastVisit: endTime},
-
- // Test an image link, with annotations
- {isInQuery: true, isVisit: true, isDetails: true, isPageAnnotation: true,
- title: "mozzie the dino", uri: "https://foo.com/mozzie.png",
- annoName: goodAnnoName, annoVal: val, lastVisit: jan14_2130},
-
- // Begin the invalid queries: Test too early
- {isInQuery: false, isVisit:true, isDetails: true, title: "moz",
- uri: "http://foo.com/tooearly.php", lastVisit: jan6_700},
-
- // Test Bad Annotation
- {isInQuery: false, isVisit:true, isDetails: true, isPageAnnotation: true,
- title: "moz", uri: "http://foo.com/badanno.htm", lastVisit: jan12_1730,
- annoName: badAnnoName, annoVal: val},
-
- // Test bad URI
- {isInQuery: false, isVisit:true, isDetails: true, title: "moz",
- uri: "http://somefoo.com/justwrong.htm", lastVisit: jan11_800},
-
- // Test afterward, one to update
- {isInQuery: false, isVisit:true, isDetails: true, title: "changeme",
- uri: "http://foo.com/changeme1.htm", lastVisit: jan12_1730},
-
- // Test invalid title
- {isInQuery: false, isVisit:true, isDetails: true, title: "changeme2",
- uri: "http://foo.com/changeme2.htm", lastVisit: jan7_800},
-
- // Test changing the lastVisit
- {isInQuery: false, isVisit:true, isDetails: true, title: "moz",
- uri: "http://foo.com/changeme3.htm", lastVisit: dec27_800}];
-
-/**
- * This test will test a Query using several terms and do a bit of negative
- * testing for items that should be ignored while querying over history.
- * The Query:WHERE absoluteTime(matches) AND searchTerms AND URI
- * AND annotationIsNot(match) GROUP BY Domain, Day SORT BY uri,ascending
- * excludeITems(should be ignored)
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_abstime_annotation_domain()
-{
- // Initialize database
- yield task_populateDB(testData);
-
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.beginTime = beginTime;
- query.endTime = endTime;
- query.beginTimeReference = PlacesUtils.history.TIME_RELATIVE_EPOCH;
- query.endTimeReference = PlacesUtils.history.TIME_RELATIVE_EPOCH;
- query.searchTerms = "moz";
- query.domain = "foo.com";
- query.domainIsHost = false;
- query.annotation = "text/foo";
- query.annotationIsNot = true;
-
- // Options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_URI_ASCENDING;
- options.resultType = options.RESULTS_AS_URI;
- // The next two options should be ignored
- // can't use this one, breaks test - bug 419779
- // options.excludeItems = true;
-
- // Results
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- // Ensure the result set is correct
- compareArrayToResult(testData, root);
-
- // Make some changes to the result set
- // Let's add something first
- var addItem = [{isInQuery: true, isVisit: true, isDetails: true, title: "moz",
- uri: "http://www.foo.com/i-am-added.html", lastVisit: jan11_800}];
- yield task_populateDB(addItem);
- do_print("Adding item foo.com/i-am-added.html");
- do_check_eq(isInResult(addItem, root), true);
-
- // Let's update something by title
- var change1 = [{isDetails: true, uri: "http://foo.com/changeme1",
- lastVisit: jan12_1730, title: "moz moz mozzie"}];
- yield task_populateDB(change1);
- do_print("LiveUpdate by changing title");
- do_check_eq(isInResult(change1, root), true);
-
- // Let's update something by annotation
- // Updating a page by removing an annotation does not cause it to join this
- // query set. I tend to think that it should cause that page to join this
- // query set, because this visit fits all theother specified criteria once the
- // annotation is removed. Uncommenting this will fail the test.
- // Bug 424050
- /* var change2 = [{isPageAnnotation: true, uri: "http://foo.com/badannotaion.html",
- annoName: "text/mozilla", annoVal: "test"}];
- yield task_populateDB(change2);
- do_print("LiveUpdate by removing annotation");
- do_check_eq(isInResult(change2, root), true);*/
-
- // Let's update by adding a visit in the time range for an existing URI
- var change3 = [{isDetails: true, uri: "http://foo.com/changeme3.htm",
- title: "moz", lastVisit: jan15_2045}];
- yield task_populateDB(change3);
- do_print("LiveUpdate by adding visit within timerange");
- do_check_eq(isInResult(change3, root), true);
-
- // And delete something from the result set - using annotation
- // Once again, bug 424050 prevents this from passing
- /* var change4 = [{isPageAnnotation: true, uri: "ftp://foo.com/ftp",
- annoVal: "test", annoName: badAnnoName}];
- yield task_populateDB(change4);
- do_print("LiveUpdate by deleting item from set by adding annotation");
- do_check_eq(isInResult(change4, root), false);*/
-
- // Delete something by changing the title
- var change5 = [{isDetails: true, uri: "http://foo.com/end.html", title: "deleted"}];
- yield task_populateDB(change5);
- do_print("LiveUpdate by deleting item by changing title");
- do_check_eq(isInResult(change5, root), false);
-
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_abstime-annotation-uri.js b/toolkit/components/places/tests/queries/test_abstime-annotation-uri.js
deleted file mode 100644
index 145d2cb59..000000000
--- a/toolkit/components/places/tests/queries/test_abstime-annotation-uri.js
+++ /dev/null
@@ -1,162 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const DAY_MSEC = 86400000;
-const MIN_MSEC = 60000;
-const HOUR_MSEC = 3600000;
-// Jan 6 2008 at 8am is our begin edge of the query
-var beginTimeDate = new Date(2008, 0, 6, 8, 0, 0, 0);
-// Jan 15 2008 at 9:30pm is our ending edge of the query
-var endTimeDate = new Date(2008, 0, 15, 21, 30, 0, 0);
-
-// These as millisecond values
-var beginTime = beginTimeDate.getTime();
-var endTime = endTimeDate.getTime();
-
-// Some range dates inside our query - mult by 1000 to convert to PRTIME
-var jan7_800 = (beginTime + DAY_MSEC) * 1000;
-var jan6_815 = (beginTime + (MIN_MSEC * 15)) * 1000;
-var jan11_800 = (beginTime + (DAY_MSEC * 5)) * 1000;
-var jan14_2130 = (endTime - DAY_MSEC) * 1000;
-var jan15_2045 = (endTime - (MIN_MSEC * 45)) * 1000;
-var jan12_1730 = (endTime - (DAY_MSEC * 3) - (HOUR_MSEC*4)) * 1000;
-
-// Dates outside our query - mult by 1000 to convert to PRTIME
-var jan6_700 = (beginTime - HOUR_MSEC) * 1000;
-var jan5_800 = (beginTime - DAY_MSEC) * 1000;
-var dec27_800 = (beginTime - (DAY_MSEC * 10)) * 1000;
-var jan15_2145 = (endTime + (MIN_MSEC * 15)) * 1000;
-var jan16_2130 = (endTime + (DAY_MSEC)) * 1000;
-var jan25_2130 = (endTime + (DAY_MSEC * 10)) * 1000;
-
-// So that we can easily use these too, convert them to PRTIME
-beginTime *= 1000;
-endTime *= 1000;
-
-/**
- * Array of objects to build our test database
- */
-var goodAnnoName = "moz-test-places/testing123";
-var val = "test";
-var badAnnoName = "text/foo";
-
-// The test data for our database, note that the ordering of the results that
-// will be returned by the query (the isInQuery: true objects) is IMPORTANT.
-// see compareArrayToResult in head_queries.js for more info.
-var testData = [
-
- // Test flat domain with annotation
- {isInQuery: true, isVisit: true, isDetails: true, isPageAnnotation: true,
- uri: "http://foo.com/", annoName: goodAnnoName, annoVal: val,
- lastVisit: jan14_2130, title: "moz"},
-
- // Begin the invalid queries:
- // Test www. style URI is not included, with an annotation
- {isInQuery: false, isVisit: true, isDetails: true, isPageAnnotation: true,
- uri: "http://www.foo.com/yiihah", annoName: goodAnnoName, annoVal: val,
- lastVisit: jan7_800, title: "moz"},
-
- // Test subdomain not inclued at the leading time edge
- {isInQuery: false, isVisit: true, isDetails: true,
- uri: "http://mail.foo.com/yiihah", title: "moz", lastVisit: jan6_815},
-
- // Test https protocol
- {isInQuery: false, isVisit: true, isDetails: true, title: "moz",
- uri: "https://foo.com/", lastVisit: jan15_2045},
-
- // Test ftp protocol
- {isInQuery: false, isVisit: true, isDetails: true,
- uri: "ftp://foo.com/ftp", lastVisit: jan12_1730,
- title: "hugelongconfmozlagurationofwordswithasearchtermsinit whoo-hoo"},
-
- // Test too early
- {isInQuery: false, isVisit:true, isDetails: true, title: "moz",
- uri: "http://foo.com/tooearly.php", lastVisit: jan6_700},
-
- // Test Bad Annotation
- {isInQuery: false, isVisit:true, isDetails: true, isPageAnnotation: true,
- title: "moz", uri: "http://foo.com/badanno.htm", lastVisit: jan12_1730,
- annoName: badAnnoName, annoVal: val},
-
- // Test afterward, one to update
- {isInQuery: false, isVisit:true, isDetails: true, title: "changeme",
- uri: "http://foo.com/changeme1.htm", lastVisit: jan12_1730},
-
- // Test invalid title
- {isInQuery: false, isVisit:true, isDetails: true, title: "changeme2",
- uri: "http://foo.com/changeme2.htm", lastVisit: jan7_800},
-
- // Test changing the lastVisit
- {isInQuery: false, isVisit:true, isDetails: true, title: "moz",
- uri: "http://foo.com/changeme3.htm", lastVisit: dec27_800}];
-
-/**
- * This test will test a Query using several terms and do a bit of negative
- * testing for items that should be ignored while querying over history.
- * The Query:WHERE absoluteTime(matches) AND searchTerms AND URI
- * AND annotationIsNot(match) GROUP BY Domain, Day SORT BY uri,ascending
- * excludeITems(should be ignored)
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_abstime_annotation_uri()
-{
- // Initialize database
- yield task_populateDB(testData);
-
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.beginTime = beginTime;
- query.endTime = endTime;
- query.beginTimeReference = PlacesUtils.history.TIME_RELATIVE_EPOCH;
- query.endTimeReference = PlacesUtils.history.TIME_RELATIVE_EPOCH;
- query.searchTerms = "moz";
- query.uri = uri("http://foo.com");
- query.annotation = "text/foo";
- query.annotationIsNot = true;
-
- // Options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_URI_ASCENDING;
- options.resultType = options.RESULTS_AS_URI;
- // The next two options should be ignored
- // can't use this one, breaks test - bug 419779
- // options.excludeItems = true;
-
- // Results
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- // Ensure the result set is correct
- compareArrayToResult(testData, root);
-
- // live update.
- do_print("change title");
- var change1 = [{isDetails: true, uri:"http://foo.com/",
- title: "mo"}, ];
- yield task_populateDB(change1);
- do_check_false(isInResult({uri: "http://foo.com/"}, root));
-
- var change2 = [{isDetails: true, uri:"http://foo.com/",
- title: "moz", lastvisit: endTime}, ];
- yield task_populateDB(change2);
- dump_table("moz_places");
- do_check_false(isInResult({uri: "http://foo.com/"}, root));
-
- // Let's delete something from the result set - using annotation
- var change3 = [{isPageAnnotation: true,
- uri: "http://foo.com/",
- annoName: badAnnoName, annoVal: "test"}];
- yield task_populateDB(change3);
- do_print("LiveUpdate by removing annotation");
- do_check_false(isInResult({uri: "http://foo.com/"}, root));
-
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_async.js b/toolkit/components/places/tests/queries/test_async.js
deleted file mode 100644
index 0ec99f8fc..000000000
--- a/toolkit/components/places/tests/queries/test_async.js
+++ /dev/null
@@ -1,371 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [
- {
- desc: "nsNavHistoryFolderResultNode: Basic test, asynchronously open and " +
- "close container with a single child",
-
- loading: function (node, newState, oldState) {
- this.checkStateChanged("loading", 1);
- this.checkArgs("loading", node, oldState, node.STATE_CLOSED);
- },
-
- opened: function (node, newState, oldState) {
- this.checkStateChanged("opened", 1);
- this.checkState("loading", 1);
- this.checkArgs("opened", node, oldState, node.STATE_LOADING);
-
- print("Checking node children");
- compareArrayToResult(this.data, node);
-
- print("Closing container");
- node.containerOpen = false;
- },
-
- closed: function (node, newState, oldState) {
- this.checkStateChanged("closed", 1);
- this.checkState("opened", 1);
- this.checkArgs("closed", node, oldState, node.STATE_OPENED);
- this.success();
- }
- },
-
- {
- desc: "nsNavHistoryFolderResultNode: After async open and no changes, " +
- "second open should be synchronous",
-
- loading: function (node, newState, oldState) {
- this.checkStateChanged("loading", 1);
- this.checkState("closed", 0);
- this.checkArgs("loading", node, oldState, node.STATE_CLOSED);
- },
-
- opened: function (node, newState, oldState) {
- let cnt = this.checkStateChanged("opened", 1, 2);
- let expectOldState = cnt === 1 ? node.STATE_LOADING : node.STATE_CLOSED;
- this.checkArgs("opened", node, oldState, expectOldState);
-
- print("Checking node children");
- compareArrayToResult(this.data, node);
-
- print("Closing container");
- node.containerOpen = false;
- },
-
- closed: function (node, newState, oldState) {
- let cnt = this.checkStateChanged("closed", 1, 2);
- this.checkArgs("closed", node, oldState, node.STATE_OPENED);
-
- switch (cnt) {
- case 1:
- node.containerOpen = true;
- break;
- case 2:
- this.success();
- break;
- }
- }
- },
-
- {
- desc: "nsNavHistoryFolderResultNode: After closing container in " +
- "loading(), opened() should not be called",
-
- loading: function (node, newState, oldState) {
- this.checkStateChanged("loading", 1);
- this.checkArgs("loading", node, oldState, node.STATE_CLOSED);
- print("Closing container");
- node.containerOpen = false;
- },
-
- opened: function (node, newState, oldState) {
- do_throw("opened should not be called");
- },
-
- closed: function (node, newState, oldState) {
- this.checkStateChanged("closed", 1);
- this.checkState("loading", 1);
- this.checkArgs("closed", node, oldState, node.STATE_LOADING);
- this.success();
- }
- }
-];
-
-
-/**
- * Instances of this class become the prototypes of the test objects above.
- * Each test can therefore use the methods of this class, or they can override
- * them if they want. To run a test, call setup() and then run().
- */
-function Test() {
- // This maps a state name to the number of times it's been observed.
- this.stateCounts = {};
- // Promise object resolved when the next test can be run.
- this.deferNextTest = Promise.defer();
-}
-
-Test.prototype = {
- /**
- * Call this when an observer observes a container state change to sanity
- * check the arguments.
- *
- * @param aNewState
- * The name of the new state. Used only for printing out helpful info.
- * @param aNode
- * The node argument passed to containerStateChanged.
- * @param aOldState
- * The old state argument passed to containerStateChanged.
- * @param aExpectOldState
- * The expected old state.
- */
- checkArgs: function (aNewState, aNode, aOldState, aExpectOldState) {
- print("Node passed on " + aNewState + " should be result.root");
- do_check_eq(this.result.root, aNode);
- print("Old state passed on " + aNewState + " should be " + aExpectOldState);
-
- // aOldState comes from xpconnect and will therefore be defined. It may be
- // zero, though, so use strict equality just to make sure aExpectOldState is
- // also defined.
- do_check_true(aOldState === aExpectOldState);
- },
-
- /**
- * Call this when an observer observes a container state change. It registers
- * the state change and ensures that it has been observed the given number
- * of times. See checkState for parameter explanations.
- *
- * @return The number of times aState has been observed, including the new
- * observation.
- */
- checkStateChanged: function (aState, aExpectedMin, aExpectedMax) {
- print(aState + " state change observed");
- if (!this.stateCounts.hasOwnProperty(aState))
- this.stateCounts[aState] = 0;
- this.stateCounts[aState]++;
- return this.checkState(aState, aExpectedMin, aExpectedMax);
- },
-
- /**
- * Ensures that the state has been observed the given number of times.
- *
- * @param aState
- * The name of the state.
- * @param aExpectedMin
- * The state must have been observed at least this number of times.
- * @param aExpectedMax
- * The state must have been observed at most this number of times.
- * This parameter is optional. If undefined, it's set to
- * aExpectedMin.
- * @return The number of times aState has been observed, including the new
- * observation.
- */
- checkState: function (aState, aExpectedMin, aExpectedMax) {
- let cnt = this.stateCounts[aState] || 0;
- if (aExpectedMax === undefined)
- aExpectedMax = aExpectedMin;
- if (aExpectedMin === aExpectedMax) {
- print(aState + " should be observed only " + aExpectedMin +
- " times (actual = " + cnt + ")");
- }
- else {
- print(aState + " should be observed at least " + aExpectedMin +
- " times and at most " + aExpectedMax + " times (actual = " +
- cnt + ")");
- }
- do_check_true(cnt >= aExpectedMin && cnt <= aExpectedMax);
- return cnt;
- },
-
- /**
- * Asynchronously opens the root of the test's result.
- */
- openContainer: function () {
- // Set up the result observer. It delegates to this object's callbacks and
- // wraps them in a try-catch so that errors don't get eaten.
- let self = this;
- this.observer = {
- containerStateChanged: function (container, oldState, newState) {
- print("New state passed to containerStateChanged() should equal the " +
- "container's current state");
- do_check_eq(newState, container.state);
-
- try {
- switch (newState) {
- case Ci.nsINavHistoryContainerResultNode.STATE_LOADING:
- self.loading(container, newState, oldState);
- break;
- case Ci.nsINavHistoryContainerResultNode.STATE_OPENED:
- self.opened(container, newState, oldState);
- break;
- case Ci.nsINavHistoryContainerResultNode.STATE_CLOSED:
- self.closed(container, newState, oldState);
- break;
- default:
- do_throw("Unexpected new state! " + newState);
- }
- }
- catch (err) {
- do_throw(err);
- }
- },
- };
- this.result.addObserver(this.observer, false);
-
- print("Opening container");
- this.result.root.containerOpen = true;
- },
-
- /**
- * Starts the test and returns a promise resolved when the test completes.
- */
- run: function () {
- this.openContainer();
- return this.deferNextTest.promise;
- },
-
- /**
- * This must be called before run(). It adds a bookmark and sets up the
- * test's result. Override if need be.
- */
- setup: function*() {
- // Populate the database with different types of bookmark items.
- this.data = DataHelper.makeDataArray([
- { type: "bookmark" },
- { type: "separator" },
- { type: "folder" },
- { type: "bookmark", uri: "place:terms=foo" }
- ]);
- yield task_populateDB(this.data);
-
- // Make a query.
- this.query = PlacesUtils.history.getNewQuery();
- this.query.setFolders([DataHelper.defaults.bookmark.parent], 1);
- this.opts = PlacesUtils.history.getNewQueryOptions();
- this.opts.asyncEnabled = true;
- this.result = PlacesUtils.history.executeQuery(this.query, this.opts);
- },
-
- /**
- * Call this when the test has succeeded. It cleans up resources and starts
- * the next test.
- */
- success: function () {
- this.result.removeObserver(this.observer);
-
- // Resolve the promise object that indicates that the next test can be run.
- this.deferNextTest.resolve();
- }
-};
-
-/**
- * This makes it a little bit easier to use the functions of head_queries.js.
- */
-var DataHelper = {
- defaults: {
- bookmark: {
- parent: PlacesUtils.bookmarks.unfiledBookmarksFolder,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- uri: "http://example.com/",
- title: "test bookmark"
- },
-
- folder: {
- parent: PlacesUtils.bookmarks.unfiledBookmarksFolder,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "test folder"
- },
-
- separator: {
- parent: PlacesUtils.bookmarks.unfiledBookmarksFolder,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- }
- },
-
- /**
- * Converts an array of simple bookmark item descriptions to the more verbose
- * format required by task_populateDB() in head_queries.js.
- *
- * @param aData
- * An array of objects, each of which describes a bookmark item.
- * @return An array of objects suitable for passing to populateDB().
- */
- makeDataArray: function DH_makeDataArray(aData) {
- let self = this;
- return aData.map(function (dat) {
- let type = dat.type;
- dat = self._makeDataWithDefaults(dat, self.defaults[type]);
- switch (type) {
- case "bookmark":
- return {
- isBookmark: true,
- uri: dat.uri,
- parentGuid: dat.parentGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: dat.title,
- isInQuery: true
- };
- case "separator":
- return {
- isSeparator: true,
- parentGuid: dat.parentGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- isInQuery: true
- };
- case "folder":
- return {
- isFolder: true,
- parentGuid: dat.parentGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: dat.title,
- isInQuery: true
- };
- default:
- do_throw("Unknown data type when populating DB: " + type);
- return undefined;
- }
- });
- },
-
- /**
- * Returns a copy of aData, except that any properties that are undefined but
- * defined in aDefaults are set to the corresponding values in aDefaults.
- *
- * @param aData
- * An object describing a bookmark item.
- * @param aDefaults
- * An object describing the default bookmark item.
- * @return A copy of aData with defaults values set.
- */
- _makeDataWithDefaults: function DH__makeDataWithDefaults(aData, aDefaults) {
- let dat = {};
- for (let [prop, val] of Object.entries(aDefaults)) {
- dat[prop] = aData.hasOwnProperty(prop) ? aData[prop] : val;
- }
- return dat;
- }
-};
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_async()
-{
- for (let test of tests) {
- yield PlacesUtils.bookmarks.eraseEverything();
-
- test.__proto__ = new Test();
- yield test.setup();
-
- print("------ Running test: " + test.desc);
- yield test.run();
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
- print("All tests done, exiting");
-});
diff --git a/toolkit/components/places/tests/queries/test_containersQueries_sorting.js b/toolkit/components/places/tests/queries/test_containersQueries_sorting.js
deleted file mode 100644
index ab9f2bf90..000000000
--- a/toolkit/components/places/tests/queries/test_containersQueries_sorting.js
+++ /dev/null
@@ -1,411 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Testing behavior of bug 473157
- * "Want to sort history in container view without sorting the containers"
- * and regression bug 488783
- * Tags list no longer sorted (alphabetized).
- * This test is for global testing sorting containers queries.
- */
-
-// Globals and Constants
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var bh = hs.QueryInterface(Ci.nsIBrowserHistory);
-var tagging = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-
-var resultTypes = [
- {value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY, name: "RESULTS_AS_DATE_QUERY"},
- {value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY, name: "RESULTS_AS_SITE_QUERY"},
- {value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY, name: "RESULTS_AS_DATE_SITE_QUERY"},
- {value: Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY, name: "RESULTS_AS_TAG_QUERY"},
-];
-
-var sortingModes = [
- {value: Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING, name: "SORT_BY_TITLE_ASCENDING"},
- {value: Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_DESCENDING, name: "SORT_BY_TITLE_DESCENDING"},
- {value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING, name: "SORT_BY_DATE_ASCENDING"},
- {value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING, name: "SORT_BY_DATE_DESCENDING"},
- {value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING, name: "SORT_BY_DATEADDED_ASCENDING"},
- {value: Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING, name: "SORT_BY_DATEADDED_DESCENDING"},
-];
-
-// These pages will be added from newest to oldest and from less visited to most
-// visited.
-var pages = [
- "http://www.mozilla.org/c/",
- "http://www.mozilla.org/a/",
- "http://www.mozilla.org/b/",
- "http://www.mozilla.com/c/",
- "http://www.mozilla.com/a/",
- "http://www.mozilla.com/b/",
-];
-
-var tags = [
- "mozilla",
- "Development",
- "test",
-];
-
-// Test Runner
-
-/**
- * Enumerates all the sequences of the cartesian product of the arrays contained
- * in aSequences. Examples:
- *
- * cartProd([[1, 2, 3], ["a", "b"]], callback);
- * // callback is called 3 * 2 = 6 times with the following arrays:
- * // [1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]
- *
- * cartProd([["a"], [1, 2, 3], ["X", "Y"]], callback);
- * // callback is called 1 * 3 * 2 = 6 times with the following arrays:
- * // ["a", 1, "X"], ["a", 1, "Y"], ["a", 2, "X"], ["a", 2, "Y"],
- * // ["a", 3, "X"], ["a", 3, "Y"]
- *
- * cartProd([[1], [2], [3], [4]], callback);
- * // callback is called 1 * 1 * 1 * 1 = 1 time with the following array:
- * // [1, 2, 3, 4]
- *
- * cartProd([], callback);
- * // callback is 0 times
- *
- * cartProd([[1, 2, 3, 4]], callback);
- * // callback is called 4 times with the following arrays:
- * // [1], [2], [3], [4]
- *
- * @param aSequences
- * an array that contains an arbitrary number of arrays
- * @param aCallback
- * a function that is passed each sequence of the product as it's
- * computed
- * @return the total number of sequences in the product
- */
-function cartProd(aSequences, aCallback)
-{
- if (aSequences.length === 0)
- return 0;
-
- // For each sequence in aSequences, we maintain a pointer (an array index,
- // really) to the element we're currently enumerating in that sequence
- var seqEltPtrs = aSequences.map(i => 0);
-
- var numProds = 0;
- var done = false;
- while (!done) {
- numProds++;
-
- // prod = sequence in product we're currently enumerating
- var prod = [];
- for (var i = 0; i < aSequences.length; i++) {
- prod.push(aSequences[i][seqEltPtrs[i]]);
- }
- aCallback(prod);
-
- // The next sequence in the product differs from the current one by just a
- // single element. Determine which element that is. We advance the
- // "rightmost" element pointer to the "right" by one. If we move past the
- // end of that pointer's sequence, reset the pointer to the first element
- // in its sequence and then try the sequence to the "left", and so on.
-
- // seqPtr = index of rightmost input sequence whose element pointer is not
- // past the end of the sequence
- var seqPtr = aSequences.length - 1;
- while (!done) {
- // Advance the rightmost element pointer.
- seqEltPtrs[seqPtr]++;
-
- // The rightmost element pointer is past the end of its sequence.
- if (seqEltPtrs[seqPtr] >= aSequences[seqPtr].length) {
- seqEltPtrs[seqPtr] = 0;
- seqPtr--;
-
- // All element pointers are past the ends of their sequences.
- if (seqPtr < 0)
- done = true;
- }
- else break;
- }
- }
- return numProds;
-}
-
-/**
- * Test a query based on passed-in options.
- *
- * @param aSequence
- * array of options we will use to query.
- */
-function test_query_callback(aSequence) {
- do_check_eq(aSequence.length, 2);
- var resultType = aSequence[0];
- var sortingMode = aSequence[1];
- print("\n\n*** Testing default sorting for resultType (" + resultType.name + ") and sortingMode (" + sortingMode.name + ")");
-
- // Skip invalid combinations sorting queries by none.
- if (resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY &&
- (sortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING ||
- sortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING)) {
- // This is a bookmark query, we can't sort by visit date.
- sortingMode.value = Ci.nsINavHistoryQueryOptions.SORT_BY_NONE;
- }
- if (resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
- resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY ||
- resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY) {
- // This is an history query, we can't sort by date added.
- if (sortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING ||
- sortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING)
- sortingMode.value = Ci.nsINavHistoryQueryOptions.SORT_BY_NONE;
- }
-
- // Create a new query with required options.
- var query = PlacesUtils.history.getNewQuery();
- var options = PlacesUtils.history.getNewQueryOptions();
- options.resultType = resultType.value;
- options.sortingMode = sortingMode.value;
-
- // Compare resultset with expectedData.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- if (resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
- resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY) {
- // Date containers are always sorted by date descending.
- check_children_sorting(root,
- Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING);
- }
- else
- check_children_sorting(root, sortingMode.value);
-
- // Now Check sorting of the first child container.
- var container = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- container.containerOpen = true;
-
- if (resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY) {
- // Has more than one level of containers, first we check the sorting of
- // the first level (site containers), those won't inherit sorting...
- check_children_sorting(container,
- Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING);
- // ...then we check sorting of the contained urls, we can't inherit sorting
- // since the above level does not inherit it, so they will be sorted by
- // title ascending.
- let innerContainer = container.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- innerContainer.containerOpen = true;
- check_children_sorting(innerContainer,
- Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING);
- innerContainer.containerOpen = false;
- }
- else if (resultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY) {
- // Sorting mode for tag contents is hardcoded for now, to allow for faster
- // duplicates filtering.
- check_children_sorting(container,
- Ci.nsINavHistoryQueryOptions.SORT_BY_NONE);
- }
- else
- check_children_sorting(container, sortingMode.value);
-
- container.containerOpen = false;
- root.containerOpen = false;
-
- test_result_sortingMode_change(result, resultType, sortingMode);
-}
-
-/**
- * Sets sortingMode on aResult and checks for correct sorting of children.
- * Containers should not change their sorting, while contained uri nodes should.
- *
- * @param aResult
- * nsINavHistoryResult generated by our query.
- * @param aResultType
- * required result type.
- * @param aOriginalSortingMode
- * the sorting mode from query's options.
- */
-function test_result_sortingMode_change(aResult, aResultType, aOriginalSortingMode) {
- var root = aResult.root;
- // Now we set sortingMode on the result and check that containers are not
- // sorted while children are.
- sortingModes.forEach(function sortingModeChecker(aForcedSortingMode) {
- print("\n* Test setting sortingMode (" + aForcedSortingMode.name + ") " +
- "on result with resultType (" + aResultType.name + ") " +
- "currently sorted as (" + aOriginalSortingMode.name + ")");
-
- aResult.sortingMode = aForcedSortingMode.value;
- root.containerOpen = true;
-
- if (aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
- aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY) {
- // Date containers are always sorted by date descending.
- check_children_sorting(root,
- Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING);
- }
- else if (aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY &&
- (aOriginalSortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING ||
- aOriginalSortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING)) {
- // Site containers don't have a good time property to sort by.
- check_children_sorting(root,
- Ci.nsINavHistoryQueryOptions.SORT_BY_NONE);
- }
- else
- check_children_sorting(root, aOriginalSortingMode.value);
-
- // Now Check sorting of the first child container.
- var container = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- container.containerOpen = true;
-
- if (aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY) {
- // Has more than one level of containers, first we check the sorting of
- // the first level (site containers), those won't be sorted...
- check_children_sorting(container,
- Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING);
- // ...then we check sorting of the second level of containers, result
- // will sort them through recursiveSort.
- let innerContainer = container.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- innerContainer.containerOpen = true;
- check_children_sorting(innerContainer, aForcedSortingMode.value);
- innerContainer.containerOpen = false;
- }
- else {
- if (aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
- aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY ||
- aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY) {
- // Date containers are always sorted by date descending.
- check_children_sorting(root, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE);
- }
- else if (aResultType.value == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY &&
- (aOriginalSortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING ||
- aOriginalSortingMode.value == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING)) {
- // Site containers don't have a good time property to sort by.
- check_children_sorting(root, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE);
- }
- else
- check_children_sorting(root, aOriginalSortingMode.value);
-
- // Children should always be sorted.
- check_children_sorting(container, aForcedSortingMode.value);
- }
-
- container.containerOpen = false;
- root.containerOpen = false;
- });
-}
-
-/**
- * Test if children of aRootNode are correctly sorted.
- * @param aRootNode
- * already opened root node from our query's result.
- * @param aExpectedSortingMode
- * The sortingMode we expect results to be.
- */
-function check_children_sorting(aRootNode, aExpectedSortingMode) {
- var results = [];
- print("Found children:");
- for (let i = 0; i < aRootNode.childCount; i++) {
- results[i] = aRootNode.getChild(i);
- print(i + " " + results[i].title);
- }
-
- // Helper for case insensitive string comparison.
- function caseInsensitiveStringComparator(a, b) {
- var aLC = a.toLowerCase();
- var bLC = b.toLowerCase();
- if (aLC < bLC)
- return -1;
- if (aLC > bLC)
- return 1;
- return 0;
- }
-
- // Get a comparator based on expected sortingMode.
- var comparator;
- switch (aExpectedSortingMode) {
- case Ci.nsINavHistoryQueryOptions.SORT_BY_NONE:
- comparator = function (a, b) {
- return 0;
- }
- break;
- case Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING:
- comparator = function (a, b) {
- return caseInsensitiveStringComparator(a.title, b.title);
- }
- break;
- case Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_DESCENDING:
- comparator = function (a, b) {
- return -caseInsensitiveStringComparator(a.title, b.title);
- }
- break;
- case Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING:
- comparator = function (a, b) {
- return a.time - b.time;
- }
- break;
- case Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING:
- comparator = function (a, b) {
- return b.time - a.time;
- }
- case Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING:
- comparator = function (a, b) {
- return a.dateAdded - b.dateAdded;
- }
- break;
- case Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING:
- comparator = function (a, b) {
- return b.dateAdded - a.dateAdded;
- }
- break;
- default:
- do_throw("Unknown sorting type: " + aExpectedSortingMode);
- }
-
- // Make an independent copy of the results array and sort it.
- var sortedResults = results.slice();
- sortedResults.sort(comparator);
- // Actually compare returned children with our sorted array.
- for (let i = 0; i < sortedResults.length; i++) {
- if (sortedResults[i].title != results[i].title)
- print(i + " index wrong, expected " + sortedResults[i].title +
- " found " + results[i].title);
- do_check_eq(sortedResults[i].title, results[i].title);
- }
-}
-
-// Main
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_containersQueries_sorting()
-{
- // Add visits, bookmarks and tags to our database.
- var timeInMilliseconds = Date.now();
- var visitCount = 0;
- var dayOffset = 0;
- var visits = [];
- pages.forEach(aPageUrl => visits.push(
- { isVisit: true,
- isBookmark: true,
- transType: Ci.nsINavHistoryService.TRANSITION_TYPED,
- uri: aPageUrl,
- title: aPageUrl,
- // subtract 5 hours per iteration, to expose more than one day container.
- lastVisit: (timeInMilliseconds - (18000 * 1000 * dayOffset++)) * 1000,
- visitCount: visitCount++,
- isTag: true,
- tagArray: tags,
- isInQuery: true }));
- yield task_populateDB(visits);
-
- cartProd([resultTypes, sortingModes], test_query_callback);
-});
diff --git a/toolkit/components/places/tests/queries/test_history_queries_tags_liveUpdate.js b/toolkit/components/places/tests/queries/test_history_queries_tags_liveUpdate.js
deleted file mode 100644
index fbbacf6c9..000000000
--- a/toolkit/components/places/tests/queries/test_history_queries_tags_liveUpdate.js
+++ /dev/null
@@ -1,200 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This test ensures that tags changes are correctly live-updated in a history
-// query.
-
-let timeInMicroseconds = PlacesUtils.toPRTime(Date.now() - 10000);
-
-function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds + 1000;
- return timeInMicroseconds;
-}
-
-var gTestData = [
- {
- isVisit: true,
- uri: "http://example.com/1/",
- lastVisit: newTimeInMicroseconds(),
- isInQuery: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "example1",
- },
- {
- isVisit: true,
- uri: "http://example.com/2/",
- lastVisit: newTimeInMicroseconds(),
- isInQuery: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "example2",
- },
- {
- isVisit: true,
- uri: "http://example.com/3/",
- lastVisit: newTimeInMicroseconds(),
- isInQuery: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "example3",
- },
-];
-
-function newQueryWithOptions()
-{
- return [ PlacesUtils.history.getNewQuery(),
- PlacesUtils.history.getNewQueryOptions() ];
-}
-
-function testQueryContents(aQuery, aOptions, aCallback)
-{
- let root = PlacesUtils.history.executeQuery(aQuery, aOptions).root;
- root.containerOpen = true;
- aCallback(root);
- root.containerOpen = false;
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_initialize()
-{
- yield task_populateDB(gTestData);
-});
-
-add_task(function pages_query()
-{
- let [query, options] = newQueryWithOptions();
- testQueryContents(query, options, function (root) {
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- let uri = NetUtil.newURI(node.uri);
- do_check_eq(node.tags, null);
- PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, "test-tag");
- PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, null);
- }
- });
-});
-
-add_task(function visits_query()
-{
- let [query, options] = newQueryWithOptions();
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- testQueryContents(query, options, function (root) {
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- let uri = NetUtil.newURI(node.uri);
- do_check_eq(node.tags, null);
- PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, "test-tag");
- PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, null);
- }
- });
-});
-
-add_task(function bookmarks_query()
-{
- let [query, options] = newQueryWithOptions();
- query.setFolders([PlacesUtils.unfiledBookmarksFolderId], 1);
- testQueryContents(query, options, function (root) {
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- let uri = NetUtil.newURI(node.uri);
- do_check_eq(node.tags, null);
- PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, "test-tag");
- PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, null);
- }
- });
-});
-
-add_task(function pages_searchterm_query()
-{
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "example";
- testQueryContents(query, options, function (root) {
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- let uri = NetUtil.newURI(node.uri);
- do_check_eq(node.tags, null);
- PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, "test-tag");
- PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, null);
- }
- });
-});
-
-add_task(function visits_searchterm_query()
-{
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "example";
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- testQueryContents(query, options, function (root) {
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- let uri = NetUtil.newURI(node.uri);
- do_check_eq(node.tags, null);
- PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, "test-tag");
- PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
- do_check_eq(node.tags, null);
- }
- });
-});
-
-add_task(function pages_searchterm_is_tag_query()
-{
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "test-tag";
- testQueryContents(query, options, function (root) {
- compareArrayToResult([], root);
- gTestData.forEach(function (data) {
- let uri = NetUtil.newURI(data.uri);
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- data.title);
- PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
- compareArrayToResult([data], root);
- PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
- compareArrayToResult([], root);
- });
- });
-});
-
-add_task(function visits_searchterm_is_tag_query()
-{
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "test-tag";
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- testQueryContents(query, options, function (root) {
- compareArrayToResult([], root);
- gTestData.forEach(function (data) {
- let uri = NetUtil.newURI(data.uri);
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- data.title);
- PlacesUtils.tagging.tagURI(uri, ["test-tag"]);
- compareArrayToResult([data], root);
- PlacesUtils.tagging.untagURI(uri, ["test-tag"]);
- compareArrayToResult([], root);
- });
- });
-});
diff --git a/toolkit/components/places/tests/queries/test_history_queries_titles_liveUpdate.js b/toolkit/components/places/tests/queries/test_history_queries_titles_liveUpdate.js
deleted file mode 100644
index eec87fe0e..000000000
--- a/toolkit/components/places/tests/queries/test_history_queries_titles_liveUpdate.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This test ensures that tags changes are correctly live-updated in a history
-// query.
-
-let timeInMicroseconds = PlacesUtils.toPRTime(Date.now() - 10000);
-
-function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds + 1000;
- return timeInMicroseconds;
-}
-
-var gTestData = [
- {
- isVisit: true,
- uri: "http://example.com/1/",
- lastVisit: newTimeInMicroseconds(),
- isInQuery: true,
- title: "title1",
- },
- {
- isVisit: true,
- uri: "http://example.com/2/",
- lastVisit: newTimeInMicroseconds(),
- isInQuery: true,
- title: "title2",
- },
- {
- isVisit: true,
- uri: "http://example.com/3/",
- lastVisit: newTimeInMicroseconds(),
- isInQuery: true,
- title: "title3",
- },
-];
-
-function searchNodeHavingUrl(aRoot, aUrl) {
- for (let i = 0; i < aRoot.childCount; i++) {
- if (aRoot.getChild(i).uri == aUrl) {
- return aRoot.getChild(i);
- }
- }
- return undefined;
-}
-
-function newQueryWithOptions()
-{
- return [ PlacesUtils.history.getNewQuery(),
- PlacesUtils.history.getNewQueryOptions() ];
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* pages_query()
-{
- yield task_populateDB(gTestData);
-
- let [query, options] = newQueryWithOptions();
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- do_check_eq(node.title, gTestData[i].title);
- let uri = NetUtil.newURI(node.uri);
- yield PlacesTestUtils.addVisits({uri: uri, title: "changedTitle"});
- do_check_eq(node.title, "changedTitle");
- yield PlacesTestUtils.addVisits({uri: uri, title: gTestData[i].title});
- do_check_eq(node.title, gTestData[i].title);
- }
-
- root.containerOpen = false;
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* visits_query()
-{
- yield task_populateDB(gTestData);
-
- let [query, options] = newQueryWithOptions();
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
-
- for (let testData of gTestData) {
- let uri = NetUtil.newURI(testData.uri);
- let node = searchNodeHavingUrl(root, testData.uri);
- do_check_eq(node.title, testData.title);
- yield PlacesTestUtils.addVisits({uri: uri, title: "changedTitle"});
- node = searchNodeHavingUrl(root, testData.uri);
- do_check_eq(node.title, "changedTitle");
- yield PlacesTestUtils.addVisits({uri: uri, title: testData.title});
- node = searchNodeHavingUrl(root, testData.uri);
- do_check_eq(node.title, testData.title);
- }
-
- root.containerOpen = false;
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* pages_searchterm_query()
-{
- yield task_populateDB(gTestData);
-
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "example";
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- let uri = NetUtil.newURI(node.uri);
- do_check_eq(node.title, gTestData[i].title);
- yield PlacesTestUtils.addVisits({uri: uri, title: "changedTitle"});
- do_check_eq(node.title, "changedTitle");
- yield PlacesTestUtils.addVisits({uri: uri, title: gTestData[i].title});
- do_check_eq(node.title, gTestData[i].title);
- }
-
- root.containerOpen = false;
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* visits_searchterm_query()
-{
- yield task_populateDB(gTestData);
-
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "example";
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- compareArrayToResult([gTestData[0], gTestData[1], gTestData[2]], root);
- for (let testData of gTestData) {
- let uri = NetUtil.newURI(testData.uri);
- let node = searchNodeHavingUrl(root, testData.uri);
- do_check_eq(node.title, testData.title);
- yield PlacesTestUtils.addVisits({uri: uri, title: "changedTitle"});
- node = searchNodeHavingUrl(root, testData.uri);
- do_check_eq(node.title, "changedTitle");
- yield PlacesTestUtils.addVisits({uri: uri, title: testData.title});
- node = searchNodeHavingUrl(root, testData.uri);
- do_check_eq(node.title, testData.title);
- }
-
- root.containerOpen = false;
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* pages_searchterm_is_title_query()
-{
- yield task_populateDB(gTestData);
-
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "match";
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- compareArrayToResult([], root);
- for (let data of gTestData) {
- let uri = NetUtil.newURI(data.uri);
- let origTitle = data.title;
- data.title = "match";
- yield PlacesTestUtils.addVisits({ uri: uri, title: data.title,
- visitDate: data.lastVisit });
- compareArrayToResult([data], root);
- data.title = origTitle;
- yield PlacesTestUtils.addVisits({ uri: uri, title: data.title,
- visitDate: data.lastVisit });
- compareArrayToResult([], root);
- }
-
- root.containerOpen = false;
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* visits_searchterm_is_title_query()
-{
- yield task_populateDB(gTestData);
-
- let [query, options] = newQueryWithOptions();
- query.searchTerms = "match";
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- compareArrayToResult([], root);
- for (let data of gTestData) {
- let uri = NetUtil.newURI(data.uri);
- let origTitle = data.title;
- data.title = "match";
- yield PlacesTestUtils.addVisits({ uri: uri, title: data.title,
- visitDate: data.lastVisit });
- compareArrayToResult([data], root);
- data.title = origTitle;
- yield PlacesTestUtils.addVisits({ uri: uri, title: data.title,
- visitDate: data.lastVisit });
- compareArrayToResult([], root);
- }
-
- root.containerOpen = false;
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/queries/test_onlyBookmarked.js b/toolkit/components/places/tests/queries/test_onlyBookmarked.js
deleted file mode 100644
index 45704c109..000000000
--- a/toolkit/components/places/tests/queries/test_onlyBookmarked.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * The next thing we do is create a test database for us. Each test runs with
- * its own database (tail_queries.js will clear it after the run). Take a look
- * at the queryData object in head_queries.js, and you'll see how this object
- * works. You can call it anything you like, but I usually use "testData".
- * I'll include a couple of example entries in the database.
- *
- * Note that to use the compareArrayToResult API, you need to put all the
- * results that are in the query set at the top of the testData list, and those
- * results MUST be in the same sort order as the items in the resulting query.
- */
-
-var testData = [
- // Add a bookmark that should be in the results
- { isBookmark: true,
- uri: "http://bookmarked.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- isInQuery: true },
-
- // Add a bookmark that should not be in the results
- { isBookmark: true,
- uri: "http://bookmarked-elsewhere.com/",
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- isInQuery: false },
-
- // Add an un-bookmarked visit
- { isVisit: true,
- uri: "http://notbookmarked.com/",
- isInQuery: false }
-];
-
-
-/**
- * run_test is where the magic happens. This is automatically run by the test
- * harness. It is where you do the work of creating the query, running it, and
- * playing with the result set.
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_onlyBookmarked()
-{
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(testData);
-
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.toolbarFolderId], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_HISTORY;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- // You can use this to compare the data in the array with the result set,
- // if the array's isInQuery: true items are sorted the same way as the result
- // set.
- do_print("begin first test");
- compareArrayToResult(testData, root);
- do_print("end first test");
-
- // Test live-update
- var liveUpdateTestData = [
- // Add a bookmark that should show up
- { isBookmark: true,
- uri: "http://bookmarked2.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- isInQuery: true },
-
- // Add a bookmark that should not show up
- { isBookmark: true,
- uri: "http://bookmarked-elsewhere2.com/",
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- isInQuery: false }
- ];
-
- yield task_populateDB(liveUpdateTestData); // add to the db
-
- // add to the test data
- testData.push(liveUpdateTestData[0]);
- testData.push(liveUpdateTestData[1]);
-
- // re-query and test
- do_print("begin live-update test");
- compareArrayToResult(testData, root);
- do_print("end live-update test");
-/*
- // we are actually not updating during a batch.
- // see bug 432706 for details.
-
- // Here's a batch update
- var updateBatch = {
- runBatched: function (aUserData) {
- liveUpdateTestData[0].uri = "http://bookmarked3.com";
- liveUpdateTestData[1].uri = "http://bookmarked-elsewhere3.com";
- populateDB(liveUpdateTestData);
- testData.push(liveUpdateTestData[0]);
- testData.push(liveUpdateTestData[1]);
- }
- };
-
- PlacesUtils.history.runInBatchMode(updateBatch, null);
-
- // re-query and test
- do_print("begin batched test");
- compareArrayToResult(testData, root);
- do_print("end batched test");
-*/
- // Close the container when finished
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_queryMultipleFolder.js b/toolkit/components/places/tests/queries/test_queryMultipleFolder.js
deleted file mode 100644
index 694728a43..000000000
--- a/toolkit/components/places/tests/queries/test_queryMultipleFolder.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_queryMultipleFolders() {
- // adding bookmarks in the folders
- let folderIds = [];
- let bookmarkIds = [];
- for (let i = 0; i < 3; ++i) {
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: `Folder${i}`
- });
- folderIds.push(yield PlacesUtils.promiseItemId(folder.guid));
-
- for (let j = 0; j < 7; ++j) {
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: (yield PlacesUtils.promiseItemGuid(folderIds[i])),
- url: `http://Bookmark${i}_${j}.com`,
- title: ""
- });
- bookmarkIds.push(yield PlacesUtils.promiseItemId(bm.guid));
- }
- }
-
- // using queryStringToQueries
- let query = {};
- let options = {};
- let maxResults = 20;
- let queryString = "place:" + folderIds.map((id) => {
- return "folder=" + id;
- }).join('&') + "&sort=5&maxResults=" + maxResults;
- PlacesUtils.history.queryStringToQueries(queryString, query, {}, options);
- let rootNode = PlacesUtils.history.executeQuery(query.value[0], options.value).root;
- rootNode.containerOpen = true;
- let resultLength = rootNode.childCount;
- Assert.equal(resultLength, maxResults);
- for (let i = 0; i < resultLength; ++i) {
- let node = rootNode.getChild(i);
- Assert.equal(bookmarkIds[i], node.itemId, node.uri);
- }
- rootNode.containerOpen = false;
-
- // using getNewQuery and getNewQueryOptions
- query = PlacesUtils.history.getNewQuery();
- options = PlacesUtils.history.getNewQueryOptions();
- query.setFolders(folderIds, folderIds.length);
- options.sortingMode = options.SORT_BY_URI_ASCENDING;
- options.maxResults = maxResults;
- rootNode = PlacesUtils.history.executeQuery(query, options).root;
- rootNode.containerOpen = true;
- resultLength = rootNode.childCount;
- Assert.equal(resultLength, maxResults);
- for (let i = 0; i < resultLength; ++i) {
- let node = rootNode.getChild(i);
- Assert.equal(bookmarkIds[i], node.itemId, node.uri);
- }
- rootNode.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_querySerialization.js b/toolkit/components/places/tests/queries/test_querySerialization.js
deleted file mode 100644
index 24cf8aa9b..000000000
--- a/toolkit/components/places/tests/queries/test_querySerialization.js
+++ /dev/null
@@ -1,797 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Tests Places query serialization. Associated bug is
- * https://bugzilla.mozilla.org/show_bug.cgi?id=370197
- *
- * The simple idea behind this test is to try out different combinations of
- * query switches and ensure that queries are the same before serialization
- * as they are after de-serialization.
- *
- * In the code below, "switch" refers to a query option -- "option" in a broad
- * sense, not nsINavHistoryQueryOptions specifically (which is why we refer to
- * them as switches, not options). Both nsINavHistoryQuery and
- * nsINavHistoryQueryOptions allow you to specify switches that affect query
- * strings. nsINavHistoryQuery instances have attributes hasBeginTime,
- * hasEndTime, hasSearchTerms, and so on. nsINavHistoryQueryOptions instances
- * have attributes sortingMode, resultType, excludeItems, etc.
- *
- * Ideally we would like to test all 2^N subsets of switches, where N is the
- * total number of switches; switches might interact in erroneous or other ways
- * we do not expect. However, since N is large (21 at this time), that's
- * impractical for a single test in a suite.
- *
- * Instead we choose all possible subsets of a certain, smaller size. In fact
- * we begin by choosing CHOOSE_HOW_MANY_SWITCHES_LO and ramp up to
- * CHOOSE_HOW_MANY_SWITCHES_HI.
- *
- * There are two more wrinkles. First, for some switches we'd like to be able to
- * test multiple values. For example, it seems like a good idea to test both an
- * empty string and a non-empty string for switch nsINavHistoryQuery.searchTerms.
- * When switches have more than one value for a test run, we use the Cartesian
- * product of their values to generate all possible combinations of values.
- *
- * Second, we need to also test serialization of multiple nsINavHistoryQuery
- * objects at once. To do this, we remember the previous NUM_MULTIPLE_QUERIES
- * queries we tested individually and then serialize them together. We do this
- * each time we test an individual query. Thus the set of queries we test
- * together loses one query and gains another each time.
- *
- * To summarize, here's how this test works:
- *
- * - For n = CHOOSE_HOW_MANY_SWITCHES_LO to CHOOSE_HOW_MANY_SWITCHES_HI:
- * - From the total set of switches choose all possible subsets of size n.
- * For each of those subsets s:
- * - Collect the test runs of each switch in subset s and take their
- * Cartesian product. For each sequence in the product:
- * - Create nsINavHistoryQuery and nsINavHistoryQueryOptions objects
- * with the chosen switches and test run values.
- * - Serialize the query.
- * - De-serialize and ensure that the de-serialized query objects equal
- * the originals.
- * - For each of the previous NUM_MULTIPLE_QUERIES
- * nsINavHistoryQueryOptions objects o we created:
- * - Serialize the previous NUM_MULTIPLE_QUERIES nsINavHistoryQuery
- * objects together with o.
- * - De-serialize and ensure that the de-serialized query objects
- * equal the originals.
- */
-
-const CHOOSE_HOW_MANY_SWITCHES_LO = 1;
-const CHOOSE_HOW_MANY_SWITCHES_HI = 2;
-
-const NUM_MULTIPLE_QUERIES = 2;
-
-// The switches are represented by objects below, in arrays querySwitches and
-// queryOptionSwitches. Use them to set up test runs.
-//
-// Some switches have special properties (where noted), but all switches must
-// have the following properties:
-//
-// matches: A function that takes two nsINavHistoryQuery objects (in the case
-// of nsINavHistoryQuery switches) or two nsINavHistoryQueryOptions
-// objects (for nsINavHistoryQueryOptions switches) and returns true
-// if the values of the switch in the two objects are equal. This is
-// the foundation of how we determine if two queries are equal.
-// runs: An array of functions. Each function takes an nsINavHistoryQuery
-// object and an nsINavHistoryQueryOptions object. The functions
-// should set the attributes of one of the two objects as appropriate
-// to their switches. This is how switch values are set for each test
-// run.
-//
-// The following properties are optional:
-//
-// desc: An informational string to print out during runs when the switch
-// is chosen. Hopefully helpful if the test fails.
-
-// nsINavHistoryQuery switches
-const querySwitches = [
- // hasBeginTime
- {
- // flag and subswitches are used by the flagSwitchMatches function. Several
- // of the nsINavHistoryQuery switches (like this one) are really guard flags
- // that indicate if other "subswitches" are enabled.
- flag: "hasBeginTime",
- subswitches: ["beginTime", "beginTimeReference", "absoluteBeginTime"],
- desc: "nsINavHistoryQuery.hasBeginTime",
- matches: flagSwitchMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.beginTime = Date.now() * 1000;
- aQuery.beginTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_EPOCH;
- },
- function (aQuery, aQueryOptions) {
- aQuery.beginTime = Date.now() * 1000;
- aQuery.beginTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_TODAY;
- }
- ]
- },
- // hasEndTime
- {
- flag: "hasEndTime",
- subswitches: ["endTime", "endTimeReference", "absoluteEndTime"],
- desc: "nsINavHistoryQuery.hasEndTime",
- matches: flagSwitchMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.endTime = Date.now() * 1000;
- aQuery.endTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_EPOCH;
- },
- function (aQuery, aQueryOptions) {
- aQuery.endTime = Date.now() * 1000;
- aQuery.endTimeReference = Ci.nsINavHistoryQuery.TIME_RELATIVE_TODAY;
- }
- ]
- },
- // hasSearchTerms
- {
- flag: "hasSearchTerms",
- subswitches: ["searchTerms"],
- desc: "nsINavHistoryQuery.hasSearchTerms",
- matches: flagSwitchMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.searchTerms = "shrimp and white wine";
- },
- function (aQuery, aQueryOptions) {
- aQuery.searchTerms = "";
- }
- ]
- },
- // hasDomain
- {
- flag: "hasDomain",
- subswitches: ["domain", "domainIsHost"],
- desc: "nsINavHistoryQuery.hasDomain",
- matches: flagSwitchMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.domain = "mozilla.com";
- aQuery.domainIsHost = false;
- },
- function (aQuery, aQueryOptions) {
- aQuery.domain = "www.mozilla.com";
- aQuery.domainIsHost = true;
- },
- function (aQuery, aQueryOptions) {
- aQuery.domain = "";
- }
- ]
- },
- // hasUri
- {
- flag: "hasUri",
- subswitches: ["uri"],
- desc: "nsINavHistoryQuery.hasUri",
- matches: flagSwitchMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.uri = uri("http://mozilla.com");
- },
- ]
- },
- // hasAnnotation
- {
- flag: "hasAnnotation",
- subswitches: ["annotation", "annotationIsNot"],
- desc: "nsINavHistoryQuery.hasAnnotation",
- matches: flagSwitchMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.annotation = "bookmarks/toolbarFolder";
- aQuery.annotationIsNot = false;
- },
- function (aQuery, aQueryOptions) {
- aQuery.annotation = "bookmarks/toolbarFolder";
- aQuery.annotationIsNot = true;
- }
- ]
- },
- // minVisits
- {
- // property is used by function simplePropertyMatches.
- property: "minVisits",
- desc: "nsINavHistoryQuery.minVisits",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.minVisits = 0x7fffffff; // 2^31 - 1
- }
- ]
- },
- // maxVisits
- {
- property: "maxVisits",
- desc: "nsINavHistoryQuery.maxVisits",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.maxVisits = 0x7fffffff; // 2^31 - 1
- }
- ]
- },
- // onlyBookmarked
- {
- property: "onlyBookmarked",
- desc: "nsINavHistoryQuery.onlyBookmarked",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.onlyBookmarked = true;
- }
- ]
- },
- // getFolders
- {
- desc: "nsINavHistoryQuery.getFolders",
- matches: function (aQuery1, aQuery2) {
- var q1Folders = aQuery1.getFolders();
- var q2Folders = aQuery2.getFolders();
- if (q1Folders.length !== q2Folders.length)
- return false;
- for (let i = 0; i < q1Folders.length; i++) {
- if (q2Folders.indexOf(q1Folders[i]) < 0)
- return false;
- }
- for (let i = 0; i < q2Folders.length; i++) {
- if (q1Folders.indexOf(q2Folders[i]) < 0)
- return false;
- }
- return true;
- },
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.setFolders([], 0);
- },
- function (aQuery, aQueryOptions) {
- aQuery.setFolders([PlacesUtils.placesRootId], 1);
- },
- function (aQuery, aQueryOptions) {
- aQuery.setFolders([PlacesUtils.placesRootId, PlacesUtils.tagsFolderId], 2);
- }
- ]
- },
- // tags
- {
- desc: "nsINavHistoryQuery.getTags",
- matches: function (aQuery1, aQuery2) {
- if (aQuery1.tagsAreNot !== aQuery2.tagsAreNot)
- return false;
- var q1Tags = aQuery1.tags;
- var q2Tags = aQuery2.tags;
- if (q1Tags.length !== q2Tags.length)
- return false;
- for (let i = 0; i < q1Tags.length; i++) {
- if (q2Tags.indexOf(q1Tags[i]) < 0)
- return false;
- }
- for (let i = 0; i < q2Tags.length; i++) {
- if (q1Tags.indexOf(q2Tags[i]) < 0)
- return false;
- }
- return true;
- },
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.tags = [];
- },
- function (aQuery, aQueryOptions) {
- aQuery.tags = [""];
- },
- function (aQuery, aQueryOptions) {
- aQuery.tags = [
- "foo",
- "七難",
- "",
- "いっぱいおっぱい",
- "Abracadabra",
- "123",
- "Here's a pretty long tag name with some = signs and 1 2 3s and spaces oh jeez will it work I hope so!",
- "アスキーでございません",
- "あいうえお",
- ];
- },
- function (aQuery, aQueryOptions) {
- aQuery.tags = [
- "foo",
- "七難",
- "",
- "いっぱいおっぱい",
- "Abracadabra",
- "123",
- "Here's a pretty long tag name with some = signs and 1 2 3s and spaces oh jeez will it work I hope so!",
- "アスキーでございません",
- "あいうえお",
- ];
- aQuery.tagsAreNot = true;
- }
- ]
- },
- // transitions
- {
- desc: "tests nsINavHistoryQuery.getTransitions",
- matches: function (aQuery1, aQuery2) {
- var q1Trans = aQuery1.getTransitions();
- var q2Trans = aQuery2.getTransitions();
- if (q1Trans.length !== q2Trans.length)
- return false;
- for (let i = 0; i < q1Trans.length; i++) {
- if (q2Trans.indexOf(q1Trans[i]) < 0)
- return false;
- }
- for (let i = 0; i < q2Trans.length; i++) {
- if (q1Trans.indexOf(q2Trans[i]) < 0)
- return false;
- }
- return true;
- },
- runs: [
- function (aQuery, aQueryOptions) {
- aQuery.setTransitions([], 0);
- },
- function (aQuery, aQueryOptions) {
- aQuery.setTransitions([Ci.nsINavHistoryService.TRANSITION_DOWNLOAD],
- 1);
- },
- function (aQuery, aQueryOptions) {
- aQuery.setTransitions([Ci.nsINavHistoryService.TRANSITION_TYPED,
- Ci.nsINavHistoryService.TRANSITION_BOOKMARK], 2);
- }
- ]
- },
-];
-
-// nsINavHistoryQueryOptions switches
-const queryOptionSwitches = [
- // sortingMode
- {
- desc: "nsINavHistoryQueryOptions.sortingMode",
- matches: function (aOptions1, aOptions2) {
- if (aOptions1.sortingMode === aOptions2.sortingMode) {
- switch (aOptions1.sortingMode) {
- case aOptions1.SORT_BY_ANNOTATION_ASCENDING:
- case aOptions1.SORT_BY_ANNOTATION_DESCENDING:
- return aOptions1.sortingAnnotation === aOptions2.sortingAnnotation;
- }
- return true;
- }
- return false;
- },
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.sortingMode = aQueryOptions.SORT_BY_DATE_ASCENDING;
- },
- function (aQuery, aQueryOptions) {
- aQueryOptions.sortingMode = aQueryOptions.SORT_BY_ANNOTATION_ASCENDING;
- aQueryOptions.sortingAnnotation = "bookmarks/toolbarFolder";
- }
- ]
- },
- // resultType
- {
- // property is used by function simplePropertyMatches.
- property: "resultType",
- desc: "nsINavHistoryQueryOptions.resultType",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.resultType = aQueryOptions.RESULTS_AS_URI;
- },
- function (aQuery, aQueryOptions) {
- aQueryOptions.resultType = aQueryOptions.RESULTS_AS_FULL_VISIT;
- }
- ]
- },
- // excludeItems
- {
- property: "excludeItems",
- desc: "nsINavHistoryQueryOptions.excludeItems",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.excludeItems = true;
- }
- ]
- },
- // excludeQueries
- {
- property: "excludeQueries",
- desc: "nsINavHistoryQueryOptions.excludeQueries",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.excludeQueries = true;
- }
- ]
- },
- // expandQueries
- {
- property: "expandQueries",
- desc: "nsINavHistoryQueryOptions.expandQueries",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.expandQueries = true;
- }
- ]
- },
- // includeHidden
- {
- property: "includeHidden",
- desc: "nsINavHistoryQueryOptions.includeHidden",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.includeHidden = true;
- }
- ]
- },
- // maxResults
- {
- property: "maxResults",
- desc: "nsINavHistoryQueryOptions.maxResults",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.maxResults = 0xffffffff; // 2^32 - 1
- }
- ]
- },
- // queryType
- {
- property: "queryType",
- desc: "nsINavHistoryQueryOptions.queryType",
- matches: simplePropertyMatches,
- runs: [
- function (aQuery, aQueryOptions) {
- aQueryOptions.queryType = aQueryOptions.QUERY_TYPE_HISTORY;
- },
- function (aQuery, aQueryOptions) {
- aQueryOptions.queryType = aQueryOptions.QUERY_TYPE_UNIFIED;
- }
- ]
- },
-];
-
-/**
- * Enumerates all the sequences of the cartesian product of the arrays contained
- * in aSequences. Examples:
- *
- * cartProd([[1, 2, 3], ["a", "b"]], callback);
- * // callback is called 3 * 2 = 6 times with the following arrays:
- * // [1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]
- *
- * cartProd([["a"], [1, 2, 3], ["X", "Y"]], callback);
- * // callback is called 1 * 3 * 2 = 6 times with the following arrays:
- * // ["a", 1, "X"], ["a", 1, "Y"], ["a", 2, "X"], ["a", 2, "Y"],
- * // ["a", 3, "X"], ["a", 3, "Y"]
- *
- * cartProd([[1], [2], [3], [4]], callback);
- * // callback is called 1 * 1 * 1 * 1 = 1 time with the following array:
- * // [1, 2, 3, 4]
- *
- * cartProd([], callback);
- * // callback is 0 times
- *
- * cartProd([[1, 2, 3, 4]], callback);
- * // callback is called 4 times with the following arrays:
- * // [1], [2], [3], [4]
- *
- * @param aSequences
- * an array that contains an arbitrary number of arrays
- * @param aCallback
- * a function that is passed each sequence of the product as it's
- * computed
- * @return the total number of sequences in the product
- */
-function cartProd(aSequences, aCallback)
-{
- if (aSequences.length === 0)
- return 0;
-
- // For each sequence in aSequences, we maintain a pointer (an array index,
- // really) to the element we're currently enumerating in that sequence
- var seqEltPtrs = aSequences.map(i => 0);
-
- var numProds = 0;
- var done = false;
- while (!done) {
- numProds++;
-
- // prod = sequence in product we're currently enumerating
- let prod = [];
- for (let i = 0; i < aSequences.length; i++) {
- prod.push(aSequences[i][seqEltPtrs[i]]);
- }
- aCallback(prod);
-
- // The next sequence in the product differs from the current one by just a
- // single element. Determine which element that is. We advance the
- // "rightmost" element pointer to the "right" by one. If we move past the
- // end of that pointer's sequence, reset the pointer to the first element
- // in its sequence and then try the sequence to the "left", and so on.
-
- // seqPtr = index of rightmost input sequence whose element pointer is not
- // past the end of the sequence
- let seqPtr = aSequences.length - 1;
- while (!done) {
- // Advance the rightmost element pointer.
- seqEltPtrs[seqPtr]++;
-
- // The rightmost element pointer is past the end of its sequence.
- if (seqEltPtrs[seqPtr] >= aSequences[seqPtr].length) {
- seqEltPtrs[seqPtr] = 0;
- seqPtr--;
-
- // All element pointers are past the ends of their sequences.
- if (seqPtr < 0)
- done = true;
- }
- else break;
- }
- }
- return numProds;
-}
-
-/**
- * Enumerates all the subsets in aSet of size aHowMany. There are
- * C(aSet.length, aHowMany) such subsets. aCallback will be passed each subset
- * as it is generated. Note that aSet and the subsets enumerated are -- even
- * though they're arrays -- not sequences; the ordering of their elements is not
- * important. Example:
- *
- * choose([1, 2, 3, 4], 2, callback);
- * // callback is called C(4, 2) = 6 times with the following sets (arrays):
- * // [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]
- *
- * @param aSet
- * an array from which to choose elements, aSet.length > 0
- * @param aHowMany
- * the number of elements to choose, > 0 and <= aSet.length
- * @return the total number of sets chosen
- */
-function choose(aSet, aHowMany, aCallback)
-{
- // ptrs = indices of the elements in aSet we're currently choosing
- var ptrs = [];
- for (let i = 0; i < aHowMany; i++) {
- ptrs.push(i);
- }
-
- var numFound = 0;
- var done = false;
- while (!done) {
- numFound++;
- aCallback(ptrs.map(p => aSet[p]));
-
- // The next subset to be chosen differs from the current one by just a
- // single element. Determine which element that is. Advance the "rightmost"
- // pointer to the "right" by one. If we move past the end of set, move the
- // next non-adjacent rightmost pointer to the right by one, and reset all
- // succeeding pointers so that they're adjacent to it. When all pointers
- // are clustered all the way to the right, we're done.
-
- // Advance the rightmost pointer.
- ptrs[ptrs.length - 1]++;
-
- // The rightmost pointer has gone past the end of set.
- if (ptrs[ptrs.length - 1] >= aSet.length) {
- // Find the next rightmost pointer that is not adjacent to the current one.
- let si = aSet.length - 2; // aSet index
- let pi = ptrs.length - 2; // ptrs index
- while (pi >= 0 && ptrs[pi] === si) {
- pi--;
- si--;
- }
-
- // All pointers are adjacent and clustered all the way to the right.
- if (pi < 0)
- done = true;
- else {
- // pi = index of rightmost pointer with a gap between it and its
- // succeeding pointer. Move it right and reset all succeeding pointers
- // so that they're adjacent to it.
- ptrs[pi]++;
- for (let i = 0; i < ptrs.length - pi - 1; i++) {
- ptrs[i + pi + 1] = ptrs[pi] + i + 1;
- }
- }
- }
- }
- return numFound;
-}
-
-/**
- * Convenience function for nsINavHistoryQuery switches that act as flags. This
- * is attached to switch objects. See querySwitches array above.
- *
- * @param aQuery1
- * an nsINavHistoryQuery object
- * @param aQuery2
- * another nsINavHistoryQuery object
- * @return true if this switch is the same in both aQuery1 and aQuery2
- */
-function flagSwitchMatches(aQuery1, aQuery2)
-{
- if (aQuery1[this.flag] && aQuery2[this.flag]) {
- for (let p in this.subswitches) {
- if (p in aQuery1 && p in aQuery2) {
- if (aQuery1[p] instanceof Ci.nsIURI) {
- if (!aQuery1[p].equals(aQuery2[p]))
- return false;
- }
- else if (aQuery1[p] !== aQuery2[p])
- return false;
- }
- }
- }
- else if (aQuery1[this.flag] || aQuery2[this.flag])
- return false;
-
- return true;
-}
-
-/**
- * Tests if aObj1 and aObj2 are equal. This function is general and may be used
- * for either nsINavHistoryQuery or nsINavHistoryQueryOptions objects. aSwitches
- * determines which set of switches is used for comparison. Pass in either
- * querySwitches or queryOptionSwitches.
- *
- * @param aSwitches
- * determines which set of switches applies to aObj1 and aObj2, either
- * querySwitches or queryOptionSwitches
- * @param aObj1
- * an nsINavHistoryQuery or nsINavHistoryQueryOptions object
- * @param aObj2
- * another nsINavHistoryQuery or nsINavHistoryQueryOptions object
- * @return true if aObj1 and aObj2 are equal
- */
-function queryObjsEqual(aSwitches, aObj1, aObj2)
-{
- for (let i = 0; i < aSwitches.length; i++) {
- if (!aSwitches[i].matches(aObj1, aObj2))
- return false;
- }
- return true;
-}
-
-/**
- * This drives the test runs. See the comment at the top of this file.
- *
- * @param aHowManyLo
- * the size of the switch subsets to start with
- * @param aHowManyHi
- * the size of the switch subsets to end with (inclusive)
- */
-function runQuerySequences(aHowManyLo, aHowManyHi)
-{
- var allSwitches = querySwitches.concat(queryOptionSwitches);
- var prevQueries = [];
- var prevOpts = [];
-
- // Choose aHowManyLo switches up to aHowManyHi switches.
- for (let howMany = aHowManyLo; howMany <= aHowManyHi; howMany++) {
- let numIters = 0;
- print("CHOOSING " + howMany + " SWITCHES");
-
- // Choose all subsets of size howMany from allSwitches.
- choose(allSwitches, howMany, function (chosenSwitches) {
- print(numIters);
- numIters++;
-
- // Collect the runs.
- // runs = [ [runs from switch 1], ..., [runs from switch howMany] ]
- var runs = chosenSwitches.map(function (s) {
- if (s.desc)
- print(" " + s.desc);
- return s.runs;
- });
-
- // cartProd(runs) => [
- // [switch 1 run 1, switch 2 run 1, ..., switch howMany run 1 ],
- // ...,
- // [switch 1 run 1, switch 2 run 1, ..., switch howMany run N ],
- // ..., ...,
- // [switch 1 run N, switch 2 run N, ..., switch howMany run 1 ],
- // ...,
- // [switch 1 run N, switch 2 run N, ..., switch howMany run N ],
- // ]
- cartProd(runs, function (runSet) {
- // Create a new query, apply the switches in runSet, and test it.
- var query = PlacesUtils.history.getNewQuery();
- var opts = PlacesUtils.history.getNewQueryOptions();
- for (let i = 0; i < runSet.length; i++) {
- runSet[i](query, opts);
- }
- serializeDeserialize([query], opts);
-
- // Test the previous NUM_MULTIPLE_QUERIES queries together.
- prevQueries.push(query);
- prevOpts.push(opts);
- if (prevQueries.length >= NUM_MULTIPLE_QUERIES) {
- // We can serialize multiple nsINavHistoryQuery objects together but
- // only one nsINavHistoryQueryOptions object with them. So, test each
- // of the previous NUM_MULTIPLE_QUERIES nsINavHistoryQueryOptions.
- for (let i = 0; i < prevOpts.length; i++) {
- serializeDeserialize(prevQueries, prevOpts[i]);
- }
- prevQueries.shift();
- prevOpts.shift();
- }
- });
- });
- }
- print("\n");
-}
-
-/**
- * Serializes the nsINavHistoryQuery objects in aQueryArr and the
- * nsINavHistoryQueryOptions object aQueryOptions, de-serializes the
- * serialization, and ensures (using do_check_* functions) that the
- * de-serialized objects equal the originals.
- *
- * @param aQueryArr
- * an array containing nsINavHistoryQuery objects
- * @param aQueryOptions
- * an nsINavHistoryQueryOptions object
- */
-function serializeDeserialize(aQueryArr, aQueryOptions)
-{
- var queryStr = PlacesUtils.history.queriesToQueryString(aQueryArr,
- aQueryArr.length,
- aQueryOptions);
- print(" " + queryStr);
- var queryArr2 = {};
- var opts2 = {};
- PlacesUtils.history.queryStringToQueries(queryStr, queryArr2, {}, opts2);
- queryArr2 = queryArr2.value;
- opts2 = opts2.value;
-
- // The two sets of queries cannot be the same if their lengths differ.
- do_check_eq(aQueryArr.length, queryArr2.length);
-
- // Although the query serialization code as it is written now practically
- // ensures that queries appear in the query string in the same order they
- // appear in both the array to be serialized and the array resulting from
- // de-serialization, the interface does not guarantee any ordering. So, for
- // each query in aQueryArr, find its equivalent in queryArr2 and delete it
- // from queryArr2. If queryArr2 is empty after looping through aQueryArr,
- // the two sets of queries are equal.
- for (let i = 0; i < aQueryArr.length; i++) {
- let j = 0;
- for (; j < queryArr2.length; j++) {
- if (queryObjsEqual(querySwitches, aQueryArr[i], queryArr2[j]))
- break;
- }
- if (j < queryArr2.length)
- queryArr2.splice(j, 1);
- }
- do_check_eq(queryArr2.length, 0);
-
- // Finally check the query options objects.
- do_check_true(queryObjsEqual(queryOptionSwitches, aQueryOptions, opts2));
-}
-
-/**
- * Convenience function for switches that have simple values. This is attached
- * to switch objects. See querySwitches and queryOptionSwitches arrays above.
- *
- * @param aObj1
- * an nsINavHistoryQuery or nsINavHistoryQueryOptions object
- * @param aObj2
- * another nsINavHistoryQuery or nsINavHistoryQueryOptions object
- * @return true if this switch is the same in both aObj1 and aObj2
- */
-function simplePropertyMatches(aObj1, aObj2)
-{
- return aObj1[this.property] === aObj2[this.property];
-}
-
-function run_test()
-{
- runQuerySequences(CHOOSE_HOW_MANY_SWITCHES_LO, CHOOSE_HOW_MANY_SWITCHES_HI);
-}
diff --git a/toolkit/components/places/tests/queries/test_redirects.js b/toolkit/components/places/tests/queries/test_redirects.js
deleted file mode 100644
index 1be5a626f..000000000
--- a/toolkit/components/places/tests/queries/test_redirects.js
+++ /dev/null
@@ -1,311 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Array of visits we will add to the database, will be populated later
-// in the test.
-var visits = [];
-
-/**
- * Takes a sequence of query options, and compare query results obtained through
- * them with a custom filtered array of visits, based on the values we are
- * expecting from the query.
- *
- * @param aSequence
- * an array that contains query options in the form:
- * [includeHidden, maxResults, sortingMode]
- */
-function check_results_callback(aSequence) {
- // Sanity check: we should receive 3 parameters.
- do_check_eq(aSequence.length, 3);
- let includeHidden = aSequence[0];
- let maxResults = aSequence[1];
- let sortingMode = aSequence[2];
- print("\nTESTING: includeHidden(" + includeHidden + ")," +
- " maxResults(" + maxResults + ")," +
- " sortingMode(" + sortingMode + ").");
-
- function isHidden(aVisit) {
- return aVisit.transType == Ci.nsINavHistoryService.TRANSITION_FRAMED_LINK ||
- aVisit.isRedirect;
- }
-
- // Build expectedData array.
- let expectedData = visits.filter(function (aVisit, aIndex, aArray) {
- // Embed visits never appear in results.
- if (aVisit.transType == Ci.nsINavHistoryService.TRANSITION_EMBED)
- return false;
-
- if (!includeHidden && isHidden(aVisit)) {
- // If the page has any non-hidden visit, then it's visible.
- if (visits.filter(function (refVisit) {
- return refVisit.uri == aVisit.uri && !isHidden(refVisit);
- }).length == 0)
- return false;
- }
-
- return true;
- });
-
- // Remove duplicates, since queries are RESULTS_AS_URI (unique pages).
- let seen = [];
- expectedData = expectedData.filter(function (aData) {
- if (seen.includes(aData.uri)) {
- return false;
- }
- seen.push(aData.uri);
- return true;
- });
-
- // Sort expectedData.
- function getFirstIndexFor(aEntry) {
- for (let i = 0; i < visits.length; i++) {
- if (visits[i].uri == aEntry.uri)
- return i;
- }
- return undefined;
- }
- function comparator(a, b) {
- if (sortingMode == Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING) {
- return b.lastVisit - a.lastVisit;
- }
- if (sortingMode == Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING) {
- return b.visitCount - a.visitCount;
- }
- return getFirstIndexFor(a) - getFirstIndexFor(b);
- }
- expectedData.sort(comparator);
-
- // Crop results to maxResults if it's defined.
- if (maxResults) {
- expectedData = expectedData.slice(0, maxResults);
- }
-
- // Create a new query with required options.
- let query = PlacesUtils.history.getNewQuery();
- let options = PlacesUtils.history.getNewQueryOptions();
- options.includeHidden = includeHidden;
- options.sortingMode = sortingMode;
- if (maxResults)
- options.maxResults = maxResults;
-
- // Compare resultset with expectedData.
- let result = PlacesUtils.history.executeQuery(query, options);
- let root = result.root;
- root.containerOpen = true;
- compareArrayToResult(expectedData, root);
- root.containerOpen = false;
-}
-
-/**
- * Enumerates all the sequences of the cartesian product of the arrays contained
- * in aSequences. Examples:
- *
- * cartProd([[1, 2, 3], ["a", "b"]], callback);
- * // callback is called 3 * 2 = 6 times with the following arrays:
- * // [1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]
- *
- * cartProd([["a"], [1, 2, 3], ["X", "Y"]], callback);
- * // callback is called 1 * 3 * 2 = 6 times with the following arrays:
- * // ["a", 1, "X"], ["a", 1, "Y"], ["a", 2, "X"], ["a", 2, "Y"],
- * // ["a", 3, "X"], ["a", 3, "Y"]
- *
- * cartProd([[1], [2], [3], [4]], callback);
- * // callback is called 1 * 1 * 1 * 1 = 1 time with the following array:
- * // [1, 2, 3, 4]
- *
- * cartProd([], callback);
- * // callback is 0 times
- *
- * cartProd([[1, 2, 3, 4]], callback);
- * // callback is called 4 times with the following arrays:
- * // [1], [2], [3], [4]
- *
- * @param aSequences
- * an array that contains an arbitrary number of arrays
- * @param aCallback
- * a function that is passed each sequence of the product as it's
- * computed
- * @return the total number of sequences in the product
- */
-function cartProd(aSequences, aCallback)
-{
- if (aSequences.length === 0)
- return 0;
-
- // For each sequence in aSequences, we maintain a pointer (an array index,
- // really) to the element we're currently enumerating in that sequence
- let seqEltPtrs = aSequences.map(i => 0);
-
- let numProds = 0;
- let done = false;
- while (!done) {
- numProds++;
-
- // prod = sequence in product we're currently enumerating
- let prod = [];
- for (let i = 0; i < aSequences.length; i++) {
- prod.push(aSequences[i][seqEltPtrs[i]]);
- }
- aCallback(prod);
-
- // The next sequence in the product differs from the current one by just a
- // single element. Determine which element that is. We advance the
- // "rightmost" element pointer to the "right" by one. If we move past the
- // end of that pointer's sequence, reset the pointer to the first element
- // in its sequence and then try the sequence to the "left", and so on.
-
- // seqPtr = index of rightmost input sequence whose element pointer is not
- // past the end of the sequence
- let seqPtr = aSequences.length - 1;
- while (!done) {
- // Advance the rightmost element pointer.
- seqEltPtrs[seqPtr]++;
-
- // The rightmost element pointer is past the end of its sequence.
- if (seqEltPtrs[seqPtr] >= aSequences[seqPtr].length) {
- seqEltPtrs[seqPtr] = 0;
- seqPtr--;
-
- // All element pointers are past the ends of their sequences.
- if (seqPtr < 0)
- done = true;
- }
- else break;
- }
- }
- return numProds;
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-/**
- * Populate the visits array and add visits to the database.
- * We will generate visit-chains like:
- * visit -> redirect_temp -> redirect_perm
- */
-add_task(function* test_add_visits_to_database()
-{
- yield PlacesUtils.bookmarks.eraseEverything();
-
- // We don't really bother on this, but we need a time to add visits.
- let timeInMicroseconds = Date.now() * 1000;
- let visitCount = 1;
-
- // Array of all possible transition types we could be redirected from.
- let t = [
- Ci.nsINavHistoryService.TRANSITION_LINK,
- Ci.nsINavHistoryService.TRANSITION_TYPED,
- Ci.nsINavHistoryService.TRANSITION_BOOKMARK,
- // Embed visits are not added to the database and we don't want redirects
- // to them, thus just avoid addition.
- // Ci.nsINavHistoryService.TRANSITION_EMBED,
- Ci.nsINavHistoryService.TRANSITION_FRAMED_LINK,
- // Would make hard sorting by visit date because last_visit_date is actually
- // calculated excluding download transitions, but the query includes
- // downloads.
- // TODO: Bug 488966 could fix this behavior.
- //Ci.nsINavHistoryService.TRANSITION_DOWNLOAD,
- ];
-
- function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds - 1000;
- return timeInMicroseconds;
- }
-
- // we add a visit for each of the above transition types.
- t.forEach(transition => visits.push(
- { isVisit: true,
- transType: transition,
- uri: "http://" + transition + ".example.com/",
- title: transition + "-example",
- isRedirect: true,
- lastVisit: newTimeInMicroseconds(),
- visitCount: (transition == Ci.nsINavHistoryService.TRANSITION_EMBED ||
- transition == Ci.nsINavHistoryService.TRANSITION_FRAMED_LINK) ? 0 : visitCount++,
- isInQuery: true }));
-
- // Add a REDIRECT_TEMPORARY layer of visits for each of the above visits.
- t.forEach(transition => visits.push(
- { isVisit: true,
- transType: Ci.nsINavHistoryService.TRANSITION_REDIRECT_TEMPORARY,
- uri: "http://" + transition + ".redirect.temp.example.com/",
- title: transition + "-redirect-temp-example",
- lastVisit: newTimeInMicroseconds(),
- isRedirect: true,
- referrer: "http://" + transition + ".example.com/",
- visitCount: visitCount++,
- isInQuery: true }));
-
- // Add a REDIRECT_PERMANENT layer of visits for each of the above redirects.
- t.forEach(transition => visits.push(
- { isVisit: true,
- transType: Ci.nsINavHistoryService.TRANSITION_REDIRECT_PERMANENT,
- uri: "http://" + transition + ".redirect.perm.example.com/",
- title: transition + "-redirect-perm-example",
- lastVisit: newTimeInMicroseconds(),
- isRedirect: true,
- referrer: "http://" + transition + ".redirect.temp.example.com/",
- visitCount: visitCount++,
- isInQuery: true }));
-
- // Add a REDIRECT_PERMANENT layer of visits that loop to the first visit.
- // These entries should not change visitCount or lastVisit, otherwise
- // guessing an order would be a nightmare.
- function getLastValue(aURI, aProperty) {
- for (let i = 0; i < visits.length; i++) {
- if (visits[i].uri == aURI) {
- return visits[i][aProperty];
- }
- }
- do_throw("Unknown uri.");
- return null;
- }
- t.forEach(transition => visits.push(
- { isVisit: true,
- transType: Ci.nsINavHistoryService.TRANSITION_REDIRECT_PERMANENT,
- uri: "http://" + transition + ".example.com/",
- title: getLastValue("http://" + transition + ".example.com/", "title"),
- lastVisit: getLastValue("http://" + transition + ".example.com/", "lastVisit"),
- isRedirect: true,
- referrer: "http://" + transition + ".redirect.perm.example.com/",
- visitCount: getLastValue("http://" + transition + ".example.com/", "visitCount"),
- isInQuery: true }));
-
- // Add an unvisited bookmark in the database, it should never appear.
- visits.push({ isBookmark: true,
- uri: "http://unvisited.bookmark.com/",
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "Unvisited Bookmark",
- isInQuery: false });
-
- // Put visits in the database.
- yield task_populateDB(visits);
-});
-
-add_task(function* test_redirects()
-{
- // Frecency and hidden are updated asynchronously, wait for them.
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- // This array will be used by cartProd to generate a matrix of all possible
- // combinations.
- let includeHidden_options = [true, false];
- let maxResults_options = [5, 10, 20, null];
- // These sortingMode are choosen to toggle using special queries for history
- // menu and most visited smart bookmark.
- let sorting_options = [Ci.nsINavHistoryQueryOptions.SORT_BY_NONE,
- Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING,
- Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING];
- // Will execute check_results_callback() for each generated combination.
- cartProd([includeHidden_options, maxResults_options, sorting_options],
- check_results_callback);
-
- yield PlacesUtils.bookmarks.eraseEverything();
-
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/queries/test_results-as-tag-contents-query.js b/toolkit/components/places/tests/queries/test_results-as-tag-contents-query.js
deleted file mode 100644
index f1cbfd4d8..000000000
--- a/toolkit/components/places/tests/queries/test_results-as-tag-contents-query.js
+++ /dev/null
@@ -1,127 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var testData = [
- { isInQuery: true,
- isDetails: true,
- title: "bmoz",
- uri: "http://foo.com/",
- isBookmark: true,
- isTag: true,
- tagArray: ["bugzilla"] },
-
- { isInQuery: true,
- isDetails: true,
- title: "C Moz",
- uri: "http://foo.com/changeme1.html",
- isBookmark: true,
- isTag: true,
- tagArray: ["moz", "bugzilla"] },
-
- { isInQuery: false,
- isDetails: true,
- title: "amo",
- uri: "http://foo2.com/",
- isBookmark: true,
- isTag: true,
- tagArray: ["moz"] },
-
- { isInQuery: false,
- isDetails: true,
- title: "amo",
- uri: "http://foo.com/changeme2.html",
- isBookmark: true },
-];
-
-function getIdForTag(aTagName) {
- var id = -1;
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.tagsFolderId], 1);
- var options = PlacesUtils.history.getNewQueryOptions();
- var root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- var cc = root.childCount;
- do_check_eq(root.childCount, 2);
- for (let i = 0; i < cc; i++) {
- let node = root.getChild(i);
- if (node.title == aTagName) {
- id = node.itemId;
- break;
- }
- }
- root.containerOpen = false;
- return id;
-}
-
- /**
- * This test will test Queries that use relative search terms and URI options
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_results_as_tag_contents_query()
-{
- yield task_populateDB(testData);
-
- // Get tag id.
- let tagId = getIdForTag("bugzilla");
- do_check_true(tagId > 0);
-
- var options = PlacesUtils.history.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_TAG_CONTENTS;
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([tagId], 1);
-
- var root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- displayResultSet(root);
- // Cannot use compare array to results, since results ordering is hardcoded
- // and depending on lastModified (that could have VM timers issues).
- testData.forEach(function(aEntry) {
- if (aEntry.isInResult)
- do_check_true(isInResult({uri: "http://foo.com/added.html"}, root));
- });
-
- // If that passes, check liveupdate
- // Add to the query set
- var change1 = { isVisit: true,
- isDetails: true,
- uri: "http://foo.com/added.html",
- title: "mozadded",
- isBookmark: true,
- isTag: true,
- tagArray: ["moz", "bugzilla"] };
- do_print("Adding item to query");
- yield task_populateDB([change1]);
- do_print("These results should have been LIVE UPDATED with the new addition");
- displayResultSet(root);
- do_check_true(isInResult(change1, root));
-
- // Add one by adding a tag, remove one by removing search term.
- do_print("Updating items");
- var change2 = [{ isDetails: true,
- uri: "http://foo3.com/",
- title: "foo"},
- { isDetails: true,
- uri: "http://foo.com/changeme2.html",
- title: "zydeco",
- isBookmark:true,
- isTag: true,
- tagArray: ["bugzilla", "moz"] }];
- yield task_populateDB(change2);
- do_check_false(isInResult({uri: "http://fooz.com/"}, root));
- do_check_true(isInResult({uri: "http://foo.com/changeme2.html"}, root));
-
- // Test removing a tag updates us.
- do_print("Deleting item");
- PlacesUtils.tagging.untagURI(uri("http://foo.com/changeme2.html"), ["bugzilla"]);
- do_check_false(isInResult({uri: "http://foo.com/changeme2.html"}, root));
-
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_results-as-visit.js b/toolkit/components/places/tests/queries/test_results-as-visit.js
deleted file mode 100644
index d0f270bd2..000000000
--- a/toolkit/components/places/tests/queries/test_results-as-visit.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-var testData = [];
-var timeInMicroseconds = PlacesUtils.toPRTime(Date.now() - 10000);
-
-function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds + 1000;
- return timeInMicroseconds;
-}
-
-function createTestData() {
- function generateVisits(aPage) {
- for (var i = 0; i < aPage.visitCount; i++) {
- testData.push({ isInQuery: aPage.inQuery,
- isVisit: true,
- title: aPage.title,
- uri: aPage.uri,
- lastVisit: newTimeInMicroseconds(),
- isTag: aPage.tags && aPage.tags.length > 0,
- tagArray: aPage.tags });
- }
- }
-
- var pages = [
- { uri: "http://foo.com/", title: "amo", tags: ["moz"], visitCount: 3, inQuery: true },
- { uri: "http://moilla.com/", title: "bMoz", tags: ["bugzilla"], visitCount: 5, inQuery: true },
- { uri: "http://foo.mail.com/changeme1.html", title: "c Moz", visitCount: 7, inQuery: true },
- { uri: "http://foo.mail.com/changeme2.html", tags: ["moz"], title: "", visitCount: 1, inQuery: false },
- { uri: "http://foo.mail.com/changeme3.html", title: "zydeco", visitCount: 5, inQuery: false },
- ];
- pages.forEach(generateVisits);
-}
-
-/**
- * This test will test Queries that use relative search terms and URI options
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_results_as_visit()
-{
- createTestData();
- yield task_populateDB(testData);
- var query = PlacesUtils.history.getNewQuery();
- query.searchTerms = "moz";
- query.minVisits = 2;
-
- // Options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_VISITCOUNT_ASCENDING;
- options.resultType = options.RESULTS_AS_VISIT;
-
- // Results
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- do_print("Number of items in result set: " + root.childCount);
- for (let i=0; i < root.childCount; ++i) {
- do_print("result: " + root.getChild(i).uri + " Title: " + root.getChild(i).title);
- }
-
- // Check our inital result set
- compareArrayToResult(testData, root);
-
- // If that passes, check liveupdate
- // Add to the query set
- do_print("Adding item to query")
- var tmp = [];
- for (let i=0; i < 2; i++) {
- tmp.push({ isVisit: true,
- uri: "http://foo.com/added.html",
- title: "ab moz" });
- }
- yield task_populateDB(tmp);
- for (let i=0; i < 2; i++)
- do_check_eq(root.getChild(i).title, "ab moz");
-
- // Update an existing URI
- do_print("Updating Item");
- var change2 = [{ isVisit: true,
- title: "moz",
- uri: "http://foo.mail.com/changeme2.html" }];
- yield task_populateDB(change2);
- do_check_true(isInResult(change2, root));
-
- // Update some visits - add one and take one out of query set, and simply
- // change one so that it still applies to the query.
- do_print("Updating More Items");
- var change3 = [{ isVisit: true,
- lastVisit: newTimeInMicroseconds(),
- uri: "http://foo.mail.com/changeme1.html",
- title: "foo"},
- { isVisit: true,
- lastVisit: newTimeInMicroseconds(),
- uri: "http://foo.mail.com/changeme3.html",
- title: "moz",
- isTag: true,
- tagArray: ["foo", "moz"] }];
- yield task_populateDB(change3);
- do_check_false(isInResult({uri: "http://foo.mail.com/changeme1.html"}, root));
- do_check_true(isInResult({uri: "http://foo.mail.com/changeme3.html"}, root));
-
- // And now, delete one
- do_print("Delete item outside of batch");
- var change4 = [{ isVisit: true,
- lastVisit: newTimeInMicroseconds(),
- uri: "http://moilla.com/",
- title: "mo,z" }];
- yield task_populateDB(change4);
- do_check_false(isInResult(change4, root));
-
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_searchTerms_includeHidden.js b/toolkit/components/places/tests/queries/test_searchTerms_includeHidden.js
deleted file mode 100644
index 038367c0b..000000000
--- a/toolkit/components/places/tests/queries/test_searchTerms_includeHidden.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Tests the interaction of includeHidden and searchTerms search options.
-
-var timeInMicroseconds = Date.now() * 1000;
-
-const VISITS = [
- { isVisit: true,
- transType: TRANSITION_TYPED,
- uri: "http://redirect.example.com/",
- title: "example",
- isRedirect: true,
- lastVisit: timeInMicroseconds--
- },
- { isVisit: true,
- transType: TRANSITION_TYPED,
- uri: "http://target.example.com/",
- title: "example",
- lastVisit: timeInMicroseconds--
- }
-];
-
-const HIDDEN_VISITS = [
- { isVisit: true,
- transType: TRANSITION_FRAMED_LINK,
- uri: "http://hidden.example.com/",
- title: "red",
- lastVisit: timeInMicroseconds--
- },
-];
-
-const TEST_DATA = [
- { searchTerms: "example",
- includeHidden: true,
- expectedResults: 2
- },
- { searchTerms: "example",
- includeHidden: false,
- expectedResults: 1
- },
- { searchTerms: "red",
- includeHidden: true,
- expectedResults: 1
- }
-];
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_initalize()
-{
- yield task_populateDB(VISITS);
-});
-
-add_task(function* test_searchTerms_includeHidden()
-{
- for (let data of TEST_DATA) {
- let query = PlacesUtils.history.getNewQuery();
- query.searchTerms = data.searchTerms;
- let options = PlacesUtils.history.getNewQueryOptions();
- options.includeHidden = data.includeHidden;
-
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- let cc = root.childCount;
- // Live update with hidden visits.
- yield task_populateDB(HIDDEN_VISITS);
- let cc_update = root.childCount;
-
- root.containerOpen = false;
-
- do_check_eq(cc, data.expectedResults);
- do_check_eq(cc_update, data.expectedResults + (data.includeHidden ? 1 : 0));
-
- PlacesUtils.bhistory.removePage(uri("http://hidden.example.com/"));
- }
-});
diff --git a/toolkit/components/places/tests/queries/test_searchterms-bookmarklets.js b/toolkit/components/places/tests/queries/test_searchterms-bookmarklets.js
deleted file mode 100644
index 7bd91f057..000000000
--- a/toolkit/components/places/tests/queries/test_searchterms-bookmarklets.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Check that bookmarklets are returned by searches with searchTerms.
-
-var testData = [
- { isInQuery: true
- , isBookmark: true
- , title: "bookmark 1"
- , uri: "http://mozilla.org/script/"
- },
-
- { isInQuery: true
- , isBookmark: true
- , title: "bookmark 2"
- , uri: "javascript:alert('moz');"
- }
-];
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_initalize()
-{
- yield task_populateDB(testData);
-});
-
-add_test(function test_search_by_title()
-{
- let query = PlacesUtils.history.getNewQuery();
- query.searchTerms = "bookmark";
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- compareArrayToResult(testData, root);
- root.containerOpen = false;
-
- run_next_test();
-});
-
-add_test(function test_search_by_schemeToken()
-{
- let query = PlacesUtils.history.getNewQuery();
- query.searchTerms = "script";
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- compareArrayToResult(testData, root);
- root.containerOpen = false;
-
- run_next_test();
-});
-
-add_test(function test_search_by_uriAndTitle()
-{
- let query = PlacesUtils.history.getNewQuery();
- query.searchTerms = "moz";
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- compareArrayToResult(testData, root);
- root.containerOpen = false;
-
- run_next_test();
-});
diff --git a/toolkit/components/places/tests/queries/test_searchterms-domain.js b/toolkit/components/places/tests/queries/test_searchterms-domain.js
deleted file mode 100644
index 4f42e7000..000000000
--- a/toolkit/components/places/tests/queries/test_searchterms-domain.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- // The test data for our database, note that the ordering of the results that
- // will be returned by the query (the isInQuery: true objects) is IMPORTANT.
- // see compareArrayToResult in head_queries.js for more info.
- var testData = [
- // Test ftp protocol - vary the title length, embed search term
- {isInQuery: true, isVisit: true, isDetails: true,
- uri: "ftp://foo.com/ftp", lastVisit: lastweek,
- title: "hugelongconfmozlagurationofwordswithasearchtermsinit whoo-hoo"},
-
- // Test flat domain with annotation, search term in sentence
- {isInQuery: true, isVisit: true, isDetails: true, isPageAnnotation: true,
- uri: "http://foo.com/", annoName: "moz/test", annoVal: "val",
- lastVisit: lastweek, title: "you know, moz is cool"},
-
- // Test subdomain included with isRedirect=true, different transtype
- {isInQuery: true, isVisit: true, isDetails: true, title: "amozzie",
- isRedirect: true, uri: "http://mail.foo.com/redirect", lastVisit: old,
- referrer: "http://myreferrer.com", transType: PlacesUtils.history.TRANSITION_LINK},
-
- // Test subdomain inclued, search term at end
- {isInQuery: true, isVisit: true, isDetails: true,
- uri: "http://mail.foo.com/yiihah", title: "blahmoz", lastVisit: daybefore},
-
- // Test www. style URI is included, with a tag
- {isInQuery: true, isVisit: true, isDetails: true, isTag: true,
- uri: "http://www.foo.com/yiihah", tagArray: ["moz"],
- lastVisit: yesterday, title: "foo"},
-
- // Test https protocol
- {isInQuery: true, isVisit: true, isDetails: true, title: "moz",
- uri: "https://foo.com/", lastVisit: today},
-
- // Begin the invalid queries: wrong search term
- {isInQuery: false, isVisit:true, isDetails: true, title: "m o z",
- uri: "http://foo.com/tooearly.php", lastVisit: today},
-
- // Test bad URI
- {isInQuery: false, isVisit:true, isDetails: true, title: "moz",
- uri: "http://sffoo.com/justwrong.htm", lastVisit: yesterday},
-
- // Test what we do with escaping in titles
- {isInQuery: false, isVisit:true, isDetails: true, title: "m%0o%0z",
- uri: "http://foo.com/changeme1.htm", lastVisit: yesterday},
-
- // Test another invalid title - for updating later
- {isInQuery: false, isVisit:true, isDetails: true, title: "m,oz",
- uri: "http://foo.com/changeme2.htm", lastVisit: yesterday}];
-
-/**
- * This test will test Queries that use relative search terms and domain options
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_searchterms_domain()
-{
- yield task_populateDB(testData);
- var query = PlacesUtils.history.getNewQuery();
- query.searchTerms = "moz";
- query.domain = "foo.com";
- query.domainIsHost = false;
-
- // Options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_ASCENDING;
- options.resultType = options.RESULTS_AS_URI;
-
- // Results
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- do_print("Number of items in result set: " + root.childCount);
- for (var i=0; i < root.childCount; ++i) {
- do_print("result: " + root.getChild(i).uri + " Title: " + root.getChild(i).title);
- }
-
- // Check our inital result set
- compareArrayToResult(testData, root);
-
- // If that passes, check liveupdate
- // Add to the query set
- do_print("Adding item to query");
- var change1 = [{isVisit: true, isDetails: true, uri: "http://foo.com/added.htm",
- title: "moz", transType: PlacesUtils.history.TRANSITION_LINK}];
- yield task_populateDB(change1);
- do_check_true(isInResult(change1, root));
-
- // Update an existing URI
- do_print("Updating Item");
- var change2 = [{isDetails: true, uri: "http://foo.com/changeme1.htm",
- title: "moz" }];
- yield task_populateDB(change2);
- do_check_true(isInResult(change2, root));
-
- // Add one and take one out of query set, and simply change one so that it
- // still applies to the query.
- do_print("Updating More Items");
- var change3 = [{isDetails: true, uri:"http://foo.com/changeme2.htm",
- title: "moz"},
- {isDetails: true, uri: "http://mail.foo.com/yiihah",
- title: "moz now updated"},
- {isDetails: true, uri: "ftp://foo.com/ftp", title: "gone"}];
- yield task_populateDB(change3);
- do_check_true(isInResult({uri: "http://foo.com/changeme2.htm"}, root));
- do_check_true(isInResult({uri: "http://mail.foo.com/yiihah"}, root));
- do_check_false(isInResult({uri: "ftp://foo.com/ftp"}, root));
-
- // And now, delete one
- do_print("Deleting items");
- var change4 = [{isDetails: true, uri: "https://foo.com/",
- title: "mo,z"}];
- yield task_populateDB(change4);
- do_check_false(isInResult(change4, root));
-
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_searchterms-uri.js b/toolkit/components/places/tests/queries/test_searchterms-uri.js
deleted file mode 100644
index af4efe196..000000000
--- a/toolkit/components/places/tests/queries/test_searchterms-uri.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- // The test data for our database, note that the ordering of the results that
- // will be returned by the query (the isInQuery: true objects) is IMPORTANT.
- // see compareArrayToResult in head_queries.js for more info.
- var testData = [
- // Test flat domain with annotation, search term in sentence
- {isInQuery: true, isVisit: true, isDetails: true, isPageAnnotation: true,
- uri: "http://foo.com/", annoName: "moz/test", annoVal: "val",
- lastVisit: lastweek, title: "you know, moz is cool"},
-
- // Test https protocol
- {isInQuery: false, isVisit: true, isDetails: true, title: "moz",
- uri: "https://foo.com/", lastVisit: today},
-
- // Begin the invalid queries: wrong search term
- {isInQuery: false, isVisit:true, isDetails: true, title: "m o z",
- uri: "http://foo.com/wrongsearch.php", lastVisit: today},
-
- // Test subdomain inclued, search term at end
- {isInQuery: false, isVisit: true, isDetails: true,
- uri: "http://mail.foo.com/yiihah", title: "blahmoz", lastVisit: daybefore},
-
- // Test ftp protocol - vary the title length, embed search term
- {isInQuery: false, isVisit: true, isDetails: true,
- uri: "ftp://foo.com/ftp", lastVisit: lastweek,
- title: "hugelongconfmozlagurationofwordswithasearchtermsinit whoo-hoo"},
-
- // Test what we do with escaping in titles
- {isInQuery: false, isVisit:true, isDetails: true, title: "m%0o%0z",
- uri: "http://foo.com/changeme1.htm", lastVisit: yesterday},
-
- // Test another invalid title - for updating later
- {isInQuery: false, isVisit:true, isDetails: true, title: "m,oz",
- uri: "http://foo.com/changeme2.htm", lastVisit: yesterday}];
-
-/**
- * This test will test Queries that use relative search terms and URI options
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_searchterms_uri()
-{
- yield task_populateDB(testData);
- var query = PlacesUtils.history.getNewQuery();
- query.searchTerms = "moz";
- query.uri = uri("http://foo.com");
-
- // Options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_ASCENDING;
- options.resultType = options.RESULTS_AS_URI;
-
- // Results
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- do_print("Number of items in result set: " + root.childCount);
- for (var i=0; i < root.childCount; ++i) {
- do_print("result: " + root.getChild(i).uri + " Title: " + root.getChild(i).title);
- }
-
- // Check our inital result set
- compareArrayToResult(testData, root);
-
- // live update.
- do_print("change title");
- var change1 = [{isDetails: true, uri:"http://foo.com/",
- title: "mo"}, ];
- yield task_populateDB(change1);
-
- do_check_false(isInResult({uri: "http://foo.com/"}, root));
- var change2 = [{isDetails: true, uri:"http://foo.com/",
- title: "moz"}, ];
- yield task_populateDB(change2);
- do_check_true(isInResult({uri: "http://foo.com/"}, root));
-
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/queries/test_sort-date-site-grouping.js b/toolkit/components/places/tests/queries/test_sort-date-site-grouping.js
deleted file mode 100644
index 7ca50e6de..000000000
--- a/toolkit/components/places/tests/queries/test_sort-date-site-grouping.js
+++ /dev/null
@@ -1,225 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* ***** BEGIN LICENSE BLOCK *****
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
- * ***** END LICENSE BLOCK ***** */
-
-// This test ensures that the date and site type of |place:| query maintains
-// its quantifications correctly. Namely, it ensures that the date part of the
-// query is not lost when the domain queries are made.
-
-// We specifically craft these entries so that if a by Date and Site sorting is
-// applied, we find one domain in the today range, and two domains in the older
-// than six months range.
-// The correspondence between item in |testData| and date range is stored in
-// leveledTestData.
-var testData = [
- {
- isVisit: true,
- uri: "file:///directory/1",
- lastVisit: today,
- title: "test visit",
- isInQuery: true
- },
- {
- isVisit: true,
- uri: "http://example.com/1",
- lastVisit: today,
- title: "test visit",
- isInQuery: true
- },
- {
- isVisit: true,
- uri: "http://example.com/2",
- lastVisit: today,
- title: "test visit",
- isInQuery: true
- },
- {
- isVisit: true,
- uri: "file:///directory/2",
- lastVisit: olderthansixmonths,
- title: "test visit",
- isInQuery: true
- },
- {
- isVisit: true,
- uri: "http://example.com/3",
- lastVisit: olderthansixmonths,
- title: "test visit",
- isInQuery: true
- },
- {
- isVisit: true,
- uri: "http://example.com/4",
- lastVisit: olderthansixmonths,
- title: "test visit",
- isInQuery: true
- },
- {
- isVisit: true,
- uri: "http://example.net/1",
- lastVisit: olderthansixmonths + 1000,
- title: "test visit",
- isInQuery: true
- }
-];
-var domainsInRange = [2, 3];
-var leveledTestData = [// Today
- [[0], // Today, local files
- [1, 2]], // Today, example.com
- // Older than six months
- [[3], // Older than six months, local files
- [4, 5], // Older than six months, example.com
- [6] // Older than six months, example.net
- ]];
-
-// This test data is meant for live updating. The |levels| property indicates
-// date range index and then domain index.
-var testDataAddedLater = [
- {
- isVisit: true,
- uri: "http://example.com/5",
- lastVisit: olderthansixmonths,
- title: "test visit",
- isInQuery: true,
- levels: [1, 1]
- },
- {
- isVisit: true,
- uri: "http://example.com/6",
- lastVisit: olderthansixmonths,
- title: "test visit",
- isInQuery: true,
- levels: [1, 1]
- },
- {
- isVisit: true,
- uri: "http://example.com/7",
- lastVisit: today,
- title: "test visit",
- isInQuery: true,
- levels: [0, 1]
- },
- {
- isVisit: true,
- uri: "file:///directory/3",
- lastVisit: today,
- title: "test visit",
- isInQuery: true,
- levels: [0, 0]
- }
-];
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_sort_date_site_grouping()
-{
- yield task_populateDB(testData);
-
- // On Linux, the (local files) folder is shown after sites unlike Mac/Windows.
- // Thus, we avoid running this test on Linux but this should be re-enabled
- // after bug 624024 is resolved.
- let isLinux = ("@mozilla.org/gnome-gconf-service;1" in Components.classes);
- if (isLinux)
- return;
-
- // In this test, there are three levels of results:
- // 1st: Date queries. e.g., today, last week, or older than 6 months.
- // 2nd: Domain queries restricted to a date. e.g. mozilla.com today.
- // 3rd: Actual visits. e.g. mozilla.com/index.html today.
- //
- // We store all the third level result roots so that we can easily close all
- // containers and test live updating into specific results.
- let roots = [];
-
- let query = PlacesUtils.history.getNewQuery();
- let options = PlacesUtils.history.getNewQueryOptions();
- options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY;
-
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- // This corresponds to the number of date ranges.
- do_check_eq(root.childCount, leveledTestData.length);
-
- // We pass off to |checkFirstLevel| to check the first level of results.
- for (let index = 0; index < leveledTestData.length; index++) {
- let node = root.getChild(index);
- checkFirstLevel(index, node, roots);
- }
-
- // Test live updating.
- for (let visit of testDataAddedLater) {
- yield task_populateDB([visit]);
- let oldLength = testData.length;
- let i = visit.levels[0];
- let j = visit.levels[1];
- testData.push(visit);
- leveledTestData[i][j].push(oldLength);
- compareArrayToResult(leveledTestData[i][j].
- map(x => testData[x]), roots[i][j]);
- }
-
- for (let i = 0; i < roots.length; i++) {
- for (let j = 0; j < roots[i].length; j++)
- roots[i][j].containerOpen = false;
- }
-
- root.containerOpen = false;
-});
-
-function checkFirstLevel(index, node, roots) {
- PlacesUtils.asContainer(node).containerOpen = true;
-
- do_check_true(PlacesUtils.nodeIsDay(node));
- PlacesUtils.asQuery(node);
- let queries = node.getQueries();
- let options = node.queryOptions;
-
- do_check_eq(queries.length, 1);
- let query = queries[0];
-
- do_check_true(query.hasBeginTime && query.hasEndTime);
-
- // Here we check the second level of results.
- let root = PlacesUtils.history.executeQuery(query, options).root;
- roots.push([]);
- root.containerOpen = true;
-
- do_check_eq(root.childCount, leveledTestData[index].length);
- for (var secondIndex = 0; secondIndex < root.childCount; secondIndex++) {
- let child = PlacesUtils.asQuery(root.getChild(secondIndex));
- checkSecondLevel(index, secondIndex, child, roots);
- }
- root.containerOpen = false;
- node.containerOpen = false;
-}
-
-function checkSecondLevel(index, secondIndex, child, roots) {
- let queries = child.getQueries();
- let options = child.queryOptions;
-
- do_check_eq(queries.length, 1);
- let query = queries[0];
-
- do_check_true(query.hasDomain);
- do_check_true(query.hasBeginTime && query.hasEndTime);
-
- let root = PlacesUtils.history.executeQuery(query, options).root;
- // We should now have that roots[index][secondIndex] is set to the second
- // level's results root.
- roots[index].push(root);
-
- // We pass off to compareArrayToResult to check the third level of
- // results.
- root.containerOpen = true;
- compareArrayToResult(leveledTestData[index][secondIndex].
- map(x => testData[x]), root);
- // We close |root|'s container later so that we can test live
- // updates into it.
-}
diff --git a/toolkit/components/places/tests/queries/test_sorting.js b/toolkit/components/places/tests/queries/test_sorting.js
deleted file mode 100644
index 4d8e1146d..000000000
--- a/toolkit/components/places/tests/queries/test_sorting.js
+++ /dev/null
@@ -1,1265 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var tests = [];
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_NONE,
-
- *setup() {
- do_print("Sorting test 1: SORT BY NONE");
-
- this._unsortedData = [
- { isBookmark: true,
- uri: "http://example.com/b",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "y",
- keyword: "b",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/a",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "z",
- keyword: "a",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "x",
- keyword: "c",
- isInQuery: true },
- ];
-
- this._sortedData = this._unsortedData;
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- // no reverse sorting for SORT BY NONE
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_ASCENDING,
-
- *setup() {
- do_print("Sorting test 2: SORT BY TITLE");
-
- this._unsortedData = [
- { isBookmark: true,
- uri: "http://example.com/b1",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "y",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/a",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "z",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "x",
- isInQuery: true },
-
- // if titles are equal, should fall back to URI
- { isBookmark: true,
- uri: "http://example.com/b2",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "y",
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[2],
- this._unsortedData[0],
- this._unsortedData[3],
- this._unsortedData[1],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_TITLE_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_ASCENDING,
-
- *setup() {
- do_print("Sorting test 3: SORT BY DATE");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isVisit: true,
- isDetails: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0,
- uri: "http://example.com/c1",
- lastVisit: timeInMicroseconds - 2000,
- title: "x1",
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- uri: "http://example.com/a",
- lastVisit: timeInMicroseconds - 1000,
- title: "z",
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 2,
- uri: "http://example.com/b",
- lastVisit: timeInMicroseconds - 3000,
- title: "y",
- isInQuery: true },
-
- // if dates are equal, should fall back to title
- { isVisit: true,
- isDetails: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 3,
- uri: "http://example.com/c2",
- lastVisit: timeInMicroseconds - 2000,
- title: "x2",
- isInQuery: true },
-
- // if dates and title are equal, should fall back to bookmark index
- { isVisit: true,
- isDetails: true,
- isBookmark: true,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 4,
- uri: "http://example.com/c2",
- lastVisit: timeInMicroseconds - 2000,
- title: "x2",
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[2],
- this._unsortedData[0],
- this._unsortedData[3],
- this._unsortedData[4],
- this._unsortedData[1],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_URI_ASCENDING,
-
- *setup() {
- do_print("Sorting test 4: SORT BY URI");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isBookmark: true,
- isDetails: true,
- lastVisit: timeInMicroseconds,
- uri: "http://example.com/b",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0,
- title: "y",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- title: "x",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/a",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 2,
- title: "z",
- isInQuery: true },
-
- // if URIs are equal, should fall back to date
- { isBookmark: true,
- isDetails: true,
- lastVisit: timeInMicroseconds + 1000,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 3,
- title: "x",
- isInQuery: true },
-
- // if no URI (e.g., node is a folder), should fall back to title
- { isFolder: true,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 4,
- title: "a",
- isInQuery: true },
-
- // if URIs and dates are equal, should fall back to bookmark index
- { isBookmark: true,
- isDetails: true,
- lastVisit: timeInMicroseconds + 1000,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 5,
- title: "x",
- isInQuery: true },
-
- // if no URI and titles are equal, should fall back to bookmark index
- { isFolder: true,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 6,
- title: "a",
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[4],
- this._unsortedData[6],
- this._unsortedData[2],
- this._unsortedData[0],
- this._unsortedData[1],
- this._unsortedData[3],
- this._unsortedData[5],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_URI_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_ASCENDING,
-
- *setup() {
- do_print("Sorting test 5: SORT BY VISITCOUNT");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isBookmark: true,
- uri: "http://example.com/a",
- lastVisit: timeInMicroseconds,
- title: "z",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0,
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/c",
- lastVisit: timeInMicroseconds,
- title: "x",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/b1",
- lastVisit: timeInMicroseconds,
- title: "y1",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 2,
- isInQuery: true },
-
- // if visitCounts are equal, should fall back to date
- { isBookmark: true,
- uri: "http://example.com/b2",
- lastVisit: timeInMicroseconds + 1000,
- title: "y2a",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 3,
- isInQuery: true },
-
- // if visitCounts and dates are equal, should fall back to bookmark index
- { isBookmark: true,
- uri: "http://example.com/b2",
- lastVisit: timeInMicroseconds + 1000,
- title: "y2b",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 4,
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[0],
- this._unsortedData[2],
- this._unsortedData[3],
- this._unsortedData[4],
- this._unsortedData[1],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- // add visits to increase visit count
- yield PlacesTestUtils.addVisits([
- { uri: uri("http://example.com/a"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds },
- { uri: uri("http://example.com/b1"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds },
- { uri: uri("http://example.com/b1"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds },
- { uri: uri("http://example.com/b2"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds + 1000 },
- { uri: uri("http://example.com/b2"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds + 1000 },
- { uri: uri("http://example.com/c"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds },
- { uri: uri("http://example.com/c"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds },
- { uri: uri("http://example.com/c"), transition: TRANSITION_TYPED, visitDate: timeInMicroseconds },
- ]);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_KEYWORD_ASCENDING,
-
- *setup() {
- do_print("Sorting test 6: SORT BY KEYWORD");
-
- this._unsortedData = [
- { isBookmark: true,
- uri: "http://example.com/a",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "z",
- keyword: "a",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "x",
- keyword: "c",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/b1",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "y9",
- keyword: "b",
- isInQuery: true },
-
- // without a keyword, should fall back to title
- { isBookmark: true,
- uri: "http://example.com/null2",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "null8",
- keyword: null,
- isInQuery: true },
-
- // without a keyword, should fall back to title
- { isBookmark: true,
- uri: "http://example.com/null1",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "null9",
- keyword: null,
- isInQuery: true },
-
- // if keywords are equal, should fall back to title
- { isBookmark: true,
- uri: "http://example.com/b1",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "y8",
- keyword: "b",
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[3],
- this._unsortedData[4],
- this._unsortedData[0],
- this._unsortedData[5],
- this._unsortedData[2],
- this._unsortedData[1],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_KEYWORD_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_ASCENDING,
-
- *setup() {
- do_print("Sorting test 7: SORT BY DATEADDED");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isBookmark: true,
- uri: "http://example.com/b1",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0,
- title: "y1",
- dateAdded: timeInMicroseconds - 1000,
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/a",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- title: "z",
- dateAdded: timeInMicroseconds - 2000,
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 2,
- title: "x",
- dateAdded: timeInMicroseconds,
- isInQuery: true },
-
- // if dateAddeds are equal, should fall back to title
- { isBookmark: true,
- uri: "http://example.com/b2",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 3,
- title: "y2",
- dateAdded: timeInMicroseconds - 1000,
- isInQuery: true },
-
- // if dateAddeds and titles are equal, should fall back to bookmark index
- { isBookmark: true,
- uri: "http://example.com/b3",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 4,
- title: "y3",
- dateAdded: timeInMicroseconds - 1000,
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[1],
- this._unsortedData[0],
- this._unsortedData[3],
- this._unsortedData[4],
- this._unsortedData[2],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_LASTMODIFIED_ASCENDING,
-
- *setup() {
- do_print("Sorting test 8: SORT BY LASTMODIFIED");
-
- var timeInMicroseconds = Date.now() * 1000;
- var timeAddedInMicroseconds = timeInMicroseconds - 10000;
-
- this._unsortedData = [
- { isBookmark: true,
- uri: "http://example.com/b1",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 0,
- title: "y1",
- dateAdded: timeAddedInMicroseconds,
- lastModified: timeInMicroseconds - 1000,
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/a",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- title: "z",
- dateAdded: timeAddedInMicroseconds,
- lastModified: timeInMicroseconds - 2000,
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://example.com/c",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 2,
- title: "x",
- dateAdded: timeAddedInMicroseconds,
- lastModified: timeInMicroseconds,
- isInQuery: true },
-
- // if lastModifieds are equal, should fall back to title
- { isBookmark: true,
- uri: "http://example.com/b2",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 3,
- title: "y2",
- dateAdded: timeAddedInMicroseconds,
- lastModified: timeInMicroseconds - 1000,
- isInQuery: true },
-
- // if lastModifieds and titles are equal, should fall back to bookmark
- // index
- { isBookmark: true,
- uri: "http://example.com/b3",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: 4,
- title: "y3",
- dateAdded: timeAddedInMicroseconds,
- lastModified: timeInMicroseconds - 1000,
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[1],
- this._unsortedData[0],
- this._unsortedData[3],
- this._unsortedData[4],
- this._unsortedData[2],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_LASTMODIFIED_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_TAGS_ASCENDING,
-
- *setup() {
- do_print("Sorting test 9: SORT BY TAGS");
-
- this._unsortedData = [
- { isBookmark: true,
- uri: "http://url2.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "title x",
- isTag: true,
- tagArray: ["x", "y", "z"],
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://url1a.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "title y1",
- isTag: true,
- tagArray: ["a", "b"],
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://url3a.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "title w1",
- isInQuery: true },
-
- { isBookmark: true,
- uri: "http://url0.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "title z",
- isTag: true,
- tagArray: ["a", "y", "z"],
- isInQuery: true },
-
- // if tags are equal, should fall back to title
- { isBookmark: true,
- uri: "http://url1b.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "title y2",
- isTag: true,
- tagArray: ["b", "a"],
- isInQuery: true },
-
- // if tags are equal, should fall back to title
- { isBookmark: true,
- uri: "http://url3b.com/",
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- title: "title w2",
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[2],
- this._unsortedData[5],
- this._unsortedData[1],
- this._unsortedData[4],
- this._unsortedData[3],
- this._unsortedData[0],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.bookmarks.toolbarFolder], 1);
- query.onlyBookmarked = true;
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_TAGS_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-// SORT_BY_ANNOTATION_* (int32)
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_ASCENDING,
-
- *setup() {
- do_print("Sorting test 10: SORT BY ANNOTATION (int32)");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isVisit: true,
- isDetails: true,
- lastVisit: timeInMicroseconds,
- uri: "http://example.com/b1",
- title: "y1",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 2,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- lastVisit: timeInMicroseconds,
- uri: "http://example.com/a",
- title: "z",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 1,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- lastVisit: timeInMicroseconds,
- uri: "http://example.com/c",
- title: "x",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 3,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- // if annotations are equal, should fall back to title
- { isVisit: true,
- isDetails: true,
- lastVisit: timeInMicroseconds,
- uri: "http://example.com/b2",
- title: "y2",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 2,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[1],
- this._unsortedData[0],
- this._unsortedData[3],
- this._unsortedData[2],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingAnnotation = "sorting";
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-// SORT_BY_ANNOTATION_* (int64)
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_ASCENDING,
-
- *setup() {
- do_print("Sorting test 11: SORT BY ANNOTATION (int64)");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isVisit: true,
- isDetails: true,
- uri: "http://moz.com/",
- lastVisit: timeInMicroseconds,
- title: "I",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 0xffffffff1,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://is.com/",
- lastVisit: timeInMicroseconds,
- title: "love",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 0xffffffff0,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://best.com/",
- lastVisit: timeInMicroseconds,
- title: "moz",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 0xffffffff2,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[1],
- this._unsortedData[0],
- this._unsortedData[2],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingAnnotation = "sorting";
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-// SORT_BY_ANNOTATION_* (string)
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_ASCENDING,
-
- *setup() {
- do_print("Sorting test 12: SORT BY ANNOTATION (string)");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isVisit: true,
- isDetails: true,
- uri: "http://moz.com/",
- lastVisit: timeInMicroseconds,
- title: "I",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: "a",
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://is.com/",
- lastVisit: timeInMicroseconds,
- title: "love",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: "",
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://best.com/",
- lastVisit: timeInMicroseconds,
- title: "moz",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: "z",
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[1],
- this._unsortedData[0],
- this._unsortedData[2],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingAnnotation = "sorting";
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-// SORT_BY_ANNOTATION_* (double)
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_ASCENDING,
-
- *setup() {
- do_print("Sorting test 13: SORT BY ANNOTATION (double)");
-
- var timeInMicroseconds = Date.now() * 1000;
- this._unsortedData = [
- { isVisit: true,
- isDetails: true,
- uri: "http://moz.com/",
- lastVisit: timeInMicroseconds,
- title: "I",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 1.2,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://is.com/",
- lastVisit: timeInMicroseconds,
- title: "love",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 1.1,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://best.com/",
- lastVisit: timeInMicroseconds,
- title: "moz",
- isPageAnnotation: true,
- annoName: "sorting",
- annoVal: 1.3,
- annoFlags: 0,
- annoExpiration: Ci.nsIAnnotationService.EXPIRE_NEVER,
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[1],
- this._unsortedData[0],
- this._unsortedData[2],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- // Query
- var query = PlacesUtils.history.getNewQuery();
-
- // query options
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingAnnotation = "sorting";
- options.sortingMode = this._sortingMode;
-
- // Results - this gets the result set and opens it for reading and modification.
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-// SORT_BY_FRECENCY_*
-
-tests.push({
- _sortingMode: Ci.nsINavHistoryQueryOptions.SORT_BY_FRECENCY_ASCENDING,
-
- *setup() {
- do_print("Sorting test 13: SORT BY FRECENCY ");
-
- let timeInMicroseconds = PlacesUtils.toPRTime(Date.now() - 10000);
-
- function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds + 1000;
- return timeInMicroseconds;
- }
-
- this._unsortedData = [
- { isVisit: true,
- isDetails: true,
- uri: "http://moz.com/",
- lastVisit: newTimeInMicroseconds(),
- title: "I",
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://moz.com/",
- lastVisit: newTimeInMicroseconds(),
- title: "I",
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://moz.com/",
- lastVisit: newTimeInMicroseconds(),
- title: "I",
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://is.com/",
- lastVisit: newTimeInMicroseconds(),
- title: "love",
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://best.com/",
- lastVisit: newTimeInMicroseconds(),
- title: "moz",
- isInQuery: true },
-
- { isVisit: true,
- isDetails: true,
- uri: "http://best.com/",
- lastVisit: newTimeInMicroseconds(),
- title: "moz",
- isInQuery: true },
- ];
-
- this._sortedData = [
- this._unsortedData[3],
- this._unsortedData[5],
- this._unsortedData[2],
- ];
-
- // This function in head_queries.js creates our database with the above data
- yield task_populateDB(this._unsortedData);
- },
-
- check: function() {
- var query = PlacesUtils.history.getNewQuery();
- var options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = this._sortingMode;
-
- var root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- compareArrayToResult(this._sortedData, root);
- root.containerOpen = false;
- },
-
- check_reverse: function() {
- this._sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_FRECENCY_DESCENDING;
- this._sortedData.reverse();
- this.check();
- }
-});
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_sorting()
-{
- for (let test of tests) {
- yield test.setup();
- yield PlacesTestUtils.promiseAsyncUpdates();
- test.check();
- // sorting reversed, usually SORT_BY have ASC and DESC
- test.check_reverse();
- // Execute cleanup tasks
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
- }
-});
diff --git a/toolkit/components/places/tests/queries/test_tags.js b/toolkit/components/places/tests/queries/test_tags.js
deleted file mode 100644
index afda3f03f..000000000
--- a/toolkit/components/places/tests/queries/test_tags.js
+++ /dev/null
@@ -1,743 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Tests bookmark and history queries with tags. See bug 399799.
- */
-
-"use strict";
-
-add_task(function* tags_getter_setter() {
- do_print("Tags getter/setter should work correctly");
- do_print("Without setting tags, tags getter should return empty array");
- var [query] = makeQuery();
- do_check_eq(query.tags.length, 0);
-
- do_print("Setting tags to an empty array, tags getter should return "+
- "empty array");
- [query] = makeQuery([]);
- do_check_eq(query.tags.length, 0);
-
- do_print("Setting a few tags, tags getter should return correct array");
- var tags = ["bar", "baz", "foo"];
- [query] = makeQuery(tags);
- setsAreEqual(query.tags, tags, true);
-
- do_print("Setting some dupe tags, tags getter return unique tags");
- [query] = makeQuery(["foo", "foo", "bar", "foo", "baz", "bar"]);
- setsAreEqual(query.tags, ["bar", "baz", "foo"], true);
-});
-
-add_task(function* invalid_setter_calls() {
- do_print("Invalid calls to tags setter should fail");
- try {
- var query = PlacesUtils.history.getNewQuery();
- query.tags = null;
- do_throw("Passing null to SetTags should fail");
- }
- catch (exc) {}
-
- try {
- query = PlacesUtils.history.getNewQuery();
- query.tags = "this should not work";
- do_throw("Passing a string to SetTags should fail");
- }
- catch (exc) {}
-
- try {
- makeQuery([null]);
- do_throw("Passing one-element array with null to SetTags should fail");
- }
- catch (exc) {}
-
- try {
- makeQuery([undefined]);
- do_throw("Passing one-element array with undefined to SetTags " +
- "should fail");
- }
- catch (exc) {}
-
- try {
- makeQuery(["foo", null, "bar"]);
- do_throw("Passing mixture of tags and null to SetTags should fail");
- }
- catch (exc) {}
-
- try {
- makeQuery(["foo", undefined, "bar"]);
- do_throw("Passing mixture of tags and undefined to SetTags " +
- "should fail");
- }
- catch (exc) {}
-
- try {
- makeQuery([1, 2, 3]);
- do_throw("Passing numbers to SetTags should fail");
- }
- catch (exc) {}
-
- try {
- makeQuery(["foo", 1, 2, 3]);
- do_throw("Passing mixture of tags and numbers to SetTags should fail");
- }
- catch (exc) {}
-
- try {
- var str = PlacesUtils.toISupportsString("foo");
- query = PlacesUtils.history.getNewQuery();
- query.tags = str;
- do_throw("Passing nsISupportsString to SetTags should fail");
- }
- catch (exc) {}
-
- try {
- makeQuery([str]);
- do_throw("Passing array of nsISupportsStrings to SetTags should fail");
- }
- catch (exc) {}
-});
-
-add_task(function* not_setting_tags() {
- do_print("Not setting tags at all should not affect query URI");
- checkQueryURI();
-});
-
-add_task(function* empty_array_tags() {
- do_print("Setting tags with an empty array should not affect query URI");
- checkQueryURI([]);
-});
-
-add_task(function* set_tags() {
- do_print("Setting some tags should result in correct query URI");
- checkQueryURI([
- "foo",
- "七難",
- "",
- "いっぱいおっぱい",
- "Abracadabra",
- "123",
- "Here's a pretty long tag name with some = signs and 1 2 3s and spaces oh jeez will it work I hope so!",
- "アスキーでございません",
- "あいうえお",
- ]);
-});
-
-add_task(function* no_tags_tagsAreNot() {
- do_print("Not setting tags at all but setting tagsAreNot should " +
- "affect query URI");
- checkQueryURI(null, true);
-});
-
-add_task(function* empty_array_tags_tagsAreNot() {
- do_print("Setting tags with an empty array and setting tagsAreNot " +
- "should affect query URI");
- checkQueryURI([], true);
-});
-
-add_task(function* () {
- do_print("Setting some tags and setting tagsAreNot should result in " +
- "correct query URI");
- checkQueryURI([
- "foo",
- "七難",
- "",
- "いっぱいおっぱい",
- "Abracadabra",
- "123",
- "Here's a pretty long tag name with some = signs and 1 2 3s and spaces oh jeez will it work I hope so!",
- "アスキーでございません",
- "あいうえお",
- ], true);
-});
-
-add_task(function* tag_to_uri() {
- do_print("Querying history on tag associated with a URI should return " +
- "that URI");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["bar"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["baz"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- });
-});
-
-add_task(function* tags_to_uri() {
- do_print("Querying history on many tags associated with a URI should " +
- "return that URI");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo", "bar"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["foo", "baz"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["bar", "baz"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["foo", "bar", "baz"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- });
-});
-
-add_task(function* repeated_tag() {
- do_print("Specifying the same tag multiple times in a history query " +
- "should not matter");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo", "foo"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["foo", "foo", "foo", "bar", "bar", "baz"]);
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- });
-});
-
-add_task(function* many_tags_no_uri() {
- do_print("Querying history on many tags associated with a URI and " +
- "tags not associated with that URI should not return that URI");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo", "bogus"]);
- executeAndCheckQueryResults(query, opts, []);
- [query, opts] = makeQuery(["foo", "bar", "bogus"]);
- executeAndCheckQueryResults(query, opts, []);
- [query, opts] = makeQuery(["foo", "bar", "baz", "bogus"]);
- executeAndCheckQueryResults(query, opts, []);
- });
-});
-
-add_task(function* nonexistent_tags() {
- do_print("Querying history on nonexistent tags should return no results");
- yield task_doWithVisit(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["bogus"]);
- executeAndCheckQueryResults(query, opts, []);
- [query, opts] = makeQuery(["bogus", "gnarly"]);
- executeAndCheckQueryResults(query, opts, []);
- });
-});
-
-add_task(function* tag_to_bookmark() {
- do_print("Querying bookmarks on tag associated with a URI should " +
- "return that URI");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["bar"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["baz"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- });
-});
-
-add_task(function* many_tags_to_bookmark() {
- do_print("Querying bookmarks on many tags associated with a URI " +
- "should return that URI");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo", "bar"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["foo", "baz"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["bar", "baz"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["foo", "bar", "baz"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- });
-});
-
-add_task(function* repeated_tag_to_bookmarks() {
- do_print("Specifying the same tag multiple times in a bookmark query " +
- "should not matter");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo", "foo"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- [query, opts] = makeQuery(["foo", "foo", "foo", "bar", "bar", "baz"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, [aURI.spec]);
- });
-});
-
-add_task(function* many_tags_no_bookmark() {
- do_print("Querying bookmarks on many tags associated with a URI and " +
- "tags not associated with that URI should not return that URI");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["foo", "bogus"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, []);
- [query, opts] = makeQuery(["foo", "bar", "bogus"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, []);
- [query, opts] = makeQuery(["foo", "bar", "baz", "bogus"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, []);
- });
-});
-
-add_task(function* nonexistent_tags_bookmark() {
- do_print("Querying bookmarks on nonexistent tag should return no results");
- yield task_doWithBookmark(["foo", "bar", "baz"], function (aURI) {
- var [query, opts] = makeQuery(["bogus"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, []);
- [query, opts] = makeQuery(["bogus", "gnarly"]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- executeAndCheckQueryResults(query, opts, []);
- });
-});
-
-add_task(function* tagsAreNot_history() {
- do_print("Querying history using tagsAreNot should work correctly");
- var urisAndTags = {
- "http://example.com/1": ["foo", "bar"],
- "http://example.com/2": ["baz", "qux"],
- "http://example.com/3": null
- };
-
- do_print("Add visits and tag the URIs");
- for (let [pURI, tags] of Object.entries(urisAndTags)) {
- let nsiuri = uri(pURI);
- yield PlacesTestUtils.addVisits(nsiuri);
- if (tags)
- PlacesUtils.tagging.tagURI(nsiuri, tags);
- }
-
- do_print(' Querying for "foo" should match only /2 and /3');
- var [query, opts] = makeQuery(["foo"], true);
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/2", "http://example.com/3"]);
-
- do_print(' Querying for "foo" and "bar" should match only /2 and /3');
- [query, opts] = makeQuery(["foo", "bar"], true);
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/2", "http://example.com/3"]);
-
- do_print(' Querying for "foo" and "bogus" should match only /2 and /3');
- [query, opts] = makeQuery(["foo", "bogus"], true);
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/2", "http://example.com/3"]);
-
- do_print(' Querying for "foo" and "baz" should match only /3');
- [query, opts] = makeQuery(["foo", "baz"], true);
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/3"]);
-
- do_print(' Querying for "bogus" should match all');
- [query, opts] = makeQuery(["bogus"], true);
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/1",
- "http://example.com/2",
- "http://example.com/3"]);
-
- // Clean up.
- for (let [pURI, tags] of Object.entries(urisAndTags)) {
- let nsiuri = uri(pURI);
- if (tags)
- PlacesUtils.tagging.untagURI(nsiuri, tags);
- }
- yield task_cleanDatabase();
-});
-
-add_task(function* tagsAreNot_bookmarks() {
- do_print("Querying bookmarks using tagsAreNot should work correctly");
- var urisAndTags = {
- "http://example.com/1": ["foo", "bar"],
- "http://example.com/2": ["baz", "qux"],
- "http://example.com/3": null
- };
-
- do_print("Add bookmarks and tag the URIs");
- for (let [pURI, tags] of Object.entries(urisAndTags)) {
- let nsiuri = uri(pURI);
- yield addBookmark(nsiuri);
- if (tags)
- PlacesUtils.tagging.tagURI(nsiuri, tags);
- }
-
- do_print(' Querying for "foo" should match only /2 and /3');
- var [query, opts] = makeQuery(["foo"], true);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/2", "http://example.com/3"]);
-
- do_print(' Querying for "foo" and "bar" should match only /2 and /3');
- [query, opts] = makeQuery(["foo", "bar"], true);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/2", "http://example.com/3"]);
-
- do_print(' Querying for "foo" and "bogus" should match only /2 and /3');
- [query, opts] = makeQuery(["foo", "bogus"], true);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/2", "http://example.com/3"]);
-
- do_print(' Querying for "foo" and "baz" should match only /3');
- [query, opts] = makeQuery(["foo", "baz"], true);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/3"]);
-
- do_print(' Querying for "bogus" should match all');
- [query, opts] = makeQuery(["bogus"], true);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root,
- ["http://example.com/1",
- "http://example.com/2",
- "http://example.com/3"]);
-
- // Clean up.
- for (let [pURI, tags] of Object.entries(urisAndTags)) {
- let nsiuri = uri(pURI);
- if (tags)
- PlacesUtils.tagging.untagURI(nsiuri, tags);
- }
- yield task_cleanDatabase();
-});
-
-add_task(function* duplicate_tags() {
- do_print("Duplicate existing tags (i.e., multiple tag folders with " +
- "same name) should not throw off query results");
- var tagName = "foo";
-
- do_print("Add bookmark and tag it normally");
- yield addBookmark(TEST_URI);
- PlacesUtils.tagging.tagURI(TEST_URI, [tagName]);
-
- do_print("Manually create tag folder with same name as tag and insert " +
- "bookmark");
- let dupTag = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.tagsGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: tagName
- });
-
- yield PlacesUtils.bookmarks.insert({
- parentGuid: dupTag.guid,
- title: "title",
- url: TEST_URI
- });
-
- do_print("Querying for tag should match URI");
- var [query, opts] = makeQuery([tagName]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root, [TEST_URI.spec]);
-
- PlacesUtils.tagging.untagURI(TEST_URI, [tagName]);
- yield task_cleanDatabase();
-});
-
-add_task(function* folder_named_as_tag() {
- do_print("Regular folders with the same name as tag should not throw " +
- "off query results");
- var tagName = "foo";
-
- do_print("Add bookmark and tag it");
- yield addBookmark(TEST_URI);
- PlacesUtils.tagging.tagURI(TEST_URI, [tagName]);
-
- do_print("Create folder with same name as tag");
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: tagName
- });
-
- do_print("Querying for tag should match URI");
- var [query, opts] = makeQuery([tagName]);
- opts.queryType = opts.QUERY_TYPE_BOOKMARKS;
- queryResultsAre(PlacesUtils.history.executeQuery(query, opts).root, [TEST_URI.spec]);
-
- PlacesUtils.tagging.untagURI(TEST_URI, [tagName]);
- yield task_cleanDatabase();
-});
-
-add_task(function* ORed_queries() {
- do_print("Multiple queries ORed together should work");
- var urisAndTags = {
- "http://example.com/1": [],
- "http://example.com/2": []
- };
-
- // Search with lots of tags to make sure tag parameter substitution in SQL
- // can handle it with more than one query.
- for (let i = 0; i < 11; i++) {
- urisAndTags["http://example.com/1"].push("/1 tag " + i);
- urisAndTags["http://example.com/2"].push("/2 tag " + i);
- }
-
- do_print("Add visits and tag the URIs");
- for (let [pURI, tags] of Object.entries(urisAndTags)) {
- let nsiuri = uri(pURI);
- yield PlacesTestUtils.addVisits(nsiuri);
- if (tags)
- PlacesUtils.tagging.tagURI(nsiuri, tags);
- }
-
- do_print("Query for /1 OR query for /2 should match both /1 and /2");
- var [query1, opts] = makeQuery(urisAndTags["http://example.com/1"]);
- var [query2] = makeQuery(urisAndTags["http://example.com/2"]);
- var root = PlacesUtils.history.executeQueries([query1, query2], 2, opts).root;
- queryResultsAre(root, ["http://example.com/1", "http://example.com/2"]);
-
- do_print("Query for /1 OR query on bogus tag should match only /1");
- [query1, opts] = makeQuery(urisAndTags["http://example.com/1"]);
- [query2] = makeQuery(["bogus"]);
- root = PlacesUtils.history.executeQueries([query1, query2], 2, opts).root;
- queryResultsAre(root, ["http://example.com/1"]);
-
- do_print("Query for /1 OR query for /1 should match only /1");
- [query1, opts] = makeQuery(urisAndTags["http://example.com/1"]);
- [query2] = makeQuery(urisAndTags["http://example.com/1"]);
- root = PlacesUtils.history.executeQueries([query1, query2], 2, opts).root;
- queryResultsAre(root, ["http://example.com/1"]);
-
- do_print("Query for /1 with tagsAreNot OR query for /2 with tagsAreNot " +
- "should match both /1 and /2");
- [query1, opts] = makeQuery(urisAndTags["http://example.com/1"], true);
- [query2] = makeQuery(urisAndTags["http://example.com/2"], true);
- root = PlacesUtils.history.executeQueries([query1, query2], 2, opts).root;
- queryResultsAre(root, ["http://example.com/1", "http://example.com/2"]);
-
- do_print("Query for /1 OR query for /2 with tagsAreNot should match " +
- "only /1");
- [query1, opts] = makeQuery(urisAndTags["http://example.com/1"]);
- [query2] = makeQuery(urisAndTags["http://example.com/2"], true);
- root = PlacesUtils.history.executeQueries([query1, query2], 2, opts).root;
- queryResultsAre(root, ["http://example.com/1"]);
-
- do_print("Query for /1 OR query for /1 with tagsAreNot should match " +
- "both URIs");
- [query1, opts] = makeQuery(urisAndTags["http://example.com/1"]);
- [query2] = makeQuery(urisAndTags["http://example.com/1"], true);
- root = PlacesUtils.history.executeQueries([query1, query2], 2, opts).root;
- queryResultsAre(root, ["http://example.com/1", "http://example.com/2"]);
-
- // Clean up.
- for (let [pURI, tags] of Object.entries(urisAndTags)) {
- let nsiuri = uri(pURI);
- if (tags)
- PlacesUtils.tagging.untagURI(nsiuri, tags);
- }
- yield task_cleanDatabase();
-});
-
-// The tag keys in query URIs, i.e., "place:tag=foo&!tags=1"
-// --- -----
-const QUERY_KEY_TAG = "tag";
-const QUERY_KEY_NOT_TAGS = "!tags";
-
-const TEST_URI = uri("http://example.com/");
-
-/**
- * Adds a bookmark.
- *
- * @param aURI
- * URI of the page (an nsIURI)
- */
-function addBookmark(aURI) {
- return PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: aURI.spec,
- url: aURI
- });
-}
-
-/**
- * Asynchronous task that removes all pages from history and bookmarks.
- */
-function* task_cleanDatabase(aCallback) {
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-}
-
-/**
- * Sets up a query with the specified tags, converts it to a URI, and makes sure
- * the URI is what we expect it to be.
- *
- * @param aTags
- * The query's tags will be set to those in this array
- * @param aTagsAreNot
- * The query's tagsAreNot property will be set to this
- */
-function checkQueryURI(aTags, aTagsAreNot) {
- var pairs = (aTags || []).sort().map(t => QUERY_KEY_TAG + "=" + encodeTag(t));
- if (aTagsAreNot)
- pairs.push(QUERY_KEY_NOT_TAGS + "=1");
- var expURI = "place:" + pairs.join("&");
- var [query, opts] = makeQuery(aTags, aTagsAreNot);
- var actualURI = queryURI(query, opts);
- do_print("Query URI should be what we expect for the given tags");
- do_check_eq(actualURI, expURI);
-}
-
-/**
- * Asynchronous task that executes a callback task in a "scoped" database state.
- * A bookmark is added and tagged before the callback is called, and afterward
- * the database is cleared.
- *
- * @param aTags
- * A bookmark will be added and tagged with this array of tags
- * @param aCallback
- * A task function that will be called after the bookmark has been tagged
- */
-function* task_doWithBookmark(aTags, aCallback) {
- yield addBookmark(TEST_URI);
- PlacesUtils.tagging.tagURI(TEST_URI, aTags);
- yield aCallback(TEST_URI);
- PlacesUtils.tagging.untagURI(TEST_URI, aTags);
- yield task_cleanDatabase();
-}
-
-/**
- * Asynchronous task that executes a callback function in a "scoped" database
- * state. A history visit is added and tagged before the callback is called,
- * and afterward the database is cleared.
- *
- * @param aTags
- * A history visit will be added and tagged with this array of tags
- * @param aCallback
- * A function that will be called after the visit has been tagged
- */
-function* task_doWithVisit(aTags, aCallback) {
- yield PlacesTestUtils.addVisits(TEST_URI);
- PlacesUtils.tagging.tagURI(TEST_URI, aTags);
- yield aCallback(TEST_URI);
- PlacesUtils.tagging.untagURI(TEST_URI, aTags);
- yield task_cleanDatabase();
-}
-
-/**
- * queriesToQueryString() encodes every character in the query URI that doesn't
- * match /[a-zA-Z]/. There's no simple JavaScript function that does the same,
- * but encodeURIComponent() comes close, only missing some punctuation. This
- * function takes care of all of that.
- *
- * @param aTag
- * A tag name to encode
- * @return A UTF-8 escaped string suitable for inclusion in a query URI
- */
-function encodeTag(aTag) {
- return encodeURIComponent(aTag).
- replace(/[-_.!~*'()]/g, // '
- s => "%" + s.charCodeAt(0).toString(16));
-}
-
-/**
- * Executes the given query and compares the results to the given URIs.
- * See queryResultsAre().
- *
- * @param aQuery
- * An nsINavHistoryQuery
- * @param aQueryOpts
- * An nsINavHistoryQueryOptions
- * @param aExpectedURIs
- * Array of URIs (as strings) that aResultRoot should contain
- */
-function executeAndCheckQueryResults(aQuery, aQueryOpts, aExpectedURIs) {
- var root = PlacesUtils.history.executeQuery(aQuery, aQueryOpts).root;
- root.containerOpen = true;
- queryResultsAre(root, aExpectedURIs);
- root.containerOpen = false;
-}
-
-/**
- * Returns new query and query options objects. The query's tags will be
- * set to aTags. aTags may be null, in which case setTags() is not called at
- * all on the query.
- *
- * @param aTags
- * The query's tags will be set to those in this array
- * @param aTagsAreNot
- * The query's tagsAreNot property will be set to this
- * @return [query, queryOptions]
- */
-function makeQuery(aTags, aTagsAreNot) {
- aTagsAreNot = !!aTagsAreNot;
- do_print("Making a query " +
- (aTags ?
- "with tags " + aTags.toSource() :
- "without calling setTags() at all") +
- " and with tagsAreNot=" +
- aTagsAreNot);
- var query = PlacesUtils.history.getNewQuery();
- query.tagsAreNot = aTagsAreNot;
- if (aTags) {
- query.tags = aTags;
- var uniqueTags = [];
- aTags.forEach(function (t) {
- if (typeof(t) === "string" && uniqueTags.indexOf(t) < 0)
- uniqueTags.push(t);
- });
- uniqueTags.sort();
- }
-
- do_print("Made query should be correct for tags and tagsAreNot");
- if (uniqueTags)
- setsAreEqual(query.tags, uniqueTags, true);
- var expCount = uniqueTags ? uniqueTags.length : 0;
- do_check_eq(query.tags.length, expCount);
- do_check_eq(query.tagsAreNot, aTagsAreNot);
-
- return [query, PlacesUtils.history.getNewQueryOptions()];
-}
-
-/**
- * Ensures that the URIs of aResultRoot are the same as those in aExpectedURIs.
- *
- * @param aResultRoot
- * The nsINavHistoryContainerResultNode root of an nsINavHistoryResult
- * @param aExpectedURIs
- * Array of URIs (as strings) that aResultRoot should contain
- */
-function queryResultsAre(aResultRoot, aExpectedURIs) {
- var rootWasOpen = aResultRoot.containerOpen;
- if (!rootWasOpen)
- aResultRoot.containerOpen = true;
- var actualURIs = [];
- for (let i = 0; i < aResultRoot.childCount; i++) {
- actualURIs.push(aResultRoot.getChild(i).uri);
- }
- setsAreEqual(actualURIs, aExpectedURIs);
- if (!rootWasOpen)
- aResultRoot.containerOpen = false;
-}
-
-/**
- * Converts the given query into its query URI.
- *
- * @param aQuery
- * An nsINavHistoryQuery
- * @param aQueryOpts
- * An nsINavHistoryQueryOptions
- * @return The query's URI
- */
-function queryURI(aQuery, aQueryOpts) {
- return PlacesUtils.history.queriesToQueryString([aQuery], 1, aQueryOpts);
-}
-
-/**
- * Ensures that the arrays contain the same elements and, optionally, in the
- * same order.
- */
-function setsAreEqual(aArr1, aArr2, aIsOrdered) {
- do_check_eq(aArr1.length, aArr2.length);
- if (aIsOrdered) {
- for (let i = 0; i < aArr1.length; i++) {
- do_check_eq(aArr1[i], aArr2[i]);
- }
- }
- else {
- aArr1.forEach(u => do_check_true(aArr2.indexOf(u) >= 0));
- aArr2.forEach(u => do_check_true(aArr1.indexOf(u) >= 0));
- }
-}
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/queries/test_transitions.js b/toolkit/components/places/tests/queries/test_transitions.js
deleted file mode 100644
index bbd4c9e01..000000000
--- a/toolkit/components/places/tests/queries/test_transitions.js
+++ /dev/null
@@ -1,178 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* ***** BEGIN LICENSE BLOCK *****
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
- * ***** END LICENSE BLOCK ***** */
-var beginTime = Date.now();
-var testData = [
- {
- isVisit: true,
- title: "page 0",
- uri: "http://mozilla.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_TYPED
- },
- {
- isVisit: true,
- title: "page 1",
- uri: "http://google.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_DOWNLOAD
- },
- {
- isVisit: true,
- title: "page 2",
- uri: "http://microsoft.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_DOWNLOAD
- },
- {
- isVisit: true,
- title: "page 3",
- uri: "http://en.wikipedia.org/",
- transType: Ci.nsINavHistoryService.TRANSITION_BOOKMARK
- },
- {
- isVisit: true,
- title: "page 4",
- uri: "http://fr.wikipedia.org/",
- transType: Ci.nsINavHistoryService.TRANSITION_DOWNLOAD
- },
- {
- isVisit: true,
- title: "page 5",
- uri: "http://apple.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_TYPED
- },
- {
- isVisit: true,
- title: "page 6",
- uri: "http://campus-bike-store.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_DOWNLOAD
- },
- {
- isVisit: true,
- title: "page 7",
- uri: "http://uwaterloo.ca/",
- transType: Ci.nsINavHistoryService.TRANSITION_TYPED
- },
- {
- isVisit: true,
- title: "page 8",
- uri: "http://pugcleaner.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_BOOKMARK
- },
- {
- isVisit: true,
- title: "page 9",
- uri: "http://de.wikipedia.org/",
- transType: Ci.nsINavHistoryService.TRANSITION_TYPED
- },
- {
- isVisit: true,
- title: "arewefastyet",
- uri: "http://arewefastyet.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_DOWNLOAD
- },
- {
- isVisit: true,
- title: "arewefastyet",
- uri: "http://arewefastyet.com/",
- transType: Ci.nsINavHistoryService.TRANSITION_BOOKMARK
- }];
-// sets of indices of testData array by transition type
-var testDataTyped = [0, 5, 7, 9];
-var testDataDownload = [1, 2, 4, 6, 10];
-var testDataBookmark = [3, 8, 11];
-
-/**
- * run_test is where the magic happens. This is automatically run by the test
- * harness. It is where you do the work of creating the query, running it, and
- * playing with the result set.
- */
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_transitions()
-{
- let timeNow = Date.now();
- for (let item of testData) {
- yield PlacesTestUtils.addVisits({
- uri: uri(item.uri),
- transition: item.transType,
- visitDate: timeNow++ * 1000,
- title: item.title
- });
- }
-
- // dump_table("moz_places");
- // dump_table("moz_historyvisits");
-
- var numSortFunc = function (a, b) { return (a - b); };
- var arrs = testDataTyped.concat(testDataDownload).concat(testDataBookmark)
- .sort(numSortFunc);
-
- // Four tests which compare the result of a query to an expected set.
- var data = arrs.filter(function (index) {
- return (testData[index].uri.match(/arewefastyet\.com/) &&
- testData[index].transType ==
- Ci.nsINavHistoryService.TRANSITION_DOWNLOAD);
- });
-
- compareQueryToTestData("place:domain=arewefastyet.com&transition=" +
- Ci.nsINavHistoryService.TRANSITION_DOWNLOAD,
- data.slice());
-
- compareQueryToTestData("place:transition=" +
- Ci.nsINavHistoryService.TRANSITION_DOWNLOAD,
- testDataDownload.slice());
-
- compareQueryToTestData("place:transition=" +
- Ci.nsINavHistoryService.TRANSITION_TYPED,
- testDataTyped.slice());
-
- compareQueryToTestData("place:transition=" +
- Ci.nsINavHistoryService.TRANSITION_DOWNLOAD +
- "&transition=" +
- Ci.nsINavHistoryService.TRANSITION_BOOKMARK,
- data);
-
- // Tests the live update property of transitions.
- var query = {};
- var options = {};
- PlacesUtils.history.
- queryStringToQueries("place:transition=" +
- Ci.nsINavHistoryService.TRANSITION_DOWNLOAD,
- query, {}, options);
- query = (query.value)[0];
- options = PlacesUtils.history.getNewQueryOptions();
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- do_check_eq(testDataDownload.length, root.childCount);
- yield PlacesTestUtils.addVisits({
- uri: uri("http://getfirefox.com"),
- transition: TRANSITION_DOWNLOAD
- });
- do_check_eq(testDataDownload.length + 1, root.childCount);
- root.containerOpen = false;
-});
-
-/*
- * Takes a query and a set of indices. The indices correspond to elements
- * of testData that are the result of the query.
- */
-function compareQueryToTestData(queryStr, data) {
- var query = {};
- var options = {};
- PlacesUtils.history.queryStringToQueries(queryStr, query, {}, options);
- query = query.value[0];
- options = options.value;
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- for (var i = 0; i < data.length; i++) {
- data[i] = testData[data[i]];
- data[i].isInQuery = true;
- }
- compareArrayToResult(data, root);
-}
diff --git a/toolkit/components/places/tests/queries/xpcshell.ini b/toolkit/components/places/tests/queries/xpcshell.ini
deleted file mode 100644
index 7ff864679..000000000
--- a/toolkit/components/places/tests/queries/xpcshell.ini
+++ /dev/null
@@ -1,34 +0,0 @@
-[DEFAULT]
-head = head_queries.js
-tail =
-skip-if = toolkit == 'android'
-
-[test_415716.js]
-[test_abstime-annotation-domain.js]
-[test_abstime-annotation-uri.js]
-[test_async.js]
-[test_containersQueries_sorting.js]
-[test_history_queries_tags_liveUpdate.js]
-[test_history_queries_titles_liveUpdate.js]
-[test_onlyBookmarked.js]
-[test_queryMultipleFolder.js]
-[test_querySerialization.js]
-[test_redirects.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_results-as-tag-contents-query.js]
-[test_results-as-visit.js]
-[test_searchterms-domain.js]
-[test_searchterms-uri.js]
-[test_searchterms-bookmarklets.js]
-[test_sort-date-site-grouping.js]
-[test_sorting.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_tags.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_transitions.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_searchTerms_includeHidden.js]
diff --git a/toolkit/components/places/tests/unifiedcomplete/.eslintrc.js b/toolkit/components/places/tests/unifiedcomplete/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/unifiedcomplete/data/engine-rel-searchform.xml b/toolkit/components/places/tests/unifiedcomplete/data/engine-rel-searchform.xml
deleted file mode 100644
index f4baad28a..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/data/engine-rel-searchform.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>engine-rel-searchform.xml</ShortName>
-<Url type="text/html" method="GET" template="http://example.com/?search" rel="searchform"/>
-</SearchPlugin>
diff --git a/toolkit/components/places/tests/unifiedcomplete/data/engine-suggestions.xml b/toolkit/components/places/tests/unifiedcomplete/data/engine-suggestions.xml
deleted file mode 100644
index a322a7c86..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/data/engine-suggestions.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/ -->
-
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>engine-suggestions.xml</ShortName>
-<Url type="application/x-suggestions+json"
- method="GET"
- template="http://localhost:9000/suggest?{searchTerms}"/>
-<Url type="text/html"
- method="GET"
- template="http://localhost:9000/search"
- rel="searchform"/>
-</SearchPlugin>
diff --git a/toolkit/components/places/tests/unifiedcomplete/head_autocomplete.js b/toolkit/components/places/tests/unifiedcomplete/head_autocomplete.js
deleted file mode 100644
index bc252efe0..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/head_autocomplete.js
+++ /dev/null
@@ -1,505 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-const FRECENCY_DEFAULT = 10000;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://testing-common/httpd.js");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
-
-const TITLE_SEARCH_ENGINE_SEPARATOR = " \u00B7\u2013\u00B7 ";
-
-function run_test() {
- run_next_test();
-}
-
-function* cleanup() {
- Services.prefs.clearUserPref("browser.urlbar.autocomplete.enabled");
- Services.prefs.clearUserPref("browser.urlbar.autoFill");
- Services.prefs.clearUserPref("browser.urlbar.autoFill.typed");
- Services.prefs.clearUserPref("browser.urlbar.autoFill.searchEngines");
- let suggestPrefs = [
- "history",
- "bookmark",
- "history.onlyTyped",
- "openpage",
- "searches",
- ];
- for (let type of suggestPrefs) {
- Services.prefs.clearUserPref("browser.urlbar.suggest." + type);
- }
- Services.prefs.clearUserPref("browser.search.suggest.enabled");
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-}
-do_register_cleanup(cleanup);
-
-/**
- * @param aSearches
- * Array of AutoCompleteSearch names.
- */
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- popup: {
- selectedIndex: -1,
- invalidate: function () {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup])
- },
- popupOpen: false,
-
- disableAutoComplete: false,
- completeDefaultIndex: true,
- completeSelectedIndex: true,
- forceComplete: false,
-
- minResultsForPopup: 0,
- maxRows: 0,
-
- showCommentColumn: false,
- showImageColumn: false,
-
- timeout: 10,
- searchParam: "",
-
- get searchCount() {
- return this.searches.length;
- },
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- textValue: "",
- // Text selection range
- _selStart: 0,
- _selEnd: 0,
- get selectionStart() {
- return this._selStart;
- },
- get selectionEnd() {
- return this._selEnd;
- },
- selectTextRange: function(aStart, aEnd) {
- this._selStart = aStart;
- this._selEnd = aEnd;
- },
-
- onSearchBegin: function () {},
- onSearchComplete: function () {},
-
- onTextEntered: () => false,
- onTextReverted: () => false,
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
-}
-
-// A helper for check_autocomplete to check a specific match against data from
-// the controller.
-function _check_autocomplete_matches(match, result) {
- let { uri, title, tags, style } = match;
- if (tags)
- title += " \u2013 " + tags.sort().join(", ");
- if (style)
- style = style.sort();
- else
- style = ["favicon"];
-
- do_print(`Checking against expected "${uri.spec}", "${title}"`);
- // Got a match on both uri and title?
- if (stripPrefix(uri.spec) != stripPrefix(result.value) || title != result.comment) {
- return false;
- }
-
- let actualStyle = result.style.split(/\s+/).sort();
- if (style)
- Assert.equal(actualStyle.toString(), style.toString(), "Match should have expected style");
- if (uri.spec.startsWith("moz-action:")) {
- Assert.ok(actualStyle.includes("action"), "moz-action results should always have 'action' in their style");
- }
-
- if (match.icon)
- Assert.equal(result.image, match.icon, "Match should have expected image");
-
- return true;
-}
-
-function* check_autocomplete(test) {
- // At this point frecency could still be updating due to latest pages
- // updates.
- // This is not a problem in real life, but autocomplete tests should
- // return reliable resultsets, thus we have to wait.
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- // Make an AutoCompleteInput that uses our searches and confirms results.
- let input = new AutoCompleteInput(["unifiedcomplete"]);
- input.textValue = test.search;
-
- if (test.searchParam)
- input.searchParam = test.searchParam;
-
- // Caret must be at the end for autoFill to happen.
- let strLen = test.search.length;
- input.selectTextRange(strLen, strLen);
- Assert.equal(input.selectionStart, strLen, "Selection starts at end");
- Assert.equal(input.selectionEnd, strLen, "Selection ends at the end");
-
- let controller = Cc["@mozilla.org/autocomplete/controller;1"]
- .getService(Ci.nsIAutoCompleteController);
- controller.input = input;
-
- let numSearchesStarted = 0;
- input.onSearchBegin = () => {
- do_print("onSearchBegin received");
- numSearchesStarted++;
- };
- let searchCompletePromise = new Promise(resolve => {
- input.onSearchComplete = () => {
- do_print("onSearchComplete received");
- resolve();
- }
- });
- let expectedSearches = 1;
- if (test.incompleteSearch) {
- controller.startSearch(test.incompleteSearch);
- expectedSearches++;
- }
-
- do_print("Searching for: '" + test.search + "'");
- controller.startSearch(test.search);
- yield searchCompletePromise;
-
- Assert.equal(numSearchesStarted, expectedSearches, "All searches started");
-
- // Check to see the expected uris and titles match up. If 'enable-actions'
- // is specified, we check that the first specified match is the first
- // controller value (as this is the "special" always selected item), but the
- // rest can match in any order.
- // If 'enable-actions' is not specified, they can match in any order.
- if (test.matches) {
- // Do not modify the test original matches.
- let matches = test.matches.slice();
-
- if (matches.length) {
- let firstIndexToCheck = 0;
- if (test.searchParam && test.searchParam.includes("enable-actions")) {
- firstIndexToCheck = 1;
- do_print("Checking first match is first autocomplete entry")
- let result = {
- value: controller.getValueAt(0),
- comment: controller.getCommentAt(0),
- style: controller.getStyleAt(0),
- image: controller.getImageAt(0),
- }
- do_print(`First match is "${result.value}", "${result.comment}"`);
- Assert.ok(_check_autocomplete_matches(matches[0], result), "first item is correct");
- do_print("Checking rest of the matches");
- }
-
- for (let i = firstIndexToCheck; i < controller.matchCount; i++) {
- let result = {
- value: controller.getValueAt(i),
- comment: controller.getCommentAt(i),
- style: controller.getStyleAt(i),
- image: controller.getImageAt(i),
- }
- do_print(`Looking for "${result.value}", "${result.comment}" in expected results...`);
- let lowerBound = test.checkSorting ? i : firstIndexToCheck;
- let upperBound = test.checkSorting ? i + 1 : matches.length;
- let found = false;
- for (let j = lowerBound; j < upperBound; ++j) {
- // Skip processed expected results
- if (matches[j] == undefined)
- continue;
- if (_check_autocomplete_matches(matches[j], result)) {
- do_print("Got a match at index " + j + "!");
- // Make it undefined so we don't process it again
- matches[j] = undefined;
- found = true;
- break;
- }
- }
-
- if (!found)
- do_throw(`Didn't find the current result ("${result.value}", "${result.comment}") in matches`); // ' (Emacs syntax highlighting fix)
- }
- }
-
- Assert.equal(controller.matchCount, matches.length,
- "Got as many results as expected");
-
- // If we expect results, make sure we got matches.
- do_check_eq(controller.searchStatus, matches.length ?
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH :
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
- }
-
- if (test.autofilled) {
- // Check the autoFilled result.
- Assert.equal(input.textValue, test.autofilled,
- "Autofilled value is correct");
-
- // Now force completion and check correct casing of the result.
- // This ensures the controller is able to do its magic case-preserving
- // stuff and correct replacement of the user's casing with result's one.
- controller.handleEnter(false);
- Assert.equal(input.textValue, test.completed,
- "Completed value is correct");
- }
-}
-
-var addBookmark = Task.async(function* (aBookmarkObj) {
- Assert.ok(!!aBookmarkObj.uri, "Bookmark object contains an uri");
- let parentId = aBookmarkObj.parentId ? aBookmarkObj.parentId
- : PlacesUtils.unfiledBookmarksFolderId;
-
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: (yield PlacesUtils.promiseItemGuid(parentId)),
- title: aBookmarkObj.title || "A bookmark",
- url: aBookmarkObj.uri
- });
- yield PlacesUtils.promiseItemId(bm.guid);
-
- if (aBookmarkObj.keyword) {
- yield PlacesUtils.keywords.insert({ keyword: aBookmarkObj.keyword,
- url: aBookmarkObj.uri.spec,
- postData: aBookmarkObj.postData
- });
- }
-
- if (aBookmarkObj.tags) {
- PlacesUtils.tagging.tagURI(aBookmarkObj.uri, aBookmarkObj.tags);
- }
-});
-
-function addOpenPages(aUri, aCount=1) {
- let ac = Cc["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"]
- .getService(Ci.mozIPlacesAutoComplete);
- for (let i = 0; i < aCount; i++) {
- ac.registerOpenPage(aUri);
- }
-}
-
-function removeOpenPages(aUri, aCount=1) {
- let ac = Cc["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"]
- .getService(Ci.mozIPlacesAutoComplete);
- for (let i = 0; i < aCount; i++) {
- ac.unregisterOpenPage(aUri);
- }
-}
-
-function changeRestrict(aType, aChar) {
- let branch = "browser.urlbar.";
- // "title" and "url" are different from everything else, so special case them.
- if (aType == "title" || aType == "url")
- branch += "match.";
- else
- branch += "restrict.";
-
- do_print("changing restrict for " + aType + " to '" + aChar + "'");
- Services.prefs.setCharPref(branch + aType, aChar);
-}
-
-function resetRestrict(aType) {
- let branch = "browser.urlbar.";
- // "title" and "url" are different from everything else, so special case them.
- if (aType == "title" || aType == "url")
- branch += "match.";
- else
- branch += "restrict.";
-
- Services.prefs.clearUserPref(branch + aType);
-}
-
-/**
- * Strip prefixes from the URI that we don't care about for searching.
- *
- * @param spec
- * The text to modify.
- * @return the modified spec.
- */
-function stripPrefix(spec)
-{
- ["http://", "https://", "ftp://"].some(scheme => {
- if (spec.startsWith(scheme)) {
- spec = spec.slice(scheme.length);
- return true;
- }
- return false;
- });
-
- if (spec.startsWith("www.")) {
- spec = spec.slice(4);
- }
- return spec;
-}
-
-function makeActionURI(action, params) {
- let encodedParams = {};
- for (let key in params) {
- encodedParams[key] = encodeURIComponent(params[key]);
- }
- let url = "moz-action:" + action + "," + JSON.stringify(encodedParams);
- return NetUtil.newURI(url);
-}
-
-// Creates a full "match" entry for a search result, suitable for passing as
-// an entry to check_autocomplete.
-function makeSearchMatch(input, extra = {}) {
- // Note that counter-intuitively, the order the object properties are defined
- // in the object passed to makeActionURI is important for check_autocomplete
- // to match them :(
- let params = {
- engineName: extra.engineName || "MozSearch",
- input,
- searchQuery: "searchQuery" in extra ? extra.searchQuery : input,
- };
- if ("alias" in extra) {
- // May be undefined, which is expected, but in that case make sure it's not
- // included in the params of the moz-action URL.
- params.alias = extra.alias;
- }
- let style = [ "action", "searchengine" ];
- if (Array.isArray(extra.style)) {
- style.push(...extra.style);
- }
- if (extra.heuristic) {
- style.push("heuristic");
- }
- return {
- uri: makeActionURI("searchengine", params),
- title: params.engineName,
- style,
- }
-}
-
-// Creates a full "match" entry for a search result, suitable for passing as
-// an entry to check_autocomplete.
-function makeVisitMatch(input, url, extra = {}) {
- // Note that counter-intuitively, the order the object properties are defined
- // in the object passed to makeActionURI is important for check_autocomplete
- // to match them :(
- let params = {
- url,
- input,
- }
- let style = [ "action", "visiturl" ];
- if (extra.heuristic) {
- style.push("heuristic");
- }
- return {
- uri: makeActionURI("visiturl", params),
- title: extra.title || url,
- style,
- }
-}
-
-function makeSwitchToTabMatch(url, extra = {}) {
- return {
- uri: makeActionURI("switchtab", {url}),
- title: extra.title || url,
- style: [ "action", "switchtab" ],
- }
-}
-
-function makeExtensionMatch(extra = {}) {
- let style = [ "action", "extension" ];
- if (extra.heuristic) {
- style.push("heuristic");
- }
-
- return {
- uri: makeActionURI("extension", {
- content: extra.content,
- keyword: extra.keyword,
- }),
- title: extra.description,
- style,
- };
-}
-
-function setFaviconForHref(href, iconHref) {
- return new Promise(resolve => {
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- NetUtil.newURI(href),
- NetUtil.newURI(iconHref),
- true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- resolve,
- Services.scriptSecurityManager.getSystemPrincipal()
- );
- });
-}
-
-function makeTestServer(port=-1) {
- let httpServer = new HttpServer();
- httpServer.start(port);
- do_register_cleanup(() => httpServer.stop(() => {}));
- return httpServer;
-}
-
-function* addTestEngine(basename, httpServer=undefined) {
- httpServer = httpServer || makeTestServer();
- httpServer.registerDirectory("/", do_get_cwd());
- let dataUrl =
- "http://localhost:" + httpServer.identity.primaryPort + "/data/";
-
- do_print("Adding engine: " + basename);
- return yield new Promise(resolve => {
- Services.obs.addObserver(function obs(subject, topic, data) {
- let engine = subject.QueryInterface(Ci.nsISearchEngine);
- do_print("Observed " + data + " for " + engine.name);
- if (data != "engine-added" || engine.name != basename) {
- return;
- }
-
- Services.obs.removeObserver(obs, "browser-search-engine-modified");
- do_register_cleanup(() => Services.search.removeEngine(engine));
- resolve(engine);
- }, "browser-search-engine-modified", false);
-
- do_print("Adding engine from URL: " + dataUrl + basename);
- Services.search.addEngine(dataUrl + basename, null, null, false);
- });
-}
-
-// Ensure we have a default search engine and the keyword.enabled preference
-// set.
-add_task(function* ensure_search_engine() {
- // keyword.enabled is necessary for the tests to see keyword searches.
- Services.prefs.setBoolPref("keyword.enabled", true);
-
- // Initialize the search service, but first set this geo IP pref to a dummy
- // string. When the search service is initialized, it contacts the URI named
- // in this pref, which breaks the test since outside connections aren't
- // allowed.
- let geoPref = "browser.search.geoip.url";
- Services.prefs.setCharPref(geoPref, "");
- do_register_cleanup(() => Services.prefs.clearUserPref(geoPref));
- yield new Promise(resolve => {
- Services.search.init(resolve);
- });
-
- // Remove any existing engines before adding ours.
- for (let engine of Services.search.getEngines()) {
- Services.search.removeEngine(engine);
- }
- Services.search.addEngineWithDetails("MozSearch", "", "", "", "GET",
- "http://s.example.com/search");
- let engine = Services.search.getEngineByName("MozSearch");
- Services.search.currentEngine = engine;
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_416211.js b/toolkit/components/places/tests/unifiedcomplete/test_416211.js
deleted file mode 100644
index e02906ddc..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_416211.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/. */
-
-/*
- * Test bug 416211 to make sure results that match the tag show the bookmark
- * title instead of the page title.
- */
-
-add_task(function* test_tag_match_has_bookmark_title() {
- do_print("Make sure the tag match gives the bookmark title");
- let uri = NetUtil.newURI("http://theuri/");
- yield PlacesTestUtils.addVisits({ uri: uri, title: "Page title" });
- yield addBookmark({ uri: uri,
- title: "Bookmark title",
- tags: [ "superTag" ]});
- yield check_autocomplete({
- search: "superTag",
- matches: [ { uri: uri, title: "Bookmark title", tags: [ "superTag" ], style: [ "bookmark-tag" ] } ]
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_416214.js b/toolkit/components/places/tests/unifiedcomplete/test_416214.js
deleted file mode 100644
index a30b3fe74..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_416214.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/. */
-
-/*
- * Test autocomplete for non-English URLs that match the tag bug 416214. Also
- * test bug 417441 by making sure escaped ascii characters like "+" remain
- * escaped.
- *
- * - add a visit for a page with a non-English URL
- * - add a tag for the page
- * - search for the tag
- * - test number of matches (should be exactly one)
- * - make sure the url is decoded
- */
-
-add_task(function* test_tag_match_url() {
- do_print("Make sure tag matches return the right url as well as '+' remain escaped");
- let uri1 = NetUtil.newURI("http://escaped/ユニコード");
- let uri2 = NetUtil.newURI("http://asciiescaped/blocking-firefox3%2B");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "title" },
- { uri: uri2, title: "title" }
- ]);
- yield addBookmark({ uri: uri1,
- title: "title",
- tags: [ "superTag" ],
- style: [ "bookmark-tag" ] });
- yield addBookmark({ uri: uri2,
- title: "title",
- tags: [ "superTag" ],
- style: [ "bookmark-tag" ] });
- yield check_autocomplete({
- search: "superTag",
- matches: [ { uri: uri1, title: "title", tags: [ "superTag" ], style: [ "bookmark-tag" ] },
- { uri: uri2, title: "title", tags: [ "superTag" ], style: [ "bookmark-tag" ] } ]
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_417798.js b/toolkit/components/places/tests/unifiedcomplete/test_417798.js
deleted file mode 100644
index bed14b2ce..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_417798.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for bug 417798 to make sure javascript: URIs don't show up unless the
- * user searches for javascript: explicitly.
- */
-
-add_task(function* test_javascript_match() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", false);
-
- let uri1 = NetUtil.newURI("http://abc/def");
- let uri2 = NetUtil.newURI("javascript:5");
- yield PlacesTestUtils.addVisits([ { uri: uri1, title: "Title with javascript:" } ]);
- yield addBookmark({ uri: uri2,
- title: "Title with javascript:" });
-
- do_print("Match non-javascript: with plain search");
- yield check_autocomplete({
- search: "a",
- matches: [ { uri: uri1, title: "Title with javascript:" } ]
- });
-
- do_print("Match non-javascript: with almost javascript:");
- yield check_autocomplete({
- search: "javascript",
- matches: [ { uri: uri1, title: "Title with javascript:" } ]
- });
-
- do_print("Match javascript:");
- yield check_autocomplete({
- search: "javascript:",
- matches: [ { uri: uri1, title: "Title with javascript:" },
- { uri: uri2, title: "Title with javascript:", style: [ "bookmark" ]} ]
- });
-
- do_print("Match nothing with non-first javascript:");
- yield check_autocomplete({
- search: "5 javascript:",
- matches: [ ]
- });
-
- do_print("Match javascript: with multi-word search");
- yield check_autocomplete({
- search: "javascript: 5",
- matches: [ { uri: uri2, title: "Title with javascript:", style: [ "bookmark" ]} ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_418257.js b/toolkit/components/places/tests/unifiedcomplete/test_418257.js
deleted file mode 100644
index 323c2a7af..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_418257.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test bug 418257 by making sure tags are returned with the title as part of
- * the "comment" if there are tags even if we didn't match in the tags. They
- * are separated from the title by a endash.
- */
-
-add_task(function* test_javascript_match() {
- let uri1 = NetUtil.newURI("http://page1");
- let uri2 = NetUtil.newURI("http://page2");
- let uri3 = NetUtil.newURI("http://page3");
- let uri4 = NetUtil.newURI("http://page4");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "tagged" },
- { uri: uri2, title: "tagged" },
- { uri: uri3, title: "tagged" },
- { uri: uri4, title: "tagged" }
- ]);
- yield addBookmark({ uri: uri1,
- title: "tagged",
- tags: [ "tag1" ] });
- yield addBookmark({ uri: uri2,
- title: "tagged",
- tags: [ "tag1", "tag2" ] });
- yield addBookmark({ uri: uri3,
- title: "tagged",
- tags: [ "tag1", "tag3" ] });
- yield addBookmark({ uri: uri4,
- title: "tagged",
- tags: [ "tag1", "tag2", "tag3" ] });
-
- do_print("Make sure tags come back in the title when matching tags");
- yield check_autocomplete({
- search: "page1 tag",
- matches: [ { uri: uri1, title: "tagged", tags: [ "tag1" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("Check tags in title for page2");
- yield check_autocomplete({
- search: "page2 tag",
- matches: [ { uri: uri2, title: "tagged", tags: [ "tag1", "tag2" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("Make sure tags appear even when not matching the tag");
- yield check_autocomplete({
- search: "page3",
- matches: [ { uri: uri3, title: "tagged", tags: [ "tag1", "tag3" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("Multiple tags come in commas for page4");
- yield check_autocomplete({
- search: "page4",
- matches: [ { uri: uri4, title: "tagged", tags: [ "tag1", "tag2", "tag3" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("Extra test just to make sure we match the title");
- yield check_autocomplete({
- search: "tag2",
- matches: [ { uri: uri2, title: "tagged", tags: [ "tag1", "tag2" ], style: [ "bookmark-tag" ] },
- { uri: uri4, title: "tagged", tags: [ "tag1", "tag2", "tag3" ], style: [ "bookmark-tag" ] } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_422277.js b/toolkit/components/places/tests/unifiedcomplete/test_422277.js
deleted file mode 100644
index df6f7601a..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_422277.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/. */
-
-/**
- * Test bug 422277 to make sure bad escaped uris don't get escaped. This makes
- * sure we don't hit an assertion for "not a UTF8 string".
- */
-
-add_task(function* test_javascript_match() {
- do_print("Bad escaped uri stays escaped");
- let uri1 = NetUtil.newURI("http://site/%EAid");
- yield PlacesTestUtils.addVisits([ { uri: uri1, title: "title" } ]);
- yield check_autocomplete({
- search: "site",
- matches: [ { uri: uri1, title: "title" } ]
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_autocomplete_functional.js b/toolkit/components/places/tests/unifiedcomplete/test_autocomplete_functional.js
deleted file mode 100644
index cd2dfdb17..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_autocomplete_functional.js
+++ /dev/null
@@ -1,171 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Functional tests for inline autocomplete
-
-const PREF_AUTOCOMPLETE_ENABLED = "browser.urlbar.autocomplete.enabled";
-
-add_task(function* test_disabling_autocomplete() {
- do_print("Check disabling autocomplete disables autofill");
- Services.prefs.setBoolPref(PREF_AUTOCOMPLETE_ENABLED, false);
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://visit.mozilla.org"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "vis",
- autofilled: "vis",
- completed: "vis"
- });
- yield cleanup();
-});
-
-add_task(function* test_urls_order() {
- do_print("Add urls, check for correct order");
- let places = [{ uri: NetUtil.newURI("http://visit1.mozilla.org") },
- { uri: NetUtil.newURI("http://visit2.mozilla.org"),
- transition: TRANSITION_TYPED }];
- yield PlacesTestUtils.addVisits(places);
- yield check_autocomplete({
- search: "vis",
- autofilled: "visit2.mozilla.org/",
- completed: "visit2.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_ignore_prefix() {
- do_print("Add urls, make sure www and http are ignored");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://www.visit1.mozilla.org"));
- yield check_autocomplete({
- search: "visit1",
- autofilled: "visit1.mozilla.org/",
- completed: "visit1.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_after_host() {
- do_print("Autocompleting after an existing host completes to the url");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://www.visit3.mozilla.org"));
- yield check_autocomplete({
- search: "visit3.mozilla.org/",
- autofilled: "visit3.mozilla.org/",
- completed: "visit3.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_respect_www() {
- do_print("Searching for www.me should yield www.me.mozilla.org/");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://www.me.mozilla.org"));
- yield check_autocomplete({
- search: "www.me",
- autofilled: "www.me.mozilla.org/",
- completed: "www.me.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_bookmark_first() {
- do_print("With a bookmark and history, the query result should be the bookmark");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield addBookmark({ uri: NetUtil.newURI("http://bookmark1.mozilla.org/") });
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://bookmark1.mozilla.org/foo"));
- yield check_autocomplete({
- search: "bookmark",
- autofilled: "bookmark1.mozilla.org/",
- completed: "bookmark1.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_full_path() {
- do_print("Check to make sure we get the proper results with full paths");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- let places = [{ uri: NetUtil.newURI("http://smokey.mozilla.org/foo/bar/baz?bacon=delicious") },
- { uri: NetUtil.newURI("http://smokey.mozilla.org/foo/bar/baz?bacon=smokey") }];
- yield PlacesTestUtils.addVisits(places);
- yield check_autocomplete({
- search: "smokey",
- autofilled: "smokey.mozilla.org/",
- completed: "smokey.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_complete_to_slash() {
- do_print("Check to make sure we autocomplete to the following '/'");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- let places = [{ uri: NetUtil.newURI("http://smokey.mozilla.org/foo/bar/baz?bacon=delicious") },
- { uri: NetUtil.newURI("http://smokey.mozilla.org/foo/bar/baz?bacon=smokey") }];
- yield PlacesTestUtils.addVisits(places);
- yield check_autocomplete({
- search: "smokey.mozilla.org/fo",
- autofilled: "smokey.mozilla.org/foo/",
- completed: "http://smokey.mozilla.org/foo/",
- });
- yield cleanup();
-});
-
-add_task(function* test_complete_to_slash_with_www() {
- do_print("Check to make sure we autocomplete to the following '/'");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- let places = [{ uri: NetUtil.newURI("http://www.smokey.mozilla.org/foo/bar/baz?bacon=delicious") },
- { uri: NetUtil.newURI("http://www.smokey.mozilla.org/foo/bar/baz?bacon=smokey") }];
- yield PlacesTestUtils.addVisits(places);
- yield check_autocomplete({
- search: "smokey.mozilla.org/fo",
- autofilled: "smokey.mozilla.org/foo/",
- completed: "http://www.smokey.mozilla.org/foo/",
- });
- yield cleanup();
-});
-
-add_task(function* test_complete_querystring() {
- do_print("Check to make sure we autocomplete after ?");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://smokey.mozilla.org/foo?bacon=delicious"));
- yield check_autocomplete({
- search: "smokey.mozilla.org/foo?",
- autofilled: "smokey.mozilla.org/foo?bacon=delicious",
- completed: "http://smokey.mozilla.org/foo?bacon=delicious",
- });
- yield cleanup();
-});
-
-add_task(function* test_complete_fragment() {
- do_print("Check to make sure we autocomplete after #");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://smokey.mozilla.org/foo?bacon=delicious#bar"));
- yield check_autocomplete({
- search: "smokey.mozilla.org/foo?bacon=delicious#bar",
- autofilled: "smokey.mozilla.org/foo?bacon=delicious#bar",
- completed: "http://smokey.mozilla.org/foo?bacon=delicious#bar",
- });
- yield cleanup();
-});
-
-add_task(function* test_autocomplete_enabled_pref() {
- Services.prefs.setBoolPref(PREF_AUTOCOMPLETE_ENABLED, false);
- let types = ["history", "bookmark", "openpage"];
- for (type of types) {
- do_check_eq(Services.prefs.getBoolPref("browser.urlbar.suggest." + type), false,
- "suggest." + type + "pref should be false");
- }
- Services.prefs.setBoolPref(PREF_AUTOCOMPLETE_ENABLED, true);
- for (type of types) {
- do_check_eq(Services.prefs.getBoolPref("browser.urlbar.suggest." + type), true,
- "suggest." + type + "pref should be true");
- }
-
- // Clear prefs.
- Services.prefs.clearUserPref(PREF_AUTOCOMPLETE_ENABLED);
- for (type of types) {
- Services.prefs.clearUserPref("browser.urlbar.suggest." + type);
- }
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_autocomplete_on_value_removed_479089.js b/toolkit/components/places/tests/unifiedcomplete/test_autocomplete_on_value_removed_479089.js
deleted file mode 100644
index ecc96266b..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_autocomplete_on_value_removed_479089.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * Need to test that removing a page from autocomplete actually removes a page
- * Description From Shawn Wilsher :sdwilsh 2009-02-18 11:29:06 PST
- * We don't test the code path of onValueRemoved
- * for the autocomplete implementation
- * Bug 479089
- */
-
-add_task(function* test_autocomplete_on_value_removed() {
- let listener = Cc["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"].
- getService(Components.interfaces.nsIAutoCompleteSimpleResultListener);
-
- let testUri = NetUtil.newURI("http://foo.mozilla.com/");
- yield PlacesTestUtils.addVisits({
- uri: testUri,
- referrer: uri("http://mozilla.com/")
- });
-
- let query = PlacesUtils.history.getNewQuery();
- let options = PlacesUtils.history.getNewQueryOptions();
- // look for this uri only
- query.uri = testUri;
-
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- Assert.equal(root.childCount, 1);
- // call the untested code path
- listener.onValueRemoved(null, testUri.spec, true);
- // make sure it is GONE from the DB
- Assert.equal(root.childCount, 0);
- // close the container
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_autofill_default_behavior.js b/toolkit/components/places/tests/unifiedcomplete/test_autofill_default_behavior.js
deleted file mode 100644
index 482fcf485..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_autofill_default_behavior.js
+++ /dev/null
@@ -1,310 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 autoFill for different default behaviors.
- */
-
-add_task(function* test_default_behavior_host() {
- let uri1 = NetUtil.newURI("http://typed/");
- let uri2 = NetUtil.newURI("http://visited/");
- let uri3 = NetUtil.newURI("http://bookmarked/");
- let uri4 = NetUtil.newURI("http://tpbk/");
- let uri5 = NetUtil.newURI("http://tagged/");
-
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "typed", transition: TRANSITION_TYPED },
- { uri: uri2, title: "visited" },
- { uri: uri4, title: "tpbk", transition: TRANSITION_TYPED },
- ]);
- yield addBookmark( { uri: uri3, title: "bookmarked" } );
- yield addBookmark( { uri: uri4, title: "tpbk" } );
- yield addBookmark( { uri: uri5, title: "title", tags: ["foo"] } );
-
- yield setFaviconForHref(uri1.spec, "chrome://global/skin/icons/information-16.png");
- yield setFaviconForHref(uri3.spec, "chrome://global/skin/icons/error-16.png");
-
- // RESTRICT TO HISTORY.
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.history.onlyTyped", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", false);
-
- do_print("Restrict history, common visit, should not autoFill");
- yield check_autocomplete({
- search: "vi",
- matches: [ { uri: uri2, title: "visited" } ],
- autofilled: "vi",
- completed: "vi"
- });
-
- do_print("Restrict history, typed visit, should autoFill");
- yield check_autocomplete({
- search: "ty",
- matches: [ { uri: uri1, title: "typed", style: [ "autofill", "heuristic" ],
- icon: "chrome://global/skin/icons/information-16.png" } ],
- autofilled: "typed/",
- completed: "typed/"
- });
-
- // Don't autoFill this one cause it's not typed.
- do_print("Restrict history, bookmark, should not autoFill");
- yield check_autocomplete({
- search: "bo",
- matches: [ ],
- autofilled: "bo",
- completed: "bo"
- });
-
- // Note we don't show this one cause it's not typed.
- do_print("Restrict history, typed bookmark, should autoFill");
- yield check_autocomplete({
- search: "tp",
- matches: [ { uri: uri4, title: "tpbk", style: [ "autofill", "heuristic" ] } ],
- autofilled: "tpbk/",
- completed: "tpbk/"
- });
-
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
-
- // We are not restricting on typed, so we autoFill the bookmark even if we
- // are restricted to history. We accept that cause not doing that
- // would be a perf hit and the privacy implications are very weak.
- do_print("Restrict history, bookmark, autoFill.typed = false, should autoFill");
- yield check_autocomplete({
- search: "bo",
- matches: [ { uri: uri3, title: "bookmarked", style: [ "autofill", "heuristic" ],
- icon: "chrome://global/skin/icons/error-16.png" } ],
- autofilled: "bookmarked/",
- completed: "bookmarked/"
- });
-
- do_print("Restrict history, common visit, autoFill.typed = false, should autoFill");
- yield check_autocomplete({
- search: "vi",
- matches: [ { uri: uri2, title: "visited", style: [ "autofill", "heuristic" ] } ],
- autofilled: "visited/",
- completed: "visited/"
- });
-
- // RESTRICT TO TYPED.
- // This should basically ignore autoFill.typed and acts as if it would be set.
- Services.prefs.setBoolPref("browser.urlbar.suggest.history.onlyTyped", true);
-
- // Typed behavior basically acts like history, but filters on typed.
- do_print("Restrict typed, common visit, autoFill.typed = false, should not autoFill");
- yield check_autocomplete({
- search: "vi",
- matches: [ ],
- autofilled: "vi",
- completed: "vi"
- });
-
- do_print("Restrict typed, typed visit, autofill.typed = false, should autoFill");
- yield check_autocomplete({
- search: "ty",
- matches: [ { uri: uri1, title: "typed", style: [ "autofill", "heuristic" ],
- icon: "chrome://global/skin/icons/information-16.png"} ],
- autofilled: "typed/",
- completed: "typed/"
- });
-
- do_print("Restrict typed, bookmark, autofill.typed = false, should not autoFill");
- yield check_autocomplete({
- search: "bo",
- matches: [ ],
- autofilled: "bo",
- completed: "bo"
- });
-
- do_print("Restrict typed, typed bookmark, autofill.typed = false, should autoFill");
- yield check_autocomplete({
- search: "tp",
- matches: [ { uri: uri4, title: "tpbk", style: [ "autofill", "heuristic" ] } ],
- autofilled: "tpbk/",
- completed: "tpbk/"
- });
-
- // RESTRICT BOOKMARKS.
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", true);
-
- do_print("Restrict bookmarks, common visit, should not autoFill");
- yield check_autocomplete({
- search: "vi",
- matches: [ ],
- autofilled: "vi",
- completed: "vi"
- });
-
- do_print("Restrict bookmarks, typed visit, should not autoFill");
- yield check_autocomplete({
- search: "ty",
- matches: [ ],
- autofilled: "ty",
- completed: "ty"
- });
-
- // Don't autoFill this one cause it's not typed.
- do_print("Restrict bookmarks, bookmark, should not autoFill");
- yield check_autocomplete({
- search: "bo",
- matches: [ { uri: uri3, title: "bookmarked", style: [ "bookmark" ],
- icon: "chrome://global/skin/icons/error-16.png"} ],
- autofilled: "bo",
- completed: "bo"
- });
-
- // Note we don't show this one cause it's not typed.
- do_print("Restrict bookmarks, typed bookmark, should autoFill");
- yield check_autocomplete({
- search: "tp",
- matches: [ { uri: uri4, title: "tpbk", style: [ "autofill", "heuristic" ] } ],
- autofilled: "tpbk/",
- completed: "tpbk/"
- });
-
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
-
- do_print("Restrict bookmarks, bookmark, autofill.typed = false, should autoFill");
- yield check_autocomplete({
- search: "bo",
- matches: [ { uri: uri3, title: "bookmarked", style: [ "autofill", "heuristic" ],
- icon: "chrome://global/skin/icons/error-16.png" } ],
- autofilled: "bookmarked/",
- completed: "bookmarked/"
- });
-
- // Don't autofill because it's a title.
- do_print("Restrict bookmarks, title, autofill.typed = false, should not autoFill");
- yield check_autocomplete({
- search: "# ta",
- matches: [ ],
- autofilled: "# ta",
- completed: "# ta"
- });
-
- // Don't autofill because it's a tag.
- do_print("Restrict bookmarks, tag, autofill.typed = false, should not autoFill");
- yield check_autocomplete({
- search: "+ ta",
- matches: [ { uri: uri5, title: "title", tags: [ "foo" ], style: [ "tag" ] } ],
- autofilled: "+ ta",
- completed: "+ ta"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_default_behavior_url() {
- let uri1 = NetUtil.newURI("http://typed/ty/");
- let uri2 = NetUtil.newURI("http://visited/vi/");
- let uri3 = NetUtil.newURI("http://bookmarked/bo/");
- let uri4 = NetUtil.newURI("http://tpbk/tp/");
-
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "typed", transition: TRANSITION_TYPED },
- { uri: uri2, title: "visited" },
- { uri: uri4, title: "tpbk", transition: TRANSITION_TYPED },
- ]);
- yield addBookmark( { uri: uri3, title: "bookmarked" } );
- yield addBookmark( { uri: uri4, title: "tpbk" } );
-
- yield setFaviconForHref(uri1.spec, "chrome://global/skin/icons/information-16.png");
- yield setFaviconForHref(uri3.spec, "chrome://global/skin/icons/error-16.png");
-
- // RESTRICT TO HISTORY.
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.history.onlyTyped", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", false);
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", true);
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", false);
-
- do_print("URL: Restrict history, common visit, should not autoFill");
- yield check_autocomplete({
- search: "visited/v",
- matches: [ { uri: uri2, title: "visited" } ],
- autofilled: "visited/v",
- completed: "visited/v"
- });
-
- do_print("URL: Restrict history, typed visit, should autoFill");
- yield check_autocomplete({
- search: "typed/t",
- matches: [ { uri: uri1, title: "typed/ty/", style: [ "autofill", "heuristic" ],
- icon: "chrome://global/skin/icons/information-16.png"} ],
- autofilled: "typed/ty/",
- completed: "http://typed/ty/"
- });
-
- // Don't autoFill this one cause it's not typed.
- do_print("URL: Restrict history, bookmark, should not autoFill");
- yield check_autocomplete({
- search: "bookmarked/b",
- matches: [ ],
- autofilled: "bookmarked/b",
- completed: "bookmarked/b"
- });
-
- // Note we don't show this one cause it's not typed.
- do_print("URL: Restrict history, typed bookmark, should autoFill");
- yield check_autocomplete({
- search: "tpbk/t",
- matches: [ { uri: uri4, title: "tpbk/tp/", style: [ "autofill", "heuristic" ] } ],
- autofilled: "tpbk/tp/",
- completed: "http://tpbk/tp/"
- });
-
- // RESTRICT BOOKMARKS.
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
-
- do_print("URL: Restrict bookmarks, common visit, should not autoFill");
- yield check_autocomplete({
- search: "visited/v",
- matches: [ ],
- autofilled: "visited/v",
- completed: "visited/v"
- });
-
- do_print("URL: Restrict bookmarks, typed visit, should not autoFill");
- yield check_autocomplete({
- search: "typed/t",
- matches: [ ],
- autofilled: "typed/t",
- completed: "typed/t"
- });
-
- // Don't autoFill this one cause it's not typed.
- do_print("URL: Restrict bookmarks, bookmark, should not autoFill");
- yield check_autocomplete({
- search: "bookmarked/b",
- matches: [ { uri: uri3, title: "bookmarked", style: [ "bookmark" ],
- icon: "chrome://global/skin/icons/error-16.png" } ],
- autofilled: "bookmarked/b",
- completed: "bookmarked/b"
- });
-
- // Note we don't show this one cause it's not typed.
- do_print("URL: Restrict bookmarks, typed bookmark, should autoFill");
- yield check_autocomplete({
- search: "tpbk/t",
- matches: [ { uri: uri4, title: "tpbk/tp/", style: [ "autofill", "heuristic" ] } ],
- autofilled: "tpbk/tp/",
- completed: "http://tpbk/tp/"
- });
-
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
-
- do_print("URL: Restrict bookmarks, bookmark, autofill.typed = false, should autoFill");
- yield check_autocomplete({
- search: "bookmarked/b",
- matches: [ { uri: uri3, title: "bookmarked/bo/", style: [ "autofill", "heuristic" ],
- icon: "chrome://global/skin/icons/error-16.png" } ],
- autofilled: "bookmarked/bo/",
- completed: "http://bookmarked/bo/"
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_avoid_middle_complete.js b/toolkit/components/places/tests/unifiedcomplete/test_avoid_middle_complete.js
deleted file mode 100644
index 54fc343ca..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_avoid_middle_complete.js
+++ /dev/null
@@ -1,179 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* test_prefix_space_noautofill() {
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://moz.org/test/"),
- transition: TRANSITION_TYPED
- });
-
- do_print("Should not try to autoFill if search string contains a space");
- yield check_autocomplete({
- search: " mo",
- autofilled: " mo",
- completed: " mo"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_trailing_space_noautofill() {
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://moz.org/test/"),
- transition: TRANSITION_TYPED
- });
-
- do_print("Should not try to autoFill if search string contains a space");
- yield check_autocomplete({
- search: "mo ",
- autofilled: "mo ",
- completed: "mo "
- });
-
- yield cleanup();
-});
-
-add_task(function* test_searchEngine_autofill() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", true);
- Services.search.addEngineWithDetails("CakeSearch", "", "", "",
- "GET", "http://cake.search/");
- let engine = Services.search.getEngineByName("CakeSearch");
- engine.addParam("q", "{searchTerms}", null);
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
- do_print("Should autoFill search engine if search string does not contains a space");
- yield check_autocomplete({
- search: "ca",
- autofilled: "cake.search",
- completed: "http://cake.search"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_searchEngine_prefix_space_noautofill() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", true);
- Services.search.addEngineWithDetails("CupcakeSearch", "", "", "",
- "GET", "http://cupcake.search/");
- let engine = Services.search.getEngineByName("CupcakeSearch");
- engine.addParam("q", "{searchTerms}", null);
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
- do_print("Should not try to autoFill search engine if search string contains a space");
- yield check_autocomplete({
- search: " cu",
- autofilled: " cu",
- completed: " cu"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_searchEngine_trailing_space_noautofill() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", true);
- Services.search.addEngineWithDetails("BaconSearch", "", "", "",
- "GET", "http://bacon.search/");
- let engine = Services.search.getEngineByName("BaconSearch");
- engine.addParam("q", "{searchTerms}", null);
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
- do_print("Should not try to autoFill search engine if search string contains a space");
- yield check_autocomplete({
- search: "ba ",
- autofilled: "ba ",
- completed: "ba "
- });
-
- yield cleanup();
-});
-
-add_task(function* test_searchEngine_www_noautofill() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", true);
- Services.search.addEngineWithDetails("HamSearch", "", "", "",
- "GET", "http://ham.search/");
- let engine = Services.search.getEngineByName("HamSearch");
- engine.addParam("q", "{searchTerms}", null);
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
- do_print("Should not autoFill search engine if search string contains www. but engine doesn't");
- yield check_autocomplete({
- search: "www.ham",
- autofilled: "www.ham",
- completed: "www.ham"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_searchEngine_different_scheme_noautofill() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", true);
- Services.search.addEngineWithDetails("PieSearch", "", "", "",
- "GET", "https://pie.search/");
- let engine = Services.search.getEngineByName("PieSearch");
- engine.addParam("q", "{searchTerms}", null);
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
- do_print("Should not autoFill search engine if search string has a different scheme.");
- yield check_autocomplete({
- search: "http://pie",
- autofilled: "http://pie",
- completed: "http://pie"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_searchEngine_matching_prefix_autofill() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", true);
- Services.search.addEngineWithDetails("BeanSearch", "", "", "",
- "GET", "http://www.bean.search/");
- let engine = Services.search.getEngineByName("BeanSearch");
- engine.addParam("q", "{searchTerms}", null);
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
-
- do_print("Should autoFill search engine if search string has matching prefix.");
- yield check_autocomplete({
- search: "http://www.be",
- autofilled: "http://www.bean.search",
- completed: "http://www.bean.search"
- })
-
- do_print("Should autoFill search engine if search string has www prefix.");
- yield check_autocomplete({
- search: "www.be",
- autofilled: "www.bean.search",
- completed: "http://www.bean.search"
- });
-
- do_print("Should autoFill search engine if search string has matching scheme.");
- yield check_autocomplete({
- search: "http://be",
- autofilled: "http://bean.search",
- completed: "http://www.bean.search"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_prefix_autofill() {
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://moz.org/test/"),
- transition: TRANSITION_TYPED
- });
-
- do_print("Should not try to autoFill in-the-middle if a search is canceled immediately");
- yield check_autocomplete({
- incompleteSearch: "moz",
- search: "mozi",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_avoid_stripping_to_empty_tokens.js b/toolkit/components/places/tests/unifiedcomplete/test_avoid_stripping_to_empty_tokens.js
deleted file mode 100644
index 1fcfe1c75..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_avoid_stripping_to_empty_tokens.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* test_protocol_trimming() {
- for (let prot of ["http", "https", "ftp"]) {
- let visit = {
- // Include the protocol in the query string to ensure we get matches (see bug 1059395)
- uri: NetUtil.newURI(prot + "://www.mozilla.org/test/?q=" + prot + encodeURIComponent("://") + "www.foo"),
- title: "Test title",
- transition: TRANSITION_TYPED
- };
- yield PlacesTestUtils.addVisits(visit);
- let matches = [{uri: visit.uri, title: visit.title}];
-
- let inputs = [
- prot + "://",
- prot + ":// ",
- prot + ":// mo",
- prot + "://mo te",
- prot + "://www.",
- prot + "://www. ",
- prot + "://www. mo",
- prot + "://www.mo te",
- "www.",
- "www. ",
- "www. mo",
- "www.mo te"
- ];
- for (let input of inputs) {
- do_print("Searching for: " + input);
- yield check_autocomplete({
- search: input,
- matches: matches
- });
- }
-
- yield cleanup();
- }
-});
-
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_casing.js b/toolkit/components/places/tests/unifiedcomplete/test_casing.js
deleted file mode 100644
index 585b51be1..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_casing.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* test_casing_1() {
- do_print("Searching for cased entry 1");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "MOZ",
- autofilled: "MOZilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_casing_2() {
- do_print("Searching for cased entry 2");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/T",
- autofilled: "mozilla.org/T",
- completed: "mozilla.org/T"
- });
- yield cleanup();
-});
-
-add_task(function* test_casing_3() {
- do_print("Searching for cased entry 3");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/T",
- autofilled: "mozilla.org/Test/",
- completed: "http://mozilla.org/Test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_casing_4() {
- do_print("Searching for cased entry 4");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mOzilla.org/t",
- autofilled: "mOzilla.org/t",
- completed: "mOzilla.org/t"
- });
- yield cleanup();
-});
-
-add_task(function* test_casing_5() {
- do_print("Searching for cased entry 5");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mOzilla.org/T",
- autofilled: "mOzilla.org/Test/",
- completed: "http://mozilla.org/Test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_casing() {
- do_print("Searching for untrimmed cased entry");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "http://mOz",
- autofilled: "http://mOzilla.org/",
- completed: "http://mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_www_casing() {
- do_print("Searching for untrimmed cased entry with www");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://www.mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "http://www.mOz",
- autofilled: "http://www.mOzilla.org/",
- completed: "http://www.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_path_casing() {
- do_print("Searching for untrimmed cased entry with path");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "http://mOzilla.org/t",
- autofilled: "http://mOzilla.org/t",
- completed: "http://mOzilla.org/t"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_path_casing_2() {
- do_print("Searching for untrimmed cased entry with path 2");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "http://mOzilla.org/T",
- autofilled: "http://mOzilla.org/Test/",
- completed: "http://mozilla.org/Test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_path_www_casing() {
- do_print("Searching for untrimmed cased entry with www and path");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://www.mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "http://www.mOzilla.org/t",
- autofilled: "http://www.mOzilla.org/t",
- completed: "http://www.mOzilla.org/t"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_path_www_casing_2() {
- do_print("Searching for untrimmed cased entry with www and path 2");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://www.mozilla.org/Test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "http://www.mOzilla.org/T",
- autofilled: "http://www.mOzilla.org/Test/",
- completed: "http://www.mozilla.org/Test/"
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_do_not_trim.js b/toolkit/components/places/tests/unifiedcomplete/test_do_not_trim.js
deleted file mode 100644
index 014d74998..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_do_not_trim.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Inline should never return matches shorter than the search string, since
-// that largely confuses completeDefaultIndex
-
-add_task(function* test_not_autofill_ws_1() {
- do_print("Do not autofill whitespaced entry 1");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/link/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org ",
- autofilled: "mozilla.org ",
- completed: "mozilla.org "
- });
- yield cleanup();
-});
-
-add_task(function* test_not_autofill_ws_2() {
- do_print("Do not autofill whitespaced entry 2");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/link/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/ ",
- autofilled: "mozilla.org/ ",
- completed: "mozilla.org/ "
- });
- yield cleanup();
-});
-
-add_task(function* test_not_autofill_ws_3() {
- do_print("Do not autofill whitespaced entry 3");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/link/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/link ",
- autofilled: "mozilla.org/link ",
- completed: "mozilla.org/link "
- });
- yield cleanup();
-});
-
-add_task(function* test_not_autofill_ws_4() {
- do_print("Do not autofill whitespaced entry 4");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/link/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/link/ ",
- autofilled: "mozilla.org/link/ ",
- completed: "mozilla.org/link/ "
- });
- yield cleanup();
-});
-
-
-add_task(function* test_not_autofill_ws_5() {
- do_print("Do not autofill whitespaced entry 5");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/link/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "moz illa ",
- autofilled: "moz illa ",
- completed: "moz illa "
- });
- yield cleanup();
-});
-
-add_task(function* test_not_autofill_ws_6() {
- do_print("Do not autofill whitespaced entry 6");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/link/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: " mozilla",
- autofilled: " mozilla",
- completed: " mozilla"
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_download_embed_bookmarks.js b/toolkit/components/places/tests/unifiedcomplete/test_download_embed_bookmarks.js
deleted file mode 100644
index 72661d075..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_download_embed_bookmarks.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim:set ts=2 sw=2 sts=2 et:
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Tests bug 449406 to ensure that TRANSITION_DOWNLOAD, TRANSITION_EMBED and
- * TRANSITION_FRAMED_LINK bookmarked uri's show up in the location bar.
- */
-
-add_task(function* test_download_embed_bookmarks() {
- let uri1 = NetUtil.newURI("http://download/bookmarked");
- let uri2 = NetUtil.newURI("http://embed/bookmarked");
- let uri3 = NetUtil.newURI("http://framed/bookmarked");
- let uri4 = NetUtil.newURI("http://download");
- let uri5 = NetUtil.newURI("http://embed");
- let uri6 = NetUtil.newURI("http://framed");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "download-bookmark", transition: TRANSITION_DOWNLOAD },
- { uri: uri2, title: "embed-bookmark", transition: TRANSITION_EMBED },
- { uri: uri3, title: "framed-bookmark", transition: TRANSITION_FRAMED_LINK},
- { uri: uri4, title: "download2", transition: TRANSITION_DOWNLOAD },
- { uri: uri5, title: "embed2", transition: TRANSITION_EMBED },
- { uri: uri6, title: "framed2", transition: TRANSITION_FRAMED_LINK }
- ]);
- yield addBookmark({ uri: uri1,
- title: "download-bookmark" });
- yield addBookmark({ uri: uri2,
- title: "embed-bookmark" });
- yield addBookmark({ uri: uri3,
- title: "framed-bookmark" });
-
- do_print("Searching for bookmarked download uri matches");
- yield check_autocomplete({
- search: "download-bookmark",
- matches: [ { uri: uri1, title: "download-bookmark", style: [ "bookmark" ] } ]
- });
-
- do_print("Searching for bookmarked embed uri matches");
- yield check_autocomplete({
- search: "embed-bookmark",
- matches: [ { uri: uri2, title: "embed-bookmark", style: [ "bookmark" ] } ]
- });
-
- do_print("Searching for bookmarked framed uri matches");
- yield check_autocomplete({
- search: "framed-bookmark",
- matches: [ { uri: uri3, title: "framed-bookmark", style: [ "bookmark" ] } ]
- });
-
- do_print("Searching for download uri does not match");
- yield check_autocomplete({
- search: "download2",
- matches: [ ]
- });
-
- do_print("Searching for embed uri does not match");
- yield check_autocomplete({
- search: "embed2",
- matches: [ ]
- });
-
- do_print("Searching for framed uri does not match");
- yield check_autocomplete({
- search: "framed2",
- matches: [ ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_dupe_urls.js b/toolkit/components/places/tests/unifiedcomplete/test_dupe_urls.js
deleted file mode 100644
index a39c15236..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_dupe_urls.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Ensure inline autocomplete doesn't return zero frecency pages.
-
-add_task(function* test_dupe_urls() {
- do_print("Searching for urls with dupes should only show one");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/"),
- transition: TRANSITION_TYPED
- }, {
- uri: NetUtil.newURI("http://mozilla.org/?")
- });
- yield check_autocomplete({
- search: "moz",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/",
- matches: [ { uri: NetUtil.newURI("http://mozilla.org/"),
- title: "mozilla.org",
- style: [ "autofill", "heuristic" ] } ]
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_empty_search.js b/toolkit/components/places/tests/unifiedcomplete/test_empty_search.js
deleted file mode 100644
index ef1159705..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_empty_search.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for bug 426864 that makes sure the empty search (drop down list) only
- * shows typed pages from history.
- */
-
-add_task(function* test_javascript_match() {
- let uri1 = NetUtil.newURI("http://t.foo/0");
- let uri2 = NetUtil.newURI("http://t.foo/1");
- let uri3 = NetUtil.newURI("http://t.foo/2");
- let uri4 = NetUtil.newURI("http://t.foo/3");
- let uri5 = NetUtil.newURI("http://t.foo/4");
- let uri6 = NetUtil.newURI("http://t.foo/5");
- let uri7 = NetUtil.newURI("http://t.foo/6");
-
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "title" },
- { uri: uri2, title: "title" },
- { uri: uri3, title: "title", transition: TRANSITION_TYPED},
- { uri: uri4, title: "title", transition: TRANSITION_TYPED },
- { uri: uri6, title: "title", transition: TRANSITION_TYPED },
- { uri: uri7, title: "title" }
- ]);
-
- yield addBookmark({ uri: uri2,
- title: "title" });
- yield addBookmark({ uri: uri4,
- title: "title" });
- yield addBookmark({ uri: uri5,
- title: "title" });
- yield addBookmark({ uri: uri6,
- title: "title" });
-
- addOpenPages(uri7, 1);
-
- // Now remove page 6 from history, so it is an unvisited bookmark.
- PlacesUtils.history.removePage(uri6);
-
- do_print("Match everything");
- yield check_autocomplete({
- search: "foo",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("foo", { heuristic: true }),
- { uri: uri1, title: "title" },
- { uri: uri2, title: "title", style: ["bookmark"] },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "title", style: ["bookmark"] },
- { uri: uri5, title: "title", style: ["bookmark"] },
- { uri: uri6, title: "title", style: ["bookmark"] },
- makeSwitchToTabMatch("http://t.foo/6", { title: "title" }),
- ]
- });
-
- // Note the next few tests do *not* get a search result as enable-actions
- // isn't specified.
- do_print("Match only typed history");
- yield check_autocomplete({
- search: "foo ^ ~",
- matches: [ { uri: uri3, title: "title" },
- { uri: uri4, title: "title" } ]
- });
-
- do_print("Drop-down empty search matches only typed history");
- yield check_autocomplete({
- search: "",
- matches: [ { uri: uri3, title: "title" },
- { uri: uri4, title: "title" } ]
- });
-
- do_print("Drop-down empty search matches only bookmarks");
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
- yield check_autocomplete({
- search: "",
- matches: [ { uri: uri2, title: "title", style: ["bookmark"] },
- { uri: uri4, title: "title", style: ["bookmark"] },
- { uri: uri5, title: "title", style: ["bookmark"] },
- { uri: uri6, title: "title", style: ["bookmark"] } ]
- });
-
- do_print("Drop-down empty search matches only open tabs");
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", false);
- yield check_autocomplete({
- search: "",
- searchParam: "enable-actions",
- matches: [
- makeSwitchToTabMatch("http://t.foo/6", { title: "title" }),
- ]
- });
-
- Services.prefs.clearUserPref("browser.urlbar.suggest.history");
- Services.prefs.clearUserPref("browser.urlbar.suggest.bookmark");
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_enabled.js b/toolkit/components/places/tests/unifiedcomplete/test_enabled.js
deleted file mode 100644
index dee8df8ec..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_enabled.js
+++ /dev/null
@@ -1,68 +0,0 @@
-add_task(function* test_enabled() {
- // Test for bug 471903 to make sure searching in autocomplete can be turned on
- // and off. Also test bug 463535 for pref changing search.
- let uri = NetUtil.newURI("http://url/0");
- yield PlacesTestUtils.addVisits([ { uri: uri, title: "title" } ]);
-
- do_print("plain search");
- yield check_autocomplete({
- search: "url",
- matches: [ { uri: uri, title: "title" } ]
- });
-
- do_print("search disabled");
- Services.prefs.setBoolPref("browser.urlbar.autocomplete.enabled", false);
- yield check_autocomplete({
- search: "url",
- matches: [ ]
- });
-
- do_print("resume normal search");
- Services.prefs.setBoolPref("browser.urlbar.autocomplete.enabled", true);
- yield check_autocomplete({
- search: "url",
- matches: [ { uri: uri, title: "title" } ]
- });
-
- yield cleanup();
-});
-
-add_task(function* test_sync_enabled() {
- // Initialize unified complete.
- Cc["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"]
- .getService(Ci.mozIPlacesAutoComplete);
-
- let types = [ "history", "bookmark", "openpage", "searches" ];
-
- // Test the service keeps browser.urlbar.autocomplete.enabled synchronized
- // with browser.urlbar.suggest prefs.
- for (let type of types) {
- Services.prefs.setBoolPref("browser.urlbar.suggest." + type, true);
- }
- Assert.equal(Services.prefs.getBoolPref("browser.urlbar.autocomplete.enabled"), true);
-
- // Disable autocomplete and check all the suggest prefs are set to false.
- Services.prefs.setBoolPref("browser.urlbar.autocomplete.enabled", false);
- for (let type of types) {
- Assert.equal(Services.prefs.getBoolPref("browser.urlbar.suggest." + type), false);
- }
-
- // Setting even a single suggest pref to true should enable autocomplete.
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- for (let type of types.filter(t => t != "history")) {
- Assert.equal(Services.prefs.getBoolPref("browser.urlbar.suggest." + type), false);
- }
- Assert.equal(Services.prefs.getBoolPref("browser.urlbar.autocomplete.enabled"), true);
-
- // Disable autocoplete again, then re-enable it and check suggest prefs
- // have been reset.
- Services.prefs.setBoolPref("browser.urlbar.autocomplete.enabled", false);
- Services.prefs.setBoolPref("browser.urlbar.autocomplete.enabled", true);
- for (let type of types.filter(t => t != "history")) {
- if (type == "searches") {
- Assert.equal(Services.prefs.getBoolPref("browser.urlbar.suggest." + type), false);
- } else {
- Assert.equal(Services.prefs.getBoolPref("browser.urlbar.suggest." + type), true);
- }
- }
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_escape_self.js b/toolkit/components/places/tests/unifiedcomplete/test_escape_self.js
deleted file mode 100644
index ff6e5f929..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_escape_self.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test bug 422698 to make sure searches with urls from the location bar
- * correctly match itself when it contains escaped characters.
- */
-
-add_task(function* test_escape() {
- let uri1 = NetUtil.newURI("http://unescapeduri/");
- let uri2 = NetUtil.newURI("http://escapeduri/%40/");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "title" },
- { uri: uri2, title: "title" }
- ]);
-
- do_print("Unescaped location matches itself");
- yield check_autocomplete({
- search: "http://unescapeduri/",
- matches: [ { uri: uri1, title: "title" } ]
- });
-
- do_print("Escaped location matches itself");
- yield check_autocomplete({
- search: "http://escapeduri/%40/",
- matches: [ { uri: uri2, title: "title" } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_extension_matches.js b/toolkit/components/places/tests/unifiedcomplete/test_extension_matches.js
deleted file mode 100644
index 76af20558..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_extension_matches.js
+++ /dev/null
@@ -1,384 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim:set ts=2 sw=2 sts=2 et:
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Cu.import("resource://gre/modules/ExtensionSearchHandler.jsm");
-
-let controller = Cc["@mozilla.org/autocomplete/controller;1"].getService(Ci.nsIAutoCompleteController);
-
-add_task(function* test_correct_errors_are_thrown() {
- let keyword = "foo";
- let anotherKeyword = "bar";
- let unregisteredKeyword = "baz";
-
- // Register a keyword.
- ExtensionSearchHandler.registerKeyword(keyword, { emit: () => {} });
-
- // Try registering the keyword again.
- Assert.throws(() => ExtensionSearchHandler.registerKeyword(keyword, { emit: () => {} }));
-
- // Register a different keyword.
- ExtensionSearchHandler.registerKeyword(anotherKeyword, { emit: () => {} });
-
- // Try calling handleSearch for an unregistered keyword.
- Assert.throws(() => ExtensionSearchHandler.handleSearch(unregisteredKeyword, `${unregisteredKeyword} `, () => {}));
-
- // Try calling handleSearch without a callback.
- Assert.throws(() => ExtensionSearchHandler.handleSearch(unregisteredKeyword, `${unregisteredKeyword} `));
-
- // Try getting the description for a keyword which isn't registered.
- Assert.throws(() => ExtensionSearchHandler.getDescription(unregisteredKeyword));
-
- // Try getting the extension name for a keyword which isn't registered.
- Assert.throws(() => ExtensionSearchHandler.getExtensionName(unregisteredKeyword));
-
- // Try setting the default suggestion for a keyword which isn't registered.
- Assert.throws(() => ExtensionSearchHandler.setDefaultSuggestion(unregisteredKeyword, "suggestion"));
-
- // Try calling handleInputCancelled when there is no active input session.
- Assert.throws(() => ExtensionSearchHandler.handleInputCancelled());
-
- // Try calling handleInputEntered when there is no active input session.
- Assert.throws(() => ExtensionSearchHandler.handleInputEntered(anotherKeyword, `${anotherKeyword} test`, "tab"));
-
- // Start a session by calling handleSearch with the registered keyword.
- ExtensionSearchHandler.handleSearch(keyword, `${keyword} test`, () => {});
-
- // Try providing suggestions for an unregistered keyword.
- Assert.throws(() => ExtensionSearchHandler.addSuggestions(unregisteredKeyword, 0, []));
-
- // Try providing suggestions for an inactive keyword.
- Assert.throws(() => ExtensionSearchHandler.addSuggestions(anotherKeyword, 0, []));
-
- // Try calling handleSearch for an inactive keyword.
- Assert.throws(() => ExtensionSearchHandler.handleSearch(anotherKeyword, `${anotherKeyword} `, () => {}));
-
- // Try calling addSuggestions with an old callback ID.
- Assert.throws(() => ExtensionSearchHandler.addSuggestions(keyword, 0, []));
-
- // Add suggestions with a valid callback ID.
- ExtensionSearchHandler.addSuggestions(keyword, 1, []);
-
- // Add suggestions again with a valid callback ID.
- ExtensionSearchHandler.addSuggestions(keyword, 1, []);
-
- // Try calling addSuggestions with a future callback ID.
- Assert.throws(() => ExtensionSearchHandler.addSuggestions(keyword, 2, []));
-
- // End the input session by calling handleInputCancelled.
- ExtensionSearchHandler.handleInputCancelled();
-
- // Try calling handleInputCancelled after the session has ended.
- Assert.throws(() => ExtensionSearchHandler.handleInputCancelled());
-
- // Try calling handleSearch that doesn't have a space after the keyword.
- Assert.throws(() => ExtensionSearchHandler.handleSearch(anotherKeyword, `${anotherKeyword}`, () => {}));
-
- // Try calling handleSearch with text starting with the wrong keyword.
- Assert.throws(() => ExtensionSearchHandler.handleSearch(anotherKeyword, `${keyword} test`, () => {}));
-
- // Start a new session by calling handleSearch with a different keyword
- ExtensionSearchHandler.handleSearch(anotherKeyword, `${anotherKeyword} test`, () => {});
-
- // Try adding suggestions again with the same callback ID now that the input session has ended.
- Assert.throws(() => ExtensionSearchHandler.addSuggestions(keyword, 1, []));
-
- // Add suggestions with a valid callback ID.
- ExtensionSearchHandler.addSuggestions(anotherKeyword, 2, []);
-
- // Try adding suggestions with a valid callback ID but a different keyword.
- Assert.throws(() => ExtensionSearchHandler.addSuggestions(keyword, 2, []));
-
- // Try adding suggestions with a valid callback ID but an unregistered keyword.
- Assert.throws(() => ExtensionSearchHandler.addSuggestions(unregisteredKeyword, 2, []));
-
- // Set the default suggestion.
- ExtensionSearchHandler.setDefaultSuggestion(anotherKeyword, {description: "test result"});
-
- // Try ending the session using handleInputEntered with a different keyword.
- Assert.throws(() => ExtensionSearchHandler.handleInputEntered(keyword, `${keyword} test`, "tab"));
-
- // Try calling handleInputEntered with invalid text.
- Assert.throws(() => ExtensionSearchHandler.handleInputEntered(anotherKeyword, ` test`, "tab"));
-
- // Try calling handleInputEntered with an invalid disposition.
- Assert.throws(() => ExtensionSearchHandler.handleInputEntered(anotherKeyword, `${anotherKeyword} test`, "invalid"));
-
- // End the session by calling handleInputEntered.
- ExtensionSearchHandler.handleInputEntered(anotherKeyword, `${anotherKeyword} test`, "tab");
-
- // Try calling handleInputEntered after the session has ended.
- Assert.throws(() => ExtensionSearchHandler.handleInputEntered(anotherKeyword, `${anotherKeyword} test`, "tab"));
-
- // Unregister the keyword.
- ExtensionSearchHandler.unregisterKeyword(keyword);
-
- // Try setting the default suggestion for the unregistered keyword.
- Assert.throws(() => ExtensionSearchHandler.setDefaultSuggestion(keyword, {description: "test"}));
-
- // Try handling a search with the unregistered keyword.
- Assert.throws(() => ExtensionSearchHandler.handleSearch(keyword, `${keyword} test`, () => {}));
-
- // Try unregistering the keyword again.
- Assert.throws(() => ExtensionSearchHandler.unregisterKeyword(keyword));
-
- // Unregister the other keyword.
- ExtensionSearchHandler.unregisterKeyword(anotherKeyword);
-
- // Try unregistering the word which was never registered.
- Assert.throws(() => ExtensionSearchHandler.unregisterKeyword(unregisteredKeyword));
-
- // Try setting the default suggestion for a word that was never registered.
- Assert.throws(() => ExtensionSearchHandler.setDefaultSuggestion(unregisteredKeyword, {description: "test"}));
-
- yield cleanup();
-});
-
-add_task(function* test_correct_events_are_emitted() {
- let events = [];
- function checkEvents(expectedEvents) {
- Assert.equal(events.length, expectedEvents.length, "The correct number of events fired");
- expectedEvents.forEach((e, i) => Assert.equal(e, events[i], `Expected "${e}" event to fire`));
- events = [];
- }
-
- let mockExtension = { emit: message => events.push(message) };
-
- let keyword = "foo";
- let anotherKeyword = "bar";
-
- ExtensionSearchHandler.registerKeyword(keyword, mockExtension);
- ExtensionSearchHandler.registerKeyword(anotherKeyword, mockExtension);
-
- ExtensionSearchHandler.handleSearch(keyword, `${keyword} `, () => {});
- checkEvents([ExtensionSearchHandler.MSG_INPUT_STARTED]);
-
- ExtensionSearchHandler.handleSearch(keyword, `${keyword} f`, () => {});
- checkEvents([ExtensionSearchHandler.MSG_INPUT_CHANGED]);
-
- ExtensionSearchHandler.handleInputEntered(keyword, `${keyword} f`, "tab");
- checkEvents([ExtensionSearchHandler.MSG_INPUT_ENTERED]);
-
- ExtensionSearchHandler.handleSearch(keyword, `${keyword} f`, () => {});
- checkEvents([
- ExtensionSearchHandler.MSG_INPUT_STARTED,
- ExtensionSearchHandler.MSG_INPUT_CHANGED
- ]);
-
- ExtensionSearchHandler.handleInputCancelled();
- checkEvents([ExtensionSearchHandler.MSG_INPUT_CANCELLED]);
-
- ExtensionSearchHandler.handleSearch(anotherKeyword, `${anotherKeyword} baz`, () => {});
- checkEvents([
- ExtensionSearchHandler.MSG_INPUT_STARTED,
- ExtensionSearchHandler.MSG_INPUT_CHANGED
- ]);
-
- ExtensionSearchHandler.handleInputEntered(anotherKeyword, `${anotherKeyword} baz`, "tab");
- checkEvents([ExtensionSearchHandler.MSG_INPUT_ENTERED]);
-
- ExtensionSearchHandler.unregisterKeyword(keyword);
-});
-
-add_task(function* test_removes_suggestion_if_its_content_is_typed_in() {
- let keyword = "test";
- let extensionName = "Foo Bar";
-
- let mockExtension = {
- name: extensionName,
- emit(message, text, id) {
- if (message === ExtensionSearchHandler.MSG_INPUT_CHANGED) {
- ExtensionSearchHandler.addSuggestions(keyword, id, [
- {content: "foo", description: "first suggestion"},
- {content: "bar", description: "second suggestion"},
- {content: "baz", description: "third suggestion"},
- ]);
- controller.stopSearch();
- }
- }
- };
-
- ExtensionSearchHandler.registerKeyword(keyword, mockExtension);
-
- yield check_autocomplete({
- search: `${keyword} unmatched`,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: extensionName, content: `${keyword} unmatched`}),
- makeExtensionMatch({keyword, content: `${keyword} foo`, description: "first suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} bar`, description: "second suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} baz`, description: "third suggestion"})
- ]
- });
-
- yield check_autocomplete({
- search: `${keyword} foo`,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: extensionName, content: `${keyword} foo`}),
- makeExtensionMatch({keyword, content: `${keyword} bar`, description: "second suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} baz`, description: "third suggestion"})
- ]
- });
-
- yield check_autocomplete({
- search: `${keyword} bar`,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: extensionName, content: `${keyword} bar`}),
- makeExtensionMatch({keyword, content: `${keyword} foo`, description: "first suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} baz`, description: "third suggestion"})
- ]
- });
-
- yield check_autocomplete({
- search: `${keyword} baz`,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: extensionName, content: `${keyword} baz`}),
- makeExtensionMatch({keyword, content: `${keyword} foo`, description: "first suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} bar`, description: "second suggestion"})
- ]
- });
-
- ExtensionSearchHandler.unregisterKeyword(keyword);
- yield cleanup();
-});
-
-add_task(function* test_extension_results_should_come_first() {
- let keyword = "test";
- let extensionName = "Omnibox Example";
-
- let uri = NetUtil.newURI(`http://a.com/b`);
- yield PlacesTestUtils.addVisits([
- { uri, title: `${keyword} -` },
- ]);
-
- let mockExtension = {
- name: extensionName,
- emit(message, text, id) {
- if (message === ExtensionSearchHandler.MSG_INPUT_CHANGED) {
- ExtensionSearchHandler.addSuggestions(keyword, id, [
- {content: "foo", description: "first suggestion"},
- {content: "bar", description: "second suggestion"},
- {content: "baz", description: "third suggestion"},
- ]);
- }
- controller.stopSearch();
- }
- };
-
- ExtensionSearchHandler.registerKeyword(keyword, mockExtension);
-
- // Start an input session before testing MSG_INPUT_CHANGED.
- ExtensionSearchHandler.handleSearch(keyword, `${keyword} `, () => {});
-
- yield check_autocomplete({
- search: `${keyword} -`,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: extensionName, content: `${keyword} -`}),
- makeExtensionMatch({keyword, content: `${keyword} foo`, description: "first suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} bar`, description: "second suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} baz`, description: "third suggestion"}),
- { uri, title: `${keyword} -` }
- ]
- });
-
- ExtensionSearchHandler.unregisterKeyword(keyword);
- yield cleanup();
-});
-
-add_task(function* test_setting_the_default_suggestion() {
- let keyword = "test";
- let extensionName = "Omnibox Example";
-
- let mockExtension = {
- name: extensionName,
- emit(message, text, id) {
- if (message === ExtensionSearchHandler.MSG_INPUT_CHANGED) {
- ExtensionSearchHandler.addSuggestions(keyword, id, []);
- }
- controller.stopSearch();
- }
- };
-
- ExtensionSearchHandler.registerKeyword(keyword, mockExtension);
-
- ExtensionSearchHandler.setDefaultSuggestion(keyword, {
- description: "hello world"
- });
-
- let searchString = `${keyword} search query`;
- yield check_autocomplete({
- search: searchString,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: "hello world", content: searchString}),
- ]
- });
-
- ExtensionSearchHandler.setDefaultSuggestion(keyword, {
- description: "foo bar"
- });
-
- yield check_autocomplete({
- search: searchString,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: "foo bar", content: searchString}),
- ]
- });
-
- ExtensionSearchHandler.unregisterKeyword(keyword);
- yield cleanup();
-});
-
-add_task(function* test_maximum_number_of_suggestions_is_enforced() {
- let keyword = "test";
- let extensionName = "Omnibox Example";
-
- let mockExtension = {
- name: extensionName,
- emit(message, text, id) {
- if (message === ExtensionSearchHandler.MSG_INPUT_CHANGED) {
- ExtensionSearchHandler.addSuggestions(keyword, id, [
- {content: "a", description: "first suggestion"},
- {content: "b", description: "second suggestion"},
- {content: "c", description: "third suggestion"},
- {content: "d", description: "fourth suggestion"},
- {content: "e", description: "fifth suggestion"},
- {content: "f", description: "sixth suggestion"},
- {content: "g", description: "seventh suggestion"},
- {content: "h", description: "eigth suggestion"},
- {content: "i", description: "ninth suggestion"},
- {content: "j", description: "tenth suggestion"},
- ]);
- controller.stopSearch();
- }
- }
- };
-
- ExtensionSearchHandler.registerKeyword(keyword, mockExtension);
-
- // Start an input session before testing MSG_INPUT_CHANGED.
- ExtensionSearchHandler.handleSearch(keyword, `${keyword} `, () => {});
-
- yield check_autocomplete({
- search: `${keyword} #`,
- searchParam: "enable-actions",
- matches: [
- makeExtensionMatch({heuristic: true, keyword, description: extensionName, content: `${keyword} #`}),
- makeExtensionMatch({keyword, content: `${keyword} a`, description: "first suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} b`, description: "second suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} c`, description: "third suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} d`, description: "fourth suggestion"}),
- makeExtensionMatch({keyword, content: `${keyword} e`, description: "fifth suggestion"}),
- ]
- });
-
- ExtensionSearchHandler.unregisterKeyword(keyword);
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_ignore_protocol.js b/toolkit/components/places/tests/unifiedcomplete/test_ignore_protocol.js
deleted file mode 100644
index 92e7f601a..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_ignore_protocol.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/. */
-
-/**
- * Test bug 424509 to make sure searching for "h" doesn't match "http" of urls.
- */
-
-add_task(function* test_escape() {
- let uri1 = NetUtil.newURI("http://site/");
- let uri2 = NetUtil.newURI("http://happytimes/");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "title" },
- { uri: uri2, title: "title" }
- ]);
-
- do_print("Searching for h matches site and not http://");
- yield check_autocomplete({
- search: "h",
- matches: [ { uri: uri2, title: "title" } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_keyword_search.js b/toolkit/components/places/tests/unifiedcomplete/test_keyword_search.js
deleted file mode 100644
index 12b7fea77..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_keyword_search.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/. */
-
-/**
- * Test for bug 392143 that puts keyword results into the autocomplete. Makes
- * sure that multiple parameter queries get spaces converted to +, + converted
- * to %2B, non-ascii become escaped, and pages in history that match the
- * keyword uses the page's title.
- *
- * Also test for bug 249468 by making sure multiple keyword bookmarks with the
- * same keyword appear in the list.
- */
-
-add_task(function* test_keyword_searc() {
- let uri1 = NetUtil.newURI("http://abc/?search=%s");
- let uri2 = NetUtil.newURI("http://abc/?search=ThisPageIsInHistory");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "Generic page title" },
- { uri: uri2, title: "Generic page title" }
- ]);
- yield addBookmark({ uri: uri1, title: "Bookmark title", keyword: "key"});
-
- do_print("Plain keyword query");
- yield check_autocomplete({
- search: "key term",
- matches: [ { uri: NetUtil.newURI("http://abc/?search=term"), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Plain keyword UC");
- yield check_autocomplete({
- search: "key TERM",
- matches: [ { uri: NetUtil.newURI("http://abc/?search=TERM"), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Multi-word keyword query");
- yield check_autocomplete({
- search: "key multi word",
- matches: [ { uri: NetUtil.newURI("http://abc/?search=multi%20word"), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Keyword query with +");
- yield check_autocomplete({
- search: "key blocking+",
- matches: [ { uri: NetUtil.newURI("http://abc/?search=blocking%2B"), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Unescaped term in query");
- yield check_autocomplete({
- search: "key ユニコード",
- matches: [ { uri: NetUtil.newURI("http://abc/?search=ユニコード"), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Keyword that happens to match a page");
- yield check_autocomplete({
- search: "key ThisPageIsInHistory",
- matches: [ { uri: NetUtil.newURI("http://abc/?search=ThisPageIsInHistory"), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Keyword without query (without space)");
- yield check_autocomplete({
- search: "key",
- matches: [ { uri: NetUtil.newURI("http://abc/?search="), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Keyword without query (with space)");
- yield check_autocomplete({
- search: "key ",
- matches: [ { uri: NetUtil.newURI("http://abc/?search="), title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_keyword_search_actions.js b/toolkit/components/places/tests/unifiedcomplete/test_keyword_search_actions.js
deleted file mode 100644
index 61d98f72d..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_keyword_search_actions.js
+++ /dev/null
@@ -1,149 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for bug 392143 that puts keyword results into the autocomplete. Makes
- * sure that multiple parameter queries get spaces converted to +, + converted
- * to %2B, non-ascii become escaped, and pages in history that match the
- * keyword uses the page's title.
- *
- * Also test for bug 249468 by making sure multiple keyword bookmarks with the
- * same keyword appear in the list.
- */
-
-add_task(function* test_keyword_search() {
- let uri1 = NetUtil.newURI("http://abc/?search=%s");
- let uri2 = NetUtil.newURI("http://abc/?search=ThisPageIsInHistory");
- let uri3 = NetUtil.newURI("http://abc/?search=%s&raw=%S");
- let uri4 = NetUtil.newURI("http://abc/?search=%s&raw=%S&mozcharset=ISO-8859-1");
- yield PlacesTestUtils.addVisits([{ uri: uri1 },
- { uri: uri2 },
- { uri: uri3 }]);
- yield addBookmark({ uri: uri1, title: "Keyword", keyword: "key"});
- yield addBookmark({ uri: uri1, title: "Post", keyword: "post", postData: "post_search=%s"});
- yield addBookmark({ uri: uri3, title: "Encoded", keyword: "encoded"});
- yield addBookmark({ uri: uri4, title: "Charset", keyword: "charset"});
- yield addBookmark({ uri: uri2, title: "Noparam", keyword: "noparam"});
- yield addBookmark({ uri: uri2, title: "Noparam-Post", keyword: "post_noparam", postData: "noparam=1"});
-
- do_print("Plain keyword query");
- yield check_autocomplete({
- search: "key term",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=term", input: "key term"}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Plain keyword UC");
- yield check_autocomplete({
- search: "key TERM",
- matches: [ { uri: NetUtil.newURI("http://abc/?search=TERM"),
- title: "abc", style: ["keyword", "heuristic"] } ]
- });
-
- do_print("Multi-word keyword query");
- yield check_autocomplete({
- search: "key multi word",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=multi%20word", input: "key multi word"}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Keyword query with +");
- yield check_autocomplete({
- search: "key blocking+",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=blocking%2B", input: "key blocking+"}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Unescaped term in query");
- // ... but note that UnifiedComplete calls encodeURIComponent() on the query
- // string when it builds the URL, so the expected result will have the
- // ユニコード substring encoded in the URL.
- yield check_autocomplete({
- search: "key ユニコード",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=" + encodeURIComponent("ユニコード"), input: "key ユニコード"}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Keyword that happens to match a page");
- yield check_autocomplete({
- search: "key ThisPageIsInHistory",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=ThisPageIsInHistory", input: "key ThisPageIsInHistory"}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Keyword without query (without space)");
- yield check_autocomplete({
- search: "key",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=", input: "key"}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Keyword without query (with space)");
- yield check_autocomplete({
- search: "key ",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=", input: "key "}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("POST Keyword");
- yield check_autocomplete({
- search: "post foo",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=foo", input: "post foo", postData: "post_search=foo"}),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Bug 420328: no-param keyword with a param");
- yield check_autocomplete({
- search: "noparam foo",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("noparam foo", { heuristic: true }) ]
- });
- yield check_autocomplete({
- search: "post_noparam foo",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("post_noparam foo", { heuristic: true }) ]
- });
-
- do_print("escaping with default UTF-8 charset");
- yield check_autocomplete({
- search: "encoded foé",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=fo%C3%A9&raw=foé", input: "encoded foé" }),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("escaping with forced ISO-8859-1 charset");
- yield check_autocomplete({
- search: "charset foé",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=fo%E9&raw=foé", input: "charset foé" }),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Bug 359809: escaping +, / and @ with default UTF-8 charset");
- yield check_autocomplete({
- search: "encoded +/@",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=%2B%2F%40&raw=+/@", input: "encoded +/@" }),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- do_print("Bug 359809: escaping +, / and @ with forced ISO-8859-1 charset");
- yield check_autocomplete({
- search: "charset +/@",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("keyword", {url: "http://abc/?search=%2B%2F%40&raw=+/@", input: "charset +/@" }),
- title: "abc", style: [ "action", "keyword", "heuristic" ] } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_keywords.js b/toolkit/components/places/tests/unifiedcomplete/test_keywords.js
deleted file mode 100644
index 93e8d7a6f..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_keywords.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/. */
-
-add_task(function* test_non_keyword() {
- do_print("Searching for non-keyworded entry should autoFill it");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield addBookmark({ uri: NetUtil.newURI("http://mozilla.org/test/") });
- yield check_autocomplete({
- search: "moz",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_keyword() {
- do_print("Searching for keyworded entry should not autoFill it");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield addBookmark({ uri: NetUtil.newURI("http://mozilla.org/test/"), keyword: "moz" });
- yield check_autocomplete({
- search: "moz",
- autofilled: "moz",
- completed: "moz",
- });
- yield cleanup();
-});
-
-add_task(function* test_more_than_keyword() {
- do_print("Searching for more than keyworded entry should autoFill it");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield addBookmark({ uri: NetUtil.newURI("http://mozilla.org/test/"), keyword: "moz" });
- yield check_autocomplete({
- search: "mozi",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_less_than_keyword() {
- do_print("Searching for less than keyworded entry should autoFill it");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield addBookmark({ uri: NetUtil.newURI("http://mozilla.org/test/"), keyword: "moz" });
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/",
- });
- yield cleanup();
-});
-
-add_task(function* test_keyword_casing() {
- do_print("Searching for keyworded entry is case-insensitive");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield addBookmark({ uri: NetUtil.newURI("http://mozilla.org/test/"), keyword: "moz" });
- yield check_autocomplete({
- search: "MoZ",
- autofilled: "MoZ",
- completed: "MoZ"
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_match_beginning.js b/toolkit/components/places/tests/unifiedcomplete/test_match_beginning.js
deleted file mode 100644
index 57a1efaeb..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_match_beginning.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test bug 451760 which allows matching only at the beginning of urls or
- * titles to simulate Firefox 2 functionality.
- */
-
-add_task(function* test_match_beginning() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", false);
-
- let uri1 = NetUtil.newURI("http://x.com/y");
- let uri2 = NetUtil.newURI("https://y.com/x");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "a b" },
- { uri: uri2, title: "b a" }
- ]);
-
- do_print("Match at the beginning of titles");
- Services.prefs.setIntPref("browser.urlbar.matchBehavior", 3);
- yield check_autocomplete({
- search: "a",
- matches: [ { uri: uri1, title: "a b" } ]
- });
-
- do_print("Match at the beginning of titles");
- yield check_autocomplete({
- search: "b",
- matches: [ { uri: uri2, title: "b a" } ]
- });
-
- do_print("Match at the beginning of urls");
- yield check_autocomplete({
- search: "x",
- matches: [ { uri: uri1, title: "a b" } ]
- });
-
- do_print("Match at the beginning of urls");
- yield check_autocomplete({
- search: "y",
- matches: [ { uri: uri2, title: "b a" } ]
- });
-
- do_print("Sanity check that matching anywhere finds more");
- Services.prefs.setIntPref("browser.urlbar.matchBehavior", 1);
- yield check_autocomplete({
- search: "a",
- matches: [ { uri: uri1, title: "a b" },
- { uri: uri2, title: "b a" } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_multi_word_search.js b/toolkit/components/places/tests/unifiedcomplete/test_multi_word_search.js
deleted file mode 100644
index c6c9e952e..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_multi_word_search.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for bug 401869 to allow multiple words separated by spaces to match in
- * the page title, page url, or bookmark title to be considered a match. All
- * terms must match but not all terms need to be in the title, etc.
- *
- * Test bug 424216 by making sure bookmark titles are always shown if one is
- * available. Also bug 425056 makes sure matches aren't found partially in the
- * page title and partially in the bookmark.
- */
-
-add_task(function* test_match_beginning() {
- let uri1 = NetUtil.newURI("http://a.b.c/d-e_f/h/t/p");
- let uri2 = NetUtil.newURI("http://d.e.f/g-h_i/h/t/p");
- let uri3 = NetUtil.newURI("http://g.h.i/j-k_l/h/t/p");
- let uri4 = NetUtil.newURI("http://j.k.l/m-n_o/h/t/p");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "f(o)o b<a>r" },
- { uri: uri2, title: "b(a)r b<a>z" },
- { uri: uri3, title: "f(o)o b<a>r" },
- { uri: uri4, title: "f(o)o b<a>r" }
- ]);
- yield addBookmark({ uri: uri3, title: "f(o)o b<a>r" });
- yield addBookmark({ uri: uri4, title: "b(a)r b<a>z" });
-
- do_print("Match 2 terms all in url");
- yield check_autocomplete({
- search: "c d",
- matches: [ { uri: uri1, title: "f(o)o b<a>r" } ]
- });
-
- do_print("Match 1 term in url and 1 term in title");
- yield check_autocomplete({
- search: "b e",
- matches: [ { uri: uri1, title: "f(o)o b<a>r" },
- { uri: uri2, title: "b(a)r b<a>z" } ]
- });
-
- do_print("Match 3 terms all in title; display bookmark title if matched");
- yield check_autocomplete({
- search: "b a z",
- matches: [ { uri: uri2, title: "b(a)r b<a>z" },
- { uri: uri4, title: "b(a)r b<a>z", style: [ "bookmark" ] } ]
- });
-
- do_print("Match 2 terms in url and 1 in title; make sure bookmark title is used for search");
- yield check_autocomplete({
- search: "k f t",
- matches: [ { uri: uri3, title: "f(o)o b<a>r", style: [ "bookmark" ] } ]
- });
-
- do_print("Match 3 terms in url and 1 in title");
- yield check_autocomplete({
- search: "d i g z",
- matches: [ { uri: uri2, title: "b(a)r b<a>z" } ]
- });
-
- do_print("Match nothing");
- yield check_autocomplete({
- search: "m o z i",
- matches: [ ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_query_url.js b/toolkit/components/places/tests/unifiedcomplete/test_query_url.js
deleted file mode 100644
index 915ba770e..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_query_url.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* test_no_slash() {
- do_print("Searching for host match without slash should match host");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://file.org/test/"),
- transition: TRANSITION_TYPED
- }, {
- uri: NetUtil.newURI("file:///c:/test.html"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "file",
- autofilled: "file.org/",
- completed: "file.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_w_slash() {
- do_print("Searching match with slash at the end should do nothing");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://file.org/test/"),
- transition: TRANSITION_TYPED
- }, {
- uri: NetUtil.newURI("file:///c:/test.html"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "file.org/",
- autofilled: "file.org/",
- completed: "file.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_middle() {
- do_print("Searching match with slash in the middle should match url");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://file.org/test/"),
- transition: TRANSITION_TYPED
- }, {
- uri: NetUtil.newURI("file:///c:/test.html"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "file.org/t",
- autofilled: "file.org/test/",
- completed: "http://file.org/test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_nonhost() {
- do_print("Searching for non-host match without slash should not match url");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("file:///c:/test.html"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "file",
- autofilled: "file",
- completed: "file"
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_remote_tab_matches.js b/toolkit/components/places/tests/unifiedcomplete/test_remote_tab_matches.js
deleted file mode 100644
index 56998d4d6..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_remote_tab_matches.js
+++ /dev/null
@@ -1,203 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim:set ts=2 sw=2 sts=2 et:
-*/
-"use strict";
-
-Cu.import("resource://services-sync/main.js");
-
-Services.prefs.setCharPref("services.sync.username", "someone@somewhere.com");
-
-// A mock "Tabs" engine which autocomplete will use instead of the real
-// engine. We pass a constructor that Sync creates.
-function MockTabsEngine() {
- this.clients = null; // We'll set this dynamically
-}
-
-MockTabsEngine.prototype = {
- name: "tabs",
-
- getAllClients() {
- return this.clients;
- },
-}
-
-// A clients engine that doesn't need to be a constructor.
-let MockClientsEngine = {
- isMobile(guid) {
- Assert.ok(guid.endsWith("desktop") || guid.endsWith("mobile"));
- return guid.endsWith("mobile");
- },
-}
-
-// Tell Sync about the mocks.
-Weave.Service.engineManager.register(MockTabsEngine);
-Weave.Service.clientsEngine = MockClientsEngine;
-
-// Tell the Sync XPCOM service it is initialized.
-let weaveXPCService = Cc["@mozilla.org/weave/service;1"]
- .getService(Ci.nsISupports)
- .wrappedJSObject;
-weaveXPCService.ready = true;
-
-// Configure the singleton engine for a test.
-function configureEngine(clients) {
- // Configure the instance Sync created.
- let engine = Weave.Service.engineManager.get("tabs");
- engine.clients = clients;
- // Send an observer that pretends the engine just finished a sync.
- Services.obs.notifyObservers(null, "weave:engine:sync:finish", "tabs");
-}
-
-// Make a match object suitable for passing to check_autocomplete.
-function makeRemoteTabMatch(url, deviceName, extra = {}) {
- return {
- uri: makeActionURI("remotetab", {url, deviceName}),
- title: extra.title || url,
- style: [ "action", "remotetab" ],
- icon: extra.icon,
- }
-}
-
-// The tests.
-add_task(function* test_nomatch() {
- // Nothing matches.
- configureEngine({
- guid_desktop: {
- clientName: "My Desktop",
- tabs: [{
- urlHistory: ["http://foo.com/"],
- }],
- }
- });
-
- // No remote tabs match here, so we only expect search results.
- yield check_autocomplete({
- search: "ex",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("ex", { heuristic: true }) ],
- });
-});
-
-add_task(function* test_minimal() {
- // The minimal client and tabs info we can get away with.
- configureEngine({
- guid_desktop: {
- clientName: "My Desktop",
- tabs: [{
- urlHistory: ["http://example.com/"],
- }],
- }
- });
-
- yield check_autocomplete({
- search: "ex",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("ex", { heuristic: true }),
- makeRemoteTabMatch("http://example.com/", "My Desktop") ],
- });
-});
-
-add_task(function* test_maximal() {
- // Every field that could possibly exist on a remote record.
- configureEngine({
- guid_mobile: {
- clientName: "My Phone",
- tabs: [{
- urlHistory: ["http://example.com/"],
- title: "An Example",
- icon: "http://favicon",
- }],
- }
- });
-
- yield check_autocomplete({
- search: "ex",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("ex", { heuristic: true }),
- makeRemoteTabMatch("http://example.com/", "My Phone",
- { title: "An Example",
- icon: "moz-anno:favicon:http://favicon/"
- }),
- ],
- });
-});
-
-add_task(function* test_noShowIcons() {
- Services.prefs.setBoolPref("services.sync.syncedTabs.showRemoteIcons", false);
- configureEngine({
- guid_mobile: {
- clientName: "My Phone",
- tabs: [{
- urlHistory: ["http://example.com/"],
- title: "An Example",
- icon: "http://favicon",
- }],
- }
- });
-
- yield check_autocomplete({
- search: "ex",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("ex", { heuristic: true }),
- makeRemoteTabMatch("http://example.com/", "My Phone",
- { title: "An Example",
- // expecting the default favicon due to that pref.
- icon: "",
- }),
- ],
- });
- Services.prefs.clearUserPref("services.sync.syncedTabs.showRemoteIcons");
-});
-
-add_task(function* test_matches_title() {
- // URL doesn't match search expression, should still match the title.
- configureEngine({
- guid_mobile: {
- clientName: "My Phone",
- tabs: [{
- urlHistory: ["http://foo.com/"],
- title: "An Example",
- }],
- }
- });
-
- yield check_autocomplete({
- search: "ex",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("ex", { heuristic: true }),
- makeRemoteTabMatch("http://foo.com/", "My Phone",
- { title: "An Example" }),
- ],
- });
-});
-
-add_task(function* test_localtab_matches_override() {
- // We have an open tab to the same page on a remote device, only "switch to
- // tab" should appear as duplicate detection removed the remote one.
-
- // First setup Sync to have the page as a remote tab.
- configureEngine({
- guid_mobile: {
- clientName: "My Phone",
- tabs: [{
- urlHistory: ["http://foo.com/"],
- title: "An Example",
- }],
- }
- });
-
- // Setup Places to think the tab is open locally.
- let uri = NetUtil.newURI("http://foo.com/");
- yield PlacesTestUtils.addVisits([
- { uri: uri, title: "An Example" },
- ]);
- addOpenPages(uri, 1);
-
- yield check_autocomplete({
- search: "ex",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("ex", { heuristic: true }),
- makeSwitchToTabMatch("http://foo.com/", { title: "An Example" }),
- ],
- });
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_alias.js b/toolkit/components/places/tests/unifiedcomplete/test_search_engine_alias.js
deleted file mode 100644
index f35242e21..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_alias.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-add_task(function*() {
- // Note that head_autocomplete.js has already added a MozSearch engine.
- // Here we add another engine with a search alias.
- Services.search.addEngineWithDetails("AliasedGETMozSearch", "", "get", "",
- "GET", "http://s.example.com/search");
- Services.search.addEngineWithDetails("AliasedPOSTMozSearch", "", "post", "",
- "POST", "http://s.example.com/search");
-
- for (let alias of ["get", "post"]) {
- yield check_autocomplete({
- search: alias,
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(alias, { engineName: `Aliased${alias.toUpperCase()}MozSearch`,
- searchQuery: "", alias, heuristic: true }) ]
- });
-
- yield check_autocomplete({
- search: `${alias} `,
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(`${alias} `, { engineName: `Aliased${alias.toUpperCase()}MozSearch`,
- searchQuery: "", alias, heuristic: true }) ]
- });
-
- yield check_autocomplete({
- search: `${alias} mozilla`,
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(`${alias} mozilla`, { engineName: `Aliased${alias.toUpperCase()}MozSearch`,
- searchQuery: "mozilla", alias, heuristic: true }) ]
- });
-
- yield check_autocomplete({
- search: `${alias} MoZiLlA`,
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(`${alias} MoZiLlA`, { engineName: `Aliased${alias.toUpperCase()}MozSearch`,
- searchQuery: "MoZiLlA", alias, heuristic: true }) ]
- });
-
- yield check_autocomplete({
- search: `${alias} mozzarella mozilla`,
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(`${alias} mozzarella mozilla`, { engineName: `Aliased${alias.toUpperCase()}MozSearch`,
- searchQuery: "mozzarella mozilla", alias, heuristic: true }) ]
- });
- }
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_current.js b/toolkit/components/places/tests/unifiedcomplete/test_search_engine_current.js
deleted file mode 100644
index b41d9884b..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_current.js
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-add_task(function*() {
- // Note that head_autocomplete.js has already added a MozSearch engine.
- // Here we add another engine with a search alias.
- Services.search.addEngineWithDetails("AliasedMozSearch", "", "doit", "",
- "GET", "http://s.example.com/search");
-
- do_print("search engine");
- yield check_autocomplete({
- search: "mozilla",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("mozilla", { heuristic: true }) ]
- });
-
- do_print("search engine, uri-like input");
- yield check_autocomplete({
- search: "http:///",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("http:///", { heuristic: true }) ]
- });
-
- do_print("search engine, multiple words");
- yield check_autocomplete({
- search: "mozzarella cheese",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("mozzarella cheese", { heuristic: true }) ]
- });
-
- do_print("search engine, after current engine has changed");
- Services.search.addEngineWithDetails("MozSearch2", "", "", "", "GET",
- "http://s.example.com/search2");
- engine = Services.search.getEngineByName("MozSearch2");
- notEqual(Services.search.currentEngine, engine, "New engine shouldn't be the current engine yet");
- Services.search.currentEngine = engine;
- yield check_autocomplete({
- search: "mozilla",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("mozilla", { engineName: "MozSearch2", heuristic: true }) ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_host.js b/toolkit/components/places/tests/unifiedcomplete/test_search_engine_host.js
deleted file mode 100644
index 61b9826f7..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_host.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-add_task(function* test_searchEngine_autoFill() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", true);
- Services.search.addEngineWithDetails("MySearchEngine", "", "", "",
- "GET", "http://my.search.com/");
- let engine = Services.search.getEngineByName("MySearchEngine");
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
- // Add an uri that matches the search string with high frecency.
- let uri = NetUtil.newURI("http://www.example.com/my/");
- let visits = [];
- for (let i = 0; i < 100; ++i) {
- visits.push({ uri, title: "Terms - SearchEngine Search" });
- }
- yield PlacesTestUtils.addVisits(visits);
- yield addBookmark({ uri: uri, title: "Example bookmark" });
- yield PlacesTestUtils.promiseAsyncUpdates();
- ok(frecencyForUrl(uri) > 10000, "Added URI should have expected high frecency");
-
- do_print("Check search domain is autoFilled even if there's an higher frecency match");
- yield check_autocomplete({
- search: "my",
- autofilled: "my.search.com",
- completed: "http://my.search.com"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_searchEngine_noautoFill() {
- let engineName = "engine-rel-searchform.xml";
- let engine = yield addTestEngine(engineName);
- equal(engine.searchForm, "http://example.com/?search");
-
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://example.com/my/"));
-
- do_print("Check search domain is not autoFilled if it matches a visited domain");
- yield check_autocomplete({
- search: "example",
- autofilled: "example.com/",
- completed: "example.com/"
- });
-
- yield cleanup();
-});
-
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_restyle.js b/toolkit/components/places/tests/unifiedcomplete/test_search_engine_restyle.js
deleted file mode 100644
index 2a5f2d78e..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_search_engine_restyle.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* test_searchEngine() {
- Services.search.addEngineWithDetails("SearchEngine", "", "", "",
- "GET", "http://s.example.com/search");
- let engine = Services.search.getEngineByName("SearchEngine");
- engine.addParam("q", "{searchTerms}", null);
- do_register_cleanup(() => Services.search.removeEngine(engine));
-
- let uri1 = NetUtil.newURI("http://s.example.com/search?q=Terms&client=1");
- let uri2 = NetUtil.newURI("http://s.example.com/search?q=Terms&client=2");
- yield PlacesTestUtils.addVisits({ uri: uri1, title: "Terms - SearchEngine Search" });
- yield addBookmark({ uri: uri2, title: "Terms - SearchEngine Search" });
-
- do_print("Past search terms should be styled, unless bookmarked");
- Services.prefs.setBoolPref("browser.urlbar.restyleSearches", true);
- yield check_autocomplete({
- search: "term",
- matches: [
- makeSearchMatch("Terms", {
- engineName: "SearchEngine",
- style: ["favicon"]
- }),
- {
- uri: uri2,
- title: "Terms - SearchEngine Search",
- style: ["bookmark"]
- }
- ]
- });
-
- do_print("Past search terms should not be styled if restyling is disabled");
- Services.prefs.setBoolPref("browser.urlbar.restyleSearches", false);
- yield check_autocomplete({
- search: "term",
- matches: [ { uri: uri1, title: "Terms - SearchEngine Search" },
- { uri: uri2, title: "Terms - SearchEngine Search", style: ["bookmark"] } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_search_suggestions.js b/toolkit/components/places/tests/unifiedcomplete/test_search_suggestions.js
deleted file mode 100644
index 63b428cd4..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_search_suggestions.js
+++ /dev/null
@@ -1,651 +0,0 @@
-Cu.import("resource://gre/modules/FormHistory.jsm");
-
-const ENGINE_NAME = "engine-suggestions.xml";
-const SERVER_PORT = 9000;
-const SUGGEST_PREF = "browser.urlbar.suggest.searches";
-const SUGGEST_ENABLED_PREF = "browser.search.suggest.enabled";
-const SUGGEST_RESTRICT_TOKEN = "$";
-
-var suggestionsFn;
-var previousSuggestionsFn;
-
-function setSuggestionsFn(fn) {
- previousSuggestionsFn = suggestionsFn;
- suggestionsFn = fn;
-}
-
-function* cleanUpSuggestions() {
- yield cleanup();
- if (previousSuggestionsFn) {
- suggestionsFn = previousSuggestionsFn;
- previousSuggestionsFn = null;
- }
-}
-
-add_task(function* setUp() {
- // Set up a server that provides some suggestions by appending strings onto
- // the search query.
- let server = makeTestServer(SERVER_PORT);
- server.registerPathHandler("/suggest", (req, resp) => {
- // URL query params are x-www-form-urlencoded, which converts spaces into
- // plus signs, so un-convert any plus signs back to spaces.
- let searchStr = decodeURIComponent(req.queryString.replace(/\+/g, " "));
- let suggestions = suggestionsFn(searchStr);
- let data = [searchStr, suggestions];
- resp.setHeader("Content-Type", "application/json", false);
- resp.write(JSON.stringify(data));
- });
- setSuggestionsFn(searchStr => {
- let suffixes = ["foo", "bar"];
- return suffixes.map(s => searchStr + " " + s);
- });
-
- // Install the test engine.
- let oldCurrentEngine = Services.search.currentEngine;
- do_register_cleanup(() => Services.search.currentEngine = oldCurrentEngine);
- let engine = yield addTestEngine(ENGINE_NAME, server);
- Services.search.currentEngine = engine;
-});
-
-add_task(function* disabled_urlbarSuggestions() {
- Services.prefs.setBoolPref(SUGGEST_PREF, false);
- Services.prefs.setBoolPref(SUGGEST_ENABLED_PREF, true);
- yield check_autocomplete({
- search: "hello",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("hello", { engineName: ENGINE_NAME, heuristic: true }),
- ],
- });
- yield cleanUpSuggestions();
-});
-
-add_task(function* disabled_allSuggestions() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_ENABLED_PREF, false);
- yield check_autocomplete({
- search: "hello",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("hello", { engineName: ENGINE_NAME, heuristic: true }),
- ],
- });
- yield cleanUpSuggestions();
-});
-
-add_task(function* disabled_privateWindow() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_ENABLED_PREF, true);
- yield check_autocomplete({
- search: "hello",
- searchParam: "private-window enable-actions",
- matches: [
- makeSearchMatch("hello", { engineName: ENGINE_NAME, heuristic: true }),
- ],
- });
- yield cleanUpSuggestions();
-});
-
-add_task(function* singleWordQuery() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_ENABLED_PREF, true);
-
- yield check_autocomplete({
- search: "hello",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("hello", { engineName: ENGINE_NAME, heuristic: true }),
- { uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello foo",
- searchQuery: "hello",
- searchSuggestion: "hello foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }, {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello bar",
- searchQuery: "hello",
- searchSuggestion: "hello bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }],
- });
-
- yield cleanUpSuggestions();
-});
-
-add_task(function* multiWordQuery() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_ENABLED_PREF, true);
-
- yield check_autocomplete({
- search: "hello world",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("hello world", { engineName: ENGINE_NAME, heuristic: true }),
- { uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello world foo",
- searchQuery: "hello world",
- searchSuggestion: "hello world foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }, {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello world bar",
- searchQuery: "hello world",
- searchSuggestion: "hello world bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }],
- });
-
- yield cleanUpSuggestions();
-});
-
-add_task(function* suffixMatch() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_ENABLED_PREF, true);
-
- setSuggestionsFn(searchStr => {
- let prefixes = ["baz", "quux"];
- return prefixes.map(p => p + " " + searchStr);
- });
-
- yield check_autocomplete({
- search: "hello",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("hello", { engineName: ENGINE_NAME, heuristic: true }),
- { uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "baz hello",
- searchQuery: "hello",
- searchSuggestion: "baz hello",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }, {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "quux hello",
- searchQuery: "hello",
- searchSuggestion: "quux hello",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }],
- });
-
- yield cleanUpSuggestions();
-});
-
-add_task(function* queryIsNotASubstring() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
-
- setSuggestionsFn(searchStr => {
- return ["aaa", "bbb"];
- });
-
- yield check_autocomplete({
- search: "hello",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("hello", { engineName: ENGINE_NAME, heuristic: true }),
- { uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "aaa",
- searchQuery: "hello",
- searchSuggestion: "aaa",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }, {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "bbb",
- searchQuery: "hello",
- searchSuggestion: "bbb",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }],
- });
-
- yield cleanUpSuggestions();
-});
-
-add_task(function* restrictToken() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
- Services.prefs.setBoolPref(SUGGEST_ENABLED_PREF, true);
-
- // Add a visit and a bookmark. Actually, make the bookmark visited too so
- // that it's guaranteed, with its higher frecency, to appear above the search
- // suggestions.
- yield PlacesTestUtils.addVisits([
- {
- uri: NetUtil.newURI("http://example.com/hello-visit"),
- title: "hello visit",
- },
- {
- uri: NetUtil.newURI("http://example.com/hello-bookmark"),
- title: "hello bookmark",
- },
- ]);
-
- yield addBookmark({
- uri: NetUtil.newURI("http://example.com/hello-bookmark"),
- title: "hello bookmark",
- });
-
- // Do an unrestricted search to make sure everything appears in it, including
- // the visit and bookmark.
- yield check_autocomplete({
- search: "hello",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("hello", { engineName: ENGINE_NAME, heuristic: true }),
- {
- uri: NetUtil.newURI("http://example.com/hello-visit"),
- title: "hello visit",
- },
- {
- uri: NetUtil.newURI("http://example.com/hello-bookmark"),
- title: "hello bookmark",
- style: ["bookmark"],
- },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello foo",
- searchQuery: "hello",
- searchSuggestion: "hello foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello bar",
- searchQuery: "hello",
- searchSuggestion: "hello bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- ],
- });
-
- // Now do a restricted search to make sure only suggestions appear.
- yield check_autocomplete({
- search: SUGGEST_RESTRICT_TOKEN + " hello",
- searchParam: "enable-actions",
- matches: [
- // TODO (bug 1177895) This is wrong.
- makeSearchMatch(SUGGEST_RESTRICT_TOKEN + " hello", { engineName: ENGINE_NAME, heuristic: true }),
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello foo",
- searchQuery: "hello",
- searchSuggestion: "hello foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "hello bar",
- searchQuery: "hello",
- searchSuggestion: "hello bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- }
- ],
- });
-
- yield cleanUpSuggestions();
-});
-
-add_task(function* mixup_frecency() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
-
- // Add a visit and a bookmark. Actually, make the bookmark visited too so
- // that it's guaranteed, with its higher frecency, to appear above the search
- // suggestions.
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("http://example.com/lo0"),
- title: "low frecency 0" },
- { uri: NetUtil.newURI("http://example.com/lo1"),
- title: "low frecency 1" },
- { uri: NetUtil.newURI("http://example.com/lo2"),
- title: "low frecency 2" },
- { uri: NetUtil.newURI("http://example.com/lo3"),
- title: "low frecency 3" },
- { uri: NetUtil.newURI("http://example.com/lo4"),
- title: "low frecency 4" },
- ]);
-
- for (let i = 0; i < 4; i++) {
- let href = `http://example.com/lo${i}`;
- let frecency = frecencyForUrl(href);
- Assert.ok(frecency < FRECENCY_DEFAULT,
- `frecency for ${href}: ${frecency}, should be lower than ${FRECENCY_DEFAULT}`);
- }
-
- for (let i = 0; i < 5; i++) {
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("http://example.com/hi0"),
- title: "high frecency 0",
- transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://example.com/hi1"),
- title: "high frecency 1",
- transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://example.com/hi2"),
- title: "high frecency 2",
- transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://example.com/hi3"),
- title: "high frecency 3",
- transition: TRANSITION_TYPED },
- ]);
- }
-
- for (let i = 0; i < 4; i++) {
- let href = `http://example.com/hi${i}`;
- yield addBookmark({ uri: href, title: `high frecency ${i}` });
- let frecency = frecencyForUrl(href);
- Assert.ok(frecency > FRECENCY_DEFAULT,
- `frecency for ${href}: ${frecency}, should be higher than ${FRECENCY_DEFAULT}`);
- }
-
- // Do an unrestricted search to make sure everything appears in it, including
- // the visit and bookmark.
- yield check_autocomplete({
- checkSorting: true,
- search: "frecency",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("frecency", { engineName: ENGINE_NAME, heuristic: true }),
- { uri: NetUtil.newURI("http://example.com/hi3"),
- title: "high frecency 3",
- style: [ "bookmark" ] },
- { uri: NetUtil.newURI("http://example.com/hi2"),
- title: "high frecency 2",
- style: [ "bookmark" ] },
- { uri: NetUtil.newURI("http://example.com/hi1"),
- title: "high frecency 1",
- style: [ "bookmark" ] },
- { uri: NetUtil.newURI("http://example.com/hi0"),
- title: "high frecency 0",
- style: [ "bookmark" ] },
- { uri: NetUtil.newURI("http://example.com/lo4"),
- title: "low frecency 4" },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "frecency foo",
- searchQuery: "frecency",
- searchSuggestion: "frecency foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "frecency bar",
- searchQuery: "frecency",
- searchSuggestion: "frecency bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- { uri: NetUtil.newURI("http://example.com/lo3"),
- title: "low frecency 3" },
- { uri: NetUtil.newURI("http://example.com/lo2"),
- title: "low frecency 2" },
- { uri: NetUtil.newURI("http://example.com/lo1"),
- title: "low frecency 1" },
- { uri: NetUtil.newURI("http://example.com/lo0"),
- title: "low frecency 0" },
- ],
- });
-
- yield cleanUpSuggestions();
-});
-
-add_task(function* prohibit_suggestions() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
-
- yield check_autocomplete({
- search: "localhost",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("localhost", { engineName: ENGINE_NAME, heuristic: true }),
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "localhost foo",
- searchQuery: "localhost",
- searchSuggestion: "localhost foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "localhost bar",
- searchQuery: "localhost",
- searchSuggestion: "localhost bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- ],
- });
- Services.prefs.setBoolPref("browser.fixup.domainwhitelist.localhost", true);
- do_register_cleanup(() => {
- Services.prefs.clearUserPref("browser.fixup.domainwhitelist.localhost");
- });
- yield check_autocomplete({
- search: "localhost",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("localhost", "http://localhost/", { heuristic: true }),
- makeSearchMatch("localhost", { engineName: ENGINE_NAME, heuristic: false })
- ],
- });
-
- // When using multiple words, we should still get suggestions:
- yield check_autocomplete({
- search: "localhost other",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("localhost other", { engineName: ENGINE_NAME, heuristic: true }),
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "localhost other foo",
- searchQuery: "localhost other",
- searchSuggestion: "localhost other foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "localhost other bar",
- searchQuery: "localhost other",
- searchSuggestion: "localhost other bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- ],
- });
-
- // Clear the whitelist for localhost, and try preferring DNS for any single
- // word instead:
- Services.prefs.clearUserPref("browser.fixup.domainwhitelist.localhost");
- Services.prefs.setBoolPref("browser.fixup.dns_first_for_single_words", true);
- do_register_cleanup(() => {
- Services.prefs.clearUserPref("browser.fixup.dns_first_for_single_words");
- });
-
- yield check_autocomplete({
- search: "localhost",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("localhost", "http://localhost/", { heuristic: true }),
- makeSearchMatch("localhost", { engineName: ENGINE_NAME, heuristic: false })
- ],
- });
-
- yield check_autocomplete({
- search: "somethingelse",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("somethingelse", "http://somethingelse/", { heuristic: true }),
- makeSearchMatch("somethingelse", { engineName: ENGINE_NAME, heuristic: false })
- ],
- });
-
- // When using multiple words, we should still get suggestions:
- yield check_autocomplete({
- search: "localhost other",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("localhost other", { engineName: ENGINE_NAME, heuristic: true }),
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "localhost other foo",
- searchQuery: "localhost other",
- searchSuggestion: "localhost other foo",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "localhost other bar",
- searchQuery: "localhost other",
- searchSuggestion: "localhost other bar",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- ],
- });
-
- Services.prefs.clearUserPref("browser.fixup.dns_first_for_single_words");
-
- yield check_autocomplete({
- search: "1.2.3.4",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("1.2.3.4", "http://1.2.3.4/", { heuristic: true }),
- ],
- });
- yield check_autocomplete({
- search: "[2001::1]:30",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("[2001::1]:30", "http://[2001::1]:30/", { heuristic: true }),
- ],
- });
- yield check_autocomplete({
- search: "user:pass@test",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("user:pass@test", "http://user:pass@test/", { heuristic: true }),
- ],
- });
- yield check_autocomplete({
- search: "test/test",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("test/test", "http://test/test", { heuristic: true }),
- ],
- });
- yield check_autocomplete({
- search: "data:text/plain,Content",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("data:text/plain,Content", "data:text/plain,Content", { heuristic: true }),
- ],
- });
-
- yield check_autocomplete({
- search: "a",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("a", { engineName: ENGINE_NAME, heuristic: true }),
- ],
- });
-
- yield cleanUpSuggestions();
-});
-
-add_task(function* avoid_url_suggestions() {
- Services.prefs.setBoolPref(SUGGEST_PREF, true);
-
- setSuggestionsFn(searchStr => {
- let suffixes = [".com", "/test", ":1]", "@test", ". com"];
- return suffixes.map(s => searchStr + s);
- });
-
- yield check_autocomplete({
- search: "test",
- searchParam: "enable-actions",
- matches: [
- makeSearchMatch("test", { engineName: ENGINE_NAME, heuristic: true }),
- {
- uri: makeActionURI(("searchengine"), {
- engineName: ENGINE_NAME,
- input: "test. com",
- searchQuery: "test",
- searchSuggestion: "test. com",
- }),
- title: ENGINE_NAME,
- style: ["action", "searchengine"],
- icon: "",
- },
- ],
- });
-
- yield cleanUpSuggestions();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_special_search.js b/toolkit/components/places/tests/unifiedcomplete/test_special_search.js
deleted file mode 100644
index 21df7046c..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_special_search.js
+++ /dev/null
@@ -1,447 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for bug 395161 that allows special searches that restrict results to
- * history/bookmark/tagged items and title/url matches.
- *
- * Test 485122 by making sure results don't have tags when restricting result
- * to just history either by default behavior or dynamic query restrict.
- */
-
-function setSuggestPrefsToFalse() {
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.history.onlyTyped", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", false);
-}
-
-add_task(function* test_special_searches() {
- let uri1 = NetUtil.newURI("http://url/");
- let uri2 = NetUtil.newURI("http://url/2");
- let uri3 = NetUtil.newURI("http://foo.bar/");
- let uri4 = NetUtil.newURI("http://foo.bar/2");
- let uri5 = NetUtil.newURI("http://url/star");
- let uri6 = NetUtil.newURI("http://url/star/2");
- let uri7 = NetUtil.newURI("http://foo.bar/star");
- let uri8 = NetUtil.newURI("http://foo.bar/star/2");
- let uri9 = NetUtil.newURI("http://url/tag");
- let uri10 = NetUtil.newURI("http://url/tag/2");
- let uri11 = NetUtil.newURI("http://foo.bar/tag");
- let uri12 = NetUtil.newURI("http://foo.bar/tag/2");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "title", transition: TRANSITION_TYPED },
- { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar", transition: TRANSITION_TYPED },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", transition: TRANSITION_TYPED }
- ]);
- yield addBookmark( { uri: uri5, title: "title" } );
- yield addBookmark( { uri: uri6, title: "foo.bar" } );
- yield addBookmark( { uri: uri7, title: "title" } );
- yield addBookmark( { uri: uri8, title: "foo.bar" } );
- yield addBookmark( { uri: uri9, title: "title", tags: [ "foo.bar" ] } );
- yield addBookmark( { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ] } );
- yield addBookmark( { uri: uri11, title: "title", tags: [ "foo.bar" ] } );
- yield addBookmark( { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ] } );
-
- // Test restricting searches
- do_print("History restrict");
- yield check_autocomplete({
- search: "^",
- matches: [ { uri: uri1, title: "title" },
- { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("Star restrict");
- yield check_autocomplete({
- search: "*",
- matches: [ { uri: uri5, title: "title", style: [ "bookmark" ] },
- { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar"], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("Tag restrict");
- yield check_autocomplete({
- search: "+",
- matches: [ { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- // Test specials as any word position
- do_print("Special as first word");
- yield check_autocomplete({
- search: "^ foo bar",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("Special as middle word");
- yield check_autocomplete({
- search: "foo ^ bar",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("Special as last word");
- yield check_autocomplete({
- search: "foo bar ^",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- // Test restricting and matching searches with a term
- do_print("foo ^ -> history");
- yield check_autocomplete({
- search: "foo ^",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo | -> history (change pref)");
- changeRestrict("history", "|");
- yield check_autocomplete({
- search: "foo |",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo * -> is star");
- resetRestrict("history");
- yield check_autocomplete({
- search: "foo *",
- matches: [ { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo | -> is star (change pref)");
- changeRestrict("bookmark", "|");
- yield check_autocomplete({
- search: "foo |",
- matches: [ { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo # -> in title");
- resetRestrict("bookmark");
- yield check_autocomplete({
- search: "foo #",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo | -> in title (change pref)");
- changeRestrict("title", "|");
- yield check_autocomplete({
- search: "foo |",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo @ -> in url");
- resetRestrict("title");
- yield check_autocomplete({
- search: "foo @",
- matches: [ { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo | -> in url (change pref)");
- changeRestrict("url", "|");
- yield check_autocomplete({
- search: "foo |",
- matches: [ { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo + -> is tag");
- resetRestrict("url");
- yield check_autocomplete({
- search: "foo +",
- matches: [ { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo | -> is tag (change pref)");
- changeRestrict("tag", "|");
- yield check_autocomplete({
- search: "foo |",
- matches: [ { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo ~ -> is typed");
- resetRestrict("tag");
- yield check_autocomplete({
- search: "foo ~",
- matches: [ { uri: uri4, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo | -> is typed (change pref)");
- changeRestrict("typed", "|");
- yield check_autocomplete({
- search: "foo |",
- matches: [ { uri: uri4, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- // Test various pairs of special searches
- do_print("foo ^ * -> history, is star");
- resetRestrict("typed");
- yield check_autocomplete({
- search: "foo ^ *",
- matches: [ { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo ^ # -> history, in title");
- yield check_autocomplete({
- search: "foo ^ #",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo ^ @ -> history, in url");
- yield check_autocomplete({
- search: "foo ^ @",
- matches: [ { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo ^ + -> history, is tag");
- yield check_autocomplete({
- search: "foo ^ +",
- matches: [ { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo ^ ~ -> history, is typed");
- yield check_autocomplete({
- search: "foo ^ ~",
- matches: [ { uri: uri4, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo * # -> is star, in title");
- yield check_autocomplete({
- search: "foo * #",
- matches: [ { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo * @ -> is star, in url");
- yield check_autocomplete({
- search: "foo * @",
- matches: [ { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo * + -> same as +");
- yield check_autocomplete({
- search: "foo * +",
- matches: [ { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo * ~ -> is star, is typed");
- yield check_autocomplete({
- search: "foo * ~",
- matches: [ { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo # @ -> in title, in url");
- yield check_autocomplete({
- search: "foo # @",
- matches: [ { uri: uri4, title: "foo.bar" },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo # + -> in title, is tag");
- yield check_autocomplete({
- search: "foo # +",
- matches: [ { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo # ~ -> in title, is typed");
- yield check_autocomplete({
- search: "foo # ~",
- matches: [ { uri: uri4, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo @ + -> in url, is tag");
- yield check_autocomplete({
- search: "foo @ +",
- matches: [ { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo @ ~ -> in url, is typed");
- yield check_autocomplete({
- search: "foo @ ~",
- matches: [ { uri: uri4, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- do_print("foo + ~ -> is tag, is typed");
- yield check_autocomplete({
- search: "foo + ~",
- matches: [ { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "tag" ] } ]
- });
-
- // Disable autoFill for the next tests, see test_autoFill_default_behavior.js
- // for specific tests.
- Services.prefs.setBoolPref("browser.urlbar.autoFill", false);
-
- // Test default usage by setting certain browser.urlbar.suggest.* prefs
- do_print("foo -> default history");
- setSuggestPrefsToFalse();
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- yield check_autocomplete({
- search: "foo",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar" },
- { uri: uri11, title: "title", tags: ["foo.bar"], style: [ "tag" ] } ]
- });
-
- do_print("foo -> default history, is star");
- setSuggestPrefsToFalse();
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
- yield check_autocomplete({
- search: "foo",
- matches: [ { uri: uri2, title: "foo.bar" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "foo.bar" },
- { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar"], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo -> default history, is star, is typed");
- setSuggestPrefsToFalse();
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.history.onlyTyped", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
- yield check_autocomplete({
- search: "foo",
- matches: [ { uri: uri4, title: "foo.bar" },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo -> is star");
- setSuggestPrefsToFalse();
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
- yield check_autocomplete({
- search: "foo",
- matches: [ { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("foo -> is star, is typed");
- setSuggestPrefsToFalse();
- // only typed should be ignored
- Services.prefs.setBoolPref("browser.urlbar.suggest.history.onlyTyped", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
- yield check_autocomplete({
- search: "foo",
- matches: [ { uri: uri6, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri7, title: "title", style: [ "bookmark" ] },
- { uri: uri8, title: "foo.bar", style: [ "bookmark" ] },
- { uri: uri9, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri11, title: "title", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] },
- { uri: uri12, title: "foo.bar", tags: [ "foo.bar" ], style: [ "bookmark-tag" ] } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_swap_protocol.js b/toolkit/components/places/tests/unifiedcomplete/test_swap_protocol.js
deleted file mode 100644
index 89ccc3206..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_swap_protocol.js
+++ /dev/null
@@ -1,153 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 bug 424717 to make sure searching with an existing location like
- * http://site/ also matches https://site/ or ftp://site/. Same thing for
- * ftp://site/ and https://site/.
- *
- * Test bug 461483 to make sure a search for "w" doesn't match the "www." from
- * site subdomains.
- */
-
-add_task(function* test_swap_protocol() {
- let uri1 = NetUtil.newURI("http://www.site/");
- let uri2 = NetUtil.newURI("http://site/");
- let uri3 = NetUtil.newURI("ftp://ftp.site/");
- let uri4 = NetUtil.newURI("ftp://site/");
- let uri5 = NetUtil.newURI("https://www.site/");
- let uri6 = NetUtil.newURI("https://site/");
- let uri7 = NetUtil.newURI("http://woohoo/");
- let uri8 = NetUtil.newURI("http://wwwwwwacko/");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "title" },
- { uri: uri2, title: "title" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "title" },
- { uri: uri5, title: "title" },
- { uri: uri6, title: "title" },
- { uri: uri7, title: "title" },
- { uri: uri8, title: "title" }
- ]);
-
- let allMatches = [
- { uri: uri1, title: "title" },
- { uri: uri2, title: "title" },
- { uri: uri3, title: "title" },
- { uri: uri4, title: "title" },
- { uri: uri5, title: "title" },
- { uri: uri6, title: "title" }
- ];
-
- // Disable autoFill to avoid handling the first result.
- Services.prefs.setBoolPref("browser.urlbar.autoFill", "false");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", false);
-
- do_print("http://www.site matches all site");
- yield check_autocomplete({
- search: "http://www.site",
- matches: allMatches
- });
-
- do_print("http://site matches all site");
- yield check_autocomplete({
- search: "http://site",
- matches: allMatches
- });
-
- do_print("ftp://ftp.site matches itself");
- yield check_autocomplete({
- search: "ftp://ftp.site",
- matches: [ { uri: uri3, title: "title" } ]
- });
-
- do_print("ftp://site matches all site");
- yield check_autocomplete({
- search: "ftp://site",
- matches: allMatches
- });
-
- do_print("https://www.site matches all site");
- yield check_autocomplete({
- search: "https://www.site",
- matches: allMatches
- });
-
- do_print("https://site matches all site");
- yield check_autocomplete({
- search: "https://site",
- matches: allMatches
- });
-
- do_print("www.site matches all site");
- yield check_autocomplete({
- search: "www.site",
- matches: allMatches
- });
-
- do_print("w matches none of www.");
- yield check_autocomplete({
- search: "w",
- matches: [ { uri: uri7, title: "title" },
- { uri: uri8, title: "title" } ]
- });
-
- do_print("http://w matches none of www.");
- yield check_autocomplete({
- search: "http://w",
- matches: [ { uri: uri7, title: "title" },
- { uri: uri8, title: "title" } ]
- });
-
- do_print("http://w matches none of www.");
- yield check_autocomplete({
- search: "http://www.w",
- matches: [ { uri: uri7, title: "title" },
- { uri: uri8, title: "title" } ]
- });
-
- do_print("ww matches none of www.");
- yield check_autocomplete({
- search: "ww",
- matches: [ { uri: uri8, title: "title" } ]
- });
-
- do_print("ww matches none of www.");
- yield check_autocomplete({
- search: "ww",
- matches: [ { uri: uri8, title: "title" } ]
- });
-
- do_print("http://ww matches none of www.");
- yield check_autocomplete({
- search: "http://ww",
- matches: [ { uri: uri8, title: "title" } ]
- });
-
- do_print("http://www.ww matches none of www.");
- yield check_autocomplete({
- search: "http://www.ww",
- matches: [ { uri: uri8, title: "title" } ]
- });
-
- do_print("www matches none of www.");
- yield check_autocomplete({
- search: "www",
- matches: [ { uri: uri8, title: "title" } ]
- });
-
- do_print("http://www matches none of www.");
- yield check_autocomplete({
- search: "http://www",
- matches: [ { uri: uri8, title: "title" } ]
- });
-
- do_print("http://www.www matches none of www.");
- yield check_autocomplete({
- search: "http://www.www",
- matches: [ { uri: uri8, title: "title" } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_tab_matches.js b/toolkit/components/places/tests/unifiedcomplete/test_tab_matches.js
deleted file mode 100644
index 646519c32..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_tab_matches.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim:set ts=2 sw=2 sts=2 et:
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var gTabRestrictChar = "%";
-
-add_task(function* test_tab_matches() {
- let uri1 = NetUtil.newURI("http://abc.com/");
- let uri2 = NetUtil.newURI("http://xyz.net/");
- let uri3 = NetUtil.newURI("about:mozilla");
- let uri4 = NetUtil.newURI("data:text/html,test");
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "ABC rocks" },
- { uri: uri2, title: "xyz.net - we're better than ABC" }
- ]);
- addOpenPages(uri1, 1);
- // Pages that cannot be registered in history.
- addOpenPages(uri3, 1);
- addOpenPages(uri4, 1);
-
- do_print("two results, normal result is a tab match");
- yield check_autocomplete({
- search: "abc.com",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("abc.com", "http://abc.com/", { heuristic: true }),
- makeSwitchToTabMatch("http://abc.com/", { title: "ABC rocks" }),
- makeSearchMatch("abc.com", { heuristic: false }) ]
- });
-
- do_print("three results, one tab match");
- yield check_autocomplete({
- search: "abc",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("abc", { heuristic: true }),
- makeSwitchToTabMatch("http://abc.com/", { title: "ABC rocks" }),
- { uri: uri2, title: "xyz.net - we're better than ABC", style: [ "favicon" ] } ]
- });
-
- do_print("three results, both normal results are tab matches");
- addOpenPages(uri2, 1);
- yield check_autocomplete({
- search: "abc",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("abc", { heuristic: true }),
- makeSwitchToTabMatch("http://abc.com/", { title: "ABC rocks" }),
- makeSwitchToTabMatch("http://xyz.net/", { title: "xyz.net - we're better than ABC" }) ]
- });
-
- do_print("three results, both normal results are tab matches, one has multiple tabs");
- addOpenPages(uri2, 5);
- yield check_autocomplete({
- search: "abc",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("abc", { heuristic: true }),
- makeSwitchToTabMatch("http://abc.com/", { title: "ABC rocks" }),
- makeSwitchToTabMatch("http://xyz.net/", { title: "xyz.net - we're better than ABC" }) ]
- });
-
- do_print("three results, no tab matches (disable-private-actions)");
- yield check_autocomplete({
- search: "abc",
- searchParam: "enable-actions disable-private-actions",
- matches: [ makeSearchMatch("abc", { heuristic: true }),
- { uri: uri1, title: "ABC rocks", style: [ "favicon" ] },
- { uri: uri2, title: "xyz.net - we're better than ABC", style: [ "favicon" ] } ]
- });
-
- do_print("two results (actions disabled)");
- yield check_autocomplete({
- search: "abc",
- searchParam: "",
- matches: [ { uri: uri1, title: "ABC rocks", style: [ "favicon" ] },
- { uri: uri2, title: "xyz.net - we're better than ABC", style: [ "favicon" ] } ]
- });
-
- do_print("three results, no tab matches");
- removeOpenPages(uri1, 1);
- removeOpenPages(uri2, 6);
- yield check_autocomplete({
- search: "abc",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("abc", { heuristic: true }),
- { uri: uri1, title: "ABC rocks", style: [ "favicon" ] },
- { uri: uri2, title: "xyz.net - we're better than ABC", style: [ "favicon" ] } ]
- });
-
- do_print("tab match search with restriction character");
- addOpenPages(uri1, 1);
- yield check_autocomplete({
- search: gTabRestrictChar + " abc",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(gTabRestrictChar + " abc", { heuristic: true }),
- makeSwitchToTabMatch("http://abc.com/", { title: "ABC rocks" }) ]
- });
-
- do_print("tab match with not-addable pages");
- yield check_autocomplete({
- search: "mozilla",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("mozilla", { heuristic: true }),
- makeSwitchToTabMatch("about:mozilla") ]
- });
-
- do_print("tab match with not-addable pages and restriction character");
- yield check_autocomplete({
- search: gTabRestrictChar + " mozilla",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(gTabRestrictChar + " mozilla", { heuristic: true }),
- makeSwitchToTabMatch("about:mozilla") ]
- });
-
- do_print("tab match with not-addable pages and only restriction character");
- yield check_autocomplete({
- search: gTabRestrictChar,
- searchParam: "enable-actions",
- matches: [ makeSearchMatch(gTabRestrictChar, { heuristic: true }),
- makeSwitchToTabMatch("http://abc.com/", { title: "ABC rocks" }),
- makeSwitchToTabMatch("about:mozilla"),
- makeSwitchToTabMatch("data:text/html,test") ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_trimming.js b/toolkit/components/places/tests/unifiedcomplete/test_trimming.js
deleted file mode 100644
index e55b009ff..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_trimming.js
+++ /dev/null
@@ -1,313 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-add_task(function* test_untrimmed_secure_www() {
- do_print("Searching for untrimmed https://www entry");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("https://www.mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "https://www.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_secure_www_path() {
- do_print("Searching for untrimmed https://www entry with path");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("https://www.mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/t",
- autofilled: "mozilla.org/test/",
- completed: "https://www.mozilla.org/test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_secure() {
- do_print("Searching for untrimmed https:// entry");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("https://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "https://mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_secure_path() {
- do_print("Searching for untrimmed https:// entry with path");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("https://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/t",
- autofilled: "mozilla.org/test/",
- completed: "https://mozilla.org/test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_www() {
- do_print("Searching for untrimmed http://www entry");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://www.mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "www.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_www_path() {
- do_print("Searching for untrimmed http://www entry with path");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://www.mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/t",
- autofilled: "mozilla.org/test/",
- completed: "http://www.mozilla.org/test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_ftp() {
- do_print("Searching for untrimmed ftp:// entry");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("ftp://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "ftp://mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untrimmed_ftp_path() {
- do_print("Searching for untrimmed ftp:// entry with path");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("ftp://mozilla.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "mozilla.org/t",
- autofilled: "mozilla.org/test/",
- completed: "ftp://mozilla.org/test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_priority_1() {
- do_print("Ensuring correct priority 1");
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("https://www.mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("https://mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("ftp://mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://www.mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://mozilla.org/test/"), transition: TRANSITION_TYPED }
- ]);
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_periority_2() {
- do_print( "Ensuring correct priority 2");
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("https://mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("ftp://mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://www.mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://mozilla.org/test/"), transition: TRANSITION_TYPED }
- ]);
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_periority_3() {
- do_print("Ensuring correct priority 3");
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("ftp://mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://www.mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://mozilla.org/test/"), transition: TRANSITION_TYPED }
- ]);
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_periority_4() {
- do_print("Ensuring correct priority 4");
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("http://www.mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://mozilla.org/test/"), transition: TRANSITION_TYPED }
- ]);
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_priority_5() {
- do_print("Ensuring correct priority 5");
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("ftp://mozilla.org/test/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("ftp://www.mozilla.org/test/"), transition: TRANSITION_TYPED }
- ]);
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "ftp://mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_priority_6() {
- do_print("Ensuring correct priority 6");
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("http://www.mozilla.org/test1/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://www.mozilla.org/test2/"), transition: TRANSITION_TYPED }
- ]);
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.org/",
- completed: "www.mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_longer_domain() {
- do_print("Ensuring longer domain can't match");
- // The .co should be preferred, but should not get the https from the .com.
- // The .co domain must be added later to activate the trigger bug.
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("https://mozilla.com/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://mozilla.co/"), transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://mozilla.co/"), transition: TRANSITION_TYPED }
- ]);
- yield check_autocomplete({
- search: "mo",
- autofilled: "mozilla.co/",
- completed: "mozilla.co/"
- });
-
- yield cleanup();
-});
-
-add_task(function* test_escaped_chars() {
- do_print("Searching for URL with characters that are normally escaped");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("https://www.mozilla.org/啊-test"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "https://www.mozilla.org/啊-test",
- autofilled: "https://www.mozilla.org/啊-test",
- completed: "https://www.mozilla.org/啊-test"
- });
- yield cleanup();
-});
-
-add_task(function* test_unsecure_secure() {
- do_print("Don't return unsecure URL when searching for secure ones");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://test.moz.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "https://test.moz.org/t",
- autofilled: "https://test.moz.org/test/",
- completed: "https://test.moz.org/test/"
- });
- yield cleanup();
-});
-
-add_task(function* test_unsecure_secure_domain() {
- do_print("Don't return unsecure domain when searching for secure ones");
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://test.moz.org/test/"),
- transition: TRANSITION_TYPED
- });
- yield check_autocomplete({
- search: "https://test.moz",
- autofilled: "https://test.moz.org/",
- completed: "https://test.moz.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untyped_www() {
- do_print("Untyped is not accounted for www");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("http://www.moz.org/test/") });
- yield check_autocomplete({
- search: "mo",
- autofilled: "moz.org/",
- completed: "moz.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untyped_ftp() {
- do_print("Untyped is not accounted for ftp");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("ftp://moz.org/test/") });
- yield check_autocomplete({
- search: "mo",
- autofilled: "moz.org/",
- completed: "moz.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untyped_secure() {
- do_print("Untyped is not accounted for https");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("https://moz.org/test/") });
- yield check_autocomplete({
- search: "mo",
- autofilled: "moz.org/",
- completed: "moz.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untyped_secure_www() {
- do_print("Untyped is not accounted for https://www");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("https://www.moz.org/test/") });
- yield check_autocomplete({
- search: "mo",
- autofilled: "moz.org/",
- completed: "moz.org/"
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_typed.js b/toolkit/components/places/tests/unifiedcomplete/test_typed.js
deleted file mode 100644
index 72f76159c..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_typed.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/. */
-
-// First do searches with typed behavior forced to false, so later tests will
-// ensure autocomplete is able to dinamically switch behavior.
-
-const FAVICON_HREF = NetUtil.newURI(do_get_file("../favicons/favicon-normal16.png")).spec;
-
-add_task(function* test_domain() {
- do_print("Searching for domain should autoFill it");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://mozilla.org/link/"));
- yield setFaviconForHref("http://mozilla.org/link/", FAVICON_HREF);
- yield check_autocomplete({
- search: "moz",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/",
- icon: "moz-anno:favicon:" + FAVICON_HREF
- });
- yield cleanup();
-});
-
-add_task(function* test_url() {
- do_print("Searching for url should autoFill it");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://mozilla.org/link/"));
- yield setFaviconForHref("http://mozilla.org/link/", FAVICON_HREF);
- yield check_autocomplete({
- search: "mozilla.org/li",
- autofilled: "mozilla.org/link/",
- completed: "http://mozilla.org/link/",
- icon: "moz-anno:favicon:" + FAVICON_HREF
- });
- yield cleanup();
-});
-
-// Now do searches with typed behavior forced to true.
-
-add_task(function* test_untyped_domain() {
- do_print("Searching for non-typed domain should not autoFill it");
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://mozilla.org/link/"));
- yield check_autocomplete({
- search: "moz",
- autofilled: "moz",
- completed: "moz"
- });
- yield cleanup();
-});
-
-add_task(function* test_typed_domain() {
- do_print("Searching for typed domain should autoFill it");
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("http://mozilla.org/typed/"),
- transition: TRANSITION_TYPED });
- yield check_autocomplete({
- search: "moz",
- autofilled: "mozilla.org/",
- completed: "mozilla.org/"
- });
- yield cleanup();
-});
-
-add_task(function* test_untyped_url() {
- do_print("Searching for non-typed url should not autoFill it");
- yield PlacesTestUtils.addVisits(NetUtil.newURI("http://mozilla.org/link/"));
- yield check_autocomplete({
- search: "mozilla.org/li",
- autofilled: "mozilla.org/li",
- completed: "mozilla.org/li"
- });
- yield cleanup();
-});
-
-add_task(function* test_typed_url() {
- do_print("Searching for typed url should autoFill it");
- yield PlacesTestUtils.addVisits({ uri: NetUtil.newURI("http://mozilla.org/link/"),
- transition: TRANSITION_TYPED });
- yield check_autocomplete({
- search: "mozilla.org/li",
- autofilled: "mozilla.org/link/",
- completed: "http://mozilla.org/link/"
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_visit_url.js b/toolkit/components/places/tests/unifiedcomplete/test_visit_url.js
deleted file mode 100644
index eaccb23e5..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_visit_url.js
+++ /dev/null
@@ -1,186 +0,0 @@
-add_task(function*() {
- do_print("visit url, no protocol");
- yield check_autocomplete({
- search: "mozilla.org",
- searchParam: "enable-actions",
- matches: [
- { uri: makeActionURI("visiturl", {url: "http://mozilla.org/", input: "mozilla.org"}), title: "http://mozilla.org/", style: [ "action", "visiturl", "heuristic" ] },
- { uri: makeActionURI("searchengine", {engineName: "MozSearch", input: "mozilla.org", searchQuery: "mozilla.org"}), title: "MozSearch", style: ["action", "searchengine"] }
- ]
- });
-
- do_print("visit url, no protocol but with 2 dots");
- yield check_autocomplete({
- search: "www.mozilla.org",
- searchParam: "enable-actions",
- matches: [
- { uri: makeActionURI("visiturl", {url: "http://www.mozilla.org/", input: "www.mozilla.org"}), title: "http://www.mozilla.org/", style: [ "action", "visiturl", "heuristic" ] },
- { uri: makeActionURI("searchengine", {engineName: "MozSearch", input: "www.mozilla.org", searchQuery: "www.mozilla.org"}), title: "MozSearch", style: ["action", "searchengine"] }
- ]
- });
-
- do_print("visit url, no protocol but with 3 dots");
- yield check_autocomplete({
- search: "www.mozilla.org.tw",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("visiturl", {url: "http://www.mozilla.org.tw/", input: "www.mozilla.org.tw"}), title: "http://www.mozilla.org.tw/", style: [ "action", "visiturl", "heuristic" ] } ]
- });
-
- do_print("visit url, with protocol but with 2 dots");
- yield check_autocomplete({
- search: "https://www.mozilla.org",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("visiturl", {url: "https://www.mozilla.org/", input: "https://www.mozilla.org"}), title: "https://www.mozilla.org/", style: [ "action", "visiturl", "heuristic" ] } ]
- });
-
- do_print("visit url, with protocol but with 3 dots");
- yield check_autocomplete({
- search: "https://www.mozilla.org.tw",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("visiturl", {url: "https://www.mozilla.org.tw/", input: "https://www.mozilla.org.tw"}), title: "https://www.mozilla.org.tw/", style: [ "action", "visiturl", "heuristic" ] } ]
- });
-
- do_print("visit url, with protocol");
- yield check_autocomplete({
- search: "https://mozilla.org",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("visiturl", {url: "https://mozilla.org/", input: "https://mozilla.org"}), title: "https://mozilla.org/", style: [ "action", "visiturl", "heuristic" ] } ]
- });
-
- do_print("visit url, about: protocol (no host)");
- yield check_autocomplete({
- search: "about:config",
- searchParam: "enable-actions",
- matches: [ { uri: makeActionURI("visiturl", {url: "about:config", input: "about:config"}), title: "about:config", style: [ "action", "visiturl", "heuristic" ] } ]
- });
-
- // This is distinct because of how we predict being able to url autofill via
- // host lookups.
- do_print("visit url, host matching visited host but not visited url");
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("http://mozilla.org/wine/"), title: "Mozilla Wine", transition: TRANSITION_TYPED },
- ]);
- yield check_autocomplete({
- search: "mozilla.org/rum",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("mozilla.org/rum", "http://mozilla.org/rum", { heuristic: true }) ]
- });
-
- // And hosts with no dot in them are special, due to requiring whitelisting.
- do_print("non-whitelisted host");
- yield check_autocomplete({
- search: "firefox",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("firefox", { heuristic: true }) ]
- });
-
- do_print("url with non-whitelisted host");
- yield check_autocomplete({
- search: "firefox/get",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("firefox/get", "http://firefox/get", { heuristic: true }) ]
- });
-
- Services.prefs.setBoolPref("browser.fixup.domainwhitelist.firefox", true);
- do_register_cleanup(() => {
- Services.prefs.clearUserPref("browser.fixup.domainwhitelist.firefox");
- });
-
- do_print("whitelisted host");
- yield check_autocomplete({
- search: "firefox",
- searchParam: "enable-actions",
- matches: [
- makeVisitMatch("firefox", "http://firefox/", { heuristic: true }),
- makeSearchMatch("firefox", { heuristic: false })
- ]
- });
-
- do_print("url with whitelisted host");
- yield check_autocomplete({
- search: "firefox/get",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("firefox/get", "http://firefox/get", { heuristic: true }) ]
- });
-
- do_print("visit url, host matching visited host but not visited url, whitelisted host");
- Services.prefs.setBoolPref("browser.fixup.domainwhitelist.mozilla", true);
- do_register_cleanup(() => {
- Services.prefs.clearUserPref("browser.fixup.domainwhitelist.mozilla");
- });
- yield check_autocomplete({
- search: "mozilla/rum",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("mozilla/rum", "http://mozilla/rum", { heuristic: true }) ]
- });
-
- // ipv4 and ipv6 literal addresses should offer to visit.
- do_print("visit url, ipv4 literal");
- yield check_autocomplete({
- search: "127.0.0.1",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("127.0.0.1", "http://127.0.0.1/", { heuristic: true }) ]
- });
-
- do_print("visit url, ipv6 literal");
- yield check_autocomplete({
- search: "[2001:db8::1]",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("[2001:db8::1]", "http://[2001:db8::1]/", { heuristic: true }) ]
- });
-
- // Setting keyword.enabled to false should always try to visit.
- let keywordEnabled = Services.prefs.getBoolPref("keyword.enabled");
- Services.prefs.setBoolPref("keyword.enabled", false);
- do_register_cleanup(() => {
- Services.prefs.clearUserPref("keyword.enabled");
- });
- do_print("visit url, keyword.enabled = false");
- yield check_autocomplete({
- search: "bacon",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("bacon", "http://bacon/", { heuristic: true }) ]
- });
- do_print("visit two word query, keyword.enabled = false");
- yield check_autocomplete({
- search: "bacon lovers",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("bacon lovers", "bacon lovers", { heuristic: true }) ]
- });
- Services.prefs.setBoolPref("keyword.enabled", keywordEnabled);
-
- do_print("visit url, scheme+host");
- yield check_autocomplete({
- search: "http://example",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("http://example", "http://example/", { heuristic: true }) ]
- });
-
- do_print("visit url, scheme+host");
- yield check_autocomplete({
- search: "ftp://example",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("ftp://example", "ftp://example/", { heuristic: true }) ]
- });
-
- do_print("visit url, host+port");
- yield check_autocomplete({
- search: "example:8080",
- searchParam: "enable-actions",
- matches: [ makeVisitMatch("example:8080", "http://example:8080/", { heuristic: true }) ]
- });
-
- do_print("numerical operations that look like urls should search");
- yield check_autocomplete({
- search: "123/12",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("123/12", { heuristic: true }) ]
- });
-
- do_print("numerical operations that look like urls should search");
- yield check_autocomplete({
- search: "123.12/12.1",
- searchParam: "enable-actions",
- matches: [ makeSearchMatch("123.12/12.1", { heuristic: true }) ]
- });
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_word_boundary_search.js b/toolkit/components/places/tests/unifiedcomplete/test_word_boundary_search.js
deleted file mode 100644
index f79573ae6..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_word_boundary_search.js
+++ /dev/null
@@ -1,175 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 bug 393678 to make sure matches against the url, title, tags are only
- * made on word boundaries instead of in the middle of words.
- *
- * Make sure we don't try matching one after a CamelCase because the upper-case
- * isn't really a word boundary. (bug 429498)
- *
- * Bug 429531 provides switching between "must match on word boundary" and "can
- * match," so leverage "must match" pref for checking word boundary logic and
- * make sure "can match" matches anywhere.
- */
-
-var katakana = ["\u30a8", "\u30c9"]; // E, Do
-var ideograph = ["\u4efb", "\u5929", "\u5802"]; // Nin Ten Do
-
-add_task(function* test_escape() {
- Services.prefs.setBoolPref("browser.urlbar.autoFill.searchEngines", false);
-
- let uri1 = NetUtil.newURI("http://matchme/");
- let uri2 = NetUtil.newURI("http://dontmatchme/");
- let uri3 = NetUtil.newURI("http://title/1");
- let uri4 = NetUtil.newURI("http://title/2");
- let uri5 = NetUtil.newURI("http://tag/1");
- let uri6 = NetUtil.newURI("http://tag/2");
- let uri7 = NetUtil.newURI("http://crazytitle/");
- let uri8 = NetUtil.newURI("http://katakana/");
- let uri9 = NetUtil.newURI("http://ideograph/");
- let uri10 = NetUtil.newURI("http://camel/pleaseMatchMe/");
-
- yield PlacesTestUtils.addVisits([
- { uri: uri1, title: "title1" },
- { uri: uri2, title: "title1" },
- { uri: uri3, title: "matchme2" },
- { uri: uri4, title: "dontmatchme3" },
- { uri: uri5, title: "title1" },
- { uri: uri6, title: "title1" },
- { uri: uri7, title: "!@#$%^&*()_+{}|:<>?word" },
- { uri: uri8, title: katakana.join("") },
- { uri: uri9, title: ideograph.join("") },
- { uri: uri10, title: "title1" }
- ]);
- yield addBookmark( { uri: uri5, title: "title1", tags: [ "matchme2" ] } );
- yield addBookmark( { uri: uri6, title: "title1", tags: [ "dontmatchme3" ] } );
-
- // match only on word boundaries
- Services.prefs.setIntPref("browser.urlbar.matchBehavior", 2);
-
- do_print("Match 'match' at the beginning or after / or on a CamelCase");
- yield check_autocomplete({
- search: "match",
- matches: [ { uri: uri1, title: "title1" },
- { uri: uri3, title: "matchme2" },
- { uri: uri5, title: "title1", tags: [ "matchme2" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "title1" } ]
- });
-
- do_print("Match 'dont' at the beginning or after /");
- yield check_autocomplete({
- search: "dont",
- matches: [ { uri: uri2, title: "title1" },
- { uri: uri4, title: "dontmatchme3" },
- { uri: uri6, title: "title1", tags: [ "dontmatchme3" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("Match 'match' at the beginning or after / or on a CamelCase");
- yield check_autocomplete({
- search: "2",
- matches: [ { uri: uri3, title: "matchme2" },
- { uri: uri4, title: "dontmatchme3" },
- { uri: uri5, title: "title1", tags: [ "matchme2" ], style: [ "bookmark-tag" ] },
- { uri: uri6, title: "title1", tags: [ "dontmatchme3" ], style: [ "bookmark-tag" ] } ]
- });
-
- do_print("Match 't' at the beginning or after /");
- yield check_autocomplete({
- search: "t",
- matches: [ { uri: uri1, title: "title1" },
- { uri: uri2, title: "title1" },
- { uri: uri3, title: "matchme2" },
- { uri: uri4, title: "dontmatchme3" },
- { uri: uri5, title: "title1", tags: [ "matchme2" ], style: [ "bookmark-tag" ] },
- { uri: uri6, title: "title1", tags: [ "dontmatchme3" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "title1" } ]
- });
-
- do_print("Match 'word' after many consecutive word boundaries");
- yield check_autocomplete({
- search: "word",
- matches: [ { uri: uri7, title: "!@#$%^&*()_+{}|:<>?word" } ]
- });
-
- do_print("Match a word boundary '/' for everything");
- yield check_autocomplete({
- search: "/",
- matches: [ { uri: uri1, title: "title1" },
- { uri: uri2, title: "title1" },
- { uri: uri3, title: "matchme2" },
- { uri: uri4, title: "dontmatchme3" },
- { uri: uri5, title: "title1", tags: [ "matchme2" ], style: [ "bookmark-tag" ] },
- { uri: uri6, title: "title1", tags: [ "dontmatchme3" ], style: [ "bookmark-tag" ] },
- { uri: uri7, title: "!@#$%^&*()_+{}|:<>?word" },
- { uri: uri8, title: katakana.join("") },
- { uri: uri9, title: ideograph.join("") },
- { uri: uri10, title: "title1" } ]
- });
-
- do_print("Match word boundaries '()_+' that are among word boundaries");
- yield check_autocomplete({
- search: "()_+",
- matches: [ { uri: uri7, title: "!@#$%^&*()_+{}|:<>?word" } ]
- });
-
- do_print("Katakana characters form a string, so match the beginning");
- yield check_autocomplete({
- search: katakana[0],
- matches: [ { uri: uri8, title: katakana.join("") } ]
- });
-
-/*
- do_print("Middle of a katakana word shouldn't be matched");
- yield check_autocomplete({
- search: katakana[1],
- matches: [ ]
- });
-*/
- do_print("Ideographs are treated as words so 'nin' is one word");
- yield check_autocomplete({
- search: ideograph[0],
- matches: [ { uri: uri9, title: ideograph.join("") } ]
- });
-
- do_print("Ideographs are treated as words so 'ten' is another word");
- yield check_autocomplete({
- search: ideograph[1],
- matches: [ { uri: uri9, title: ideograph.join("") } ]
- });
-
- do_print("Ideographs are treated as words so 'do' is yet another word");
- yield check_autocomplete({
- search: ideograph[2],
- matches: [ { uri: uri9, title: ideograph.join("") } ]
- });
-
- do_print("Extra negative assert that we don't match in the middle");
- yield check_autocomplete({
- search: "ch",
- matches: [ ]
- });
-
- do_print("Don't match one character after a camel-case word boundary (bug 429498)");
- yield check_autocomplete({
- search: "atch",
- matches: [ ]
- });
-
- // match against word boundaries and anywhere
- Services.prefs.setIntPref("browser.urlbar.matchBehavior", 1);
-
- yield check_autocomplete({
- search: "tch",
- matches: [ { uri: uri1, title: "title1" },
- { uri: uri2, title: "title1" },
- { uri: uri3, title: "matchme2" },
- { uri: uri4, title: "dontmatchme3" },
- { uri: uri5, title: "title1", tags: [ "matchme2" ], style: [ "bookmark-tag" ] },
- { uri: uri6, title: "title1", tags: [ "dontmatchme3" ], style: [ "bookmark-tag" ] },
- { uri: uri10, title: "title1" } ]
- });
-
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/test_zero_frecency.js b/toolkit/components/places/tests/unifiedcomplete/test_zero_frecency.js
deleted file mode 100644
index adf638886..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/test_zero_frecency.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Ensure inline autocomplete doesn't return zero frecency pages.
-
-add_task(function* test_zzero_frec_domain() {
- do_print("Searching for zero frecency domain should not autoFill it");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/framed_link/"),
- transition: TRANSITION_FRAMED_LINK
- });
- yield check_autocomplete({
- search: "moz",
- autofilled: "moz",
- completed: "moz"
- });
- yield cleanup();
-});
-
-add_task(function* test_zzero_frec_url() {
- do_print("Searching for zero frecency url should not autoFill it");
- Services.prefs.setBoolPref("browser.urlbar.autoFill.typed", false);
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://mozilla.org/framed_link/"),
- transition: TRANSITION_FRAMED_LINK
- });
- yield check_autocomplete({
- search: "mozilla.org/f",
- autofilled: "mozilla.org/f",
- completed: "mozilla.org/f"
- });
- yield cleanup();
-});
diff --git a/toolkit/components/places/tests/unifiedcomplete/xpcshell.ini b/toolkit/components/places/tests/unifiedcomplete/xpcshell.ini
deleted file mode 100644
index 60ef8c48a..000000000
--- a/toolkit/components/places/tests/unifiedcomplete/xpcshell.ini
+++ /dev/null
@@ -1,49 +0,0 @@
-[DEFAULT]
-head = head_autocomplete.js
-tail =
-skip-if = toolkit == 'android'
-support-files =
- data/engine-rel-searchform.xml
- data/engine-suggestions.xml
- !/toolkit/components/places/tests/favicons/favicon-normal16.png
-
-[test_416211.js]
-[test_416214.js]
-[test_417798.js]
-[test_418257.js]
-[test_422277.js]
-[test_autocomplete_functional.js]
-[test_autocomplete_on_value_removed_479089.js]
-[test_autofill_default_behavior.js]
-[test_avoid_middle_complete.js]
-[test_avoid_stripping_to_empty_tokens.js]
-[test_casing.js]
-[test_do_not_trim.js]
-[test_download_embed_bookmarks.js]
-[test_dupe_urls.js]
-[test_empty_search.js]
-[test_enabled.js]
-[test_escape_self.js]
-[test_extension_matches.js]
-[test_ignore_protocol.js]
-[test_keyword_search.js]
-[test_keyword_search_actions.js]
-[test_keywords.js]
-[test_match_beginning.js]
-[test_multi_word_search.js]
-[test_query_url.js]
-[test_remote_tab_matches.js]
-skip-if = !sync
-[test_search_engine_alias.js]
-[test_search_engine_current.js]
-[test_search_engine_host.js]
-[test_search_engine_restyle.js]
-[test_search_suggestions.js]
-[test_special_search.js]
-[test_swap_protocol.js]
-[test_tab_matches.js]
-[test_trimming.js]
-[test_typed.js]
-[test_visit_url.js]
-[test_word_boundary_search.js]
-[test_zero_frecency.js]
diff --git a/toolkit/components/places/tests/unit/.eslintrc.js b/toolkit/components/places/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/places/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/places/tests/unit/bookmarks.corrupt.html b/toolkit/components/places/tests/unit/bookmarks.corrupt.html
deleted file mode 100644
index 3cf43367f..000000000
--- a/toolkit/components/places/tests/unit/bookmarks.corrupt.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<!DOCTYPE NETSCAPE-Bookmark-file-1>
-<!-- This is an automatically generated file.
- It will be read and overwritten.
- DO NOT EDIT! -->
-<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
-<TITLE>Bookmarks</TITLE>
-<H1 LAST_MODIFIED="1177541029">Bookmarks</H1>
-
-<DL><p>
- <DT><H3 ID="rdf:#$ZvPhC3">Mozilla Firefox</H3>
- <DL><p>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/help/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$22iCK1">Help and Tutorials</A>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/customize/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$32iCK1">Customize Firefox</A>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/community/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$42iCK1">Get Involved</A>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/about/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$52iCK1">About Us</A>
- <DT><A HREF="b0rked" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$52iCK1">About Us</A>
- </DL><p>
- <DT><H3 ADD_DATE="1177541020" LAST_MODIFIED="1177541050" ID="rdf:#$74Gpx2">test</H3>
-<DD>folder test comment
- <DL><p>
- <DT><A HREF="http://test/post" ADD_DATE="1177375336" LAST_MODIFIED="1177375423" SHORTCUTURL="test" WEB_PANEL="true" POST_DATA="hidden1%3Dbar&amp;text1%3D%25s" LAST_CHARSET="ISO-8859-1" ID="rdf:#$pYFe7">test post keyword</A>
-<DD>item description
- </DL>
- <DT><H3 UNFILED_BOOKMARKS_FOLDER="true">Unsorted Bookmarks</H3>
- <DL><p>
- <DT><A HREF="http://example.tld">Example.tld</A>
- </DL><p>
- <DT><H3 LAST_MODIFIED="1177541040" PERSONAL_TOOLBAR_FOLDER="true" ID="rdf:#$FvPhC3">Bookmarks Toolbar Folder</H3>
-<DD>Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar
- <DL><p>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/central/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$GvPhC3">Getting Started</A>
- <DT><A HREF="http://en-US.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/" LAST_MODIFIED="1177541035" FEEDURL="http://en-US.fxfeeds.mozilla.com/en-US/firefox/headlines.xml" ID="rdf:#$HvPhC3">Latest Headlines</A>
- <DT><A HREF="http://bogus-icon.mozilla.com/" ICON="b0rked" ID="rdf:#$GvPhC3">Getting Started</A>
-<DD>Livemark test comment
- </DL><p>
-</DL><p>
diff --git a/toolkit/components/places/tests/unit/bookmarks.json b/toolkit/components/places/tests/unit/bookmarks.json
deleted file mode 100644
index afe62abae..000000000
--- a/toolkit/components/places/tests/unit/bookmarks.json
+++ /dev/null
@@ -1 +0,0 @@
-{"guid":"root________","title":"","id":1,"dateAdded":1361551978957783,"lastModified":1361551978957783,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"guid":"menu________","title":"Bookmarks Menu","id":2,"parent":1,"dateAdded":1361551978957783,"lastModified":1361551979382837,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"guid":"OCyeUO5uu9FF","title":"Mozilla Firefox","id":6,"parent":2,"dateAdded":1361551979350273,"lastModified":1361551979376699,"type":"text/x-moz-place-container","children":[{"guid":"OCyeUO5uu9FG","title":"Help and Tutorials","id":7,"parent":6,"dateAdded":1361551979356436,"lastModified":1361551979362718,"type":"text/x-moz-place","uri":"http://en-us.www.mozilla.com/en-US/firefox/help/", "icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="},{"guid":"OCyeUO5uu9FH","index":1,"title":"Customize Firefox","id":8,"parent":6,"dateAdded":1361551979365662,"lastModified":1361551979368077,"type":"text/x-moz-place","uri":"http://en-us.www.mozilla.com/en-US/firefox/customize/", "icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="},{"guid":"OCyeUO5uu9FI","index":2,"title":"Get Involved","id":9,"parent":6,"dateAdded":1361551979371071,"lastModified":1361551979373745,"type":"text/x-moz-place","uri":"http://en-us.www.mozilla.com/en-US/firefox/community/", "icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="},{"guid":"OCyeUO5uu9FJ","index":3,"title":"About Us","id":10,"parent":6,"dateAdded":1361551979376699,"lastModified":1361551979379060,"type":"text/x-moz-place","uri":"http://en-us.www.mozilla.com/en-US/about/", "icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="}]},{"guid":"OCyeUO5uu9FK","index":1,"title":"","id":11,"parent":2,"dateAdded":1361551979380988,"lastModified":1361551979380988,"type":"text/x-moz-place-separator"},{"guid":"OCyeUO5uu9FL","index":2,"title":"test","id":12,"parent":2,"dateAdded":1177541020000000,"lastModified":1177541050000000,"annos":[{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"folder test comment"}],"type":"text/x-moz-place-container","children":[{"guid":"OCyeUO5uu9GX","title":"test post keyword","id":13,"parent":12,"dateAdded":1177375336000000,"lastModified":1177375423000000,"annos":[{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"item description"},{"name":"bookmarkProperties/POSTData","flags":0,"expires":4,"mimeType":null,"type":3,"value":"hidden1%3Dbar&text1%3D%25s"},{"name":"bookmarkProperties/loadInSidebar","flags":0,"expires":4,"mimeType":null,"type":1,"value":1}],"type":"text/x-moz-place","uri":"http://test/post","keyword":"test","charset":"ISO-8859-1"}]}]},{"index":1,"title":"Bookmarks Toolbar","id":3,"parent":1,"dateAdded":1361551978957783,"lastModified":1177541050000000,"annos":[{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar"}],"type":"text/x-moz-place-container","root":"toolbarFolder","children":[{"guid":"OCyeUO5uu9FB","title":"Getting Started","id":15,"parent":3,"dateAdded":1361551979409695,"lastModified":1361551979412080,"type":"text/x-moz-place","uri":"http://en-us.www.mozilla.com/en-US/firefox/central/", "icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="},{"guid":"OCyeUO5uu9FR","index":1,"title":"Latest Headlines","id":16,"parent":3,"dateAdded":1361551979451584,"lastModified":1361551979457086,"livemark":1,"annos":[{"name":"placesInternal/READ_ONLY","flags":0,"expires":4,"mimeType":null,"type":1,"value":1},{"name":"livemark/feedURI","flags":0,"expires":4,"mimeType":null,"type":3,"value":"http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml"},{"name":"livemark/siteURI","flags":0,"expires":4,"mimeType":null,"type":3,"value":"http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/"}],"type":"text/x-moz-place-container","children":[]}]},{"index":2,"title":"Tags","id":4,"parent":1,"dateAdded":1361551978957783,"lastModified":1361551978957783,"type":"text/x-moz-place-container","root":"tagsFolder","children":[]},{"index":3,"title":"Unsorted Bookmarks","id":5,"parent":1,"dateAdded":1361551978957783,"lastModified":1177541050000000,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder","children":[{"guid":"OCyeUO5uu9FW","title":"Example.tld","id":14,"parent":5,"dateAdded":1361551979401846,"lastModified":1361551979402952,"type":"text/x-moz-place","uri":"http://example.tld/"}]}]}
diff --git a/toolkit/components/places/tests/unit/bookmarks.preplaces.html b/toolkit/components/places/tests/unit/bookmarks.preplaces.html
deleted file mode 100644
index 2e5a1baf0..000000000
--- a/toolkit/components/places/tests/unit/bookmarks.preplaces.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<!DOCTYPE NETSCAPE-Bookmark-file-1>
-<!-- This is an automatically generated file.
- It will be read and overwritten.
- DO NOT EDIT! -->
-<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
-<TITLE>Bookmarks</TITLE>
-<H1 LAST_MODIFIED="1177541029">Bookmarks</H1>
-
-<DL><p>
- <DT><H3 ID="rdf:#$ZvPhC3">Mozilla Firefox</H3>
- <DL><p>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/help/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$22iCK1">Help and Tutorials</A>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/customize/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$32iCK1">Customize Firefox</A>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/community/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$42iCK1">Get Involved</A>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/about/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$52iCK1">About Us</A>
- </DL><p>
- <HR>
- <DT><H3 ADD_DATE="1177541020" LAST_MODIFIED="1177541050" ID="rdf:#$74Gpx2">test</H3>
-<DD>folder test comment
- <DL><p>
- <DT><A HREF="http://test/post" ADD_DATE="1177375336" LAST_MODIFIED="1177375423" SHORTCUTURL="test" WEB_PANEL="true" POST_DATA="hidden1%3Dbar&amp;text1%3D%25s" LAST_CHARSET="ISO-8859-1" ID="rdf:#$pYFe7">test post keyword</A>
-<DD>item description
- </DL>
- <DT><H3 UNFILED_BOOKMARKS_FOLDER="true">Unsorted Bookmarks</H3>
- <DL><p>
- <DT><A HREF="http://example.tld">Example.tld</A>
- </DL><p>
- <DT><H3 LAST_MODIFIED="1177541040" PERSONAL_TOOLBAR_FOLDER="true" ID="rdf:#$FvPhC3">Bookmarks Toolbar Folder</H3>
-<DD>Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar
- <DL><p>
- <DT><A HREF="http://en-US.www.mozilla.com/en-US/firefox/central/" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg==" ID="rdf:#$GvPhC3">Getting Started</A>
- <DT><A HREF="http://en-US.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/" LAST_MODIFIED="1177541035" FEEDURL="http://en-US.fxfeeds.mozilla.com/en-US/firefox/headlines.xml" ID="rdf:#$HvPhC3">Latest Headlines</A>
-<DD>Livemark test comment
- </DL><p>
-</DL><p>
diff --git a/toolkit/components/places/tests/unit/bookmarks_html_singleframe.html b/toolkit/components/places/tests/unit/bookmarks_html_singleframe.html
deleted file mode 100644
index 9fe662f32..000000000
--- a/toolkit/components/places/tests/unit/bookmarks_html_singleframe.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<!DOCTYPE NETSCAPE-Bookmark-file-1>
- <HTML>
- <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
- <Title>Bookmarks</Title>
- <H1>Bookmarks</H1>
- <DT><H3>Subtitle</H3>
- <DL><p>
- <DT><A HREF="http://www.mozilla.org/">Mozilla</A>
- </DL><p>
-</HTML>
diff --git a/toolkit/components/places/tests/unit/bug476292.sqlite b/toolkit/components/places/tests/unit/bug476292.sqlite
deleted file mode 100644
index 43130cb51..000000000
--- a/toolkit/components/places/tests/unit/bug476292.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/unit/corruptDB.sqlite b/toolkit/components/places/tests/unit/corruptDB.sqlite
deleted file mode 100644
index b234246ca..000000000
--- a/toolkit/components/places/tests/unit/corruptDB.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/unit/default.sqlite b/toolkit/components/places/tests/unit/default.sqlite
deleted file mode 100644
index 8fbd3bc9a..000000000
--- a/toolkit/components/places/tests/unit/default.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/unit/head_bookmarks.js b/toolkit/components/places/tests/unit/head_bookmarks.js
deleted file mode 100644
index 842a66b31..000000000
--- a/toolkit/components/places/tests/unit/head_bookmarks.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// Import common head.
-{
- let commonFile = do_get_file("../head_common.js", false);
- let uri = Services.io.newFileURI(commonFile);
- Services.scriptloader.loadSubScript(uri.spec, this);
-}
-
-// Put any other stuff relative to this test folder below.
diff --git a/toolkit/components/places/tests/unit/livemark.xml b/toolkit/components/places/tests/unit/livemark.xml
deleted file mode 100644
index db2ea9023..000000000
--- a/toolkit/components/places/tests/unit/livemark.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<feed xmlns="http://www.w3.org/2005/Atom">
- <title>Livemark Feed</title>
- <link href="https://example.com/"/>
- <updated>2016-08-09T19:51:45.147Z</updated>
- <author>
- <name>John Doe</name>
- </author>
- <id>urn:uuid:e7947414-6ee0-4009-ae75-8b0ad3c6894b</id>
- <entry>
- <title>Some awesome article</title>
- <link href="https://example.com/some-article"/>
- <id>urn:uuid:d72ce019-0a56-4a0b-ac03-f66117d78141</id>
- <updated>2016-08-09T19:57:22.178Z</updated>
- <summary>My great article summary.</summary>
- </entry>
-</feed>
diff --git a/toolkit/components/places/tests/unit/mobile_bookmarks_folder_import.json b/toolkit/components/places/tests/unit/mobile_bookmarks_folder_import.json
deleted file mode 100644
index 38762b3f1..000000000
--- a/toolkit/components/places/tests/unit/mobile_bookmarks_folder_import.json
+++ /dev/null
@@ -1 +0,0 @@
-{"guid":"root________","title":"","index":0,"dateAdded":1475084731479000,"lastModified":1475084731479000,"id":1,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"guid":"menu________","title":"Bookmarks Menu","index":0,"dateAdded":1475084731479000,"lastModified":1475084731768000,"id":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"guid":"X6lUyOspVYwi","title":"Test Pilot","index":0,"dateAdded":1475084731768000,"lastModified":1475084731768000,"id":3,"type":"text/x-moz-place","uri":"https://testpilot.firefox.com/"},{"guid":"XF4yRP6bTuil","title":"Mobile bookmarks query","index":1,"dateAdded":1475084731768000,"lastModified":1475084731768000,"id":11,"type":"text/x-moz-place","uri":"place:folder=101"}]},{"guid":"toolbar_____","title":"Bookmarks Toolbar","index":1,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":4,"type":"text/x-moz-place-container","root":"toolbarFolder","children":[{"guid":"buy7711R3ZgE","title":"MDN","index":0,"dateAdded":1475084731769000,"lastModified":1475084731769000,"id":5,"type":"text/x-moz-place","uri":"https://developer.mozilla.org"}]},{"guid":"3qmd_imziEBE","title":"Mobile Bookmarks","index":5,"dateAdded":1475084731479000,"lastModified":1475084731770000,"id":101,"annos":[{"name":"mobile/bookmarksRoot","flags":0,"expires":4,"value":1},{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"A description of the mobile folder that should be ignored on import"}],"type":"text/x-moz-place-container","children":[{"guid":"_o8e1_zxTJFg","title":"Get Firefox!","index":0,"dateAdded":1475084731769000,"lastModified":1475084731769000,"id":7,"type":"text/x-moz-place","uri":"http://getfirefox.com/"},{"guid":"QCtSqkVYUbXB","title":"Get Thunderbird!","index":1,"dateAdded":1475084731770000,"lastModified":1475084731770000,"id":8,"type":"text/x-moz-place","uri":"http://getthunderbird.com/"}]},{"guid":"unfiled_____","title":"Other Bookmarks","index":3,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":9,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder","children":[{"guid":"KIa9iKZab2Z5","title":"Add-ons","index":0,"dateAdded":1475084731769000,"lastModified":1475084731769000,"id":10,"type":"text/x-moz-place","uri":"https://addons.mozilla.org"}]}]} \ No newline at end of file
diff --git a/toolkit/components/places/tests/unit/mobile_bookmarks_folder_merge.json b/toolkit/components/places/tests/unit/mobile_bookmarks_folder_merge.json
deleted file mode 100644
index 7319a3a52..000000000
--- a/toolkit/components/places/tests/unit/mobile_bookmarks_folder_merge.json
+++ /dev/null
@@ -1 +0,0 @@
-{"guid":"root________","title":"","index":0,"dateAdded":1475084731479000,"lastModified":1475084731479000,"id":1,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"guid":"menu________","title":"Bookmarks Menu","index":0,"dateAdded":1475084731479000,"lastModified":1475084731768000,"id":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"guid":"Utodo9b0oVws","title":"Firefox Accounts","index":0,"dateAdded":1475084731955000,"lastModified":1475084731955000,"id":3,"type":"text/x-moz-place","uri":"https://accounts.firefox.com/"}]},{"guid":"toolbar_____","title":"Bookmarks Toolbar","index":1,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":4,"type":"text/x-moz-place-container","root":"toolbarFolder"},{"guid":"3qmd_imziEBE","title":"Mobile Bookmarks","index":5,"dateAdded":1475084731479000,"lastModified":1475084731770000,"id":5,"annos":[{"name":"mobile/bookmarksRoot","flags":0,"expires":4,"value":1},{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"A description of the mobile folder that should be ignored on import"}],"type":"text/x-moz-place-container","children":[{"guid":"a17yW6-nTxEJ","title":"Mozilla","index":0,"dateAdded":1475084731959000,"lastModified":1475084731959000,"id":6,"type":"text/x-moz-place","uri":"https://mozilla.org/"},{"guid":"xV10h9Wi3FBM","title":"Bugzilla","index":1,"dateAdded":1475084731961000,"lastModified":1475084731961000,"id":7,"type":"text/x-moz-place","uri":"https://bugzilla.mozilla.org/"}]},{"guid":"unfiled_____","title":"Other Bookmarks","index":3,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":8,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder"}]} \ No newline at end of file
diff --git a/toolkit/components/places/tests/unit/mobile_bookmarks_multiple_folders.json b/toolkit/components/places/tests/unit/mobile_bookmarks_multiple_folders.json
deleted file mode 100644
index afe13c975..000000000
--- a/toolkit/components/places/tests/unit/mobile_bookmarks_multiple_folders.json
+++ /dev/null
@@ -1 +0,0 @@
-{"guid":"root________","title":"","index":0,"dateAdded":1475084731479000,"lastModified":1475084731479000,"id":1,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"guid":"menu________","title":"Bookmarks Menu","index":0,"dateAdded":1475084731479000,"lastModified":1475084731768000,"id":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"guid":"buy7711R3ZgE","title":"MDN","index":0,"dateAdded":1475084731769000,"lastModified":1475084731769000,"id":3,"type":"text/x-moz-place","uri":"https://developer.mozilla.org"},{"guid":"F_LBgd1fS_uQ","title":"Mobile bookmarks query for first folder","index":1,"dateAdded":1475084731768000,"lastModified":1475084731768000,"id":11,"type":"text/x-moz-place","uri":"place:folder=101"},{"guid":"oIpmQXMWsXvY","title":"Mobile bookmarks query for second folder","index":2,"dateAdded":1475084731768000,"lastModified":1475084731768000,"id":12,"type":"text/x-moz-place","uri":"place:folder=102"}]},{"guid":"3qmd_imziEBE","title":"Mobile Bookmarks","index":5,"dateAdded":1475084731479000,"lastModified":1475084731770000,"id":101,"annos":[{"name":"mobile/bookmarksRoot","flags":0,"expires":4,"value":1},{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"A description of the mobile folder that should be ignored on import"}],"type":"text/x-moz-place-container","children":[{"guid":"a17yW6-nTxEJ","title":"Mozilla","index":0,"dateAdded":1475084731959000,"lastModified":1475084731959000,"id":5,"type":"text/x-moz-place","uri":"https://mozilla.org/"}]},{"guid":"toolbar_____","title":"Bookmarks Toolbar","index":1,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":6,"type":"text/x-moz-place-container","root":"toolbarFolder","children":[{"guid":"Utodo9b0oVws","title":"Firefox Accounts","index":0,"dateAdded":1475084731955000,"lastModified":1475084731955000,"id":7,"type":"text/x-moz-place","uri":"https://accounts.firefox.com/"}]},{"guid":"o4YjJpgsufU-","title":"Mobile Bookmarks","index":7,"dateAdded":1475084731479000,"lastModified":1475084731770000,"id":102,"annos":[{"name":"mobile/bookmarksRoot","flags":0,"expires":4,"value":1}],"type":"text/x-moz-place-container","children":[{"guid":"sSZ86WT9WbN3","title":"DXR","index":0,"dateAdded":1475084731769000,"lastModified":1475084731769000,"id":9,"type":"text/x-moz-place","uri":"https://dxr.mozilla.org"}]},{"guid":"unfiled_____","title":"Other Bookmarks","index":3,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":10,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder","children":[{"guid":"xV10h9Wi3FBM","title":"Bugzilla","index":1,"dateAdded":1475084731961000,"lastModified":1475084731961000,"id":11,"type":"text/x-moz-place","uri":"https://bugzilla.mozilla.org/"}]}]} \ No newline at end of file
diff --git a/toolkit/components/places/tests/unit/mobile_bookmarks_root_import.json b/toolkit/components/places/tests/unit/mobile_bookmarks_root_import.json
deleted file mode 100644
index 27f5825ec..000000000
--- a/toolkit/components/places/tests/unit/mobile_bookmarks_root_import.json
+++ /dev/null
@@ -1 +0,0 @@
-{"guid":"root________","title":"","index":0,"dateAdded":1475084731479000,"lastModified":1475084731479000,"id":1,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"guid":"menu________","title":"Bookmarks Menu","index":0,"dateAdded":1475084731479000,"lastModified":1475084731768000,"id":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"guid":"X6lUyOspVYwi","title":"Test Pilot","index":0,"dateAdded":1475084731768000,"lastModified":1475084731768000,"id":3,"type":"text/x-moz-place","uri":"https://testpilot.firefox.com/"}]},{"guid":"toolbar_____","title":"Bookmarks Toolbar","index":1,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":4,"type":"text/x-moz-place-container","root":"toolbarFolder"},{"guid":"unfiled_____","title":"Other Bookmarks","index":3,"dateAdded":1475084731479000,"lastModified":1475084731742000,"id":5,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder"},{"guid":"mobile______","title":"Mobile Bookmarks","index":4,"dateAdded":1475084731479000,"lastModified":1475084731770000,"id":6,"annos":[{"name":"mobile/bookmarksRoot","flags":0,"expires":4,"value":1}],"type":"text/x-moz-place-container","root":"mobileFolder","children":[{"guid":"_o8e1_zxTJFg","title":"Get Firefox!","index":0,"dateAdded":1475084731769000,"lastModified":1475084731769000,"id":7,"type":"text/x-moz-place","uri":"http://getfirefox.com/"},{"guid":"QCtSqkVYUbXB","title":"Get Thunderbird!","index":1,"dateAdded":1475084731770000,"lastModified":1475084731770000,"id":8,"type":"text/x-moz-place","uri":"http://getthunderbird.com/"}]}]} \ No newline at end of file
diff --git a/toolkit/components/places/tests/unit/mobile_bookmarks_root_merge.json b/toolkit/components/places/tests/unit/mobile_bookmarks_root_merge.json
deleted file mode 100644
index 85721f2fa..000000000
--- a/toolkit/components/places/tests/unit/mobile_bookmarks_root_merge.json
+++ /dev/null
@@ -1 +0,0 @@
-{"guid":"root________","title":"","index":0,"dateAdded":1475084731479000,"lastModified":1475084731479000,"id":1,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"guid":"menu________","title":"Bookmarks Menu","index":0,"dateAdded":1475084731479000,"lastModified":1475084731955000,"id":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"guid":"Utodo9b0oVws","title":"Firefox Accounts","index":0,"dateAdded":1475084731955000,"lastModified":1475084731955000,"id":3,"type":"text/x-moz-place","uri":"https://accounts.firefox.com/"}]},{"guid":"toolbar_____","title":"Bookmarks Toolbar","index":1,"dateAdded":1475084731479000,"lastModified":1475084731938000,"id":4,"type":"text/x-moz-place-container","root":"toolbarFolder"},{"guid":"unfiled_____","title":"Other Bookmarks","index":3,"dateAdded":1475084731479000,"lastModified":1475084731938000,"id":5,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder"},{"guid":"mobile______","title":"Mobile Bookmarks","index":4,"dateAdded":1475084731479000,"lastModified":1475084731961000,"id":6,"annos":[{"name":"mobile/bookmarksRoot","flags":0,"expires":4,"value":1}],"type":"text/x-moz-place-container","root":"mobileFolder","children":[{"guid":"a17yW6-nTxEJ","title":"Mozilla","index":0,"dateAdded":1475084731959000,"lastModified":1475084731959000,"id":7,"type":"text/x-moz-place","uri":"https://mozilla.org/"},{"guid":"xV10h9Wi3FBM","title":"Bugzilla","index":1,"dateAdded":1475084731961000,"lastModified":1475084731961000,"id":8,"type":"text/x-moz-place","uri":"https://bugzilla.mozilla.org/"}]}]} \ No newline at end of file
diff --git a/toolkit/components/places/tests/unit/nsDummyObserver.js b/toolkit/components/places/tests/unit/nsDummyObserver.js
deleted file mode 100644
index 9049d04b3..000000000
--- a/toolkit/components/places/tests/unit/nsDummyObserver.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-
-// Dummy boomark/history observer
-function DummyObserver() {
- Services.obs.notifyObservers(null, "dummy-observer-created", null);
-}
-
-DummyObserver.prototype = {
- // history observer
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID, aTransitionType) {
- Services.obs.notifyObservers(null, "dummy-observer-visited", null);
- },
- onTitleChanged: function () {},
- onDeleteURI: function () {},
- onClearHistory: function () {},
- onPageChanged: function () {},
- onDeleteVisits: function () {},
-
- // bookmark observer
- // onBeginUpdateBatch: function() {},
- // onEndUpdateBatch: function() {},
- onItemAdded: function(aItemId, aParentId, aIndex, aItemType, aURI) {
- Services.obs.notifyObservers(null, "dummy-observer-item-added", null);
- },
- onItemChanged: function () {},
- onItemRemoved: function() {},
- onItemVisited: function() {},
- onItemMoved: function() {},
-
- classID: Components.ID("62e221d3-68c3-4e1a-8943-a27beb5005fe"),
-
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver,
- Ci.nsINavHistoryObserver,
- ])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DummyObserver]);
diff --git a/toolkit/components/places/tests/unit/nsDummyObserver.manifest b/toolkit/components/places/tests/unit/nsDummyObserver.manifest
deleted file mode 100644
index ed4d87fff..000000000
--- a/toolkit/components/places/tests/unit/nsDummyObserver.manifest
+++ /dev/null
@@ -1,4 +0,0 @@
-component 62e221d3-68c3-4e1a-8943-a27beb5005fe nsDummyObserver.js
-contract @mozilla.org/places/test/dummy-observer;1 62e221d3-68c3-4e1a-8943-a27beb5005fe
-category bookmark-observers nsDummyObserver @mozilla.org/places/test/dummy-observer;1
-category history-observers nsDummyObserver @mozilla.org/places/test/dummy-observer;1
diff --git a/toolkit/components/places/tests/unit/places.sparse.sqlite b/toolkit/components/places/tests/unit/places.sparse.sqlite
deleted file mode 100644
index 915089021..000000000
--- a/toolkit/components/places/tests/unit/places.sparse.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/places/tests/unit/test_000_frecency.js b/toolkit/components/places/tests/unit/test_000_frecency.js
deleted file mode 100644
index 64ee86b59..000000000
--- a/toolkit/components/places/tests/unit/test_000_frecency.js
+++ /dev/null
@@ -1,267 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
-
-Autocomplete Frecency Tests
-
-- add a visit for each score permutation
-- search
-- test number of matches
-- test each item's location in results
-
-*/
-
-try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
- var prefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-} catch (ex) {
- do_throw("Could not get services\n");
-}
-
-var bucketPrefs = [
- [ "firstBucketCutoff", "firstBucketWeight"],
- [ "secondBucketCutoff", "secondBucketWeight"],
- [ "thirdBucketCutoff", "thirdBucketWeight"],
- [ "fourthBucketCutoff", "fourthBucketWeight"],
- [ null, "defaultBucketWeight"]
-];
-
-var bonusPrefs = {
- embedVisitBonus: Ci.nsINavHistoryService.TRANSITION_EMBED,
- framedLinkVisitBonus: Ci.nsINavHistoryService.TRANSITION_FRAMED_LINK,
- linkVisitBonus: Ci.nsINavHistoryService.TRANSITION_LINK,
- typedVisitBonus: Ci.nsINavHistoryService.TRANSITION_TYPED,
- bookmarkVisitBonus: Ci.nsINavHistoryService.TRANSITION_BOOKMARK,
- downloadVisitBonus: Ci.nsINavHistoryService.TRANSITION_DOWNLOAD,
- permRedirectVisitBonus: Ci.nsINavHistoryService.TRANSITION_REDIRECT_PERMANENT,
- tempRedirectVisitBonus: Ci.nsINavHistoryService.TRANSITION_REDIRECT_TEMPORARY,
- reloadVisitBonus: Ci.nsINavHistoryService.TRANSITION_RELOAD,
-};
-
-// create test data
-var searchTerm = "frecency";
-var results = [];
-var matchCount = 0;
-var now = Date.now();
-var prefPrefix = "places.frecency.";
-
-function* task_initializeBucket(bucket) {
- let [cutoffName, weightName] = bucket;
- // get pref values
- var weight = prefs.getIntPref(prefPrefix + weightName, 0);
- var cutoff = prefs.getIntPref(prefPrefix + cutoffName, 0);
- if (cutoff < 1)
- return;
-
- // generate a date within the cutoff period
- var dateInPeriod = (now - ((cutoff - 1) * 86400 * 1000)) * 1000;
-
- for (let [bonusName, visitType] of Object.entries(bonusPrefs)) {
- var frecency = -1;
- var calculatedURI = null;
- var matchTitle = "";
- var bonusValue = prefs.getIntPref(prefPrefix + bonusName);
- // unvisited (only for first cutoff date bucket)
- if (bonusName == "unvisitedBookmarkBonus" || bonusName == "unvisitedTypedBonus") {
- if (cutoffName == "firstBucketCutoff") {
- let points = Math.ceil(bonusValue / parseFloat(100.0) * weight);
- var visitCount = 1; // bonusName == "unvisitedBookmarkBonus" ? 1 : 0;
- frecency = Math.ceil(visitCount * points);
- calculatedURI = uri("http://" + searchTerm + ".com/" +
- bonusName + ":" + bonusValue + "/cutoff:" + cutoff +
- "/weight:" + weight + "/frecency:" + frecency);
- if (bonusName == "unvisitedBookmarkBonus") {
- matchTitle = searchTerm + "UnvisitedBookmark";
- bmsvc.insertBookmark(bmsvc.unfiledBookmarksFolder, calculatedURI, bmsvc.DEFAULT_INDEX, matchTitle);
- }
- else {
- matchTitle = searchTerm + "UnvisitedTyped";
- yield PlacesTestUtils.addVisits({
- uri: calculatedURI,
- title: matchTitle,
- transition: visitType,
- visitDate: now
- });
- histsvc.markPageAsTyped(calculatedURI);
- }
- }
- }
- else {
- // visited
- // visited bookmarks get the visited bookmark bonus twice
- if (visitType == Ci.nsINavHistoryService.TRANSITION_BOOKMARK)
- bonusValue = bonusValue * 2;
-
- let points = Math.ceil(1 * ((bonusValue / parseFloat(100.000000)).toFixed(6) * weight) / 1);
- if (!points) {
- if (visitType == Ci.nsINavHistoryService.TRANSITION_EMBED ||
- visitType == Ci.nsINavHistoryService.TRANSITION_FRAMED_LINK ||
- visitType == Ci.nsINavHistoryService.TRANSITION_DOWNLOAD ||
- visitType == Ci.nsINavHistoryService.TRANSITION_RELOAD ||
- bonusName == "defaultVisitBonus")
- frecency = 0;
- else
- frecency = -1;
- }
- else
- frecency = points;
- calculatedURI = uri("http://" + searchTerm + ".com/" +
- bonusName + ":" + bonusValue + "/cutoff:" + cutoff +
- "/weight:" + weight + "/frecency:" + frecency);
- if (visitType == Ci.nsINavHistoryService.TRANSITION_BOOKMARK) {
- matchTitle = searchTerm + "Bookmarked";
- bmsvc.insertBookmark(bmsvc.unfiledBookmarksFolder, calculatedURI, bmsvc.DEFAULT_INDEX, matchTitle);
- }
- else
- matchTitle = calculatedURI.spec.substr(calculatedURI.spec.lastIndexOf("/")+1);
- yield PlacesTestUtils.addVisits({
- uri: calculatedURI,
- transition: visitType,
- visitDate: dateInPeriod
- });
- }
-
- if (calculatedURI && frecency) {
- results.push([calculatedURI, frecency, matchTitle]);
- yield PlacesTestUtils.addVisits({
- uri: calculatedURI,
- title: matchTitle,
- transition: visitType,
- visitDate: dateInPeriod
- });
- }
- }
-}
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-add_task(function* test_frecency()
-{
- // Disable autoFill for this test.
- Services.prefs.setBoolPref("browser.urlbar.autoFill", false);
- do_register_cleanup(() => Services.prefs.clearUserPref("browser.urlbar.autoFill"));
- for (let bucket of bucketPrefs) {
- yield task_initializeBucket(bucket);
- }
-
- // sort results by frecency
- results.sort((a, b) => b[1] - a[1]);
- // Make sure there's enough results returned
- prefs.setIntPref("browser.urlbar.maxRichResults", results.length);
-
- // DEBUG
- // results.every(function(el) { dump("result: " + el[1] + ": " + el[0].spec + " (" + el[2] + ")\n"); return true; })
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput(["unifiedcomplete"]);
-
- controller.input = input;
-
- // always search in history + bookmarks, no matter what the default is
- prefs.setIntPref("browser.urlbar.search.sources", 3);
- prefs.setIntPref("browser.urlbar.default.behavior", 0);
-
- var numSearchesStarted = 0;
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- let deferred = Promise.defer();
- input.onSearchComplete = function() {
- do_check_eq(numSearchesStarted, 1);
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
-
- // test that all records with non-zero frecency were matched
- do_check_eq(controller.matchCount, results.length);
-
- // test that matches are sorted by frecency
- for (var i = 0; i < controller.matchCount; i++) {
- let searchURL = controller.getValueAt(i);
- let expectURL = results[i][0].spec;
- if (searchURL == expectURL) {
- do_check_eq(controller.getValueAt(i), results[i][0].spec);
- do_check_eq(controller.getCommentAt(i), results[i][2]);
- } else {
- // If the results didn't match exactly, perhaps it's still the right
- // frecency just in the wrong "order" (order of same frecency is
- // undefined), so check if frecency matches. This is okay because we
- // can still ensure the correct number of expected frecencies.
- let getFrecency = aURL => aURL.match(/frecency:(-?\d+)$/)[1];
- print("### checking for same frecency between '" + searchURL +
- "' and '" + expectURL + "'");
- do_check_eq(getFrecency(searchURL), getFrecency(expectURL));
- }
- }
- deferred.resolve();
- };
-
- controller.startSearch(searchTerm);
-
- yield deferred.promise;
-});
diff --git a/toolkit/components/places/tests/unit/test_1085291.js b/toolkit/components/places/tests/unit/test_1085291.js
deleted file mode 100644
index 3159ff8bc..000000000
--- a/toolkit/components/places/tests/unit/test_1085291.js
+++ /dev/null
@@ -1,42 +0,0 @@
-add_task(function* () {
- // test that nodes inserted by incremental update for bookmarks of all types
- // have the extra bookmark properties (bookmarkGuid, dateAdded, lastModified).
-
- // getFolderContents opens the root node.
- let root = PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId).root;
-
- function* insertAndTest(bmInfo) {
- bmInfo = yield PlacesUtils.bookmarks.insert(bmInfo);
- let node = root.getChild(root.childCount - 1);
- Assert.equal(node.bookmarkGuid, bmInfo.guid);
- Assert.equal(node.dateAdded, bmInfo.dateAdded * 1000);
- Assert.equal(node.lastModified, bmInfo.lastModified * 1000);
- }
-
- // Normal bookmark.
- yield insertAndTest({ parentGuid: root.bookmarkGuid
- , type: PlacesUtils.bookmarks.TYPE_BOOKMARK
- , title: "Test Bookmark"
- , url: "http://test.url.tld" });
-
- // place: query
- yield insertAndTest({ parentGuid: root.bookmarkGuid
- , type: PlacesUtils.bookmarks.TYPE_BOOKMARK
- , title: "Test Query"
- , url: "place:folder=BOOKMARKS_MENU" });
-
- // folder
- yield insertAndTest({ parentGuid: root.bookmarkGuid
- , type: PlacesUtils.bookmarks.TYPE_FOLDER
- , title: "Test Folder" });
-
- // separator
- yield insertAndTest({ parentGuid: root.bookmarkGuid
- , type: PlacesUtils.bookmarks.TYPE_SEPARATOR });
-
- root.containerOpen = false;
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_1105208.js b/toolkit/components/places/tests/unit/test_1105208.js
deleted file mode 100644
index 39a27c95f..000000000
--- a/toolkit/components/places/tests/unit/test_1105208.js
+++ /dev/null
@@ -1,24 +0,0 @@
-// Test that result node for folder shortcuts get the target folder title if
-// the shortcut itself has no title set.
-add_task(function* () {
- let shortcutInfo = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "place:folder=TOOLBAR"
- });
-
- let unfiledRoot =
- PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- let shortcutNode = unfiledRoot.getChild(unfiledRoot.childCount - 1);
- Assert.equal(shortcutNode.bookmarkGuid, shortcutInfo.guid);
-
- let toolbarInfo =
- yield PlacesUtils.bookmarks.fetch(PlacesUtils.bookmarks.toolbarGuid);
- Assert.equal(shortcutNode.title, toolbarInfo.title);
-
- unfiledRoot.containerOpen = false;
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_1105866.js b/toolkit/components/places/tests/unit/test_1105866.js
deleted file mode 100644
index eb376bbe2..000000000
--- a/toolkit/components/places/tests/unit/test_1105866.js
+++ /dev/null
@@ -1,63 +0,0 @@
-add_task(function* test_folder_shortcuts() {
- let shortcutInfo = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "place:folder=TOOLBAR"
- });
-
- let unfiledRoot =
- PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- let shortcutNode = unfiledRoot.getChild(unfiledRoot.childCount - 1);
- Assert.strictEqual(shortcutNode.itemId,
- yield PlacesUtils.promiseItemId(shortcutInfo.guid));
- Assert.strictEqual(PlacesUtils.asQuery(shortcutNode).folderItemId,
- PlacesUtils.toolbarFolderId);
- Assert.strictEqual(shortcutNode.bookmarkGuid, shortcutInfo.guid);
- Assert.strictEqual(PlacesUtils.asQuery(shortcutNode).targetFolderGuid,
- PlacesUtils.bookmarks.toolbarGuid);
-
- // test that a node added incrementally also behaves just as well.
- shortcutInfo = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: "place:folder=BOOKMARKS_MENU"
- });
- shortcutNode = unfiledRoot.getChild(unfiledRoot.childCount - 1);
- Assert.strictEqual(shortcutNode.itemId,
- yield PlacesUtils.promiseItemId(shortcutInfo.guid));
- Assert.strictEqual(PlacesUtils.asQuery(shortcutNode).folderItemId,
- PlacesUtils.bookmarksMenuFolderId);
- Assert.strictEqual(shortcutNode.bookmarkGuid, shortcutInfo.guid);
- Assert.strictEqual(PlacesUtils.asQuery(shortcutNode).targetFolderGuid,
- PlacesUtils.bookmarks.menuGuid);
-
- unfiledRoot.containerOpen = false;
-});
-
-add_task(function* test_plain_folder() {
- let folderInfo = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- });
-
- let unfiledRoot =
- PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- let lastChild = unfiledRoot.getChild(unfiledRoot.childCount - 1);
- Assert.strictEqual(lastChild.bookmarkGuid, folderInfo.guid);
- Assert.strictEqual(PlacesUtils.asQuery(lastChild).targetFolderGuid,
- folderInfo.guid);
-});
-
-add_task(function* test_non_item_query() {
- let options = PlacesUtils.history.getNewQueryOptions();
- let root = PlacesUtils.history.executeQuery(
- PlacesUtils.history.getNewQuery(), options).root;
- Assert.strictEqual(root.itemId, -1);
- Assert.strictEqual(PlacesUtils.asQuery(root).folderItemId, -1);
- Assert.strictEqual(root.bookmarkGuid, "");
- Assert.strictEqual(PlacesUtils.asQuery(root).targetFolderGuid, "");
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_317472.js b/toolkit/components/places/tests/unit/test_317472.js
deleted file mode 100644
index a08651916..000000000
--- a/toolkit/components/places/tests/unit/test_317472.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const charset = "UTF-8";
-const CHARSET_ANNO = "URIProperties/characterSet";
-
-const TEST_URI = uri("http://foo.com");
-const TEST_BOOKMARKED_URI = uri("http://bar.com");
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- // add pages to history
- yield PlacesTestUtils.addVisits(TEST_URI);
- yield PlacesTestUtils.addVisits(TEST_BOOKMARKED_URI);
-
- // create bookmarks on TEST_BOOKMARKED_URI
- PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId,
- TEST_BOOKMARKED_URI, PlacesUtils.bookmarks.DEFAULT_INDEX,
- TEST_BOOKMARKED_URI.spec);
- PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.toolbarFolderId,
- TEST_BOOKMARKED_URI, PlacesUtils.bookmarks.DEFAULT_INDEX,
- TEST_BOOKMARKED_URI.spec);
-
- // set charset on not-bookmarked page
- yield PlacesUtils.setCharsetForURI(TEST_URI, charset);
- // set charset on bookmarked page
- yield PlacesUtils.setCharsetForURI(TEST_BOOKMARKED_URI, charset);
-
- // check that we have created a page annotation
- do_check_eq(PlacesUtils.annotations.getPageAnnotation(TEST_URI, CHARSET_ANNO), charset);
-
- // get charset from not-bookmarked page
- do_check_eq((yield PlacesUtils.getCharsetForURI(TEST_URI)), charset);
-
- // get charset from bookmarked page
- do_check_eq((yield PlacesUtils.getCharsetForURI(TEST_BOOKMARKED_URI)), charset);
-
- yield PlacesTestUtils.clearHistory();
-
- // ensure that charset has gone for not-bookmarked page
- do_check_neq((yield PlacesUtils.getCharsetForURI(TEST_URI)), charset);
-
- // check that page annotation has been removed
- try {
- PlacesUtils.annotations.getPageAnnotation(TEST_URI, CHARSET_ANNO);
- do_throw("Charset page annotation has not been removed correctly");
- } catch (e) {}
-
- // ensure that charset still exists for bookmarked page
- do_check_eq((yield PlacesUtils.getCharsetForURI(TEST_BOOKMARKED_URI)), charset);
-
- // remove charset from bookmark and check that has gone
- yield PlacesUtils.setCharsetForURI(TEST_BOOKMARKED_URI, "");
- do_check_neq((yield PlacesUtils.getCharsetForURI(TEST_BOOKMARKED_URI)), charset);
-});
diff --git a/toolkit/components/places/tests/unit/test_331487.js b/toolkit/components/places/tests/unit/test_331487.js
deleted file mode 100644
index 55d41aebf..000000000
--- a/toolkit/components/places/tests/unit/test_331487.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get history service
-try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsINavHistoryService);
-} catch (ex) {
- do_throw("Could not get history service\n");
-}
-
-var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-// main
-function run_test() {
- // add a folder
- var folder = bmsvc.createFolder(bmsvc.placesRoot, "test folder", bmsvc.DEFAULT_INDEX);
-
- // add a bookmark to the folder
- var b1 = bmsvc.insertBookmark(folder, uri("http://a1.com/"),
- bmsvc.DEFAULT_INDEX, "1 title");
- // add a subfolder
- var sf1 = bmsvc.createFolder(folder, "subfolder 1", bmsvc.DEFAULT_INDEX);
-
- // add a bookmark to the subfolder
- var b2 = bmsvc.insertBookmark(sf1, uri("http://a2.com/"),
- bmsvc.DEFAULT_INDEX, "2 title");
-
- // add a subfolder to the subfolder
- var sf2 = bmsvc.createFolder(sf1, "subfolder 2", bmsvc.DEFAULT_INDEX);
-
- // add a bookmark to the subfolder of the subfolder
- var b3 = bmsvc.insertBookmark(sf2, uri("http://a3.com/"),
- bmsvc.DEFAULT_INDEX, "3 title");
-
- // bookmark query that should result in the "hierarchical" result
- // because there is one query, one folder,
- // no begin time, no end time, no domain, no uri, no search term
- // and no max results. See GetSimpleBookmarksQueryFolder()
- // for more details.
- var options = histsvc.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- var query = histsvc.getNewQuery();
- query.setFolders([folder], 1);
- var result = histsvc.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 2);
- do_check_eq(root.getChild(0).itemId, b1);
- do_check_eq(root.getChild(1).itemId, sf1);
-
- // check the contents of the subfolder
- var sf1Node = root.getChild(1);
- sf1Node = sf1Node.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- sf1Node.containerOpen = true;
- do_check_eq(sf1Node.childCount, 2);
- do_check_eq(sf1Node.getChild(0).itemId, b2);
- do_check_eq(sf1Node.getChild(1).itemId, sf2);
-
- // check the contents of the subfolder's subfolder
- var sf2Node = sf1Node.getChild(1);
- sf2Node = sf2Node.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- sf2Node.containerOpen = true;
- do_check_eq(sf2Node.childCount, 1);
- do_check_eq(sf2Node.getChild(0).itemId, b3);
-
- sf2Node.containerOpen = false;
- sf1Node.containerOpen = false;
- root.containerOpen = false;
-
- // bookmark query that should result in a flat list
- // because we specified max results
- options = histsvc.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- options.maxResults = 10;
- query = histsvc.getNewQuery();
- query.setFolders([folder], 1);
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 3);
- do_check_eq(root.getChild(0).itemId, b1);
- do_check_eq(root.getChild(1).itemId, b2);
- do_check_eq(root.getChild(2).itemId, b3);
- root.containerOpen = false;
-
- // XXX TODO
- // test that if we have: more than one query,
- // multiple folders, a begin time, an end time, a domain, a uri
- // or a search term, that we get the (correct) flat list results
- // (like we do when specified maxResults)
-}
diff --git a/toolkit/components/places/tests/unit/test_384370.js b/toolkit/components/places/tests/unit/test_384370.js
deleted file mode 100644
index ec6f43683..000000000
--- a/toolkit/components/places/tests/unit/test_384370.js
+++ /dev/null
@@ -1,173 +0,0 @@
-const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
-const DESCRIPTION_ANNO = "bookmarkProperties/description";
-
-var tagData = [
- { uri: uri("http://slint.us"), tags: ["indie", "kentucky", "music"] },
- { uri: uri("http://en.wikipedia.org/wiki/Diplodocus"), tags: ["dinosaur", "dj", "rad word"] }
-];
-
-var bookmarkData = [
- { uri: uri("http://slint.us"), title: "indie, kentucky, music" },
- { uri: uri("http://en.wikipedia.org/wiki/Diplodocus"), title: "dinosaur, dj, rad word" }
-];
-
-function run_test() {
- run_next_test();
-}
-
-/*
- HTML+FEATURES SUMMARY:
- - import legacy bookmarks
- - export as json, import, test (tests integrity of html > json)
- - export as html, import, test (tests integrity of json > html)
-
- BACKUP/RESTORE SUMMARY:
- - create a bookmark in each root
- - tag multiple URIs with multiple tags
- - export as json, import, test
-*/
-add_task(function* () {
- // Remove eventual bookmarks.exported.json.
- let jsonFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.exported.json");
- if ((yield OS.File.exists(jsonFile)))
- yield OS.File.remove(jsonFile);
-
- // Test importing a pre-Places canonical bookmarks file.
- // Note: we do not empty the db before this import to catch bugs like 380999
- let htmlFile = OS.Path.join(do_get_cwd().path, "bookmarks.preplaces.html");
- yield BookmarkHTMLUtils.importFromFile(htmlFile, true);
-
- // Populate the database.
- for (let { uri, tags } of tagData) {
- PlacesUtils.tagging.tagURI(uri, tags);
- }
- for (let { uri, title } of bookmarkData) {
- yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: uri,
- title });
- }
- for (let { uri, title } of bookmarkData) {
- yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: uri,
- title });
- }
-
- yield validate();
-
- // Test exporting a Places canonical json file.
- // 1. export to bookmarks.exported.json
- yield BookmarkJSONUtils.exportToFile(jsonFile);
- do_print("exported json");
-
- // 2. empty bookmarks db
- // 3. import bookmarks.exported.json
- yield BookmarkJSONUtils.importFromFile(jsonFile, true);
- do_print("imported json");
-
- // 4. run the test-suite
- yield validate();
- do_print("validated import");
-});
-
-function* validate() {
- yield testMenuBookmarks();
- yield testToolbarBookmarks();
- testUnfiledBookmarks();
- testTags();
- yield PlacesTestUtils.promiseAsyncUpdates();
-}
-
-// Tests a bookmarks datastore that has a set of bookmarks, etc
-// that flex each supported field and feature.
-function* testMenuBookmarks() {
- let root = PlacesUtils.getFolderContents(PlacesUtils.bookmarksMenuFolderId).root;
- Assert.equal(root.childCount, 3);
-
- let separatorNode = root.getChild(1);
- Assert.equal(separatorNode.type, separatorNode.RESULT_TYPE_SEPARATOR);
-
- let folderNode = root.getChild(2);
- Assert.equal(folderNode.type, folderNode.RESULT_TYPE_FOLDER);
- Assert.equal(folderNode.title, "test");
- let folder = yield PlacesUtils.bookmarks.fetch(folderNode.bookmarkGuid);
- Assert.equal(folder.dateAdded.getTime(), 1177541020000);
-
- Assert.equal(PlacesUtils.asQuery(folderNode).hasChildren, true);
-
- Assert.equal("folder test comment",
- PlacesUtils.annotations.getItemAnnotation(folderNode.itemId,
- DESCRIPTION_ANNO));
-
- // open test folder, and test the children
- folderNode.containerOpen = true;
- Assert.equal(folderNode.childCount, 1);
-
- let bookmarkNode = folderNode.getChild(0);
- Assert.equal("http://test/post", bookmarkNode.uri);
- Assert.equal("test post keyword", bookmarkNode.title);
- Assert.ok(PlacesUtils.annotations.itemHasAnnotation(bookmarkNode.itemId,
- LOAD_IN_SIDEBAR_ANNO));
- Assert.equal(bookmarkNode.dateAdded, 1177375336000000);
-
- let entry = yield PlacesUtils.keywords.fetch({ url: bookmarkNode.uri });
- Assert.equal("test", entry.keyword);
- Assert.equal("hidden1%3Dbar&text1%3D%25s", entry.postData);
-
- Assert.equal("ISO-8859-1",
- (yield PlacesUtils.getCharsetForURI(NetUtil.newURI(bookmarkNode.uri))));
- Assert.equal("item description",
- PlacesUtils.annotations.getItemAnnotation(bookmarkNode.itemId,
- DESCRIPTION_ANNO));
-
- folderNode.containerOpen = false;
- root.containerOpen = false;
-}
-
-function* testToolbarBookmarks() {
- let root = PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId).root;
-
- // child count (add 2 for pre-existing items)
- Assert.equal(root.childCount, bookmarkData.length + 2);
-
- let livemarkNode = root.getChild(1);
- Assert.equal("Latest Headlines", livemarkNode.title);
-
- let livemark = yield PlacesUtils.livemarks.getLivemark({ id: livemarkNode.itemId });
- Assert.equal("http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/",
- livemark.siteURI.spec);
- Assert.equal("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml",
- livemark.feedURI.spec);
-
- // test added bookmark data
- let bookmarkNode = root.getChild(2);
- Assert.equal(bookmarkNode.uri, bookmarkData[0].uri.spec);
- Assert.equal(bookmarkNode.title, bookmarkData[0].title);
- bookmarkNode = root.getChild(3);
- Assert.equal(bookmarkNode.uri, bookmarkData[1].uri.spec);
- Assert.equal(bookmarkNode.title, bookmarkData[1].title);
-
- root.containerOpen = false;
-}
-
-function testUnfiledBookmarks() {
- let root = PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- // child count (add 1 for pre-existing item)
- Assert.equal(root.childCount, bookmarkData.length + 1);
- for (let i = 1; i < root.childCount; ++i) {
- let child = root.getChild(i);
- Assert.equal(child.uri, bookmarkData[i - 1].uri.spec);
- Assert.equal(child.title, bookmarkData[i - 1].title);
- if (child.tags)
- Assert.equal(child.tags, bookmarkData[i - 1].title);
- }
- root.containerOpen = false;
-}
-
-function testTags() {
- for (let { uri, tags } of tagData) {
- do_print("Test tags for " + uri.spec + ": " + tags + "\n");
- let foundTags = PlacesUtils.tagging.getTagsForURI(uri);
- Assert.equal(foundTags.length, tags.length);
- Assert.ok(tags.every(tag => foundTags.includes(tag)));
- }
-}
diff --git a/toolkit/components/places/tests/unit/test_385397.js b/toolkit/components/places/tests/unit/test_385397.js
deleted file mode 100644
index 4b60d4768..000000000
--- a/toolkit/components/places/tests/unit/test_385397.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const TOTAL_SITES = 20;
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- let now = (Date.now() - 10000) * 1000;
-
- for (let i = 0; i < TOTAL_SITES; i++) {
- let site = "http://www.test-" + i + ".com/";
- let testURI = uri(site);
- let testImageURI = uri(site + "blank.gif");
- let when = now + (i * TOTAL_SITES * 1000);
- yield PlacesTestUtils.addVisits([
- { uri: testURI, visitDate: when, transition: TRANSITION_TYPED },
- { uri: testImageURI, visitDate: when + 1000, transition: TRANSITION_EMBED },
- { uri: testImageURI, visitDate: when + 2000, transition: TRANSITION_FRAMED_LINK },
- { uri: testURI, visitDate: when + 3000, transition: TRANSITION_LINK },
- ]);
- }
-
- // verify our visits AS_VISIT, ordered by date descending
- // including hidden
- // we should get 80 visits:
- // http://www.test-19.com/
- // http://www.test-19.com/blank.gif
- // http://www.test-19.com/
- // http://www.test-19.com/
- // ...
- // http://www.test-0.com/
- // http://www.test-0.com/blank.gif
- // http://www.test-0.com/
- // http://www.test-0.com/
- let options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- options.resultType = options.RESULTS_AS_VISIT;
- options.includeHidden = true;
- let root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(),
- options).root;
- root.containerOpen = true;
- let cc = root.childCount;
- // Embed visits are not added to the database, thus they won't appear.
- do_check_eq(cc, 3 * TOTAL_SITES);
- for (let i = 0; i < TOTAL_SITES; i++) {
- let index = i * 3;
- let node = root.getChild(index);
- let site = "http://www.test-" + (TOTAL_SITES - 1 - i) + ".com/";
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- node = root.getChild(++index);
- do_check_eq(node.uri, site + "blank.gif");
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- node = root.getChild(++index);
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- }
- root.containerOpen = false;
-
- // verify our visits AS_VISIT, ordered by date descending
- // we should get 40 visits:
- // http://www.test-19.com/
- // http://www.test-19.com/
- // ...
- // http://www.test-0.com/
- // http://www.test-0.com/
- options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- options.resultType = options.RESULTS_AS_VISIT;
- root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(),
- options).root;
- root.containerOpen = true;
- cc = root.childCount;
- // 2 * TOTAL_SITES because we count the TYPED and LINK, but not EMBED or FRAMED
- do_check_eq(cc, 2 * TOTAL_SITES);
- for (let i=0; i < TOTAL_SITES; i++) {
- let index = i * 2;
- let node = root.getChild(index);
- let site = "http://www.test-" + (TOTAL_SITES - 1 - i) + ".com/";
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- node = root.getChild(++index);
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- }
- root.containerOpen = false;
-
- // test our optimized query for the places menu
- // place:type=0&sort=4&maxResults=10
- // verify our visits AS_URI, ordered by date descending
- // we should get 10 visits:
- // http://www.test-19.com/
- // ...
- // http://www.test-10.com/
- options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- options.maxResults = 10;
- options.resultType = options.RESULTS_AS_URI;
- root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(),
- options).root;
- root.containerOpen = true;
- cc = root.childCount;
- do_check_eq(cc, options.maxResults);
- for (let i=0; i < cc; i++) {
- let node = root.getChild(i);
- let site = "http://www.test-" + (TOTAL_SITES - 1 - i) + ".com/";
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- }
- root.containerOpen = false;
-
- // test without a maxResults, which executes a different query
- // but the first 10 results should be the same.
- // verify our visits AS_URI, ordered by date descending
- // we should get 20 visits, but the first 10 should be
- // http://www.test-19.com/
- // ...
- // http://www.test-10.com/
- options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- options.resultType = options.RESULTS_AS_URI;
- root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(),
- options).root;
- root.containerOpen = true;
- cc = root.childCount;
- do_check_eq(cc, TOTAL_SITES);
- for (let i=0; i < 10; i++) {
- let node = root.getChild(i);
- let site = "http://www.test-" + (TOTAL_SITES - 1 - i) + ".com/";
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- }
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_399264_query_to_string.js b/toolkit/components/places/tests/unit/test_399264_query_to_string.js
deleted file mode 100644
index 6e6cc279c..000000000
--- a/toolkit/components/places/tests/unit/test_399264_query_to_string.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Obtains the id of the folder obtained from the query.
- *
- * @param aFolderID
- * The id of the folder we want to generate a query for.
- * @returns the string representation of the query for the given folder.
- */
-function query_string(aFolderID)
-{
- var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
- var query = hs.getNewQuery();
- query.setFolders([aFolderID], 1);
- var options = hs.getNewQueryOptions();
- return hs.queriesToQueryString([query], 1, options);
-}
-
-function run_test()
-{
- var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
- const QUERIES = [
- "folder=PLACES_ROOT"
- , "folder=BOOKMARKS_MENU"
- , "folder=TAGS"
- , "folder=UNFILED_BOOKMARKS"
- , "folder=TOOLBAR"
- ];
- const FOLDER_IDS = [
- bs.placesRoot
- , bs.bookmarksMenuFolder
- , bs.tagsFolder
- , bs.unfiledBookmarksFolder
- , bs.toolbarFolder
- ];
-
-
- for (var i = 0; i < QUERIES.length; i++) {
- var result = query_string(FOLDER_IDS[i]);
- dump("Looking for '" + QUERIES[i] + "' in '" + result + "'\n");
- do_check_neq(-1, result.indexOf(QUERIES[i]));
- }
-}
diff --git a/toolkit/components/places/tests/unit/test_399264_string_to_query.js b/toolkit/components/places/tests/unit/test_399264_string_to_query.js
deleted file mode 100644
index bd29316d9..000000000
--- a/toolkit/components/places/tests/unit/test_399264_string_to_query.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Obtains the id of the folder obtained from the query.
- *
- * @param aQuery
- * The query to obtain the folder id from.
- * @returns the folder id of the folder of the root node of the query.
- */
-function folder_id(aQuery)
-{
- var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
- dump("Checking query '" + aQuery + "'\n");
- var options = { };
- var queries = { };
- var size = { };
- hs.queryStringToQueries(aQuery, queries, size, options);
- var result = hs.executeQueries(queries.value, size.value, options.value);
- var root = result.root;
- root.containerOpen = true;
- do_check_true(root.hasChildren);
- var folderID = root.getChild(0).parent.itemId;
- root.containerOpen = false;
- return folderID;
-}
-
-function run_test()
-{
- var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
- const QUERIES = [
- "place:folder=PLACES_ROOT"
- , "place:folder=BOOKMARKS_MENU"
- , "place:folder=TAGS"
- , "place:folder=UNFILED_BOOKMARKS"
- , "place:folder=TOOLBAR"
- ];
- const FOLDER_IDS = [
- bs.placesRoot
- , bs.bookmarksMenuFolder
- , bs.tagsFolder
- , bs.unfiledBookmarksFolder
- , bs.toolbarFolder
- ];
-
- // add something in the bookmarks menu folder so a query to it returns results
- bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://example.com/bmf/"),
- Ci.nsINavBookmarksService.DEFAULT_INDEX, "bmf");
-
- // add something to the tags folder
- var ts = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
- ts.tagURI(uri("http://www.example.com/"), ["tag"]);
-
- // add something to the unfiled bookmarks folder
- bs.insertBookmark(bs.unfiledBookmarksFolder, uri("http://example.com/ubf/"),
- Ci.nsINavBookmarksService.DEFAULT_INDEX, "ubf");
-
- // add something to the toolbar folder
- bs.insertBookmark(bs.toolbarFolder, uri("http://example.com/tf/"),
- Ci.nsINavBookmarksService.DEFAULT_INDEX, "tf");
-
- for (var i = 0; i < QUERIES.length; i++) {
- var result = folder_id(QUERIES[i]);
- dump("expected " + FOLDER_IDS[i] + ", got " + result + "\n");
- do_check_eq(FOLDER_IDS[i], result);
- }
-}
diff --git a/toolkit/components/places/tests/unit/test_399266.js b/toolkit/components/places/tests/unit/test_399266.js
deleted file mode 100644
index 296d69414..000000000
--- a/toolkit/components/places/tests/unit/test_399266.js
+++ /dev/null
@@ -1,78 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const TOTAL_SITES = 20;
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- let places = [];
- for (let i = 0; i < TOTAL_SITES; i++) {
- for (let j = 0; j <= i; j++) {
- places.push({ uri: uri("http://www.test-" + i + ".com/"),
- transition: TRANSITION_TYPED });
- // because these are embedded visits, they should not show up on our
- // query results. If they do, we have a problem.
- places.push({ uri: uri("http://www.hidden.com/hidden.gif"),
- transition: TRANSITION_EMBED });
- places.push({ uri: uri("http://www.alsohidden.com/hidden.gif"),
- transition: TRANSITION_FRAMED_LINK });
- }
- }
- yield PlacesTestUtils.addVisits(places);
-
- // test our optimized query for the "Most Visited" item
- // in the "Smart Bookmarks" folder
- // place:queryType=0&sort=8&maxResults=10
- // verify our visits AS_URI, ordered by visit count descending
- // we should get 10 visits:
- // http://www.test-19.com/
- // ...
- // http://www.test-10.com/
- let options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_VISITCOUNT_DESCENDING;
- options.maxResults = 10;
- options.resultType = options.RESULTS_AS_URI;
- let root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(),
- options).root;
- root.containerOpen = true;
- let cc = root.childCount;
- do_check_eq(cc, options.maxResults);
- for (let i = 0; i < cc; i++) {
- let node = root.getChild(i);
- let site = "http://www.test-" + (TOTAL_SITES - 1 - i) + ".com/";
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- }
- root.containerOpen = false;
-
- // test without a maxResults, which executes a different query
- // but the first 10 results should be the same.
- // verify our visits AS_URI, ordered by visit count descending
- // we should get 20 visits, but the first 10 should be
- // http://www.test-19.com/
- // ...
- // http://www.test-10.com/
- options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_VISITCOUNT_DESCENDING;
- options.resultType = options.RESULTS_AS_URI;
- root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(),
- options).root;
- root.containerOpen = true;
- cc = root.childCount;
- do_check_eq(cc, TOTAL_SITES);
- for (let i = 0; i < 10; i++) {
- let node = root.getChild(i);
- let site = "http://www.test-" + (TOTAL_SITES - 1 - i) + ".com/";
- do_check_eq(node.uri, site);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- }
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_402799.js b/toolkit/components/places/tests/unit/test_402799.js
deleted file mode 100644
index 263e20aa5..000000000
--- a/toolkit/components/places/tests/unit/test_402799.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get history services
-try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
- var bhist = histsvc.QueryInterface(Ci.nsIBrowserHistory);
-} catch (ex) {
- do_throw("Could not get history services\n");
-}
-
-// Get bookmark service
-try {
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-}
-catch (ex) {
- do_throw("Could not get the nav-bookmarks-service\n");
-}
-
-// Get tagging service
-try {
- var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-} catch (ex) {
- do_throw("Could not get tagging service\n");
-}
-
-
-// main
-function run_test() {
- var uri1 = uri("http://foo.bar/");
-
- // create 2 bookmarks on the same uri
- bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri1,
- bmsvc.DEFAULT_INDEX, "title 1");
- bmsvc.insertBookmark(bmsvc.toolbarFolder, uri1,
- bmsvc.DEFAULT_INDEX, "title 2");
- // add some tags
- tagssvc.tagURI(uri1, ["foo", "bar", "foobar", "foo bar"]);
-
- // check that a generic bookmark query returns only real bookmarks
- var options = histsvc.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
-
- var query = histsvc.getNewQuery();
- var result = histsvc.executeQuery(query, options);
- var root = result.root;
-
- root.containerOpen = true;
- var cc = root.childCount;
- do_check_eq(cc, 2);
- var node1 = root.getChild(0);
- do_check_eq(bmsvc.getFolderIdForItem(node1.itemId), bmsvc.bookmarksMenuFolder);
- var node2 = root.getChild(1);
- do_check_eq(bmsvc.getFolderIdForItem(node2.itemId), bmsvc.toolbarFolder);
- root.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/unit/test_405497.js b/toolkit/components/places/tests/unit/test_405497.js
deleted file mode 100644
index 951302b84..000000000
--- a/toolkit/components/places/tests/unit/test_405497.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-/**
- * The callback object for runInBatchMode.
- *
- * @param aService
- * Takes a reference to the history service or the bookmark service.
- * This determines which service should be called when calling the second
- * runInBatchMode the second time.
- */
-function callback(aService)
-{
- this.callCount = 0;
- this.service = aService;
-}
-callback.prototype = {
- // nsINavHistoryBatchCallback
-
- runBatched: function(aUserData)
- {
- this.callCount++;
-
- if (this.callCount == 1) {
- // We want to call run in batched once more.
- this.service.runInBatchMode(this, null);
- return;
- }
-
- do_check_eq(this.callCount, 2);
- do_test_finished();
- },
-
- // nsISupports
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryBatchCallback])
-};
-
-function run_test() {
- // checking the history service
- do_test_pending();
- hs.runInBatchMode(new callback(hs), null);
-
- // checking the bookmark service
- do_test_pending();
- bs.runInBatchMode(new callback(bs), null);
-}
diff --git a/toolkit/components/places/tests/unit/test_408221.js b/toolkit/components/places/tests/unit/test_408221.js
deleted file mode 100644
index 2b41ce1a2..000000000
--- a/toolkit/components/places/tests/unit/test_408221.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var current_test = 0;
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-// Get tagging service
-try {
- var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-} catch (ex) {
- do_throw("Could not get tagging service\n");
-}
-
-function ensure_tag_results(uris, searchTerm)
-{
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput(["unifiedcomplete"]);
-
- controller.input = input;
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- var numSearchesStarted = 0;
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function() {
- do_check_eq(numSearchesStarted, 1);
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- do_check_eq(controller.matchCount, uris.length);
- let vals = [];
- for (let i=0; i<controller.matchCount; i++) {
- // Keep the URL for later because order of tag results is undefined
- vals.push(controller.getValueAt(i));
- do_check_eq(controller.getStyleAt(i), "bookmark-tag");
- }
- // Sort the results then check if we have the right items
- vals.sort().forEach((val, i) => do_check_eq(val, uris[i].spec))
-
- if (current_test < (tests.length - 1)) {
- current_test++;
- tests[current_test]();
- }
-
- do_test_finished();
- };
-
- controller.startSearch(searchTerm);
-}
-
-var uri1 = uri("http://site.tld/1");
-var uri2 = uri("http://site.tld/2");
-var uri3 = uri("http://site.tld/3");
-var uri4 = uri("http://site.tld/4");
-var uri5 = uri("http://site.tld/5");
-var uri6 = uri("http://site.tld/6");
-
-var tests = [function() { ensure_tag_results([uri1, uri2, uri3], "foo"); },
- function() { ensure_tag_results([uri1, uri2, uri3], "Foo"); },
- function() { ensure_tag_results([uri1, uri2, uri3], "foO"); },
- function() { ensure_tag_results([uri4, uri5, uri6], "bar mud"); },
- function() { ensure_tag_results([uri4, uri5, uri6], "BAR MUD"); },
- function() { ensure_tag_results([uri4, uri5, uri6], "Bar Mud"); }];
-
-/**
- * Properly tags a uri adding it to bookmarks.
- *
- * @param aURI
- * The nsIURI to tag.
- * @param aTags
- * The tags to add.
- */
-function tagURI(aURI, aTags) {
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- aURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "A title");
- tagssvc.tagURI(aURI, aTags);
-}
-
-/**
- * Test bug #408221
- */
-function run_test() {
- // always search in history + bookmarks, no matter what the default is
- var prefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
- prefs.setIntPref("browser.urlbar.search.sources", 3);
- prefs.setIntPref("browser.urlbar.default.behavior", 0);
-
- tagURI(uri1, ["Foo"]);
- tagURI(uri2, ["FOO"]);
- tagURI(uri3, ["foO"]);
- tagURI(uri4, ["BAR"]);
- tagURI(uri4, ["MUD"]);
- tagURI(uri5, ["bar"]);
- tagURI(uri5, ["mud"]);
- tagURI(uri6, ["baR"]);
- tagURI(uri6, ["muD"]);
-
- tests[0]();
-}
diff --git a/toolkit/components/places/tests/unit/test_412132.js b/toolkit/components/places/tests/unit/test_412132.js
deleted file mode 100644
index 827391f18..000000000
--- a/toolkit/components/places/tests/unit/test_412132.js
+++ /dev/null
@@ -1,136 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * TEST DESCRIPTION:
- *
- * Tests patch to Bug 412132:
- * https://bugzilla.mozilla.org/show_bug.cgi?id=412132
- */
-
-add_task(function* changeuri_unvisited_bookmark()
-{
- do_print("After changing URI of bookmark, frecency of bookmark's " +
- "original URI should be zero if original URI is unvisited and " +
- "no longer bookmarked.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- let id = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark title");
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- PlacesUtils.bookmarks.changeBookmarkURI(id, uri("http://example.com/2"));
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Unvisited URI no longer bookmarked => frecency should = 0");
- do_check_eq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* changeuri_visited_bookmark()
-{
- do_print("After changing URI of bookmark, frecency of bookmark's " +
- "original URI should not be zero if original URI is visited.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- let id = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark title");
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesTestUtils.addVisits(TEST_URI);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- PlacesUtils.bookmarks.changeBookmarkURI(id, uri("http://example.com/2"));
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("*Visited* URI no longer bookmarked => frecency should != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* changeuri_bookmark_still_bookmarked()
-{
- do_print("After changing URI of bookmark, frecency of bookmark's " +
- "original URI should not be zero if original URI is still " +
- "bookmarked.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- let id1 = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark 1 title");
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark 2 title");
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- PlacesUtils.bookmarks.changeBookmarkURI(id1, uri("http://example.com/2"));
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("URI still bookmarked => frecency should != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* changeuri_nonexistent_bookmark()
-{
- do_print("Changing the URI of a nonexistent bookmark should fail.");
- function tryChange(itemId)
- {
- try {
- PlacesUtils.bookmarks.changeBookmarkURI(itemId + 1, uri("http://example.com/2"));
- do_throw("Nonexistent bookmark should throw.");
- }
- catch (ex) {}
- }
-
- // First try a straight-up bogus item ID, one greater than the current max
- // ID.
- let stmt = DBConn().createStatement("SELECT MAX(id) FROM moz_bookmarks");
- stmt.executeStep();
- let maxId = stmt.getInt32(0);
- stmt.finalize();
- tryChange(maxId + 1);
-
- // Now add a bookmark, delete it, and check.
- let id = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri("http://example.com/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark title");
- PlacesUtils.bookmarks.removeItem(id);
- tryChange(id);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-function run_test()
-{
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_413784.js b/toolkit/components/places/tests/unit/test_413784.js
deleted file mode 100644
index 6df4dfbbb..000000000
--- a/toolkit/components/places/tests/unit/test_413784.js
+++ /dev/null
@@ -1,118 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
-
-Test autocomplete for non-English URLs
-
-- add a visit for a page with a non-English URL
-- search
-- test number of matches (should be exactly one)
-
-*/
-
-var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-// create test data
-var searchTerm = "ユニコード";
-var decoded = "http://www.foobar.com/" + searchTerm + "/";
-var url = uri(decoded);
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-function run_test()
-{
- do_test_pending();
- PlacesTestUtils.addVisits(url).then(continue_test);
-}
-
-function continue_test()
-{
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput(["unifiedcomplete"]);
-
- controller.input = input;
-
- var numSearchesStarted = 0;
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function() {
- do_check_eq(numSearchesStarted, 1);
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
-
- // test that we found the entry we added
- do_check_eq(controller.matchCount, 1);
-
- // Make sure the url is the same according to spec, so it can be deleted
- do_check_eq(controller.getValueAt(0), url.spec);
-
- do_test_finished();
- };
-
- controller.startSearch(searchTerm);
-}
diff --git a/toolkit/components/places/tests/unit/test_415460.js b/toolkit/components/places/tests/unit/test_415460.js
deleted file mode 100644
index f2e049f09..000000000
--- a/toolkit/components/places/tests/unit/test_415460.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-/**
- * Checks to see that a search has exactly one result in the database.
- *
- * @param aTerms
- * The terms to search for.
- * @returns true if the search returns one result, false otherwise.
- */
-function search_has_result(aTerms)
-{
- var options = hs.getNewQueryOptions();
- options.maxResults = 1;
- options.resultType = options.RESULTS_AS_URI;
- var query = hs.getNewQuery();
- query.searchTerms = aTerms;
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var cc = root.childCount;
- root.containerOpen = false;
- return (cc == 1);
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- const SEARCH_TERM = "ユニコード";
- const TEST_URL = "http://example.com/" + SEARCH_TERM + "/";
- yield PlacesTestUtils.addVisits(uri(TEST_URL));
- do_check_true(search_has_result(SEARCH_TERM));
-});
diff --git a/toolkit/components/places/tests/unit/test_415757.js b/toolkit/components/places/tests/unit/test_415757.js
deleted file mode 100644
index afd396183..000000000
--- a/toolkit/components/places/tests/unit/test_415757.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Checks to see that a URI is in the database.
- *
- * @param aURI
- * The URI to check.
- * @returns true if the URI is in the DB, false otherwise.
- */
-function uri_in_db(aURI) {
- var options = PlacesUtils.history.getNewQueryOptions();
- options.maxResults = 1;
- options.resultType = options.RESULTS_AS_URI
- var query = PlacesUtils.history.getNewQuery();
- query.uri = aURI;
- var result = PlacesUtils.history.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var cc = root.childCount;
- root.containerOpen = false;
- return (cc == 1);
-}
-
-const TOTAL_SITES = 20;
-
-// main
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- // add pages to global history
- for (let i = 0; i < TOTAL_SITES; i++) {
- let site = "http://www.test-" + i + ".com/";
- let testURI = uri(site);
- let when = Date.now() * 1000 + (i * TOTAL_SITES);
- yield PlacesTestUtils.addVisits({ uri: testURI, visitDate: when });
- }
- for (let i = 0; i < TOTAL_SITES; i++) {
- let site = "http://www.test.com/" + i + "/";
- let testURI = uri(site);
- let when = Date.now() * 1000 + (i * TOTAL_SITES);
- yield PlacesTestUtils.addVisits({ uri: testURI, visitDate: when });
- }
-
- // set a page annotation on one of the urls that will be removed
- var testAnnoDeletedURI = uri("http://www.test.com/1/");
- var testAnnoDeletedName = "foo";
- var testAnnoDeletedValue = "bar";
- PlacesUtils.annotations.setPageAnnotation(testAnnoDeletedURI,
- testAnnoDeletedName,
- testAnnoDeletedValue, 0,
- PlacesUtils.annotations.EXPIRE_WITH_HISTORY);
-
- // set a page annotation on one of the urls that will NOT be removed
- var testAnnoRetainedURI = uri("http://www.test-1.com/");
- var testAnnoRetainedName = "foo";
- var testAnnoRetainedValue = "bar";
- PlacesUtils.annotations.setPageAnnotation(testAnnoRetainedURI,
- testAnnoRetainedName,
- testAnnoRetainedValue, 0,
- PlacesUtils.annotations.EXPIRE_WITH_HISTORY);
-
- // remove pages from www.test.com
- PlacesUtils.history.removePagesFromHost("www.test.com", false);
-
- // check that all pages in www.test.com have been removed
- for (let i = 0; i < TOTAL_SITES; i++) {
- let site = "http://www.test.com/" + i + "/";
- let testURI = uri(site);
- do_check_false(uri_in_db(testURI));
- }
-
- // check that all pages in www.test-X.com have NOT been removed
- for (let i = 0; i < TOTAL_SITES; i++) {
- let site = "http://www.test-" + i + ".com/";
- let testURI = uri(site);
- do_check_true(uri_in_db(testURI));
- }
-
- // check that annotation on the removed item does not exists
- try {
- PlacesUtils.annotations.getPageAnnotation(testAnnoDeletedURI, testAnnoName);
- do_throw("fetching page-annotation that doesn't exist, should've thrown");
- } catch (ex) {}
-
- // check that annotation on the NOT removed item still exists
- try {
- var annoVal = PlacesUtils.annotations.getPageAnnotation(testAnnoRetainedURI,
- testAnnoRetainedName);
- } catch (ex) {
- do_throw("The annotation has been removed erroneously");
- }
- do_check_eq(annoVal, testAnnoRetainedValue);
-
-});
diff --git a/toolkit/components/places/tests/unit/test_418643_removeFolderChildren.js b/toolkit/components/places/tests/unit/test_418643_removeFolderChildren.js
deleted file mode 100644
index 2eed02921..000000000
--- a/toolkit/components/places/tests/unit/test_418643_removeFolderChildren.js
+++ /dev/null
@@ -1,143 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get services.
-try {
- var histSvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
- var bmSvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
- var annoSvc = Cc["@mozilla.org/browser/annotation-service;1"]
- .getService(Ci.nsIAnnotationService);
-} catch (ex) {
- do_throw("Could not get services\n");
-}
-
-var validAnnoName = "validAnno";
-var validItemName = "validItem";
-var deletedAnnoName = "deletedAnno";
-var deletedItemName = "deletedItem";
-var bookmarkedURI = uri("http://www.mozilla.org/");
-// set lastModified to the past to prevent VM timing bugs
-var pastDate = Date.now() * 1000 - 1;
-var deletedBookmarkIds = [];
-
-// bookmarks observer
-var observer = {
- // cached ordered array of notified items
- _onItemRemovedItemIds: [],
- onItemRemoved: function(aItemId, aParentId, aIndex) {
- // We should first get notifications for children, then for their parent
- do_check_eq(this._onItemRemovedItemIds.indexOf(aParentId), -1);
- // Ensure we are not wrongly removing 1 level up
- do_check_neq(aParentId, bmSvc.toolbarFolder);
- // Removed item must be one of those we have manually deleted
- do_check_neq(deletedBookmarkIds.indexOf(aItemId), -1);
- this._onItemRemovedItemIds.push(aItemId);
- },
-
- QueryInterface: function(aIID) {
- if (aIID.equals(Ci.nsINavBookmarkObserver) ||
- aIID.equals(Ci.nsISupports)) {
- return this;
- }
- throw Cr.NS_ERROR_NO_INTERFACE;
- }
-};
-
-bmSvc.addObserver(observer, false);
-
-function add_bookmarks() {
- // This is the folder we will cleanup
- var validFolderId = bmSvc.createFolder(bmSvc.toolbarFolder,
- validItemName,
- bmSvc.DEFAULT_INDEX);
- annoSvc.setItemAnnotation(validFolderId, validAnnoName,
- "annotation", 0,
- annoSvc.EXPIRE_NEVER);
- bmSvc.setItemLastModified(validFolderId, pastDate);
-
- // This bookmark should not be deleted
- var validItemId = bmSvc.insertBookmark(bmSvc.toolbarFolder,
- bookmarkedURI,
- bmSvc.DEFAULT_INDEX,
- validItemName);
- annoSvc.setItemAnnotation(validItemId, validAnnoName,
- "annotation", 0, annoSvc.EXPIRE_NEVER);
-
- // The following contents should be deleted
- var deletedItemId = bmSvc.insertBookmark(validFolderId,
- bookmarkedURI,
- bmSvc.DEFAULT_INDEX,
- deletedItemName);
- annoSvc.setItemAnnotation(deletedItemId, deletedAnnoName,
- "annotation", 0, annoSvc.EXPIRE_NEVER);
- deletedBookmarkIds.push(deletedItemId);
-
- var internalFolderId = bmSvc.createFolder(validFolderId,
- deletedItemName,
- bmSvc.DEFAULT_INDEX);
- annoSvc.setItemAnnotation(internalFolderId, deletedAnnoName,
- "annotation", 0, annoSvc.EXPIRE_NEVER);
- deletedBookmarkIds.push(internalFolderId);
-
- deletedItemId = bmSvc.insertBookmark(internalFolderId,
- bookmarkedURI,
- bmSvc.DEFAULT_INDEX,
- deletedItemName);
- annoSvc.setItemAnnotation(deletedItemId, deletedAnnoName,
- "annotation", 0, annoSvc.EXPIRE_NEVER);
- deletedBookmarkIds.push(deletedItemId);
-
- return validFolderId;
-}
-
-function check_bookmarks(aFolderId) {
- // check that we still have valid bookmarks
- var bookmarks = bmSvc.getBookmarkIdsForURI(bookmarkedURI);
- for (var i = 0; i < bookmarks.length; i++) {
- do_check_eq(bmSvc.getItemTitle(bookmarks[i]), validItemName);
- do_check_true(annoSvc.itemHasAnnotation(bookmarks[i], validAnnoName));
- }
-
- // check that folder exists and has still its annotation
- do_check_eq(bmSvc.getItemTitle(aFolderId), validItemName);
- do_check_true(annoSvc.itemHasAnnotation(aFolderId, validAnnoName));
-
- // check that folder is empty
- var options = histSvc.getNewQueryOptions();
- var query = histSvc.getNewQuery();
- query.setFolders([aFolderId], 1);
- var result = histSvc.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 0);
- root.containerOpen = false;
-
- // test that lastModified got updated
- do_check_true(pastDate < bmSvc.getItemLastModified(aFolderId));
-
- // test that all children have been deleted, we use annos for that
- var deletedItems = annoSvc.getItemsWithAnnotation(deletedAnnoName);
- do_check_eq(deletedItems.length, 0);
-
- // test that observer has been called for (and only for) deleted items
- do_check_eq(observer._onItemRemovedItemIds.length, deletedBookmarkIds.length);
-
- // Sanity check: all roots should be intact
- do_check_eq(bmSvc.getFolderIdForItem(bmSvc.placesRoot), 0);
- do_check_eq(bmSvc.getFolderIdForItem(bmSvc.bookmarksMenuFolder), bmSvc.placesRoot);
- do_check_eq(bmSvc.getFolderIdForItem(bmSvc.tagsFolder), bmSvc.placesRoot);
- do_check_eq(bmSvc.getFolderIdForItem(bmSvc.unfiledBookmarksFolder), bmSvc.placesRoot);
- do_check_eq(bmSvc.getFolderIdForItem(bmSvc.toolbarFolder), bmSvc.placesRoot);
-}
-
-// main
-function run_test() {
- var folderId = add_bookmarks();
- bmSvc.removeFolderChildren(folderId);
- check_bookmarks(folderId);
-}
diff --git a/toolkit/components/places/tests/unit/test_419731.js b/toolkit/components/places/tests/unit/test_419731.js
deleted file mode 100644
index b1a434e12..000000000
--- a/toolkit/components/places/tests/unit/test_419731.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- let uri1 = NetUtil.newURI("http://foo.bar/");
-
- // create 2 bookmarks
- let bookmark1id = PlacesUtils.bookmarks
- .insertBookmark(PlacesUtils.bookmarksMenuFolderId,
- uri1,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "title 1");
- let bookmark2id = PlacesUtils.bookmarks
- .insertBookmark(PlacesUtils.toolbarFolderId,
- uri1,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "title 2");
- // add a new tag
- PlacesUtils.tagging.tagURI(uri1, ["foo"]);
-
- // get tag folder id
- let options = PlacesUtils.history.getNewQueryOptions();
- let query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.tagsFolderId], 1);
- let result = PlacesUtils.history.executeQuery(query, options);
- let tagRoot = result.root;
- tagRoot.containerOpen = true;
- let tagNode = tagRoot.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- let tagItemId = tagNode.itemId;
- tagRoot.containerOpen = false;
-
- // change bookmark 1 title
- PlacesUtils.bookmarks.setItemTitle(bookmark1id, "new title 1");
-
- // Workaround timers resolution and time skews.
- let bookmark2LastMod = PlacesUtils.bookmarks.getItemLastModified(bookmark2id);
- PlacesUtils.bookmarks.setItemLastModified(bookmark1id, bookmark2LastMod + 1000);
-
- // Query the tag.
- options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- options.resultType = options.RESULTS_AS_TAG_QUERY;
-
- query = PlacesUtils.history.getNewQuery();
- result = PlacesUtils.history.executeQuery(query, options);
- let root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 1);
-
- let theTag = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- // Bug 524219: Check that renaming the tag shows up in the result.
- do_check_eq(theTag.title, "foo")
- PlacesUtils.bookmarks.setItemTitle(tagItemId, "bar");
-
- // Check that the item has been replaced
- do_check_neq(theTag, root.getChild(0));
- theTag = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(theTag.title, "bar");
-
- // Check that tag container contains new title
- theTag.containerOpen = true;
- do_check_eq(theTag.childCount, 1);
- let node = theTag.getChild(0);
- do_check_eq(node.title, "new title 1");
- theTag.containerOpen = false;
- root.containerOpen = false;
-
- // Change bookmark 2 title.
- PlacesUtils.bookmarks.setItemTitle(bookmark2id, "new title 2");
-
- // Workaround timers resolution and time skews.
- let bookmark1LastMod = PlacesUtils.bookmarks.getItemLastModified(bookmark1id);
- PlacesUtils.bookmarks.setItemLastModified(bookmark2id, bookmark1LastMod + 1000);
-
- // Check that tag container contains new title
- options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- options.resultType = options.RESULTS_AS_TAG_CONTENTS;
-
- query = PlacesUtils.history.getNewQuery();
- query.setFolders([tagItemId], 1);
- result = PlacesUtils.history.executeQuery(query, options);
- root = result.root;
-
- root.containerOpen = true;
- do_check_eq(root.childCount, 1);
- node = root.getChild(0);
- do_check_eq(node.title, "new title 2");
- root.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/unit/test_419792_node_tags_property.js b/toolkit/components/places/tests/unit/test_419792_node_tags_property.js
deleted file mode 100644
index 4c726d667..000000000
--- a/toolkit/components/places/tests/unit/test_419792_node_tags_property.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// get services
-var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-
-function run_test() {
- // get toolbar node
- var options = histsvc.getNewQueryOptions();
- var query = histsvc.getNewQuery();
- query.setFolders([bmsvc.toolbarFolder], 1);
- var result = histsvc.executeQuery(query, options);
- var toolbarNode = result.root;
- toolbarNode.containerOpen = true;
-
- // add a bookmark
- var bookmarkURI = uri("http://foo.com");
- var bookmarkId = bmsvc.insertBookmark(bmsvc.toolbarFolder, bookmarkURI,
- bmsvc.DEFAULT_INDEX, "");
-
- // get the node for the new bookmark
- var node = toolbarNode.getChild(toolbarNode.childCount-1);
- do_check_eq(node.itemId, bookmarkId);
-
- // confirm there's no tags via the .tags property
- do_check_eq(node.tags, null);
-
- // add a tag
- tagssvc.tagURI(bookmarkURI, ["foo"]);
- do_check_eq(node.tags, "foo");
-
- // add another tag, to test delimiter and sorting
- tagssvc.tagURI(bookmarkURI, ["bar"]);
- do_check_eq(node.tags, "bar, foo");
-
- // remove the tags, confirming the property is cleared
- tagssvc.untagURI(bookmarkURI, null);
- do_check_eq(node.tags, null);
-
- toolbarNode.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/unit/test_425563.js b/toolkit/components/places/tests/unit/test_425563.js
deleted file mode 100644
index bee3a4a54..000000000
--- a/toolkit/components/places/tests/unit/test_425563.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- let count_visited_URIs = ["http://www.test-link.com/",
- "http://www.test-typed.com/",
- "http://www.test-bookmark.com/",
- "http://www.test-redirect-permanent.com/",
- "http://www.test-redirect-temporary.com/"];
-
- let notcount_visited_URIs = ["http://www.test-embed.com/",
- "http://www.test-download.com/",
- "http://www.test-framed.com/",
- "http://www.test-reload.com/"];
-
- // add visits, one for each transition type
- yield PlacesTestUtils.addVisits([
- { uri: uri("http://www.test-link.com/"),
- transition: TRANSITION_LINK },
- { uri: uri("http://www.test-typed.com/"),
- transition: TRANSITION_TYPED },
- { uri: uri("http://www.test-bookmark.com/"),
- transition: TRANSITION_BOOKMARK },
- { uri: uri("http://www.test-embed.com/"),
- transition: TRANSITION_EMBED },
- { uri: uri("http://www.test-framed.com/"),
- transition: TRANSITION_FRAMED_LINK },
- { uri: uri("http://www.test-redirect-permanent.com/"),
- transition: TRANSITION_REDIRECT_PERMANENT },
- { uri: uri("http://www.test-redirect-temporary.com/"),
- transition: TRANSITION_REDIRECT_TEMPORARY },
- { uri: uri("http://www.test-download.com/"),
- transition: TRANSITION_DOWNLOAD },
- { uri: uri("http://www.test-reload.com/"),
- transition: TRANSITION_RELOAD },
- ]);
-
- // check that all links are marked as visited
- for (let visited_uri of count_visited_URIs) {
- do_check_true(yield promiseIsURIVisited(uri(visited_uri)));
- }
- for (let visited_uri of notcount_visited_URIs) {
- do_check_true(yield promiseIsURIVisited(uri(visited_uri)));
- }
-
- // check that visit_count does not take in count embed and downloads
- // maxVisits query are directly binded to visit_count
- let options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_VISITCOUNT_DESCENDING;
- options.resultType = options.RESULTS_AS_VISIT;
- options.includeHidden = true;
- let query = PlacesUtils.history.getNewQuery();
- query.minVisits = 1;
- let root = PlacesUtils.history.executeQuery(query, options).root;
-
- root.containerOpen = true;
- let cc = root.childCount;
- do_check_eq(cc, count_visited_URIs.length);
-
- for (let i = 0; i < cc; i++) {
- let node = root.getChild(i);
- do_check_neq(count_visited_URIs.indexOf(node.uri), -1);
- }
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_429505_remove_shortcuts.js b/toolkit/components/places/tests/unit/test_429505_remove_shortcuts.js
deleted file mode 100644
index e0b6be64c..000000000
--- a/toolkit/components/places/tests/unit/test_429505_remove_shortcuts.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
-
-- add a folder
-- add a folder-shortcut to the new folder
-- query for the shortcut
-- remove the folder-shortcut
-- confirm the shortcut is removed from the query results
-
-*/
-
-function run_test() {
- const IDX = PlacesUtils.bookmarks.DEFAULT_INDEX;
- var folderId =
- PlacesUtils.bookmarks.createFolder(PlacesUtils.toolbarFolderId, "", IDX);
-
- var queryId =
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.toolbarFolderId,
- uri("place:folder=" + folderId), IDX, "");
-
- var root = PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId, false, true).root;
-
- var oldCount = root.childCount;
-
- PlacesUtils.bookmarks.removeItem(queryId);
-
- do_check_eq(root.childCount, oldCount-1);
-
- root.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/unit/test_433317_query_title_update.js b/toolkit/components/places/tests/unit/test_433317_query_title_update.js
deleted file mode 100644
index 52558e844..000000000
--- a/toolkit/components/places/tests/unit/test_433317_query_title_update.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
- } catch (ex) {
- do_throw("Unable to initialize Places services");
- }
-
- // create a query bookmark
- var queryId = bmsvc.insertBookmark(bmsvc.toolbarFolder, uri("place:"),
- 0 /* first item */, "test query");
-
- // query for that query
- var options = histsvc.getNewQueryOptions();
- var query = histsvc.getNewQuery();
- query.setFolders([bmsvc.toolbarFolder], 1);
- var result = histsvc.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var queryNode = root.getChild(0);
- do_check_eq(queryNode.title, "test query");
-
- // change the title
- bmsvc.setItemTitle(queryId, "foo");
-
- // confirm the node was updated
- do_check_eq(queryNode.title, "foo");
-
- root.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/unit/test_433525_hasChildren_crash.js b/toolkit/components/places/tests/unit/test_433525_hasChildren_crash.js
deleted file mode 100644
index 92dac0b17..000000000
--- a/toolkit/components/places/tests/unit/test_433525_hasChildren_crash.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
- } catch (ex) {
- do_throw("Unable to initialize Places services");
- }
-
- // add a visit
- var testURI = uri("http://test");
- yield PlacesTestUtils.addVisits(testURI);
-
- // query for the visit
- var options = histsvc.getNewQueryOptions();
- options.maxResults = 1;
- options.resultType = options.RESULTS_AS_URI;
- var query = histsvc.getNewQuery();
- query.uri = testURI;
- var result = histsvc.executeQuery(query, options);
- var root = result.root;
-
- // check hasChildren while the container is closed
- do_check_eq(root.hasChildren, true);
-
- // now check via the saved search path
- var queryURI = histsvc.queriesToQueryString([query], 1, options);
- bmsvc.insertBookmark(bmsvc.toolbarFolder, uri(queryURI),
- 0 /* first item */, "test query");
-
- // query for that query
- options = histsvc.getNewQueryOptions();
- query = histsvc.getNewQuery();
- query.setFolders([bmsvc.toolbarFolder], 1);
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- var queryNode = root.getChild(0);
- do_check_eq(queryNode.title, "test query");
- queryNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(queryNode.hasChildren, true);
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_452777.js b/toolkit/components/places/tests/unit/test_452777.js
deleted file mode 100644
index 97b2852f6..000000000
--- a/toolkit/components/places/tests/unit/test_452777.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim:set ts=2 sw=2 sts=2 expandtab
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * This test ensures that when removing a folder within a transaction, undoing
- * the transaction restores it with the same id (as received by the observers).
- */
-
-var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-function run_test()
-{
- const TITLE = "test folder";
-
- // Create two test folders; remove the first one. This ensures that undoing
- // the removal will not get the same id by chance (the insert id's can be
- // reused in SQLite).
- let id = bs.createFolder(bs.placesRoot, TITLE, -1);
- bs.createFolder(bs.placesRoot, "test folder 2", -1);
- let transaction = bs.getRemoveFolderTransaction(id);
- transaction.doTransaction();
-
- // Now check to make sure it gets added with the right id
- bs.addObserver({
- onItemAdded: function(aItemId, aFolder, aIndex, aItemType, aURI, aTitle)
- {
- do_check_eq(aItemId, id);
- do_check_eq(aTitle, TITLE);
- }
- }, false);
- transaction.undoTransaction();
-}
diff --git a/toolkit/components/places/tests/unit/test_454977.js b/toolkit/components/places/tests/unit/test_454977.js
deleted file mode 100644
index 606e83048..000000000
--- a/toolkit/components/places/tests/unit/test_454977.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Cache actual visit_count value, filled by add_visit, used by check_results
-var visit_count = 0;
-
-// Returns the Place ID corresponding to an added visit.
-function* task_add_visit(aURI, aVisitType)
-{
- // Add the visit asynchronously, and save its visit ID.
- let deferUpdatePlaces = new Promise((resolve, reject) =>
- {
- PlacesUtils.asyncHistory.updatePlaces({
- uri: aURI,
- visits: [{ transitionType: aVisitType, visitDate: Date.now() * 1000 }]
- }, {
- handleError: function TAV_handleError() {
- reject(new Error("Unexpected error in adding visit."));
- },
- handleResult: function (aPlaceInfo) {
- this.visitId = aPlaceInfo.visits[0].visitId;
- },
- handleCompletion: function TAV_handleCompletion() {
- resolve(this.visitId);
- }
- });
- });
-
- let visitId = yield deferUpdatePlaces;
-
- // Increase visit_count if applicable
- if (aVisitType != 0 &&
- aVisitType != TRANSITION_EMBED &&
- aVisitType != TRANSITION_FRAMED_LINK &&
- aVisitType != TRANSITION_DOWNLOAD &&
- aVisitType != TRANSITION_RELOAD) {
- visit_count ++;
- }
-
- // Get the place id
- if (visitId > 0) {
- let sql = "SELECT place_id FROM moz_historyvisits WHERE id = ?1";
- let stmt = DBConn().createStatement(sql);
- stmt.bindByIndex(0, visitId);
- do_check_true(stmt.executeStep());
- let placeId = stmt.getInt64(0);
- stmt.finalize();
- do_check_true(placeId > 0);
- return placeId;
- }
- return 0;
-}
-
-/**
- * Checks for results consistency, using visit_count as constraint
- * @param aExpectedCount
- * Number of history results we are expecting (excluded hidden ones)
- * @param aExpectedCountWithHidden
- * Number of history results we are expecting (included hidden ones)
- */
-function check_results(aExpectedCount, aExpectedCountWithHidden)
-{
- let query = PlacesUtils.history.getNewQuery();
- // used to check visit_count
- query.minVisits = visit_count;
- query.maxVisits = visit_count;
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY;
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- // Children without hidden ones
- do_check_eq(root.childCount, aExpectedCount);
- root.containerOpen = false;
-
- // Execute again with includeHidden = true
- // This will ensure visit_count is correct
- options.includeHidden = true;
- root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- // Children with hidden ones
- do_check_eq(root.childCount, aExpectedCountWithHidden);
- root.containerOpen = false;
-}
-
-// main
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- const TEST_URI = uri("http://test.mozilla.org/");
-
- // Add a visit that force hidden
- yield task_add_visit(TEST_URI, TRANSITION_EMBED);
- check_results(0, 0);
-
- let placeId = yield task_add_visit(TEST_URI, TRANSITION_FRAMED_LINK);
- check_results(0, 1);
-
- // Add a visit that force unhide and check the place id.
- // - We expect that the place gets hidden = 0 while retaining the same
- // place id and a correct visit_count.
- do_check_eq((yield task_add_visit(TEST_URI, TRANSITION_TYPED)), placeId);
- check_results(1, 1);
-
- // Add a visit that should not increase visit_count
- do_check_eq((yield task_add_visit(TEST_URI, TRANSITION_RELOAD)), placeId);
- check_results(1, 1);
-
- // Add a visit that should not increase visit_count
- do_check_eq((yield task_add_visit(TEST_URI, TRANSITION_DOWNLOAD)), placeId);
- check_results(1, 1);
-
- // Add a visit, check that hidden is not overwritten
- // - We expect that the place has still hidden = 0, while retaining
- // correct visit_count.
- yield task_add_visit(TEST_URI, TRANSITION_EMBED);
- check_results(1, 1);
-});
diff --git a/toolkit/components/places/tests/unit/test_463863.js b/toolkit/components/places/tests/unit/test_463863.js
deleted file mode 100644
index 2f7cece4a..000000000
--- a/toolkit/components/places/tests/unit/test_463863.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * TEST DESCRIPTION:
- *
- * This test checks that in a basic history query all transition types visits
- * appear but TRANSITION_EMBED and TRANSITION_FRAMED_LINK ones.
- */
-
-var transitions = [
- TRANSITION_LINK
-, TRANSITION_TYPED
-, TRANSITION_BOOKMARK
-, TRANSITION_EMBED
-, TRANSITION_FRAMED_LINK
-, TRANSITION_REDIRECT_PERMANENT
-, TRANSITION_REDIRECT_TEMPORARY
-, TRANSITION_DOWNLOAD
-];
-
-function runQuery(aResultType) {
- let options = PlacesUtils.history.getNewQueryOptions();
- options.resultType = aResultType;
- let root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(),
- options).root;
- root.containerOpen = true;
- let cc = root.childCount;
- do_check_eq(cc, transitions.length - 2);
-
- for (let i = 0; i < cc; i++) {
- let node = root.getChild(i);
- // Check that all transition types but EMBED and FRAMED appear in results
- do_check_neq(node.uri.substr(6, 1), TRANSITION_EMBED);
- do_check_neq(node.uri.substr(6, 1), TRANSITION_FRAMED_LINK);
- }
- root.containerOpen = false;
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- // add visits, one for each transition type
- for (let transition of transitions) {
- yield PlacesTestUtils.addVisits({
- uri: uri("http://" + transition + ".mozilla.org/"),
- transition: transition
- });
- }
-
- runQuery(Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT);
- runQuery(Ci.nsINavHistoryQueryOptions.RESULTS_AS_URI);
-});
diff --git a/toolkit/components/places/tests/unit/test_485442_crash_bug_nsNavHistoryQuery_GetUri.js b/toolkit/components/places/tests/unit/test_485442_crash_bug_nsNavHistoryQuery_GetUri.js
deleted file mode 100644
index 873174ffd..000000000
--- a/toolkit/components/places/tests/unit/test_485442_crash_bug_nsNavHistoryQuery_GetUri.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-function run_test() {
- var query = hs.getNewQuery();
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULT_TYPE_QUERY;
- var result = hs.executeQuery(query, options);
- result.root.containerOpen = true;
- var rootNode = result.root;
- rootNode.QueryInterface(Ci.nsINavHistoryQueryResultNode);
- var queries = rootNode.getQueries();
- do_check_eq(queries[0].uri, null); // Should be null, instead of crashing the browser
- rootNode.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/unit/test_486978_sort_by_date_queries.js b/toolkit/components/places/tests/unit/test_486978_sort_by_date_queries.js
deleted file mode 100644
index 05f3f83e7..000000000
--- a/toolkit/components/places/tests/unit/test_486978_sort_by_date_queries.js
+++ /dev/null
@@ -1,129 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * TEST DESCRIPTION:
- *
- * This test checks that setting a sort on a RESULTS_AS_DATE_QUERY query,
- * children of inside containers are sorted accordingly.
- */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-// Will be inserted in this order, so last one will be the newest visit.
-var pages = [
- "http://a.mozilla.org/1/",
- "http://a.mozilla.org/2/",
- "http://a.mozilla.org/3/",
- "http://a.mozilla.org/4/",
- "http://b.mozilla.org/5/",
- "http://b.mozilla.org/6/",
- "http://b.mozilla.org/7/",
- "http://b.mozilla.org/8/",
-];
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_initialize()
-{
- var noon = new Date();
- noon.setHours(12);
-
- // Add visits.
- for (let pageIndex = 0; pageIndex < pages.length; ++pageIndex) {
- let page = pages[pageIndex];
- yield PlacesTestUtils.addVisits({
- uri: uri(page),
- visitDate: noon - (pages.length - pageIndex) * 1000
- });
- }
-});
-
-/**
- * Tests that sorting date query by none will sort by title asc.
- */
-add_task(function() {
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_DATE_QUERY;
- // This should sort by title asc.
- options.sortingMode = options.SORT_BY_NONE;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var dayContainer = root.getChild(0).QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dayContainer.containerOpen = true;
-
- var cc = dayContainer.childCount;
- do_check_eq(cc, pages.length);
- for (var i = 0; i < cc; i++) {
- var node = dayContainer.getChild(i);
- do_check_eq(pages[i], node.uri);
- }
-
- dayContainer.containerOpen = false;
- root.containerOpen = false;
-});
-
-/**
- * Tests that sorting date query by date will sort accordingly.
- */
-add_task(function() {
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_DATE_QUERY;
- // This should sort by title asc.
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var dayContainer = root.getChild(0).QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dayContainer.containerOpen = true;
-
- var cc = dayContainer.childCount;
- do_check_eq(cc, pages.length);
- for (var i = 0; i < cc; i++) {
- var node = dayContainer.getChild(i);
- do_check_eq(pages[pages.length - i - 1], node.uri);
- }
-
- dayContainer.containerOpen = false;
- root.containerOpen = false;
-});
-
-/**
- * Tests that sorting date site query by date will still sort by title asc.
- */
-add_task(function() {
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_DATE_SITE_QUERY;
- // This should sort by title asc.
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var dayContainer = root.getChild(0).QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dayContainer.containerOpen = true;
- var siteContainer = dayContainer.getChild(0).QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(siteContainer.title, "a.mozilla.org");
- siteContainer.containerOpen = true;
-
- var cc = siteContainer.childCount;
- do_check_eq(cc, pages.length / 2);
- for (var i = 0; i < cc / 2; i++) {
- var node = siteContainer.getChild(i);
- do_check_eq(pages[i], node.uri);
- }
-
- siteContainer.containerOpen = false;
- dayContainer.containerOpen = false;
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_536081.js b/toolkit/components/places/tests/unit/test_536081.js
deleted file mode 100644
index b61b91866..000000000
--- a/toolkit/components/places/tests/unit/test_536081.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var bh = hs.QueryInterface(Ci.nsIBrowserHistory);
-var db = hs.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
-
-const URLS = [
- { u: "http://www.google.com/search?q=testing%3Bthis&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:unofficial&client=firefox-a",
- s: "goog" },
-];
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- for (let url of URLS) {
- yield task_test_url(url);
- }
-});
-
-function* task_test_url(aURL) {
- print("Testing url: " + aURL.u);
- yield PlacesTestUtils.addVisits(uri(aURL.u));
- let query = hs.getNewQuery();
- query.searchTerms = aURL.s;
- let options = hs.getNewQueryOptions();
- let root = hs.executeQuery(query, options).root;
- root.containerOpen = true;
- let cc = root.childCount;
- do_check_eq(cc, 1);
- print("Checking url is in the query.");
- let node = root.getChild(0);
- print("Found " + node.uri);
- root.containerOpen = false;
- bh.removePage(uri(node.uri));
-}
-
-function check_empty_table(table_name) {
- print("Checking url has been removed.");
- let stmt = db.createStatement("SELECT count(*) FROM " + table_name);
- try {
- stmt.executeStep();
- do_check_eq(stmt.getInt32(0), 0);
- }
- finally {
- stmt.finalize();
- }
-}
diff --git a/toolkit/components/places/tests/unit/test_PlacesSearchAutocompleteProvider.js b/toolkit/components/places/tests/unit/test_PlacesSearchAutocompleteProvider.js
deleted file mode 100644
index 1280ce3e7..000000000
--- a/toolkit/components/places/tests/unit/test_PlacesSearchAutocompleteProvider.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Cu.import("resource://gre/modules/PlacesSearchAutocompleteProvider.jsm");
-
-function run_test() {
- // Tell the search service we are running in the US. This also has the
- // desired side-effect of preventing our geoip lookup.
- Services.prefs.setBoolPref("browser.search.isUS", true);
- Services.prefs.setCharPref("browser.search.countryCode", "US");
- Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", false);
- run_next_test();
-}
-
-add_task(function* search_engine_match() {
- let engine = yield promiseDefaultSearchEngine();
- let token = engine.getResultDomain();
- let match = yield PlacesSearchAutocompleteProvider.findMatchByToken(token.substr(0, 1));
- do_check_eq(match.url, engine.searchForm);
- do_check_eq(match.engineName, engine.name);
- do_check_eq(match.iconUrl, engine.iconURI ? engine.iconURI.spec : null);
-});
-
-add_task(function* no_match() {
- do_check_eq(null, yield PlacesSearchAutocompleteProvider.findMatchByToken("test"));
-});
-
-add_task(function* hide_search_engine_nomatch() {
- let engine = yield promiseDefaultSearchEngine();
- let token = engine.getResultDomain();
- let promiseTopic = promiseSearchTopic("engine-changed");
- Services.search.removeEngine(engine);
- yield promiseTopic;
- do_check_true(engine.hidden);
- do_check_eq(null, yield PlacesSearchAutocompleteProvider.findMatchByToken(token.substr(0, 1)));
-});
-
-add_task(function* add_search_engine_match() {
- let promiseTopic = promiseSearchTopic("engine-added");
- do_check_eq(null, yield PlacesSearchAutocompleteProvider.findMatchByToken("bacon"));
- Services.search.addEngineWithDetails("bacon", "", "pork", "Search Bacon",
- "GET", "http://www.bacon.moz/?search={searchTerms}");
- yield promiseTopic;
- let match = yield PlacesSearchAutocompleteProvider.findMatchByToken("bacon");
- do_check_eq(match.url, "http://www.bacon.moz");
- do_check_eq(match.engineName, "bacon");
- do_check_eq(match.iconUrl, null);
-});
-
-add_task(function* test_aliased_search_engine_match() {
- do_check_eq(null, yield PlacesSearchAutocompleteProvider.findMatchByAlias("sober"));
- // Lower case
- let match = yield PlacesSearchAutocompleteProvider.findMatchByAlias("pork");
- do_check_eq(match.engineName, "bacon");
- do_check_eq(match.alias, "pork");
- do_check_eq(match.iconUrl, null);
- // Upper case
- let match1 = yield PlacesSearchAutocompleteProvider.findMatchByAlias("PORK");
- do_check_eq(match1.engineName, "bacon");
- do_check_eq(match1.alias, "pork");
- do_check_eq(match1.iconUrl, null);
- // Cap case
- let match2 = yield PlacesSearchAutocompleteProvider.findMatchByAlias("Pork");
- do_check_eq(match2.engineName, "bacon");
- do_check_eq(match2.alias, "pork");
- do_check_eq(match2.iconUrl, null);
-});
-
-add_task(function* test_aliased_search_engine_match_upper_case_alias() {
- let promiseTopic = promiseSearchTopic("engine-added");
- do_check_eq(null, yield PlacesSearchAutocompleteProvider.findMatchByToken("patch"));
- Services.search.addEngineWithDetails("patch", "", "PR", "Search Patch",
- "GET", "http://www.patch.moz/?search={searchTerms}");
- yield promiseTopic;
- // lower case
- let match = yield PlacesSearchAutocompleteProvider.findMatchByAlias("pr");
- do_check_eq(match.engineName, "patch");
- do_check_eq(match.alias, "PR");
- do_check_eq(match.iconUrl, null);
- // Upper case
- let match1 = yield PlacesSearchAutocompleteProvider.findMatchByAlias("PR");
- do_check_eq(match1.engineName, "patch");
- do_check_eq(match1.alias, "PR");
- do_check_eq(match1.iconUrl, null);
- // Cap case
- let match2 = yield PlacesSearchAutocompleteProvider.findMatchByAlias("Pr");
- do_check_eq(match2.engineName, "patch");
- do_check_eq(match2.alias, "PR");
- do_check_eq(match2.iconUrl, null);
-});
-
-add_task(function* remove_search_engine_nomatch() {
- let engine = Services.search.getEngineByName("bacon");
- let promiseTopic = promiseSearchTopic("engine-removed");
- Services.search.removeEngine(engine);
- yield promiseTopic;
- do_check_eq(null, yield PlacesSearchAutocompleteProvider.findMatchByToken("bacon"));
-});
-
-add_task(function* test_parseSubmissionURL_basic() {
- // Most of the logic of parseSubmissionURL is tested in the search service
- // itself, thus we only do a sanity check of the wrapper here.
- let engine = yield promiseDefaultSearchEngine();
- let submissionURL = engine.getSubmission("terms").uri.spec;
-
- let result = PlacesSearchAutocompleteProvider.parseSubmissionURL(submissionURL);
- do_check_eq(result.engineName, engine.name);
- do_check_eq(result.terms, "terms");
-
- result = PlacesSearchAutocompleteProvider.parseSubmissionURL("http://example.org/");
- do_check_eq(result, null);
-});
-
-function promiseDefaultSearchEngine() {
- let deferred = Promise.defer();
- Services.search.init( () => {
- deferred.resolve(Services.search.defaultEngine);
- });
- return deferred.promise;
-}
-
-function promiseSearchTopic(expectedVerb) {
- let deferred = Promise.defer();
- Services.obs.addObserver( function observe(subject, topic, verb) {
- do_print("browser-search-engine-modified: " + verb);
- if (verb == expectedVerb) {
- Services.obs.removeObserver(observe, "browser-search-engine-modified");
- deferred.resolve();
- }
- }, "browser-search-engine-modified", false);
- return deferred.promise;
-}
diff --git a/toolkit/components/places/tests/unit/test_PlacesUtils_asyncGetBookmarkIds.js b/toolkit/components/places/tests/unit/test_PlacesUtils_asyncGetBookmarkIds.js
deleted file mode 100644
index 182f75eac..000000000
--- a/toolkit/components/places/tests/unit/test_PlacesUtils_asyncGetBookmarkIds.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * This file tests PlacesUtils.asyncGetBookmarkIds method.
- */
-
-const TEST_URL = "http://www.example.com/";
-
-var promiseAsyncGetBookmarkIds = Task.async(function* (url) {
- yield PlacesTestUtils.promiseAsyncUpdates();
- return new Promise(resolve => {
- PlacesUtils.asyncGetBookmarkIds(url, (itemIds, uri) => {
- Assert.equal(uri, url);
- resolve({ itemIds, url });
- });
- });
-});
-
-add_task(function* test_no_bookmark() {
- let { itemIds, url } = yield promiseAsyncGetBookmarkIds(TEST_URL);
- Assert.equal(itemIds.length, 0);
- Assert.equal(url, TEST_URL);
-});
-
-add_task(function* test_one_bookmark() {
- let bookmark = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: TEST_URL,
- title: "test"
- });
- let itemId = yield PlacesUtils.promiseItemId(bookmark.guid);
- {
- let { itemIds, url } = yield promiseAsyncGetBookmarkIds(NetUtil.newURI(TEST_URL));
- Assert.equal(itemIds.length, 1);
- Assert.equal(itemIds[0], itemId);
- Assert.equal(url.spec, TEST_URL);
- }
- {
- let { itemIds, url } = yield promiseAsyncGetBookmarkIds(TEST_URL);
- Assert.equal(itemIds.length, 1);
- Assert.equal(itemIds[0], itemId);
- Assert.equal(url, TEST_URL);
- }
- yield PlacesUtils.bookmarks.remove(bookmark);
-});
-
-add_task(function* test_multiple_bookmarks() {
- let ids = [];
- let bookmark1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: TEST_URL,
- title: "test"
- });
- ids.push((yield PlacesUtils.promiseItemId(bookmark1.guid)));
- let bookmark2 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: TEST_URL,
- title: "test"
- });
- ids.push((yield PlacesUtils.promiseItemId(bookmark2.guid)));
-
- let { itemIds, url } = yield promiseAsyncGetBookmarkIds(TEST_URL);
- Assert.deepEqual(ids, itemIds);
- Assert.equal(url, TEST_URL);
-
- yield PlacesUtils.bookmarks.remove(bookmark1);
- yield PlacesUtils.bookmarks.remove(bookmark2);
-});
-
-add_task(function* test_cancel() {
- let pending = PlacesUtils.asyncGetBookmarkIds(TEST_URL, () => {
- Assert.ok(false, "A canceled pending statement should not be invoked");
- });
- pending.cancel();
-
- let { itemIds, url } = yield promiseAsyncGetBookmarkIds(TEST_URL);
- Assert.equal(itemIds.length, 0);
- Assert.equal(url, TEST_URL);
-});
diff --git a/toolkit/components/places/tests/unit/test_PlacesUtils_invalidateCachedGuidFor.js b/toolkit/components/places/tests/unit/test_PlacesUtils_invalidateCachedGuidFor.js
deleted file mode 100644
index b7906ec5c..000000000
--- a/toolkit/components/places/tests/unit/test_PlacesUtils_invalidateCachedGuidFor.js
+++ /dev/null
@@ -1,25 +0,0 @@
-add_task(function* () {
- do_print("Add a bookmark.");
- let bm = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let id = yield PlacesUtils.promiseItemId(bm.guid);
- Assert.equal((yield PlacesUtils.promiseItemGuid(id)), bm.guid);
-
- // Ensure invalidating a non-existent itemId doesn't throw.
- PlacesUtils.invalidateCachedGuidFor(null);
- PlacesUtils.invalidateCachedGuidFor(9999);
-
- do_print("Change the GUID.");
- yield PlacesUtils.withConnectionWrapper("test", Task.async(function*(db) {
- yield db.execute("UPDATE moz_bookmarks SET guid = :guid WHERE id = :id",
- { guid: "123456789012", id});
- }));
- // The cache should still point to the wrong id.
- Assert.equal((yield PlacesUtils.promiseItemGuid(id)), bm.guid);
-
- do_print("Invalidate the cache.");
- PlacesUtils.invalidateCachedGuidFor(id);
- Assert.equal((yield PlacesUtils.promiseItemGuid(id)), "123456789012");
- Assert.equal((yield PlacesUtils.promiseItemId("123456789012")), id);
- yield Assert.rejects(PlacesUtils.promiseItemId(bm.guid), /no item found for the given GUID/);
-});
diff --git a/toolkit/components/places/tests/unit/test_PlacesUtils_lazyobservers.js b/toolkit/components/places/tests/unit/test_PlacesUtils_lazyobservers.js
deleted file mode 100644
index f0e9c5517..000000000
--- a/toolkit/components/places/tests/unit/test_PlacesUtils_lazyobservers.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test() {
- do_test_pending();
-
- const TEST_URI = NetUtil.newURI("http://moz.org/")
- let observer = {
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver,
- ]),
-
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemAdded: function (aItemId, aParentId, aIndex, aItemType, aURI) {
- do_check_true(aURI.equals(TEST_URI));
- PlacesUtils.removeLazyBookmarkObserver(this);
- do_test_finished();
- },
- onItemRemoved: function () {},
- onItemChanged: function () {},
- onItemVisited: function () {},
- onItemMoved: function () {},
- };
-
- // Check registration and removal with uninitialized bookmarks service.
- PlacesUtils.addLazyBookmarkObserver(observer);
- PlacesUtils.removeLazyBookmarkObserver(observer);
-
- // Add a proper lazy observer we will test.
- PlacesUtils.addLazyBookmarkObserver(observer);
-
- // Check that we don't leak when adding and removing an observer while the
- // bookmarks service is instantiated but no change happened (bug 721319).
- PlacesUtils.bookmarks;
- PlacesUtils.addLazyBookmarkObserver(observer);
- PlacesUtils.removeLazyBookmarkObserver(observer);
- try {
- PlacesUtils.bookmarks.removeObserver(observer);
- do_throw("Trying to remove a nonexisting observer should throw!");
- } catch (ex) {}
-
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "Bookmark title");
-}
diff --git a/toolkit/components/places/tests/unit/test_adaptive.js b/toolkit/components/places/tests/unit/test_adaptive.js
deleted file mode 100644
index 78ffaedb5..000000000
--- a/toolkit/components/places/tests/unit/test_adaptive.js
+++ /dev/null
@@ -1,406 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for bug 395739 to make sure the feedback to the search results in those
- * entries getting better ranks. Additionally, exact matches should be ranked
- * higher. Because the interactions among adaptive rank and visit counts is not
- * well defined, this test holds one of the two values constant when modifying
- * the other.
- *
- * This also tests bug 395735 for the instrumentation feedback mechanism.
- *
- * Bug 411293 is tested to make sure the drop down strongly prefers previously
- * typed pages that have been selected and are moved to the top with adaptive
- * learning.
- */
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- get minResultsForPopup() {
- return 0;
- },
- get timeout() {
- return 10;
- },
- get searchParam() {
- return "";
- },
- get textValue() {
- return "";
- },
- get disableAutoComplete() {
- return false;
- },
- get completeDefaultIndex() {
- return false;
- },
-
- get searchCount() {
- return this.searches.length;
- },
- getSearchAt: function (aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function () {},
- onSearchComplete: function() {},
-
- get popupOpen() {
- return false;
- },
- popup: {
- set selectedIndex(aIndex) {},
- invalidate: function () {},
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompletePopup])
- },
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput])
-}
-
-/**
- * Checks that autocomplete results are ordered correctly.
- */
-function ensure_results(expected, searchTerm)
-{
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete.
- let input = new AutoCompleteInput(["unifiedcomplete"]);
-
- controller.input = input;
-
- input.onSearchComplete = function() {
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- do_check_eq(controller.matchCount, expected.length);
- for (let i = 0; i < controller.matchCount; i++) {
- print("Testing for '" + expected[i].uri.spec + "' got '" + controller.getValueAt(i) + "'");
- do_check_eq(controller.getValueAt(i), expected[i].uri.spec);
- do_check_eq(controller.getStyleAt(i), expected[i].style);
- }
-
- deferEnsureResults.resolve();
- };
-
- controller.startSearch(searchTerm);
-}
-
-/**
- * Asynchronous task that bumps up the rank for an uri.
- */
-function* task_setCountRank(aURI, aCount, aRank, aSearch, aBookmark)
-{
- // Bump up the visit count for the uri.
- let visits = [];
- for (let i = 0; i < aCount; i++) {
- visits.push({ uri: aURI, visitDate: d1, transition: TRANSITION_TYPED });
- }
- yield PlacesTestUtils.addVisits(visits);
-
- // Make a nsIAutoCompleteController and friends for instrumentation feedback.
- let thing = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput,
- Ci.nsIAutoCompletePopup,
- Ci.nsIAutoCompleteController]),
- get popup() {
- return thing;
- },
- get controller() {
- return thing;
- },
- popupOpen: true,
- selectedIndex: 0,
- getValueAt: function() {
- return aURI.spec;
- },
- searchString: aSearch
- };
-
- // Bump up the instrumentation feedback.
- for (let i = 0; i < aRank; i++) {
- Services.obs.notifyObservers(thing, "autocomplete-will-enter-text", null);
- }
-
- // If this is supposed to be a bookmark, add it.
- if (aBookmark) {
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- aURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test_book");
-
- // And add the tag if we need to.
- if (aBookmark == "tag") {
- PlacesUtils.tagging.tagURI(aURI, ["test_tag"]);
- }
- }
-}
-
-/**
- * Decay the adaptive entries by sending the daily idle topic.
- */
-function doAdaptiveDecay()
-{
- PlacesUtils.history.runInBatchMode({
- runBatched: function() {
- for (let i = 0; i < 10; i++) {
- PlacesUtils.history.QueryInterface(Ci.nsIObserver)
- .observe(null, "idle-daily", null);
- }
- }
- }, this);
-}
-
-var uri1 = uri("http://site.tld/1");
-var uri2 = uri("http://site.tld/2");
-
-// d1 is some date for the page visit
-var d1 = new Date(Date.now() - 1000 * 60 * 60) * 1000;
-// c1 is larger (should show up higher) than c2
-var c1 = 10;
-var c2 = 1;
-// s1 is a partial match of s2
-var s0 = "";
-var s1 = "si";
-var s2 = "site";
-
-var observer = {
- results: null,
- search: null,
- runCount: -1,
- observe: function(aSubject, aTopic, aData)
- {
- if (--this.runCount > 0)
- return;
- ensure_results(this.results, this.search);
- }
-};
-Services.obs.addObserver(observer, PlacesUtils.TOPIC_FEEDBACK_UPDATED, false);
-
-/**
- * Make the result object for a given URI that will be passed to ensure_results.
- */
-function makeResult(aURI, aStyle = "favicon") {
- return {
- uri: aURI,
- style: aStyle,
- };
-}
-
-var tests = [
- // Test things without a search term.
- function*() {
- print("Test 0 same count, diff rank, same term; no search");
- observer.results = [
- makeResult(uri1),
- makeResult(uri2),
- ];
- observer.search = s0;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c1, s2);
- yield task_setCountRank(uri2, c1, c2, s2);
- },
- function*() {
- print("Test 1 same count, diff rank, same term; no search");
- observer.results = [
- makeResult(uri2),
- makeResult(uri1),
- ];
- observer.search = s0;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c2, s2);
- yield task_setCountRank(uri2, c1, c1, s2);
- },
- function*() {
- print("Test 2 diff count, same rank, same term; no search");
- observer.results = [
- makeResult(uri1),
- makeResult(uri2),
- ];
- observer.search = s0;
- observer.runCount = c1 + c1;
- yield task_setCountRank(uri1, c1, c1, s2);
- yield task_setCountRank(uri2, c2, c1, s2);
- },
- function*() {
- print("Test 3 diff count, same rank, same term; no search");
- observer.results = [
- makeResult(uri2),
- makeResult(uri1),
- ];
- observer.search = s0;
- observer.runCount = c1 + c1;
- yield task_setCountRank(uri1, c2, c1, s2);
- yield task_setCountRank(uri2, c1, c1, s2);
- },
-
- // Test things with a search term (exact match one, partial other).
- function*() {
- print("Test 4 same count, same rank, diff term; one exact/one partial search");
- observer.results = [
- makeResult(uri1),
- makeResult(uri2),
- ];
- observer.search = s1;
- observer.runCount = c1 + c1;
- yield task_setCountRank(uri1, c1, c1, s1);
- yield task_setCountRank(uri2, c1, c1, s2);
- },
- function*() {
- print("Test 5 same count, same rank, diff term; one exact/one partial search");
- observer.results = [
- makeResult(uri2),
- makeResult(uri1),
- ];
- observer.search = s1;
- observer.runCount = c1 + c1;
- yield task_setCountRank(uri1, c1, c1, s2);
- yield task_setCountRank(uri2, c1, c1, s1);
- },
-
- // Test things with a search term (exact match both).
- function*() {
- print("Test 6 same count, diff rank, same term; both exact search");
- observer.results = [
- makeResult(uri1),
- makeResult(uri2),
- ];
- observer.search = s1;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c1, s1);
- yield task_setCountRank(uri2, c1, c2, s1);
- },
- function*() {
- print("Test 7 same count, diff rank, same term; both exact search");
- observer.results = [
- makeResult(uri2),
- makeResult(uri1),
- ];
- observer.search = s1;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c2, s1);
- yield task_setCountRank(uri2, c1, c1, s1);
- },
-
- // Test things with a search term (partial match both).
- function*() {
- print("Test 8 same count, diff rank, same term; both partial search");
- observer.results = [
- makeResult(uri1),
- makeResult(uri2),
- ];
- observer.search = s1;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c1, s2);
- yield task_setCountRank(uri2, c1, c2, s2);
- },
- function*() {
- print("Test 9 same count, diff rank, same term; both partial search");
- observer.results = [
- makeResult(uri2),
- makeResult(uri1),
- ];
- observer.search = s1;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c2, s2);
- yield task_setCountRank(uri2, c1, c1, s2);
- },
- function*() {
- print("Test 10 same count, same rank, same term, decay first; exact match");
- observer.results = [
- makeResult(uri2),
- makeResult(uri1),
- ];
- observer.search = s1;
- observer.runCount = c1 + c1;
- yield task_setCountRank(uri1, c1, c1, s1);
- doAdaptiveDecay();
- yield task_setCountRank(uri2, c1, c1, s1);
- },
- function*() {
- print("Test 11 same count, same rank, same term, decay second; exact match");
- observer.results = [
- makeResult(uri1),
- makeResult(uri2),
- ];
- observer.search = s1;
- observer.runCount = c1 + c1;
- yield task_setCountRank(uri2, c1, c1, s1);
- doAdaptiveDecay();
- yield task_setCountRank(uri1, c1, c1, s1);
- },
- // Test that bookmarks are hidden if the preferences are set right.
- function*() {
- print("Test 12 same count, diff rank, same term; no search; history only");
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.openpage", false);
- observer.results = [
- makeResult(uri1),
- makeResult(uri2),
- ];
- observer.search = s0;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c1, s2, "bookmark");
- yield task_setCountRank(uri2, c1, c2, s2);
- },
- // Test that tags are shown if the preferences are set right.
- function*() {
- print("Test 13 same count, diff rank, same term; no search; history only with tag");
- Services.prefs.setBoolPref("browser.urlbar.suggest.history", true);
- Services.prefs.setBoolPref("browser.urlbar.suggest.bookmark", false);
- Services.prefs.setBoolPref("browser.urlbar.suggest.openpage", false);
- observer.results = [
- makeResult(uri1, "tag"),
- makeResult(uri2),
- ];
- observer.search = s0;
- observer.runCount = c1 + c2;
- yield task_setCountRank(uri1, c1, c1, s2, "tag");
- yield task_setCountRank(uri2, c1, c2, s2);
- },
-];
-
-/**
- * This deferred object contains a promise that is resolved when the
- * ensure_results function has finished its execution.
- */
-var deferEnsureResults;
-
-/**
- * Test adaptive autocomplete.
- */
-add_task(function* test_adaptive()
-{
- // Disable autoFill for this test.
- Services.prefs.setBoolPref("browser.urlbar.autoFill", false);
- do_register_cleanup(() => Services.prefs.clearUserPref("browser.urlbar.autoFill"));
- for (let test of tests) {
- // Cleanup.
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.tagsFolderId);
- observer.runCount = -1;
-
- let types = ["history", "bookmark", "openpage"];
- for (let type of types) {
- Services.prefs.clearUserPref("browser.urlbar.suggest." + type);
- }
-
- yield PlacesTestUtils.clearHistory();
-
- deferEnsureResults = Promise.defer();
- yield test();
- yield deferEnsureResults.promise;
- }
-
- Services.obs.removeObserver(observer, PlacesUtils.TOPIC_FEEDBACK_UPDATED);
-});
diff --git a/toolkit/components/places/tests/unit/test_adaptive_bug527311.js b/toolkit/components/places/tests/unit/test_adaptive_bug527311.js
deleted file mode 100644
index 024553bba..000000000
--- a/toolkit/components/places/tests/unit/test_adaptive_bug527311.js
+++ /dev/null
@@ -1,141 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const TEST_URL = "http://adapt.mozilla.org/";
-const SEARCH_STRING = "adapt";
-const SUGGEST_TYPES = ["history", "bookmark", "openpage"];
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-var os = Cc["@mozilla.org/observer-service;1"].
- getService(Ci.nsIObserverService);
-var ps = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-
-const PLACES_AUTOCOMPLETE_FEEDBACK_UPDATED_TOPIC =
- "places-autocomplete-feedback-updated";
-
-function cleanup() {
- for (let type of SUGGEST_TYPES) {
- ps.clearUserPref("browser.urlbar.suggest." + type);
- }
-}
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
- searches: null,
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function ACI_getSearchAt(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchComplete: function ACI_onSearchComplete() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function() {},
- invalidate: function() {},
-
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- onSearchBegin: function() {},
-
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-
-function check_results() {
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
- let input = new AutoCompleteInput(["unifiedcomplete"]);
- controller.input = input;
-
- input.onSearchComplete = function() {
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
- do_check_eq(controller.matchCount, 0);
-
- PlacesUtils.bookmarks.eraseEverything().then(() => {
- cleanup();
- do_test_finished();
- });
- };
-
- controller.startSearch(SEARCH_STRING);
-}
-
-
-function addAdaptiveFeedback(aUrl, aSearch, aCallback) {
- let observer = {
- observe: function(aSubject, aTopic, aData) {
- os.removeObserver(observer, PLACES_AUTOCOMPLETE_FEEDBACK_UPDATED_TOPIC);
- do_timeout(0, aCallback);
- }
- };
- os.addObserver(observer, PLACES_AUTOCOMPLETE_FEEDBACK_UPDATED_TOPIC, false);
-
- let thing = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAutoCompleteInput,
- Ci.nsIAutoCompletePopup,
- Ci.nsIAutoCompleteController]),
- get popup() { return thing; },
- get controller() { return thing; },
- popupOpen: true,
- selectedIndex: 0,
- getValueAt: () => aUrl,
- searchString: aSearch
- };
-
- os.notifyObservers(thing, "autocomplete-will-enter-text", null);
-}
-
-
-function run_test() {
- do_test_pending();
-
- // Add a bookmark to our url.
- bs.insertBookmark(bs.unfiledBookmarksFolder, uri(TEST_URL),
- bs.DEFAULT_INDEX, "test_book");
- // We want to search only history.
- for (let type of SUGGEST_TYPES) {
- type == "history" ? ps.setBoolPref("browser.urlbar.suggest." + type, true)
- : ps.setBoolPref("browser.urlbar.suggest." + type, false);
- }
-
- // Add an adaptive entry.
- addAdaptiveFeedback(TEST_URL, SEARCH_STRING, check_results);
-}
diff --git a/toolkit/components/places/tests/unit/test_analyze.js b/toolkit/components/places/tests/unit/test_analyze.js
deleted file mode 100644
index 456270101..000000000
--- a/toolkit/components/places/tests/unit/test_analyze.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests sqlite_sta1 table exists, it should be created by analyze.
-// Since the bookmark roots are created when the DB is created (bug 704855),
-// the table will contain data.
-
-function run_test() {
- do_test_pending();
-
- let stmt = DBConn().createAsyncStatement(
- "SELECT ROWID FROM sqlite_stat1"
- );
- stmt.executeAsync({
- _gotResult: false,
- handleResult: function(aResultSet) {
- this._gotResult = true;
- },
- handleError: function(aError) {
- do_throw("Unexpected error (" + aError.result + "): " + aError.message);
- },
- handleCompletion: function(aReason) {
- do_check_true(this._gotResult);
- do_test_finished();
- }
- });
- stmt.finalize();
-}
diff --git a/toolkit/components/places/tests/unit/test_annotations.js b/toolkit/components/places/tests/unit/test_annotations.js
deleted file mode 100644
index a37d7e6c9..000000000
--- a/toolkit/components/places/tests/unit/test_annotations.js
+++ /dev/null
@@ -1,363 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get bookmark service
-try {
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Ci.nsINavBookmarksService);
-} catch (ex) {
- do_throw("Could not get nav-bookmarks-service\n");
-}
-
-// Get annotation service
-try {
- var annosvc= Cc["@mozilla.org/browser/annotation-service;1"].getService(Ci.nsIAnnotationService);
-} catch (ex) {
- do_throw("Could not get annotation service\n");
-}
-
-var annoObserver = {
- PAGE_lastSet_URI: "",
- PAGE_lastSet_AnnoName: "",
-
- onPageAnnotationSet: function(aURI, aName) {
- this.PAGE_lastSet_URI = aURI.spec;
- this.PAGE_lastSet_AnnoName = aName;
- },
-
- ITEM_lastSet_Id: -1,
- ITEM_lastSet_AnnoName: "",
- onItemAnnotationSet: function(aItemId, aName) {
- this.ITEM_lastSet_Id = aItemId;
- this.ITEM_lastSet_AnnoName = aName;
- },
-
- PAGE_lastRemoved_URI: "",
- PAGE_lastRemoved_AnnoName: "",
- onPageAnnotationRemoved: function(aURI, aName) {
- this.PAGE_lastRemoved_URI = aURI.spec;
- this.PAGE_lastRemoved_AnnoName = aName;
- },
-
- ITEM_lastRemoved_Id: -1,
- ITEM_lastRemoved_AnnoName: "",
- onItemAnnotationRemoved: function(aItemId, aName) {
- this.ITEM_lastRemoved_Id = aItemId;
- this.ITEM_lastRemoved_AnnoName = aName;
- }
-};
-
-// main
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- var testURI = uri("http://mozilla.com/");
- var testItemId = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, testURI, -1, "");
- var testAnnoName = "moz-test-places/annotations";
- var testAnnoVal = "test";
-
- annosvc.addObserver(annoObserver);
- // create new string annotation
- try {
- annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, 0);
- } catch (ex) {
- do_throw("unable to add page-annotation");
- }
- do_check_eq(annoObserver.PAGE_lastSet_URI, testURI.spec);
- do_check_eq(annoObserver.PAGE_lastSet_AnnoName, testAnnoName);
-
- // get string annotation
- do_check_true(annosvc.pageHasAnnotation(testURI, testAnnoName));
- var storedAnnoVal = annosvc.getPageAnnotation(testURI, testAnnoName);
- do_check_true(testAnnoVal === storedAnnoVal);
- // string item-annotation
- try {
- var lastModified = bmsvc.getItemLastModified(testItemId);
- // Verify that lastModified equals dateAdded before we set the annotation.
- do_check_eq(lastModified, bmsvc.getItemDateAdded(testItemId));
- // Workaround possible VM timers issues moving last modified to the past.
- bmsvc.setItemLastModified(testItemId, --lastModified);
- annosvc.setItemAnnotation(testItemId, testAnnoName, testAnnoVal, 0, 0);
- var lastModified2 = bmsvc.getItemLastModified(testItemId);
- // verify that setting the annotation updates the last modified time
- do_check_true(lastModified2 > lastModified);
- } catch (ex) {
- do_throw("unable to add item annotation");
- }
- do_check_eq(annoObserver.ITEM_lastSet_Id, testItemId);
- do_check_eq(annoObserver.ITEM_lastSet_AnnoName, testAnnoName);
-
- try {
- var annoVal = annosvc.getItemAnnotation(testItemId, testAnnoName);
- // verify the anno value
- do_check_true(testAnnoVal === annoVal);
- } catch (ex) {
- do_throw("unable to get item annotation");
- }
-
- // test getPagesWithAnnotation
- var uri2 = uri("http://www.tests.tld");
- yield PlacesTestUtils.addVisits(uri2);
- annosvc.setPageAnnotation(uri2, testAnnoName, testAnnoVal, 0, 0);
- var pages = annosvc.getPagesWithAnnotation(testAnnoName);
- do_check_eq(pages.length, 2);
- // Don't rely on the order
- do_check_false(pages[0].equals(pages[1]));
- do_check_true(pages[0].equals(testURI) || pages[1].equals(testURI));
- do_check_true(pages[0].equals(uri2) || pages[1].equals(uri2));
-
- // test getItemsWithAnnotation
- var testItemId2 = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri2, -1, "");
- annosvc.setItemAnnotation(testItemId2, testAnnoName, testAnnoVal, 0, 0);
- var items = annosvc.getItemsWithAnnotation(testAnnoName);
- do_check_eq(items.length, 2);
- // Don't rely on the order
- do_check_true(items[0] != items[1]);
- do_check_true(items[0] == testItemId || items[1] == testItemId);
- do_check_true(items[0] == testItemId2 || items[1] == testItemId2);
-
- // get annotation that doesn't exist
- try {
- annosvc.getPageAnnotation(testURI, "blah");
- do_throw("fetching page-annotation that doesn't exist, should've thrown");
- } catch (ex) {}
- try {
- annosvc.getItemAnnotation(testURI, "blah");
- do_throw("fetching item-annotation that doesn't exist, should've thrown");
- } catch (ex) {}
-
- // get annotation info
- var flags = {}, exp = {}, storageType = {};
- annosvc.getPageAnnotationInfo(testURI, testAnnoName, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- do_check_eq(storageType.value, Ci.nsIAnnotationService.TYPE_STRING);
- annosvc.getItemAnnotationInfo(testItemId, testAnnoName, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- do_check_eq(storageType.value, Ci.nsIAnnotationService.TYPE_STRING);
-
- // get annotation names for a uri
- var annoNames = annosvc.getPageAnnotationNames(testURI);
- do_check_eq(annoNames.length, 1);
- do_check_eq(annoNames[0], "moz-test-places/annotations");
-
- // get annotation names for an item
- annoNames = annosvc.getItemAnnotationNames(testItemId);
- do_check_eq(annoNames.length, 1);
- do_check_eq(annoNames[0], "moz-test-places/annotations");
-
- // copy annotations to another uri
- var newURI = uri("http://mozilla.org");
- yield PlacesTestUtils.addVisits(newURI);
- annosvc.setPageAnnotation(testURI, "oldAnno", "new", 0, 0);
- annosvc.setPageAnnotation(newURI, "oldAnno", "old", 0, 0);
- annoNames = annosvc.getPageAnnotationNames(newURI);
- do_check_eq(annoNames.length, 1);
- do_check_eq(annoNames[0], "oldAnno");
- var oldAnnoNames = annosvc.getPageAnnotationNames(testURI);
- do_check_eq(oldAnnoNames.length, 2);
- var copiedAnno = oldAnnoNames[0];
- annosvc.copyPageAnnotations(testURI, newURI, false);
- var newAnnoNames = annosvc.getPageAnnotationNames(newURI);
- do_check_eq(newAnnoNames.length, 2);
- do_check_true(annosvc.pageHasAnnotation(newURI, "oldAnno"));
- do_check_true(annosvc.pageHasAnnotation(newURI, copiedAnno));
- do_check_eq(annosvc.getPageAnnotation(newURI, "oldAnno"), "old");
- annosvc.setPageAnnotation(newURI, "oldAnno", "new", 0, 0);
- annosvc.copyPageAnnotations(testURI, newURI, true);
- newAnnoNames = annosvc.getPageAnnotationNames(newURI);
- do_check_eq(newAnnoNames.length, 2);
- do_check_true(annosvc.pageHasAnnotation(newURI, "oldAnno"));
- do_check_true(annosvc.pageHasAnnotation(newURI, copiedAnno));
- do_check_eq(annosvc.getPageAnnotation(newURI, "oldAnno"), "new");
-
-
- // copy annotations to another item
- newURI = uri("http://mozilla.org");
- var newItemId = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, newURI, -1, "");
- var itemId = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, testURI, -1, "");
- annosvc.setItemAnnotation(itemId, "oldAnno", "new", 0, 0);
- annosvc.setItemAnnotation(itemId, "testAnno", "test", 0, 0);
- annosvc.setItemAnnotation(newItemId, "oldAnno", "old", 0, 0);
- annoNames = annosvc.getItemAnnotationNames(newItemId);
- do_check_eq(annoNames.length, 1);
- do_check_eq(annoNames[0], "oldAnno");
- oldAnnoNames = annosvc.getItemAnnotationNames(itemId);
- do_check_eq(oldAnnoNames.length, 2);
- copiedAnno = oldAnnoNames[0];
- annosvc.copyItemAnnotations(itemId, newItemId, false);
- newAnnoNames = annosvc.getItemAnnotationNames(newItemId);
- do_check_eq(newAnnoNames.length, 2);
- do_check_true(annosvc.itemHasAnnotation(newItemId, "oldAnno"));
- do_check_true(annosvc.itemHasAnnotation(newItemId, copiedAnno));
- do_check_eq(annosvc.getItemAnnotation(newItemId, "oldAnno"), "old");
- annosvc.setItemAnnotation(newItemId, "oldAnno", "new", 0, 0);
- annosvc.copyItemAnnotations(itemId, newItemId, true);
- newAnnoNames = annosvc.getItemAnnotationNames(newItemId);
- do_check_eq(newAnnoNames.length, 2);
- do_check_true(annosvc.itemHasAnnotation(newItemId, "oldAnno"));
- do_check_true(annosvc.itemHasAnnotation(newItemId, copiedAnno));
- do_check_eq(annosvc.getItemAnnotation(newItemId, "oldAnno"), "new");
-
- // test int32 anno type
- var int32Key = testAnnoName + "/types/Int32";
- var int32Val = 23;
- annosvc.setPageAnnotation(testURI, int32Key, int32Val, 0, 0);
- do_check_true(annosvc.pageHasAnnotation(testURI, int32Key));
- flags = {}, exp = {}, storageType = {};
- annosvc.getPageAnnotationInfo(testURI, int32Key, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- do_check_eq(storageType.value, Ci.nsIAnnotationService.TYPE_INT32);
- var storedVal = annosvc.getPageAnnotation(testURI, int32Key);
- do_check_true(int32Val === storedVal);
- annosvc.setItemAnnotation(testItemId, int32Key, int32Val, 0, 0);
- do_check_true(annosvc.itemHasAnnotation(testItemId, int32Key));
- annosvc.getItemAnnotationInfo(testItemId, int32Key, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- storedVal = annosvc.getItemAnnotation(testItemId, int32Key);
- do_check_true(int32Val === storedVal);
-
- // test int64 anno type
- var int64Key = testAnnoName + "/types/Int64";
- var int64Val = 4294967296;
- annosvc.setPageAnnotation(testURI, int64Key, int64Val, 0, 0);
- annosvc.getPageAnnotationInfo(testURI, int64Key, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- storedVal = annosvc.getPageAnnotation(testURI, int64Key);
- do_check_true(int64Val === storedVal);
- annosvc.setItemAnnotation(testItemId, int64Key, int64Val, 0, 0);
- do_check_true(annosvc.itemHasAnnotation(testItemId, int64Key));
- annosvc.getItemAnnotationInfo(testItemId, int64Key, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- storedVal = annosvc.getItemAnnotation(testItemId, int64Key);
- do_check_true(int64Val === storedVal);
-
- // test double anno type
- var doubleKey = testAnnoName + "/types/Double";
- var doubleVal = 0.000002342;
- annosvc.setPageAnnotation(testURI, doubleKey, doubleVal, 0, 0);
- annosvc.getPageAnnotationInfo(testURI, doubleKey, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- storedVal = annosvc.getPageAnnotation(testURI, doubleKey);
- do_check_true(doubleVal === storedVal);
- annosvc.setItemAnnotation(testItemId, doubleKey, doubleVal, 0, 0);
- do_check_true(annosvc.itemHasAnnotation(testItemId, doubleKey));
- annosvc.getItemAnnotationInfo(testItemId, doubleKey, flags, exp, storageType);
- do_check_eq(flags.value, 0);
- do_check_eq(exp.value, 0);
- do_check_eq(storageType.value, Ci.nsIAnnotationService.TYPE_DOUBLE);
- storedVal = annosvc.getItemAnnotation(testItemId, doubleKey);
- do_check_true(doubleVal === storedVal);
-
- // test annotation removal
- annosvc.removePageAnnotation(testURI, int32Key);
-
- annosvc.setItemAnnotation(testItemId, testAnnoName, testAnnoVal, 0, 0);
- // verify that removing an annotation updates the last modified date
- var lastModified3 = bmsvc.getItemLastModified(testItemId);
- // Workaround possible VM timers issues moving last modified to the past.
- bmsvc.setItemLastModified(testItemId, --lastModified3);
- annosvc.removeItemAnnotation(testItemId, int32Key);
- var lastModified4 = bmsvc.getItemLastModified(testItemId);
- do_print("verify that removing an annotation updates the last modified date");
- do_print("lastModified3 = " + lastModified3);
- do_print("lastModified4 = " + lastModified4);
- do_check_true(lastModified4 > lastModified3);
-
- do_check_eq(annoObserver.PAGE_lastRemoved_URI, testURI.spec);
- do_check_eq(annoObserver.PAGE_lastRemoved_AnnoName, int32Key);
- do_check_eq(annoObserver.ITEM_lastRemoved_Id, testItemId);
- do_check_eq(annoObserver.ITEM_lastRemoved_AnnoName, int32Key);
-
- // test that getItems/PagesWithAnnotation returns an empty array after
- // removing all items/pages which had the annotation set, see bug 380317.
- do_check_eq(annosvc.getItemsWithAnnotation(int32Key).length, 0);
- do_check_eq(annosvc.getPagesWithAnnotation(int32Key).length, 0);
-
- // Setting item annotations on invalid item ids should throw
- var invalidIds = [-1, 0, 37643];
- for (var id of invalidIds) {
- try {
- annosvc.setItemAnnotation(id, "foo", "bar", 0, 0);
- do_throw("setItemAnnotation* should throw for invalid item id: " + id)
- }
- catch (ex) { }
- }
-
- // setting an annotation with EXPIRE_HISTORY for an item should throw
- itemId = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, testURI, -1, "");
- try {
- annosvc.setItemAnnotation(itemId, "foo", "bar", 0, annosvc.EXPIRE_WITH_HISTORY);
- do_throw("setting an item annotation with EXPIRE_HISTORY should throw");
- }
- catch (ex) {
- }
-
- annosvc.removeObserver(annoObserver);
-});
-
-add_test(function test_getAnnotationsHavingName() {
- let uri = NetUtil.newURI("http://cat.mozilla.org");
- let id = PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX, "cat");
- let fid = PlacesUtils.bookmarks.createFolder(
- PlacesUtils.unfiledBookmarksFolderId, "pillow",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
-
- const ANNOS = {
- "int": 7,
- "double": 7.7,
- "string": "seven"
- };
- for (let name in ANNOS) {
- PlacesUtils.annotations.setPageAnnotation(
- uri, name, ANNOS[name], 0,
- PlacesUtils.annotations.EXPIRE_SESSION);
- PlacesUtils.annotations.setItemAnnotation(
- id, name, ANNOS[name], 0,
- PlacesUtils.annotations.EXPIRE_SESSION);
- PlacesUtils.annotations.setItemAnnotation(
- fid, name, ANNOS[name], 0,
- PlacesUtils.annotations.EXPIRE_SESSION);
- }
-
- for (let name in ANNOS) {
- let results = PlacesUtils.annotations.getAnnotationsWithName(name);
- do_check_eq(results.length, 3);
-
- for (let result of results) {
- do_check_eq(result.annotationName, name);
- do_check_eq(result.annotationValue, ANNOS[name]);
- if (result.uri)
- do_check_true(result.uri.equals(uri));
- else
- do_check_true(result.itemId > 0);
-
- if (result.itemId != -1) {
- if (result.uri)
- do_check_eq(result.itemId, id);
- else
- do_check_eq(result.itemId, fid);
- do_check_guid_for_bookmark(result.itemId, result.guid);
- }
- else {
- do_check_guid_for_uri(result.uri, result.guid);
- }
- }
- }
-
- run_next_test();
-});
diff --git a/toolkit/components/places/tests/unit/test_asyncExecuteLegacyQueries.js b/toolkit/components/places/tests/unit/test_asyncExecuteLegacyQueries.js
deleted file mode 100644
index 7296fe061..000000000
--- a/toolkit/components/places/tests/unit/test_asyncExecuteLegacyQueries.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-// This is a test for asyncExecuteLegacyQueries API.
-
-var tests = [
-
-function test_history_query() {
- let uri = NetUtil.newURI("http://test.visit.mozilla.com/");
- let title = "Test visit";
- PlacesTestUtils.addVisits({ uri: uri, title: title }).then(function () {
- let options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING;
- let query = PlacesUtils.history.getNewQuery();
-
- PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .asyncExecuteLegacyQueries([query], 1, options, {
- handleResult: function (aResultSet) {
- for (let row; (row = aResultSet.getNextRow());) {
- try {
- do_check_eq(row.getResultByIndex(1), uri.spec);
- do_check_eq(row.getResultByIndex(2), title);
- } catch (e) {
- do_throw("Error while fetching page data.");
- }
- }
- },
- handleError: function (aError) {
- do_throw("Async execution error (" + aError.result + "): " + aError.message);
- },
- handleCompletion: function (aReason) {
- run_next_test();
- },
- });
- });
-},
-
-function test_bookmarks_query() {
- let uri = NetUtil.newURI("http://test.bookmark.mozilla.com/");
- let title = "Test bookmark";
- bookmark(uri, title);
- let options = PlacesUtils.history.getNewQueryOptions();
- options.sortingMode = Ci.nsINavHistoryQueryOptions.SORT_BY_LASMODIFIED_DESCENDING;
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- let query = PlacesUtils.history.getNewQuery();
-
- PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
- .asyncExecuteLegacyQueries([query], 1, options, {
- handleResult: function (aResultSet) {
- for (let row; (row = aResultSet.getNextRow());) {
- try {
- do_check_eq(row.getResultByIndex(1), uri.spec);
- do_check_eq(row.getResultByIndex(2), title);
- } catch (e) {
- do_throw("Error while fetching page data.");
- }
- }
- },
- handleError: function (aError) {
- do_throw("Async execution error (" + aError.result + "): " + aError.message);
- },
- handleCompletion: function (aReason) {
- run_next_test();
- },
- });
-},
-
-];
-
-function bookmark(aURI, aTitle)
-{
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- aURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- aTitle);
-}
-
-function run_test()
-{
- do_test_pending();
- run_next_test();
-}
-
-function run_next_test() {
- if (tests.length == 0) {
- do_test_finished();
- return;
- }
-
- Promise.all([
- PlacesTestUtils.clearHistory(),
- PlacesUtils.bookmarks.eraseEverything()
- ]).then(tests.shift());
-}
diff --git a/toolkit/components/places/tests/unit/test_async_history_api.js b/toolkit/components/places/tests/unit/test_async_history_api.js
deleted file mode 100644
index a012fcda2..000000000
--- a/toolkit/components/places/tests/unit/test_async_history_api.js
+++ /dev/null
@@ -1,1118 +0,0 @@
-/**
- * This file tests the async history API exposed by mozIAsyncHistory.
- */
-
-// Globals
-
-const TEST_DOMAIN = "http://mozilla.org/";
-const URI_VISIT_SAVED = "uri-visit-saved";
-const RECENT_EVENT_THRESHOLD = 15 * 60 * 1000000;
-
-// Helpers
-/**
- * Object that represents a mozIVisitInfo object.
- *
- * @param [optional] aTransitionType
- * The transition type of the visit. Defaults to TRANSITION_LINK if not
- * provided.
- * @param [optional] aVisitTime
- * The time of the visit. Defaults to now if not provided.
- */
-function VisitInfo(aTransitionType,
- aVisitTime) {
- this.transitionType =
- aTransitionType === undefined ? TRANSITION_LINK : aTransitionType;
- this.visitDate = aVisitTime || Date.now() * 1000;
-}
-
-function promiseUpdatePlaces(aPlaces) {
- return new Promise((resolve, reject) => {
- PlacesUtils.asyncHistory.updatePlaces(aPlaces, {
- _errors: [],
- _results: [],
- handleError(aResultCode, aPlace) {
- this._errors.push({ resultCode: aResultCode, info: aPlace});
- },
- handleResult(aPlace) {
- this._results.push(aPlace);
- },
- handleCompletion() {
- resolve({ errors: this._errors, results: this._results });
- }
- });
- });
-}
-
-/**
- * Listens for a title change notification, and calls aCallback when it gets it.
- *
- * @param aURI
- * The URI of the page we expect a notification for.
- * @param aExpectedTitle
- * The expected title of the URI we expect a notification for.
- * @param aCallback
- * The method to call when we have gotten the proper notification about
- * the title changing.
- */
-function TitleChangedObserver(aURI,
- aExpectedTitle,
- aCallback) {
- this.uri = aURI;
- this.expectedTitle = aExpectedTitle;
- this.callback = aCallback;
-}
-TitleChangedObserver.prototype = {
- __proto__: NavHistoryObserver.prototype,
- onTitleChanged(aURI, aTitle, aGUID) {
- do_print("onTitleChanged(" + aURI.spec + ", " + aTitle + ", " + aGUID + ")");
- if (!this.uri.equals(aURI)) {
- return;
- }
- do_check_eq(aTitle, this.expectedTitle);
- do_check_guid_for_uri(aURI, aGUID);
- this.callback();
- },
-};
-
-/**
- * Listens for a visit notification, and calls aCallback when it gets it.
- *
- * @param aURI
- * The URI of the page we expect a notification for.
- * @param aCallback
- * The method to call when we have gotten the proper notification about
- * being visited.
- */
-function VisitObserver(aURI,
- aGUID,
- aCallback)
-{
- this.uri = aURI;
- this.guid = aGUID;
- this.callback = aCallback;
-}
-VisitObserver.prototype = {
- __proto__: NavHistoryObserver.prototype,
- onVisit: function(aURI,
- aVisitId,
- aTime,
- aSessionId,
- aReferringId,
- aTransitionType,
- aGUID)
- {
- do_print("onVisit(" + aURI.spec + ", " + aVisitId + ", " + aTime +
- ", " + aSessionId + ", " + aReferringId + ", " +
- aTransitionType + ", " + aGUID + ")");
- if (!this.uri.equals(aURI) || this.guid != aGUID) {
- return;
- }
- this.callback(aTime, aTransitionType);
- },
-};
-
-/**
- * Tests that a title was set properly in the database.
- *
- * @param aURI
- * The uri to check.
- * @param aTitle
- * The expected title in the database.
- */
-function do_check_title_for_uri(aURI,
- aTitle)
-{
- let stack = Components.stack.caller;
- let stmt = DBConn().createStatement(
- `SELECT title
- FROM moz_places
- WHERE url_hash = hash(:url) AND url = :url`
- );
- stmt.params.url = aURI.spec;
- do_check_true(stmt.executeStep(), stack);
- do_check_eq(stmt.row.title, aTitle, stack);
- stmt.finalize();
-}
-
-// Test Functions
-
-add_task(function* test_interface_exists() {
- let history = Cc["@mozilla.org/browser/history;1"].getService(Ci.nsISupports);
- do_check_true(history instanceof Ci.mozIAsyncHistory);
-});
-
-add_task(function* test_invalid_uri_throws() {
- // First, test passing in nothing.
- let place = {
- visits: [
- new VisitInfo(),
- ],
- };
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
-
- // Now, test other bogus things.
- const TEST_VALUES = [
- null,
- undefined,
- {},
- [],
- TEST_DOMAIN + "test_invalid_id_throws",
- ];
- for (let i = 0; i < TEST_VALUES.length; i++) {
- place.uri = TEST_VALUES[i];
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
- }
-});
-
-add_task(function* test_invalid_places_throws() {
- // First, test passing in nothing.
- try {
- PlacesUtils.asyncHistory.updatePlaces();
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS);
- }
-
- // Now, test other bogus things.
- const TEST_VALUES = [
- null,
- undefined,
- {},
- [],
- "",
- ];
- for (let i = 0; i < TEST_VALUES.length; i++) {
- let value = TEST_VALUES[i];
- try {
- yield promiseUpdatePlaces(value);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
- }
-});
-
-add_task(function* test_invalid_guid_throws() {
- // First check invalid length guid.
- let place = {
- guid: "BAD_GUID",
- uri: NetUtil.newURI(TEST_DOMAIN + "test_invalid_guid_throws"),
- visits: [
- new VisitInfo(),
- ],
- };
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
-
- // Now check invalid character guid.
- place.guid = "__BADGUID+__";
- do_check_eq(place.guid.length, 12);
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_no_visits_throws() {
- const TEST_URI =
- NetUtil.newURI(TEST_DOMAIN + "test_no_id_or_guid_no_visits_throws");
- const TEST_GUID = "_RANDOMGUID_";
-
- let log_test_conditions = function(aPlace) {
- let str = "Testing place with " +
- (aPlace.uri ? "uri" : "no uri") + ", " +
- (aPlace.guid ? "guid" : "no guid") + ", " +
- (aPlace.visits ? "visits array" : "no visits array");
- do_print(str);
- };
-
- // Loop through every possible case. Note that we don't actually care about
- // the case where we have no uri, place id, or guid (covered by another test),
- // but it is easier to just make sure it too throws than to exclude it.
- let place = { };
- for (let uri = 1; uri >= 0; uri--) {
- place.uri = uri ? TEST_URI : undefined;
-
- for (let guid = 1; guid >= 0; guid--) {
- place.guid = guid ? TEST_GUID : undefined;
-
- for (let visits = 1; visits >= 0; visits--) {
- place.visits = visits ? [] : undefined;
-
- log_test_conditions(place);
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
- }
- }
- }
-});
-
-add_task(function* test_add_visit_no_date_throws() {
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_add_visit_no_date_throws"),
- visits: [
- new VisitInfo(),
- ],
- };
- delete place.visits[0].visitDate;
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_add_visit_no_transitionType_throws() {
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_add_visit_no_transitionType_throws"),
- visits: [
- new VisitInfo(),
- ],
- };
- delete place.visits[0].transitionType;
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_add_visit_invalid_transitionType_throws() {
- // First, test something that has a transition type lower than the first one.
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN +
- "test_add_visit_invalid_transitionType_throws"),
- visits: [
- new VisitInfo(TRANSITION_LINK - 1),
- ],
- };
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
-
- // Now, test something that has a transition type greater than the last one.
- place.visits[0] = new VisitInfo(TRANSITION_RELOAD + 1);
- try {
- yield promiseUpdatePlaces(place);
- do_throw("Should have thrown!");
- }
- catch (e) {
- do_check_eq(e.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_non_addable_uri_errors() {
- // Array of protocols that nsINavHistoryService::canAddURI returns false for.
- const URLS = [
- "about:config",
- "imap://cyrus.andrew.cmu.edu/archive.imap",
- "news://new.mozilla.org/mozilla.dev.apps.firefox",
- "mailbox:Inbox",
- "moz-anno:favicon:http://mozilla.org/made-up-favicon",
- "view-source:http://mozilla.org",
- "chrome://browser/content/browser.xul",
- "resource://gre-resources/hiddenWindow.html",
- "data:,Hello%2C%20World!",
- "wyciwyg:/0/http://mozilla.org",
- "javascript:alert('hello wolrd!');",
- "blob:foo",
- ];
- let places = [];
- URLS.forEach(function(url) {
- try {
- let place = {
- uri: NetUtil.newURI(url),
- title: "test for " + url,
- visits: [
- new VisitInfo(),
- ],
- };
- places.push(place);
- }
- catch (e) {
- if (e.result != Cr.NS_ERROR_FAILURE) {
- throw e;
- }
- // NetUtil.newURI() can throw if e.g. our app knows about imap://
- // but the account is not set up and so the URL is invalid for us.
- // Note this in the log but ignore as it's not the subject of this test.
- do_print("Could not construct URI for '" + url + "'; ignoring");
- }
- });
-
- let placesResult = yield promiseUpdatePlaces(places);
- if (placesResult.results.length > 0) {
- do_throw("Unexpected success.");
- }
- for (let place of placesResult.errors) {
- do_print("Checking '" + place.info.uri.spec + "'");
- do_check_eq(place.resultCode, Cr.NS_ERROR_INVALID_ARG);
- do_check_false(yield promiseIsURIVisited(place.info.uri));
- }
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_duplicate_guid_errors() {
- // This test ensures that trying to add a visit, with a guid already found in
- // another visit, fails.
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_duplicate_guid_fails_first"),
- visits: [
- new VisitInfo(),
- ],
- };
-
- do_check_false(yield promiseIsURIVisited(place.uri));
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- let placeInfo = placesResult.results[0];
- do_check_true(yield promiseIsURIVisited(placeInfo.uri));
-
- let badPlace = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_duplicate_guid_fails_second"),
- visits: [
- new VisitInfo(),
- ],
- guid: placeInfo.guid,
- };
-
- do_check_false(yield promiseIsURIVisited(badPlace.uri));
- placesResult = yield promiseUpdatePlaces(badPlace);
- if (placesResult.results.length > 0) {
- do_throw("Unexpected success.");
- }
- let badPlaceInfo = placesResult.errors[0];
- do_check_eq(badPlaceInfo.resultCode, Cr.NS_ERROR_STORAGE_CONSTRAINT);
- do_check_false(yield promiseIsURIVisited(badPlaceInfo.info.uri));
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_invalid_referrerURI_ignored() {
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN +
- "test_invalid_referrerURI_ignored"),
- visits: [
- new VisitInfo(),
- ],
- };
- place.visits[0].referrerURI = NetUtil.newURI(place.uri.spec + "_unvisistedURI");
- do_check_false(yield promiseIsURIVisited(place.uri));
- do_check_false(yield promiseIsURIVisited(place.visits[0].referrerURI));
-
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- let placeInfo = placesResult.results[0];
- do_check_true(yield promiseIsURIVisited(placeInfo.uri));
-
- // Check to make sure we do not visit the invalid referrer.
- do_check_false(yield promiseIsURIVisited(place.visits[0].referrerURI));
-
- // Check to make sure from_visit is zero in database.
- let stmt = DBConn().createStatement(
- `SELECT from_visit
- FROM moz_historyvisits
- WHERE id = :visit_id`
- );
- stmt.params.visit_id = placeInfo.visits[0].visitId;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.from_visit, 0);
- stmt.finalize();
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_nonnsIURI_referrerURI_ignored() {
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN +
- "test_nonnsIURI_referrerURI_ignored"),
- visits: [
- new VisitInfo(),
- ],
- };
- place.visits[0].referrerURI = place.uri.spec + "_nonnsIURI";
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- let placeInfo = placesResult.results[0];
- do_check_true(yield promiseIsURIVisited(placeInfo.uri));
-
- // Check to make sure from_visit is zero in database.
- let stmt = DBConn().createStatement(
- `SELECT from_visit
- FROM moz_historyvisits
- WHERE id = :visit_id`
- );
- stmt.params.visit_id = placeInfo.visits[0].visitId;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.from_visit, 0);
- stmt.finalize();
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_old_referrer_ignored() {
- // This tests that a referrer for a visit which is not recent (specifically,
- // older than 15 minutes as per RECENT_EVENT_THRESHOLD) is not saved by
- // updatePlaces.
- let oldTime = (Date.now() * 1000) - (RECENT_EVENT_THRESHOLD + 1);
- let referrerPlace = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_old_referrer_ignored_referrer"),
- visits: [
- new VisitInfo(TRANSITION_LINK, oldTime),
- ],
- };
-
- // First we must add our referrer to the history so that it is not ignored
- // as being invalid.
- do_check_false(yield promiseIsURIVisited(referrerPlace.uri));
- let placesResult = yield promiseUpdatePlaces(referrerPlace);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
-
- // Now that the referrer is added, we can add a page with a valid
- // referrer to determine if the recency of the referrer is taken into
- // account.
- do_check_true(yield promiseIsURIVisited(referrerPlace.uri));
-
- let visitInfo = new VisitInfo();
- visitInfo.referrerURI = referrerPlace.uri;
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_old_referrer_ignored_page"),
- visits: [
- visitInfo,
- ],
- };
-
- do_check_false(yield promiseIsURIVisited(place.uri));
- placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- let placeInfo = placesResult.results[0];
- do_check_true(yield promiseIsURIVisited(place.uri));
-
- // Though the visit will not contain the referrer, we must examine the
- // database to be sure.
- do_check_eq(placeInfo.visits[0].referrerURI, null);
- let stmt = DBConn().createStatement(
- `SELECT COUNT(1) AS count
- FROM moz_historyvisits
- JOIN moz_places h ON h.id = place_id
- WHERE url_hash = hash(:page_url) AND url = :page_url
- AND from_visit = 0`
- );
- stmt.params.page_url = place.uri.spec;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.count, 1);
- stmt.finalize();
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_place_id_ignored() {
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_place_id_ignored_first"),
- visits: [
- new VisitInfo(),
- ],
- };
-
- do_check_false(yield promiseIsURIVisited(place.uri));
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- let placeInfo = placesResult.results[0];
- do_check_true(yield promiseIsURIVisited(place.uri));
-
- let placeId = placeInfo.placeId;
- do_check_neq(placeId, 0);
-
- let badPlace = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_place_id_ignored_second"),
- visits: [
- new VisitInfo(),
- ],
- placeId: placeId,
- };
-
- do_check_false(yield promiseIsURIVisited(badPlace.uri));
- placesResult = yield promiseUpdatePlaces(badPlace);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- placeInfo = placesResult.results[0];
-
- do_check_neq(placeInfo.placeId, placeId);
- do_check_true(yield promiseIsURIVisited(badPlace.uri));
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_handleCompletion_called_when_complete() {
- // We test a normal visit, and embeded visit, and a uri that would fail
- // the canAddURI test to make sure that the notification happens after *all*
- // of them have had a callback.
- let places = [
- { uri: NetUtil.newURI(TEST_DOMAIN +
- "test_handleCompletion_called_when_complete"),
- visits: [
- new VisitInfo(),
- new VisitInfo(TRANSITION_EMBED),
- ],
- },
- { uri: NetUtil.newURI("data:,Hello%2C%20World!"),
- visits: [
- new VisitInfo(),
- ],
- },
- ];
- do_check_false(yield promiseIsURIVisited(places[0].uri));
- do_check_false(yield promiseIsURIVisited(places[1].uri));
-
- const EXPECTED_COUNT_SUCCESS = 2;
- const EXPECTED_COUNT_FAILURE = 1;
-
- let {results, errors} = yield promiseUpdatePlaces(places);
-
- do_check_eq(results.length, EXPECTED_COUNT_SUCCESS);
- do_check_eq(errors.length, EXPECTED_COUNT_FAILURE);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_add_visit() {
- const VISIT_TIME = Date.now() * 1000;
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_add_visit"),
- title: "test_add_visit title",
- visits: [],
- };
- for (let t in PlacesUtils.history.TRANSITIONS) {
- let transitionType = PlacesUtils.history.TRANSITIONS[t];
- place.visits.push(new VisitInfo(transitionType, VISIT_TIME));
- }
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- let callbackCount = 0;
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- for (let placeInfo of placesResult.results) {
- do_check_true(yield promiseIsURIVisited(place.uri));
-
- // Check mozIPlaceInfo properties.
- do_check_true(place.uri.equals(placeInfo.uri));
- do_check_eq(placeInfo.frecency, -1); // We don't pass frecency here!
- do_check_eq(placeInfo.title, place.title);
-
- // Check mozIVisitInfo properties.
- let visits = placeInfo.visits;
- do_check_eq(visits.length, 1);
- let visit = visits[0];
- do_check_eq(visit.visitDate, VISIT_TIME);
- do_check_true(Object.values(PlacesUtils.history.TRANSITIONS).includes(visit.transitionType));
- do_check_true(visit.referrerURI === null);
-
- // For TRANSITION_EMBED visits, many properties will always be zero or
- // undefined.
- if (visit.transitionType == TRANSITION_EMBED) {
- // Check mozIPlaceInfo properties.
- do_check_eq(placeInfo.placeId, 0, '//');
- do_check_eq(placeInfo.guid, null);
-
- // Check mozIVisitInfo properties.
- do_check_eq(visit.visitId, 0);
- }
- // But they should be valid for non-embed visits.
- else {
- // Check mozIPlaceInfo properties.
- do_check_true(placeInfo.placeId > 0);
- do_check_valid_places_guid(placeInfo.guid);
-
- // Check mozIVisitInfo properties.
- do_check_true(visit.visitId > 0);
- }
-
- // If we have had all of our callbacks, continue running tests.
- if (++callbackCount == place.visits.length) {
- yield PlacesTestUtils.promiseAsyncUpdates();
- }
- }
-});
-
-add_task(function* test_properties_saved() {
- // Check each transition type to make sure it is saved properly.
- let places = [];
- for (let t in PlacesUtils.history.TRANSITIONS) {
- let transitionType = PlacesUtils.history.TRANSITIONS[t];
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_properties_saved/" +
- transitionType),
- title: "test_properties_saved test",
- visits: [
- new VisitInfo(transitionType),
- ],
- };
- do_check_false(yield promiseIsURIVisited(place.uri));
- places.push(place);
- }
-
- let callbackCount = 0;
- let placesResult = yield promiseUpdatePlaces(places);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- for (let placeInfo of placesResult.results) {
- let uri = placeInfo.uri;
- do_check_true(yield promiseIsURIVisited(uri));
- let visit = placeInfo.visits[0];
- print("TEST-INFO | test_properties_saved | updatePlaces callback for " +
- "transition type " + visit.transitionType);
-
- // Note that TRANSITION_EMBED should not be in the database.
- const EXPECTED_COUNT = visit.transitionType == TRANSITION_EMBED ? 0 : 1;
-
- // mozIVisitInfo::date
- let stmt = DBConn().createStatement(
- `SELECT COUNT(1) AS count
- FROM moz_places h
- JOIN moz_historyvisits v
- ON h.id = v.place_id
- WHERE h.url_hash = hash(:page_url) AND h.url = :page_url
- AND v.visit_date = :visit_date`
- );
- stmt.params.page_url = uri.spec;
- stmt.params.visit_date = visit.visitDate;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.count, EXPECTED_COUNT);
- stmt.finalize();
-
- // mozIVisitInfo::transitionType
- stmt = DBConn().createStatement(
- `SELECT COUNT(1) AS count
- FROM moz_places h
- JOIN moz_historyvisits v
- ON h.id = v.place_id
- WHERE h.url_hash = hash(:page_url) AND h.url = :page_url
- AND v.visit_type = :transition_type`
- );
- stmt.params.page_url = uri.spec;
- stmt.params.transition_type = visit.transitionType;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.count, EXPECTED_COUNT);
- stmt.finalize();
-
- // mozIPlaceInfo::title
- stmt = DBConn().createStatement(
- `SELECT COUNT(1) AS count
- FROM moz_places h
- WHERE h.url_hash = hash(:page_url) AND h.url = :page_url
- AND h.title = :title`
- );
- stmt.params.page_url = uri.spec;
- stmt.params.title = placeInfo.title;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.count, EXPECTED_COUNT);
- stmt.finalize();
-
- // If we have had all of our callbacks, continue running tests.
- if (++callbackCount == places.length) {
- yield PlacesTestUtils.promiseAsyncUpdates();
- }
- }
-});
-
-add_task(function* test_guid_saved() {
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_guid_saved"),
- guid: "__TESTGUID__",
- visits: [
- new VisitInfo(),
- ],
- };
- do_check_valid_places_guid(place.guid);
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- let placeInfo = placesResult.results[0];
- let uri = placeInfo.uri;
- do_check_true(yield promiseIsURIVisited(uri));
- do_check_eq(placeInfo.guid, place.guid);
- do_check_guid_for_uri(uri, place.guid);
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_referrer_saved() {
- let places = [
- { uri: NetUtil.newURI(TEST_DOMAIN + "test_referrer_saved/referrer"),
- visits: [
- new VisitInfo(),
- ],
- },
- { uri: NetUtil.newURI(TEST_DOMAIN + "test_referrer_saved/test"),
- visits: [
- new VisitInfo(),
- ],
- },
- ];
- places[1].visits[0].referrerURI = places[0].uri;
- do_check_false(yield promiseIsURIVisited(places[0].uri));
- do_check_false(yield promiseIsURIVisited(places[1].uri));
-
- let resultCount = 0;
- let placesResult = yield promiseUpdatePlaces(places);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- for (let placeInfo of placesResult.results) {
- let uri = placeInfo.uri;
- do_check_true(yield promiseIsURIVisited(uri));
- let visit = placeInfo.visits[0];
-
- // We need to insert all of our visits before we can test conditions.
- if (++resultCount == places.length) {
- do_check_true(places[0].uri.equals(visit.referrerURI));
-
- let stmt = DBConn().createStatement(
- `SELECT COUNT(1) AS count
- FROM moz_historyvisits
- JOIN moz_places h ON h.id = place_id
- WHERE url_hash = hash(:page_url) AND url = :page_url
- AND from_visit = (
- SELECT v.id
- FROM moz_historyvisits v
- JOIN moz_places h ON h.id = place_id
- WHERE url_hash = hash(:referrer) AND url = :referrer
- )`
- );
- stmt.params.page_url = uri.spec;
- stmt.params.referrer = visit.referrerURI.spec;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.count, 1);
- stmt.finalize();
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- }
- }
-});
-
-add_task(function* test_guid_change_saved() {
- // First, add a visit for it.
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_guid_change_saved"),
- visits: [
- new VisitInfo(),
- ],
- };
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- // Then, change the guid with visits.
- place.guid = "_GUIDCHANGE_";
- place.visits = [new VisitInfo()];
- placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- do_check_guid_for_uri(place.uri, place.guid);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_title_change_saved() {
- // First, add a visit for it.
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_title_change_saved"),
- title: "original title",
- visits: [
- new VisitInfo(),
- ],
- };
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
-
- // Now, make sure the empty string clears the title.
- place.title = "";
- place.visits = [new VisitInfo()];
- placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- do_check_title_for_uri(place.uri, null);
-
- // Then, change the title with visits.
- place.title = "title change";
- place.visits = [new VisitInfo()];
- placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- do_check_title_for_uri(place.uri, place.title);
-
- // Lastly, check that the title is cleared if we set it to null.
- place.title = null;
- place.visits = [new VisitInfo()];
- placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- do_check_title_for_uri(place.uri, place.title);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_no_title_does_not_clear_title() {
- const TITLE = "test title";
- // First, add a visit for it.
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_no_title_does_not_clear_title"),
- title: TITLE,
- visits: [
- new VisitInfo(),
- ],
- };
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- // Now, make sure that not specifying a title does not clear it.
- delete place.title;
- place.visits = [new VisitInfo()];
- placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
- do_check_title_for_uri(place.uri, TITLE);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_title_change_notifies() {
- // There are three cases to test. The first case is to make sure we do not
- // get notified if we do not specify a title.
- let place = {
- uri: NetUtil.newURI(TEST_DOMAIN + "test_title_change_notifies"),
- visits: [
- new VisitInfo(),
- ],
- };
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- let silentObserver =
- new TitleChangedObserver(place.uri, "DO NOT WANT", function() {
- do_throw("unexpected callback!");
- });
-
- PlacesUtils.history.addObserver(silentObserver, false);
- let placesResult = yield promiseUpdatePlaces(place);
- if (placesResult.errors.length > 0) {
- do_throw("Unexpected error.");
- }
-
- // The second case to test is that we get the notification when we add
- // it for the first time. The first case will fail before our callback if it
- // is busted, so we can do this now.
- place.uri = NetUtil.newURI(place.uri.spec + "/new-visit-with-title");
- place.title = "title 1";
- function promiseTitleChangedObserver(aPlace) {
- return new Promise((resolve, reject) => {
- let callbackCount = 0;
- let observer = new TitleChangedObserver(aPlace.uri, aPlace.title, function() {
- switch (++callbackCount) {
- case 1:
- // The third case to test is to make sure we get a notification when
- // we change an existing place.
- observer.expectedTitle = place.title = "title 2";
- place.visits = [new VisitInfo()];
- PlacesUtils.asyncHistory.updatePlaces(place);
- break;
- case 2:
- PlacesUtils.history.removeObserver(silentObserver);
- PlacesUtils.history.removeObserver(observer);
- resolve();
- break;
- }
- });
-
- PlacesUtils.history.addObserver(observer, false);
- PlacesUtils.asyncHistory.updatePlaces(aPlace);
- });
- }
-
- yield promiseTitleChangedObserver(place);
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_visit_notifies() {
- // There are two observers we need to see for each visit. One is an
- // nsINavHistoryObserver and the other is the uri-visit-saved observer topic.
- let place = {
- guid: "abcdefghijkl",
- uri: NetUtil.newURI(TEST_DOMAIN + "test_visit_notifies"),
- visits: [
- new VisitInfo(),
- ],
- };
- do_check_false(yield promiseIsURIVisited(place.uri));
-
- function promiseVisitObserver(aPlace) {
- return new Promise((resolve, reject) => {
- let callbackCount = 0;
- let finisher = function() {
- if (++callbackCount == 2) {
- resolve();
- }
- }
- let visitObserver = new VisitObserver(place.uri, place.guid,
- function(aVisitDate,
- aTransitionType) {
- let visit = place.visits[0];
- do_check_eq(visit.visitDate, aVisitDate);
- do_check_eq(visit.transitionType, aTransitionType);
-
- PlacesUtils.history.removeObserver(visitObserver);
- finisher();
- });
- PlacesUtils.history.addObserver(visitObserver, false);
- let observer = function(aSubject, aTopic, aData) {
- do_print("observe(" + aSubject + ", " + aTopic + ", " + aData + ")");
- do_check_true(aSubject instanceof Ci.nsIURI);
- do_check_true(aSubject.equals(place.uri));
-
- Services.obs.removeObserver(observer, URI_VISIT_SAVED);
- finisher();
- };
- Services.obs.addObserver(observer, URI_VISIT_SAVED, false);
- PlacesUtils.asyncHistory.updatePlaces(place);
- });
- }
-
- yield promiseVisitObserver(place);
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-// test with empty mozIVisitInfoCallback object
-add_task(function* test_callbacks_not_supplied() {
- const URLS = [
- "imap://cyrus.andrew.cmu.edu/archive.imap", // bad URI
- "http://mozilla.org/" // valid URI
- ];
- let places = [];
- URLS.forEach(function(url) {
- try {
- let place = {
- uri: NetUtil.newURI(url),
- title: "test for " + url,
- visits: [
- new VisitInfo(),
- ],
- };
- places.push(place);
- }
- catch (e) {
- if (e.result != Cr.NS_ERROR_FAILURE) {
- throw e;
- }
- // NetUtil.newURI() can throw if e.g. our app knows about imap://
- // but the account is not set up and so the URL is invalid for us.
- // Note this in the log but ignore as it's not the subject of this test.
- do_print("Could not construct URI for '" + url + "'; ignoring");
- }
- });
-
- PlacesUtils.asyncHistory.updatePlaces(places, {});
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-// Test that we don't wrongly overwrite typed and hidden when adding new visits.
-add_task(function* test_typed_hidden_not_overwritten() {
- yield PlacesTestUtils.clearHistory();
- let places = [
- { uri: NetUtil.newURI("http://mozilla.org/"),
- title: "test",
- visits: [
- new VisitInfo(TRANSITION_TYPED),
- new VisitInfo(TRANSITION_LINK)
- ]
- },
- { uri: NetUtil.newURI("http://mozilla.org/"),
- title: "test",
- visits: [
- new VisitInfo(TRANSITION_FRAMED_LINK)
- ]
- },
- ];
- yield promiseUpdatePlaces(places);
-
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(
- "SELECT hidden, typed FROM moz_places WHERE url_hash = hash(:url) AND url = :url",
- { url: "http://mozilla.org/" });
- Assert.equal(rows[0].getResultByName("typed"), 1,
- "The page should be marked as typed");
- Assert.equal(rows[0].getResultByName("hidden"), 0,
- "The page should be marked as not hidden");
-});
-
-function run_test()
-{
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_async_in_batchmode.js b/toolkit/components/places/tests/unit/test_async_in_batchmode.js
deleted file mode 100644
index b39b26519..000000000
--- a/toolkit/components/places/tests/unit/test_async_in_batchmode.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// This is testing the frankenstein situation Sync forces Places into.
-// Sync does runInBatchMode() and before the callback returns the Places async
-// APIs are used (either by Sync itself, or by any other code in the system)
-// As seen in bug 1197856 and bug 1190131.
-
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-
-// This function "waits" for a promise to resolve by spinning a nested event
-// loop.
-function waitForPromise(promise) {
- let thread = Cc["@mozilla.org/thread-manager;1"].getService().currentThread;
-
- let finalResult, finalException;
-
- promise.then(result => {
- finalResult = result;
- }, err => {
- finalException = err;
- });
-
- // Keep waiting until our callback is triggered (unless the app is quitting).
- while (!finalResult && !finalException) {
- thread.processNextEvent(true);
- }
- if (finalException) {
- throw finalException;
- }
- return finalResult;
-}
-
-add_test(function() {
- let testCompleted = false;
- PlacesUtils.bookmarks.runInBatchMode({
- runBatched() {
- // create a bookmark.
- let info = { parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "http://example.com/" };
- let insertPromise = PlacesUtils.bookmarks.insert(info);
- let bookmark = waitForPromise(insertPromise);
- // Check we got a bookmark (bookmark creation failed completely in
- // bug 1190131)
- equal(bookmark.url, info.url);
- // Check the promiseItemGuid and promiseItemId helpers - failure in these
- // was the underlying reason for the failure.
- let id = waitForPromise(PlacesUtils.promiseItemId(bookmark.guid));
- let guid = waitForPromise(PlacesUtils.promiseItemGuid(id));
- equal(guid, bookmark.guid, "id and guid round-tripped correctly");
- testCompleted = true;
- }
- }, null);
- // make sure we tested what we think we tested.
- ok(testCompleted);
- run_next_test();
-});
diff --git a/toolkit/components/places/tests/unit/test_async_transactions.js b/toolkit/components/places/tests/unit/test_async_transactions.js
deleted file mode 100644
index edc9abf87..000000000
--- a/toolkit/components/places/tests/unit/test_async_transactions.js
+++ /dev/null
@@ -1,1739 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const bmsvc = PlacesUtils.bookmarks;
-const tagssvc = PlacesUtils.tagging;
-const annosvc = PlacesUtils.annotations;
-const PT = PlacesTransactions;
-const rootGuid = PlacesUtils.bookmarks.rootGuid;
-
-Components.utils.importGlobalProperties(["URL"]);
-
-// Create and add bookmarks observer.
-var observer = {
- __proto__: NavBookmarkObserver.prototype,
-
- tagRelatedGuids: new Set(),
-
- reset: function () {
- this.itemsAdded = new Map();
- this.itemsRemoved = new Map();
- this.itemsChanged = new Map();
- this.itemsMoved = new Map();
- this.beginUpdateBatch = false;
- this.endUpdateBatch = false;
- },
-
- onBeginUpdateBatch: function () {
- this.beginUpdateBatch = true;
- },
-
- onEndUpdateBatch: function () {
- this.endUpdateBatch = true;
- },
-
- onItemAdded:
- function (aItemId, aParentId, aIndex, aItemType, aURI, aTitle, aDateAdded,
- aGuid, aParentGuid) {
- // Ignore tag items.
- if (aParentId == PlacesUtils.tagsFolderId ||
- (aParentId != PlacesUtils.placesRootId &&
- bmsvc.getFolderIdForItem(aParentId) == PlacesUtils.tagsFolderId)) {
- this.tagRelatedGuids.add(aGuid);
- return;
- }
-
- this.itemsAdded.set(aGuid, { itemId: aItemId
- , parentGuid: aParentGuid
- , index: aIndex
- , itemType: aItemType
- , title: aTitle
- , url: aURI });
- },
-
- onItemRemoved:
- function (aItemId, aParentId, aIndex, aItemType, aURI, aGuid, aParentGuid) {
- if (this.tagRelatedGuids.has(aGuid))
- return;
-
- this.itemsRemoved.set(aGuid, { parentGuid: aParentGuid
- , index: aIndex
- , itemType: aItemType });
- },
-
- onItemChanged:
- function (aItemId, aProperty, aIsAnnoProperty, aNewValue, aLastModified,
- aItemType, aParentId, aGuid, aParentGuid) {
- if (this.tagRelatedGuids.has(aGuid))
- return;
-
- let changesForGuid = this.itemsChanged.get(aGuid);
- if (changesForGuid === undefined) {
- changesForGuid = new Map();
- this.itemsChanged.set(aGuid, changesForGuid);
- }
-
- let newValue = aNewValue;
- if (aIsAnnoProperty) {
- if (annosvc.itemHasAnnotation(aItemId, aProperty))
- newValue = annosvc.getItemAnnotation(aItemId, aProperty);
- else
- newValue = null;
- }
- let change = { isAnnoProperty: aIsAnnoProperty
- , newValue: newValue
- , lastModified: aLastModified
- , itemType: aItemType };
- changesForGuid.set(aProperty, change);
- },
-
- onItemVisited: () => {},
-
- onItemMoved:
- function (aItemId, aOldParent, aOldIndex, aNewParent, aNewIndex, aItemType,
- aGuid, aOldParentGuid, aNewParentGuid) {
- this.itemsMoved.set(aGuid, { oldParentGuid: aOldParentGuid
- , oldIndex: aOldIndex
- , newParentGuid: aNewParentGuid
- , newIndex: aNewIndex
- , itemType: aItemType });
- }
-};
-observer.reset();
-
-// index at which items should begin
-var bmStartIndex = 0;
-
-function run_test() {
- bmsvc.addObserver(observer, false);
- do_register_cleanup(function () {
- bmsvc.removeObserver(observer);
- });
-
- run_next_test();
-}
-
-function sanityCheckTransactionHistory() {
- do_check_true(PT.undoPosition <= PT.length);
-
- let check_entry_throws = f => {
- try {
- f();
- do_throw("PT.entry should throw for invalid input");
- } catch (ex) {}
- };
- check_entry_throws( () => PT.entry(-1) );
- check_entry_throws( () => PT.entry({}) );
- check_entry_throws( () => PT.entry(PT.length) );
-
- if (PT.undoPosition < PT.length)
- do_check_eq(PT.topUndoEntry, PT.entry(PT.undoPosition));
- else
- do_check_null(PT.topUndoEntry);
- if (PT.undoPosition > 0)
- do_check_eq(PT.topRedoEntry, PT.entry(PT.undoPosition - 1));
- else
- do_check_null(PT.topRedoEntry);
-}
-
-function getTransactionsHistoryState() {
- let history = [];
- for (let i = 0; i < PT.length; i++) {
- history.push(PT.entry(i));
- }
- return [history, PT.undoPosition];
-}
-
-function ensureUndoState(aExpectedEntries = [], aExpectedUndoPosition = 0) {
- // ensureUndoState is called in various places during this test, so it's
- // a good places to sanity-check the transaction-history APIs in all
- // cases.
- sanityCheckTransactionHistory();
-
- let [actualEntries, actualUndoPosition] = getTransactionsHistoryState();
- do_check_eq(actualEntries.length, aExpectedEntries.length);
- do_check_eq(actualUndoPosition, aExpectedUndoPosition);
-
- function checkEqualEntries(aExpectedEntry, aActualEntry) {
- do_check_eq(aExpectedEntry.length, aActualEntry.length);
- aExpectedEntry.forEach( (t, i) => do_check_eq(t, aActualEntry[i]) );
- }
- aExpectedEntries.forEach( (e, i) => checkEqualEntries(e, actualEntries[i]) );
-}
-
-function ensureItemsAdded(...items) {
- Assert.equal(observer.itemsAdded.size, items.length);
- for (let item of items) {
- Assert.ok(observer.itemsAdded.has(item.guid));
- let info = observer.itemsAdded.get(item.guid);
- Assert.equal(info.parentGuid, item.parentGuid);
- for (let propName of ["title", "index", "itemType"]) {
- if (propName in item)
- Assert.equal(info[propName], item[propName]);
- }
- if ("url" in item)
- Assert.ok(info.url.equals(item.url));
- }
-}
-
-function ensureItemsRemoved(...items) {
- Assert.equal(observer.itemsRemoved.size, items.length);
- for (let item of items) {
- // We accept both guids and full info object here.
- if (typeof(item) == "string") {
- Assert.ok(observer.itemsRemoved.has(item));
- }
- else {
- Assert.ok(observer.itemsRemoved.has(item.guid));
- let info = observer.itemsRemoved.get(item.guid);
- Assert.equal(info.parentGuid, item.parentGuid);
- if ("index" in item)
- Assert.equal(info.index, item.index);
- }
- }
-}
-
-function ensureItemsChanged(...items) {
- for (let item of items) {
- do_check_true(observer.itemsChanged.has(item.guid));
- let changes = observer.itemsChanged.get(item.guid);
- do_check_true(changes.has(item.property));
- let info = changes.get(item.property);
- do_check_eq(info.isAnnoProperty, Boolean(item.isAnnoProperty));
- do_check_eq(info.newValue, item.newValue);
- if ("url" in item)
- do_check_true(item.url.equals(info.url));
- }
-}
-
-function ensureAnnotationsSet(aGuid, aAnnos) {
- do_check_true(observer.itemsChanged.has(aGuid));
- let changes = observer.itemsChanged.get(aGuid);
- for (let anno of aAnnos) {
- do_check_true(changes.has(anno.name));
- let changeInfo = changes.get(anno.name);
- do_check_true(changeInfo.isAnnoProperty);
- do_check_eq(changeInfo.newValue, anno.value);
- }
-}
-
-function ensureItemsMoved(...items) {
- do_check_true(observer.itemsMoved.size, items.length);
- for (let item of items) {
- do_check_true(observer.itemsMoved.has(item.guid));
- let info = observer.itemsMoved.get(item.guid);
- do_check_eq(info.oldParentGuid, item.oldParentGuid);
- do_check_eq(info.oldIndex, item.oldIndex);
- do_check_eq(info.newParentGuid, item.newParentGuid);
- do_check_eq(info.newIndex, item.newIndex);
- }
-}
-
-function ensureTimestampsUpdated(aGuid, aCheckDateAdded = false) {
- do_check_true(observer.itemsChanged.has(aGuid));
- let changes = observer.itemsChanged.get(aGuid);
- if (aCheckDateAdded)
- do_check_true(changes.has("dateAdded"))
- do_check_true(changes.has("lastModified"));
-}
-
-function ensureTagsForURI(aURI, aTags) {
- let tagsSet = tagssvc.getTagsForURI(aURI);
- do_check_eq(tagsSet.length, aTags.length);
- do_check_true(aTags.every( t => tagsSet.includes(t)));
-}
-
-function createTestFolderInfo(aTitle = "Test Folder") {
- return { parentGuid: rootGuid, title: "Test Folder" };
-}
-
-function isLivemarkTree(aTree) {
- return !!aTree.annos &&
- aTree.annos.some( a => a.name == PlacesUtils.LMANNO_FEEDURI );
-}
-
-function* ensureLivemarkCreatedByAddLivemark(aLivemarkGuid) {
- // This throws otherwise.
- yield PlacesUtils.livemarks.getLivemark({ guid: aLivemarkGuid });
-}
-
-// Checks if two bookmark trees (as returned by promiseBookmarksTree) are the
-// same.
-// false value for aCheckParentAndPosition is ignored if aIsRestoredItem is set.
-function* ensureEqualBookmarksTrees(aOriginal,
- aNew,
- aIsRestoredItem = true,
- aCheckParentAndPosition = false) {
- // Note "id" is not-enumerable, and is therefore skipped by Object.keys (both
- // ours and the one at deepEqual). This is fine for us because ids are not
- // restored by Redo.
- if (aIsRestoredItem) {
- Assert.deepEqual(aOriginal, aNew);
- if (isLivemarkTree(aNew))
- yield ensureLivemarkCreatedByAddLivemark(aNew.guid);
- return;
- }
-
- for (let property of Object.keys(aOriginal)) {
- if (property == "children") {
- Assert.equal(aOriginal.children.length, aNew.children.length);
- for (let i = 0; i < aOriginal.children.length; i++) {
- yield ensureEqualBookmarksTrees(aOriginal.children[i],
- aNew.children[i],
- false,
- true);
- }
- }
- else if (property == "guid") {
- // guid shouldn't be copied if the item was not restored.
- Assert.notEqual(aOriginal.guid, aNew.guid);
- }
- else if (property == "dateAdded") {
- // dateAdded shouldn't be copied if the item was not restored.
- Assert.ok(is_time_ordered(aOriginal.dateAdded, aNew.dateAdded));
- }
- else if (property == "lastModified") {
- // same same, except for the never-changed case
- if (!aOriginal.lastModified)
- Assert.ok(!aNew.lastModified);
- else
- Assert.ok(is_time_ordered(aOriginal.lastModified, aNew.lastModified));
- }
- else if (aCheckParentAndPosition ||
- (property != "parentGuid" && property != "index")) {
- Assert.deepEqual(aOriginal[property], aNew[property]);
- }
- }
-
- if (isLivemarkTree(aNew))
- yield ensureLivemarkCreatedByAddLivemark(aNew.guid);
-}
-
-function* ensureBookmarksTreeRestoredCorrectly(...aOriginalBookmarksTrees) {
- for (let originalTree of aOriginalBookmarksTrees) {
- let restoredTree =
- yield PlacesUtils.promiseBookmarksTree(originalTree.guid);
- yield ensureEqualBookmarksTrees(originalTree, restoredTree);
- }
-}
-
-function* ensureNonExistent(...aGuids) {
- for (let guid of aGuids) {
- Assert.strictEqual((yield PlacesUtils.promiseBookmarksTree(guid)), null);
- }
-}
-
-add_task(function* test_recycled_transactions() {
- function* ensureTransactThrowsFor(aTransaction) {
- let [txns, undoPosition] = getTransactionsHistoryState();
- try {
- yield aTransaction.transact();
- do_throw("Shouldn't be able to use the same transaction twice");
- }
- catch (ex) { }
- ensureUndoState(txns, undoPosition);
- }
-
- let txn_a = PT.NewFolder(createTestFolderInfo());
- yield txn_a.transact();
- ensureUndoState([[txn_a]], 0);
- yield ensureTransactThrowsFor(txn_a);
-
- yield PT.undo();
- ensureUndoState([[txn_a]], 1);
- ensureTransactThrowsFor(txn_a);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
- ensureTransactThrowsFor(txn_a);
-
- let txn_b = PT.NewFolder(createTestFolderInfo());
- yield PT.batch(function* () {
- try {
- yield txn_a.transact();
- do_throw("Shouldn't be able to use the same transaction twice");
- }
- catch (ex) { }
- ensureUndoState();
- yield txn_b.transact();
- });
- ensureUndoState([[txn_b]], 0);
-
- yield PT.undo();
- ensureUndoState([[txn_b]], 1);
- ensureTransactThrowsFor(txn_a);
- ensureTransactThrowsFor(txn_b);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
- observer.reset();
-});
-
-add_task(function* test_new_folder_with_annotation() {
- const ANNO = { name: "TestAnno", value: "TestValue" };
- let folder_info = createTestFolderInfo();
- folder_info.index = bmStartIndex;
- folder_info.annotations = [ANNO];
- ensureUndoState();
- let txn = PT.NewFolder(folder_info);
- folder_info.guid = yield txn.transact();
- let ensureDo = function* (aRedo = false) {
- ensureUndoState([[txn]], 0);
- yield ensureItemsAdded(folder_info);
- ensureAnnotationsSet(folder_info.guid, [ANNO]);
- if (aRedo)
- ensureTimestampsUpdated(folder_info.guid, true);
- observer.reset();
- };
-
- let ensureUndo = () => {
- ensureUndoState([[txn]], 1);
- ensureItemsRemoved({ guid: folder_info.guid
- , parentGuid: folder_info.parentGuid
- , index: bmStartIndex });
- observer.reset();
- };
-
- yield ensureDo();
- yield PT.undo();
- yield ensureUndo();
- yield PT.redo();
- yield ensureDo(true);
- yield PT.undo();
- ensureUndo();
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_new_bookmark() {
- let bm_info = { parentGuid: rootGuid
- , url: NetUtil.newURI("http://test_create_item.com")
- , index: bmStartIndex
- , title: "Test creating an item" };
-
- ensureUndoState();
- let txn = PT.NewBookmark(bm_info);
- bm_info.guid = yield txn.transact();
-
- let ensureDo = function* (aRedo = false) {
- ensureUndoState([[txn]], 0);
- yield ensureItemsAdded(bm_info);
- if (aRedo)
- ensureTimestampsUpdated(bm_info.guid, true);
- observer.reset();
- };
- let ensureUndo = () => {
- ensureUndoState([[txn]], 1);
- ensureItemsRemoved({ guid: bm_info.guid
- , parentGuid: bm_info.parentGuid
- , index: bmStartIndex });
- observer.reset();
- };
-
- yield ensureDo();
- yield PT.undo();
- ensureUndo();
- yield PT.redo(true);
- yield ensureDo();
- yield PT.undo();
- ensureUndo();
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_merge_create_folder_and_item() {
- let folder_info = createTestFolderInfo();
- let bm_info = { url: NetUtil.newURI("http://test_create_item_to_folder.com")
- , title: "Test Bookmark"
- , index: bmStartIndex };
-
- let [folderTxnResult, bkmTxnResult] = yield PT.batch(function* () {
- let folderTxn = PT.NewFolder(folder_info);
- folder_info.guid = bm_info.parentGuid = yield folderTxn.transact();
- let bkmTxn = PT.NewBookmark(bm_info);
- bm_info.guid = yield bkmTxn.transact();
- return [folderTxn, bkmTxn];
- });
-
- let ensureDo = function* () {
- ensureUndoState([[bkmTxnResult, folderTxnResult]], 0);
- yield ensureItemsAdded(folder_info, bm_info);
- observer.reset();
- };
-
- let ensureUndo = () => {
- ensureUndoState([[bkmTxnResult, folderTxnResult]], 1);
- ensureItemsRemoved(folder_info, bm_info);
- observer.reset();
- };
-
- yield ensureDo();
- yield PT.undo();
- ensureUndo();
- yield PT.redo();
- yield ensureDo();
- yield PT.undo();
- ensureUndo();
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_move_items_to_folder() {
- let folder_a_info = createTestFolderInfo("Folder A");
- let bkm_a_info = { url: new URL("http://test_move_items.com")
- , title: "Bookmark A" };
- let bkm_b_info = { url: NetUtil.newURI("http://test_move_items.com")
- , title: "Bookmark B" };
-
- // Test moving items within the same folder.
- let [folder_a_txn_result, bkm_a_txn_result, bkm_b_txn_result] = yield PT.batch(function* () {
- let folder_a_txn = PT.NewFolder(folder_a_info);
-
- folder_a_info.guid = bkm_a_info.parentGuid = bkm_b_info.parentGuid =
- yield folder_a_txn.transact();
- let bkm_a_txn = PT.NewBookmark(bkm_a_info);
- bkm_a_info.guid = yield bkm_a_txn.transact();
- let bkm_b_txn = PT.NewBookmark(bkm_b_info);
- bkm_b_info.guid = yield bkm_b_txn.transact();
- return [folder_a_txn, bkm_a_txn, bkm_b_txn];
- });
-
- ensureUndoState([[bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 0);
-
- let moveTxn = PT.Move({ guid: bkm_a_info.guid
- , newParentGuid: folder_a_info.guid });
- yield moveTxn.transact();
-
- let ensureDo = () => {
- ensureUndoState([[moveTxn], [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 0);
- ensureItemsMoved({ guid: bkm_a_info.guid
- , oldParentGuid: folder_a_info.guid
- , newParentGuid: folder_a_info.guid
- , oldIndex: 0
- , newIndex: 1 });
- observer.reset();
- };
- let ensureUndo = () => {
- ensureUndoState([[moveTxn], [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 1);
- ensureItemsMoved({ guid: bkm_a_info.guid
- , oldParentGuid: folder_a_info.guid
- , newParentGuid: folder_a_info.guid
- , oldIndex: 1
- , newIndex: 0 });
- observer.reset();
- };
-
- ensureDo();
- yield PT.undo();
- ensureUndo();
- yield PT.redo();
- ensureDo();
- yield PT.undo();
- ensureUndo();
-
- yield PT.clearTransactionsHistory(false, true);
- ensureUndoState([[bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result]], 0);
-
- // Test moving items between folders.
- let folder_b_info = createTestFolderInfo("Folder B");
- let folder_b_txn = PT.NewFolder(folder_b_info);
- folder_b_info.guid = yield folder_b_txn.transact();
- ensureUndoState([ [folder_b_txn]
- , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 0);
-
- moveTxn = PT.Move({ guid: bkm_a_info.guid
- , newParentGuid: folder_b_info.guid
- , newIndex: bmsvc.DEFAULT_INDEX });
- yield moveTxn.transact();
-
- ensureDo = () => {
- ensureUndoState([ [moveTxn]
- , [folder_b_txn]
- , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 0);
- ensureItemsMoved({ guid: bkm_a_info.guid
- , oldParentGuid: folder_a_info.guid
- , newParentGuid: folder_b_info.guid
- , oldIndex: 0
- , newIndex: 0 });
- observer.reset();
- };
- ensureUndo = () => {
- ensureUndoState([ [moveTxn]
- , [folder_b_txn]
- , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 1);
- ensureItemsMoved({ guid: bkm_a_info.guid
- , oldParentGuid: folder_b_info.guid
- , newParentGuid: folder_a_info.guid
- , oldIndex: 0
- , newIndex: 0 });
- observer.reset();
- };
-
- ensureDo();
- yield PT.undo();
- ensureUndo();
- yield PT.redo();
- ensureDo();
- yield PT.undo();
- ensureUndo();
-
- // Clean up
- yield PT.undo(); // folder_b_txn
- yield PT.undo(); // folder_a_txn + the bookmarks;
- do_check_eq(observer.itemsRemoved.size, 4);
- ensureUndoState([ [moveTxn]
- , [folder_b_txn]
- , [bkm_b_txn_result, bkm_a_txn_result, folder_a_txn_result] ], 3);
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_remove_folder() {
- let folder_level_1_info = createTestFolderInfo("Folder Level 1");
- let folder_level_2_info = { title: "Folder Level 2" };
- let [folder_level_1_txn_result,
- folder_level_2_txn_result] = yield PT.batch(function* () {
- let folder_level_1_txn = PT.NewFolder(folder_level_1_info);
- folder_level_1_info.guid = yield folder_level_1_txn.transact();
- folder_level_2_info.parentGuid = folder_level_1_info.guid;
- let folder_level_2_txn = PT.NewFolder(folder_level_2_info);
- folder_level_2_info.guid = yield folder_level_2_txn.transact();
- return [folder_level_1_txn, folder_level_2_txn];
- });
-
- ensureUndoState([[folder_level_2_txn_result, folder_level_1_txn_result]]);
- yield ensureItemsAdded(folder_level_1_info, folder_level_2_info);
- observer.reset();
-
- let remove_folder_2_txn = PT.Remove(folder_level_2_info);
- yield remove_folder_2_txn.transact();
-
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ]);
- yield ensureItemsRemoved(folder_level_2_info);
-
- // Undo Remove "Folder Level 2"
- yield PT.undo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
- yield ensureItemsAdded(folder_level_2_info);
- ensureTimestampsUpdated(folder_level_2_info.guid, true);
- observer.reset();
-
- // Redo Remove "Folder Level 2"
- yield PT.redo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ]);
- yield ensureItemsRemoved(folder_level_2_info);
- observer.reset();
-
- // Undo it again
- yield PT.undo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
- yield ensureItemsAdded(folder_level_2_info);
- ensureTimestampsUpdated(folder_level_2_info.guid, true);
- observer.reset();
-
- // Undo the creation of both folders
- yield PT.undo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ], 2);
- yield ensureItemsRemoved(folder_level_2_info, folder_level_1_info);
- observer.reset();
-
- // Redo the creation of both folders
- yield PT.redo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
- yield ensureItemsAdded(folder_level_1_info, folder_level_2_info);
- ensureTimestampsUpdated(folder_level_1_info.guid, true);
- ensureTimestampsUpdated(folder_level_2_info.guid, true);
- observer.reset();
-
- // Redo Remove "Folder Level 2"
- yield PT.redo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ]);
- yield ensureItemsRemoved(folder_level_2_info);
- observer.reset();
-
- // Undo everything one last time
- yield PT.undo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ], 1);
- yield ensureItemsAdded(folder_level_2_info);
- observer.reset();
-
- yield PT.undo();
- ensureUndoState([ [remove_folder_2_txn]
- , [folder_level_2_txn_result, folder_level_1_txn_result] ], 2);
- yield ensureItemsRemoved(folder_level_2_info, folder_level_2_info);
- observer.reset();
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_add_and_remove_bookmarks_with_additional_info() {
- const testURI = NetUtil.newURI("http://add.remove.tag");
- const TAG_1 = "TestTag1";
- const TAG_2 = "TestTag2";
- const KEYWORD = "test_keyword";
- const POST_DATA = "post_data";
- const ANNO = { name: "TestAnno", value: "TestAnnoValue" };
-
- let folder_info = createTestFolderInfo();
- folder_info.guid = yield PT.NewFolder(folder_info).transact();
- let ensureTags = ensureTagsForURI.bind(null, testURI);
-
- // Check that the NewBookmark transaction preserves tags.
- observer.reset();
- let b1_info = { parentGuid: folder_info.guid, url: testURI, tags: [TAG_1] };
- b1_info.guid = yield PT.NewBookmark(b1_info).transact();
- ensureTags([TAG_1]);
- yield PT.undo();
- ensureTags([]);
-
- observer.reset();
- yield PT.redo();
- ensureTimestampsUpdated(b1_info.guid, true);
- ensureTags([TAG_1]);
-
- // Check if the Remove transaction removes and restores tags of children
- // correctly.
- yield PT.Remove(folder_info.guid).transact();
- ensureTags([]);
-
- observer.reset();
- yield PT.undo();
- ensureTimestampsUpdated(b1_info.guid, true);
- ensureTags([TAG_1]);
-
- yield PT.redo();
- ensureTags([]);
-
- observer.reset();
- yield PT.undo();
- ensureTimestampsUpdated(b1_info.guid, true);
- ensureTags([TAG_1]);
-
- // * Check that no-op tagging (the uri is already tagged with TAG_1) is
- // also a no-op on undo.
- // * Test the "keyword" property of the NewBookmark transaction.
- observer.reset();
- let b2_info = { parentGuid: folder_info.guid
- , url: testURI, tags: [TAG_1, TAG_2]
- , keyword: KEYWORD
- , postData: POST_DATA
- , annotations: [ANNO] };
- b2_info.guid = yield PT.NewBookmark(b2_info).transact();
- let b2_post_creation_changes = [
- { guid: b2_info.guid
- , isAnnoProperty: true
- , property: ANNO.name
- , newValue: ANNO.value },
- { guid: b2_info.guid
- , property: "keyword"
- , newValue: KEYWORD } ];
- ensureItemsChanged(...b2_post_creation_changes);
- ensureTags([TAG_1, TAG_2]);
-
- observer.reset();
- yield PT.undo();
- yield ensureItemsRemoved(b2_info);
- ensureTags([TAG_1]);
-
- // Check if Remove correctly restores keywords, tags and annotations.
- // Since both bookmarks share the same uri, they also share the keyword that
- // is not removed along with one of the bookmarks.
- observer.reset();
- yield PT.redo();
- ensureItemsChanged({ guid: b2_info.guid
- , isAnnoProperty: true
- , property: ANNO.name
- , newValue: ANNO.value });
- ensureTags([TAG_1, TAG_2]);
-
- // Test Remove for multiple items.
- observer.reset();
- yield PT.Remove(b1_info.guid).transact();
- yield PT.Remove(b2_info.guid).transact();
- yield PT.Remove(folder_info.guid).transact();
- yield ensureItemsRemoved(b1_info, b2_info, folder_info);
- ensureTags([]);
- // There is no keyword removal notification cause all bookmarks are removed
- // before the keyword itself, so there's no one to notify.
- let entry = yield PlacesUtils.keywords.fetch(KEYWORD);
- Assert.equal(entry, null, "keyword has been removed");
-
- observer.reset();
- yield PT.undo();
- yield ensureItemsAdded(folder_info);
- ensureTags([]);
-
- observer.reset();
- yield PT.undo();
- ensureItemsChanged(...b2_post_creation_changes);
- ensureTags([TAG_1, TAG_2]);
-
- observer.reset();
- yield PT.undo();
- yield ensureItemsAdded(b1_info);
- ensureTags([TAG_1, TAG_2]);
-
- // The redo calls below cleanup everything we did.
- observer.reset();
- yield PT.redo();
- yield ensureItemsRemoved(b1_info);
- ensureTags([TAG_1, TAG_2]);
-
- observer.reset();
- yield PT.redo();
- yield ensureItemsRemoved(b2_info);
- ensureTags([]);
-
- observer.reset();
- yield PT.redo();
- yield ensureItemsRemoved(folder_info);
- ensureTags([]);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_creating_and_removing_a_separator() {
- let folder_info = createTestFolderInfo();
- let separator_info = {};
- let undoEntries = [];
-
- observer.reset();
- let create_txns = yield PT.batch(function* () {
- let folder_txn = PT.NewFolder(folder_info);
- folder_info.guid = separator_info.parentGuid = yield folder_txn.transact();
- let separator_txn = PT.NewSeparator(separator_info);
- separator_info.guid = yield separator_txn.transact();
- return [separator_txn, folder_txn];
- });
- undoEntries.unshift(create_txns);
- ensureUndoState(undoEntries, 0);
- ensureItemsAdded(folder_info, separator_info);
-
- observer.reset();
- yield PT.undo();
- ensureUndoState(undoEntries, 1);
- ensureItemsRemoved(folder_info, separator_info);
-
- observer.reset();
- yield PT.redo();
- ensureUndoState(undoEntries, 0);
- ensureItemsAdded(folder_info, separator_info);
-
- observer.reset();
- let remove_sep_txn = PT.Remove(separator_info);
- yield remove_sep_txn.transact();
- undoEntries.unshift([remove_sep_txn]);
- ensureUndoState(undoEntries, 0);
- ensureItemsRemoved(separator_info);
-
- observer.reset();
- yield PT.undo();
- ensureUndoState(undoEntries, 1);
- ensureItemsAdded(separator_info);
-
- observer.reset();
- yield PT.undo();
- ensureUndoState(undoEntries, 2);
- ensureItemsRemoved(folder_info, separator_info);
-
- observer.reset();
- yield PT.redo();
- ensureUndoState(undoEntries, 1);
- ensureItemsAdded(folder_info, separator_info);
-
- // Clear redo entries and check that |redo| does nothing
- observer.reset();
- yield PT.clearTransactionsHistory(false, true);
- undoEntries.shift();
- ensureUndoState(undoEntries, 0);
- yield PT.redo();
- ensureItemsAdded();
- ensureItemsRemoved();
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureUndoState(undoEntries, 1);
- ensureItemsRemoved(folder_info, separator_info);
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_add_and_remove_livemark() {
- let createLivemarkTxn = PT.NewLivemark(
- { feedUrl: NetUtil.newURI("http://test.remove.livemark")
- , parentGuid: rootGuid
- , title: "Test Remove Livemark" });
- let guid = yield createLivemarkTxn.transact();
- let originalInfo = yield PlacesUtils.promiseBookmarksTree(guid);
- Assert.ok(originalInfo);
- yield ensureLivemarkCreatedByAddLivemark(guid);
-
- let removeTxn = PT.Remove(guid);
- yield removeTxn.transact();
- yield ensureNonExistent(guid);
- function* undo() {
- ensureUndoState([[removeTxn], [createLivemarkTxn]], 0);
- yield PT.undo();
- ensureUndoState([[removeTxn], [createLivemarkTxn]], 1);
- yield ensureBookmarksTreeRestoredCorrectly(originalInfo);
- yield PT.undo();
- ensureUndoState([[removeTxn], [createLivemarkTxn]], 2);
- yield ensureNonExistent(guid);
- }
- function* redo() {
- ensureUndoState([[removeTxn], [createLivemarkTxn]], 2);
- yield PT.redo();
- ensureUndoState([[removeTxn], [createLivemarkTxn]], 1);
- yield ensureBookmarksTreeRestoredCorrectly(originalInfo);
- yield PT.redo();
- ensureUndoState([[removeTxn], [createLivemarkTxn]], 0);
- yield ensureNonExistent(guid);
- }
-
- yield undo();
- yield redo();
- yield undo();
- yield redo();
-
- // Cleanup
- yield undo();
- observer.reset();
- yield PT.clearTransactionsHistory();
-});
-
-add_task(function* test_edit_title() {
- let bm_info = { parentGuid: rootGuid
- , url: NetUtil.newURI("http://test_create_item.com")
- , title: "Original Title" };
-
- function ensureTitleChange(aCurrentTitle) {
- ensureItemsChanged({ guid: bm_info.guid
- , property: "title"
- , newValue: aCurrentTitle});
- }
-
- bm_info.guid = yield PT.NewBookmark(bm_info).transact();
-
- observer.reset();
- yield PT.EditTitle({ guid: bm_info.guid, title: "New Title" }).transact();
- ensureTitleChange("New Title");
-
- observer.reset();
- yield PT.undo();
- ensureTitleChange("Original Title");
-
- observer.reset();
- yield PT.redo();
- ensureTitleChange("New Title");
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureTitleChange("Original Title");
- yield PT.undo();
- ensureItemsRemoved(bm_info);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_edit_url() {
- let oldURI = NetUtil.newURI("http://old.test_editing_item_uri.com/");
- let newURI = NetUtil.newURI("http://new.test_editing_item_uri.com/");
- let bm_info = { parentGuid: rootGuid, url: oldURI, tags: ["TestTag"] };
- function ensureURIAndTags(aPreChangeURI, aPostChangeURI, aOLdURITagsPreserved) {
- ensureItemsChanged({ guid: bm_info.guid
- , property: "uri"
- , newValue: aPostChangeURI.spec });
- ensureTagsForURI(aPostChangeURI, bm_info.tags);
- ensureTagsForURI(aPreChangeURI, aOLdURITagsPreserved ? bm_info.tags : []);
- }
-
- bm_info.guid = yield PT.NewBookmark(bm_info).transact();
- ensureTagsForURI(oldURI, bm_info.tags);
-
- // When there's a single bookmark for the same url, tags should be moved.
- observer.reset();
- yield PT.EditUrl({ guid: bm_info.guid, url: newURI }).transact();
- ensureURIAndTags(oldURI, newURI, false);
-
- observer.reset();
- yield PT.undo();
- ensureURIAndTags(newURI, oldURI, false);
-
- observer.reset();
- yield PT.redo();
- ensureURIAndTags(oldURI, newURI, false);
-
- observer.reset();
- yield PT.undo();
- ensureURIAndTags(newURI, oldURI, false);
-
- // When there're multiple bookmarks for the same url, tags should be copied.
- let bm2_info = Object.create(bm_info);
- bm2_info.guid = yield PT.NewBookmark(bm2_info).transact();
- let bm3_info = Object.create(bm_info);
- bm3_info.url = newURI;
- bm3_info.guid = yield PT.NewBookmark(bm3_info).transact();
-
- observer.reset();
- yield PT.EditUrl({ guid: bm_info.guid, url: newURI }).transact();
- ensureURIAndTags(oldURI, newURI, true);
-
- observer.reset();
- yield PT.undo();
- ensureURIAndTags(newURI, oldURI, true);
-
- observer.reset();
- yield PT.redo();
- ensureURIAndTags(oldURI, newURI, true);
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureURIAndTags(newURI, oldURI, true);
- yield PT.undo();
- yield PT.undo();
- yield PT.undo();
- ensureItemsRemoved(bm3_info, bm2_info, bm_info);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_edit_keyword() {
- let bm_info = { parentGuid: rootGuid
- , url: NetUtil.newURI("http://test.edit.keyword") };
- const KEYWORD = "test_keyword";
- bm_info.guid = yield PT.NewBookmark(bm_info).transact();
- function ensureKeywordChange(aCurrentKeyword = "") {
- ensureItemsChanged({ guid: bm_info.guid
- , property: "keyword"
- , newValue: aCurrentKeyword });
- }
-
- bm_info.guid = yield PT.NewBookmark(bm_info).transact();
-
- observer.reset();
- yield PT.EditKeyword({ guid: bm_info.guid, keyword: KEYWORD, postData: "postData" }).transact();
- ensureKeywordChange(KEYWORD);
- let entry = yield PlacesUtils.keywords.fetch(KEYWORD);
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData");
-
- observer.reset();
- yield PT.undo();
- ensureKeywordChange();
- entry = yield PlacesUtils.keywords.fetch(KEYWORD);
- Assert.equal(entry, null);
-
- observer.reset();
- yield PT.redo();
- ensureKeywordChange(KEYWORD);
- entry = yield PlacesUtils.keywords.fetch(KEYWORD);
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData");
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureKeywordChange();
- yield PT.undo();
- ensureItemsRemoved(bm_info);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_edit_specific_keyword() {
- let bm_info = { parentGuid: rootGuid
- , url: NetUtil.newURI("http://test.edit.keyword") };
- bm_info.guid = yield PT.NewBookmark(bm_info).transact();
- function ensureKeywordChange(aCurrentKeyword = "", aPreviousKeyword = "") {
- ensureItemsChanged({ guid: bm_info.guid
- , property: "keyword"
- , newValue: aCurrentKeyword
- });
- }
-
- yield PlacesUtils.keywords.insert({ keyword: "kw1", url: bm_info.url.spec, postData: "postData1" });
- yield PlacesUtils.keywords.insert({ keyword: "kw2", url: bm_info.url.spec, postData: "postData2" });
- bm_info.guid = yield PT.NewBookmark(bm_info).transact();
-
- observer.reset();
- yield PT.EditKeyword({ guid: bm_info.guid, keyword: "keyword", oldKeyword: "kw2" }).transact();
- ensureKeywordChange("keyword", "kw2");
- let entry = yield PlacesUtils.keywords.fetch("kw1");
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData1");
- entry = yield PlacesUtils.keywords.fetch("keyword");
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData2");
- entry = yield PlacesUtils.keywords.fetch("kw2");
- Assert.equal(entry, null);
-
- observer.reset();
- yield PT.undo();
- ensureKeywordChange("kw2", "keyword");
- entry = yield PlacesUtils.keywords.fetch("kw1");
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData1");
- entry = yield PlacesUtils.keywords.fetch("kw2");
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData2");
- entry = yield PlacesUtils.keywords.fetch("keyword");
- Assert.equal(entry, null);
-
- observer.reset();
- yield PT.redo();
- ensureKeywordChange("keyword", "kw2");
- entry = yield PlacesUtils.keywords.fetch("kw1");
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData1");
- entry = yield PlacesUtils.keywords.fetch("keyword");
- Assert.equal(entry.url.href, bm_info.url.spec);
- Assert.equal(entry.postData, "postData2");
- entry = yield PlacesUtils.keywords.fetch("kw2");
- Assert.equal(entry, null);
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureKeywordChange("kw2");
- yield PT.undo();
- ensureItemsRemoved(bm_info);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_tag_uri() {
- // This also tests passing uri specs.
- let bm_info_a = { url: "http://bookmarked.uri"
- , parentGuid: rootGuid };
- let bm_info_b = { url: NetUtil.newURI("http://bookmarked2.uri")
- , parentGuid: rootGuid };
- let unbookmarked_uri = NetUtil.newURI("http://un.bookmarked.uri");
-
- function* promiseIsBookmarked(aURI) {
- let deferred = Promise.defer();
- PlacesUtils.asyncGetBookmarkIds(aURI, ids => {
- deferred.resolve(ids.length > 0);
- });
- return deferred.promise;
- }
-
- yield PT.batch(function* () {
- bm_info_a.guid = yield PT.NewBookmark(bm_info_a).transact();
- bm_info_b.guid = yield PT.NewBookmark(bm_info_b).transact();
- });
-
- function* doTest(aInfo) {
- let urls = "url" in aInfo ? [aInfo.url] : aInfo.urls;
- let tags = "tag" in aInfo ? [aInfo.tag] : aInfo.tags;
-
- let ensureURI = url => typeof(url) == "string" ? NetUtil.newURI(url) : url;
- urls = urls.map(ensureURI);
-
- let tagWillAlsoBookmark = new Set();
- for (let url of urls) {
- if (!(yield promiseIsBookmarked(url))) {
- tagWillAlsoBookmark.add(url);
- }
- }
-
- function* ensureTagsSet() {
- for (let url of urls) {
- ensureTagsForURI(url, tags);
- Assert.ok(yield promiseIsBookmarked(url));
- }
- }
- function* ensureTagsUnset() {
- for (let url of urls) {
- ensureTagsForURI(url, []);
- if (tagWillAlsoBookmark.has(url))
- Assert.ok(!(yield promiseIsBookmarked(url)));
- else
- Assert.ok(yield promiseIsBookmarked(url));
- }
- }
-
- yield PT.Tag(aInfo).transact();
- yield ensureTagsSet();
- yield PT.undo();
- yield ensureTagsUnset();
- yield PT.redo();
- yield ensureTagsSet();
- yield PT.undo();
- yield ensureTagsUnset();
- }
-
- yield doTest({ url: bm_info_a.url, tags: ["MyTag"] });
- yield doTest({ urls: [bm_info_a.url], tag: "MyTag" });
- yield doTest({ urls: [bm_info_a.url, bm_info_b.url], tags: ["A, B"] });
- yield doTest({ urls: [bm_info_a.url, unbookmarked_uri], tag: "C" });
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureItemsRemoved(bm_info_a, bm_info_b);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_untag_uri() {
- let bm_info_a = { url: NetUtil.newURI("http://bookmarked.uri")
- , parentGuid: rootGuid
- , tags: ["A", "B"] };
- let bm_info_b = { url: NetUtil.newURI("http://bookmarked2.uri")
- , parentGuid: rootGuid
- , tag: "B" };
-
- yield PT.batch(function* () {
- bm_info_a.guid = yield PT.NewBookmark(bm_info_a).transact();
- ensureTagsForURI(bm_info_a.url, bm_info_a.tags);
- bm_info_b.guid = yield PT.NewBookmark(bm_info_b).transact();
- ensureTagsForURI(bm_info_b.url, [bm_info_b.tag]);
- });
-
- function* doTest(aInfo) {
- let urls, tagsRemoved;
- if (aInfo instanceof Ci.nsIURI) {
- urls = [aInfo];
- tagsRemoved = [];
- }
- else if (Array.isArray(aInfo)) {
- urls = aInfo;
- tagsRemoved = [];
- }
- else {
- urls = "url" in aInfo ? [aInfo.url] : aInfo.urls;
- tagsRemoved = "tag" in aInfo ? [aInfo.tag] : aInfo.tags;
- }
-
- let preRemovalTags = new Map();
- for (let url of urls) {
- preRemovalTags.set(url, tagssvc.getTagsForURI(url));
- }
-
- function ensureTagsSet() {
- for (let url of urls) {
- ensureTagsForURI(url, preRemovalTags.get(url));
- }
- }
- function ensureTagsUnset() {
- for (let url of urls) {
- let expectedTags = tagsRemoved.length == 0 ?
- [] : preRemovalTags.get(url).filter(tag => !tagsRemoved.includes(tag));
- ensureTagsForURI(url, expectedTags);
- }
- }
-
- yield PT.Untag(aInfo).transact();
- yield ensureTagsUnset();
- yield PT.undo();
- yield ensureTagsSet();
- yield PT.redo();
- yield ensureTagsUnset();
- yield PT.undo();
- yield ensureTagsSet();
- }
-
- yield doTest(bm_info_a);
- yield doTest(bm_info_b);
- yield doTest(bm_info_a.url);
- yield doTest(bm_info_b.url);
- yield doTest([bm_info_a.url, bm_info_b.url]);
- yield doTest({ urls: [bm_info_a.url, bm_info_b.url], tags: ["A", "B"] });
- yield doTest({ urls: [bm_info_a.url, bm_info_b.url], tag: "B" });
- yield doTest({ urls: [bm_info_a.url, bm_info_b.url], tag: "C" });
- yield doTest({ urls: [bm_info_a.url, bm_info_b.url], tags: ["C"] });
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureItemsRemoved(bm_info_a, bm_info_b);
-
- yield PT.clearTransactionsHistory();
- ensureUndoState();
-});
-
-add_task(function* test_annotate() {
- let bm_info = { url: NetUtil.newURI("http://test.item.annotation")
- , parentGuid: rootGuid };
- let anno_info = { name: "TestAnno", value: "TestValue" };
- function ensureAnnoState(aSet) {
- ensureAnnotationsSet(bm_info.guid,
- [{ name: anno_info.name
- , value: aSet ? anno_info.value : null }]);
- }
-
- bm_info.guid = yield PT.NewBookmark(bm_info).transact();
-
- observer.reset();
- yield PT.Annotate({ guid: bm_info.guid, annotation: anno_info }).transact();
- ensureAnnoState(true);
-
- observer.reset();
- yield PT.undo();
- ensureAnnoState(false);
-
- observer.reset();
- yield PT.redo();
- ensureAnnoState(true);
-
- // Test removing the annotation by not passing the |value| property.
- observer.reset();
- yield PT.Annotate({ guid: bm_info.guid,
- annotation: { name: anno_info.name }}).transact();
- ensureAnnoState(false);
-
- observer.reset();
- yield PT.undo();
- ensureAnnoState(true);
-
- observer.reset();
- yield PT.redo();
- ensureAnnoState(false);
-
- // Cleanup
- yield PT.undo();
- observer.reset();
-});
-
-add_task(function* test_annotate_multiple() {
- let guid = yield PT.NewFolder(createTestFolderInfo()).transact();
- let itemId = yield PlacesUtils.promiseItemId(guid);
-
- function AnnoObj(aName, aValue) {
- this.name = aName;
- this.value = aValue;
- this.flags = 0;
- this.expires = Ci.nsIAnnotationService.EXPIRE_NEVER;
- }
-
- function annos(a = null, b = null) {
- return [new AnnoObj("A", a), new AnnoObj("B", b)];
- }
-
- function verifyAnnoValues(a = null, b = null) {
- let currentAnnos = PlacesUtils.getAnnotationsForItem(itemId);
- let expectedAnnos = [];
- if (a !== null)
- expectedAnnos.push(new AnnoObj("A", a));
- if (b !== null)
- expectedAnnos.push(new AnnoObj("B", b));
-
- Assert.deepEqual(currentAnnos, expectedAnnos);
- }
-
- yield PT.Annotate({ guid: guid, annotations: annos(1, 2) }).transact();
- verifyAnnoValues(1, 2);
- yield PT.undo();
- verifyAnnoValues();
- yield PT.redo();
- verifyAnnoValues(1, 2);
-
- yield PT.Annotate({ guid: guid
- , annotation: { name: "A" } }).transact();
- verifyAnnoValues(null, 2);
-
- yield PT.Annotate({ guid: guid
- , annotation: { name: "B", value: 0 } }).transact();
- verifyAnnoValues(null, 0);
- yield PT.undo();
- verifyAnnoValues(null, 2);
- yield PT.redo();
- verifyAnnoValues(null, 0);
- yield PT.undo();
- verifyAnnoValues(null, 2);
- yield PT.undo();
- verifyAnnoValues(1, 2);
- yield PT.undo();
- verifyAnnoValues();
-
- // Cleanup
- yield PT.undo();
- observer.reset();
-});
-
-add_task(function* test_sort_folder_by_name() {
- let folder_info = createTestFolderInfo();
-
- let url = NetUtil.newURI("http://sort.by.name/");
- let preSep = ["3", "2", "1"].map(i => ({ title: i, url }));
- let sep = {};
- let postSep = ["c", "b", "a"].map(l => ({ title: l, url }));
- let originalOrder = [...preSep, sep, ...postSep];
- let sortedOrder = [...preSep.slice(0).reverse(),
- sep,
- ...postSep.slice(0).reverse()];
- yield PT.batch(function* () {
- folder_info.guid = yield PT.NewFolder(folder_info).transact();
- for (let info of originalOrder) {
- info.parentGuid = folder_info.guid;
- info.guid = yield info == sep ?
- PT.NewSeparator(info).transact() :
- PT.NewBookmark(info).transact();
- }
- });
-
- let folderId = yield PlacesUtils.promiseItemId(folder_info.guid);
- let folderContainer = PlacesUtils.getFolderContents(folderId).root;
- function ensureOrder(aOrder) {
- for (let i = 0; i < folderContainer.childCount; i++) {
- do_check_eq(folderContainer.getChild(i).bookmarkGuid, aOrder[i].guid);
- }
- }
-
- ensureOrder(originalOrder);
- yield PT.SortByName(folder_info.guid).transact();
- ensureOrder(sortedOrder);
- yield PT.undo();
- ensureOrder(originalOrder);
- yield PT.redo();
- ensureOrder(sortedOrder);
-
- // Cleanup
- observer.reset();
- yield PT.undo();
- ensureOrder(originalOrder);
- yield PT.undo();
- ensureItemsRemoved(...originalOrder, folder_info);
-});
-
-add_task(function* test_livemark_txns() {
- let livemark_info =
- { feedUrl: NetUtil.newURI("http://test.feed.uri")
- , parentGuid: rootGuid
- , title: "Test Livemark" };
- function ensureLivemarkAdded() {
- ensureItemsAdded({ guid: livemark_info.guid
- , title: livemark_info.title
- , parentGuid: livemark_info.parentGuid
- , itemType: bmsvc.TYPE_FOLDER });
- let annos = [{ name: PlacesUtils.LMANNO_FEEDURI
- , value: livemark_info.feedUrl.spec }];
- if ("siteUrl" in livemark_info) {
- annos.push({ name: PlacesUtils.LMANNO_SITEURI
- , value: livemark_info.siteUrl.spec });
- }
- ensureAnnotationsSet(livemark_info.guid, annos);
- }
- function ensureLivemarkRemoved() {
- ensureItemsRemoved({ guid: livemark_info.guid
- , parentGuid: livemark_info.parentGuid });
- }
-
- function* _testDoUndoRedoUndo() {
- observer.reset();
- livemark_info.guid = yield PT.NewLivemark(livemark_info).transact();
- ensureLivemarkAdded();
-
- observer.reset();
- yield PT.undo();
- ensureLivemarkRemoved();
-
- observer.reset();
- yield PT.redo();
- ensureLivemarkAdded();
-
- yield PT.undo();
- ensureLivemarkRemoved();
- }
-
- yield* _testDoUndoRedoUndo()
- livemark_info.siteUrl = NetUtil.newURI("http://feed.site.uri");
- yield* _testDoUndoRedoUndo();
-
- // Cleanup
- observer.reset();
- yield PT.clearTransactionsHistory();
-});
-
-add_task(function* test_copy() {
- function* duplicate_and_test(aOriginalGuid) {
- let txn = PT.Copy({ guid: aOriginalGuid, newParentGuid: rootGuid });
- yield duplicateGuid = yield txn.transact();
- let originalInfo = yield PlacesUtils.promiseBookmarksTree(aOriginalGuid);
- let duplicateInfo = yield PlacesUtils.promiseBookmarksTree(duplicateGuid);
- yield ensureEqualBookmarksTrees(originalInfo, duplicateInfo, false);
-
- function* redo() {
- yield PT.redo();
- yield ensureBookmarksTreeRestoredCorrectly(originalInfo);
- yield PT.redo();
- yield ensureBookmarksTreeRestoredCorrectly(duplicateInfo);
- }
- function* undo() {
- yield PT.undo();
- // also undo the original item addition.
- yield PT.undo();
- yield ensureNonExistent(aOriginalGuid, duplicateGuid);
- }
-
- yield undo();
- yield redo();
- yield undo();
- yield redo();
-
- // Cleanup. This also remove the original item.
- yield PT.undo();
- observer.reset();
- yield PT.clearTransactionsHistory();
- }
-
- // Test duplicating leafs (bookmark, separator, empty folder)
- PT.NewBookmark({ url: new URL("http://test.item.duplicate")
- , parentGuid: rootGuid
- , annos: [{ name: "Anno", value: "AnnoValue"}] });
- let sepTxn = PT.NewSeparator({ parentGuid: rootGuid, index: 1 });
- let livemarkTxn = PT.NewLivemark(
- { feedUrl: new URL("http://test.feed.uri")
- , parentGuid: rootGuid
- , title: "Test Livemark", index: 1 });
- let emptyFolderTxn = PT.NewFolder(createTestFolderInfo());
- for (let txn of [livemarkTxn, sepTxn, emptyFolderTxn]) {
- let guid = yield txn.transact();
- yield duplicate_and_test(guid);
- }
-
- // Test duplicating a folder having some contents.
- let filledFolderGuid = yield PT.batch(function *() {
- let folderGuid = yield PT.NewFolder(createTestFolderInfo()).transact();
- let nestedFolderGuid =
- yield PT.NewFolder({ parentGuid: folderGuid
- , title: "Nested Folder" }).transact();
- // Insert a bookmark under the nested folder.
- yield PT.NewBookmark({ url: new URL("http://nested.nested.bookmark")
- , parentGuid: nestedFolderGuid }).transact();
- // Insert a separator below the nested folder
- yield PT.NewSeparator({ parentGuid: folderGuid }).transact();
- // And another bookmark.
- yield PT.NewBookmark({ url: new URL("http://nested.bookmark")
- , parentGuid: folderGuid }).transact();
- return folderGuid;
- });
-
- yield duplicate_and_test(filledFolderGuid);
-
- // Cleanup
- yield PT.clearTransactionsHistory();
-});
-
-add_task(function* test_array_input_for_batch() {
- let folderTxn = PT.NewFolder(createTestFolderInfo());
- let folderGuid = yield folderTxn.transact();
-
- let sep1_txn = PT.NewSeparator({ parentGuid: folderGuid });
- let sep2_txn = PT.NewSeparator({ parentGuid: folderGuid });
- yield PT.batch([sep1_txn, sep2_txn]);
- ensureUndoState([[sep2_txn, sep1_txn], [folderTxn]], 0);
-
- let ensureChildCount = function* (count) {
- let tree = yield PlacesUtils.promiseBookmarksTree(folderGuid);
- if (count == 0)
- Assert.ok(!("children" in tree));
- else
- Assert.equal(tree.children.length, count);
- };
-
- yield ensureChildCount(2);
- yield PT.undo();
- yield ensureChildCount(0);
- yield PT.redo()
- yield ensureChildCount(2);
- yield PT.undo();
- yield ensureChildCount(0);
-
- yield PT.undo();
- Assert.equal((yield PlacesUtils.promiseBookmarksTree(folderGuid)), null);
-
- // Cleanup
- yield PT.clearTransactionsHistory();
-});
-
-add_task(function* test_copy_excluding_annotations() {
- let folderInfo = createTestFolderInfo();
- let anno = n => { return { name: n, value: 1 } };
- folderInfo.annotations = [anno("a"), anno("b"), anno("c")];
- let folderGuid = yield PT.NewFolder(folderInfo).transact();
-
- let ensureAnnosSet = function* (guid, ...expectedAnnoNames) {
- let tree = yield PlacesUtils.promiseBookmarksTree(guid);
- let annoNames = "annos" in tree ?
- tree.annos.map(a => a.name).sort() : [];
- Assert.deepEqual(annoNames, expectedAnnoNames);
- };
-
- yield ensureAnnosSet(folderGuid, "a", "b", "c");
-
- let excluding_a_dupeGuid =
- yield PT.Copy({ guid: folderGuid
- , newParentGuid: rootGuid
- , excludingAnnotation: "a" }).transact();
- yield ensureAnnosSet(excluding_a_dupeGuid, "b", "c");
-
- let excluding_ac_dupeGuid =
- yield PT.Copy({ guid: folderGuid
- , newParentGuid: rootGuid
- , excludingAnnotations: ["a", "c"] }).transact();
- yield ensureAnnosSet(excluding_ac_dupeGuid, "b");
-
- // Cleanup
- yield PT.undo();
- yield PT.undo();
- yield PT.undo();
- yield PT.clearTransactionsHistory();
-});
-
-add_task(function* test_invalid_uri_spec_throws() {
- Assert.throws(() =>
- PT.NewBookmark({ parentGuid: rootGuid
- , url: "invalid uri spec"
- , title: "test bookmark" }));
- Assert.throws(() =>
- PT.Tag({ tag: "TheTag"
- , urls: ["invalid uri spec"] }));
- Assert.throws(() =>
- PT.Tag({ tag: "TheTag"
- , urls: ["about:blank", "invalid uri spec"] }));
-});
-
-add_task(function* test_annotate_multiple_items() {
- let parentGuid = rootGuid;
- let guids = [
- yield PT.NewBookmark({ url: "about:blank", parentGuid }).transact(),
- yield PT.NewFolder({ title: "Test Folder", parentGuid }).transact()];
-
- let annotation = { name: "TestAnno", value: "TestValue" };
- yield PT.Annotate({ guids, annotation }).transact();
-
- function *ensureAnnoSet() {
- for (let guid of guids) {
- let itemId = yield PlacesUtils.promiseItemId(guid);
- Assert.equal(annosvc.getItemAnnotation(itemId, annotation.name),
- annotation.value);
- }
- }
- function *ensureAnnoUnset() {
- for (let guid of guids) {
- let itemId = yield PlacesUtils.promiseItemId(guid);
- Assert.ok(!annosvc.itemHasAnnotation(itemId, annotation.name));
- }
- }
-
- yield ensureAnnoSet();
- yield PT.undo();
- yield ensureAnnoUnset();
- yield PT.redo();
- yield ensureAnnoSet();
- yield PT.undo();
- yield ensureAnnoUnset();
-
- // Cleanup
- yield PT.undo();
- yield PT.undo();
- yield ensureNonExistent(...guids);
- yield PT.clearTransactionsHistory();
- observer.reset();
-});
-
-add_task(function* test_remove_multiple() {
- let guids = [];
- yield PT.batch(function* () {
- let folderGuid = yield PT.NewFolder({ title: "Test Folder"
- , parentGuid: rootGuid }).transact();
- let nestedFolderGuid =
- yield PT.NewFolder({ title: "Nested Test Folder"
- , parentGuid: folderGuid }).transact();
- yield PT.NewSeparator(nestedFolderGuid).transact();
-
- guids.push(folderGuid);
-
- let bmGuid =
- yield PT.NewBookmark({ url: new URL("http://test.bookmark.removed")
- , parentGuid: rootGuid }).transact();
- guids.push(bmGuid);
- });
-
- let originalInfos = [];
- for (let guid of guids) {
- originalInfos.push(yield PlacesUtils.promiseBookmarksTree(guid));
- }
-
- yield PT.Remove(guids).transact();
- yield ensureNonExistent(...guids);
- yield PT.undo();
- yield ensureBookmarksTreeRestoredCorrectly(...originalInfos);
- yield PT.redo();
- yield ensureNonExistent(...guids);
- yield PT.undo();
- yield ensureBookmarksTreeRestoredCorrectly(...originalInfos);
-
- // Undo the New* transactions batch.
- yield PT.undo();
- yield ensureNonExistent(...guids);
-
- // Redo it.
- yield PT.redo();
- yield ensureBookmarksTreeRestoredCorrectly(...originalInfos);
-
- // Redo remove.
- yield PT.redo();
- yield ensureNonExistent(...guids);
-
- // Cleanup
- yield PT.clearTransactionsHistory();
- observer.reset();
-});
-
-add_task(function* test_remove_bookmarks_for_urls() {
- let urls = [new URL("http://test.url.1"), new URL("http://test.url.2")];
- let guids = [];
- yield PT.batch(function* () {
- for (let url of urls) {
- for (let title of ["test title a", "test title b"]) {
- let txn = PT.NewBookmark({ url, title, parentGuid: rootGuid });
- guids.push(yield txn.transact());
- }
- }
- });
-
- let originalInfos = [];
- for (let guid of guids) {
- originalInfos.push(yield PlacesUtils.promiseBookmarksTree(guid));
- }
-
- yield PT.RemoveBookmarksForUrls(urls).transact();
- yield ensureNonExistent(...guids);
- yield PT.undo();
- yield ensureBookmarksTreeRestoredCorrectly(...originalInfos);
- yield PT.redo();
- yield ensureNonExistent(...guids);
- yield PT.undo();
- yield ensureBookmarksTreeRestoredCorrectly(...originalInfos);
-
- // Cleanup.
- yield PT.redo();
- yield ensureNonExistent(...guids);
- yield PT.clearTransactionsHistory();
- observer.reset();
-});
diff --git a/toolkit/components/places/tests/unit/test_autocomplete_stopSearch_no_throw.js b/toolkit/components/places/tests/unit/test_autocomplete_stopSearch_no_throw.js
deleted file mode 100644
index 7d5df565f..000000000
--- a/toolkit/components/places/tests/unit/test_autocomplete_stopSearch_no_throw.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Added with bug 508102 to make sure that calling stopSearch on our
- * AutoComplete implementation does not throw.
- */
-
-// Globals and Constants
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var ac = Cc["@mozilla.org/autocomplete/search;1?name=unifiedcomplete"].
- getService(Ci.nsIAutoCompleteSearch);
-
-// Test Functions
-
-function test_stopSearch()
-{
- try {
- ac.stopSearch();
- }
- catch (e) {
- do_throw("we should not have caught anything!");
- }
-}
-
-// Test Runner
-
-var tests = [
- test_stopSearch,
-];
-function run_test()
-{
- tests.forEach(test => test());
-}
diff --git a/toolkit/components/places/tests/unit/test_bookmark_catobs.js b/toolkit/components/places/tests/unit/test_bookmark_catobs.js
deleted file mode 100644
index e2b589090..000000000
--- a/toolkit/components/places/tests/unit/test_bookmark_catobs.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test() {
- run_next_test()
-}
-
-add_task(function* test_observers() {
- do_load_manifest("nsDummyObserver.manifest");
-
- let dummyCreated = false;
- let dummyReceivedOnItemAdded = false;
-
- Services.obs.addObserver(function created() {
- Services.obs.removeObserver(created, "dummy-observer-created");
- dummyCreated = true;
- }, "dummy-observer-created", false);
- Services.obs.addObserver(function added() {
- Services.obs.removeObserver(added, "dummy-observer-item-added");
- dummyReceivedOnItemAdded = true;
- }, "dummy-observer-item-added", false);
-
- let initialObservers = PlacesUtils.bookmarks.getObservers();
-
- // Add a common observer, it should be invoked after the category observer.
- let notificationsPromised = new Promise((resolve, reject) => {
- PlacesUtils.bookmarks.addObserver( {
- __proto__: NavBookmarkObserver.prototype,
- onItemAdded() {
- let observers = PlacesUtils.bookmarks.getObservers();
- Assert.equal(observers.length, initialObservers.length + 1);
-
- // Check the common observer is the last one.
- for (let i = 0; i < initialObservers.length; ++i) {
- Assert.equal(initialObservers[i], observers[i]);
- }
-
- PlacesUtils.bookmarks.removeObserver(this);
- observers = PlacesUtils.bookmarks.getObservers();
- Assert.equal(observers.length, initialObservers.length);
-
- // Check the category observer has been invoked before this one.
- Assert.ok(dummyCreated);
- Assert.ok(dummyReceivedOnItemAdded);
- resolve();
- }
- }, false);
- });
-
- // Add a bookmark
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri("http://typed.mozilla.org"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark");
-
- yield notificationsPromised;
-});
diff --git a/toolkit/components/places/tests/unit/test_bookmarks_html.js b/toolkit/components/places/tests/unit/test_bookmarks_html.js
deleted file mode 100644
index b10dc6185..000000000
--- a/toolkit/components/places/tests/unit/test_bookmarks_html.js
+++ /dev/null
@@ -1,385 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
-const DESCRIPTION_ANNO = "bookmarkProperties/description";
-
-// An object representing the contents of bookmarks.preplaces.html.
-var test_bookmarks = {
- menu: [
- { title: "Mozilla Firefox",
- children: [
- { title: "Help and Tutorials",
- url: "http://en-us.www.mozilla.com/en-US/firefox/help/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { title: "Customize Firefox",
- url: "http://en-us.www.mozilla.com/en-US/firefox/customize/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { title: "Get Involved",
- url: "http://en-us.www.mozilla.com/en-US/firefox/community/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { title: "About Us",
- url: "http://en-us.www.mozilla.com/en-US/about/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- }
- ]
- },
- {
- type: Ci.nsINavHistoryResultNode.RESULT_TYPE_SEPARATOR
- },
- { title: "test",
- description: "folder test comment",
- dateAdded: 1177541020000000,
- lastModified: 1177541050000000,
- children: [
- { title: "test post keyword",
- description: "item description",
- dateAdded: 1177375336000000,
- lastModified: 1177375423000000,
- keyword: "test",
- sidebar: true,
- postData: "hidden1%3Dbar&text1%3D%25s",
- charset: "ISO-8859-1",
- url: "http://test/post"
- }
- ]
- }
- ],
- toolbar: [
- { title: "Getting Started",
- url: "http://en-us.www.mozilla.com/en-US/firefox/central/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { title: "Latest Headlines",
- url: "http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/",
- feedUrl: "http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml"
- }
- ],
- unfiled: [
- { title: "Example.tld",
- url: "http://example.tld/"
- }
- ]
-};
-
-// Pre-Places bookmarks.html file pointer.
-var gBookmarksFileOld;
-// Places bookmarks.html file pointer.
-var gBookmarksFileNew;
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* setup() {
- // Avoid creating smart bookmarks during the test.
- Services.prefs.setIntPref("browser.places.smartBookmarksVersion", -1);
-
- // File pointer to legacy bookmarks file.
- gBookmarksFileOld = do_get_file("bookmarks.preplaces.html");
-
- // File pointer to a new Places-exported bookmarks file.
- gBookmarksFileNew = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
- gBookmarksFileNew.append("bookmarks.exported.html");
- if (gBookmarksFileNew.exists()) {
- gBookmarksFileNew.remove(false);
- }
-
- // This test must be the first one, since it setups the new bookmarks.html.
- // Test importing a pre-Places canonical bookmarks file.
- // 1. import bookmarks.preplaces.html
- // 2. run the test-suite
- // Note: we do not empty the db before this import to catch bugs like 380999
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileOld, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield testImportedBookmarks();
-
- yield BookmarkHTMLUtils.exportToFile(gBookmarksFileNew);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_import_new()
-{
- // Test importing a Places bookmarks.html file.
- // 1. import bookmarks.exported.html
- // 2. run the test-suite
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileNew, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- yield testImportedBookmarks();
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_emptytitle_export()
-{
- // Test exporting and importing with an empty-titled bookmark.
- // 1. import bookmarks
- // 2. create an empty-titled bookmark.
- // 3. export to bookmarks.exported.html
- // 4. empty bookmarks db
- // 5. import bookmarks.exported.html
- // 6. run the test-suite
- // 7. remove the empty-titled bookmark
- // 8. export to bookmarks.exported.html
- // 9. empty bookmarks db and continue
-
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileNew, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- const NOTITLE_URL = "http://notitle.mozilla.org/";
- let bookmark = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: NOTITLE_URL
- });
- test_bookmarks.unfiled.push({ title: "", url: NOTITLE_URL });
-
- yield BookmarkHTMLUtils.exportToFile(gBookmarksFileNew);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield PlacesUtils.bookmarks.eraseEverything();
-
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileNew, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield testImportedBookmarks();
-
- // Cleanup.
- test_bookmarks.unfiled.pop();
- // HTML imports don't restore GUIDs yet.
- let reimportedBookmark = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX
- });
- Assert.equal(reimportedBookmark.url.href, bookmark.url.href);
- yield PlacesUtils.bookmarks.remove(reimportedBookmark);
-
- yield BookmarkHTMLUtils.exportToFile(gBookmarksFileNew);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_import_chromefavicon()
-{
- // Test exporting and importing with a bookmark pointing to a chrome favicon.
- // 1. import bookmarks
- // 2. create a bookmark pointing to a chrome favicon.
- // 3. export to bookmarks.exported.html
- // 4. empty bookmarks db
- // 5. import bookmarks.exported.html
- // 6. run the test-suite
- // 7. remove the bookmark pointing to a chrome favicon.
- // 8. export to bookmarks.exported.html
- // 9. empty bookmarks db and continue
-
- const PAGE_URI = NetUtil.newURI("http://example.com/chromefavicon_page");
- const CHROME_FAVICON_URI = NetUtil.newURI("chrome://global/skin/icons/information-16.png");
- const CHROME_FAVICON_URI_2 = NetUtil.newURI("chrome://global/skin/icons/error-16.png");
-
- do_print("Importing from html");
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileNew, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Insert bookmark");
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: PAGE_URI,
- title: "Test"
- });
-
- do_print("Set favicon");
- yield new Promise(resolve => {
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- PAGE_URI, CHROME_FAVICON_URI, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- resolve, Services.scriptSecurityManager.getSystemPrincipal());
- });
-
- let data = yield new Promise(resolve => {
- PlacesUtils.favicons.getFaviconDataForPage(
- PAGE_URI, (uri, dataLen, faviconData, mimeType) => resolve(faviconData));
- });
-
- let base64Icon = "data:image/png;base64," +
- base64EncodeString(String.fromCharCode.apply(String, data));
-
- test_bookmarks.unfiled.push(
- { title: "Test", url: PAGE_URI.spec, icon: base64Icon });
-
- do_print("Export to html");
- yield BookmarkHTMLUtils.exportToFile(gBookmarksFileNew);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Set favicon");
- // Change the favicon to check it's really imported again later.
- yield new Promise(resolve => {
- PlacesUtils.favicons.setAndFetchFaviconForPage(
- PAGE_URI, CHROME_FAVICON_URI_2, true,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- resolve, Services.scriptSecurityManager.getSystemPrincipal());
- });
-
- do_print("import from html");
- yield PlacesUtils.bookmarks.eraseEverything();
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileNew, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- do_print("Test imported bookmarks");
- yield testImportedBookmarks();
-
- // Cleanup.
- test_bookmarks.unfiled.pop();
- // HTML imports don't restore GUIDs yet.
- let reimportedBookmark = yield PlacesUtils.bookmarks.fetch({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX
- });
- yield PlacesUtils.bookmarks.remove(reimportedBookmark);
-
- yield BookmarkHTMLUtils.exportToFile(gBookmarksFileNew);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_import_ontop()
-{
- // Test importing the exported bookmarks.html file *on top of* the existing
- // bookmarks.
- // 1. empty bookmarks db
- // 2. import the exported bookmarks file
- // 3. export to file
- // 3. import the exported bookmarks file
- // 4. run the test-suite
-
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileNew, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield BookmarkHTMLUtils.exportToFile(gBookmarksFileNew);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- yield BookmarkHTMLUtils.importFromFile(gBookmarksFileNew, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield testImportedBookmarks();
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-function* testImportedBookmarks()
-{
- for (let group in test_bookmarks) {
- do_print("[testImportedBookmarks()] Checking group '" + group + "'");
-
- let root;
- switch (group) {
- case "menu":
- root = PlacesUtils.getFolderContents(PlacesUtils.bookmarksMenuFolderId).root;
- break;
- case "toolbar":
- root = PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId).root;
- break;
- case "unfiled":
- root = PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- break;
- }
-
- let items = test_bookmarks[group];
- do_check_eq(root.childCount, items.length);
-
- for (let key in items) {
- yield checkItem(items[key], root.getChild(key));
- }
-
- root.containerOpen = false;
- }
-}
-
-function* checkItem(aExpected, aNode)
-{
- let id = aNode.itemId;
-
- return Task.spawn(function* () {
- for (prop in aExpected) {
- switch (prop) {
- case "type":
- do_check_eq(aNode.type, aExpected.type);
- break;
- case "title":
- do_check_eq(aNode.title, aExpected.title);
- break;
- case "description":
- do_check_eq(PlacesUtils.annotations
- .getItemAnnotation(id, DESCRIPTION_ANNO),
- aExpected.description);
- break;
- case "dateAdded":
- do_check_eq(PlacesUtils.bookmarks.getItemDateAdded(id),
- aExpected.dateAdded);
- break;
- case "lastModified":
- do_check_eq(PlacesUtils.bookmarks.getItemLastModified(id),
- aExpected.lastModified);
- break;
- case "url":
- if (!("feedUrl" in aExpected))
- do_check_eq(aNode.uri, aExpected.url)
- break;
- case "icon":
- let deferred = Promise.defer();
- PlacesUtils.favicons.getFaviconDataForPage(
- NetUtil.newURI(aExpected.url),
- function (aURI, aDataLen, aData, aMimeType) {
- deferred.resolve(aData);
- });
- let data = yield deferred.promise;
- let base64Icon = "data:image/png;base64," +
- base64EncodeString(String.fromCharCode.apply(String, data));
- do_check_true(base64Icon == aExpected.icon);
- break;
- case "keyword": {
- let entry = yield PlacesUtils.keywords.fetch({ url: aNode.uri });
- Assert.equal(entry.keyword, aExpected.keyword);
- break;
- }
- case "sidebar":
- do_check_eq(PlacesUtils.annotations
- .itemHasAnnotation(id, LOAD_IN_SIDEBAR_ANNO),
- aExpected.sidebar);
- break;
- case "postData": {
- let entry = yield PlacesUtils.keywords.fetch({ url: aNode.uri });
- Assert.equal(entry.postData, aExpected.postData);
- break;
- }
- case "charset":
- let testURI = NetUtil.newURI(aNode.uri);
- do_check_eq((yield PlacesUtils.getCharsetForURI(testURI)), aExpected.charset);
- break;
- case "feedUrl":
- let livemark = yield PlacesUtils.livemarks.getLivemark({ id: id });
- do_check_eq(livemark.siteURI.spec, aExpected.url);
- do_check_eq(livemark.feedURI.spec, aExpected.feedUrl);
- break;
- case "children":
- let folder = aNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(folder.hasChildren, aExpected.children.length > 0);
- folder.containerOpen = true;
- do_check_eq(folder.childCount, aExpected.children.length);
-
- for (let index = 0; index < aExpected.children.length; index++) {
- yield checkItem(aExpected.children[index], folder.getChild(index));
- }
-
- folder.containerOpen = false;
- break;
- default:
- throw new Error("Unknown property");
- }
- }
- });
-}
diff --git a/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js b/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js
deleted file mode 100644
index 845b2227b..000000000
--- a/toolkit/components/places/tests/unit/test_bookmarks_html_corrupt.js
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * This test ensures that importing/exporting to HTML does not stop
- * if a malformed uri is found.
- */
-
-const DESCRIPTION_ANNO = "bookmarkProperties/description";
-const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
-
-const TEST_FAVICON_PAGE_URL = "http://en-US.www.mozilla.com/en-US/firefox/central/";
-const TEST_FAVICON_DATA_SIZE = 580;
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_corrupt_file() {
- // avoid creating the places smart folder during tests
- Services.prefs.setIntPref("browser.places.smartBookmarksVersion", -1);
-
- // Import bookmarks from the corrupt file.
- let corruptHtml = OS.Path.join(do_get_cwd().path, "bookmarks.corrupt.html");
- yield BookmarkHTMLUtils.importFromFile(corruptHtml, true);
-
- // Check that bookmarks that are not corrupt have been imported.
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield database_check();
-});
-
-add_task(function* test_corrupt_database() {
- // Create corruption in the database, then export.
- let corruptBookmark = yield PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- url: "http://test.mozilla.org",
- title: "We love belugas" });
- yield PlacesUtils.withConnectionWrapper("test", Task.async(function*(db) {
- yield db.execute("UPDATE moz_bookmarks SET fk = NULL WHERE guid = :guid",
- { guid: corruptBookmark.guid });
- }));
-
- let bookmarksFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.exported.html");
- if ((yield OS.File.exists(bookmarksFile)))
- yield OS.File.remove(bookmarksFile);
- yield BookmarkHTMLUtils.exportToFile(bookmarksFile);
-
- // Import again and check for correctness.
- yield PlacesUtils.bookmarks.eraseEverything();
- yield BookmarkHTMLUtils.importFromFile(bookmarksFile, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield database_check();
-});
-
-/*
- * Check for imported bookmarks correctness
- *
- * @return {Promise}
- * @resolves When the checks are finished.
- * @rejects Never.
- */
-var database_check = Task.async(function* () {
- // BOOKMARKS MENU
- let root = PlacesUtils.getFolderContents(PlacesUtils.bookmarksMenuFolderId).root;
- Assert.equal(root.childCount, 2);
-
- let folderNode = root.getChild(1);
- Assert.equal(folderNode.type, folderNode.RESULT_TYPE_FOLDER);
- Assert.equal(folderNode.title, "test");
- Assert.equal(PlacesUtils.bookmarks.getItemDateAdded(folderNode.itemId), 1177541020000000);
- Assert.equal(PlacesUtils.bookmarks.getItemLastModified(folderNode.itemId), 1177541050000000);
- Assert.equal("folder test comment",
- PlacesUtils.annotations.getItemAnnotation(folderNode.itemId,
- DESCRIPTION_ANNO));
- // open test folder, and test the children
- PlacesUtils.asQuery(folderNode);
- Assert.equal(folderNode.hasChildren, true);
- folderNode.containerOpen = true;
- Assert.equal(folderNode.childCount, 1);
-
- let bookmarkNode = folderNode.getChild(0);
- Assert.equal("http://test/post", bookmarkNode.uri);
- Assert.equal("test post keyword", bookmarkNode.title);
-
- let entry = yield PlacesUtils.keywords.fetch({ url: bookmarkNode.uri });
- Assert.equal("test", entry.keyword);
- Assert.equal("hidden1%3Dbar&text1%3D%25s", entry.postData);
-
- Assert.ok(PlacesUtils.annotations.itemHasAnnotation(bookmarkNode.itemId,
- LOAD_IN_SIDEBAR_ANNO));
- Assert.equal(bookmarkNode.dateAdded, 1177375336000000);
- Assert.equal(bookmarkNode.lastModified, 1177375423000000);
-
- Assert.equal((yield PlacesUtils.getCharsetForURI(NetUtil.newURI(bookmarkNode.uri))),
- "ISO-8859-1");
-
- Assert.equal("item description",
- PlacesUtils.annotations.getItemAnnotation(bookmarkNode.itemId,
- DESCRIPTION_ANNO));
-
- // clean up
- folderNode.containerOpen = false;
- root.containerOpen = false;
-
- // BOOKMARKS TOOLBAR
- root = PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId).root;
- Assert.equal(root.childCount, 3);
-
- // For now some promises are resolved later, so we can't guarantee an order.
- let foundLivemark = false;
- for (let i = 0; i < root.childCount; ++i) {
- let node = root.getChild(i);
- if (node.title == "Latest Headlines") {
- foundLivemark = true;
- Assert.equal("Latest Headlines", node.title);
-
- let livemark = yield PlacesUtils.livemarks.getLivemark({ guid: node.bookmarkGuid });
- Assert.equal("http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/",
- livemark.siteURI.spec);
- Assert.equal("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml",
- livemark.feedURI.spec);
- }
- }
- Assert.ok(foundLivemark);
-
- // cleanup
- root.containerOpen = false;
-
- // UNFILED BOOKMARKS
- root = PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- Assert.equal(root.childCount, 1);
- root.containerOpen = false;
-
- // favicons
- yield new Promise(resolve => {
- PlacesUtils.favicons.getFaviconDataForPage(uri(TEST_FAVICON_PAGE_URL),
- (aURI, aDataLen, aData, aMimeType) => {
- // aURI should never be null when aDataLen > 0.
- Assert.notEqual(aURI, null);
- // Favicon data is stored in the bookmarks file as a "data:" URI. For
- // simplicity, instead of converting the data we receive to a "data:" URI
- // and comparing it, we just check the data size.
- Assert.equal(TEST_FAVICON_DATA_SIZE, aDataLen);
- resolve();
- });
- });
-});
diff --git a/toolkit/components/places/tests/unit/test_bookmarks_html_import_tags.js b/toolkit/components/places/tests/unit/test_bookmarks_html_import_tags.js
deleted file mode 100644
index e4ba433a3..000000000
--- a/toolkit/components/places/tests/unit/test_bookmarks_html_import_tags.js
+++ /dev/null
@@ -1,57 +0,0 @@
-var bookmarkData = [
- { uri: uri("http://www.toastytech.com"),
- title: "Nathan's Toasty Technology Page",
- tags: ["technology", "personal", "retro"] },
- { uri: uri("http://www.reddit.com"),
- title: "reddit: the front page of the internet",
- tags: ["social media", "news", "humour"] },
- { uri: uri("http://www.4chan.org"),
- title: "4chan",
- tags: ["discussion", "imageboard", "anime"] }
-];
-
-/*
- TEST SUMMARY
- - Add bookmarks with tags
- - Export tagged bookmarks as HTML file
- - Delete bookmarks
- - Import bookmarks from HTML file
- - Check that all bookmarks are successfully imported with tags
-*/
-
-add_task(function* test_import_tags() {
- // Removes bookmarks.html if the file already exists.
- let HTMLFile = OS.Path.join(OS.Constants.Path.profileDir, "bookmarks.html");
- if ((yield OS.File.exists(HTMLFile)))
- yield OS.File.remove(HTMLFile);
-
- // Adds bookmarks and tags to the database.
- let bookmarkList = new Set();
- for (let { uri, title, tags } of bookmarkData) {
- bookmarkList.add(yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- url: uri,
- title }));
- PlacesUtils.tagging.tagURI(uri, tags);
- }
-
- // Exports the bookmarks as a HTML file.
- yield BookmarkHTMLUtils.exportToFile(HTMLFile);
-
- // Deletes bookmarks and tags from the database.
- for (let bookmark of bookmarkList) {
- yield PlacesUtils.bookmarks.remove(bookmark.guid);
- }
-
- // Re-imports the bookmarks from the HTML file.
- yield BookmarkHTMLUtils.importFromFile(HTMLFile, true);
-
- // Tests to ensure that the tags are still present for each bookmark URI.
- for (let { uri, tags } of bookmarkData) {
- do_print("Test tags for " + uri.spec + ": " + tags + "\n");
- let foundTags = PlacesUtils.tagging.getTagsForURI(uri);
- Assert.equal(foundTags.length, tags.length);
- Assert.ok(tags.every(tag => foundTags.includes(tag)));
- }
-});
-
diff --git a/toolkit/components/places/tests/unit/test_bookmarks_html_singleframe.js b/toolkit/components/places/tests/unit/test_bookmarks_html_singleframe.js
deleted file mode 100644
index 02b430ff2..000000000
--- a/toolkit/components/places/tests/unit/test_bookmarks_html_singleframe.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Test for bug #801450
-
-// Get Services
-Cu.import("resource://gre/modules/BookmarkHTMLUtils.jsm");
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_bookmarks_html_singleframe()
-{
- let bookmarksFile = OS.Path.join(do_get_cwd().path, "bookmarks_html_singleframe.html");
- yield BookmarkHTMLUtils.importFromFile(bookmarksFile, true);
-
- let root = PlacesUtils.getFolderContents(PlacesUtils.bookmarksMenuFolderId).root;
- do_check_eq(root.childCount, 1);
- let folder = root.getChild(0);
- PlacesUtils.asContainer(folder).containerOpen = true;
- do_check_eq(folder.title, "Subtitle");
- do_check_eq(folder.childCount, 1);
- let bookmark = folder.getChild(0);
- do_check_eq(bookmark.uri, "http://www.mozilla.org/");
- do_check_eq(bookmark.title, "Mozilla");
- folder.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_bookmarks_json.js b/toolkit/components/places/tests/unit/test_bookmarks_json.js
deleted file mode 100644
index a6801540a..000000000
--- a/toolkit/components/places/tests/unit/test_bookmarks_json.js
+++ /dev/null
@@ -1,241 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Cu.import("resource://gre/modules/BookmarkJSONUtils.jsm");
-
-function run_test() {
- run_next_test();
-}
-
-const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
-const DESCRIPTION_ANNO = "bookmarkProperties/description";
-
-// An object representing the contents of bookmarks.json.
-var test_bookmarks = {
- menu: [
- { guid: "OCyeUO5uu9FF",
- title: "Mozilla Firefox",
- children: [
- { guid:"OCyeUO5uu9FG",
- title: "Help and Tutorials",
- url: "http://en-us.www.mozilla.com/en-US/firefox/help/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { guid:"OCyeUO5uu9FH",
- title: "Customize Firefox",
- url: "http://en-us.www.mozilla.com/en-US/firefox/customize/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { guid:"OCyeUO5uu9FI",
- title: "Get Involved",
- url: "http://en-us.www.mozilla.com/en-US/firefox/community/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { guid:"OCyeUO5uu9FJ",
- title: "About Us",
- url: "http://en-us.www.mozilla.com/en-US/about/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- }
- ]
- },
- {
- guid: "OCyeUO5uu9FK",
- type: Ci.nsINavHistoryResultNode.RESULT_TYPE_SEPARATOR
- },
- {
- guid:"OCyeUO5uu9FL",
- title: "test",
- description: "folder test comment",
- dateAdded: 1177541020000000,
- // lastModified: 1177541050000000,
- children: [
- { guid:"OCyeUO5uu9GX",
- title: "test post keyword",
- description: "item description",
- dateAdded: 1177375336000000,
- // lastModified: 1177375423000000,
- keyword: "test",
- sidebar: true,
- postData: "hidden1%3Dbar&text1%3D%25s",
- charset: "ISO-8859-1"
- }
- ]
- }
- ],
- toolbar: [
- { guid: "OCyeUO5uu9FB",
- title: "Getting Started",
- url: "http://en-us.www.mozilla.com/en-US/firefox/central/",
- icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHWSURBVHjaYvz//z8DJQAggJiQOe/fv2fv7Oz8rays/N+VkfG/iYnJfyD/1+rVq7ffu3dPFpsBAAHEAHIBCJ85c8bN2Nj4vwsDw/8zQLwKiO8CcRoQu0DxqlWrdsHUwzBAAIGJmTNnPgYa9j8UqhFElwPxf2MIDeIrKSn9FwSJoRkAEEAM0DD4DzMAyPi/G+QKY4hh5WAXGf8PDQ0FGwJ22d27CjADAAIIrLmjo+MXA9R2kAHvGBA2wwx6B8W7od6CeQcggKCmCEL8bgwxYCbUIGTDVkHDBia+CuotgACCueD3TDQN75D4xmAvCoK9ARMHBzAw0AECiBHkAlC0Mdy7x9ABNA3obAZXIAa6iKEcGlMVQHwWyjYuL2d4v2cPg8vZswx7gHyAAAK7AOif7SAbOqCmn4Ha3AHFsIDtgPq/vLz8P4MSkJ2W9h8ggBjevXvHDo4FQUQg/kdypqCg4H8lUIACnQ/SOBMYI8bAsAJFPcj1AAEEjwVQqLpAbXmH5BJjqI0gi9DTAAgDBBCcAVLkgmQ7yKCZxpCQxqUZhAECCJ4XgMl493ug21ZD+aDAXH0WLM4A9MZPXJkJIIAwTAR5pQMalaCABQUULttBGCCAGCnNzgABBgAMJ5THwGvJLAAAAABJRU5ErkJggg=="
- },
- { guid:"OCyeUO5uu9FR",
- title: "Latest Headlines",
- url: "http://en-us.fxfeeds.mozilla.com/en-US/firefox/livebookmarks/",
- feedUrl: "http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml"
- }
- ],
- unfiled: [
- { guid: "OCyeUO5uu9FW",
- title: "Example.tld",
- url: "http://example.tld/"
- }
- ]
-};
-
-// Exported bookmarks file pointer.
-var bookmarksExportedFile;
-
-add_task(function* test_import_bookmarks() {
- let bookmarksFile = OS.Path.join(do_get_cwd().path, "bookmarks.json");
-
- yield BookmarkJSONUtils.importFromFile(bookmarksFile, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield testImportedBookmarks();
-});
-
-add_task(function* test_export_bookmarks() {
- bookmarksExportedFile = OS.Path.join(OS.Constants.Path.profileDir,
- "bookmarks.exported.json");
- yield BookmarkJSONUtils.exportToFile(bookmarksExportedFile);
- yield PlacesTestUtils.promiseAsyncUpdates();
-});
-
-add_task(function* test_import_exported_bookmarks() {
- yield PlacesUtils.bookmarks.eraseEverything();
- yield BookmarkJSONUtils.importFromFile(bookmarksExportedFile, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield testImportedBookmarks();
-});
-
-add_task(function* test_import_ontop() {
- yield PlacesUtils.bookmarks.eraseEverything();
- yield BookmarkJSONUtils.importFromFile(bookmarksExportedFile, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield BookmarkJSONUtils.exportToFile(bookmarksExportedFile);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield BookmarkJSONUtils.importFromFile(bookmarksExportedFile, true);
- yield PlacesTestUtils.promiseAsyncUpdates();
- yield testImportedBookmarks();
-});
-
-add_task(function* test_clean() {
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-function* testImportedBookmarks() {
- for (let group in test_bookmarks) {
- do_print("[testImportedBookmarks()] Checking group '" + group + "'");
-
- let root;
- switch (group) {
- case "menu":
- root =
- PlacesUtils.getFolderContents(PlacesUtils.bookmarksMenuFolderId).root;
- break;
- case "toolbar":
- root =
- PlacesUtils.getFolderContents(PlacesUtils.toolbarFolderId).root;
- break;
- case "unfiled":
- root =
- PlacesUtils.getFolderContents(PlacesUtils.unfiledBookmarksFolderId).root;
- break;
- }
-
- let items = test_bookmarks[group];
- do_check_eq(root.childCount, items.length);
-
- for (let key in items) {
- yield checkItem(items[key], root.getChild(key));
- }
-
- root.containerOpen = false;
- }
-}
-
-function* checkItem(aExpected, aNode) {
- let id = aNode.itemId;
-
- return Task.spawn(function* () {
- for (prop in aExpected) {
- switch (prop) {
- case "type":
- do_check_eq(aNode.type, aExpected.type);
- break;
- case "title":
- do_check_eq(aNode.title, aExpected.title);
- break;
- case "description":
- do_check_eq(PlacesUtils.annotations.getItemAnnotation(
- id, DESCRIPTION_ANNO), aExpected.description);
- break;
- case "dateAdded":
- do_check_eq(PlacesUtils.bookmarks.getItemDateAdded(id),
- aExpected.dateAdded);
- break;
- case "lastModified":
- do_check_eq(PlacesUtils.bookmarks.getItemLastModified(id),
- aExpected.lastModified);
- break;
- case "url":
- if (!("feedUrl" in aExpected))
- do_check_eq(aNode.uri, aExpected.url);
- break;
- case "icon":
- let deferred = Promise.defer();
- PlacesUtils.favicons.getFaviconDataForPage(
- NetUtil.newURI(aExpected.url),
- function (aURI, aDataLen, aData, aMimeType) {
- deferred.resolve(aData);
- });
- let data = yield deferred.promise;
- let base64Icon = "data:image/png;base64," +
- base64EncodeString(String.fromCharCode.apply(String, data));
- do_check_true(base64Icon == aExpected.icon);
- break;
- case "keyword": {
- let entry = yield PlacesUtils.keywords.fetch({ url: aNode.uri });
- Assert.equal(entry.keyword, aExpected.keyword);
- break;
- }
- case "guid":
- let guid = yield PlacesUtils.promiseItemGuid(id);
- do_check_eq(guid, aExpected.guid);
- break;
- case "sidebar":
- do_check_eq(PlacesUtils.annotations.itemHasAnnotation(
- id, LOAD_IN_SIDEBAR_ANNO), aExpected.sidebar);
- break;
- case "postData": {
- let entry = yield PlacesUtils.keywords.fetch({ url: aNode.uri });
- Assert.equal(entry.postData, aExpected.postData);
- break;
- }
- case "charset":
- let testURI = NetUtil.newURI(aNode.uri);
- do_check_eq((yield PlacesUtils.getCharsetForURI(testURI)), aExpected.charset);
- break;
- case "feedUrl":
- let livemark = yield PlacesUtils.livemarks.getLivemark({ id: id });
- do_check_eq(livemark.siteURI.spec, aExpected.url);
- do_check_eq(livemark.feedURI.spec, aExpected.feedUrl);
- break;
- case "children":
- let folder = aNode.QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(folder.hasChildren, aExpected.children.length > 0);
- folder.containerOpen = true;
- do_check_eq(folder.childCount, aExpected.children.length);
-
- for (let index = 0; index < aExpected.children.length; index++) {
- yield checkItem(aExpected.children[index], folder.getChild(index));
- }
-
- folder.containerOpen = false;
- break;
- default:
- throw new Error("Unknown property");
- }
- }
- });
-}
diff --git a/toolkit/components/places/tests/unit/test_bookmarks_restore_notification.js b/toolkit/components/places/tests/unit/test_bookmarks_restore_notification.js
deleted file mode 100644
index 2f8022c6b..000000000
--- a/toolkit/components/places/tests/unit/test_bookmarks_restore_notification.js
+++ /dev/null
@@ -1,325 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-Cu.import("resource://gre/modules/BookmarkHTMLUtils.jsm");
-
-/**
- * Tests the bookmarks-restore-* nsIObserver notifications after restoring
- * bookmarks from JSON and HTML. See bug 470314.
- */
-
-// The topics and data passed to nsIObserver.observe() on bookmarks restore
-const NSIOBSERVER_TOPIC_BEGIN = "bookmarks-restore-begin";
-const NSIOBSERVER_TOPIC_SUCCESS = "bookmarks-restore-success";
-const NSIOBSERVER_TOPIC_FAILED = "bookmarks-restore-failed";
-const NSIOBSERVER_DATA_JSON = "json";
-const NSIOBSERVER_DATA_HTML = "html";
-const NSIOBSERVER_DATA_HTML_INIT = "html-initial";
-
-// Bookmarks are added for these URIs
-var uris = [
- "http://example.com/1",
- "http://example.com/2",
- "http://example.com/3",
- "http://example.com/4",
- "http://example.com/5",
-];
-
-/**
- * Adds some bookmarks for the URIs in |uris|.
- */
-function* addBookmarks() {
- for (let url of uris) {
- yield PlacesUtils.bookmarks.insert({
- url: url, parentGuid: PlacesUtils.bookmarks.menuGuid
- })
- }
- checkBookmarksExist();
-}
-
-/**
- * Checks that all of the bookmarks created for |uris| exist. It works by
- * creating one query per URI and then ORing all the queries. The number of
- * results returned should be uris.length.
- */
-function checkBookmarksExist() {
- let hs = PlacesUtils.history;
- let queries = uris.map(function (u) {
- let q = hs.getNewQuery();
- q.uri = uri(u);
- return q;
- });
- let options = hs.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- let root = hs.executeQueries(queries, uris.length, options).root;
- root.containerOpen = true;
- Assert.equal(root.childCount, uris.length);
- root.containerOpen = false;
-}
-
-/**
- * Creates an file in the profile directory.
- *
- * @param aBasename
- * e.g., "foo.txt" in the path /some/long/path/foo.txt
- * @return {Promise}
- * @resolves to an OS.File path
- */
-function promiseFile(aBasename) {
- let path = OS.Path.join(OS.Constants.Path.profileDir, aBasename);
- do_print("opening " + path);
- return OS.File.open(path, { truncate: true })
- .then(aFile => {
- aFile.close();
- return path;
- });
-}
-
-/**
- * Register observers via promiseTopicObserved helper.
- *
- * @param {boolean} expectSuccess pass true when expect a success notification
- * @return {Promise[]}
- */
-function registerObservers(expectSuccess) {
- let promiseBegin = promiseTopicObserved(NSIOBSERVER_TOPIC_BEGIN);
- let promiseResult;
- if (expectSuccess) {
- promiseResult = promiseTopicObserved(NSIOBSERVER_TOPIC_SUCCESS);
- } else {
- promiseResult = promiseTopicObserved(NSIOBSERVER_TOPIC_FAILED);
- }
-
- return [promiseBegin, promiseResult];
-}
-
-/**
- * Check notification results.
- *
- * @param {Promise[]} expectPromises array contain promiseBegin and promiseResult
- * @param {object} expectedData contain data and folderId
- */
-function* checkObservers(expectPromises, expectedData) {
- let [promiseBegin, promiseResult] = expectPromises;
-
- let beginData = (yield promiseBegin)[1];
- Assert.equal(beginData, expectedData.data,
- "Data for current test should be what is expected");
-
- let [resultSubject, resultData] = yield promiseResult;
- Assert.equal(resultData, expectedData.data,
- "Data for current test should be what is expected");
-
- // Make sure folder ID is what is expected. For importing HTML into a
- // folder, this will be an integer, otherwise null.
- if (resultSubject) {
- Assert.equal(aSubject.QueryInterface(Ci.nsISupportsPRInt64).data,
- expectedData.folderId);
- } else {
- Assert.equal(expectedData.folderId, null);
- }
-}
-
-/**
- * Run after every test cases.
- */
-function* teardown(file, begin, success, fail) {
- // On restore failed, file may not exist, so wrap in try-catch.
- try {
- yield OS.File.remove(file, {ignoreAbsent: true});
- } catch (e) {}
-
- // clean up bookmarks
- yield PlacesUtils.bookmarks.eraseEverything();
-}
-
-add_task(function* test_json_restore_normal() {
- // data: the data passed to nsIObserver.observe() corresponding to the test
- // folderId: for HTML restore into a folder, the folder ID to restore into;
- // otherwise, set it to null
- let expectedData = {
- data: NSIOBSERVER_DATA_JSON,
- folderId: null
- }
- let expectPromises = registerObservers(true);
-
- do_print("JSON restore: normal restore should succeed");
- let file = yield promiseFile("bookmarks-test_restoreNotification.json");
- yield addBookmarks();
-
- yield BookmarkJSONUtils.exportToFile(file);
- yield PlacesUtils.bookmarks.eraseEverything();
- try {
- yield BookmarkJSONUtils.importFromFile(file, true);
- } catch (e) {
- do_throw(" Restore should not have failed" + e);
- }
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_json_restore_empty() {
- let expectedData = {
- data: NSIOBSERVER_DATA_JSON,
- folderId: null
- }
- let expectPromises = registerObservers(true);
-
- do_print("JSON restore: empty file should succeed");
- let file = yield promiseFile("bookmarks-test_restoreNotification.json");
- try {
- yield BookmarkJSONUtils.importFromFile(file, true);
- } catch (e) {
- do_throw(" Restore should not have failed" + e);
- }
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_json_restore_nonexist() {
- let expectedData = {
- data: NSIOBSERVER_DATA_JSON,
- folderId: null
- }
- let expectPromises = registerObservers(false);
-
- do_print("JSON restore: nonexistent file should fail");
- let file = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
- file.append("this file doesn't exist because nobody created it 1");
- try {
- yield BookmarkJSONUtils.importFromFile(file, true);
- do_throw(" Restore should have failed");
- } catch (e) {}
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_html_restore_normal() {
- let expectedData = {
- data: NSIOBSERVER_DATA_HTML,
- folderId: null
- }
- let expectPromises = registerObservers(true);
-
- do_print("HTML restore: normal restore should succeed");
- let file = yield promiseFile("bookmarks-test_restoreNotification.html");
- yield addBookmarks();
- yield BookmarkHTMLUtils.exportToFile(file);
- yield PlacesUtils.bookmarks.eraseEverything();
- try {
- BookmarkHTMLUtils.importFromFile(file, false)
- .then(null, do_report_unexpected_exception);
- } catch (e) {
- do_throw(" Restore should not have failed");
- }
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_html_restore_empty() {
- let expectedData = {
- data: NSIOBSERVER_DATA_HTML,
- folderId: null
- }
- let expectPromises = registerObservers(true);
-
- do_print("HTML restore: empty file should succeed");
- let file = yield promiseFile("bookmarks-test_restoreNotification.init.html");
- try {
- BookmarkHTMLUtils.importFromFile(file, false)
- .then(null, do_report_unexpected_exception);
- } catch (e) {
- do_throw(" Restore should not have failed");
- }
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_html_restore_nonexist() {
- let expectedData = {
- data: NSIOBSERVER_DATA_HTML,
- folderId: null
- }
- let expectPromises = registerObservers(false);
-
- do_print("HTML restore: nonexistent file should fail");
- let file = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
- file.append("this file doesn't exist because nobody created it 2");
- try {
- yield BookmarkHTMLUtils.importFromFile(file, false);
- do_throw("Should fail!");
- } catch (e) {}
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_html_init_restore_normal() {
- let expectedData = {
- data: NSIOBSERVER_DATA_HTML_INIT,
- folderId: null
- }
- let expectPromises = registerObservers(true);
-
- do_print("HTML initial restore: normal restore should succeed");
- let file = yield promiseFile("bookmarks-test_restoreNotification.init.html");
- yield addBookmarks();
- yield BookmarkHTMLUtils.exportToFile(file);
- yield PlacesUtils.bookmarks.eraseEverything();
- try {
- BookmarkHTMLUtils.importFromFile(file, true)
- .then(null, do_report_unexpected_exception);
- } catch (e) {
- do_throw(" Restore should not have failed");
- }
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_html_init_restore_empty() {
- let expectedData = {
- data: NSIOBSERVER_DATA_HTML_INIT,
- folderId: null
- }
- let expectPromises = registerObservers(true);
-
- do_print("HTML initial restore: empty file should succeed");
- let file = yield promiseFile("bookmarks-test_restoreNotification.init.html");
- try {
- BookmarkHTMLUtils.importFromFile(file, true)
- .then(null, do_report_unexpected_exception);
- } catch (e) {
- do_throw(" Restore should not have failed");
- }
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
-
-add_task(function* test_html_init_restore_nonexist() {
- let expectedData = {
- data: NSIOBSERVER_DATA_HTML_INIT,
- folderId: null
- }
- let expectPromises = registerObservers(false);
-
- do_print("HTML initial restore: nonexistent file should fail");
- let file = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
- file.append("this file doesn't exist because nobody created it 3");
- try {
- yield BookmarkHTMLUtils.importFromFile(file, true);
- do_throw("Should fail!");
- } catch (e) {}
-
- yield checkObservers(expectPromises, expectedData);
- yield teardown(file);
-});
diff --git a/toolkit/components/places/tests/unit/test_bookmarks_setNullTitle.js b/toolkit/components/places/tests/unit/test_bookmarks_setNullTitle.js
deleted file mode 100644
index 959dfe85f..000000000
--- a/toolkit/components/places/tests/unit/test_bookmarks_setNullTitle.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Both SetItemtitle and insertBookmark should allow for null titles.
- */
-
-const bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-const TEST_URL = "http://www.mozilla.org";
-
-function run_test() {
- // Insert a bookmark with an empty title.
- var itemId = bs.insertBookmark(bs.toolbarFolder,
- uri(TEST_URL),
- bs.DEFAULT_INDEX,
- "");
- // Check returned title is an empty string.
- do_check_eq(bs.getItemTitle(itemId), "");
- // Set title to null.
- bs.setItemTitle(itemId, null);
- // Check returned title is null.
- do_check_eq(bs.getItemTitle(itemId), null);
- // Cleanup.
- bs.removeItem(itemId);
-
- // Insert a bookmark with a null title.
- itemId = bs.insertBookmark(bs.toolbarFolder,
- uri(TEST_URL),
- bs.DEFAULT_INDEX,
- null);
- // Check returned title is null.
- do_check_eq(bs.getItemTitle(itemId), null);
- // Set title to an empty string.
- bs.setItemTitle(itemId, "");
- // Check returned title is an empty string.
- do_check_eq(bs.getItemTitle(itemId), "");
- // Cleanup.
- bs.removeItem(itemId);
-}
diff --git a/toolkit/components/places/tests/unit/test_broken_folderShortcut_result.js b/toolkit/components/places/tests/unit/test_broken_folderShortcut_result.js
deleted file mode 100644
index b67e141e6..000000000
--- a/toolkit/components/places/tests/unit/test_broken_folderShortcut_result.js
+++ /dev/null
@@ -1,79 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, NetUtil.newURI("http://1.moz.org/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, "Bookmark 1"
- );
- let id1 = PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, NetUtil.newURI("place:folder=1234"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, "Shortcut 1"
- );
- let id2 = PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, NetUtil.newURI("place:folder=-1"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, "Shortcut 2"
- );
- PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, NetUtil.newURI("http://2.moz.org/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX, "Bookmark 2"
- );
-
- // Add also a simple visit.
- yield PlacesTestUtils.addVisits(uri(("http://3.moz.org/")));
-
- // Query containing a broken folder shortcuts among results.
- let query = PlacesUtils.history.getNewQuery();
- query.setFolders([PlacesUtils.unfiledBookmarksFolderId], 1);
- let options = PlacesUtils.history.getNewQueryOptions();
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- do_check_eq(root.childCount, 4);
-
- let shortcut = root.getChild(1);
- do_check_eq(shortcut.uri, "place:folder=1234");
- PlacesUtils.asContainer(shortcut);
- shortcut.containerOpen = true;
- do_check_eq(shortcut.childCount, 0);
- shortcut.containerOpen = false;
- // Remove the broken shortcut while the containing result is open.
- PlacesUtils.bookmarks.removeItem(id1);
- do_check_eq(root.childCount, 3);
-
- shortcut = root.getChild(1);
- do_check_eq(shortcut.uri, "place:folder=-1");
- PlacesUtils.asContainer(shortcut);
- shortcut.containerOpen = true;
- do_check_eq(shortcut.childCount, 0);
- shortcut.containerOpen = false;
- // Remove the broken shortcut while the containing result is open.
- PlacesUtils.bookmarks.removeItem(id2);
- do_check_eq(root.childCount, 2);
-
- root.containerOpen = false;
-
- // Broken folder shortcut as root node.
- query = PlacesUtils.history.getNewQuery();
- query.setFolders([1234], 1);
- options = PlacesUtils.history.getNewQueryOptions();
- root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 0);
- root.containerOpen = false;
-
- // Broken folder shortcut as root node with folder=-1.
- query = PlacesUtils.history.getNewQuery();
- query.setFolders([-1], 1);
- options = PlacesUtils.history.getNewQueryOptions();
- root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 0);
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_browserhistory.js b/toolkit/components/places/tests/unit/test_browserhistory.js
deleted file mode 100644
index 5f88c26e3..000000000
--- a/toolkit/components/places/tests/unit/test_browserhistory.js
+++ /dev/null
@@ -1,129 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const TEST_URI = NetUtil.newURI("http://mozilla.com/");
-const TEST_SUBDOMAIN_URI = NetUtil.newURI("http://foobar.mozilla.com/");
-
-add_task(function* test_addPage() {
- yield PlacesTestUtils.addVisits(TEST_URI);
- do_check_eq(1, PlacesUtils.history.hasHistoryEntries);
-});
-
-add_task(function* test_removePage() {
- PlacesUtils.bhistory.removePage(TEST_URI);
- do_check_eq(0, PlacesUtils.history.hasHistoryEntries);
-});
-
-add_task(function* test_removePages() {
- let pages = [];
- for (let i = 0; i < 8; i++) {
- pages.push(NetUtil.newURI(TEST_URI.spec + i));
- }
-
- yield PlacesTestUtils.addVisits(pages.map(uri => ({ uri: uri })));
- // Bookmarked item should not be removed from moz_places.
- const ANNO_INDEX = 1;
- const ANNO_NAME = "testAnno";
- const ANNO_VALUE = "foo";
- const BOOKMARK_INDEX = 2;
- PlacesUtils.annotations.setPageAnnotation(pages[ANNO_INDEX],
- ANNO_NAME, ANNO_VALUE, 0,
- Ci.nsIAnnotationService.EXPIRE_NEVER);
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- pages[BOOKMARK_INDEX],
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test bookmark");
- PlacesUtils.annotations.setPageAnnotation(pages[BOOKMARK_INDEX],
- ANNO_NAME, ANNO_VALUE, 0,
- Ci.nsIAnnotationService.EXPIRE_NEVER);
-
- PlacesUtils.bhistory.removePages(pages, pages.length);
- do_check_eq(0, PlacesUtils.history.hasHistoryEntries);
-
- // Check that the bookmark and its annotation still exist.
- do_check_true(PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId, 0) > 0);
- do_check_eq(PlacesUtils.annotations.getPageAnnotation(pages[BOOKMARK_INDEX], ANNO_NAME),
- ANNO_VALUE);
-
- // Check the annotation on the non-bookmarked page does not exist anymore.
- try {
- PlacesUtils.annotations.getPageAnnotation(pages[ANNO_INDEX], ANNO_NAME);
- do_throw("did not expire expire_never anno on a not bookmarked item");
- } catch (ex) {}
-
- // Cleanup.
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_removePagesByTimeframe() {
- let visits = [];
- let startDate = (Date.now() - 10000) * 1000;
- for (let i = 0; i < 10; i++) {
- visits.push({
- uri: NetUtil.newURI(TEST_URI.spec + i),
- visitDate: startDate + i * 1000
- });
- }
-
- yield PlacesTestUtils.addVisits(visits);
-
- // Delete all pages except the first and the last.
- PlacesUtils.bhistory.removePagesByTimeframe(startDate + 1000, startDate + 8000);
-
- // Check that we have removed the correct pages.
- for (let i = 0; i < 10; i++) {
- do_check_eq(page_in_database(NetUtil.newURI(TEST_URI.spec + i)) == 0,
- i > 0 && i < 9);
- }
-
- // Clear remaining items and check that all pages have been removed.
- PlacesUtils.bhistory.removePagesByTimeframe(startDate, startDate + 9000);
- do_check_eq(0, PlacesUtils.history.hasHistoryEntries);
-});
-
-add_task(function* test_removePagesFromHost() {
- yield PlacesTestUtils.addVisits(TEST_URI);
- PlacesUtils.bhistory.removePagesFromHost("mozilla.com", true);
- do_check_eq(0, PlacesUtils.history.hasHistoryEntries);
-});
-
-add_task(function* test_removePagesFromHost_keepSubdomains() {
- yield PlacesTestUtils.addVisits([{ uri: TEST_URI }, { uri: TEST_SUBDOMAIN_URI }]);
- PlacesUtils.bhistory.removePagesFromHost("mozilla.com", false);
- do_check_eq(1, PlacesUtils.history.hasHistoryEntries);
-});
-
-add_task(function* test_history_clear() {
- yield PlacesTestUtils.clearHistory();
- do_check_eq(0, PlacesUtils.history.hasHistoryEntries);
-});
-
-add_task(function* test_getObservers() {
- // Ensure that getObservers() invalidates the hasHistoryEntries cache.
- yield PlacesTestUtils.addVisits(TEST_URI);
- do_check_eq(1, PlacesUtils.history.hasHistoryEntries);
- // This is just for testing purposes, never do it.
- return new Promise((resolve, reject) => {
- DBConn().executeSimpleSQLAsync("DELETE FROM moz_historyvisits", {
- handleError: function(error) {
- reject(error);
- },
- handleResult: function(result) {
- },
- handleCompletion: function(result) {
- // Just invoking getObservers should be enough to invalidate the cache.
- PlacesUtils.history.getObservers();
- do_check_eq(0, PlacesUtils.history.hasHistoryEntries);
- resolve();
- }
- });
- });
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_bug636917_isLivemark.js b/toolkit/components/places/tests/unit/test_bug636917_isLivemark.js
deleted file mode 100644
index a7ad1257a..000000000
--- a/toolkit/components/places/tests/unit/test_bug636917_isLivemark.js
+++ /dev/null
@@ -1,35 +0,0 @@
-// Test that asking for a livemark in a annotationChanged notification works.
-add_task(function* () {
- let annoPromise = new Promise(resolve => {
- let annoObserver = {
- onItemAnnotationSet(id, name) {
- if (name == PlacesUtils.LMANNO_FEEDURI) {
- PlacesUtils.annotations.removeObserver(this);
- resolve();
- }
- },
- onItemAnnotationRemoved() {},
- onPageAnnotationSet() {},
- onPageAnnotationRemoved() {},
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIAnnotationObserver
- ]),
- };
- PlacesUtils.annotations.addObserver(annoObserver, false);
- });
-
-
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "livemark title"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , index: PlacesUtils.bookmarks.DEFAULT_INDEX
- , siteURI: uri("http://example.com/")
- , feedURI: uri("http://example.com/rdf")
- });
-
- yield annoPromise;
-
- livemark = yield PlacesUtils.livemarks.getLivemark({ guid: livemark.guid });
- Assert.ok(livemark);
- yield PlacesUtils.livemarks.removeLivemark({ guid: livemark.guid });
-});
diff --git a/toolkit/components/places/tests/unit/test_childlessTags.js b/toolkit/components/places/tests/unit/test_childlessTags.js
deleted file mode 100644
index 4c3e38fa4..000000000
--- a/toolkit/components/places/tests/unit/test_childlessTags.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Ensures that removal of a bookmark untags the bookmark if it's no longer
- * contained in any regular, non-tag folders. See bug 444849.
- */
-
-// Add your tests here. Each is an object with a summary string |desc| and a
-// method run() that's called to run the test.
-var tests = [
- {
- desc: "Removing a tagged bookmark should cause the tag to be removed.",
- run: function () {
- print(" Make a bookmark.");
- var bmId = bmsvc.insertBookmark(bmsvc.unfiledBookmarksFolder,
- BOOKMARK_URI,
- bmsvc.DEFAULT_INDEX,
- "test bookmark");
- do_check_true(bmId > 0);
-
- print(" Tag it up.");
- var tags = ["foo", "bar"];
- tagssvc.tagURI(BOOKMARK_URI, tags);
- ensureTagsExist(tags);
-
- print(" Remove the bookmark. The tags should no longer exist.");
- bmsvc.removeItem(bmId);
- ensureTagsExist([]);
- }
- },
-
- {
- desc: "Removing a folder containing a tagged bookmark should cause the " +
- "tag to be removed.",
- run: function () {
- print(" Make a folder.");
- var folderId = bmsvc.createFolder(bmsvc.unfiledBookmarksFolder,
- "test folder",
- bmsvc.DEFAULT_INDEX);
- do_check_true(folderId > 0);
-
- print(" Stick a bookmark in the folder.");
- var bmId = bmsvc.insertBookmark(folderId,
- BOOKMARK_URI,
- bmsvc.DEFAULT_INDEX,
- "test bookmark");
- do_check_true(bmId > 0);
-
- print(" Tag the bookmark.");
- var tags = ["foo", "bar"];
- tagssvc.tagURI(BOOKMARK_URI, tags);
- ensureTagsExist(tags);
-
- print(" Remove the folder. The tags should no longer exist.");
- bmsvc.removeItem(folderId);
- ensureTagsExist([]);
- }
- }
-];
-
-var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-
-var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-
-const BOOKMARK_URI = uri("http://example.com/");
-
-/**
- * Runs a tag query and ensures that the tags returned are those and only those
- * in aTags. aTags may be empty, in which case this function ensures that no
- * tags exist.
- *
- * @param aTags
- * An array of tags (strings)
- */
-function ensureTagsExist(aTags) {
- var query = histsvc.getNewQuery();
- var opts = histsvc.getNewQueryOptions();
- opts.resultType = opts.RESULTS_AS_TAG_QUERY;
- var resultRoot = histsvc.executeQuery(query, opts).root;
-
- // Dupe aTags.
- var tags = aTags.slice(0);
-
- resultRoot.containerOpen = true;
-
- // Ensure that the number of tags returned from the query is the same as the
- // number in |tags|.
- do_check_eq(resultRoot.childCount, tags.length);
-
- // For each tag result from the query, ensure that it's contained in |tags|.
- // Remove the tag from |tags| so that we ensure the sets are equal.
- for (let i = 0; i < resultRoot.childCount; i++) {
- var tag = resultRoot.getChild(i).title;
- var indexOfTag = tags.indexOf(tag);
- do_check_true(indexOfTag >= 0);
- tags.splice(indexOfTag, 1);
- }
-
- resultRoot.containerOpen = false;
-}
-
-function run_test()
-{
- tests.forEach(function (test) {
- print("Running test: " + test.desc);
- test.run();
- });
-}
diff --git a/toolkit/components/places/tests/unit/test_corrupt_telemetry.js b/toolkit/components/places/tests/unit/test_corrupt_telemetry.js
deleted file mode 100644
index cd9e9ec0c..000000000
--- a/toolkit/components/places/tests/unit/test_corrupt_telemetry.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests that history initialization correctly handles a request to forcibly
-// replace the current database.
-
-add_task(function* () {
- let profileDBPath = yield OS.Path.join(OS.Constants.Path.profileDir, "places.sqlite");
- yield OS.File.remove(profileDBPath, {ignoreAbsent: true});
- // Ensure that our database doesn't already exist.
- Assert.ok(!(yield OS.File.exists(profileDBPath)), "places.sqlite shouldn't exist");
- let dir = yield OS.File.getCurrentDirectory();
- let src = OS.Path.join(dir, "corruptDB.sqlite");
- yield OS.File.copy(src, profileDBPath);
- Assert.ok(yield OS.File.exists(profileDBPath), "places.sqlite should exist");
-
- let count = Services.telemetry
- .getHistogramById("PLACES_DATABASE_CORRUPTION_HANDLING_STAGE")
- .snapshot()
- .counts[3];
- Assert.equal(count, 0, "There should be no telemetry");
-
- do_check_eq(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CORRUPT);
-
- count = Services.telemetry
- .getHistogramById("PLACES_DATABASE_CORRUPTION_HANDLING_STAGE")
- .snapshot()
- .counts[3];
- Assert.equal(count, 1, "Telemetry should have been added");
-});
diff --git a/toolkit/components/places/tests/unit/test_crash_476292.js b/toolkit/components/places/tests/unit/test_crash_476292.js
deleted file mode 100644
index 8f0862022..000000000
--- a/toolkit/components/places/tests/unit/test_crash_476292.js
+++ /dev/null
@@ -1,28 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * This tests a crash during startup found in bug 476292 that was caused by
- * getting the bookmarks service during nsNavHistory::Init when the bookmarks
- * service was created before the history service was.
- */
-
-function run_test()
-{
- // First, we need to move our old database file into our test profile
- // directory. This will trigger DATABASE_STATUS_UPGRADED (CREATE is not
- // sufficient since there will be no entries to update frecencies for, which
- // causes us to get the bookmarks service in the first place).
- let dbFile = do_get_file("bug476292.sqlite");
- let profD = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties).
- get(NS_APP_USER_PROFILE_50_DIR, Ci.nsIFile);
- dbFile.copyTo(profD, "places.sqlite");
-
- // Now get the bookmarks service. This will crash when the bug exists.
- Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-}
diff --git a/toolkit/components/places/tests/unit/test_database_replaceOnStartup.js b/toolkit/components/places/tests/unit/test_database_replaceOnStartup.js
deleted file mode 100644
index e83d0fdae..000000000
--- a/toolkit/components/places/tests/unit/test_database_replaceOnStartup.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests that history initialization correctly handles a request to forcibly
-// replace the current database.
-
-function run_test() {
- // Ensure that our database doesn't already exist.
- let dbFile = gProfD.clone();
- dbFile.append("places.sqlite");
- do_check_false(dbFile.exists());
-
- dbFile = gProfD.clone();
- dbFile.append("places.sqlite.corrupt");
- do_check_false(dbFile.exists());
-
- let file = do_get_file("default.sqlite");
- file.copyToFollowingLinks(gProfD, "places.sqlite");
- file = gProfD.clone();
- file.append("places.sqlite");
-
- // Create some unique stuff to check later.
- let db = Services.storage.openUnsharedDatabase(file);
- db.executeSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)");
- db.close();
-
- Services.prefs.setBoolPref("places.database.replaceOnStartup", true);
- do_check_eq(PlacesUtils.history.databaseStatus,
- PlacesUtils.history.DATABASE_STATUS_CORRUPT);
-
- dbFile = gProfD.clone();
- dbFile.append("places.sqlite");
- do_check_true(dbFile.exists());
-
- // Check the new database is really a new one.
- db = Services.storage.openUnsharedDatabase(file);
- try {
- db.executeSimpleSQL("DELETE * FROM test");
- do_throw("The new database should not have our unique content");
- } catch (ex) {}
- db.close();
-
- dbFile = gProfD.clone();
- dbFile.append("places.sqlite.corrupt");
- do_check_true(dbFile.exists());
-}
diff --git a/toolkit/components/places/tests/unit/test_download_history.js b/toolkit/components/places/tests/unit/test_download_history.js
deleted file mode 100644
index 643360b20..000000000
--- a/toolkit/components/places/tests/unit/test_download_history.js
+++ /dev/null
@@ -1,283 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests the nsIDownloadHistory Places implementation.
- */
-
-XPCOMUtils.defineLazyServiceGetter(this, "gDownloadHistory",
- "@mozilla.org/browser/download-history;1",
- "nsIDownloadHistory");
-
-const DOWNLOAD_URI = NetUtil.newURI("http://www.example.com/");
-const REFERRER_URI = NetUtil.newURI("http://www.example.org/");
-const PRIVATE_URI = NetUtil.newURI("http://www.example.net/");
-
-/**
- * Waits for the first visit notification to be received.
- *
- * @param aCallback
- * Callback function to be called with the same arguments of onVisit.
- */
-function waitForOnVisit(aCallback) {
- let historyObserver = {
- __proto__: NavHistoryObserver.prototype,
- onVisit: function HO_onVisit() {
- PlacesUtils.history.removeObserver(this);
- aCallback.apply(null, arguments);
- }
- };
- PlacesUtils.history.addObserver(historyObserver, false);
-}
-
-/**
- * Waits for the first onDeleteURI notification to be received.
- *
- * @param aCallback
- * Callback function to be called with the same arguments of onDeleteURI.
- */
-function waitForOnDeleteURI(aCallback) {
- let historyObserver = {
- __proto__: NavHistoryObserver.prototype,
- onDeleteURI: function HO_onDeleteURI() {
- PlacesUtils.history.removeObserver(this);
- aCallback.apply(null, arguments);
- }
- };
- PlacesUtils.history.addObserver(historyObserver, false);
-}
-
-/**
- * Waits for the first onDeleteVisits notification to be received.
- *
- * @param aCallback
- * Callback function to be called with the same arguments of onDeleteVisits.
- */
-function waitForOnDeleteVisits(aCallback) {
- let historyObserver = {
- __proto__: NavHistoryObserver.prototype,
- onDeleteVisits: function HO_onDeleteVisits() {
- PlacesUtils.history.removeObserver(this);
- aCallback.apply(null, arguments);
- }
- };
- PlacesUtils.history.addObserver(historyObserver, false);
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-add_test(function test_dh_is_from_places()
-{
- // Test that this nsIDownloadHistory is the one places implements.
- do_check_true(gDownloadHistory instanceof Ci.mozIAsyncHistory);
-
- run_next_test();
-});
-
-add_test(function test_dh_addRemoveDownload()
-{
- waitForOnVisit(function DHAD_onVisit(aURI) {
- do_check_true(aURI.equals(DOWNLOAD_URI));
-
- // Verify that the URI is already available in results at this time.
- do_check_true(!!page_in_database(DOWNLOAD_URI));
-
- waitForOnDeleteURI(function DHRAD_onDeleteURI(aDeletedURI) {
- do_check_true(aDeletedURI.equals(DOWNLOAD_URI));
-
- // Verify that the URI is already available in results at this time.
- do_check_false(!!page_in_database(DOWNLOAD_URI));
-
- run_next_test();
- });
- gDownloadHistory.removeAllDownloads();
- });
-
- gDownloadHistory.addDownload(DOWNLOAD_URI, null, Date.now() * 1000);
-});
-
-add_test(function test_dh_addMultiRemoveDownload()
-{
- PlacesTestUtils.addVisits({
- uri: DOWNLOAD_URI,
- transition: TRANSITION_TYPED
- }).then(function () {
- waitForOnVisit(function DHAD_onVisit(aURI) {
- do_check_true(aURI.equals(DOWNLOAD_URI));
- do_check_true(!!page_in_database(DOWNLOAD_URI));
-
- waitForOnDeleteVisits(function DHRAD_onDeleteVisits(aDeletedURI) {
- do_check_true(aDeletedURI.equals(DOWNLOAD_URI));
- do_check_true(!!page_in_database(DOWNLOAD_URI));
-
- PlacesTestUtils.clearHistory().then(run_next_test);
- });
- gDownloadHistory.removeAllDownloads();
- });
-
- gDownloadHistory.addDownload(DOWNLOAD_URI, null, Date.now() * 1000);
- });
-});
-
-add_test(function test_dh_addBookmarkRemoveDownload()
-{
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- DOWNLOAD_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "A bookmark");
- waitForOnVisit(function DHAD_onVisit(aURI) {
- do_check_true(aURI.equals(DOWNLOAD_URI));
- do_check_true(!!page_in_database(DOWNLOAD_URI));
-
- waitForOnDeleteVisits(function DHRAD_onDeleteVisits(aDeletedURI) {
- do_check_true(aDeletedURI.equals(DOWNLOAD_URI));
- do_check_true(!!page_in_database(DOWNLOAD_URI));
-
- PlacesTestUtils.clearHistory().then(run_next_test);
- });
- gDownloadHistory.removeAllDownloads();
- });
-
- gDownloadHistory.addDownload(DOWNLOAD_URI, null, Date.now() * 1000);
-});
-
-add_test(function test_dh_addDownload_referrer()
-{
- waitForOnVisit(function DHAD_prepareReferrer(aURI, aVisitID) {
- do_check_true(aURI.equals(REFERRER_URI));
- let referrerVisitId = aVisitID;
-
- waitForOnVisit(function DHAD_onVisit(aVisitedURI, unused, unused2, unused3,
- aReferringID) {
- do_check_true(aVisitedURI.equals(DOWNLOAD_URI));
- do_check_eq(aReferringID, referrerVisitId);
-
- // Verify that the URI is already available in results at this time.
- do_check_true(!!page_in_database(DOWNLOAD_URI));
-
- PlacesTestUtils.clearHistory().then(run_next_test);
- });
-
- gDownloadHistory.addDownload(DOWNLOAD_URI, REFERRER_URI, Date.now() * 1000);
- });
-
- // Note that we don't pass the optional callback argument here because we must
- // ensure that we receive the onVisit notification before we call addDownload.
- PlacesUtils.asyncHistory.updatePlaces({
- uri: REFERRER_URI,
- visits: [{
- transitionType: Ci.nsINavHistoryService.TRANSITION_TYPED,
- visitDate: Date.now() * 1000
- }]
- });
-});
-
-add_test(function test_dh_addDownload_disabledHistory()
-{
- waitForOnVisit(function DHAD_onVisit(aURI) {
- // We should only receive the notification for the non-private URI. This
- // test is based on the assumption that visit notifications are received in
- // the same order of the addDownload calls, which is currently true because
- // database access is serialized on the same worker thread.
- do_check_true(aURI.equals(DOWNLOAD_URI));
-
- do_check_true(!!page_in_database(DOWNLOAD_URI));
- do_check_false(!!page_in_database(PRIVATE_URI));
-
- PlacesTestUtils.clearHistory().then(run_next_test);
- });
-
- Services.prefs.setBoolPref("places.history.enabled", false);
- gDownloadHistory.addDownload(PRIVATE_URI, REFERRER_URI, Date.now() * 1000);
-
- // The addDownload functions calls CanAddURI synchronously, thus we can set
- // the preference back to true immediately (not all apps enable places by
- // default).
- Services.prefs.setBoolPref("places.history.enabled", true);
- gDownloadHistory.addDownload(DOWNLOAD_URI, REFERRER_URI, Date.now() * 1000);
-});
-
-/**
- * Tests that nsIDownloadHistory::AddDownload saves the additional download
- * details if the optional destination URL is specified.
- */
-add_test(function test_dh_details()
-{
- const REMOTE_URI = NetUtil.newURI("http://localhost/");
- const SOURCE_URI = NetUtil.newURI("http://example.com/test_dh_details");
- const DEST_FILE_NAME = "dest.txt";
-
- // We must build a real, valid file URI for the destination.
- let destFileUri = NetUtil.newURI(FileUtils.getFile("TmpD", [DEST_FILE_NAME]));
-
- let titleSet = false;
- let destinationFileUriSet = false;
- let destinationFileNameSet = false;
-
- function checkFinished()
- {
- if (titleSet && destinationFileUriSet && destinationFileNameSet) {
- PlacesUtils.annotations.removeObserver(annoObserver);
- PlacesUtils.history.removeObserver(historyObserver);
-
- PlacesTestUtils.clearHistory().then(run_next_test);
- }
- }
-
- let annoObserver = {
- onPageAnnotationSet: function AO_onPageAnnotationSet(aPage, aName)
- {
- if (aPage.equals(SOURCE_URI)) {
- let value = PlacesUtils.annotations.getPageAnnotation(aPage, aName);
- switch (aName)
- {
- case "downloads/destinationFileURI":
- destinationFileUriSet = true;
- do_check_eq(value, destFileUri.spec);
- break;
- case "downloads/destinationFileName":
- destinationFileNameSet = true;
- do_check_eq(value, DEST_FILE_NAME);
- break;
- }
- checkFinished();
- }
- },
- onItemAnnotationSet: function() {},
- onPageAnnotationRemoved: function() {},
- onItemAnnotationRemoved: function() {}
- }
-
- let historyObserver = {
- onBeginUpdateBatch: function() {},
- onEndUpdateBatch: function() {},
- onVisit: function() {},
- onTitleChanged: function HO_onTitleChanged(aURI, aPageTitle)
- {
- if (aURI.equals(SOURCE_URI)) {
- titleSet = true;
- do_check_eq(aPageTitle, DEST_FILE_NAME);
- checkFinished();
- }
- },
- onDeleteURI: function() {},
- onClearHistory: function() {},
- onPageChanged: function() {},
- onDeleteVisits: function() {}
- };
-
- PlacesUtils.annotations.addObserver(annoObserver, false);
- PlacesUtils.history.addObserver(historyObserver, false);
-
- // Both null values and remote URIs should not cause errors.
- gDownloadHistory.addDownload(SOURCE_URI, null, Date.now() * 1000);
- gDownloadHistory.addDownload(SOURCE_URI, null, Date.now() * 1000, null);
- gDownloadHistory.addDownload(SOURCE_URI, null, Date.now() * 1000, REMOTE_URI);
-
- // Valid local file URIs should cause the download details to be saved.
- gDownloadHistory.addDownload(SOURCE_URI, null, Date.now() * 1000,
- destFileUri);
-});
diff --git a/toolkit/components/places/tests/unit/test_frecency.js b/toolkit/components/places/tests/unit/test_frecency.js
deleted file mode 100644
index a04befe00..000000000
--- a/toolkit/components/places/tests/unit/test_frecency.js
+++ /dev/null
@@ -1,294 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test for bug 406358 to make sure frecency works for empty input/search, but
- * this also tests for non-empty inputs as well. Because the interactions among
- * *DIFFERENT* visit counts and visit dates is not well defined, this test
- * holds one of the two values constant when modifying the other.
- *
- * Also test bug 419068 to make sure tagged pages don't necessarily have to be
- * first in the results.
- *
- * Also test bug 426166 to make sure that the results of autocomplete searches
- * are stable. Note that failures of this test will be intermittent by nature
- * since we are testing to make sure that the unstable sort algorithm used
- * by SQLite is not changing the order of the results on us.
- */
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-function ensure_results(uris, searchTerm)
-{
- PlacesTestUtils.promiseAsyncUpdates()
- .then(() => ensure_results_internal(uris, searchTerm));
-}
-
-function ensure_results_internal(uris, searchTerm)
-{
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput(["unifiedcomplete"]);
-
- controller.input = input;
-
- var numSearchesStarted = 0;
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function() {
- do_check_eq(numSearchesStarted, 1);
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- do_check_eq(controller.matchCount, uris.length);
- for (var i=0; i<controller.matchCount; i++) {
- do_check_eq(controller.getValueAt(i), uris[i].spec);
- }
-
- deferEnsureResults.resolve();
- };
-
- controller.startSearch(searchTerm);
-}
-
-// Get history service
-try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
- var bhist = histsvc.QueryInterface(Ci.nsIBrowserHistory);
- var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
- var bmksvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-} catch (ex) {
- do_throw("Could not get history service\n");
-}
-
-function* task_setCountDate(aURI, aCount, aDate)
-{
- // We need visits so that frecency can be computed over multiple visits
- let visits = [];
- for (let i = 0; i < aCount; i++) {
- visits.push({ uri: aURI, visitDate: aDate, transition: TRANSITION_TYPED });
- }
- yield PlacesTestUtils.addVisits(visits);
-}
-
-function setBookmark(aURI)
-{
- bmksvc.insertBookmark(bmksvc.bookmarksMenuFolder, aURI, -1, "bleh");
-}
-
-function tagURI(aURI, aTags) {
- bmksvc.insertBookmark(bmksvc.unfiledBookmarksFolder, aURI,
- bmksvc.DEFAULT_INDEX, "bleh");
- tagssvc.tagURI(aURI, aTags);
-}
-
-var uri1 = uri("http://site.tld/1");
-var uri2 = uri("http://site.tld/2");
-var uri3 = uri("http://aaaaaaaaaa/1");
-var uri4 = uri("http://aaaaaaaaaa/2");
-
-// d1 is younger (should show up higher) than d2 (PRTime is in usecs not msec)
-// Make sure the dates fall into different frecency buckets
-var d1 = new Date(Date.now() - 1000 * 60 * 60) * 1000;
-var d2 = new Date(Date.now() - 1000 * 60 * 60 * 24 * 10) * 1000;
-// c1 is larger (should show up higher) than c2
-var c1 = 10;
-var c2 = 1;
-
-var tests = [
-// test things without a search term
-function*() {
- print("TEST-INFO | Test 0: same count, different date");
- yield task_setCountDate(uri1, c1, d1);
- yield task_setCountDate(uri2, c1, d2);
- tagURI(uri1, ["site"]);
- ensure_results([uri1, uri2], "");
-},
-function*() {
- print("TEST-INFO | Test 1: same count, different date");
- yield task_setCountDate(uri1, c1, d2);
- yield task_setCountDate(uri2, c1, d1);
- tagURI(uri1, ["site"]);
- ensure_results([uri2, uri1], "");
-},
-function*() {
- print("TEST-INFO | Test 2: different count, same date");
- yield task_setCountDate(uri1, c1, d1);
- yield task_setCountDate(uri2, c2, d1);
- tagURI(uri1, ["site"]);
- ensure_results([uri1, uri2], "");
-},
-function*() {
- print("TEST-INFO | Test 3: different count, same date");
- yield task_setCountDate(uri1, c2, d1);
- yield task_setCountDate(uri2, c1, d1);
- tagURI(uri1, ["site"]);
- ensure_results([uri2, uri1], "");
-},
-
-// test things with a search term
-function*() {
- print("TEST-INFO | Test 4: same count, different date");
- yield task_setCountDate(uri1, c1, d1);
- yield task_setCountDate(uri2, c1, d2);
- tagURI(uri1, ["site"]);
- ensure_results([uri1, uri2], "site");
-},
-function*() {
- print("TEST-INFO | Test 5: same count, different date");
- yield task_setCountDate(uri1, c1, d2);
- yield task_setCountDate(uri2, c1, d1);
- tagURI(uri1, ["site"]);
- ensure_results([uri2, uri1], "site");
-},
-function*() {
- print("TEST-INFO | Test 6: different count, same date");
- yield task_setCountDate(uri1, c1, d1);
- yield task_setCountDate(uri2, c2, d1);
- tagURI(uri1, ["site"]);
- ensure_results([uri1, uri2], "site");
-},
-function*() {
- print("TEST-INFO | Test 7: different count, same date");
- yield task_setCountDate(uri1, c2, d1);
- yield task_setCountDate(uri2, c1, d1);
- tagURI(uri1, ["site"]);
- ensure_results([uri2, uri1], "site");
-},
-// There are multiple tests for 8, hence the multiple functions
-// Bug 426166 section
-function*() {
- print("TEST-INFO | Test 8.1a: same count, same date");
- setBookmark(uri3);
- setBookmark(uri4);
- ensure_results([uri4, uri3], "a");
-},
-function*() {
- print("TEST-INFO | Test 8.1b: same count, same date");
- setBookmark(uri3);
- setBookmark(uri4);
- ensure_results([uri4, uri3], "aa");
-},
-function*() {
- print("TEST-INFO | Test 8.2: same count, same date");
- setBookmark(uri3);
- setBookmark(uri4);
- ensure_results([uri4, uri3], "aaa");
-},
-function*() {
- print("TEST-INFO | Test 8.3: same count, same date");
- setBookmark(uri3);
- setBookmark(uri4);
- ensure_results([uri4, uri3], "aaaa");
-},
-function*() {
- print("TEST-INFO | Test 8.4: same count, same date");
- setBookmark(uri3);
- setBookmark(uri4);
- ensure_results([uri4, uri3], "aaa");
-},
-function*() {
- print("TEST-INFO | Test 8.5: same count, same date");
- setBookmark(uri3);
- setBookmark(uri4);
- ensure_results([uri4, uri3], "aa");
-},
-function*() {
- print("TEST-INFO | Test 8.6: same count, same date");
- setBookmark(uri3);
- setBookmark(uri4);
- ensure_results([uri4, uri3], "a");
-}
-];
-
-/**
- * This deferred object contains a promise that is resolved when the
- * ensure_results_internal function has finished its execution.
- */
-var deferEnsureResults;
-
-add_task(function* test_frecency()
-{
- // Disable autoFill for this test.
- Services.prefs.setBoolPref("browser.urlbar.autoFill", false);
- do_register_cleanup(() => Services.prefs.clearUserPref("browser.urlbar.autoFill"));
- // always search in history + bookmarks, no matter what the default is
- var prefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-
- prefs.setBoolPref("browser.urlbar.suggest.history", true);
- prefs.setBoolPref("browser.urlbar.suggest.bookmark", true);
- prefs.setBoolPref("browser.urlbar.suggest.openpage", false);
- for (let test of tests) {
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-
- deferEnsureResults = Promise.defer();
- yield test();
- yield deferEnsureResults.promise;
- }
- for (let type of ["history", "bookmark", "openpage"]) {
- prefs.clearUserPref("browser.urlbar.suggest." + type);
- }
-});
diff --git a/toolkit/components/places/tests/unit/test_frecency_observers.js b/toolkit/components/places/tests/unit/test_frecency_observers.js
deleted file mode 100644
index 7fadd4ae9..000000000
--- a/toolkit/components/places/tests/unit/test_frecency_observers.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test() {
- run_next_test();
-}
-
-// Each of these tests a path that triggers a frecency update. Together they
-// hit all sites that update a frecency.
-
-// InsertVisitedURIs::UpdateFrecency and History::InsertPlace
-add_task(function* test_InsertVisitedURIs_UpdateFrecency_and_History_InsertPlace() {
- // InsertPlace is at the end of a path that UpdateFrecency is also on, so kill
- // two birds with one stone and expect two notifications. Trigger the path by
- // adding a download.
- let uri = NetUtil.newURI("http://example.com/a");
- Cc["@mozilla.org/browser/download-history;1"].
- getService(Ci.nsIDownloadHistory).
- addDownload(uri);
- yield Promise.all([onFrecencyChanged(uri), onFrecencyChanged(uri)]);
-});
-
-// nsNavHistory::UpdateFrecency
-add_task(function* test_nsNavHistory_UpdateFrecency() {
- let bm = PlacesUtils.bookmarks;
- let uri = NetUtil.newURI("http://example.com/b");
- bm.insertBookmark(bm.unfiledBookmarksFolder, uri,
- Ci.nsINavBookmarksService.DEFAULT_INDEX, "test");
- yield onFrecencyChanged(uri);
-});
-
-// nsNavHistory::invalidateFrecencies for particular pages
-add_task(function* test_nsNavHistory_invalidateFrecencies_somePages() {
- let uri = NetUtil.newURI("http://test-nsNavHistory-invalidateFrecencies-somePages.com/");
- // Bookmarking the URI is enough to add it to moz_places, and importantly, it
- // means that removePagesFromHost doesn't remove it from moz_places, so its
- // frecency is able to be changed.
- let bm = PlacesUtils.bookmarks;
- bm.insertBookmark(bm.unfiledBookmarksFolder, uri,
- Ci.nsINavBookmarksService.DEFAULT_INDEX, "test");
- PlacesUtils.history.removePagesFromHost(uri.host, false);
- yield onFrecencyChanged(uri);
-});
-
-// nsNavHistory::invalidateFrecencies for all pages
-add_task(function* test_nsNavHistory_invalidateFrecencies_allPages() {
- yield Promise.all([onManyFrecenciesChanged(), PlacesTestUtils.clearHistory()]);
-});
-
-// nsNavHistory::DecayFrecency and nsNavHistory::FixInvalidFrecencies
-add_task(function* test_nsNavHistory_DecayFrecency_and_nsNavHistory_FixInvalidFrecencies() {
- // FixInvalidFrecencies is at the end of a path that DecayFrecency is also on,
- // so expect two notifications. Trigger the path by making nsNavHistory
- // observe the idle-daily notification.
- PlacesUtils.history.QueryInterface(Ci.nsIObserver).
- observe(null, "idle-daily", "");
- yield Promise.all([onManyFrecenciesChanged(), onManyFrecenciesChanged()]);
-});
-
-function onFrecencyChanged(expectedURI) {
- let deferred = Promise.defer();
- let obs = new NavHistoryObserver();
- obs.onFrecencyChanged =
- (uri, newFrecency, guid, hidden, visitDate) => {
- PlacesUtils.history.removeObserver(obs);
- do_check_true(!!uri);
- do_check_true(uri.equals(expectedURI));
- deferred.resolve();
- };
- PlacesUtils.history.addObserver(obs, false);
- return deferred.promise;
-}
-
-function onManyFrecenciesChanged() {
- let deferred = Promise.defer();
- let obs = new NavHistoryObserver();
- obs.onManyFrecenciesChanged = () => {
- PlacesUtils.history.removeObserver(obs);
- do_check_true(true);
- deferred.resolve();
- };
- PlacesUtils.history.addObserver(obs, false);
- return deferred.promise;
-}
diff --git a/toolkit/components/places/tests/unit/test_frecency_zero_updated.js b/toolkit/components/places/tests/unit/test_frecency_zero_updated.js
deleted file mode 100644
index e60030ca5..000000000
--- a/toolkit/components/places/tests/unit/test_frecency_zero_updated.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests a zero frecency is correctly updated when inserting new valid visits.
-
-function run_test()
-{
- run_next_test()
-}
-
-add_task(function* ()
-{
- const TEST_URI = NetUtil.newURI("http://example.com/");
- let id = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- TEST_URI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "A title");
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_check_true(frecencyForUrl(TEST_URI) > 0);
-
- // Removing the bookmark should leave an orphan page with zero frecency.
- // Note this would usually be expired later by expiration.
- PlacesUtils.bookmarks.removeItem(id);
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_check_eq(frecencyForUrl(TEST_URI), 0);
-
- // Now add a valid visit to the page, frecency should increase.
- yield PlacesTestUtils.addVisits({ uri: TEST_URI });
- do_check_true(frecencyForUrl(TEST_URI) > 0);
-});
diff --git a/toolkit/components/places/tests/unit/test_getChildIndex.js b/toolkit/components/places/tests/unit/test_getChildIndex.js
deleted file mode 100644
index 4cf164d45..000000000
--- a/toolkit/components/places/tests/unit/test_getChildIndex.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
- * vim:set ts=2 sw=2 sts=2 et:
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * Tests nsNavHistoryContainerResultNode::GetChildIndex(aNode) functionality.
- */
-
-function run_test() {
- // Add a bookmark to the menu.
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
- uri("http://test.mozilla.org/bookmark/"),
- Ci.nsINavBookmarksService.DEFAULT_INDEX,
- "Test bookmark");
-
- // Add a bookmark to unfiled folder.
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri("http://test.mozilla.org/unfiled/"),
- Ci.nsINavBookmarksService.DEFAULT_INDEX,
- "Unfiled bookmark");
-
- // Get the unfiled bookmark node.
- let unfiledNode = getNodeAt(PlacesUtils.unfiledBookmarksFolderId, 0);
- if (!unfiledNode)
- do_throw("Unable to find bookmark in hierarchy!");
- do_check_eq(unfiledNode.title, "Unfiled bookmark");
-
- let hs = PlacesUtils.history;
- let query = hs.getNewQuery();
- query.setFolders([PlacesUtils.bookmarksMenuFolderId], 1);
- let options = hs.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- let root = hs.executeQuery(query, options).root;
- root.containerOpen = true;
-
- // Check functionality for proper nodes.
- for (let i = 0; i < root.childCount; i++) {
- let node = root.getChild(i);
- print("Now testing: " + node.title);
- do_check_eq(root.getChildIndex(node), i);
- }
-
- // Now search for an invalid node and expect an exception.
- try {
- root.getChildIndex(unfiledNode);
- do_throw("Searching for an invalid node should have thrown.");
- } catch (ex) {
- print("We correctly got an exception.");
- }
-
- root.containerOpen = false;
-}
-
-function getNodeAt(aFolderId, aIndex) {
- let hs = PlacesUtils.history;
- let query = hs.getNewQuery();
- query.setFolders([aFolderId], 1);
- let options = hs.getNewQueryOptions();
- options.queryType = options.QUERY_TYPE_BOOKMARKS;
- let root = hs.executeQuery(query, options).root;
- root.containerOpen = true;
- if (root.childCount < aIndex)
- do_throw("Not enough children to find bookmark!");
- let node = root.getChild(aIndex);
- root.containerOpen = false;
- return node;
-}
diff --git a/toolkit/components/places/tests/unit/test_getPlacesInfo.js b/toolkit/components/places/tests/unit/test_getPlacesInfo.js
deleted file mode 100644
index 3dfecb934..000000000
--- a/toolkit/components/places/tests/unit/test_getPlacesInfo.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function promiseGetPlacesInfo(aPlacesIdentifiers) {
- let deferred = Promise.defer();
- PlacesUtils.asyncHistory.getPlacesInfo(aPlacesIdentifiers, {
- _results: [],
- _errors: [],
-
- handleResult: function handleResult(aPlaceInfo) {
- this._results.push(aPlaceInfo);
- },
- handleError: function handleError(aResultCode, aPlaceInfo) {
- this._errors.push({ resultCode: aResultCode, info: aPlaceInfo });
- },
- handleCompletion: function handleCompletion() {
- deferred.resolve({ errors: this._errors, results: this._results });
- }
- });
-
- return deferred.promise;
-}
-
-function ensurePlacesInfoObjectsAreEqual(a, b) {
- do_check_true(a.uri.equals(b.uri));
- do_check_eq(a.title, b.title);
- do_check_eq(a.guid, b.guid);
- do_check_eq(a.placeId, b.placeId);
-}
-
-function* test_getPlacesInfoExistentPlace() {
- let testURI = NetUtil.newURI("http://www.example.tld");
- yield PlacesTestUtils.addVisits(testURI);
-
- let getPlacesInfoResult = yield promiseGetPlacesInfo([testURI]);
- do_check_eq(getPlacesInfoResult.results.length, 1);
- do_check_eq(getPlacesInfoResult.errors.length, 0);
-
- let placeInfo = getPlacesInfoResult.results[0];
- do_check_true(placeInfo instanceof Ci.mozIPlaceInfo);
-
- do_check_true(placeInfo.uri.equals(testURI));
- do_check_eq(placeInfo.title, "test visit for " + testURI.spec);
- do_check_true(placeInfo.guid.length > 0);
- do_check_eq(placeInfo.visits, null);
-}
-add_task(test_getPlacesInfoExistentPlace);
-
-function* test_getPlacesInfoNonExistentPlace() {
- let testURI = NetUtil.newURI("http://www.example_non_existent.tld");
- let getPlacesInfoResult = yield promiseGetPlacesInfo(testURI);
- do_check_eq(getPlacesInfoResult.results.length, 0);
- do_check_eq(getPlacesInfoResult.errors.length, 1);
-}
-add_task(test_getPlacesInfoNonExistentPlace);
-
-function* test_promisedHelper() {
- let uri = NetUtil.newURI("http://www.helper_existent_example.tld");
- yield PlacesTestUtils.addVisits(uri);
- let placeInfo = yield PlacesUtils.promisePlaceInfo(uri);
- do_check_true(placeInfo instanceof Ci.mozIPlaceInfo);
-
- uri = NetUtil.newURI("http://www.helper_non_existent_example.tld");
- try {
- yield PlacesUtils.promisePlaceInfo(uri);
- do_throw("PlacesUtils.promisePlaceInfo should have rejected the promise");
- }
- catch (ex) { }
-}
-add_task(test_promisedHelper);
-
-function* test_infoByGUID() {
- let testURI = NetUtil.newURI("http://www.guid_example.tld");
- yield PlacesTestUtils.addVisits(testURI);
-
- let placeInfoByURI = yield PlacesUtils.promisePlaceInfo(testURI);
- let placeInfoByGUID = yield PlacesUtils.promisePlaceInfo(placeInfoByURI.guid);
- ensurePlacesInfoObjectsAreEqual(placeInfoByURI, placeInfoByGUID);
-}
-add_task(test_infoByGUID);
-
-function* test_invalid_guid() {
- try {
- yield PlacesUtils.promisePlaceInfo("###");
- do_throw("getPlacesInfo should fail for invalid guids")
- }
- catch (ex) { }
-}
-add_task(test_invalid_guid);
-
-function* test_mixed_selection() {
- let placeInfo1, placeInfo2;
- let uri = NetUtil.newURI("http://www.mixed_selection_test_1.tld");
- yield PlacesTestUtils.addVisits(uri);
- placeInfo1 = yield PlacesUtils.promisePlaceInfo(uri);
-
- uri = NetUtil.newURI("http://www.mixed_selection_test_2.tld");
- yield PlacesTestUtils.addVisits(uri);
- placeInfo2 = yield PlacesUtils.promisePlaceInfo(uri);
-
- let getPlacesInfoResult = yield promiseGetPlacesInfo([placeInfo1.uri, placeInfo2.guid]);
- do_check_eq(getPlacesInfoResult.results.length, 2);
- do_check_eq(getPlacesInfoResult.errors.length, 0);
-
- do_check_eq(getPlacesInfoResult.results[0].uri.spec, placeInfo1.uri.spec);
- do_check_eq(getPlacesInfoResult.results[1].guid, placeInfo2.guid);
-}
-add_task(test_mixed_selection);
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_history.js b/toolkit/components/places/tests/unit/test_history.js
deleted file mode 100644
index 8d194cde1..000000000
--- a/toolkit/components/places/tests/unit/test_history.js
+++ /dev/null
@@ -1,184 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get history services
-var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-
-/**
- * Checks to see that a URI is in the database.
- *
- * @param aURI
- * The URI to check.
- * @returns true if the URI is in the DB, false otherwise.
- */
-function uri_in_db(aURI) {
- var options = histsvc.getNewQueryOptions();
- options.maxResults = 1;
- options.resultType = options.RESULTS_AS_URI
- var query = histsvc.getNewQuery();
- query.uri = aURI;
- var result = histsvc.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var cc = root.childCount;
- root.containerOpen = false;
- return (cc == 1);
-}
-
-// main
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- // we have a new profile, so we should have imported bookmarks
- do_check_eq(histsvc.databaseStatus, histsvc.DATABASE_STATUS_CREATE);
-
- // add a visit
- var testURI = uri("http://mozilla.com");
- yield PlacesTestUtils.addVisits(testURI);
-
- // now query for the visit, setting sorting and limit such that
- // we should retrieve only the visit we just added
- var options = histsvc.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- options.maxResults = 1;
- // TODO: using full visit crashes in xpcshell test
- // options.resultType = options.RESULTS_AS_FULL_VISIT;
- options.resultType = options.RESULTS_AS_VISIT;
- var query = histsvc.getNewQuery();
- var result = histsvc.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var cc = root.childCount;
- for (var i=0; i < cc; ++i) {
- var node = root.getChild(i);
- // test node properties in RESULTS_AS_VISIT
- do_check_eq(node.uri, testURI.spec);
- do_check_eq(node.type, Ci.nsINavHistoryResultNode.RESULT_TYPE_URI);
- // TODO: change query type to RESULTS_AS_FULL_VISIT and test this
- // do_check_eq(node.transitionType, histsvc.TRANSITION_TYPED);
- }
- root.containerOpen = false;
-
- // add another visit for the same URI, and a third visit for a different URI
- var testURI2 = uri("http://google.com/");
- yield PlacesTestUtils.addVisits(testURI);
- yield PlacesTestUtils.addVisits(testURI2);
-
- options.maxResults = 5;
- options.resultType = options.RESULTS_AS_URI;
-
- // test minVisits
- query.minVisits = 0;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 2);
- result.root.containerOpen = false;
- query.minVisits = 1;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 2);
- result.root.containerOpen = false;
- query.minVisits = 2;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 1);
- query.minVisits = 3;
- result.root.containerOpen = false;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 0);
- result.root.containerOpen = false;
-
- // test maxVisits
- query.minVisits = -1;
- query.maxVisits = -1;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 2);
- result.root.containerOpen = false;
- query.maxVisits = 0;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 0);
- result.root.containerOpen = false;
- query.maxVisits = 1;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 1);
- result.root.containerOpen = false;
- query.maxVisits = 2;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 2);
- result.root.containerOpen = false;
- query.maxVisits = 3;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 2);
- result.root.containerOpen = false;
-
- // test annotation-based queries
- var annos = Cc["@mozilla.org/browser/annotation-service;1"].
- getService(Ci.nsIAnnotationService);
- annos.setPageAnnotation(uri("http://mozilla.com/"), "testAnno", 0, 0,
- Ci.nsIAnnotationService.EXPIRE_NEVER);
- query.annotation = "testAnno";
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 1);
- do_check_eq(result.root.getChild(0).uri, "http://mozilla.com/");
- result.root.containerOpen = false;
-
- // test annotationIsNot
- query.annotationIsNot = true;
- result = histsvc.executeQuery(query, options);
- result.root.containerOpen = true;
- do_check_eq(result.root.childCount, 1);
- do_check_eq(result.root.getChild(0).uri, "http://google.com/");
- result.root.containerOpen = false;
-
- // By default history is enabled.
- do_check_true(!histsvc.historyDisabled);
-
- // test getPageTitle
- yield PlacesTestUtils.addVisits({ uri: uri("http://example.com"), title: "title" });
- let placeInfo = yield PlacesUtils.promisePlaceInfo(uri("http://example.com"));
- do_check_eq(placeInfo.title, "title");
-
- // query for the visit
- do_check_true(uri_in_db(testURI));
-
- // test for schema changes in bug 373239
- // get direct db connection
- var db = histsvc.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
- var q = "SELECT id FROM moz_bookmarks";
- var statement;
- try {
- statement = db.createStatement(q);
- } catch (ex) {
- do_throw("bookmarks table does not have id field, schema is too old!");
- }
- finally {
- statement.finalize();
- }
-
- // bug 394741 - regressed history text searches
- yield PlacesTestUtils.addVisits(uri("http://mozilla.com"));
- options = histsvc.getNewQueryOptions();
- // options.resultType = options.RESULTS_AS_VISIT;
- query = histsvc.getNewQuery();
- query.searchTerms = "moz";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_true(root.childCount > 0);
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_history_autocomplete_tags.js b/toolkit/components/places/tests/unit/test_history_autocomplete_tags.js
deleted file mode 100644
index a5e0e1cb1..000000000
--- a/toolkit/components/places/tests/unit/test_history_autocomplete_tags.js
+++ /dev/null
@@ -1,185 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var current_test = 0;
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-// Get tagging service
-try {
- var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-} catch (ex) {
- do_throw("Could not get tagging service\n");
-}
-
-function ensure_tag_results(uris, searchTerm)
-{
- print("Searching for '" + searchTerm + "'");
- var controller = Components.classes["@mozilla.org/autocomplete/controller;1"].
- getService(Components.interfaces.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput(["unifiedcomplete"]);
-
- controller.input = input;
-
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- var numSearchesStarted = 0;
- input.onSearchBegin = function() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function() {
- do_check_eq(numSearchesStarted, 1);
- do_check_eq(controller.searchStatus,
- uris.length ?
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH :
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
- do_check_eq(controller.matchCount, uris.length);
- let vals = [];
- for (let i=0; i<controller.matchCount; i++) {
- // Keep the URL for later because order of tag results is undefined
- vals.push(controller.getValueAt(i));
- do_check_eq(controller.getStyleAt(i), "bookmark-tag");
- }
- // Sort the results then check if we have the right items
- vals.sort().forEach((val, i) => do_check_eq(val, uris[i].spec))
-
- if (current_test < (tests.length - 1)) {
- current_test++;
- tests[current_test]();
- }
-
- do_test_finished();
- };
-
- controller.startSearch(searchTerm);
-}
-
-var uri1 = uri("http://site.tld/1/aaa");
-var uri2 = uri("http://site.tld/2/bbb");
-var uri3 = uri("http://site.tld/3/aaa");
-var uri4 = uri("http://site.tld/4/bbb");
-var uri5 = uri("http://site.tld/5/aaa");
-var uri6 = uri("http://site.tld/6/bbb");
-
-var tests = [
- () => ensure_tag_results([uri1, uri4, uri6], "foo"),
- () => ensure_tag_results([uri1], "foo aaa"),
- () => ensure_tag_results([uri4, uri6], "foo bbb"),
- () => ensure_tag_results([uri2, uri4, uri5, uri6], "bar"),
- () => ensure_tag_results([uri5], "bar aaa"),
- () => ensure_tag_results([uri2, uri4, uri6], "bar bbb"),
- () => ensure_tag_results([uri3, uri5, uri6], "cheese"),
- () => ensure_tag_results([uri3, uri5], "chees aaa"),
- () => ensure_tag_results([uri6], "chees bbb"),
- () => ensure_tag_results([uri4, uri6], "fo bar"),
- () => ensure_tag_results([], "fo bar aaa"),
- () => ensure_tag_results([uri4, uri6], "fo bar bbb"),
- () => ensure_tag_results([uri4, uri6], "ba foo"),
- () => ensure_tag_results([], "ba foo aaa"),
- () => ensure_tag_results([uri4, uri6], "ba foo bbb"),
- () => ensure_tag_results([uri5, uri6], "ba chee"),
- () => ensure_tag_results([uri5], "ba chee aaa"),
- () => ensure_tag_results([uri6], "ba chee bbb"),
- () => ensure_tag_results([uri5, uri6], "cheese bar"),
- () => ensure_tag_results([uri5], "cheese bar aaa"),
- () => ensure_tag_results([uri6], "chees bar bbb"),
- () => ensure_tag_results([uri6], "cheese bar foo"),
- () => ensure_tag_results([], "foo bar cheese aaa"),
- () => ensure_tag_results([uri6], "foo bar cheese bbb"),
-];
-
-/**
- * Properly tags a uri adding it to bookmarks.
- *
- * @param aURI
- * The nsIURI to tag.
- * @param aTags
- * The tags to add.
- */
-function tagURI(aURI, aTags) {
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- aURI,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "A title");
- tagssvc.tagURI(aURI, aTags);
-}
-
-/**
- * Test history autocomplete
- */
-function run_test() {
- // always search in history + bookmarks, no matter what the default is
- var prefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
- prefs.setIntPref("browser.urlbar.search.sources", 3);
- prefs.setIntPref("browser.urlbar.default.behavior", 0);
-
- tagURI(uri1, ["foo"]);
- tagURI(uri2, ["bar"]);
- tagURI(uri3, ["cheese"]);
- tagURI(uri4, ["foo bar"]);
- tagURI(uri5, ["bar cheese"]);
- tagURI(uri6, ["foo bar cheese"]);
-
- tests[0]();
-}
diff --git a/toolkit/components/places/tests/unit/test_history_catobs.js b/toolkit/components/places/tests/unit/test_history_catobs.js
deleted file mode 100644
index e0a81d67b..000000000
--- a/toolkit/components/places/tests/unit/test_history_catobs.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* () {
- do_load_manifest("nsDummyObserver.manifest");
-
- let dummyCreated = false;
- let dummyReceivedOnVisit = false;
-
- Services.obs.addObserver(function created() {
- Services.obs.removeObserver(created, "dummy-observer-created");
- dummyCreated = true;
- }, "dummy-observer-created", false);
- Services.obs.addObserver(function visited() {
- Services.obs.removeObserver(visited, "dummy-observer-visited");
- dummyReceivedOnVisit = true;
- }, "dummy-observer-visited", false);
-
- let initialObservers = PlacesUtils.history.getObservers();
-
- // Add a common observer, it should be invoked after the category observer.
- let notificationsPromised = new Promise((resolve, reject) => {
- PlacesUtils.history.addObserver({
- __proto__: NavHistoryObserver.prototype,
- onVisit() {
- let observers = PlacesUtils.history.getObservers();
- Assert.equal(observers.length, initialObservers.length + 1);
-
- // Check the common observer is the last one.
- for (let i = 0; i < initialObservers.length; ++i) {
- Assert.equal(initialObservers[i], observers[i]);
- }
-
- PlacesUtils.history.removeObserver(this);
- observers = PlacesUtils.history.getObservers();
- Assert.equal(observers.length, initialObservers.length);
-
- // Check the category observer has been invoked before this one.
- Assert.ok(dummyCreated);
- Assert.ok(dummyReceivedOnVisit);
- resolve();
- }
- }, false);
- });
-
- // Add a visit.
- yield PlacesTestUtils.addVisits(uri("http://typed.mozilla.org"));
-
- yield notificationsPromised;
-});
diff --git a/toolkit/components/places/tests/unit/test_history_clear.js b/toolkit/components/places/tests/unit/test_history_clear.js
deleted file mode 100644
index 56d34994f..000000000
--- a/toolkit/components/places/tests/unit/test_history_clear.js
+++ /dev/null
@@ -1,169 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var mDBConn = DBConn();
-
-function promiseOnClearHistoryObserved() {
- let deferred = Promise.defer();
-
- let historyObserver = {
- onBeginUpdateBatch: function() {},
- onEndUpdateBatch: function() {},
- onVisit: function() {},
- onTitleChanged: function() {},
- onDeleteURI: function(aURI) {},
- onPageChanged: function() {},
- onDeleteVisits: function() {},
-
- onClearHistory: function() {
- PlacesUtils.history.removeObserver(this, false);
- deferred.resolve();
- },
-
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavHistoryObserver,
- ])
- }
- PlacesUtils.history.addObserver(historyObserver, false);
- return deferred.promise;
-}
-
-// This global variable is a promise object, initialized in run_test and waited
-// upon in the first asynchronous test. It is resolved when the
-// "places-init-complete" notification is received. We cannot initialize it in
-// the asynchronous test, because then it's too late to register the observer.
-var promiseInit;
-
-function run_test() {
- // places-init-complete is notified after run_test, and it will
- // run a first frecency fix through async statements.
- // To avoid random failures we have to run after all of this.
- promiseInit = promiseTopicObserved(PlacesUtils.TOPIC_INIT_COMPLETE);
-
- run_next_test();
-}
-
-add_task(function* test_history_clear()
-{
- yield promiseInit;
-
- yield PlacesTestUtils.addVisits([
- { uri: uri("http://typed.mozilla.org/"),
- transition: TRANSITION_TYPED },
- { uri: uri("http://link.mozilla.org/"),
- transition: TRANSITION_LINK },
- { uri: uri("http://download.mozilla.org/"),
- transition: TRANSITION_DOWNLOAD },
- { uri: uri("http://redir_temp.mozilla.org/"),
- transition: TRANSITION_REDIRECT_TEMPORARY,
- referrer: "http://link.mozilla.org/"},
- { uri: uri("http://redir_perm.mozilla.org/"),
- transition: TRANSITION_REDIRECT_PERMANENT,
- referrer: "http://link.mozilla.org/"},
- ]);
-
- // add a place: bookmark
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri("place:folder=4"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "shortcut");
-
- // Add an expire never annotation
- // Actually expire never annotations are removed as soon as a page is removed
- // from the database, so this should act as a normal visit.
- PlacesUtils.annotations.setPageAnnotation(uri("http://download.mozilla.org/"),
- "never", "never", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-
- // Add a bookmark
- // Bookmarked page should have history cleared and frecency = -1
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- uri("http://typed.mozilla.org/"),
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark");
-
- yield PlacesTestUtils.addVisits([
- { uri: uri("http://typed.mozilla.org/"),
- transition: TRANSITION_BOOKMARK },
- { uri: uri("http://frecency.mozilla.org/"),
- transition: TRANSITION_LINK },
- ]);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- // Clear history and wait for the onClearHistory notification.
- let promiseWaitClearHistory = promiseOnClearHistoryObserved();
- PlacesUtils.history.clear();
- yield promiseWaitClearHistory;
-
- // check browserHistory returns no entries
- do_check_eq(0, PlacesUtils.history.hasHistoryEntries);
-
- yield promiseTopicObserved(PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- // Check that frecency for not cleared items (bookmarks) has been converted
- // to -1.
- stmt = mDBConn.createStatement(
- "SELECT h.id FROM moz_places h WHERE h.frecency > 0 ");
- do_check_false(stmt.executeStep());
- stmt.finalize();
-
- stmt = mDBConn.createStatement(
- `SELECT h.id FROM moz_places h WHERE h.frecency < 0
- AND EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) LIMIT 1`);
- do_check_true(stmt.executeStep());
- stmt.finalize();
-
- // Check that all visit_counts have been brought to 0
- stmt = mDBConn.createStatement(
- "SELECT id FROM moz_places WHERE visit_count <> 0 LIMIT 1");
- do_check_false(stmt.executeStep());
- stmt.finalize();
-
- // Check that history tables are empty
- stmt = mDBConn.createStatement(
- "SELECT * FROM (SELECT id FROM moz_historyvisits LIMIT 1)");
- do_check_false(stmt.executeStep());
- stmt.finalize();
-
- // Check that all moz_places entries except bookmarks and place: have been removed
- stmt = mDBConn.createStatement(
- `SELECT h.id FROM moz_places h WHERE
- url_hash NOT BETWEEN hash('place', 'prefix_lo') AND hash('place', 'prefix_hi')
- AND NOT EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) LIMIT 1`);
- do_check_false(stmt.executeStep());
- stmt.finalize();
-
- // Check that we only have favicons for retained places
- stmt = mDBConn.createStatement(
- `SELECT f.id FROM moz_favicons f WHERE NOT EXISTS
- (SELECT id FROM moz_places WHERE favicon_id = f.id) LIMIT 1`);
- do_check_false(stmt.executeStep());
- stmt.finalize();
-
- // Check that we only have annotations for retained places
- stmt = mDBConn.createStatement(
- `SELECT a.id FROM moz_annos a WHERE NOT EXISTS
- (SELECT id FROM moz_places WHERE id = a.place_id) LIMIT 1`);
- do_check_false(stmt.executeStep());
- stmt.finalize();
-
- // Check that we only have inputhistory for retained places
- stmt = mDBConn.createStatement(
- `SELECT i.place_id FROM moz_inputhistory i WHERE NOT EXISTS
- (SELECT id FROM moz_places WHERE id = i.place_id) LIMIT 1`);
- do_check_false(stmt.executeStep());
- stmt.finalize();
-
- // Check that place:uris have frecency 0
- stmt = mDBConn.createStatement(
- `SELECT h.id FROM moz_places h
- WHERE url_hash BETWEEN hash('place', 'prefix_lo')
- AND hash('place', 'prefix_hi')
- AND h.frecency <> 0 LIMIT 1`);
- do_check_false(stmt.executeStep());
- stmt.finalize();
-});
diff --git a/toolkit/components/places/tests/unit/test_history_notifications.js b/toolkit/components/places/tests/unit/test_history_notifications.js
deleted file mode 100644
index 4e1e635a0..000000000
--- a/toolkit/components/places/tests/unit/test_history_notifications.js
+++ /dev/null
@@ -1,38 +0,0 @@
-const NS_PLACES_INIT_COMPLETE_TOPIC = "places-init-complete";
-const NS_PLACES_DATABASE_LOCKED_TOPIC = "places-database-locked";
-
-add_task(function* () {
- // Create a dummy places.sqlite and open an unshared connection on it
- let db = Services.dirsvc.get('ProfD', Ci.nsIFile);
- db.append("places.sqlite");
- let dbConn = Services.storage.openUnsharedDatabase(db);
- Assert.ok(db.exists(), "The database should have been created");
-
- // We need an exclusive lock on the db
- dbConn.executeSimpleSQL("PRAGMA locking_mode = EXCLUSIVE");
- // Exclusive locking is lazy applied, we need to make a write to activate it
- dbConn.executeSimpleSQL("PRAGMA USER_VERSION = 1");
-
- // Try to create history service while the db is locked
- let promiseLocked = promiseTopicObserved(NS_PLACES_DATABASE_LOCKED_TOPIC);
- Assert.throws(() => Cc["@mozilla.org/browser/nav-history-service;1"]
- .getService(Ci.nsINavHistoryService),
- /NS_ERROR_XPC_GS_RETURNED_FAILURE/);
- yield promiseLocked;
-
- // Close our connection and try to cleanup the file (could fail on Windows)
- dbConn.close();
- if (db.exists()) {
- try {
- db.remove(false);
- } catch (e) {
- do_print("Unable to remove dummy places.sqlite");
- }
- }
-
- // Create history service correctly
- let promiseComplete = promiseTopicObserved(NS_PLACES_INIT_COMPLETE_TOPIC);
- Cc["@mozilla.org/browser/nav-history-service;1"]
- .getService(Ci.nsINavHistoryService);
- yield promiseComplete;
-});
diff --git a/toolkit/components/places/tests/unit/test_history_observer.js b/toolkit/components/places/tests/unit/test_history_observer.js
deleted file mode 100644
index c101cfb61..000000000
--- a/toolkit/components/places/tests/unit/test_history_observer.js
+++ /dev/null
@@ -1,215 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * Generic nsINavHistoryObserver that doesn't implement anything, but provides
- * dummy methods to prevent errors about an object not having a certain method.
- */
-function NavHistoryObserver() {
-}
-NavHistoryObserver.prototype = {
- onBeginUpdateBatch: function() { },
- onEndUpdateBatch: function() { },
- onVisit: function() { },
- onTitleChanged: function() { },
- onDeleteURI: function() { },
- onClearHistory: function() { },
- onPageChanged: function() { },
- onDeleteVisits: function() { },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
-};
-
-/**
- * Registers a one-time history observer for and calls the callback
- * when the specified nsINavHistoryObserver method is called.
- * Returns a promise that is resolved when the callback returns.
- */
-function onNotify(callback) {
- return new Promise(resolve => {
- let obs = new NavHistoryObserver();
- obs[callback.name] = function () {
- PlacesUtils.history.removeObserver(this);
- callback.apply(this, arguments);
- resolve();
- };
- PlacesUtils.history.addObserver(obs, false);
- });
-}
-
-/**
- * Asynchronous task that adds a visit to the history database.
- */
-function* task_add_visit(uri, timestamp, transition) {
- uri = uri || NetUtil.newURI("http://firefox.com/");
- timestamp = timestamp || Date.now() * 1000;
- yield PlacesTestUtils.addVisits({
- uri: uri,
- transition: transition || TRANSITION_TYPED,
- visitDate: timestamp
- });
- return [uri, timestamp];
-}
-
-add_task(function* test_onVisit() {
- let promiseNotify = onNotify(function onVisit(aURI, aVisitID, aTime,
- aSessionID, aReferringID,
- aTransitionType, aGUID,
- aHidden, aVisitCount, aTyped) {
- Assert.ok(aURI.equals(testuri));
- Assert.ok(aVisitID > 0);
- Assert.equal(aTime, testtime);
- Assert.equal(aSessionID, 0);
- Assert.equal(aReferringID, 0);
- Assert.equal(aTransitionType, TRANSITION_TYPED);
- do_check_guid_for_uri(aURI, aGUID);
- Assert.ok(!aHidden);
- Assert.equal(aVisitCount, 1);
- Assert.equal(aTyped, 1);
- });
- let testuri = NetUtil.newURI("http://firefox.com/");
- let testtime = Date.now() * 1000;
- yield task_add_visit(testuri, testtime);
- yield promiseNotify;
-});
-
-add_task(function* test_onVisit() {
- let promiseNotify = onNotify(function onVisit(aURI, aVisitID, aTime,
- aSessionID, aReferringID,
- aTransitionType, aGUID,
- aHidden, aVisitCount, aTyped) {
- Assert.ok(aURI.equals(testuri));
- Assert.ok(aVisitID > 0);
- Assert.equal(aTime, testtime);
- Assert.equal(aSessionID, 0);
- Assert.equal(aReferringID, 0);
- Assert.equal(aTransitionType, TRANSITION_FRAMED_LINK);
- do_check_guid_for_uri(aURI, aGUID);
- Assert.ok(aHidden);
- Assert.equal(aVisitCount, 1);
- Assert.equal(aTyped, 0);
- });
- let testuri = NetUtil.newURI("http://hidden.firefox.com/");
- let testtime = Date.now() * 1000;
- yield task_add_visit(testuri, testtime, TRANSITION_FRAMED_LINK);
- yield promiseNotify;
-});
-
-add_task(function* test_multiple_onVisit() {
- let testuri = NetUtil.newURI("http://self.firefox.com/");
- let promiseNotifications = new Promise(resolve => {
- let observer = {
- _c: 0,
- __proto__: NavHistoryObserver.prototype,
- onVisit(uri, id, time, unused, referrerId, transition, guid,
- hidden, visitCount, typed) {
- Assert.ok(testuri.equals(uri));
- Assert.ok(id > 0);
- Assert.ok(time > 0);
- Assert.ok(!hidden);
- do_check_guid_for_uri(uri, guid);
- switch (++this._c) {
- case 1:
- Assert.equal(referrerId, 0);
- Assert.equal(transition, TRANSITION_LINK);
- Assert.equal(visitCount, 1);
- Assert.equal(typed, 0);
- break;
- case 2:
- Assert.ok(referrerId > 0);
- Assert.equal(transition, TRANSITION_LINK);
- Assert.equal(visitCount, 2);
- Assert.equal(typed, 0);
- break;
- case 3:
- Assert.equal(referrerId, 0);
- Assert.equal(transition, TRANSITION_TYPED);
- Assert.equal(visitCount, 3);
- Assert.equal(typed, 1);
-
- PlacesUtils.history.removeObserver(observer, false);
- resolve();
- break;
- }
- }
- };
- PlacesUtils.history.addObserver(observer, false);
- });
- yield PlacesTestUtils.addVisits([
- { uri: testuri, transition: TRANSITION_LINK },
- { uri: testuri, referrer: testuri, transition: TRANSITION_LINK },
- { uri: testuri, transition: TRANSITION_TYPED },
- ]);
- yield promiseNotifications;
-});
-
-add_task(function* test_onDeleteURI() {
- let promiseNotify = onNotify(function onDeleteURI(aURI, aGUID, aReason) {
- Assert.ok(aURI.equals(testuri));
- // Can't use do_check_guid_for_uri() here because the visit is already gone.
- Assert.equal(aGUID, testguid);
- Assert.equal(aReason, Ci.nsINavHistoryObserver.REASON_DELETED);
- });
- let [testuri] = yield task_add_visit();
- let testguid = do_get_guid_for_uri(testuri);
- PlacesUtils.bhistory.removePage(testuri);
- yield promiseNotify;
-});
-
-add_task(function* test_onDeleteVisits() {
- let promiseNotify = onNotify(function onDeleteVisits(aURI, aVisitTime, aGUID,
- aReason) {
- Assert.ok(aURI.equals(testuri));
- // Can't use do_check_guid_for_uri() here because the visit is already gone.
- Assert.equal(aGUID, testguid);
- Assert.equal(aReason, Ci.nsINavHistoryObserver.REASON_DELETED);
- Assert.equal(aVisitTime, 0); // All visits have been removed.
- });
- let msecs24hrsAgo = Date.now() - (86400 * 1000);
- let [testuri] = yield task_add_visit(undefined, msecs24hrsAgo * 1000);
- // Add a bookmark so the page is not removed.
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- testuri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "test");
- let testguid = do_get_guid_for_uri(testuri);
- PlacesUtils.bhistory.removePage(testuri);
- yield promiseNotify;
-});
-
-add_task(function* test_onTitleChanged() {
- let promiseNotify = onNotify(function onTitleChanged(aURI, aTitle, aGUID) {
- Assert.ok(aURI.equals(testuri));
- Assert.equal(aTitle, title);
- do_check_guid_for_uri(aURI, aGUID);
- });
-
- let [testuri] = yield task_add_visit();
- let title = "test-title";
- yield PlacesTestUtils.addVisits({
- uri: testuri,
- title: title
- });
- yield promiseNotify;
-});
-
-add_task(function* test_onPageChanged() {
- let promiseNotify = onNotify(function onPageChanged(aURI, aChangedAttribute,
- aNewValue, aGUID) {
- Assert.equal(aChangedAttribute, Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON);
- Assert.ok(aURI.equals(testuri));
- Assert.equal(aNewValue, SMALLPNG_DATA_URI.spec);
- do_check_guid_for_uri(aURI, aGUID);
- });
-
- let [testuri] = yield task_add_visit();
-
- // The new favicon for the page must have data associated with it in order to
- // receive the onPageChanged notification. To keep this test self-contained,
- // we use an URI representing the smallest possible PNG file.
- PlacesUtils.favicons.setAndFetchFaviconForPage(testuri, SMALLPNG_DATA_URI,
- false,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null,
- Services.scriptSecurityManager.getSystemPrincipal());
- yield promiseNotify;
-});
diff --git a/toolkit/components/places/tests/unit/test_history_sidebar.js b/toolkit/components/places/tests/unit/test_history_sidebar.js
deleted file mode 100644
index 1c03547d7..000000000
--- a/toolkit/components/places/tests/unit/test_history_sidebar.js
+++ /dev/null
@@ -1,447 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get history service
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-var bh = hs.QueryInterface(Ci.nsIBrowserHistory);
-var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-var ps = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-
-/**
- * Adds a test URI visit to the database.
- *
- * @param aURI
- * The URI to add a visit for.
- * @param aTime
- * Reference "now" time.
- * @param aDayOffset
- * number of days to add, pass a negative value to subtract them.
- */
-function* task_add_normalized_visit(aURI, aTime, aDayOffset) {
- var dateObj = new Date(aTime);
- // Normalize to midnight
- dateObj.setHours(0);
- dateObj.setMinutes(0);
- dateObj.setSeconds(0);
- dateObj.setMilliseconds(0);
- // Days where DST changes should be taken in count.
- var previousDateObj = new Date(dateObj.getTime() + aDayOffset * 86400000);
- var DSTCorrection = (dateObj.getTimezoneOffset() -
- previousDateObj.getTimezoneOffset()) * 60 * 1000;
- // Substract aDayOffset
- var PRTimeWithOffset = (previousDateObj.getTime() - DSTCorrection) * 1000;
- var timeInMs = new Date(PRTimeWithOffset/1000);
- print("Adding visit to " + aURI.spec + " at " + timeInMs);
- yield PlacesTestUtils.addVisits({
- uri: aURI,
- visitDate: PRTimeWithOffset
- });
-}
-
-function days_for_x_months_ago(aNowObj, aMonths) {
- var oldTime = new Date();
- // Set day before month, otherwise we could try to calculate 30 February, or
- // other nonexistent days.
- oldTime.setDate(1);
- oldTime.setMonth(aNowObj.getMonth() - aMonths);
- oldTime.setHours(0);
- oldTime.setMinutes(0);
- oldTime.setSeconds(0);
- // Stay larger for eventual timezone issues, add 2 days.
- return parseInt((aNowObj - oldTime) / (1000*60*60*24)) + 2;
-}
-
-var nowObj = new Date();
-// This test relies on en-US locale
-// Offset is number of days
-/* eslint-disable comma-spacing */
-var containers = [
- { label: "Today" , offset: 0 , visible: true },
- { label: "Yesterday" , offset: -1 , visible: true },
- { label: "Last 7 days" , offset: -3 , visible: true },
- { label: "This month" , offset: -8 , visible: nowObj.getDate() > 8 },
- { label: "" , offset: -days_for_x_months_ago(nowObj, 0) , visible: true },
- { label: "" , offset: -days_for_x_months_ago(nowObj, 1) , visible: true },
- { label: "" , offset: -days_for_x_months_ago(nowObj, 2) , visible: true },
- { label: "" , offset: -days_for_x_months_ago(nowObj, 3) , visible: true },
- { label: "" , offset: -days_for_x_months_ago(nowObj, 4) , visible: true },
- { label: "Older than 6 months" , offset: -days_for_x_months_ago(nowObj, 5) , visible: true },
-];
-/* eslint-enable comma-spacing */
-
-var visibleContainers = containers.filter(
- function(aContainer) { return aContainer.visible });
-
-/**
- * Asynchronous task that fills history and checks containers' labels.
- */
-function* task_fill_history() {
- print("\n\n*** TEST Fill History\n");
- // We can't use "now" because our hardcoded offsets would be invalid for some
- // date. So we hardcode a date.
- for (let i = 0; i < containers.length; i++) {
- let container = containers[i];
- var testURI = uri("http://mirror"+i+".mozilla.com/b");
- yield task_add_normalized_visit(testURI, nowObj.getTime(), container.offset);
- testURI = uri("http://mirror"+i+".mozilla.com/a");
- yield task_add_normalized_visit(testURI, nowObj.getTime(), container.offset);
- testURI = uri("http://mirror"+i+".google.com/b");
- yield task_add_normalized_visit(testURI, nowObj.getTime(), container.offset);
- testURI = uri("http://mirror"+i+".google.com/a");
- yield task_add_normalized_visit(testURI, nowObj.getTime(), container.offset);
- // Bug 485703 - Hide date containers not containing additional entries
- // compared to previous ones.
- // Check after every new container is added.
- check_visit(container.offset);
- }
-
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_DATE_SITE_QUERY;
- var query = hs.getNewQuery();
-
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- var cc = root.childCount;
- print("Found containers:");
- var previousLabels = [];
- for (let i = 0; i < cc; i++) {
- let container = visibleContainers[i];
- var node = root.getChild(i);
- print(node.title);
- if (container.label)
- do_check_eq(node.title, container.label);
- // Check labels are not repeated.
- do_check_eq(previousLabels.indexOf(node.title), -1);
- previousLabels.push(node.title);
- }
- do_check_eq(cc, visibleContainers.length);
- root.containerOpen = false;
-}
-
-/**
- * Bug 485703 - Hide date containers not containing additional entries compared
- * to previous ones.
- */
-function check_visit(aOffset) {
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_DATE_SITE_QUERY;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- var cc = root.childCount;
-
- var unexpected = [];
- switch (aOffset) {
- case 0:
- unexpected = ["Yesterday", "Last 7 days", "This month"];
- break;
- case -1:
- unexpected = ["Last 7 days", "This month"];
- break;
- case -3:
- unexpected = ["This month"];
- break;
- default:
- // Other containers are tested later.
- }
-
- print("Found containers:");
- for (var i = 0; i < cc; i++) {
- var node = root.getChild(i);
- print(node.title);
- do_check_eq(unexpected.indexOf(node.title), -1);
- }
-
- root.containerOpen = false;
-}
-
-/**
- * Queries history grouped by date and site, checking containers' labels and
- * children.
- */
-function test_RESULTS_AS_DATE_SITE_QUERY() {
- print("\n\n*** TEST RESULTS_AS_DATE_SITE_QUERY\n");
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_DATE_SITE_QUERY;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- // Check one of the days
- var dayNode = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dayNode.containerOpen = true;
- do_check_eq(dayNode.childCount, 2);
-
- // Items should be sorted by host
- var site1 = dayNode.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(site1.title, "mirror0.google.com");
-
- var site2 = dayNode.getChild(1)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(site2.title, "mirror0.mozilla.com");
-
- site1.containerOpen = true;
- do_check_eq(site1.childCount, 2);
-
- // Inside of host sites are sorted by title
- var site1visit = site1.getChild(0);
- do_check_eq(site1visit.uri, "http://mirror0.google.com/a");
-
- // Bug 473157: changing sorting mode should not affect the containers
- result.sortingMode = options.SORT_BY_TITLE_DESCENDING;
-
- // Check one of the days
- dayNode = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dayNode.containerOpen = true;
- do_check_eq(dayNode.childCount, 2);
-
- // Hosts are still sorted by title
- site1 = dayNode.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(site1.title, "mirror0.google.com");
-
- site2 = dayNode.getChild(1)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(site2.title, "mirror0.mozilla.com");
-
- site1.containerOpen = true;
- do_check_eq(site1.childCount, 2);
-
- // But URLs are now sorted by title descending
- site1visit = site1.getChild(0);
- do_check_eq(site1visit.uri, "http://mirror0.google.com/b");
-
- site1.containerOpen = false;
- dayNode.containerOpen = false;
- root.containerOpen = false;
-}
-
-/**
- * Queries history grouped by date, checking containers' labels and children.
- */
-function test_RESULTS_AS_DATE_QUERY() {
- print("\n\n*** TEST RESULTS_AS_DATE_QUERY\n");
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_DATE_QUERY;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- var cc = root.childCount;
- do_check_eq(cc, visibleContainers.length);
- print("Found containers:");
- for (var i = 0; i < cc; i++) {
- var container = visibleContainers[i];
- var node = root.getChild(i);
- print(node.title);
- if (container.label)
- do_check_eq(node.title, container.label);
- }
-
- // Check one of the days
- var dayNode = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dayNode.containerOpen = true;
- do_check_eq(dayNode.childCount, 4);
-
- // Items should be sorted by title
- var visit1 = dayNode.getChild(0);
- do_check_eq(visit1.uri, "http://mirror0.google.com/a");
-
- var visit2 = dayNode.getChild(3);
- do_check_eq(visit2.uri, "http://mirror0.mozilla.com/b");
-
- // Bug 473157: changing sorting mode should not affect the containers
- result.sortingMode = options.SORT_BY_TITLE_DESCENDING;
-
- // Check one of the days
- dayNode = root.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dayNode.containerOpen = true;
- do_check_eq(dayNode.childCount, 4);
-
- // But URLs are now sorted by title descending
- visit1 = dayNode.getChild(0);
- do_check_eq(visit1.uri, "http://mirror0.mozilla.com/b");
-
- visit2 = dayNode.getChild(3);
- do_check_eq(visit2.uri, "http://mirror0.google.com/a");
-
- dayNode.containerOpen = false;
- root.containerOpen = false;
-}
-
-/**
- * Queries history grouped by site, checking containers' labels and children.
- */
-function test_RESULTS_AS_SITE_QUERY() {
- print("\n\n*** TEST RESULTS_AS_SITE_QUERY\n");
- // add a bookmark with a domain not in the set of visits in the db
- var itemId = bs.insertBookmark(bs.toolbarFolder, uri("http://foobar"),
- bs.DEFAULT_INDEX, "");
-
- var options = hs.getNewQueryOptions();
- options.resultType = options.RESULTS_AS_SITE_QUERY;
- options.sortingMode = options.SORT_BY_TITLE_ASCENDING;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, containers.length * 2);
-
-/* Expected results:
- "mirror0.google.com",
- "mirror0.mozilla.com",
- "mirror1.google.com",
- "mirror1.mozilla.com",
- "mirror2.google.com",
- "mirror2.mozilla.com",
- "mirror3.google.com", <== We check for this site (index 6)
- "mirror3.mozilla.com",
- "mirror4.google.com",
- "mirror4.mozilla.com",
- "mirror5.google.com",
- "mirror5.mozilla.com",
- ...
-*/
-
- // Items should be sorted by host
- var siteNode = root.getChild(6)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(siteNode.title, "mirror3.google.com");
-
- siteNode.containerOpen = true;
- do_check_eq(siteNode.childCount, 2);
-
- // Inside of host sites are sorted by title
- var visitNode = siteNode.getChild(0);
- do_check_eq(visitNode.uri, "http://mirror3.google.com/a");
-
- // Bug 473157: changing sorting mode should not affect the containers
- result.sortingMode = options.SORT_BY_TITLE_DESCENDING;
- siteNode = root.getChild(6)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- do_check_eq(siteNode.title, "mirror3.google.com");
-
- siteNode.containerOpen = true;
- do_check_eq(siteNode.childCount, 2);
-
- // But URLs are now sorted by title descending
- var visit = siteNode.getChild(0);
- do_check_eq(visit.uri, "http://mirror3.google.com/b");
-
- siteNode.containerOpen = false;
- root.containerOpen = false;
-
- // Cleanup.
- bs.removeItem(itemId);
-}
-
-/**
- * Checks that queries grouped by date do liveupdate correctly.
- */
-function* task_test_date_liveupdate(aResultType) {
- var midnight = nowObj;
- midnight.setHours(0);
- midnight.setMinutes(0);
- midnight.setSeconds(0);
- midnight.setMilliseconds(0);
-
- // TEST 1. Test that the query correctly updates when it is root.
- var options = hs.getNewQueryOptions();
- options.resultType = aResultType;
- var query = hs.getNewQuery();
- var result = hs.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
-
- do_check_eq(root.childCount, visibleContainers.length);
- // Remove "Today".
- hs.removePagesByTimeframe(midnight.getTime() * 1000, Date.now() * 1000);
- do_check_eq(root.childCount, visibleContainers.length - 1);
-
- // Open "Last 7 days" container, this way we will have a container accepting
- // the new visit, but we should still add back "Today" container.
- var last7Days = root.getChild(1)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- last7Days.containerOpen = true;
-
- // Add a visit for "Today". This should add back the missing "Today"
- // container.
- yield task_add_normalized_visit(uri("http://www.mozilla.org/"), nowObj.getTime(), 0);
- do_check_eq(root.childCount, visibleContainers.length);
-
- last7Days.containerOpen = false;
- root.containerOpen = false;
-
- // TEST 2. Test that the query correctly updates even if it is not root.
- var itemId = bs.insertBookmark(bs.toolbarFolder,
- uri("place:type=" + aResultType),
- bs.DEFAULT_INDEX, "");
-
- // Query toolbar and open our query container, then check again liveupdate.
- options = hs.getNewQueryOptions();
- query = hs.getNewQuery();
- query.setFolders([bs.toolbarFolder], 1);
- result = hs.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 1);
- var dateContainer = root.getChild(0).QueryInterface(Ci.nsINavHistoryContainerResultNode);
- dateContainer.containerOpen = true;
-
- do_check_eq(dateContainer.childCount, visibleContainers.length);
- // Remove "Today".
- hs.removePagesByTimeframe(midnight.getTime() * 1000, Date.now() * 1000);
- do_check_eq(dateContainer.childCount, visibleContainers.length - 1);
- // Add a visit for "Today".
- yield task_add_normalized_visit(uri("http://www.mozilla.org/"), nowObj.getTime(), 0);
- do_check_eq(dateContainer.childCount, visibleContainers.length);
-
- dateContainer.containerOpen = false;
- root.containerOpen = false;
-
- // Cleanup.
- bs.removeItem(itemId);
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_history_sidebar()
-{
- // If we're dangerously close to a date change, just bail out.
- if (nowObj.getHours() == 23 && nowObj.getMinutes() >= 50) {
- return;
- }
-
- yield task_fill_history();
- test_RESULTS_AS_DATE_SITE_QUERY();
- test_RESULTS_AS_DATE_QUERY();
- test_RESULTS_AS_SITE_QUERY();
-
- yield task_test_date_liveupdate(Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY);
- yield task_test_date_liveupdate(Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY);
-
- // The remaining views are
- // RESULTS_AS_URI + SORT_BY_VISITCOUNT_DESCENDING
- // -> test_399266.js
- // RESULTS_AS_URI + SORT_BY_DATE_DESCENDING
- // -> test_385397.js
-});
diff --git a/toolkit/components/places/tests/unit/test_hosts_triggers.js b/toolkit/components/places/tests/unit/test_hosts_triggers.js
deleted file mode 100644
index 9c3359e76..000000000
--- a/toolkit/components/places/tests/unit/test_hosts_triggers.js
+++ /dev/null
@@ -1,226 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests the validity of various triggers that add remove hosts from moz_hosts
- */
-
-XPCOMUtils.defineLazyServiceGetter(this, "gHistory",
- "@mozilla.org/browser/history;1",
- "mozIAsyncHistory");
-
-// add some visits and remove them, add a bookmark,
-// change its uri, then remove it, and
-// for each change check that moz_hosts has correctly been updated.
-
-function isHostInMozPlaces(aURI)
-{
- let stmt = DBConn().createStatement(
- `SELECT url
- FROM moz_places
- WHERE url_hash = hash(:host) AND url = :host`
- );
- let result = false;
- stmt.params.host = aURI.spec;
- while (stmt.executeStep()) {
- if (stmt.row.url == aURI.spec) {
- result = true;
- break;
- }
- }
- stmt.finalize();
- return result;
-}
-
-function isHostInMozHosts(aURI, aTyped, aPrefix)
-{
- let stmt = DBConn().createStatement(
- `SELECT host, typed, prefix
- FROM moz_hosts
- WHERE host = fixup_url(:host)
- AND frecency NOTNULL`
- );
- let result = false;
- stmt.params.host = aURI.host;
- if (stmt.executeStep()) {
- result = aTyped == stmt.row.typed && aPrefix == stmt.row.prefix;
- }
- stmt.finalize();
- return result;
-}
-
-var urls = [{uri: NetUtil.newURI("http://visit1.mozilla.org"),
- expected: "visit1.mozilla.org",
- typed: 0,
- prefix: null
- },
- {uri: NetUtil.newURI("http://visit2.mozilla.org"),
- expected: "visit2.mozilla.org",
- typed: 0,
- prefix: null
- },
- {uri: NetUtil.newURI("http://www.foo.mozilla.org"),
- expected: "foo.mozilla.org",
- typed: 1,
- prefix: "www."
- },
- ];
-
-const NEW_URL = "http://different.mozilla.org/";
-
-add_task(function* test_moz_hosts_update()
-{
- let places = [];
- urls.forEach(function(url) {
- let place = { uri: url.uri,
- title: "test for " + url.url,
- transition: url.typed ? TRANSITION_TYPED : undefined };
- places.push(place);
- });
-
- yield PlacesTestUtils.addVisits(places);
-
- do_check_true(isHostInMozHosts(urls[0].uri, urls[0].typed, urls[0].prefix));
- do_check_true(isHostInMozHosts(urls[1].uri, urls[1].typed, urls[1].prefix));
- do_check_true(isHostInMozHosts(urls[2].uri, urls[2].typed, urls[2].prefix));
-});
-
-add_task(function* test_remove_places()
-{
- for (let idx in urls) {
- PlacesUtils.history.removePage(urls[idx].uri);
- }
-
- yield PlacesTestUtils.clearHistory();
-
- for (let idx in urls) {
- do_check_false(isHostInMozHosts(urls[idx].uri, urls[idx].typed, urls[idx].prefix));
- }
-});
-
-add_task(function* test_bookmark_changes()
-{
- let testUri = NetUtil.newURI("http://test.mozilla.org");
-
- let itemId = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- testUri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "bookmark title");
-
- do_check_true(isHostInMozPlaces(testUri));
-
- // Change the hostname
- PlacesUtils.bookmarks.changeBookmarkURI(itemId, NetUtil.newURI(NEW_URL));
-
- yield PlacesTestUtils.clearHistory();
-
- let newUri = NetUtil.newURI(NEW_URL);
- do_check_true(isHostInMozPlaces(newUri));
- do_check_true(isHostInMozHosts(newUri, false, null));
- do_check_false(isHostInMozHosts(NetUtil.newURI("http://test.mozilla.org"), false, null));
-});
-
-add_task(function* test_bookmark_removal()
-{
- let itemId = PlacesUtils.bookmarks.getIdForItemAt(PlacesUtils.unfiledBookmarksFolderId,
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- let newUri = NetUtil.newURI(NEW_URL);
- PlacesUtils.bookmarks.removeItem(itemId);
- yield PlacesTestUtils.clearHistory();
-
- do_check_false(isHostInMozHosts(newUri, false, null));
-});
-
-add_task(function* test_moz_hosts_typed_update()
-{
- const TEST_URI = NetUtil.newURI("http://typed.mozilla.com");
- let places = [{ uri: TEST_URI
- , title: "test for " + TEST_URI.spec
- },
- { uri: TEST_URI
- , title: "test for " + TEST_URI.spec
- , transition: TRANSITION_TYPED
- }];
-
- yield PlacesTestUtils.addVisits(places);
-
- do_check_true(isHostInMozHosts(TEST_URI, true, null));
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_moz_hosts_www_remove()
-{
- function* test_removal(aURIToRemove, aURIToKeep, aCallback) {
- let places = [{ uri: aURIToRemove
- , title: "test for " + aURIToRemove.spec
- , transition: TRANSITION_TYPED
- },
- { uri: aURIToKeep
- , title: "test for " + aURIToKeep.spec
- , transition: TRANSITION_TYPED
- }];
-
- yield PlacesTestUtils.addVisits(places);
- print("removing " + aURIToRemove.spec + " keeping " + aURIToKeep);
- dump_table("moz_hosts");
- dump_table("moz_places");
- PlacesUtils.history.removePage(aURIToRemove);
- let prefix = /www/.test(aURIToKeep.spec) ? "www." : null;
- dump_table("moz_hosts");
- dump_table("moz_places");
- do_check_true(isHostInMozHosts(aURIToKeep, true, prefix));
- }
-
- const TEST_URI = NetUtil.newURI("http://rem.mozilla.com");
- const TEST_WWW_URI = NetUtil.newURI("http://www.rem.mozilla.com");
- yield test_removal(TEST_URI, TEST_WWW_URI);
- yield test_removal(TEST_WWW_URI, TEST_URI);
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_moz_hosts_ftp_matchall()
-{
- const TEST_URI_1 = NetUtil.newURI("ftp://www.mozilla.com/");
- const TEST_URI_2 = NetUtil.newURI("ftp://mozilla.com/");
-
- yield PlacesTestUtils.addVisits([
- { uri: TEST_URI_1, transition: TRANSITION_TYPED },
- { uri: TEST_URI_2, transition: TRANSITION_TYPED }
- ]);
-
- do_check_true(isHostInMozHosts(TEST_URI_1, true, "ftp://"));
-});
-
-add_task(function* test_moz_hosts_ftp_not_matchall()
-{
- const TEST_URI_1 = NetUtil.newURI("http://mozilla.com/");
- const TEST_URI_2 = NetUtil.newURI("ftp://mozilla.com/");
-
- yield PlacesTestUtils.addVisits([
- { uri: TEST_URI_1, transition: TRANSITION_TYPED },
- { uri: TEST_URI_2, transition: TRANSITION_TYPED }
- ]);
-
- do_check_true(isHostInMozHosts(TEST_URI_1, true, null));
-});
-
-add_task(function* test_moz_hosts_update_2()
-{
- // Check that updating trigger takes into account prefixes for different
- // rev_hosts.
- const TEST_URI_1 = NetUtil.newURI("https://www.google.it/");
- const TEST_URI_2 = NetUtil.newURI("https://google.it/");
- let places = [{ uri: TEST_URI_1
- , transition: TRANSITION_TYPED
- },
- { uri: TEST_URI_2
- }];
- yield PlacesTestUtils.addVisits(places);
-
- do_check_true(isHostInMozHosts(TEST_URI_1, true, "https://www."));
-});
-
-function run_test()
-{
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_import_mobile_bookmarks.js b/toolkit/components/places/tests/unit/test_import_mobile_bookmarks.js
deleted file mode 100644
index 771a6ac17..000000000
--- a/toolkit/components/places/tests/unit/test_import_mobile_bookmarks.js
+++ /dev/null
@@ -1,292 +0,0 @@
-function* importFromFixture(fixture, replace) {
- let cwd = yield OS.File.getCurrentDirectory();
- let path = OS.Path.join(cwd, fixture);
-
- do_print(`Importing from ${path}`);
- yield BookmarkJSONUtils.importFromFile(path, replace);
- yield PlacesTestUtils.promiseAsyncUpdates();
-}
-
-function* treeEquals(guid, expected, message) {
- let root = yield PlacesUtils.promiseBookmarksTree(guid);
- let bookmarks = (function nodeToEntry(node) {
- let entry = { guid: node.guid, index: node.index }
- if (node.children) {
- entry.children = node.children.map(nodeToEntry);
- }
- if (node.annos) {
- entry.annos = node.annos;
- }
- return entry;
- }(root));
-
- do_print(`Checking if ${guid} tree matches ${JSON.stringify(expected)}`);
- do_print(`Got bookmarks tree for ${guid}: ${JSON.stringify(bookmarks)}`);
-
- deepEqual(bookmarks, expected, message);
-}
-
-add_task(function* test_restore_mobile_bookmarks_root() {
- yield* importFromFixture("mobile_bookmarks_root_import.json",
- /* replace */ true);
-
- yield* treeEquals(PlacesUtils.bookmarks.rootGuid, {
- guid: PlacesUtils.bookmarks.rootGuid,
- index: 0,
- children: [{
- guid: PlacesUtils.bookmarks.menuGuid,
- index: 0,
- children: [
- { guid: "X6lUyOspVYwi", index: 0 },
- ],
- }, {
- guid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- }, {
- guid: PlacesUtils.bookmarks.unfiledGuid,
- index: 3,
- }, {
- guid: PlacesUtils.bookmarks.mobileGuid,
- index: 4,
- annos: [{
- name: "mobile/bookmarksRoot",
- flags: 0,
- expires: 4,
- value: 1,
- }],
- children: [
- { guid: "_o8e1_zxTJFg", index: 0 },
- { guid: "QCtSqkVYUbXB", index: 1 },
- ],
- }],
- }, "Should restore mobile bookmarks from root");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_import_mobile_bookmarks_root() {
- yield* importFromFixture("mobile_bookmarks_root_import.json",
- /* replace */ false);
- yield* importFromFixture("mobile_bookmarks_root_merge.json",
- /* replace */ false);
-
- yield* treeEquals(PlacesUtils.bookmarks.rootGuid, {
- guid: PlacesUtils.bookmarks.rootGuid,
- index: 0,
- children: [{
- guid: PlacesUtils.bookmarks.menuGuid,
- index: 0,
- children: [
- { guid: "Utodo9b0oVws", index: 0 },
- { guid: "X6lUyOspVYwi", index: 1 },
- ],
- }, {
- guid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- }, {
- guid: PlacesUtils.bookmarks.unfiledGuid,
- index: 3,
- }, {
- guid: PlacesUtils.bookmarks.mobileGuid,
- index: 4,
- annos: [{
- name: "mobile/bookmarksRoot",
- flags: 0,
- expires: 4,
- value: 1,
- }],
- children: [
- { guid: "a17yW6-nTxEJ", index: 0 },
- { guid: "xV10h9Wi3FBM", index: 1 },
- { guid: "_o8e1_zxTJFg", index: 2 },
- { guid: "QCtSqkVYUbXB", index: 3 },
- ],
- }],
- }, "Should merge bookmarks root contents");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_restore_mobile_bookmarks_folder() {
- yield* importFromFixture("mobile_bookmarks_folder_import.json",
- /* replace */ true);
-
- yield* treeEquals(PlacesUtils.bookmarks.rootGuid, {
- guid: PlacesUtils.bookmarks.rootGuid,
- index: 0,
- children: [{
- guid: PlacesUtils.bookmarks.menuGuid,
- index: 0,
- children: [
- { guid: "X6lUyOspVYwi", index: 0 },
- { guid: "XF4yRP6bTuil", index: 1 },
- ],
- }, {
- guid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- children: [{ guid: "buy7711R3ZgE", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.unfiledGuid,
- index: 3,
- children: [{ guid: "KIa9iKZab2Z5", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.mobileGuid,
- index: 4,
- annos: [{
- name: "mobile/bookmarksRoot",
- flags: 0,
- expires: 4,
- value: 1,
- }],
- children: [
- { guid: "_o8e1_zxTJFg", index: 0 },
- { guid: "QCtSqkVYUbXB", index: 1 },
- ],
- }],
- }, "Should restore mobile bookmark folder contents into mobile root");
-
- // We rewrite queries to point to the root ID instead of the name
- // ("MOBILE_BOOKMARKS") so that we don't break them if the user downgrades
- // to an earlier release channel. This can be removed along with the anno in
- // bug 1306445.
- let queryById = yield PlacesUtils.bookmarks.fetch("XF4yRP6bTuil");
- equal(queryById.url.href, "place:folder=" + PlacesUtils.mobileFolderId,
- "Should rewrite mobile query to point to root ID");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_import_mobile_bookmarks_folder() {
- yield* importFromFixture("mobile_bookmarks_folder_import.json",
- /* replace */ false);
- yield* importFromFixture("mobile_bookmarks_folder_merge.json",
- /* replace */ false);
-
- yield* treeEquals(PlacesUtils.bookmarks.rootGuid, {
- guid: PlacesUtils.bookmarks.rootGuid,
- index: 0,
- children: [{
- guid: PlacesUtils.bookmarks.menuGuid,
- index: 0,
- children: [
- { guid: "Utodo9b0oVws", index: 0 },
- { guid: "X6lUyOspVYwi", index: 1 },
- { guid: "XF4yRP6bTuil", index: 2 },
- ],
- }, {
- guid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- children: [{ guid: "buy7711R3ZgE", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.unfiledGuid,
- index: 3,
- children: [{ guid: "KIa9iKZab2Z5", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.mobileGuid,
- index: 4,
- annos: [{
- name: "mobile/bookmarksRoot",
- flags: 0,
- expires: 4,
- value: 1,
- }],
- children: [
- { guid: "a17yW6-nTxEJ", index: 0 },
- { guid: "xV10h9Wi3FBM", index: 1 },
- { guid: "_o8e1_zxTJFg", index: 2 },
- { guid: "QCtSqkVYUbXB", index: 3 },
- ],
- }],
- }, "Should merge bookmarks folder contents into mobile root");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_restore_multiple_bookmarks_folders() {
- yield* importFromFixture("mobile_bookmarks_multiple_folders.json",
- /* replace */ true);
-
- yield* treeEquals(PlacesUtils.bookmarks.rootGuid, {
- guid: PlacesUtils.bookmarks.rootGuid,
- index: 0,
- children: [{
- guid: PlacesUtils.bookmarks.menuGuid,
- index: 0,
- children: [
- { guid: "buy7711R3ZgE", index: 0 },
- { guid: "F_LBgd1fS_uQ", index: 1 },
- { guid: "oIpmQXMWsXvY", index: 2 },
- ],
- }, {
- guid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- children: [{ guid: "Utodo9b0oVws", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.unfiledGuid,
- index: 3,
- children: [{ guid: "xV10h9Wi3FBM", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.mobileGuid,
- index: 4,
- annos: [{
- name: "mobile/bookmarksRoot",
- flags: 0,
- expires: 4,
- value: 1,
- }],
- children: [
- { guid: "sSZ86WT9WbN3", index: 0 },
- { guid: "a17yW6-nTxEJ", index: 1 },
- ],
- }],
- }, "Should restore multiple bookmarks folder contents into root");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_import_multiple_bookmarks_folders() {
- yield* importFromFixture("mobile_bookmarks_root_import.json",
- /* replace */ false);
- yield* importFromFixture("mobile_bookmarks_multiple_folders.json",
- /* replace */ false);
-
- yield* treeEquals(PlacesUtils.bookmarks.rootGuid, {
- guid: PlacesUtils.bookmarks.rootGuid,
- index: 0,
- children: [{
- guid: PlacesUtils.bookmarks.menuGuid,
- index: 0,
- children: [
- { guid: "buy7711R3ZgE", index: 0 },
- { guid: "F_LBgd1fS_uQ", index: 1 },
- { guid: "oIpmQXMWsXvY", index: 2 },
- { guid: "X6lUyOspVYwi", index: 3 },
- ],
- }, {
- guid: PlacesUtils.bookmarks.toolbarGuid,
- index: 1,
- children: [{ guid: "Utodo9b0oVws", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.unfiledGuid,
- index: 3,
- children: [{ guid: "xV10h9Wi3FBM", index: 0 }],
- }, {
- guid: PlacesUtils.bookmarks.mobileGuid,
- index: 4,
- annos: [{
- name: "mobile/bookmarksRoot",
- flags: 0,
- expires: 4,
- value: 1,
- }],
- children: [
- { guid: "sSZ86WT9WbN3", index: 0 },
- { guid: "a17yW6-nTxEJ", index: 1 },
- { guid: "_o8e1_zxTJFg", index: 2 },
- { guid: "QCtSqkVYUbXB", index: 3 },
- ],
- }],
- }, "Should merge multiple mobile folders into root");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
diff --git a/toolkit/components/places/tests/unit/test_isPageInDB.js b/toolkit/components/places/tests/unit/test_isPageInDB.js
deleted file mode 100644
index 249853fa9..000000000
--- a/toolkit/components/places/tests/unit/test_isPageInDB.js
+++ /dev/null
@@ -1,10 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-
-add_task(function* test_execute() {
- var good_uri = uri("http://mozilla.com");
- var bad_uri = uri("http://google.com");
- yield PlacesTestUtils.addVisits({uri: good_uri});
- do_check_true(yield PlacesTestUtils.isPageInDB(good_uri));
- do_check_false(yield PlacesTestUtils.isPageInDB(bad_uri));
-});
diff --git a/toolkit/components/places/tests/unit/test_isURIVisited.js b/toolkit/components/places/tests/unit/test_isURIVisited.js
deleted file mode 100644
index 93c010e83..000000000
--- a/toolkit/components/places/tests/unit/test_isURIVisited.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests functionality of the isURIVisited API.
-
-const SCHEMES = {
- "http://": true,
- "https://": true,
- "ftp://": true,
- "file:///": true,
- "about:": false,
-// nsIIOService.newURI() can throw if e.g. the app knows about imap://
-// but the account is not set up and so the URL is invalid for it.
-// "imap://": false,
- "news://": false,
- "mailbox:": false,
- "moz-anno:favicon:http://": false,
- "view-source:http://": false,
- "chrome://browser/content/browser.xul?": false,
- "resource://": false,
- "data:,": false,
- "wyciwyg:/0/http://": false,
- "javascript:": false,
-};
-
-var gRunner;
-function run_test()
-{
- do_test_pending();
- gRunner = step();
- gRunner.next();
-}
-
-function* step()
-{
- let history = Cc["@mozilla.org/browser/history;1"]
- .getService(Ci.mozIAsyncHistory);
-
- for (let scheme in SCHEMES) {
- do_print("Testing scheme " + scheme);
- for (let t in PlacesUtils.history.TRANSITIONS) {
- do_print("With transition " + t);
- let transition = PlacesUtils.history.TRANSITIONS[t];
-
- let uri = NetUtil.newURI(scheme + "mozilla.org/");
-
- history.isURIVisited(uri, function(aURI, aIsVisited) {
- do_check_true(uri.equals(aURI));
- do_check_false(aIsVisited);
-
- let callback = {
- handleError: function () {},
- handleResult: function () {},
- handleCompletion: function () {
- do_print("Added visit to " + uri.spec);
-
- history.isURIVisited(uri, function (aURI2, aIsVisited2) {
- do_check_true(uri.equals(aURI2));
- let checker = SCHEMES[scheme] ? do_check_true : do_check_false;
- checker(aIsVisited2);
-
- PlacesTestUtils.clearHistory().then(function () {
- history.isURIVisited(uri, function(aURI3, aIsVisited3) {
- do_check_true(uri.equals(aURI3));
- do_check_false(aIsVisited3);
- gRunner.next();
- });
- });
- });
- },
- };
-
- history.updatePlaces({ uri: uri
- , visits: [ { transitionType: transition
- , visitDate: Date.now() * 1000
- } ]
- }, callback);
- });
- yield undefined;
- }
- }
-
- do_test_finished();
-}
diff --git a/toolkit/components/places/tests/unit/test_isvisited.js b/toolkit/components/places/tests/unit/test_isvisited.js
deleted file mode 100644
index d7bcc2851..000000000
--- a/toolkit/components/places/tests/unit/test_isvisited.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- var referrer = uri("about:blank");
-
- // add a http:// uri
- var uri1 = uri("http://mozilla.com");
- yield PlacesTestUtils.addVisits({uri: uri1, referrer: referrer});
- do_check_guid_for_uri(uri1);
- do_check_true(yield promiseIsURIVisited(uri1));
-
- // add a https:// uri
- var uri2 = uri("https://etrade.com");
- yield PlacesTestUtils.addVisits({uri: uri2, referrer: referrer});
- do_check_guid_for_uri(uri2);
- do_check_true(yield promiseIsURIVisited(uri2));
-
- // add a ftp:// uri
- var uri3 = uri("ftp://ftp.mozilla.org");
- yield PlacesTestUtils.addVisits({uri: uri3, referrer: referrer});
- do_check_guid_for_uri(uri3);
- do_check_true(yield promiseIsURIVisited(uri3));
-
- // check if a nonexistent uri is visited
- var uri4 = uri("http://foobarcheese.com");
- do_check_false(yield promiseIsURIVisited(uri4));
-
- // check that certain schemes never show up as visited
- // even if we attempt to add them to history
- // see CanAddURI() in nsNavHistory.cpp
- const URLS = [
- "about:config",
- "imap://cyrus.andrew.cmu.edu/archive.imap",
- "news://new.mozilla.org/mozilla.dev.apps.firefox",
- "mailbox:Inbox",
- "moz-anno:favicon:http://mozilla.org/made-up-favicon",
- "view-source:http://mozilla.org",
- "chrome://browser/content/browser.xul",
- "resource://gre-resources/hiddenWindow.html",
- "data:,Hello%2C%20World!",
- "wyciwyg:/0/http://mozilla.org",
- "javascript:alert('hello wolrd!');",
- "http://localhost/" + "a".repeat(1984),
- ];
- for (let currentURL of URLS) {
- try {
- var cantAddUri = uri(currentURL);
- }
- catch (e) {
- // nsIIOService.newURI() can throw if e.g. our app knows about imap://
- // but the account is not set up and so the URL is invalid for us.
- // Note this in the log but ignore as it's not the subject of this test.
- do_print("Could not construct URI for '" + currentURL + "'; ignoring");
- }
- if (cantAddUri) {
- PlacesTestUtils.addVisits({uri: cantAddUri, referrer: referrer}).then(() => {
- do_throw("Should not have added history for invalid URI.");
- }, error => {
- do_check_true(error.message.includes("No items were added to history"));
- });
- do_check_false(yield promiseIsURIVisited(cantAddUri));
- }
- }
-});
-
diff --git a/toolkit/components/places/tests/unit/test_keywords.js b/toolkit/components/places/tests/unit/test_keywords.js
deleted file mode 100644
index 57b734c5d..000000000
--- a/toolkit/components/places/tests/unit/test_keywords.js
+++ /dev/null
@@ -1,548 +0,0 @@
-"use strict"
-
-function* check_keyword(aExpectExists, aHref, aKeyword, aPostData = null) {
- // Check case-insensitivity.
- aKeyword = aKeyword.toUpperCase();
-
- let entry = yield PlacesUtils.keywords.fetch(aKeyword);
-
- Assert.deepEqual(entry, yield PlacesUtils.keywords.fetch({ keyword: aKeyword }));
-
- if (aExpectExists) {
- Assert.ok(!!entry, "A keyword should exist");
- Assert.equal(entry.url.href, aHref);
- Assert.equal(entry.postData, aPostData);
- Assert.deepEqual(entry, yield PlacesUtils.keywords.fetch({ keyword: aKeyword, url: aHref }));
- let entries = [];
- yield PlacesUtils.keywords.fetch({ url: aHref }, e => entries.push(e));
- Assert.ok(entries.some(e => e.url.href == aHref && e.keyword == aKeyword.toLowerCase()));
- } else {
- Assert.ok(!entry || entry.url.href != aHref,
- "The given keyword entry should not exist");
- Assert.equal(null, yield PlacesUtils.keywords.fetch({ keyword: aKeyword, url: aHref }));
- }
-}
-
-/**
- * Polls the keywords cache waiting for the given keyword entry.
- */
-function* promiseKeyword(keyword, expectedHref) {
- let href = null;
- do {
- yield new Promise(resolve => do_timeout(100, resolve));
- let entry = yield PlacesUtils.keywords.fetch(keyword);
- if (entry)
- href = entry.url.href;
- } while (href != expectedHref);
-}
-
-function* check_no_orphans() {
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.executeCached(
- `SELECT id FROM moz_keywords k
- WHERE NOT EXISTS (SELECT 1 FROM moz_places WHERE id = k.place_id)
- `);
- Assert.equal(rows.length, 0);
-}
-
-function expectBookmarkNotifications() {
- let notifications = [];
- let observer = new Proxy(NavBookmarkObserver, {
- get(target, name) {
- if (name == "check") {
- PlacesUtils.bookmarks.removeObserver(observer);
- return expectedNotifications =>
- Assert.deepEqual(notifications, expectedNotifications);
- }
-
- if (name.startsWith("onItemChanged")) {
- return function(itemId, property) {
- if (property != "keyword")
- return;
- let args = Array.from(arguments, arg => {
- if (arg && arg instanceof Ci.nsIURI)
- return new URL(arg.spec);
- if (arg && typeof(arg) == "number" && arg >= Date.now() * 1000)
- return new Date(parseInt(arg/1000));
- return arg;
- });
- notifications.push({ name: name, arguments: args });
- }
- }
-
- if (name in target)
- return target[name];
- return undefined;
- }
- });
- PlacesUtils.bookmarks.addObserver(observer, false);
- return observer;
-}
-
-add_task(function* test_invalid_input() {
- Assert.throws(() => PlacesUtils.keywords.fetch(null),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.fetch(5),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.fetch(undefined),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ keyword: null }),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ keyword: {} }),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ keyword: 5 }),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.fetch({}),
- /At least keyword or url must be provided/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ keyword: "test" }, "test"),
- /onResult callback must be a valid function/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ url: "test" }),
- /is not a valid URL/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ url: {} }),
- /is not a valid URL/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ url: null }),
- /is not a valid URL/);
- Assert.throws(() => PlacesUtils.keywords.fetch({ url: "" }),
- /is not a valid URL/);
-
- Assert.throws(() => PlacesUtils.keywords.insert(null),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.keywords.insert("test"),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.keywords.insert(undefined),
- /Input should be a valid object/);
- Assert.throws(() => PlacesUtils.keywords.insert({ }),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: null }),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: 5 }),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "" }),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "test", postData: 5 }),
- /Invalid POST data/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "test", postData: {} }),
- /Invalid POST data/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "test" }),
- /is not a valid URL/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "test", url: 5 }),
- /is not a valid URL/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "test", url: "" }),
- /is not a valid URL/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "test", url: null }),
- /is not a valid URL/);
- Assert.throws(() => PlacesUtils.keywords.insert({ keyword: "test", url: "mozilla" }),
- /is not a valid URL/);
-
- Assert.throws(() => PlacesUtils.keywords.remove(null),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.remove(""),
- /Invalid keyword/);
- Assert.throws(() => PlacesUtils.keywords.remove(5),
- /Invalid keyword/);
-});
-
-add_task(function* test_addKeyword() {
- yield check_keyword(false, "http://example.com/", "keyword");
- let fc = yield foreign_count("http://example.com/");
- let observer = expectBookmarkNotifications();
-
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/" });
- observer.check([]);
-
- yield check_keyword(true, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 1); // +1 keyword
-
- // Now remove the keyword.
- observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.remove("keyword");
- observer.check([]);
-
- yield check_keyword(false, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc); // -1 keyword
-
- // Check using URL.
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: new URL("http://example.com/") });
- yield check_keyword(true, "http://example.com/", "keyword");
- yield PlacesUtils.keywords.remove("keyword");
- yield check_keyword(false, "http://example.com/", "keyword");
-
- yield check_no_orphans();
-});
-
-add_task(function* test_addBookmarkAndKeyword() {
- yield check_keyword(false, "http://example.com/", "keyword");
- let fc = yield foreign_count("http://example.com/");
- let bookmark = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
-
- let observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/" });
-
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark.guid)),
- "keyword", false, "keyword",
- bookmark.lastModified, bookmark.type,
- (yield PlacesUtils.promiseItemId(bookmark.parentGuid)),
- bookmark.guid, bookmark.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- yield check_keyword(true, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 2); // +1 bookmark +1 keyword
-
- // Now remove the keyword.
- observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.remove("keyword");
-
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark.guid)),
- "keyword", false, "",
- bookmark.lastModified, bookmark.type,
- (yield PlacesUtils.promiseItemId(bookmark.parentGuid)),
- bookmark.guid, bookmark.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- yield check_keyword(false, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 1); // -1 keyword
-
- // Add again the keyword, then remove the bookmark.
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/" });
-
- observer = expectBookmarkNotifications();
- yield PlacesUtils.bookmarks.remove(bookmark.guid);
- // the notification is synchronous but the removal process is async.
- // Unfortunately there's nothing explicit we can wait for.
- while ((yield foreign_count("http://example.com/")));
- // We don't get any itemChanged notification since the bookmark has been
- // removed already.
- observer.check([]);
-
- yield check_keyword(false, "http://example.com/", "keyword");
-
- yield check_no_orphans();
-});
-
-add_task(function* test_addKeywordToURIHavingKeyword() {
- yield check_keyword(false, "http://example.com/", "keyword");
- let fc = yield foreign_count("http://example.com/");
-
- let observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/" });
- observer.check([]);
-
- yield check_keyword(true, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 1); // +1 keyword
-
- yield PlacesUtils.keywords.insert({ keyword: "keyword2", url: "http://example.com/" });
-
- yield check_keyword(true, "http://example.com/", "keyword");
- yield check_keyword(true, "http://example.com/", "keyword2");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 2); // +1 keyword
- let entries = [];
- let entry = yield PlacesUtils.keywords.fetch({ url: "http://example.com/" }, e => entries.push(e));
- Assert.equal(entries.length, 2);
- Assert.deepEqual(entries[0], entry);
-
- // Now remove the keywords.
- observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.remove("keyword");
- yield PlacesUtils.keywords.remove("keyword2");
- observer.check([]);
-
- yield check_keyword(false, "http://example.com/", "keyword");
- yield check_keyword(false, "http://example.com/", "keyword2");
- Assert.equal((yield foreign_count("http://example.com/")), fc); // -1 keyword
-
- yield check_no_orphans();
-});
-
-add_task(function* test_addBookmarkToURIHavingKeyword() {
- yield check_keyword(false, "http://example.com/", "keyword");
- let fc = yield foreign_count("http://example.com/");
- let observer = expectBookmarkNotifications();
-
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/" });
- observer.check([]);
-
- yield check_keyword(true, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 1); // +1 keyword
-
- observer = expectBookmarkNotifications();
- let bookmark = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- Assert.equal((yield foreign_count("http://example.com/")), fc + 2); // +1 bookmark
- observer.check([]);
-
- observer = expectBookmarkNotifications();
- yield PlacesUtils.bookmarks.remove(bookmark.guid);
- // the notification is synchronous but the removal process is async.
- // Unfortunately there's nothing explicit we can wait for.
- while ((yield foreign_count("http://example.com/")));
- // We don't get any itemChanged notification since the bookmark has been
- // removed already.
- observer.check([]);
-
- yield check_keyword(false, "http://example.com/", "keyword");
-
- yield check_no_orphans();
-});
-
-add_task(function* test_sameKeywordDifferentURL() {
- let fc1 = yield foreign_count("http://example1.com/");
- let bookmark1 = yield PlacesUtils.bookmarks.insert({ url: "http://example1.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let fc2 = yield foreign_count("http://example2.com/");
- let bookmark2 = yield PlacesUtils.bookmarks.insert({ url: "http://example2.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example1.com/" });
-
- yield check_keyword(true, "http://example1.com/", "keyword");
- Assert.equal((yield foreign_count("http://example1.com/")), fc1 + 2); // +1 bookmark +1 keyword
- yield check_keyword(false, "http://example2.com/", "keyword");
- Assert.equal((yield foreign_count("http://example2.com/")), fc2 + 1); // +1 bookmark
-
- // Assign the same keyword to another url.
- let observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example2.com/" });
-
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark1.guid)),
- "keyword", false, "",
- bookmark1.lastModified, bookmark1.type,
- (yield PlacesUtils.promiseItemId(bookmark1.parentGuid)),
- bookmark1.guid, bookmark1.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark2.guid)),
- "keyword", false, "keyword",
- bookmark2.lastModified, bookmark2.type,
- (yield PlacesUtils.promiseItemId(bookmark2.parentGuid)),
- bookmark2.guid, bookmark2.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- yield check_keyword(false, "http://example1.com/", "keyword");
- Assert.equal((yield foreign_count("http://example1.com/")), fc1 + 1); // -1 keyword
- yield check_keyword(true, "http://example2.com/", "keyword");
- Assert.equal((yield foreign_count("http://example2.com/")), fc2 + 2); // +1 keyword
-
- // Now remove the keyword.
- observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.remove("keyword");
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark2.guid)),
- "keyword", false, "",
- bookmark2.lastModified, bookmark2.type,
- (yield PlacesUtils.promiseItemId(bookmark2.parentGuid)),
- bookmark2.guid, bookmark2.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- yield check_keyword(false, "http://example1.com/", "keyword");
- yield check_keyword(false, "http://example2.com/", "keyword");
- Assert.equal((yield foreign_count("http://example1.com/")), fc1 + 1);
- Assert.equal((yield foreign_count("http://example2.com/")), fc2 + 1); // -1 keyword
-
- yield PlacesUtils.bookmarks.remove(bookmark1);
- yield PlacesUtils.bookmarks.remove(bookmark2);
- Assert.equal((yield foreign_count("http://example1.com/")), fc1); // -1 bookmark
- while ((yield foreign_count("http://example2.com/"))); // -1 keyword
-
- yield check_no_orphans();
-});
-
-add_task(function* test_sameURIDifferentKeyword() {
- let fc = yield foreign_count("http://example.com/");
-
- let observer = expectBookmarkNotifications();
- let bookmark = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- yield PlacesUtils.keywords.insert({keyword: "keyword", url: "http://example.com/" });
-
- yield check_keyword(true, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 2); // +1 bookmark +1 keyword
-
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark.guid)),
- "keyword", false, "keyword",
- bookmark.lastModified, bookmark.type,
- (yield PlacesUtils.promiseItemId(bookmark.parentGuid)),
- bookmark.guid, bookmark.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.insert({ keyword: "keyword2", url: "http://example.com/" });
- yield check_keyword(true, "http://example.com/", "keyword");
- yield check_keyword(true, "http://example.com/", "keyword2");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 3); // +1 keyword
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark.guid)),
- "keyword", false, "keyword2",
- bookmark.lastModified, bookmark.type,
- (yield PlacesUtils.promiseItemId(bookmark.parentGuid)),
- bookmark.guid, bookmark.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- // Add a third keyword.
- yield PlacesUtils.keywords.insert({ keyword: "keyword3", url: "http://example.com/" });
- yield check_keyword(true, "http://example.com/", "keyword");
- yield check_keyword(true, "http://example.com/", "keyword2");
- yield check_keyword(true, "http://example.com/", "keyword3");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 4); // +1 keyword
-
- // Remove one of the keywords.
- observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.remove("keyword");
- yield check_keyword(false, "http://example.com/", "keyword");
- yield check_keyword(true, "http://example.com/", "keyword2");
- yield check_keyword(true, "http://example.com/", "keyword3");
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark.guid)),
- "keyword", false, "",
- bookmark.lastModified, bookmark.type,
- (yield PlacesUtils.promiseItemId(bookmark.parentGuid)),
- bookmark.guid, bookmark.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
- Assert.equal((yield foreign_count("http://example.com/")), fc + 3); // -1 keyword
-
- // Now remove the bookmark.
- yield PlacesUtils.bookmarks.remove(bookmark);
- while ((yield foreign_count("http://example.com/")));
- yield check_keyword(false, "http://example.com/", "keyword");
- yield check_keyword(false, "http://example.com/", "keyword2");
- yield check_keyword(false, "http://example.com/", "keyword3");
-
- check_no_orphans();
-});
-
-add_task(function* test_deleteKeywordMultipleBookmarks() {
- let fc = yield foreign_count("http://example.com/");
-
- let observer = expectBookmarkNotifications();
- let bookmark1 = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- let bookmark2 = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/" });
-
- yield check_keyword(true, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 3); // +2 bookmark +1 keyword
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark2.guid)),
- "keyword", false, "keyword",
- bookmark2.lastModified, bookmark2.type,
- (yield PlacesUtils.promiseItemId(bookmark2.parentGuid)),
- bookmark2.guid, bookmark2.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark1.guid)),
- "keyword", false, "keyword",
- bookmark1.lastModified, bookmark1.type,
- (yield PlacesUtils.promiseItemId(bookmark1.parentGuid)),
- bookmark1.guid, bookmark1.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- observer = expectBookmarkNotifications();
- yield PlacesUtils.keywords.remove("keyword");
- yield check_keyword(false, "http://example.com/", "keyword");
- Assert.equal((yield foreign_count("http://example.com/")), fc + 2); // -1 keyword
- observer.check([{ name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark2.guid)),
- "keyword", false, "",
- bookmark2.lastModified, bookmark2.type,
- (yield PlacesUtils.promiseItemId(bookmark2.parentGuid)),
- bookmark2.guid, bookmark2.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] },
- { name: "onItemChanged",
- arguments: [ (yield PlacesUtils.promiseItemId(bookmark1.guid)),
- "keyword", false, "",
- bookmark1.lastModified, bookmark1.type,
- (yield PlacesUtils.promiseItemId(bookmark1.parentGuid)),
- bookmark1.guid, bookmark1.parentGuid, "",
- Ci.nsINavBookmarksService.SOURCE_DEFAULT ] } ]);
-
- // Now remove the bookmarks.
- yield PlacesUtils.bookmarks.remove(bookmark1);
- yield PlacesUtils.bookmarks.remove(bookmark2);
- Assert.equal((yield foreign_count("http://example.com/")), fc); // -2 bookmarks
-
- check_no_orphans();
-});
-
-add_task(function* test_multipleKeywordsSamePostData() {
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/", postData: "postData1" });
- yield check_keyword(true, "http://example.com/", "keyword", "postData1");
- // Add another keyword with same postData, should fail.
- yield Assert.rejects(PlacesUtils.keywords.insert({ keyword: "keyword2", url: "http://example.com/", postData: "postData1" }),
- /constraint failed/);
- yield check_keyword(false, "http://example.com/", "keyword2", "postData1");
-
- yield PlacesUtils.keywords.remove("keyword");
-
- check_no_orphans();
-});
-
-add_task(function* test_oldPostDataAPI() {
- let bookmark = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com/" });
- let itemId = yield PlacesUtils.promiseItemId(bookmark.guid);
- yield PlacesUtils.setPostDataForBookmark(itemId, "postData");
- yield check_keyword(true, "http://example.com/", "keyword", "postData");
- Assert.equal(PlacesUtils.getPostDataForBookmark(itemId), "postData");
-
- yield PlacesUtils.keywords.remove("keyword");
- yield PlacesUtils.bookmarks.remove(bookmark);
-
- check_no_orphans();
-});
-
-add_task(function* test_oldKeywordsAPI() {
- let bookmark = yield PlacesUtils.bookmarks.insert({ url: "http://example.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- yield check_keyword(false, "http://example.com/", "keyword");
- let itemId = yield PlacesUtils.promiseItemId(bookmark.guid);
-
- PlacesUtils.bookmarks.setKeywordForBookmark(itemId, "keyword");
- yield promiseKeyword("keyword", "http://example.com/");
-
- // Remove the keyword.
- PlacesUtils.bookmarks.setKeywordForBookmark(itemId, "");
- yield promiseKeyword("keyword", null);
-
- yield PlacesUtils.keywords.insert({ keyword: "keyword", url: "http://example.com" });
- Assert.equal(PlacesUtils.bookmarks.getKeywordForBookmark(itemId), "keyword");
- Assert.equal(PlacesUtils.bookmarks.getURIForKeyword("keyword").spec, "http://example.com/");
- yield PlacesUtils.bookmarks.remove(bookmark);
-
- check_no_orphans();
-});
-
-add_task(function* test_bookmarkURLChange() {
- let fc1 = yield foreign_count("http://example1.com/");
- let fc2 = yield foreign_count("http://example2.com/");
- let bookmark = yield PlacesUtils.bookmarks.insert({ url: "http://example1.com/",
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- yield PlacesUtils.keywords.insert({ keyword: "keyword",
- url: "http://example1.com/" });
-
- yield check_keyword(true, "http://example1.com/", "keyword");
- Assert.equal((yield foreign_count("http://example1.com/")), fc1 + 2); // +1 bookmark +1 keyword
-
- yield PlacesUtils.bookmarks.update({ guid: bookmark.guid,
- url: "http://example2.com/"});
- yield promiseKeyword("keyword", "http://example2.com/");
-
- yield check_keyword(false, "http://example1.com/", "keyword");
- yield check_keyword(true, "http://example2.com/", "keyword");
- Assert.equal((yield foreign_count("http://example1.com/")), fc1); // -1 bookmark -1 keyword
- Assert.equal((yield foreign_count("http://example2.com/")), fc2 + 2); // +1 bookmark +1 keyword
-});
diff --git a/toolkit/components/places/tests/unit/test_lastModified.js b/toolkit/components/places/tests/unit/test_lastModified.js
deleted file mode 100644
index c75494932..000000000
--- a/toolkit/components/places/tests/unit/test_lastModified.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Test that inserting a new bookmark will set lastModified to the same
- * values as dateAdded.
- */
-// main
-function run_test() {
- var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
- var itemId = bs.insertBookmark(bs.bookmarksMenuFolder,
- uri("http://www.mozilla.org/"),
- bs.DEFAULT_INDEX,
- "itemTitle");
- var dateAdded = bs.getItemDateAdded(itemId);
- do_check_eq(dateAdded, bs.getItemLastModified(itemId));
-
- // Change lastModified, then change dateAdded. LastModified should be set
- // to the new dateAdded.
- // This could randomly fail on virtual machines due to timing issues, so
- // we manually increase the time value. See bug 500640 for details.
- bs.setItemLastModified(itemId, dateAdded + 1000);
- do_check_true(bs.getItemLastModified(itemId) === dateAdded + 1000);
- do_check_true(bs.getItemDateAdded(itemId) < bs.getItemLastModified(itemId));
- bs.setItemDateAdded(itemId, dateAdded + 2000);
- do_check_true(bs.getItemDateAdded(itemId) === dateAdded + 2000);
- do_check_eq(bs.getItemDateAdded(itemId), bs.getItemLastModified(itemId));
-
- bs.removeItem(itemId);
-}
diff --git a/toolkit/components/places/tests/unit/test_markpageas.js b/toolkit/components/places/tests/unit/test_markpageas.js
deleted file mode 100644
index ba4f740c6..000000000
--- a/toolkit/components/places/tests/unit/test_markpageas.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var gVisits = [{url: "http://www.mozilla.com/",
- transition: TRANSITION_TYPED},
- {url: "http://www.google.com/",
- transition: TRANSITION_BOOKMARK},
- {url: "http://www.espn.com/",
- transition: TRANSITION_LINK}];
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- let observer;
- let completionPromise = new Promise(resolveCompletionPromise => {
- observer = {
- __proto__: NavHistoryObserver.prototype,
- _visitCount: 0,
- onVisit: function (aURI, aVisitID, aTime, aSessionID, aReferringID,
- aTransitionType, aAdded)
- {
- do_check_eq(aURI.spec, gVisits[this._visitCount].url);
- do_check_eq(aTransitionType, gVisits[this._visitCount].transition);
- this._visitCount++;
-
- if (this._visitCount == gVisits.length) {
- resolveCompletionPromise();
- }
- },
- };
- });
-
- PlacesUtils.history.addObserver(observer, false);
-
- for (var visit of gVisits) {
- if (visit.transition == TRANSITION_TYPED)
- PlacesUtils.history.markPageAsTyped(uri(visit.url));
- else if (visit.transition == TRANSITION_BOOKMARK)
- PlacesUtils.history.markPageAsFollowedBookmark(uri(visit.url))
- else {
- // because it is a top level visit with no referrer,
- // it will result in TRANSITION_LINK
- }
- yield PlacesTestUtils.addVisits({
- uri: uri(visit.url),
- transition: visit.transition
- });
- }
-
- yield completionPromise;
-
- PlacesUtils.history.removeObserver(observer);
-});
-
diff --git a/toolkit/components/places/tests/unit/test_mozIAsyncLivemarks.js b/toolkit/components/places/tests/unit/test_mozIAsyncLivemarks.js
deleted file mode 100644
index 5136591ba..000000000
--- a/toolkit/components/places/tests/unit/test_mozIAsyncLivemarks.js
+++ /dev/null
@@ -1,514 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests functionality of the mozIAsyncLivemarks interface.
-
-const FEED_URI = NetUtil.newURI("http://feed.rss/");
-const SITE_URI = NetUtil.newURI("http://site.org/");
-
-// This test must be the first one, since it's testing the cache.
-add_task(function* test_livemark_cache() {
- // Add a livemark through other APIs.
- let folder = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "test",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid
- });
- let id = yield PlacesUtils.promiseItemId(folder.guid);
- PlacesUtils.annotations
- .setItemAnnotation(id, PlacesUtils.LMANNO_FEEDURI,
- "http://example.com/feed",
- 0, PlacesUtils.annotations.EXPIRE_NEVER);
- PlacesUtils.annotations
- .setItemAnnotation(id, PlacesUtils.LMANNO_SITEURI,
- "http://example.com/site",
- 0, PlacesUtils.annotations.EXPIRE_NEVER);
-
- let livemark = yield PlacesUtils.livemarks.getLivemark({ guid: folder.guid });
- Assert.equal(folder.guid, livemark.guid);
- Assert.equal(folder.dateAdded * 1000, livemark.dateAdded);
- Assert.equal(folder.parentGuid, livemark.parentGuid);
- Assert.equal(folder.index, livemark.index);
- Assert.equal(folder.title, livemark.title);
- Assert.equal(id, livemark.id);
- Assert.equal(PlacesUtils.unfiledBookmarksFolderId, livemark.parentId);
- Assert.equal("http://example.com/feed", livemark.feedURI.spec);
- Assert.equal("http://example.com/site", livemark.siteURI.spec);
-
- yield PlacesUtils.livemarks.removeLivemark(livemark);
-});
-
-add_task(function* test_addLivemark_noArguments_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark();
- do_throw("Invoking addLivemark with no arguments should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_XPC_NOT_ENOUGH_ARGS);
- }
-});
-
-add_task(function* test_addLivemark_emptyObject_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark({});
- do_throw("Invoking addLivemark with empty object should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_badParentId_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark({ parentId: "test" });
- do_throw("Invoking addLivemark with a bad parent id should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_invalidParentId_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark({ parentId: -2 });
- do_throw("Invoking addLivemark with an invalid parent id should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_noIndex_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark({
- parentId: PlacesUtils.unfiledBookmarksFolderId });
- do_throw("Invoking addLivemark with no index should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_badIndex_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { parentId: PlacesUtils.unfiledBookmarksFolderId
- , index: "test" });
- do_throw("Invoking addLivemark with a bad index should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_invalidIndex_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { parentId: PlacesUtils.unfiledBookmarksFolderId
- , index: -2
- });
- do_throw("Invoking addLivemark with an invalid index should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_noFeedURI_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { parentGuid: PlacesUtils.bookmarks.unfiledGuid });
- do_throw("Invoking addLivemark with no feedURI should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_badFeedURI_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: "test" });
- do_throw("Invoking addLivemark with a bad feedURI should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_badSiteURI_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , siteURI: "test" });
- do_throw("Invoking addLivemark with a bad siteURI should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_badGuid_throws() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { parentGuid: PlacesUtils.bookmarks.unfileGuid
- , feedURI: FEED_URI
- , guid: "123456" });
- do_throw("Invoking addLivemark with a bad guid should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_parentId_succeeds() {
- let onItemAddedCalled = false;
- PlacesUtils.bookmarks.addObserver({
- __proto__: NavBookmarkObserver.prototype,
- onItemAdded: function onItemAdded(aItemId, aParentId, aIndex, aItemType,
- aURI, aTitle)
- {
- onItemAddedCalled = true;
- PlacesUtils.bookmarks.removeObserver(this);
- do_check_eq(aParentId, PlacesUtils.unfiledBookmarksFolderId);
- do_check_eq(aIndex, 0);
- do_check_eq(aItemType, Ci.nsINavBookmarksService.TYPE_FOLDER);
- do_check_eq(aTitle, "test");
- }
- }, false);
-
- yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentId: PlacesUtils.unfiledBookmarksFolderId
- , feedURI: FEED_URI });
- do_check_true(onItemAddedCalled);
-});
-
-
-add_task(function* test_addLivemark_noSiteURI_succeeds() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- });
- do_check_true(livemark.id > 0);
- do_check_valid_places_guid(livemark.guid);
- do_check_eq(livemark.title, "test");
- do_check_eq(livemark.parentId, PlacesUtils.unfiledBookmarksFolderId);
- do_check_eq(livemark.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- do_check_true(livemark.feedURI.equals(FEED_URI));
- do_check_eq(livemark.siteURI, null);
- do_check_true(livemark.lastModified > 0);
- do_check_true(is_time_ordered(livemark.dateAdded, livemark.lastModified));
-
- let bookmark = yield PlacesUtils.bookmarks.fetch(livemark.guid);
- do_check_eq(livemark.index, bookmark.index);
- do_check_eq(livemark.dateAdded, bookmark.dateAdded * 1000);
-});
-
-add_task(function* test_addLivemark_succeeds() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , siteURI: SITE_URI
- });
-
- do_check_true(livemark.id > 0);
- do_check_valid_places_guid(livemark.guid);
- do_check_eq(livemark.title, "test");
- do_check_eq(livemark.parentId, PlacesUtils.unfiledBookmarksFolderId);
- do_check_eq(livemark.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- do_check_true(livemark.feedURI.equals(FEED_URI));
- do_check_true(livemark.siteURI.equals(SITE_URI));
- do_check_true(PlacesUtils.annotations
- .itemHasAnnotation(livemark.id,
- PlacesUtils.LMANNO_FEEDURI));
- do_check_true(PlacesUtils.annotations
- .itemHasAnnotation(livemark.id,
- PlacesUtils.LMANNO_SITEURI));
-});
-
-add_task(function* test_addLivemark_bogusid_succeeds() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { id: 100 // Should be ignored.
- , title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , siteURI: SITE_URI
- });
- do_check_true(livemark.id > 0);
- do_check_neq(livemark.id, 100);
-});
-
-add_task(function* test_addLivemark_bogusParentId_fails() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentId: 187
- , feedURI: FEED_URI
- });
- do_throw("Adding a livemark with a bogus parent should fail");
- } catch (ex) {}
-});
-
-add_task(function* test_addLivemark_bogusParentGuid_fails() {
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: "123456789012"
- , feedURI: FEED_URI
- });
- do_throw("Adding a livemark with a bogus parent should fail");
- } catch (ex) {}
-})
-
-add_task(function* test_addLivemark_intoLivemark_fails() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- });
-
- try {
- yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: livemark.guid
- , feedURI: FEED_URI
- });
- do_throw("Adding a livemark into a livemark should fail");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_addLivemark_forceGuid_succeeds() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , guid: "1234567890AB"
- });
- do_check_eq(livemark.guid, "1234567890AB");
- do_check_guid_for_bookmark(livemark.id, "1234567890AB");
-});
-
-add_task(function* test_addLivemark_dateAdded_succeeds() {
- let dateAdded = new Date("2013-03-01T01:10:00") * 1000;
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , dateAdded
- });
- do_check_eq(livemark.dateAdded, dateAdded);
-});
-
-add_task(function* test_addLivemark_lastModified_succeeds() {
- let now = Date.now() * 1000;
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , lastModified: now
- });
- do_check_eq(livemark.dateAdded, now);
- do_check_eq(livemark.lastModified, now);
-});
-
-add_task(function* test_removeLivemark_emptyObject_throws() {
- try {
- yield PlacesUtils.livemarks.removeLivemark({});
- do_throw("Invoking removeLivemark with empty object should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_removeLivemark_noValidId_throws() {
- try {
- yield PlacesUtils.livemarks.removeLivemark({ id: -10, guid: "test"});
- do_throw("Invoking removeLivemark with no valid id should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_removeLivemark_nonExistent_fails() {
- try {
- yield PlacesUtils.livemarks.removeLivemark({ id: 1337 });
- do_throw("Removing a non-existent livemark should fail");
- }
- catch (ex) {
- }
-});
-
-add_task(function* test_removeLivemark_guid_succeeds() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , guid: "234567890ABC"
- });
-
- do_check_eq(livemark.guid, "234567890ABC");
-
- yield PlacesUtils.livemarks.removeLivemark({
- id: 789, guid: "234567890ABC"
- });
-
- do_check_eq((yield PlacesUtils.bookmarks.fetch("234567890ABC")), null);
-});
-
-add_task(function* test_removeLivemark_id_succeeds() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- });
-
- yield PlacesUtils.livemarks.removeLivemark({ id: livemark.id });
-
- do_check_eq((yield PlacesUtils.bookmarks.fetch("234567890ABC")), null);
-});
-
-add_task(function* test_getLivemark_emptyObject_throws() {
- try {
- yield PlacesUtils.livemarks.getLivemark({});
- do_throw("Invoking getLivemark with empty object should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_getLivemark_noValidId_throws() {
- try {
- yield PlacesUtils.livemarks.getLivemark({ id: -10, guid: "test"});
- do_throw("Invoking getLivemark with no valid id should throw");
- } catch (ex) {
- do_check_eq(ex.result, Cr.NS_ERROR_INVALID_ARG);
- }
-});
-
-add_task(function* test_getLivemark_nonExistentId_fails() {
- try {
- yield PlacesUtils.livemarks.getLivemark({ id: 1234 });
- do_throw("getLivemark for a non existent id should fail");
- } catch (ex) {}
-});
-
-add_task(function* test_getLivemark_nonExistentGUID_fails() {
- try {
- yield PlacesUtils.livemarks.getLivemark({ guid: "34567890ABCD" });
- do_throw("getLivemark for a non-existent guid should fail");
- } catch (ex) {}
-});
-
-add_task(function* test_getLivemark_guid_succeeds() {
- yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- , guid: "34567890ABCD" });
-
- // invalid id to check the guid wins.
- let livemark =
- yield PlacesUtils.livemarks.getLivemark({ id: 789, guid: "34567890ABCD" });
-
- do_check_eq(livemark.title, "test");
- do_check_eq(livemark.parentId, PlacesUtils.unfiledBookmarksFolderId);
- do_check_eq(livemark.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- do_check_true(livemark.feedURI.equals(FEED_URI));
- do_check_eq(livemark.siteURI, null);
- do_check_eq(livemark.guid, "34567890ABCD");
-
- let bookmark = yield PlacesUtils.bookmarks.fetch("34567890ABCD");
- do_check_eq(livemark.index, bookmark.index);
-});
-
-add_task(function* test_getLivemark_id_succeeds() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- });
-
- livemark = yield PlacesUtils.livemarks.getLivemark({ id: livemark.id });
-
- do_check_eq(livemark.title, "test");
- do_check_eq(livemark.parentId, PlacesUtils.unfiledBookmarksFolderId);
- do_check_eq(livemark.parentGuid, PlacesUtils.bookmarks.unfiledGuid);
- do_check_true(livemark.feedURI.equals(FEED_URI));
- do_check_eq(livemark.siteURI, null);
- do_check_guid_for_bookmark(livemark.id, livemark.guid);
-
- let bookmark = yield PlacesUtils.bookmarks.fetch(livemark.guid);
- do_check_eq(livemark.index, bookmark.index);
-});
-
-add_task(function* test_getLivemark_removeItem_contention() {
- // do not yield.
- PlacesUtils.livemarks.addLivemark({ title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- }).catch(() => { /* swallow errors*/ });
- yield PlacesUtils.bookmarks.eraseEverything();
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- });
-
- livemark = yield PlacesUtils.livemarks.getLivemark({ guid: livemark.guid });
-
- do_check_eq(livemark.title, "test");
- do_check_eq(livemark.parentId, PlacesUtils.unfiledBookmarksFolderId);
- do_check_true(livemark.feedURI.equals(FEED_URI));
- do_check_eq(livemark.siteURI, null);
- do_check_guid_for_bookmark(livemark.id, livemark.guid);
-});
-
-add_task(function* test_title_change() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI
- });
-
- yield PlacesUtils.bookmarks.update({ guid: livemark.guid,
- title: "test2" });
- // Poll for the title change.
- while (true) {
- let lm = yield PlacesUtils.livemarks.getLivemark({ guid: livemark.guid });
- if (lm.title == "test2")
- break;
- yield new Promise(resolve => do_timeout(resolve, 100));
- }
-});
-
-add_task(function* test_livemark_move() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI } );
-
- yield PlacesUtils.bookmarks.update({ guid: livemark.guid,
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX });
- // Poll for the parent change.
- while (true) {
- let lm = yield PlacesUtils.livemarks.getLivemark({ guid: livemark.guid });
- if (lm.parentGuid == PlacesUtils.bookmarks.toolbarGuid)
- break;
- yield new Promise(resolve => do_timeout(resolve, 100));
- }
-});
-
-add_task(function* test_livemark_removed() {
- let livemark = yield PlacesUtils.livemarks.addLivemark(
- { title: "test"
- , parentGuid: PlacesUtils.bookmarks.unfiledGuid
- , feedURI: FEED_URI } );
-
- yield PlacesUtils.bookmarks.remove(livemark.guid);
- // Poll for the livemark removal.
- while (true) {
- try {
- yield PlacesUtils.livemarks.getLivemark({ guid: livemark.guid });
- } catch (ex) {
- break;
- }
- yield new Promise(resolve => do_timeout(resolve, 100));
- }
-});
diff --git a/toolkit/components/places/tests/unit/test_multi_queries.js b/toolkit/components/places/tests/unit/test_multi_queries.js
deleted file mode 100644
index d485355a5..000000000
--- a/toolkit/components/places/tests/unit/test_multi_queries.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Adds a test URI visit to history.
- *
- * @param aURI
- * The URI to add a visit for.
- * @param aReferrer
- * The referring URI for the given URI. This can be null.
- */
-function* add_visit(aURI, aDayOffset, aTransition) {
- yield PlacesTestUtils.addVisits({
- uri: aURI,
- transition: aTransition,
- visitDate: (Date.now() + aDayOffset*86400000) * 1000
- });
-}
-
-function run_test()
-{
- run_next_test();
-}
-
-add_task(function* test_execute()
-{
- yield add_visit(uri("http://mirror1.mozilla.com/a"), -1, TRANSITION_LINK);
- yield add_visit(uri("http://mirror2.mozilla.com/b"), -2, TRANSITION_LINK);
- yield add_visit(uri("http://mirror3.mozilla.com/c"), -4, TRANSITION_FRAMED_LINK);
- yield add_visit(uri("http://mirror1.google.com/b"), -1, TRANSITION_EMBED);
- yield add_visit(uri("http://mirror2.google.com/a"), -2, TRANSITION_LINK);
- yield add_visit(uri("http://mirror1.apache.org/b"), -3, TRANSITION_LINK);
- yield add_visit(uri("http://mirror2.apache.org/a"), -4, TRANSITION_FRAMED_LINK);
-
- let queries = [
- PlacesUtils.history.getNewQuery(),
- PlacesUtils.history.getNewQuery()
- ];
- queries[0].domain = "mozilla.com";
- queries[1].domain = "google.com";
-
- let root = PlacesUtils.history.executeQueries(
- queries, queries.length, PlacesUtils.history.getNewQueryOptions()
- ).root;
- root.containerOpen = true;
- let childCount = root.childCount;
- root.containerOpen = false;
-
- do_check_eq(childCount, 3);
-});
diff --git a/toolkit/components/places/tests/unit/test_multi_word_tags.js b/toolkit/components/places/tests/unit/test_multi_word_tags.js
deleted file mode 100644
index 6a0e5f130..000000000
--- a/toolkit/components/places/tests/unit/test_multi_word_tags.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get history service
-try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
- getService(Ci.nsINavHistoryService);
-} catch (ex) {
- do_throw("Could not get history service\n");
-}
-
-// Get bookmark service
-try {
- var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
-}
-catch (ex) {
- do_throw("Could not get the nav-bookmarks-service\n");
-}
-
-// Get tagging service
-try {
- var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-} catch (ex) {
- do_throw("Could not get tagging service\n");
-}
-
-// main
-function run_test() {
- var uri1 = uri("http://site.tld/1");
- var uri2 = uri("http://site.tld/2");
- var uri3 = uri("http://site.tld/3");
- var uri4 = uri("http://site.tld/4");
- var uri5 = uri("http://site.tld/5");
- var uri6 = uri("http://site.tld/6");
-
- bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri1, bmsvc.DEFAULT_INDEX, null);
- bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri2, bmsvc.DEFAULT_INDEX, null);
- bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri3, bmsvc.DEFAULT_INDEX, null);
- bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri4, bmsvc.DEFAULT_INDEX, null);
- bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri5, bmsvc.DEFAULT_INDEX, null);
- bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri6, bmsvc.DEFAULT_INDEX, null);
-
- tagssvc.tagURI(uri1, ["foo"]);
- tagssvc.tagURI(uri2, ["bar"]);
- tagssvc.tagURI(uri3, ["cheese"]);
- tagssvc.tagURI(uri4, ["foo bar"]);
- tagssvc.tagURI(uri5, ["bar cheese"]);
- tagssvc.tagURI(uri6, ["foo bar cheese"]);
-
- // exclude livemark items, search for "item", should get one result
- var options = histsvc.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
-
- var query = histsvc.getNewQuery();
- query.searchTerms = "foo";
- var result = histsvc.executeQuery(query, options);
- var root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 3);
- do_check_eq(root.getChild(0).uri, "http://site.tld/1");
- do_check_eq(root.getChild(1).uri, "http://site.tld/4");
- do_check_eq(root.getChild(2).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "bar";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 4);
- do_check_eq(root.getChild(0).uri, "http://site.tld/2");
- do_check_eq(root.getChild(1).uri, "http://site.tld/4");
- do_check_eq(root.getChild(2).uri, "http://site.tld/5");
- do_check_eq(root.getChild(3).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "cheese";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 3);
- do_check_eq(root.getChild(0).uri, "http://site.tld/3");
- do_check_eq(root.getChild(1).uri, "http://site.tld/5");
- do_check_eq(root.getChild(2).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "foo bar";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 2);
- do_check_eq(root.getChild(0).uri, "http://site.tld/4");
- do_check_eq(root.getChild(1).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "bar foo";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 2);
- do_check_eq(root.getChild(0).uri, "http://site.tld/4");
- do_check_eq(root.getChild(1).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "bar cheese";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 2);
- do_check_eq(root.getChild(0).uri, "http://site.tld/5");
- do_check_eq(root.getChild(1).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "cheese bar";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 2);
- do_check_eq(root.getChild(0).uri, "http://site.tld/5");
- do_check_eq(root.getChild(1).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "foo bar cheese";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 1);
- do_check_eq(root.getChild(0).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "cheese foo bar";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 1);
- do_check_eq(root.getChild(0).uri, "http://site.tld/6");
- root.containerOpen = false;
-
- query.searchTerms = "cheese bar foo";
- result = histsvc.executeQuery(query, options);
- root = result.root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 1);
- do_check_eq(root.getChild(0).uri, "http://site.tld/6");
- root.containerOpen = false;
-}
diff --git a/toolkit/components/places/tests/unit/test_nsINavHistoryViewer.js b/toolkit/components/places/tests/unit/test_nsINavHistoryViewer.js
deleted file mode 100644
index 037ab7d08..000000000
--- a/toolkit/components/places/tests/unit/test_nsINavHistoryViewer.js
+++ /dev/null
@@ -1,256 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Get history service
-var histsvc = PlacesUtils.history;
-var bhist = PlacesUtils.bhistory;
-var bmsvc = PlacesUtils.bookmarks;
-
-var resultObserver = {
- insertedNode: null,
- nodeInserted: function(parent, node, newIndex) {
- this.insertedNode = node;
- },
- removedNode: null,
- nodeRemoved: function(parent, node, oldIndex) {
- this.removedNode = node;
- },
-
- nodeAnnotationChanged: function() {},
-
- newTitle: "",
- nodeChangedByTitle: null,
- nodeTitleChanged: function(node, newTitle) {
- this.nodeChangedByTitle = node;
- this.newTitle = newTitle;
- },
-
- newAccessCount: 0,
- newTime: 0,
- nodeChangedByHistoryDetails: null,
- nodeHistoryDetailsChanged: function(node,
- updatedVisitDate,
- updatedVisitCount) {
- this.nodeChangedByHistoryDetails = node
- this.newTime = updatedVisitDate;
- this.newAccessCount = updatedVisitCount;
- },
-
- movedNode: null,
- nodeMoved: function(node, oldParent, oldIndex, newParent, newIndex) {
- this.movedNode = node;
- },
- openedContainer: null,
- closedContainer: null,
- containerStateChanged: function (aNode, aOldState, aNewState) {
- if (aNewState == Ci.nsINavHistoryContainerResultNode.STATE_OPENED) {
- this.openedContainer = aNode;
- }
- else if (aNewState == Ci.nsINavHistoryContainerResultNode.STATE_CLOSED) {
- this.closedContainer = aNode;
- }
- },
- invalidatedContainer: null,
- invalidateContainer: function(node) {
- this.invalidatedContainer = node;
- },
- sortingMode: null,
- sortingChanged: function(sortingMode) {
- this.sortingMode = sortingMode;
- },
- inBatchMode: false,
- batching: function(aToggleMode) {
- do_check_neq(this.inBatchMode, aToggleMode);
- this.inBatchMode = aToggleMode;
- },
- result: null,
- reset: function() {
- this.insertedNode = null;
- this.removedNode = null;
- this.nodeChangedByTitle = null;
- this.nodeChangedByHistoryDetails = null;
- this.replacedNode = null;
- this.movedNode = null;
- this.openedContainer = null;
- this.closedContainer = null;
- this.invalidatedContainer = null;
- this.sortingMode = null;
- }
-};
-
-var testURI = uri("http://mozilla.com");
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function check_history_query() {
- var options = histsvc.getNewQueryOptions();
- options.sortingMode = options.SORT_BY_DATE_DESCENDING;
- options.resultType = options.RESULTS_AS_VISIT;
- var query = histsvc.getNewQuery();
- var result = histsvc.executeQuery(query, options);
- result.addObserver(resultObserver, false);
- var root = result.root;
- root.containerOpen = true;
-
- do_check_neq(resultObserver.openedContainer, null);
-
- // nsINavHistoryResultObserver.nodeInserted
- // add a visit
- PlacesTestUtils.addVisits(testURI).then(function() {
- do_check_eq(testURI.spec, resultObserver.insertedNode.uri);
-
- // nsINavHistoryResultObserver.nodeHistoryDetailsChanged
- // adding a visit causes nodeHistoryDetailsChanged for the folder
- do_check_eq(root.uri, resultObserver.nodeChangedByHistoryDetails.uri);
-
- // nsINavHistoryResultObserver.itemTitleChanged for a leaf node
- PlacesTestUtils.addVisits({ uri: testURI, title: "baz" }).then(function () {
- do_check_eq(resultObserver.nodeChangedByTitle.title, "baz");
-
- // nsINavHistoryResultObserver.nodeRemoved
- var removedURI = uri("http://google.com");
- PlacesTestUtils.addVisits(removedURI).then(function() {
- bhist.removePage(removedURI);
- do_check_eq(removedURI.spec, resultObserver.removedNode.uri);
-
- // nsINavHistoryResultObserver.invalidateContainer
- bhist.removePagesFromHost("mozilla.com", false);
- do_check_eq(root.uri, resultObserver.invalidatedContainer.uri);
-
- // nsINavHistoryResultObserver.sortingChanged
- resultObserver.invalidatedContainer = null;
- result.sortingMode = options.SORT_BY_TITLE_ASCENDING;
- do_check_eq(resultObserver.sortingMode, options.SORT_BY_TITLE_ASCENDING);
- do_check_eq(resultObserver.invalidatedContainer, result.root);
-
- // nsINavHistoryResultObserver.invalidateContainer
- PlacesTestUtils.clearHistoryEnabled().then(() => {
- do_check_eq(root.uri, resultObserver.invalidatedContainer.uri);
-
- // nsINavHistoryResultObserver.batching
- do_check_false(resultObserver.inBatchMode);
- histsvc.runInBatchMode({
- runBatched: function (aUserData) {
- do_check_true(resultObserver.inBatchMode);
- }
- }, null);
- do_check_false(resultObserver.inBatchMode);
- bmsvc.runInBatchMode({
- runBatched: function (aUserData) {
- do_check_true(resultObserver.inBatchMode);
- }
- }, null);
- do_check_false(resultObserver.inBatchMode);
-
- root.containerOpen = false;
- do_check_eq(resultObserver.closedContainer, resultObserver.openedContainer);
- result.removeObserver(resultObserver);
- resultObserver.reset();
- PlacesTestUtils.promiseAsyncUpdates().then(run_next_test);
- });
- });
- });
- });
-});
-
-add_test(function check_bookmarks_query() {
- var options = histsvc.getNewQueryOptions();
- var query = histsvc.getNewQuery();
- query.setFolders([bmsvc.bookmarksMenuFolder], 1);
- var result = histsvc.executeQuery(query, options);
- result.addObserver(resultObserver, false);
- var root = result.root;
- root.containerOpen = true;
-
- do_check_neq(resultObserver.openedContainer, null);
-
- // nsINavHistoryResultObserver.nodeInserted
- // add a bookmark
- var testBookmark = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, testURI, bmsvc.DEFAULT_INDEX, "foo");
- do_check_eq("foo", resultObserver.insertedNode.title);
- do_check_eq(testURI.spec, resultObserver.insertedNode.uri);
-
- // nsINavHistoryResultObserver.nodeHistoryDetailsChanged
- // adding a visit causes nodeHistoryDetailsChanged for the folder
- do_check_eq(root.uri, resultObserver.nodeChangedByHistoryDetails.uri);
-
- // nsINavHistoryResultObserver.nodeTitleChanged for a leaf node
- bmsvc.setItemTitle(testBookmark, "baz");
- do_check_eq(resultObserver.nodeChangedByTitle.title, "baz");
- do_check_eq(resultObserver.newTitle, "baz");
-
- var testBookmark2 = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri("http://google.com"), bmsvc.DEFAULT_INDEX, "foo");
- bmsvc.moveItem(testBookmark2, bmsvc.bookmarksMenuFolder, 0);
- do_check_eq(resultObserver.movedNode.itemId, testBookmark2);
-
- // nsINavHistoryResultObserver.nodeRemoved
- bmsvc.removeItem(testBookmark2);
- do_check_eq(testBookmark2, resultObserver.removedNode.itemId);
-
- // XXX nsINavHistoryResultObserver.invalidateContainer
-
- // nsINavHistoryResultObserver.sortingChanged
- resultObserver.invalidatedContainer = null;
- result.sortingMode = options.SORT_BY_TITLE_ASCENDING;
- do_check_eq(resultObserver.sortingMode, options.SORT_BY_TITLE_ASCENDING);
- do_check_eq(resultObserver.invalidatedContainer, result.root);
-
- // nsINavHistoryResultObserver.batching
- do_check_false(resultObserver.inBatchMode);
- histsvc.runInBatchMode({
- runBatched: function (aUserData) {
- do_check_true(resultObserver.inBatchMode);
- }
- }, null);
- do_check_false(resultObserver.inBatchMode);
- bmsvc.runInBatchMode({
- runBatched: function (aUserData) {
- do_check_true(resultObserver.inBatchMode);
- }
- }, null);
- do_check_false(resultObserver.inBatchMode);
-
- root.containerOpen = false;
- do_check_eq(resultObserver.closedContainer, resultObserver.openedContainer);
- result.removeObserver(resultObserver);
- resultObserver.reset();
- PlacesTestUtils.promiseAsyncUpdates().then(run_next_test);
-});
-
-add_test(function check_mixed_query() {
- var options = histsvc.getNewQueryOptions();
- var query = histsvc.getNewQuery();
- query.onlyBookmarked = true;
- var result = histsvc.executeQuery(query, options);
- result.addObserver(resultObserver, false);
- var root = result.root;
- root.containerOpen = true;
-
- do_check_neq(resultObserver.openedContainer, null);
-
- // nsINavHistoryResultObserver.batching
- do_check_false(resultObserver.inBatchMode);
- histsvc.runInBatchMode({
- runBatched: function (aUserData) {
- do_check_true(resultObserver.inBatchMode);
- }
- }, null);
- do_check_false(resultObserver.inBatchMode);
- bmsvc.runInBatchMode({
- runBatched: function (aUserData) {
- do_check_true(resultObserver.inBatchMode);
- }
- }, null);
- do_check_false(resultObserver.inBatchMode);
-
- root.containerOpen = false;
- do_check_eq(resultObserver.closedContainer, resultObserver.openedContainer);
- result.removeObserver(resultObserver);
- resultObserver.reset();
- PlacesTestUtils.promiseAsyncUpdates().then(run_next_test);
-});
diff --git a/toolkit/components/places/tests/unit/test_null_interfaces.js b/toolkit/components/places/tests/unit/test_null_interfaces.js
deleted file mode 100644
index 524837ca3..000000000
--- a/toolkit/components/places/tests/unit/test_null_interfaces.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
-* License, v. 2.0. If a copy of the MPL was not distributed with this
-* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test bug 489872 to make sure passing nulls to nsNavHistory doesn't crash.
- */
-
-// Make an array of services to test, each specifying a class id, interface
-// and an array of function names that don't throw when passed nulls
-var testServices = [
- ["browser/nav-history-service;1",
- ["nsINavHistoryService"],
- ["queryStringToQueries", "removePagesByTimeframe", "removePagesFromHost", "getObservers"]
- ],
- ["browser/nav-bookmarks-service;1",
- ["nsINavBookmarksService", "nsINavHistoryObserver", "nsIAnnotationObserver"],
- ["createFolder", "getObservers", "onFrecencyChanged", "onTitleChanged",
- "onPageAnnotationSet", "onPageAnnotationRemoved", "onDeleteURI"]
- ],
- ["browser/livemark-service;2", ["mozIAsyncLivemarks"], ["reloadLivemarks"]],
- ["browser/annotation-service;1", ["nsIAnnotationService"], []],
- ["browser/favicon-service;1", ["nsIFaviconService"], []],
- ["browser/tagging-service;1", ["nsITaggingService"], []],
-];
-do_print(testServices.join("\n"));
-
-function run_test()
-{
- for (let [cid, ifaces, nothrow] of testServices) {
- do_print(`Running test with ${cid} ${ifaces.join(", ")} ${nothrow}`);
- let s = Cc["@mozilla.org/" + cid].getService(Ci.nsISupports);
- for (let iface of ifaces) {
- s.QueryInterface(Ci[iface]);
- }
-
- let okName = function(name) {
- do_print(`Checking if function is okay to test: ${name}`);
- let func = s[name];
-
- let mesg = "";
- if (typeof func != "function")
- mesg = "Not a function!";
- else if (func.length == 0)
- mesg = "No args needed!";
- else if (name == "QueryInterface")
- mesg = "Ignore QI!";
-
- if (mesg) {
- do_print(`${mesg} Skipping: ${name}`);
- return false;
- }
-
- return true;
- }
-
- do_print(`Generating an array of functions to test service: ${s}`);
- for (let n of Object.keys(s).filter(i => okName(i)).sort()) {
- do_print(`\nTesting ${ifaces.join(", ")} function with null args: ${n}`);
-
- let func = s[n];
- let num = func.length;
- do_print(`Generating array of nulls for #args: ${num}`);
- let args = Array(num).fill(null);
-
- let tryAgain = true;
- while (tryAgain == true) {
- try {
- do_print(`Calling with args: ${JSON.stringify(args)}`);
- func.apply(s, args);
-
- do_print(`The function did not throw! Is it one of the nothrow? ${nothrow}`);
- Assert.notEqual(nothrow.indexOf(n), -1);
-
- do_print("Must have been an expected nothrow, so no need to try again");
- tryAgain = false;
- }
- catch (ex) {
- if (ex.result == Cr.NS_ERROR_ILLEGAL_VALUE) {
- do_print(`Caught an expected exception: ${ex.name}`);
- do_print("Moving on to the next test..");
- tryAgain = false;
- } else if (ex.result == Cr.NS_ERROR_XPC_NEED_OUT_OBJECT) {
- let pos = Number(ex.message.match(/object arg (\d+)/)[1]);
- do_print(`Function call expects an out object at ${pos}`);
- args[pos] = {};
- } else if (ex.result == Cr.NS_ERROR_NOT_IMPLEMENTED) {
- do_print(`Method not implemented exception: ${ex.name}`);
- do_print("Moving on to the next test..");
- tryAgain = false;
- } else {
- throw ex;
- }
- }
- }
- }
- }
-}
diff --git a/toolkit/components/places/tests/unit/test_onItemChanged_tags.js b/toolkit/components/places/tests/unit/test_onItemChanged_tags.js
deleted file mode 100644
index 7a0eb354d..000000000
--- a/toolkit/components/places/tests/unit/test_onItemChanged_tags.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This test checks that changing a tag for a bookmark with multiple tags
-// notifies OnItemChanged("tags") only once, and not once per tag.
-
-function run_test() {
- do_test_pending();
-
- let tags = ["a", "b", "c"];
- let uri = NetUtil.newURI("http://1.moz.org/");
-
- let id = PlacesUtils.bookmarks.insertBookmark(
- PlacesUtils.unfiledBookmarksFolderId, uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX, "Bookmark 1"
- );
- PlacesUtils.tagging.tagURI(uri, tags);
-
- let bookmarksObserver = {
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsINavBookmarkObserver
- ]),
-
- _changedCount: 0,
- onItemChanged: function (aItemId, aProperty, aIsAnnotationProperty, aValue,
- aLastModified, aItemType) {
- if (aProperty == "tags") {
- do_check_eq(aItemId, id);
- this._changedCount++;
- }
- },
-
- onItemRemoved: function (aItemId, aParentId, aIndex, aItemType) {
- if (aItemId == id) {
- PlacesUtils.bookmarks.removeObserver(this);
- do_check_eq(this._changedCount, 2);
- do_test_finished();
- }
- },
-
- onItemAdded: function () {},
- onBeginUpdateBatch: function () {},
- onEndUpdateBatch: function () {},
- onItemVisited: function () {},
- onItemMoved: function () {},
- };
- PlacesUtils.bookmarks.addObserver(bookmarksObserver, false);
-
- PlacesUtils.tagging.tagURI(uri, ["d"]);
- PlacesUtils.tagging.tagURI(uri, ["e"]);
- PlacesUtils.bookmarks.removeItem(id);
-}
diff --git a/toolkit/components/places/tests/unit/test_pageGuid_bookmarkGuid.js b/toolkit/components/places/tests/unit/test_pageGuid_bookmarkGuid.js
deleted file mode 100644
index f6131b211..000000000
--- a/toolkit/components/places/tests/unit/test_pageGuid_bookmarkGuid.js
+++ /dev/null
@@ -1,179 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const bmsvc = PlacesUtils.bookmarks;
-const histsvc = PlacesUtils.history;
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test_addBookmarksAndCheckGuids() {
- let folder = bmsvc.createFolder(bmsvc.placesRoot, "test folder", bmsvc.DEFAULT_INDEX);
- bmsvc.insertBookmark(folder, uri("http://test1.com/"),
- bmsvc.DEFAULT_INDEX, "1 title");
- bmsvc.insertBookmark(folder, uri("http://test2.com/"),
- bmsvc.DEFAULT_INDEX, "2 title");
- bmsvc.insertBookmark(folder, uri("http://test3.com/"),
- bmsvc.DEFAULT_INDEX, "3 title");
- bmsvc.insertSeparator(folder, bmsvc.DEFAULT_INDEX);
- bmsvc.createFolder(folder, "test folder 2", bmsvc.DEFAULT_INDEX);
-
- let root = PlacesUtils.getFolderContents(folder).root;
- do_check_eq(root.childCount, 5);
-
- // check bookmark guids
- let bookmarkGuidZero = root.getChild(0).bookmarkGuid;
- do_check_eq(bookmarkGuidZero.length, 12);
- // bookmarks have bookmark guids
- do_check_eq(root.getChild(1).bookmarkGuid.length, 12);
- do_check_eq(root.getChild(2).bookmarkGuid.length, 12);
- // separator has bookmark guid
- do_check_eq(root.getChild(3).bookmarkGuid.length, 12);
- // folder has bookmark guid
- do_check_eq(root.getChild(4).bookmarkGuid.length, 12);
- // all bookmark guids are different.
- do_check_neq(bookmarkGuidZero, root.getChild(1).bookmarkGuid);
- do_check_neq(root.getChild(1).bookmarkGuid, root.getChild(2).bookmarkGuid);
- do_check_neq(root.getChild(2).bookmarkGuid, root.getChild(3).bookmarkGuid);
- do_check_neq(root.getChild(3).bookmarkGuid, root.getChild(4).bookmarkGuid);
-
- // check page guids
- let pageGuidZero = root.getChild(0).pageGuid;
- do_check_eq(pageGuidZero.length, 12);
- // bookmarks have page guids
- do_check_eq(root.getChild(1).pageGuid.length, 12);
- do_check_eq(root.getChild(2).pageGuid.length, 12);
- // folder and separator don't have page guids
- do_check_eq(root.getChild(3).pageGuid, "");
- do_check_eq(root.getChild(4).pageGuid, "");
-
- do_check_neq(pageGuidZero, root.getChild(1).pageGuid);
- do_check_neq(root.getChild(1).pageGuid, root.getChild(2).pageGuid);
-
- root.containerOpen = false;
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_updateBookmarksAndCheckGuids() {
- let folder = bmsvc.createFolder(bmsvc.placesRoot, "test folder", bmsvc.DEFAULT_INDEX);
- let b1 = bmsvc.insertBookmark(folder, uri("http://test1.com/"),
- bmsvc.DEFAULT_INDEX, "1 title");
- let f1 = bmsvc.createFolder(folder, "test folder 2", bmsvc.DEFAULT_INDEX);
-
- let root = PlacesUtils.getFolderContents(folder).root;
- do_check_eq(root.childCount, 2);
-
- // ensure the bookmark and page guids remain the same after modifing other property.
- let bookmarkGuidZero = root.getChild(0).bookmarkGuid;
- let pageGuidZero = root.getChild(0).pageGuid;
- bmsvc.setItemTitle(b1, "1 title mod");
- do_check_eq(root.getChild(0).title, "1 title mod");
- do_check_eq(root.getChild(0).bookmarkGuid, bookmarkGuidZero);
- do_check_eq(root.getChild(0).pageGuid, pageGuidZero);
-
- let bookmarkGuidOne = root.getChild(1).bookmarkGuid;
- let pageGuidOne = root.getChild(1).pageGuid;
- bmsvc.setItemTitle(f1, "test foolder 234");
- do_check_eq(root.getChild(1).title, "test foolder 234");
- do_check_eq(root.getChild(1).bookmarkGuid, bookmarkGuidOne);
- do_check_eq(root.getChild(1).pageGuid, pageGuidOne);
-
- root.containerOpen = false;
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_addVisitAndCheckGuid() {
- // add a visit and test page guid and non-existing bookmark guids.
- let sourceURI = uri("http://test4.com/");
- yield PlacesTestUtils.addVisits({ uri: sourceURI });
- do_check_eq(bmsvc.getBookmarkedURIFor(sourceURI), null);
-
- let options = histsvc.getNewQueryOptions();
- let query = histsvc.getNewQuery();
- query.uri = sourceURI;
- let root = histsvc.executeQuery(query, options).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 1);
-
- do_check_valid_places_guid(root.getChild(0).pageGuid);
- do_check_eq(root.getChild(0).bookmarkGuid, "");
- root.containerOpen = false;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_addItemsWithInvalidGUIDsFails() {
- const INVALID_GUID = "XYZ";
- try {
- bmsvc.createFolder(bmsvc.placesRoot, "XYZ folder",
- bmsvc.DEFAULT_INDEX, INVALID_GUID);
- do_throw("Adding a folder with an invalid guid should fail");
- }
- catch (ex) { }
-
- let folder = bmsvc.createFolder(bmsvc.placesRoot, "test folder",
- bmsvc.DEFAULT_INDEX);
- try {
- bmsvc.insertBookmark(folder, uri("http://test.tld"), bmsvc.DEFAULT_INDEX,
- "title", INVALID_GUID);
- do_throw("Adding a bookmark with an invalid guid should fail");
- }
- catch (ex) { }
-
- try {
- bmsvc.insertSeparator(folder, bmsvc.DEFAULT_INDEX, INVALID_GUID);
- do_throw("Adding a separator with an invalid guid should fail");
- }
- catch (ex) { }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_addItemsWithGUIDs() {
- const FOLDER_GUID = "FOLDER--GUID";
- const BOOKMARK_GUID = "BM------GUID";
- const SEPARATOR_GUID = "SEP-----GUID";
-
- let folder = bmsvc.createFolder(bmsvc.placesRoot, "test folder",
- bmsvc.DEFAULT_INDEX, FOLDER_GUID);
- bmsvc.insertBookmark(folder, uri("http://test1.com/"), bmsvc.DEFAULT_INDEX,
- "1 title", BOOKMARK_GUID);
- bmsvc.insertSeparator(folder, bmsvc.DEFAULT_INDEX, SEPARATOR_GUID);
-
- let root = PlacesUtils.getFolderContents(folder).root;
- do_check_eq(root.childCount, 2);
- do_check_eq(root.bookmarkGuid, FOLDER_GUID);
- do_check_eq(root.getChild(0).bookmarkGuid, BOOKMARK_GUID);
- do_check_eq(root.getChild(1).bookmarkGuid, SEPARATOR_GUID);
-
- root.containerOpen = false;
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_emptyGUIDIgnored() {
- let folder = bmsvc.createFolder(bmsvc.placesRoot, "test folder",
- bmsvc.DEFAULT_INDEX, "");
- do_check_valid_places_guid(PlacesUtils.getFolderContents(folder)
- .root.bookmarkGuid);
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_usingSameGUIDFails() {
- const GUID = "XYZXYZXYZXYZ";
- bmsvc.createFolder(bmsvc.placesRoot, "test folder",
- bmsvc.DEFAULT_INDEX, GUID);
- try {
- bmsvc.createFolder(bmsvc.placesRoot, "test folder 2",
- bmsvc.DEFAULT_INDEX, GUID);
- do_throw("Using the same guid twice should fail");
- }
- catch (ex) { }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
diff --git a/toolkit/components/places/tests/unit/test_placeURIs.js b/toolkit/components/places/tests/unit/test_placeURIs.js
deleted file mode 100644
index 0f585ca51..000000000
--- a/toolkit/components/places/tests/unit/test_placeURIs.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-
-// Get history service
-try {
- var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsINavHistoryService);
-} catch (ex) {
- do_throw("Could not get history service\n");
-}
-
-// main
-function run_test() {
- // XXX Full testing coverage for QueriesToQueryString and
- // QueryStringToQueries
-
- var bs = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
- getService(Ci.nsINavBookmarksService);
- const NHQO = Ci.nsINavHistoryQueryOptions;
- // Bug 376798
- var query = histsvc.getNewQuery();
- query.setFolders([bs.placesRoot], 1);
- do_check_eq(histsvc.queriesToQueryString([query], 1, histsvc.getNewQueryOptions()),
- "place:folder=PLACES_ROOT");
-
- // Bug 378828
- var options = histsvc.getNewQueryOptions();
- options.sortingAnnotation = "test anno";
- options.sortingMode = NHQO.SORT_BY_ANNOTATION_DESCENDING;
- var placeURI =
- "place:folder=PLACES_ROOT&sort=" + NHQO.SORT_BY_ANNOTATION_DESCENDING +
- "&sortingAnnotation=test%20anno";
- do_check_eq(histsvc.queriesToQueryString([query], 1, options),
- placeURI);
- options = {};
- histsvc.queryStringToQueries(placeURI, { }, {}, options);
- do_check_eq(options.value.sortingAnnotation, "test anno");
- do_check_eq(options.value.sortingMode, NHQO.SORT_BY_ANNOTATION_DESCENDING);
-}
diff --git a/toolkit/components/places/tests/unit/test_placesTxn.js b/toolkit/components/places/tests/unit/test_placesTxn.js
deleted file mode 100644
index 3cc9809bb..000000000
--- a/toolkit/components/places/tests/unit/test_placesTxn.js
+++ /dev/null
@@ -1,937 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var bmsvc = PlacesUtils.bookmarks;
-var tagssvc = PlacesUtils.tagging;
-var annosvc = PlacesUtils.annotations;
-var txnManager = PlacesUtils.transactionManager;
-const DESCRIPTION_ANNO = "bookmarkProperties/description";
-
-function* promiseKeyword(keyword, href, postData) {
- while (true) {
- let entry = yield PlacesUtils.keywords.fetch(keyword);
- if (href == null && !entry)
- break;
- if (entry && entry.url.href == href && entry.postData == postData) {
- break;
- }
-
- yield new Promise(resolve => do_timeout(100, resolve));
- }
-}
-
-// create and add bookmarks observer
-var observer = {
-
- onBeginUpdateBatch: function() {
- this._beginUpdateBatch = true;
- },
- _beginUpdateBatch: false,
-
- onEndUpdateBatch: function() {
- this._endUpdateBatch = true;
- },
- _endUpdateBatch: false,
-
- onItemAdded: function(id, folder, index, itemType, uri) {
- this._itemAddedId = id;
- this._itemAddedParent = folder;
- this._itemAddedIndex = index;
- this._itemAddedType = itemType;
- },
- _itemAddedId: null,
- _itemAddedParent: null,
- _itemAddedIndex: null,
- _itemAddedType: null,
-
- onItemRemoved: function(id, folder, index, itemType) {
- this._itemRemovedId = id;
- this._itemRemovedFolder = folder;
- this._itemRemovedIndex = index;
- },
- _itemRemovedId: null,
- _itemRemovedFolder: null,
- _itemRemovedIndex: null,
-
- onItemChanged: function(id, property, isAnnotationProperty, newValue,
- lastModified, itemType) {
- // The transaction manager is being rewritten in bug 891303, so just
- // skip checking this for now.
- if (property == "tags")
- return;
- this._itemChangedId = id;
- this._itemChangedProperty = property;
- this._itemChanged_isAnnotationProperty = isAnnotationProperty;
- this._itemChangedValue = newValue;
- },
- _itemChangedId: null,
- _itemChangedProperty: null,
- _itemChanged_isAnnotationProperty: null,
- _itemChangedValue: null,
-
- onItemVisited: function(id, visitID, time) {
- this._itemVisitedId = id;
- this._itemVisitedVistId = visitID;
- this._itemVisitedTime = time;
- },
- _itemVisitedId: null,
- _itemVisitedVistId: null,
- _itemVisitedTime: null,
-
- onItemMoved: function(id, oldParent, oldIndex, newParent, newIndex,
- itemType) {
- this._itemMovedId = id;
- this._itemMovedOldParent = oldParent;
- this._itemMovedOldIndex = oldIndex;
- this._itemMovedNewParent = newParent;
- this._itemMovedNewIndex = newIndex;
- },
- _itemMovedId: null,
- _itemMovedOldParent: null,
- _itemMovedOldIndex: null,
- _itemMovedNewParent: null,
- _itemMovedNewIndex: null,
-
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsINavBookmarkObserver) ||
- iid.equals(Ci.nsISupports)) {
- return this;
- }
- throw Cr.NS_ERROR_NO_INTERFACE;
- }
-};
-
-// index at which items should begin
-var bmStartIndex = 0;
-
-// get bookmarks root id
-var root = PlacesUtils.bookmarksMenuFolderId;
-
-add_task(function* init() {
- bmsvc.addObserver(observer, false);
- do_register_cleanup(function () {
- bmsvc.removeObserver(observer);
- });
-});
-
-add_task(function* test_create_folder_with_description() {
- const TEST_FOLDERNAME = "Test creating a folder with a description";
- const TEST_DESCRIPTION = "this is my test description";
-
- let annos = [{ name: DESCRIPTION_ANNO,
- type: annosvc.TYPE_STRING,
- flags: 0,
- value: TEST_DESCRIPTION,
- expires: annosvc.EXPIRE_NEVER }];
- let txn = new PlacesCreateFolderTransaction(TEST_FOLDERNAME, root, bmStartIndex, annos);
- txnManager.doTransaction(txn);
-
- // This checks that calling undoTransaction on an "empty batch" doesn't
- // undo the previous transaction (getItemTitle will fail)
- txnManager.beginBatch(null);
- txnManager.endBatch(false);
- txnManager.undoTransaction();
-
- let folderId = observer._itemAddedId;
- do_check_eq(bmsvc.getItemTitle(folderId), TEST_FOLDERNAME);
- do_check_eq(observer._itemAddedIndex, bmStartIndex);
- do_check_eq(observer._itemAddedParent, root);
- do_check_eq(observer._itemAddedId, folderId);
- do_check_eq(TEST_DESCRIPTION, annosvc.getItemAnnotation(folderId, DESCRIPTION_ANNO));
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, folderId);
- do_check_eq(observer._itemRemovedFolder, root);
- do_check_eq(observer._itemRemovedIndex, bmStartIndex);
-
- txn.redoTransaction();
- do_check_eq(observer._itemAddedIndex, bmStartIndex);
- do_check_eq(observer._itemAddedParent, root);
- do_check_eq(observer._itemAddedId, folderId);
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, folderId);
- do_check_eq(observer._itemRemovedFolder, root);
- do_check_eq(observer._itemRemovedIndex, bmStartIndex);
-});
-
-add_task(function* test_create_item() {
- let testURI = NetUtil.newURI("http://test_create_item.com");
-
- let txn = new PlacesCreateBookmarkTransaction(testURI, root, bmStartIndex,
- "Test creating an item");
-
- txnManager.doTransaction(txn);
- let id = bmsvc.getBookmarkIdsForURI(testURI)[0];
- do_check_eq(observer._itemAddedId, id);
- do_check_eq(observer._itemAddedIndex, bmStartIndex);
- do_check_true(bmsvc.isBookmarked(testURI));
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, id);
- do_check_eq(observer._itemRemovedIndex, bmStartIndex);
- do_check_false(bmsvc.isBookmarked(testURI));
-
- txn.redoTransaction();
- do_check_true(bmsvc.isBookmarked(testURI));
- let newId = bmsvc.getBookmarkIdsForURI(testURI)[0];
- do_check_eq(observer._itemAddedIndex, bmStartIndex);
- do_check_eq(observer._itemAddedParent, root);
- do_check_eq(observer._itemAddedId, newId);
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, newId);
- do_check_eq(observer._itemRemovedFolder, root);
- do_check_eq(observer._itemRemovedIndex, bmStartIndex);
-});
-
-add_task(function* test_create_item_to_folder() {
- const TEST_FOLDERNAME = "Test creating item to a folder";
- let testURI = NetUtil.newURI("http://test_create_item_to_folder.com");
- let folderId = bmsvc.createFolder(root, TEST_FOLDERNAME, bmsvc.DEFAULT_INDEX);
-
- let txn = new PlacesCreateBookmarkTransaction(testURI, folderId, bmStartIndex,
- "Test creating item");
- txnManager.doTransaction(txn);
- let bkmId = bmsvc.getBookmarkIdsForURI(testURI)[0];
- do_check_eq(observer._itemAddedId, bkmId);
- do_check_eq(observer._itemAddedIndex, bmStartIndex);
- do_check_true(bmsvc.isBookmarked(testURI));
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, bkmId);
- do_check_eq(observer._itemRemovedIndex, bmStartIndex);
-
- txn.redoTransaction();
- let newBkmId = bmsvc.getBookmarkIdsForURI(testURI)[0];
- do_check_eq(observer._itemAddedIndex, bmStartIndex);
- do_check_eq(observer._itemAddedParent, folderId);
- do_check_eq(observer._itemAddedId, newBkmId);
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, newBkmId);
- do_check_eq(observer._itemRemovedFolder, folderId);
- do_check_eq(observer._itemRemovedIndex, bmStartIndex);
-});
-
-add_task(function* test_move_items_to_folder() {
- let testFolderId = bmsvc.createFolder(root, "Test move items", bmsvc.DEFAULT_INDEX);
- let testURI = NetUtil.newURI("http://test_move_items.com");
- let testBkmId = bmsvc.insertBookmark(testFolderId, testURI, bmsvc.DEFAULT_INDEX, "1: Test move items");
- bmsvc.insertBookmark(testFolderId, testURI, bmsvc.DEFAULT_INDEX, "2: Test move items");
-
- // Moving items between the same folder
- let sameTxn = new PlacesMoveItemTransaction(testBkmId, testFolderId, bmsvc.DEFAULT_INDEX);
-
- sameTxn.doTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, testFolderId);
- do_check_eq(observer._itemMovedOldIndex, 0);
- do_check_eq(observer._itemMovedNewParent, testFolderId);
- do_check_eq(observer._itemMovedNewIndex, 1);
-
- sameTxn.undoTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, testFolderId);
- do_check_eq(observer._itemMovedOldIndex, 1);
- do_check_eq(observer._itemMovedNewParent, testFolderId);
- do_check_eq(observer._itemMovedNewIndex, 0);
-
- sameTxn.redoTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, testFolderId);
- do_check_eq(observer._itemMovedOldIndex, 0);
- do_check_eq(observer._itemMovedNewParent, testFolderId);
- do_check_eq(observer._itemMovedNewIndex, 1);
-
- sameTxn.undoTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, testFolderId);
- do_check_eq(observer._itemMovedOldIndex, 1);
- do_check_eq(observer._itemMovedNewParent, testFolderId);
- do_check_eq(observer._itemMovedNewIndex, 0);
-
- // Moving items between different folders
- let folderId = bmsvc.createFolder(testFolderId,
- "Test move items between different folders",
- bmsvc.DEFAULT_INDEX);
- let diffTxn = new PlacesMoveItemTransaction(testBkmId, folderId, bmsvc.DEFAULT_INDEX);
-
- diffTxn.doTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, testFolderId);
- do_check_eq(observer._itemMovedOldIndex, 0);
- do_check_eq(observer._itemMovedNewParent, folderId);
- do_check_eq(observer._itemMovedNewIndex, 0);
-
- sameTxn.undoTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, folderId);
- do_check_eq(observer._itemMovedOldIndex, 0);
- do_check_eq(observer._itemMovedNewParent, testFolderId);
- do_check_eq(observer._itemMovedNewIndex, 0);
-
- diffTxn.redoTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, testFolderId);
- do_check_eq(observer._itemMovedOldIndex, 0);
- do_check_eq(observer._itemMovedNewParent, folderId);
- do_check_eq(observer._itemMovedNewIndex, 0);
-
- sameTxn.undoTransaction();
- do_check_eq(observer._itemMovedId, testBkmId);
- do_check_eq(observer._itemMovedOldParent, folderId);
- do_check_eq(observer._itemMovedOldIndex, 0);
- do_check_eq(observer._itemMovedNewParent, testFolderId);
- do_check_eq(observer._itemMovedNewIndex, 0);
-});
-
-add_task(function* test_remove_folder() {
- let testFolder = bmsvc.createFolder(root, "Test Removing a Folder", bmsvc.DEFAULT_INDEX);
- let folderId = bmsvc.createFolder(testFolder, "Removed Folder", bmsvc.DEFAULT_INDEX);
-
- let txn = new PlacesRemoveItemTransaction(folderId);
-
- txn.doTransaction();
- do_check_eq(observer._itemRemovedId, folderId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
-
- txn.undoTransaction();
- do_check_eq(observer._itemAddedId, folderId);
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
-
- txn.redoTransaction();
- do_check_eq(observer._itemRemovedId, folderId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
-
- txn.undoTransaction();
- do_check_eq(observer._itemAddedId, folderId);
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
-});
-
-add_task(function* test_remove_item_with_tag() {
- // Notice in this case the tag persists since other bookmarks have same uri.
- let testFolder = bmsvc.createFolder(root, "Test removing an item with a tag",
- bmsvc.DEFAULT_INDEX);
-
- const TAG_NAME = "tag-test_remove_item_with_tag";
- let testURI = NetUtil.newURI("http://test_remove_item_with_tag.com");
- let testBkmId = bmsvc.insertBookmark(testFolder, testURI, bmsvc.DEFAULT_INDEX, "test-item1");
-
- // create bookmark for not removing tag.
- bmsvc.insertBookmark(testFolder, testURI, bmsvc.DEFAULT_INDEX, "test-item2");
-
- // set tag
- tagssvc.tagURI(testURI, [TAG_NAME]);
-
- let txn = new PlacesRemoveItemTransaction(testBkmId);
-
- txn.doTransaction();
- do_check_eq(observer._itemRemovedId, testBkmId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
- do_check_eq(tagssvc.getTagsForURI(testURI), TAG_NAME);
-
- txn.undoTransaction();
- let newbkmk2Id = observer._itemAddedId;
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
- do_check_eq(tagssvc.getTagsForURI(testURI)[0], TAG_NAME);
-
- txn.redoTransaction();
- do_check_eq(observer._itemRemovedId, newbkmk2Id);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
- do_check_eq(tagssvc.getTagsForURI(testURI)[0], TAG_NAME);
-
- txn.undoTransaction();
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
- do_check_eq(tagssvc.getTagsForURI(testURI)[0], TAG_NAME);
-});
-
-add_task(function* test_remove_item_with_keyword() {
- // Notice in this case the tag persists since other bookmarks have same uri.
- let testFolder = bmsvc.createFolder(root, "Test removing an item with a keyword",
- bmsvc.DEFAULT_INDEX);
-
- const KEYWORD = "test: test removing an item with a keyword";
- let testURI = NetUtil.newURI("http://test_remove_item_with_keyword.com");
- let testBkmId = bmsvc.insertBookmark(testFolder, testURI, bmsvc.DEFAULT_INDEX, "test-item1");
-
- // set keyword
- yield PlacesUtils.keywords.insert({ url: testURI.spec, keyword: KEYWORD});
-
- let txn = new PlacesRemoveItemTransaction(testBkmId);
-
- txn.doTransaction();
- do_check_eq(observer._itemRemovedId, testBkmId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
- yield promiseKeyword(KEYWORD, null);
-
- txn.undoTransaction();
- let newbkmk2Id = observer._itemAddedId;
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
- yield promiseKeyword(KEYWORD, testURI.spec);
-
- txn.redoTransaction();
- do_check_eq(observer._itemRemovedId, newbkmk2Id);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
- yield promiseKeyword(KEYWORD, null);
-
- txn.undoTransaction();
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
-});
-
-add_task(function* test_creating_separator() {
- let testFolder = bmsvc.createFolder(root, "Test creating a separator", bmsvc.DEFAULT_INDEX);
-
- let txn = new PlacesCreateSeparatorTransaction(testFolder, 0);
- txn.doTransaction();
-
- let sepId = observer._itemAddedId;
- do_check_eq(observer._itemAddedIndex, 0);
- do_check_eq(observer._itemAddedParent, testFolder);
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, sepId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
-
- txn.redoTransaction();
- let newSepId = observer._itemAddedId;
- do_check_eq(observer._itemAddedIndex, 0);
- do_check_eq(observer._itemAddedParent, testFolder);
-
- txn.undoTransaction();
- do_check_eq(observer._itemRemovedId, newSepId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
-});
-
-add_task(function* test_removing_separator() {
- let testFolder = bmsvc.createFolder(root, "Test removing a separator", bmsvc.DEFAULT_INDEX);
-
- let sepId = bmsvc.insertSeparator(testFolder, 0);
- let txn = new PlacesRemoveItemTransaction(sepId);
-
- txn.doTransaction();
- do_check_eq(observer._itemRemovedId, sepId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
-
- txn.undoTransaction();
- do_check_eq(observer._itemAddedId, sepId); // New separator created
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
-
- txn.redoTransaction();
- do_check_eq(observer._itemRemovedId, sepId);
- do_check_eq(observer._itemRemovedFolder, testFolder);
- do_check_eq(observer._itemRemovedIndex, 0);
-
- txn.undoTransaction();
- do_check_eq(observer._itemAddedId, sepId); // New separator created
- do_check_eq(observer._itemAddedParent, testFolder);
- do_check_eq(observer._itemAddedIndex, 0);
-});
-
-add_task(function* test_editing_item_title() {
- const TITLE = "Test editing item title";
- const MOD_TITLE = "Mod: Test editing item title";
- let testURI = NetUtil.newURI("http://www.test_editing_item_title.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX, TITLE);
-
- let txn = new PlacesEditItemTitleTransaction(testBkmId, MOD_TITLE);
-
- txn.doTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "title");
- do_check_eq(observer._itemChangedValue, MOD_TITLE);
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "title");
- do_check_eq(observer._itemChangedValue, TITLE);
-
- txn.redoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "title");
- do_check_eq(observer._itemChangedValue, MOD_TITLE);
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "title");
- do_check_eq(observer._itemChangedValue, TITLE);
-});
-
-add_task(function* test_editing_item_uri() {
- const OLD_TEST_URI = NetUtil.newURI("http://old.test_editing_item_uri.com/");
- const NEW_TEST_URI = NetUtil.newURI("http://new.test_editing_item_uri.com/");
- let testBkmId = bmsvc.insertBookmark(root, OLD_TEST_URI, bmsvc.DEFAULT_INDEX,
- "Test editing item title");
- tagssvc.tagURI(OLD_TEST_URI, ["tag"]);
-
- let txn = new PlacesEditBookmarkURITransaction(testBkmId, NEW_TEST_URI);
-
- txn.doTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "uri");
- do_check_eq(observer._itemChangedValue, NEW_TEST_URI.spec);
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(NEW_TEST_URI)), JSON.stringify(["tag"]));
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(OLD_TEST_URI)), JSON.stringify([]));
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "uri");
- do_check_eq(observer._itemChangedValue, OLD_TEST_URI.spec);
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(OLD_TEST_URI)), JSON.stringify(["tag"]));
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(NEW_TEST_URI)), JSON.stringify([]));
-
- txn.redoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "uri");
- do_check_eq(observer._itemChangedValue, NEW_TEST_URI.spec);
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(NEW_TEST_URI)), JSON.stringify(["tag"]));
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(OLD_TEST_URI)), JSON.stringify([]));
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "uri");
- do_check_eq(observer._itemChangedValue, OLD_TEST_URI.spec);
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(OLD_TEST_URI)), JSON.stringify(["tag"]));
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(NEW_TEST_URI)), JSON.stringify([]));
-});
-
-add_task(function* test_edit_description_transaction() {
- let testURI = NetUtil.newURI("http://test_edit_description_transaction.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX, "Test edit description transaction");
-
- let anno = {
- name: DESCRIPTION_ANNO,
- type: Ci.nsIAnnotationService.TYPE_STRING,
- flags: 0,
- value: "Test edit Description",
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER,
- };
- let txn = new PlacesSetItemAnnotationTransaction(testBkmId, anno);
-
- txn.doTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, DESCRIPTION_ANNO);
-});
-
-add_task(function* test_edit_keyword() {
- const KEYWORD = "keyword-test_edit_keyword";
-
- let testURI = NetUtil.newURI("http://test_edit_keyword.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX, "Test edit keyword");
-
- let txn = new PlacesEditBookmarkKeywordTransaction(testBkmId, KEYWORD, "postData");
-
- txn.doTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "keyword");
- do_check_eq(observer._itemChangedValue, KEYWORD);
- do_check_eq(PlacesUtils.getPostDataForBookmark(testBkmId), "postData");
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "keyword");
- do_check_eq(observer._itemChangedValue, "");
- do_check_eq(PlacesUtils.getPostDataForBookmark(testBkmId), null);
-});
-
-add_task(function* test_edit_specific_keyword() {
- const KEYWORD = "keyword-test_edit_keyword2";
-
- let testURI = NetUtil.newURI("http://test_edit_keyword2.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX, "Test edit keyword");
- // Add multiple keyword to this uri.
- yield PlacesUtils.keywords.insert({ keyword: "kw1", url: testURI.spec, postData: "postData1" });
- yield PlacesUtils.keywords.insert({keyword: "kw2", url: testURI.spec, postData: "postData2" });
-
- // Try to change only kw2.
- let txn = new PlacesEditBookmarkKeywordTransaction(testBkmId, KEYWORD, "postData2", "kw2");
-
- txn.doTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "keyword");
- do_check_eq(observer._itemChangedValue, KEYWORD);
- let entry = yield PlacesUtils.keywords.fetch("kw1");
- Assert.equal(entry.url.href, testURI.spec);
- Assert.equal(entry.postData, "postData1");
- yield promiseKeyword(KEYWORD, testURI.spec, "postData2");
- yield promiseKeyword("kw2", null);
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "keyword");
- do_check_eq(observer._itemChangedValue, "kw2");
- do_check_eq(PlacesUtils.getPostDataForBookmark(testBkmId), "postData1");
- entry = yield PlacesUtils.keywords.fetch("kw1");
- Assert.equal(entry.url.href, testURI.spec);
- Assert.equal(entry.postData, "postData1");
- yield promiseKeyword("kw2", testURI.spec, "postData2");
- yield promiseKeyword("keyword", null);
-});
-
-add_task(function* test_LoadInSidebar_transaction() {
- let testURI = NetUtil.newURI("http://test_LoadInSidebar_transaction.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX, "Test LoadInSidebar transaction");
-
- const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
- let anno = { name: LOAD_IN_SIDEBAR_ANNO,
- type: Ci.nsIAnnotationService.TYPE_INT32,
- flags: 0,
- value: true,
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
- let txn = new PlacesSetItemAnnotationTransaction(testBkmId, anno);
-
- txn.doTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, LOAD_IN_SIDEBAR_ANNO);
- do_check_eq(observer._itemChanged_isAnnotationProperty, true);
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, LOAD_IN_SIDEBAR_ANNO);
- do_check_eq(observer._itemChanged_isAnnotationProperty, true);
-});
-
-add_task(function* test_generic_item_annotation() {
- let testURI = NetUtil.newURI("http://test_generic_item_annotation.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX, "Test generic item annotation");
-
- let itemAnnoObj = { name: "testAnno/testInt",
- type: Ci.nsIAnnotationService.TYPE_INT32,
- flags: 0,
- value: 123,
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
- let txn = new PlacesSetItemAnnotationTransaction(testBkmId, itemAnnoObj);
-
- txn.doTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "testAnno/testInt");
- do_check_eq(observer._itemChanged_isAnnotationProperty, true);
-
- txn.undoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "testAnno/testInt");
- do_check_eq(observer._itemChanged_isAnnotationProperty, true);
-
- txn.redoTransaction();
- do_check_eq(observer._itemChangedId, testBkmId);
- do_check_eq(observer._itemChangedProperty, "testAnno/testInt");
- do_check_eq(observer._itemChanged_isAnnotationProperty, true);
-});
-
-add_task(function* test_editing_item_date_added() {
- let testURI = NetUtil.newURI("http://test_editing_item_date_added.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX,
- "Test editing item date added");
-
- let oldAdded = bmsvc.getItemDateAdded(testBkmId);
- let newAdded = Date.now() * 1000 + 1000;
- let txn = new PlacesEditItemDateAddedTransaction(testBkmId, newAdded);
-
- txn.doTransaction();
- do_check_eq(newAdded, bmsvc.getItemDateAdded(testBkmId));
-
- txn.undoTransaction();
- do_check_eq(oldAdded, bmsvc.getItemDateAdded(testBkmId));
-});
-
-add_task(function* test_edit_item_last_modified() {
- let testURI = NetUtil.newURI("http://test_edit_item_last_modified.com");
- let testBkmId = bmsvc.insertBookmark(root, testURI, bmsvc.DEFAULT_INDEX,
- "Test editing item last modified");
-
- let oldModified = bmsvc.getItemLastModified(testBkmId);
- let newModified = Date.now() * 1000 + 1000;
- let txn = new PlacesEditItemLastModifiedTransaction(testBkmId, newModified);
-
- txn.doTransaction();
- do_check_eq(newModified, bmsvc.getItemLastModified(testBkmId));
-
- txn.undoTransaction();
- do_check_eq(oldModified, bmsvc.getItemLastModified(testBkmId));
-});
-
-add_task(function* test_generic_page_annotation() {
- const TEST_ANNO = "testAnno/testInt";
- let testURI = NetUtil.newURI("http://www.mozilla.org/");
- PlacesTestUtils.addVisits(testURI).then(function () {
- let pageAnnoObj = { name: TEST_ANNO,
- type: Ci.nsIAnnotationService.TYPE_INT32,
- flags: 0,
- value: 123,
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
- let txn = new PlacesSetPageAnnotationTransaction(testURI, pageAnnoObj);
-
- txn.doTransaction();
- do_check_true(annosvc.pageHasAnnotation(testURI, TEST_ANNO));
-
- txn.undoTransaction();
- do_check_false(annosvc.pageHasAnnotation(testURI, TEST_ANNO));
-
- txn.redoTransaction();
- do_check_true(annosvc.pageHasAnnotation(testURI, TEST_ANNO));
- });
-});
-
-add_task(function* test_sort_folder_by_name() {
- let testFolder = bmsvc.createFolder(root, "Test PlacesSortFolderByNameTransaction",
- bmsvc.DEFAULT_INDEX);
- let testURI = NetUtil.newURI("http://test_sort_folder_by_name.com");
-
- bmsvc.insertBookmark(testFolder, testURI, bmsvc.DEFAULT_INDEX, "bookmark3");
- bmsvc.insertBookmark(testFolder, testURI, bmsvc.DEFAULT_INDEX, "bookmark2");
- bmsvc.insertBookmark(testFolder, testURI, bmsvc.DEFAULT_INDEX, "bookmark1");
-
- let bkmIds = bmsvc.getBookmarkIdsForURI(testURI);
- bkmIds.sort();
-
- let b1 = bkmIds[0];
- let b2 = bkmIds[1];
- let b3 = bkmIds[2];
-
- do_check_eq(0, bmsvc.getItemIndex(b1));
- do_check_eq(1, bmsvc.getItemIndex(b2));
- do_check_eq(2, bmsvc.getItemIndex(b3));
-
- let txn = new PlacesSortFolderByNameTransaction(testFolder);
-
- txn.doTransaction();
- do_check_eq(2, bmsvc.getItemIndex(b1));
- do_check_eq(1, bmsvc.getItemIndex(b2));
- do_check_eq(0, bmsvc.getItemIndex(b3));
-
- txn.undoTransaction();
- do_check_eq(0, bmsvc.getItemIndex(b1));
- do_check_eq(1, bmsvc.getItemIndex(b2));
- do_check_eq(2, bmsvc.getItemIndex(b3));
-
- txn.redoTransaction();
- do_check_eq(2, bmsvc.getItemIndex(b1));
- do_check_eq(1, bmsvc.getItemIndex(b2));
- do_check_eq(0, bmsvc.getItemIndex(b3));
-
- txn.undoTransaction();
- do_check_eq(0, bmsvc.getItemIndex(b1));
- do_check_eq(1, bmsvc.getItemIndex(b2));
- do_check_eq(2, bmsvc.getItemIndex(b3));
-});
-
-add_task(function* test_tagURI_untagURI() {
- const TAG_1 = "tag-test_tagURI_untagURI-bar";
- const TAG_2 = "tag-test_tagURI_untagURI-foo";
- let tagURI = NetUtil.newURI("http://test_tagURI_untagURI.com");
-
- // Test tagURI
- let tagTxn = new PlacesTagURITransaction(tagURI, [TAG_1, TAG_2]);
-
- tagTxn.doTransaction();
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(tagURI)), JSON.stringify([TAG_1, TAG_2]));
-
- tagTxn.undoTransaction();
- do_check_eq(tagssvc.getTagsForURI(tagURI).length, 0);
-
- tagTxn.redoTransaction();
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(tagURI)), JSON.stringify([TAG_1, TAG_2]));
-
- // Test untagURI
- let untagTxn = new PlacesUntagURITransaction(tagURI, [TAG_1]);
-
- untagTxn.doTransaction();
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(tagURI)), JSON.stringify([TAG_2]));
-
- untagTxn.undoTransaction();
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(tagURI)), JSON.stringify([TAG_1, TAG_2]));
-
- untagTxn.redoTransaction();
- do_check_eq(JSON.stringify(tagssvc.getTagsForURI(tagURI)), JSON.stringify([TAG_2]));
-});
-
-add_task(function* test_aggregate_removeItem_Txn() {
- let testFolder = bmsvc.createFolder(root, "Test aggregate removeItem transaction", bmsvc.DEFAULT_INDEX);
-
- const TEST_URL = "http://test_aggregate_removeitem_txn.com/";
- const FOLDERNAME = "Folder";
- let testURI = NetUtil.newURI(TEST_URL);
-
- let bkmk1Id = bmsvc.insertBookmark(testFolder, testURI, 0, "Mozilla");
- let bkmk2Id = bmsvc.insertSeparator(testFolder, 1);
- let bkmk3Id = bmsvc.createFolder(testFolder, FOLDERNAME, 2);
-
- let bkmk3_1Id = bmsvc.insertBookmark(bkmk3Id, testURI, 0, "Mozilla");
- let bkmk3_2Id = bmsvc.insertSeparator(bkmk3Id, 1);
- let bkmk3_3Id = bmsvc.createFolder(bkmk3Id, FOLDERNAME, 2);
-
- let childTxn1 = new PlacesRemoveItemTransaction(bkmk1Id);
- let childTxn2 = new PlacesRemoveItemTransaction(bkmk2Id);
- let childTxn3 = new PlacesRemoveItemTransaction(bkmk3Id);
- let transactions = [childTxn1, childTxn2, childTxn3];
- let txn = new PlacesAggregatedTransaction("RemoveItems", transactions);
-
- txn.doTransaction();
- do_check_eq(bmsvc.getItemIndex(bkmk1Id), -1);
- do_check_eq(bmsvc.getItemIndex(bkmk2Id), -1);
- do_check_eq(bmsvc.getItemIndex(bkmk3Id), -1);
- do_check_eq(bmsvc.getItemIndex(bkmk3_1Id), -1);
- do_check_eq(bmsvc.getItemIndex(bkmk3_2Id), -1);
- do_check_eq(bmsvc.getItemIndex(bkmk3_3Id), -1);
- // Check last removed item id.
- do_check_eq(observer._itemRemovedId, bkmk3Id);
-
- txn.undoTransaction();
- let newBkmk1Id = bmsvc.getIdForItemAt(testFolder, 0);
- let newBkmk2Id = bmsvc.getIdForItemAt(testFolder, 1);
- let newBkmk3Id = bmsvc.getIdForItemAt(testFolder, 2);
- let newBkmk3_1Id = bmsvc.getIdForItemAt(newBkmk3Id, 0);
- let newBkmk3_2Id = bmsvc.getIdForItemAt(newBkmk3Id, 1);
- let newBkmk3_3Id = bmsvc.getIdForItemAt(newBkmk3Id, 2);
- do_check_eq(bmsvc.getItemType(newBkmk1Id), bmsvc.TYPE_BOOKMARK);
- do_check_eq(bmsvc.getBookmarkURI(newBkmk1Id).spec, TEST_URL);
- do_check_eq(bmsvc.getItemType(newBkmk2Id), bmsvc.TYPE_SEPARATOR);
- do_check_eq(bmsvc.getItemType(newBkmk3Id), bmsvc.TYPE_FOLDER);
- do_check_eq(bmsvc.getItemTitle(newBkmk3Id), FOLDERNAME);
- do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_1Id), newBkmk3Id);
- do_check_eq(bmsvc.getItemType(newBkmk3_1Id), bmsvc.TYPE_BOOKMARK);
- do_check_eq(bmsvc.getBookmarkURI(newBkmk3_1Id).spec, TEST_URL);
- do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_2Id), newBkmk3Id);
- do_check_eq(bmsvc.getItemType(newBkmk3_2Id), bmsvc.TYPE_SEPARATOR);
- do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_3Id), newBkmk3Id);
- do_check_eq(bmsvc.getItemType(newBkmk3_3Id), bmsvc.TYPE_FOLDER);
- do_check_eq(bmsvc.getItemTitle(newBkmk3_3Id), FOLDERNAME);
- // Check last added back item id.
- // Notice items are restored in reverse order.
- do_check_eq(observer._itemAddedId, newBkmk1Id);
-
- txn.redoTransaction();
- do_check_eq(bmsvc.getItemIndex(newBkmk1Id), -1);
- do_check_eq(bmsvc.getItemIndex(newBkmk2Id), -1);
- do_check_eq(bmsvc.getItemIndex(newBkmk3Id), -1);
- do_check_eq(bmsvc.getItemIndex(newBkmk3_1Id), -1);
- do_check_eq(bmsvc.getItemIndex(newBkmk3_2Id), -1);
- do_check_eq(bmsvc.getItemIndex(newBkmk3_3Id), -1);
- // Check last removed item id.
- do_check_eq(observer._itemRemovedId, newBkmk3Id);
-
- txn.undoTransaction();
- newBkmk1Id = bmsvc.getIdForItemAt(testFolder, 0);
- newBkmk2Id = bmsvc.getIdForItemAt(testFolder, 1);
- newBkmk3Id = bmsvc.getIdForItemAt(testFolder, 2);
- newBkmk3_1Id = bmsvc.getIdForItemAt(newBkmk3Id, 0);
- newBkmk3_2Id = bmsvc.getIdForItemAt(newBkmk3Id, 1);
- newBkmk3_3Id = bmsvc.getIdForItemAt(newBkmk3Id, 2);
- do_check_eq(bmsvc.getItemType(newBkmk1Id), bmsvc.TYPE_BOOKMARK);
- do_check_eq(bmsvc.getBookmarkURI(newBkmk1Id).spec, TEST_URL);
- do_check_eq(bmsvc.getItemType(newBkmk2Id), bmsvc.TYPE_SEPARATOR);
- do_check_eq(bmsvc.getItemType(newBkmk3Id), bmsvc.TYPE_FOLDER);
- do_check_eq(bmsvc.getItemTitle(newBkmk3Id), FOLDERNAME);
- do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_1Id), newBkmk3Id);
- do_check_eq(bmsvc.getItemType(newBkmk3_1Id), bmsvc.TYPE_BOOKMARK);
- do_check_eq(bmsvc.getBookmarkURI(newBkmk3_1Id).spec, TEST_URL);
- do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_2Id), newBkmk3Id);
- do_check_eq(bmsvc.getItemType(newBkmk3_2Id), bmsvc.TYPE_SEPARATOR);
- do_check_eq(bmsvc.getFolderIdForItem(newBkmk3_3Id), newBkmk3Id);
- do_check_eq(bmsvc.getItemType(newBkmk3_3Id), bmsvc.TYPE_FOLDER);
- do_check_eq(bmsvc.getItemTitle(newBkmk3_3Id), FOLDERNAME);
- // Check last added back item id.
- // Notice items are restored in reverse order.
- do_check_eq(observer._itemAddedId, newBkmk1Id);
-});
-
-add_task(function* test_create_item_with_childTxn() {
- let testFolder = bmsvc.createFolder(root, "Test creating an item with childTxns", bmsvc.DEFAULT_INDEX);
-
- const BOOKMARK_TITLE = "parent item";
- let testURI = NetUtil.newURI("http://test_create_item_with_childTxn.com");
- let childTxns = [];
- let newDateAdded = Date.now() * 1000 - 20000;
- let editDateAdddedTxn = new PlacesEditItemDateAddedTransaction(null, newDateAdded);
- childTxns.push(editDateAdddedTxn);
-
- let itemChildAnnoObj = { name: "testAnno/testInt",
- type: Ci.nsIAnnotationService.TYPE_INT32,
- flags: 0,
- value: 123,
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER };
- let annoTxn = new PlacesSetItemAnnotationTransaction(null, itemChildAnnoObj);
- childTxns.push(annoTxn);
-
- let itemWChildTxn = new PlacesCreateBookmarkTransaction(testURI, testFolder, bmStartIndex,
- BOOKMARK_TITLE, null, null,
- childTxns);
- try {
- txnManager.doTransaction(itemWChildTxn);
- let itemId = bmsvc.getBookmarkIdsForURI(testURI)[0];
- do_check_eq(observer._itemAddedId, itemId);
- do_check_eq(newDateAdded, bmsvc.getItemDateAdded(itemId));
- do_check_eq(observer._itemChangedProperty, "testAnno/testInt");
- do_check_eq(observer._itemChanged_isAnnotationProperty, true);
- do_check_true(annosvc.itemHasAnnotation(itemId, itemChildAnnoObj.name))
- do_check_eq(annosvc.getItemAnnotation(itemId, itemChildAnnoObj.name), itemChildAnnoObj.value);
-
- itemWChildTxn.undoTransaction();
- do_check_eq(observer._itemRemovedId, itemId);
-
- itemWChildTxn.redoTransaction();
- do_check_true(bmsvc.isBookmarked(testURI));
- let newId = bmsvc.getBookmarkIdsForURI(testURI)[0];
- do_check_eq(newDateAdded, bmsvc.getItemDateAdded(newId));
- do_check_eq(observer._itemAddedId, newId);
- do_check_eq(observer._itemChangedProperty, "testAnno/testInt");
- do_check_eq(observer._itemChanged_isAnnotationProperty, true);
- do_check_true(annosvc.itemHasAnnotation(newId, itemChildAnnoObj.name))
- do_check_eq(annosvc.getItemAnnotation(newId, itemChildAnnoObj.name), itemChildAnnoObj.value);
-
- itemWChildTxn.undoTransaction();
- do_check_eq(observer._itemRemovedId, newId);
- }
- catch (ex) {
- do_throw("Setting a child transaction in a createItem transaction did throw: " + ex);
- }
-});
-
-add_task(function* test_create_folder_with_child_itemTxn() {
- let childURI = NetUtil.newURI("http://test_create_folder_with_child_itemTxn.com");
- let childItemTxn = new PlacesCreateBookmarkTransaction(childURI, root,
- bmStartIndex, "childItem");
- let txn = new PlacesCreateFolderTransaction("Test creating a folder with child itemTxns",
- root, bmStartIndex, null, [childItemTxn]);
- try {
- txnManager.doTransaction(txn);
- let childItemId = bmsvc.getBookmarkIdsForURI(childURI)[0];
- do_check_eq(observer._itemAddedId, childItemId);
- do_check_eq(observer._itemAddedIndex, 0);
- do_check_true(bmsvc.isBookmarked(childURI));
-
- txn.undoTransaction();
- do_check_false(bmsvc.isBookmarked(childURI));
-
- txn.redoTransaction();
- let newchildItemId = bmsvc.getBookmarkIdsForURI(childURI)[0];
- do_check_eq(observer._itemAddedIndex, 0);
- do_check_eq(observer._itemAddedId, newchildItemId);
- do_check_true(bmsvc.isBookmarked(childURI));
-
- txn.undoTransaction();
- do_check_false(bmsvc.isBookmarked(childURI));
- }
- catch (ex) {
- do_throw("Setting a child item transaction in a createFolder transaction did throw: " + ex);
- }
-});
diff --git a/toolkit/components/places/tests/unit/test_preventive_maintenance.js b/toolkit/components/places/tests/unit/test_preventive_maintenance.js
deleted file mode 100644
index a533c8295..000000000
--- a/toolkit/components/places/tests/unit/test_preventive_maintenance.js
+++ /dev/null
@@ -1,1356 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Test preventive maintenance
- * For every maintenance query create an uncoherent db and check that we take
- * correct fix steps, without polluting valid data.
- */
-
-// Include PlacesDBUtils module
-Components.utils.import("resource://gre/modules/PlacesDBUtils.jsm");
-
-const FINISHED_MAINTENANCE_NOTIFICATION_TOPIC = "places-maintenance-finished";
-
-// Get services and database connection
-var hs = PlacesUtils.history;
-var bs = PlacesUtils.bookmarks;
-var ts = PlacesUtils.tagging;
-var as = PlacesUtils.annotations;
-var fs = PlacesUtils.favicons;
-
-var mDBConn = hs.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
-
-// ------------------------------------------------------------------------------
-// Helpers
-
-var defaultBookmarksMaxId = 0;
-function cleanDatabase() {
- mDBConn.executeSimpleSQL("DELETE FROM moz_places");
- mDBConn.executeSimpleSQL("DELETE FROM moz_historyvisits");
- mDBConn.executeSimpleSQL("DELETE FROM moz_anno_attributes");
- mDBConn.executeSimpleSQL("DELETE FROM moz_annos");
- mDBConn.executeSimpleSQL("DELETE FROM moz_items_annos");
- mDBConn.executeSimpleSQL("DELETE FROM moz_inputhistory");
- mDBConn.executeSimpleSQL("DELETE FROM moz_keywords");
- mDBConn.executeSimpleSQL("DELETE FROM moz_favicons");
- mDBConn.executeSimpleSQL("DELETE FROM moz_bookmarks WHERE id > " + defaultBookmarksMaxId);
-}
-
-function addPlace(aUrl, aFavicon) {
- let stmt = mDBConn.createStatement(
- "INSERT INTO moz_places (url, url_hash, favicon_id) VALUES (:url, hash(:url), :favicon)");
- stmt.params["url"] = aUrl || "http://www.mozilla.org";
- stmt.params["favicon"] = aFavicon || null;
- stmt.execute();
- stmt.finalize();
- return mDBConn.lastInsertRowID;
-}
-
-function addBookmark(aPlaceId, aType, aParent, aKeywordId, aFolderType, aTitle) {
- let stmt = mDBConn.createStatement(
- `INSERT INTO moz_bookmarks (fk, type, parent, keyword_id, folder_type,
- title, guid)
- VALUES (:place_id, :type, :parent, :keyword_id, :folder_type, :title,
- GENERATE_GUID())`);
- stmt.params["place_id"] = aPlaceId || null;
- stmt.params["type"] = aType || bs.TYPE_BOOKMARK;
- stmt.params["parent"] = aParent || bs.unfiledBookmarksFolder;
- stmt.params["keyword_id"] = aKeywordId || null;
- stmt.params["folder_type"] = aFolderType || null;
- stmt.params["title"] = typeof(aTitle) == "string" ? aTitle : null;
- stmt.execute();
- stmt.finalize();
- return mDBConn.lastInsertRowID;
-}
-
-// ------------------------------------------------------------------------------
-// Tests
-
-var tests = [];
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "A.1",
- desc: "Remove obsolete annotations from moz_annos",
-
- _obsoleteWeaveAttribute: "weave/test",
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid.
- this._placeId = addPlace();
- // Add an obsolete attribute.
- let stmt = mDBConn.createStatement(
- "INSERT INTO moz_anno_attributes (name) VALUES (:anno)"
- );
- stmt.params['anno'] = this._obsoleteWeaveAttribute;
- stmt.execute();
- stmt.finalize();
- stmt = mDBConn.createStatement(
- `INSERT INTO moz_annos (place_id, anno_attribute_id)
- VALUES (:place_id,
- (SELECT id FROM moz_anno_attributes WHERE name = :anno)
- )`
- );
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._obsoleteWeaveAttribute;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that the obsolete annotation has been removed.
- let stmt = mDBConn.createStatement(
- "SELECT id FROM moz_anno_attributes WHERE name = :anno"
- );
- stmt.params['anno'] = this._obsoleteWeaveAttribute;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-tests.push({
- name: "A.2",
- desc: "Remove obsolete annotations from moz_items_annos",
-
- _obsoleteSyncAttribute: "sync/children",
- _obsoleteGuidAttribute: "placesInternal/GUID",
- _obsoleteWeaveAttribute: "weave/test",
- _placeId: null,
- _bookmarkId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid.
- this._placeId = addPlace();
- // Add a bookmark.
- this._bookmarkId = addBookmark(this._placeId);
- // Add an obsolete attribute.
- let stmt = mDBConn.createStatement(
- `INSERT INTO moz_anno_attributes (name)
- VALUES (:anno1), (:anno2), (:anno3)`
- );
- stmt.params['anno1'] = this._obsoleteSyncAttribute;
- stmt.params['anno2'] = this._obsoleteGuidAttribute;
- stmt.params['anno3'] = this._obsoleteWeaveAttribute;
- stmt.execute();
- stmt.finalize();
- stmt = mDBConn.createStatement(
- `INSERT INTO moz_items_annos (item_id, anno_attribute_id)
- SELECT :item_id, id
- FROM moz_anno_attributes
- WHERE name IN (:anno1, :anno2, :anno3)`
- );
- stmt.params['item_id'] = this._bookmarkId;
- stmt.params['anno1'] = this._obsoleteSyncAttribute;
- stmt.params['anno2'] = this._obsoleteGuidAttribute;
- stmt.params['anno3'] = this._obsoleteWeaveAttribute;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that the obsolete annotations have been removed.
- let stmt = mDBConn.createStatement(
- `SELECT id FROM moz_anno_attributes
- WHERE name IN (:anno1, :anno2, :anno3)`
- );
- stmt.params['anno1'] = this._obsoleteSyncAttribute;
- stmt.params['anno2'] = this._obsoleteGuidAttribute;
- stmt.params['anno3'] = this._obsoleteWeaveAttribute;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-tests.push({
- name: "A.3",
- desc: "Remove unused attributes",
-
- _usedPageAttribute: "usedPage",
- _usedItemAttribute: "usedItem",
- _unusedAttribute: "unused",
- _placeId: null,
- _bookmarkId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // add a bookmark
- this._bookmarkId = addBookmark(this._placeId);
- // Add a used attribute and an unused one.
- let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedPageAttribute;
- stmt.execute();
- stmt.reset();
- stmt.params['anno'] = this._usedItemAttribute;
- stmt.execute();
- stmt.reset();
- stmt.params['anno'] = this._unusedAttribute;
- stmt.execute();
- stmt.finalize();
-
- stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._usedPageAttribute;
- stmt.execute();
- stmt.finalize();
- stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES(:item_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['item_id'] = this._bookmarkId;
- stmt.params['anno'] = this._usedItemAttribute;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that used attributes are still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedPageAttribute;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params['anno'] = this._usedItemAttribute;
- do_check_true(stmt.executeStep());
- stmt.reset();
- // Check that unused attribute has been removed
- stmt.params['anno'] = this._unusedAttribute;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "B.1",
- desc: "Remove annotations with an invalid attribute",
-
- _usedPageAttribute: "usedPage",
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Add a used attribute.
- let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedPageAttribute;
- stmt.execute();
- stmt.finalize();
- stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._usedPageAttribute;
- stmt.execute();
- stmt.finalize();
- // Add an annotation with a nonexistent attribute
- stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, 1337)");
- stmt.params['place_id'] = this._placeId;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that used attribute is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedPageAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // check that annotation with valid attribute is still there
- stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedPageAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // Check that annotation with bogus attribute has been removed
- stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE anno_attribute_id = 1337");
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "B.2",
- desc: "Remove orphan page annotations",
-
- _usedPageAttribute: "usedPage",
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Add a used attribute.
- let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedPageAttribute;
- stmt.execute();
- stmt.finalize();
- stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._usedPageAttribute;
- stmt.execute();
- stmt.reset();
- // Add an annotation to a nonexistent page
- stmt.params['place_id'] = 1337;
- stmt.params['anno'] = this._usedPageAttribute;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that used attribute is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedPageAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // check that annotation with valid attribute is still there
- stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedPageAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // Check that an annotation to a nonexistent page has been removed
- stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE place_id = 1337");
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-tests.push({
- name: "C.1",
- desc: "fix missing Places root",
-
- setup: function() {
- // Sanity check: ensure that roots are intact.
- do_check_eq(bs.getFolderIdForItem(bs.placesRoot), 0);
- do_check_eq(bs.getFolderIdForItem(bs.bookmarksMenuFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.tagsFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.unfiledBookmarksFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.toolbarFolder), bs.placesRoot);
-
- // Remove the root.
- mDBConn.executeSimpleSQL("DELETE FROM moz_bookmarks WHERE parent = 0");
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE parent = 0");
- do_check_false(stmt.executeStep());
- stmt.finalize();
- },
-
- check: function() {
- // Ensure the roots have been correctly restored.
- do_check_eq(bs.getFolderIdForItem(bs.placesRoot), 0);
- do_check_eq(bs.getFolderIdForItem(bs.bookmarksMenuFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.tagsFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.unfiledBookmarksFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.toolbarFolder), bs.placesRoot);
- }
-});
-
-// ------------------------------------------------------------------------------
-tests.push({
- name: "C.2",
- desc: "Fix roots titles",
-
- setup: function() {
- // Sanity check: ensure that roots titles are correct. We can use our check.
- this.check();
- // Change some roots' titles.
- bs.setItemTitle(bs.placesRoot, "bad title");
- do_check_eq(bs.getItemTitle(bs.placesRoot), "bad title");
- bs.setItemTitle(bs.unfiledBookmarksFolder, "bad title");
- do_check_eq(bs.getItemTitle(bs.unfiledBookmarksFolder), "bad title");
- },
-
- check: function() {
- // Ensure all roots titles are correct.
- do_check_eq(bs.getItemTitle(bs.placesRoot), "");
- do_check_eq(bs.getItemTitle(bs.bookmarksMenuFolder),
- PlacesUtils.getString("BookmarksMenuFolderTitle"));
- do_check_eq(bs.getItemTitle(bs.tagsFolder),
- PlacesUtils.getString("TagsFolderTitle"));
- do_check_eq(bs.getItemTitle(bs.unfiledBookmarksFolder),
- PlacesUtils.getString("OtherBookmarksFolderTitle"));
- do_check_eq(bs.getItemTitle(bs.toolbarFolder),
- PlacesUtils.getString("BookmarksToolbarFolderTitle"));
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.1",
- desc: "Remove items without a valid place",
-
- _validItemId: null,
- _invalidItemId: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this.placeId = addPlace();
- // Insert a valid bookmark
- this._validItemId = addBookmark(this.placeId);
- // Insert a bookmark with an invalid place
- this._invalidItemId = addBookmark(1337);
- },
-
- check: function() {
- // Check that valid bookmark is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE id = :item_id");
- stmt.params["item_id"] = this._validItemId;
- do_check_true(stmt.executeStep());
- stmt.reset();
- // Check that invalid bookmark has been removed
- stmt.params["item_id"] = this._invalidItemId;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.2",
- desc: "Remove items that are not uri bookmarks from tag containers",
-
- _tagId: null,
- _bookmarkId: null,
- _separatorId: null,
- _folderId: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Create a tag
- this._tagId = addBookmark(null, bs.TYPE_FOLDER, bs.tagsFolder);
- // Insert a bookmark in the tag
- this._bookmarkId = addBookmark(this._placeId, bs.TYPE_BOOKMARK, this._tagId);
- // Insert a separator in the tag
- this._separatorId = addBookmark(null, bs.TYPE_SEPARATOR, this._tagId);
- // Insert a folder in the tag
- this._folderId = addBookmark(null, bs.TYPE_FOLDER, this._tagId);
- },
-
- check: function() {
- // Check that valid bookmark is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE type = :type AND parent = :parent");
- stmt.params["type"] = bs.TYPE_BOOKMARK;
- stmt.params["parent"] = this._tagId;
- do_check_true(stmt.executeStep());
- stmt.reset();
- // Check that separator is no more there
- stmt.params["type"] = bs.TYPE_SEPARATOR;
- stmt.params["parent"] = this._tagId;
- do_check_false(stmt.executeStep());
- stmt.reset();
- // Check that folder is no more there
- stmt.params["type"] = bs.TYPE_FOLDER;
- stmt.params["parent"] = this._tagId;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.3",
- desc: "Remove empty tags",
-
- _tagId: null,
- _bookmarkId: null,
- _emptyTagId: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Create a tag
- this._tagId = addBookmark(null, bs.TYPE_FOLDER, bs.tagsFolder);
- // Insert a bookmark in the tag
- this._bookmarkId = addBookmark(this._placeId, bs.TYPE_BOOKMARK, this._tagId);
- // Create another tag (empty)
- this._emptyTagId = addBookmark(null, bs.TYPE_FOLDER, bs.tagsFolder);
- },
-
- check: function() {
- // Check that valid bookmark is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE id = :id AND type = :type AND parent = :parent");
- stmt.params["id"] = this._bookmarkId;
- stmt.params["type"] = bs.TYPE_BOOKMARK;
- stmt.params["parent"] = this._tagId;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["id"] = this._tagId;
- stmt.params["type"] = bs.TYPE_FOLDER;
- stmt.params["parent"] = bs.tagsFolder;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["id"] = this._emptyTagId;
- stmt.params["type"] = bs.TYPE_FOLDER;
- stmt.params["parent"] = bs.tagsFolder;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.4",
- desc: "Move orphan items to unsorted folder",
-
- _orphanBookmarkId: null,
- _orphanSeparatorId: null,
- _orphanFolderId: null,
- _bookmarkId: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Insert an orphan bookmark
- this._orphanBookmarkId = addBookmark(this._placeId, bs.TYPE_BOOKMARK, 8888);
- // Insert an orphan separator
- this._orphanSeparatorId = addBookmark(null, bs.TYPE_SEPARATOR, 8888);
- // Insert a orphan folder
- this._orphanFolderId = addBookmark(null, bs.TYPE_FOLDER, 8888);
- // Create a child of the last created folder
- this._bookmarkId = addBookmark(this._placeId, bs.TYPE_BOOKMARK, this._orphanFolderId);
- },
-
- check: function() {
- // Check that bookmarks are now children of a real folder (unsorted)
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE id = :item_id AND parent = :parent");
- stmt.params["item_id"] = this._orphanBookmarkId;
- stmt.params["parent"] = bs.unfiledBookmarksFolder;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["item_id"] = this._orphanSeparatorId;
- stmt.params["parent"] = bs.unfiledBookmarksFolder;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["item_id"] = this._orphanFolderId;
- stmt.params["parent"] = bs.unfiledBookmarksFolder;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["item_id"] = this._bookmarkId;
- stmt.params["parent"] = this._orphanFolderId;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.6",
- desc: "Fix wrong item types | bookmarks",
-
- _separatorId: null,
- _folderId: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Add a separator with a fk
- this._separatorId = addBookmark(this._placeId, bs.TYPE_SEPARATOR);
- // Add a folder with a fk
- this._folderId = addBookmark(this._placeId, bs.TYPE_FOLDER);
- },
-
- check: function() {
- // Check that items with an fk have been converted to bookmarks
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE id = :item_id AND type = :type");
- stmt.params["item_id"] = this._separatorId;
- stmt.params["type"] = bs.TYPE_BOOKMARK;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["item_id"] = this._folderId;
- stmt.params["type"] = bs.TYPE_BOOKMARK;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.7",
- desc: "Fix wrong item types | bookmarks",
-
- _validBookmarkId: null,
- _invalidBookmarkId: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Add a bookmark with a valid place id
- this._validBookmarkId = addBookmark(this._placeId, bs.TYPE_BOOKMARK);
- // Add a bookmark with a null place id
- this._invalidBookmarkId = addBookmark(null, bs.TYPE_BOOKMARK);
- },
-
- check: function() {
- // Check valid bookmark
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE id = :item_id AND type = :type");
- stmt.params["item_id"] = this._validBookmarkId;
- stmt.params["type"] = bs.TYPE_BOOKMARK;
- do_check_true(stmt.executeStep());
- stmt.reset();
- // Check invalid bookmark has been converted to a folder
- stmt.params["item_id"] = this._invalidBookmarkId;
- stmt.params["type"] = bs.TYPE_FOLDER;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.9",
- desc: "Fix wrong parents",
-
- _bookmarkId: null,
- _separatorId: null,
- _bookmarkId1: null,
- _bookmarkId2: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Insert a bookmark
- this._bookmarkId = addBookmark(this._placeId, bs.TYPE_BOOKMARK);
- // Insert a separator
- this._separatorId = addBookmark(null, bs.TYPE_SEPARATOR);
- // Create 3 children of these items
- this._bookmarkId1 = addBookmark(this._placeId, bs.TYPE_BOOKMARK, this._bookmarkId);
- this._bookmarkId2 = addBookmark(this._placeId, bs.TYPE_BOOKMARK, this._separatorId);
- },
-
- check: function() {
- // Check that bookmarks are now children of a real folder (unsorted)
- let stmt = mDBConn.createStatement("SELECT id FROM moz_bookmarks WHERE id = :item_id AND parent = :parent");
- stmt.params["item_id"] = this._bookmarkId1;
- stmt.params["parent"] = bs.unfiledBookmarksFolder;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["item_id"] = this._bookmarkId2;
- stmt.params["parent"] = bs.unfiledBookmarksFolder;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.10",
- desc: "Recalculate positions",
-
- _unfiledBookmarks: [],
- _toolbarBookmarks: [],
-
- setup: function() {
- const NUM_BOOKMARKS = 20;
- bs.runInBatchMode({
- runBatched: function (aUserData) {
- // Add bookmarks to two folders to better perturbate the table.
- for (let i = 0; i < NUM_BOOKMARKS; i++) {
- bs.insertBookmark(PlacesUtils.unfiledBookmarksFolderId,
- NetUtil.newURI("http://example.com/"),
- bs.DEFAULT_INDEX, "testbookmark");
- }
- for (let i = 0; i < NUM_BOOKMARKS; i++) {
- bs.insertBookmark(PlacesUtils.toolbarFolderId,
- NetUtil.newURI("http://example.com/"),
- bs.DEFAULT_INDEX, "testbookmark");
- }
- }
- }, null);
-
- function randomize_positions(aParent, aResultArray) {
- let stmt = mDBConn.createStatement(
- `UPDATE moz_bookmarks SET position = :rand
- WHERE id IN (
- SELECT id FROM moz_bookmarks WHERE parent = :parent
- ORDER BY RANDOM() LIMIT 1
- )`
- );
- for (let i = 0; i < (NUM_BOOKMARKS / 2); i++) {
- stmt.params["parent"] = aParent;
- stmt.params["rand"] = Math.round(Math.random() * (NUM_BOOKMARKS - 1));
- stmt.execute();
- stmt.reset();
- }
- stmt.finalize();
-
- // Build the expected ordered list of bookmarks.
- stmt = mDBConn.createStatement(
- `SELECT id, position
- FROM moz_bookmarks WHERE parent = :parent
- ORDER BY position ASC, ROWID ASC`
- );
- stmt.params["parent"] = aParent;
- while (stmt.executeStep()) {
- aResultArray.push(stmt.row.id);
- print(stmt.row.id + "\t" + stmt.row.position + "\t" +
- (aResultArray.length - 1));
- }
- stmt.finalize();
- }
-
- // Set random positions for the added bookmarks.
- randomize_positions(PlacesUtils.unfiledBookmarksFolderId,
- this._unfiledBookmarks);
- randomize_positions(PlacesUtils.toolbarFolderId, this._toolbarBookmarks);
- },
-
- check: function() {
- function check_order(aParent, aResultArray) {
- // Build the expected ordered list of bookmarks.
- let stmt = mDBConn.createStatement(
- `SELECT id, position FROM moz_bookmarks WHERE parent = :parent
- ORDER BY position ASC`
- );
- stmt.params["parent"] = aParent;
- let pass = true;
- while (stmt.executeStep()) {
- print(stmt.row.id + "\t" + stmt.row.position);
- if (aResultArray.indexOf(stmt.row.id) != stmt.row.position) {
- pass = false;
- }
- }
- stmt.finalize();
- if (!pass) {
- dump_table("moz_bookmarks");
- do_throw("Unexpected unfiled bookmarks order.");
- }
- }
-
- check_order(PlacesUtils.unfiledBookmarksFolderId, this._unfiledBookmarks);
- check_order(PlacesUtils.toolbarFolderId, this._toolbarBookmarks);
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "D.12",
- desc: "Fix empty-named tags",
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- let placeId = addPlace();
- // Create a empty-named tag.
- this._untitledTagId = addBookmark(null, bs.TYPE_FOLDER, bs.tagsFolder, null, null, "");
- // Insert a bookmark in the tag, otherwise it will be removed.
- addBookmark(placeId, bs.TYPE_BOOKMARK, this._untitledTagId);
- // Create a empty-named folder.
- this._untitledFolderId = addBookmark(null, bs.TYPE_FOLDER, bs.toolbarFolder, null, null, "");
- // Create a titled tag.
- this._titledTagId = addBookmark(null, bs.TYPE_FOLDER, bs.tagsFolder, null, null, "titledTag");
- // Insert a bookmark in the tag, otherwise it will be removed.
- addBookmark(placeId, bs.TYPE_BOOKMARK, this._titledTagId);
- // Create a titled folder.
- this._titledFolderId = addBookmark(null, bs.TYPE_FOLDER, bs.toolbarFolder, null, null, "titledFolder");
- },
-
- check: function() {
- // Check that valid bookmark is still there
- let stmt = mDBConn.createStatement(
- "SELECT title FROM moz_bookmarks WHERE id = :id"
- );
- stmt.params["id"] = this._untitledTagId;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.title, "(notitle)");
- stmt.reset();
- stmt.params["id"] = this._untitledFolderId;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.title, "");
- stmt.reset();
- stmt.params["id"] = this._titledTagId;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.title, "titledTag");
- stmt.reset();
- stmt.params["id"] = this._titledFolderId;
- do_check_true(stmt.executeStep());
- do_check_eq(stmt.row.title, "titledFolder");
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "E.1",
- desc: "Remove orphan icons",
-
- _placeId: null,
-
- setup: function() {
- // Insert favicon entries
- let stmt = mDBConn.createStatement("INSERT INTO moz_favicons (id, url) VALUES(:favicon_id, :url)");
- stmt.params["favicon_id"] = 1;
- stmt.params["url"] = "http://www1.mozilla.org/favicon.ico";
- stmt.execute();
- stmt.reset();
- stmt.params["favicon_id"] = 2;
- stmt.params["url"] = "http://www2.mozilla.org/favicon.ico";
- stmt.execute();
- stmt.finalize();
- // Insert a place using the existing favicon entry
- this._placeId = addPlace("http://www.mozilla.org", 1);
- },
-
- check: function() {
- // Check that used icon is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_favicons WHERE id = :favicon_id");
- stmt.params["favicon_id"] = 1;
- do_check_true(stmt.executeStep());
- stmt.reset();
- // Check that unused icon has been removed
- stmt.params["favicon_id"] = 2;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "F.1",
- desc: "Remove orphan visits",
-
- _placeId: null,
- _invalidPlaceId: 1337,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Add a valid visit and an invalid one
- stmt = mDBConn.createStatement("INSERT INTO moz_historyvisits(place_id) VALUES (:place_id)");
- stmt.params["place_id"] = this._placeId;
- stmt.execute();
- stmt.reset();
- stmt.params["place_id"] = this._invalidPlaceId;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that valid visit is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_historyvisits WHERE place_id = :place_id");
- stmt.params["place_id"] = this._placeId;
- do_check_true(stmt.executeStep());
- stmt.reset();
- // Check that invalid visit has been removed
- stmt.params["place_id"] = this._invalidPlaceId;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "G.1",
- desc: "Remove orphan input history",
-
- _placeId: null,
- _invalidPlaceId: 1337,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Add input history entries
- let stmt = mDBConn.createStatement("INSERT INTO moz_inputhistory (place_id, input) VALUES (:place_id, :input)");
- stmt.params["place_id"] = this._placeId;
- stmt.params["input"] = "moz";
- stmt.execute();
- stmt.reset();
- stmt.params["place_id"] = this._invalidPlaceId;
- stmt.params["input"] = "moz";
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that inputhistory on valid place is still there
- let stmt = mDBConn.createStatement("SELECT place_id FROM moz_inputhistory WHERE place_id = :place_id");
- stmt.params["place_id"] = this._placeId;
- do_check_true(stmt.executeStep());
- stmt.reset();
- // Check that inputhistory on invalid place has gone
- stmt.params["place_id"] = this._invalidPlaceId;
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "H.1",
- desc: "Remove item annos with an invalid attribute",
-
- _usedItemAttribute: "usedItem",
- _bookmarkId: null,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Insert a bookmark
- this._bookmarkId = addBookmark(this._placeId);
- // Add a used attribute.
- let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedItemAttribute;
- stmt.execute();
- stmt.finalize();
- stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES(:item_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['item_id'] = this._bookmarkId;
- stmt.params['anno'] = this._usedItemAttribute;
- stmt.execute();
- stmt.finalize();
- // Add an annotation with a nonexistent attribute
- stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES(:item_id, 1337)");
- stmt.params['item_id'] = this._bookmarkId;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that used attribute is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedItemAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // check that annotation with valid attribute is still there
- stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedItemAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // Check that annotation with bogus attribute has been removed
- stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE anno_attribute_id = 1337");
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "H.2",
- desc: "Remove orphan item annotations",
-
- _usedItemAttribute: "usedItem",
- _bookmarkId: null,
- _invalidBookmarkId: 8888,
- _placeId: null,
-
- setup: function() {
- // Add a place to ensure place_id = 1 is valid
- this._placeId = addPlace();
- // Insert a bookmark
- this._bookmarkId = addBookmark(this._placeId);
- // Add a used attribute.
- stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedItemAttribute;
- stmt.execute();
- stmt.finalize();
- stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES (:item_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params["item_id"] = this._bookmarkId;
- stmt.params["anno"] = this._usedItemAttribute;
- stmt.execute();
- stmt.reset();
- // Add an annotation to a nonexistent item
- stmt.params["item_id"] = this._invalidBookmarkId;
- stmt.params["anno"] = this._usedItemAttribute;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that used attribute is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedItemAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // check that annotation with valid attribute is still there
- stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedItemAttribute;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // Check that an annotation to a nonexistent page has been removed
- stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE item_id = 8888");
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "I.1",
- desc: "Remove unused keywords",
-
- _bookmarkId: null,
- _placeId: null,
-
- setup: function() {
- // Insert 2 keywords
- let stmt = mDBConn.createStatement("INSERT INTO moz_keywords (id, keyword, place_id) VALUES(:id, :keyword, :place_id)");
- stmt.params["id"] = 1;
- stmt.params["keyword"] = "unused";
- stmt.params["place_id"] = 100;
- stmt.execute();
- stmt.finalize();
- },
-
- check: function() {
- // Check that "used" keyword is still there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_keywords WHERE keyword = :keyword");
- // Check that "unused" keyword has gone
- stmt.params["keyword"] = "unused";
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "L.1",
- desc: "Fix wrong favicon ids",
-
- _validIconPlaceId: null,
- _invalidIconPlaceId: null,
-
- setup: function() {
- // Insert a favicon entry
- let stmt = mDBConn.createStatement("INSERT INTO moz_favicons (id, url) VALUES(1, :url)");
- stmt.params["url"] = "http://www.mozilla.org/favicon.ico";
- stmt.execute();
- stmt.finalize();
- // Insert a place using the existing favicon entry
- this._validIconPlaceId = addPlace("http://www1.mozilla.org", 1);
-
- // Insert a place using a nonexistent favicon entry
- this._invalidIconPlaceId = addPlace("http://www2.mozilla.org", 1337);
- },
-
- check: function() {
- // Check that bogus favicon is not there
- let stmt = mDBConn.createStatement("SELECT id FROM moz_places WHERE favicon_id = :favicon_id");
- stmt.params["favicon_id"] = 1337;
- do_check_false(stmt.executeStep());
- stmt.reset();
- // Check that valid favicon is still there
- stmt.params["favicon_id"] = 1;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- // Check that place entries are there
- stmt = mDBConn.createStatement("SELECT id FROM moz_places WHERE id = :place_id");
- stmt.params["place_id"] = this._validIconPlaceId;
- do_check_true(stmt.executeStep());
- stmt.reset();
- stmt.params["place_id"] = this._invalidIconPlaceId;
- do_check_true(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "L.2",
- desc: "Recalculate visit_count and last_visit_date",
-
- setup: function* () {
- function setVisitCount(aURL, aValue) {
- let stmt = mDBConn.createStatement(
- `UPDATE moz_places SET visit_count = :count WHERE url_hash = hash(:url)
- AND url = :url`
- );
- stmt.params.count = aValue;
- stmt.params.url = aURL;
- stmt.execute();
- stmt.finalize();
- }
- function setLastVisitDate(aURL, aValue) {
- let stmt = mDBConn.createStatement(
- `UPDATE moz_places SET last_visit_date = :date WHERE url_hash = hash(:url)
- AND url = :url`
- );
- stmt.params.date = aValue;
- stmt.params.url = aURL;
- stmt.execute();
- stmt.finalize();
- }
-
- let now = Date.now() * 1000;
- // Add a page with 1 visit.
- let url = "http://1.moz.org/";
- yield PlacesTestUtils.addVisits({ uri: uri(url), visitDate: now++ });
- // Add a page with 1 visit and set wrong visit_count.
- url = "http://2.moz.org/";
- yield PlacesTestUtils.addVisits({ uri: uri(url), visitDate: now++ });
- setVisitCount(url, 10);
- // Add a page with 1 visit and set wrong last_visit_date.
- url = "http://3.moz.org/";
- yield PlacesTestUtils.addVisits({ uri: uri(url), visitDate: now++ });
- setLastVisitDate(url, now++);
- // Add a page with 1 visit and set wrong stats.
- url = "http://4.moz.org/";
- yield PlacesTestUtils.addVisits({ uri: uri(url), visitDate: now++ });
- setVisitCount(url, 10);
- setLastVisitDate(url, now++);
-
- // Add a page without visits.
- url = "http://5.moz.org/";
- addPlace(url);
- // Add a page without visits and set wrong visit_count.
- url = "http://6.moz.org/";
- addPlace(url);
- setVisitCount(url, 10);
- // Add a page without visits and set wrong last_visit_date.
- url = "http://7.moz.org/";
- addPlace(url);
- setLastVisitDate(url, now++);
- // Add a page without visits and set wrong stats.
- url = "http://8.moz.org/";
- addPlace(url);
- setVisitCount(url, 10);
- setLastVisitDate(url, now++);
- },
-
- check: function() {
- let stmt = mDBConn.createStatement(
- `SELECT h.id FROM moz_places h
- JOIN moz_historyvisits v ON v.place_id = h.id AND visit_type NOT IN (0,4,7,8,9)
- GROUP BY h.id HAVING h.visit_count <> count(*)
- UNION ALL
- SELECT h.id FROM moz_places h
- JOIN moz_historyvisits v ON v.place_id = h.id
- GROUP BY h.id HAVING h.last_visit_date <> MAX(v.visit_date)`
- );
- do_check_false(stmt.executeStep());
- stmt.finalize();
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "L.3",
- desc: "recalculate hidden for redirects.",
-
- *setup() {
- yield PlacesTestUtils.addVisits([
- { uri: NetUtil.newURI("http://l3.moz.org/"),
- transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://l3.moz.org/redirecting/"),
- transition: TRANSITION_TYPED },
- { uri: NetUtil.newURI("http://l3.moz.org/redirecting2/"),
- transition: TRANSITION_REDIRECT_TEMPORARY,
- referrer: NetUtil.newURI("http://l3.moz.org/redirecting/") },
- { uri: NetUtil.newURI("http://l3.moz.org/target/"),
- transition: TRANSITION_REDIRECT_PERMANENT,
- referrer: NetUtil.newURI("http://l3.moz.org/redirecting2/") },
- ]);
- },
-
- check: function () {
- return new Promise(resolve => {
- let stmt = mDBConn.createAsyncStatement(
- "SELECT h.url FROM moz_places h WHERE h.hidden = 1"
- );
- stmt.executeAsync({
- _count: 0,
- handleResult: function(aResultSet) {
- for (let row; (row = aResultSet.getNextRow());) {
- let url = row.getResultByIndex(0);
- do_check_true(/redirecting/.test(url));
- this._count++;
- }
- },
- handleError: function(aError) {
- },
- handleCompletion: function(aReason) {
- dump_table("moz_places");
- dump_table("moz_historyvisits");
- do_check_eq(aReason, Ci.mozIStorageStatementCallback.REASON_FINISHED);
- do_check_eq(this._count, 2);
- resolve();
- }
- });
- stmt.finalize();
- });
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "L.4",
- desc: "recalculate foreign_count.",
-
- *setup() {
- this._pageGuid = (yield PlacesUtils.history.insert({ url: "http://l4.moz.org/",
- visits: [{ date: new Date() }] })).guid;
- yield PlacesUtils.bookmarks.insert({ url: "http://l4.moz.org/",
- parentGuid: PlacesUtils.bookmarks.unfiledGuid});
- yield PlacesUtils.keywords.insert({ url: "http://l4.moz.org/", keyword: "kw" });
- Assert.equal((yield this._getForeignCount()), 2);
- },
-
- *_getForeignCount() {
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(`SELECT foreign_count FROM moz_places
- WHERE guid = :guid`, { guid: this._pageGuid });
- return rows[0].getResultByName("foreign_count");
- },
-
- *check() {
- Assert.equal((yield this._getForeignCount()), 2);
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "L.5",
- desc: "recalculate hashes when missing.",
-
- *setup() {
- this._pageGuid = (yield PlacesUtils.history.insert({ url: "http://l5.moz.org/",
- visits: [{ date: new Date() }] })).guid;
- Assert.ok((yield this._getHash()) > 0);
- yield PlacesUtils.withConnectionWrapper("change url hash", Task.async(function* (db) {
- yield db.execute(`UPDATE moz_places SET url_hash = 0`);
- }));
- Assert.equal((yield this._getHash()), 0);
- },
-
- *_getHash() {
- let db = yield PlacesUtils.promiseDBConnection();
- let rows = yield db.execute(`SELECT url_hash FROM moz_places
- WHERE guid = :guid`, { guid: this._pageGuid });
- return rows[0].getResultByName("url_hash");
- },
-
- *check() {
- Assert.ok((yield this._getHash()) > 0);
- }
-});
-
-// ------------------------------------------------------------------------------
-
-tests.push({
- name: "Z",
- desc: "Sanity: Preventive maintenance does not touch valid items",
-
- _uri1: uri("http://www1.mozilla.org"),
- _uri2: uri("http://www2.mozilla.org"),
- _folderId: null,
- _bookmarkId: null,
- _separatorId: null,
-
- setup: function* () {
- // use valid api calls to create a bunch of items
- yield PlacesTestUtils.addVisits([
- { uri: this._uri1 },
- { uri: this._uri2 },
- ]);
-
- this._folderId = bs.createFolder(bs.toolbarFolder, "testfolder",
- bs.DEFAULT_INDEX);
- do_check_true(this._folderId > 0);
- this._bookmarkId = bs.insertBookmark(this._folderId, this._uri1,
- bs.DEFAULT_INDEX, "testbookmark");
- do_check_true(this._bookmarkId > 0);
- this._separatorId = bs.insertSeparator(bs.unfiledBookmarksFolder,
- bs.DEFAULT_INDEX);
- do_check_true(this._separatorId > 0);
- ts.tagURI(this._uri1, ["testtag"]);
- fs.setAndFetchFaviconForPage(this._uri2, SMALLPNG_DATA_URI, false,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- null,
- Services.scriptSecurityManager.getSystemPrincipal());
- yield PlacesUtils.keywords.insert({ url: this._uri1.spec, keyword: "testkeyword" });
- as.setPageAnnotation(this._uri2, "anno", "anno", 0, as.EXPIRE_NEVER);
- as.setItemAnnotation(this._bookmarkId, "anno", "anno", 0, as.EXPIRE_NEVER);
- },
-
- check: Task.async(function* () {
- // Check that all items are correct
- let isVisited = yield promiseIsURIVisited(this._uri1);
- do_check_true(isVisited);
- isVisited = yield promiseIsURIVisited(this._uri2);
- do_check_true(isVisited);
-
- do_check_eq(bs.getBookmarkURI(this._bookmarkId).spec, this._uri1.spec);
- do_check_eq(bs.getItemIndex(this._folderId), 0);
- do_check_eq(bs.getItemType(this._folderId), bs.TYPE_FOLDER);
- do_check_eq(bs.getItemType(this._separatorId), bs.TYPE_SEPARATOR);
-
- do_check_eq(ts.getTagsForURI(this._uri1).length, 1);
- do_check_eq((yield PlacesUtils.keywords.fetch({ url: this._uri1.spec })).keyword, "testkeyword");
- do_check_eq(as.getPageAnnotation(this._uri2, "anno"), "anno");
- do_check_eq(as.getItemAnnotation(this._bookmarkId, "anno"), "anno");
-
- yield new Promise(resolve => {
- fs.getFaviconURLForPage(this._uri2, aFaviconURI => {
- do_check_true(aFaviconURI.equals(SMALLPNG_DATA_URI));
- resolve();
- });
- });
- })
-});
-
-// ------------------------------------------------------------------------------
-
-add_task(function* test_preventive_maintenance()
-{
- // Get current bookmarks max ID for cleanup
- let stmt = mDBConn.createStatement("SELECT MAX(id) FROM moz_bookmarks");
- stmt.executeStep();
- defaultBookmarksMaxId = stmt.getInt32(0);
- stmt.finalize();
- do_check_true(defaultBookmarksMaxId > 0);
-
- for (let test of tests) {
- dump("\nExecuting test: " + test.name + "\n" + "*** " + test.desc + "\n");
- yield test.setup();
-
- let promiseMaintenanceFinished =
- promiseTopicObserved(FINISHED_MAINTENANCE_NOTIFICATION_TOPIC);
- Services.prefs.clearUserPref("places.database.lastMaintenance");
- let callbackInvoked = false;
- PlacesDBUtils.maintenanceOnIdle(() => callbackInvoked = true);
- yield promiseMaintenanceFinished;
- do_check_true(callbackInvoked);
-
- // Check the lastMaintenance time has been saved.
- do_check_neq(Services.prefs.getIntPref("places.database.lastMaintenance"), null);
-
- yield test.check();
-
- cleanDatabase();
- }
-
- // Sanity check: all roots should be intact
- do_check_eq(bs.getFolderIdForItem(bs.placesRoot), 0);
- do_check_eq(bs.getFolderIdForItem(bs.bookmarksMenuFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.tagsFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.unfiledBookmarksFolder), bs.placesRoot);
- do_check_eq(bs.getFolderIdForItem(bs.toolbarFolder), bs.placesRoot);
-});
diff --git a/toolkit/components/places/tests/unit/test_preventive_maintenance_checkAndFixDatabase.js b/toolkit/components/places/tests/unit/test_preventive_maintenance_checkAndFixDatabase.js
deleted file mode 100644
index a8acb4be0..000000000
--- a/toolkit/components/places/tests/unit/test_preventive_maintenance_checkAndFixDatabase.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Test preventive maintenance checkAndFixDatabase.
- */
-
-// Include PlacesDBUtils module.
-Components.utils.import("resource://gre/modules/PlacesDBUtils.jsm");
-
-function run_test() {
- do_test_pending();
- PlacesDBUtils.checkAndFixDatabase(function(aLog) {
- let sections = [];
- let positives = [];
- let negatives = [];
- let infos = [];
-
- aLog.forEach(function (aMsg) {
- print (aMsg);
- switch (aMsg.substr(0, 1)) {
- case "+":
- positives.push(aMsg);
- break;
- case "-":
- negatives.push(aMsg);
- break;
- case ">":
- sections.push(aMsg);
- break;
- default:
- infos.push(aMsg);
- }
- });
-
- print("Check that we have run all sections.");
- do_check_eq(sections.length, 5);
- print("Check that we have no negatives.");
- do_check_false(!!negatives.length);
- print("Check that we have positives.");
- do_check_true(!!positives.length);
- print("Check that we have info.");
- do_check_true(!!infos.length);
-
- do_test_finished();
- });
-}
diff --git a/toolkit/components/places/tests/unit/test_preventive_maintenance_runTasks.js b/toolkit/components/places/tests/unit/test_preventive_maintenance_runTasks.js
deleted file mode 100644
index ebe308f03..000000000
--- a/toolkit/components/places/tests/unit/test_preventive_maintenance_runTasks.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Test preventive maintenance runTasks.
- */
-
-// Include PlacesDBUtils module.
-Components.utils.import("resource://gre/modules/PlacesDBUtils.jsm");
-
-function run_test() {
- do_test_pending();
- PlacesDBUtils.runTasks([PlacesDBUtils.reindex], function(aLog) {
- let sections = [];
- let positives = [];
- let negatives = [];
- let infos = [];
-
- aLog.forEach(function (aMsg) {
- print (aMsg);
- switch (aMsg.substr(0, 1)) {
- case "+":
- positives.push(aMsg);
- break;
- case "-":
- negatives.push(aMsg);
- break;
- case ">":
- sections.push(aMsg);
- break;
- default:
- infos.push(aMsg);
- }
- });
-
- print("Check that we have run all sections.");
- do_check_eq(sections.length, 1);
- print("Check that we have no negatives.");
- do_check_false(!!negatives.length);
- print("Check that we have positives.");
- do_check_true(!!positives.length);
-
- do_test_finished();
- });
-}
diff --git a/toolkit/components/places/tests/unit/test_promiseBookmarksTree.js b/toolkit/components/places/tests/unit/test_promiseBookmarksTree.js
deleted file mode 100644
index 0719a0cd4..000000000
--- a/toolkit/components/places/tests/unit/test_promiseBookmarksTree.js
+++ /dev/null
@@ -1,256 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function* check_has_child(aParentGuid, aChildGuid) {
- let parentTree = yield PlacesUtils.promiseBookmarksTree(aParentGuid);
- do_check_true("children" in parentTree);
- do_check_true(parentTree.children.find( e => e.guid == aChildGuid ) != null);
-}
-
-function* compareToNode(aItem, aNode, aIsRootItem, aExcludedGuids = []) {
- // itemId==-1 indicates a non-bookmark node, which is unexpected.
- do_check_neq(aNode.itemId, -1);
-
- function check_unset(...aProps) {
- aProps.forEach( p => { do_check_false(p in aItem); } );
- }
- function strict_eq_check(v1, v2) {
- dump("v1: " + v1 + " v2: " + v2 + "\n");
- do_check_eq(typeof v1, typeof v2);
- do_check_eq(v1, v2);
- }
- function compare_prop(aItemProp, aNodeProp = aItemProp, aOptional = false) {
- if (aOptional && aNode[aNodeProp] === null)
- check_unset(aItemProp);
- else
- strict_eq_check(aItem[aItemProp], aNode[aNodeProp]);
- }
- function compare_prop_to_value(aItemProp, aValue, aOptional = true) {
- if (aOptional && aValue === null)
- check_unset(aItemProp);
- else
- strict_eq_check(aItem[aItemProp], aValue);
- }
-
- // Bug 1013053 - bookmarkIndex is unavailable for the query's root
- if (aNode.bookmarkIndex == -1) {
- compare_prop_to_value("index",
- PlacesUtils.bookmarks.getItemIndex(aNode.itemId),
- false);
- }
- else {
- compare_prop("index", "bookmarkIndex");
- }
-
- compare_prop("dateAdded");
- compare_prop("lastModified");
-
- if (aIsRootItem && aNode.itemId != PlacesUtils.placesRootId) {
- do_check_true("parentGuid" in aItem);
- yield check_has_child(aItem.parentGuid, aItem.guid)
- }
- else {
- check_unset("parentGuid");
- }
-
- let expectedAnnos = PlacesUtils.getAnnotationsForItem(aItem.id);
- if (expectedAnnos.length > 0) {
- let annosToString = annos => {
- return annos.map(a => a.name + ":" + a.value).sort().join(",");
- };
- do_check_true(Array.isArray(aItem.annos))
- do_check_eq(annosToString(aItem.annos), annosToString(expectedAnnos));
- }
- else {
- check_unset("annos");
- }
- const BOOKMARK_ONLY_PROPS = ["uri", "iconuri", "tags", "charset", "keyword"];
- const FOLDER_ONLY_PROPS = ["children", "root"];
-
- let nodesCount = 1;
-
- switch (aNode.type) {
- case Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER:
- do_check_eq(aItem.type, PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER);
- compare_prop("title", "title", true);
- check_unset(...BOOKMARK_ONLY_PROPS);
-
- let expectedChildrenNodes = [];
-
- PlacesUtils.asContainer(aNode);
- if (!aNode.containerOpen)
- aNode.containerOpen = true;
-
- for (let i = 0; i < aNode.childCount; i++) {
- let childNode = aNode.getChild(i);
- if (childNode.itemId == PlacesUtils.tagsFolderId ||
- aExcludedGuids.includes(childNode.bookmarkGuid)) {
- continue;
- }
- expectedChildrenNodes.push(childNode);
- }
-
- if (expectedChildrenNodes.length > 0) {
- do_check_true(Array.isArray(aItem.children));
- do_check_eq(aItem.children.length, expectedChildrenNodes.length);
- for (let i = 0; i < aItem.children.length; i++) {
- nodesCount +=
- yield compareToNode(aItem.children[i], expectedChildrenNodes[i],
- false, aExcludedGuids);
- }
- }
- else {
- check_unset("children");
- }
-
- switch (aItem.id) {
- case PlacesUtils.placesRootId:
- compare_prop_to_value("root", "placesRoot");
- break;
- case PlacesUtils.bookmarksMenuFolderId:
- compare_prop_to_value("root", "bookmarksMenuFolder");
- break;
- case PlacesUtils.toolbarFolderId:
- compare_prop_to_value("root", "toolbarFolder");
- break;
- case PlacesUtils.unfiledBookmarksFolderId:
- compare_prop_to_value("root", "unfiledBookmarksFolder");
- break;
- case PlacesUtils.mobileFolderId:
- compare_prop_to_value("root", "mobileFolder");
- break;
- default:
- check_unset("root");
- }
- break;
- case Ci.nsINavHistoryResultNode.RESULT_TYPE_SEPARATOR:
- do_check_eq(aItem.type, PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR);
- check_unset(...BOOKMARK_ONLY_PROPS, ...FOLDER_ONLY_PROPS);
- break;
- default:
- do_check_eq(aItem.type, PlacesUtils.TYPE_X_MOZ_PLACE);
- compare_prop("uri");
- // node.tags's format is "a, b" whilst promiseBoookmarksTree is "a,b"
- if (aNode.tags === null)
- check_unset("tags");
- else
- compare_prop_to_value("tags", aNode.tags.replace(/, /g, ","), false);
-
- if (aNode.icon) {
- let nodeIconData = aNode.icon.replace("moz-anno:favicon:", "");
- compare_prop_to_value("iconuri", nodeIconData);
- }
- else {
- check_unset(aItem.iconuri);
- }
-
- check_unset(...FOLDER_ONLY_PROPS);
-
- let itemURI = uri(aNode.uri);
- compare_prop_to_value("charset",
- yield PlacesUtils.getCharsetForURI(itemURI));
-
- let entry = yield PlacesUtils.keywords.fetch({ url: aNode.uri });
- compare_prop_to_value("keyword", entry ? entry.keyword : null);
-
- if ("title" in aItem)
- compare_prop("title");
- else
- do_check_null(aNode.title);
- }
-
- if (aIsRootItem)
- do_check_eq(aItem.itemsCount, nodesCount);
-
- return nodesCount;
-}
-
-var itemsCount = 0;
-function* new_bookmark(aInfo) {
- ++itemsCount;
- if (!("url" in aInfo))
- aInfo.url = uri("http://test.item." + itemsCount);
-
- if (!("title" in aInfo))
- aInfo.title = "Test Item (bookmark) " + itemsCount;
-
- yield PlacesTransactions.NewBookmark(aInfo).transact();
-}
-
-function* new_folder(aInfo) {
- if (!("title" in aInfo))
- aInfo.title = "Test Item (folder) " + itemsCount;
- return yield PlacesTransactions.NewFolder(aInfo).transact();
-}
-
-// Walks a result nodes tree and test promiseBookmarksTree for each node.
-// DO NOT COPY THIS LOGIC: It is done here to accomplish a more comprehensive
-// test of the API (the entire hierarchy data is available in the very test).
-function* test_promiseBookmarksTreeForEachNode(aNode, aOptions, aExcludedGuids) {
- do_check_true(aNode.bookmarkGuid && aNode.bookmarkGuid.length > 0);
- let item = yield PlacesUtils.promiseBookmarksTree(aNode.bookmarkGuid, aOptions);
- yield* compareToNode(item, aNode, true, aExcludedGuids);
-
- for (let i = 0; i < aNode.childCount; i++) {
- let child = aNode.getChild(i);
- if (child.itemId != PlacesUtils.tagsFolderId)
- yield test_promiseBookmarksTreeForEachNode(child,
- { includeItemIds: true },
- aExcludedGuids);
- }
- return item;
-}
-
-function* test_promiseBookmarksTreeAgainstResult(aItemGuid = "",
- aOptions = { includeItemIds: true },
- aExcludedGuids) {
- let itemId = aItemGuid ?
- yield PlacesUtils.promiseItemId(aItemGuid) : PlacesUtils.placesRootId;
- let node = PlacesUtils.getFolderContents(itemId).root;
- return yield test_promiseBookmarksTreeForEachNode(node, aOptions, aExcludedGuids);
-}
-
-add_task(function* () {
- // Add some bookmarks to cover various use cases.
- yield new_bookmark({ parentGuid: PlacesUtils.bookmarks.toolbarGuid });
- yield new_folder({ parentGuid: PlacesUtils.bookmarks.menuGuid,
- annotations: [{ name: "TestAnnoA", value: "TestVal" },
- { name: "TestAnnoB", value: 0 }]});
- let sepInfo = { parentGuid: PlacesUtils.bookmarks.menuGuid };
- yield PlacesTransactions.NewSeparator(sepInfo).transact();
- let folderGuid = yield new_folder({ parentGuid: PlacesUtils.bookmarks.menuGuid });
- yield new_bookmark({ title: null,
- parentGuid: folderGuid,
- keyword: "test_keyword",
- tags: ["TestTagA", "TestTagB"],
- annotations: [{ name: "TestAnnoA", value: "TestVal2"}]});
- let urlWithCharsetAndFavicon = uri("http://charset.and.favicon");
- yield new_bookmark({ parentGuid: folderGuid, url: urlWithCharsetAndFavicon });
- yield PlacesUtils.setCharsetForURI(urlWithCharsetAndFavicon, "UTF-8");
- yield promiseSetIconForPage(urlWithCharsetAndFavicon, SMALLPNG_DATA_URI);
- // Test the default places root without specifying it.
- yield test_promiseBookmarksTreeAgainstResult();
-
- // Do specify it
- yield test_promiseBookmarksTreeAgainstResult(PlacesUtils.bookmarks.rootGuid);
-
- // Exclude the bookmarks menu.
- // The calllback should be four times - once for the toolbar, once for
- // the bookmark we inserted under, and once for the menu (and not
- // at all for any of its descendants) and once for the unsorted bookmarks
- // folder. However, promiseBookmarksTree is called multiple times, so
- // rather than counting the calls, we count the number of unique items
- // passed in.
- let guidsPassedToExcludeCallback = new Set();
- let placesRootWithoutTheMenu =
- yield test_promiseBookmarksTreeAgainstResult(PlacesUtils.bookmarks.rootGuid, {
- excludeItemsCallback: aItem => {
- guidsPassedToExcludeCallback.add(aItem.guid);
- return aItem.root == "bookmarksMenuFolder";
- },
- includeItemIds: true
- }, [PlacesUtils.bookmarks.menuGuid]);
- do_check_eq(guidsPassedToExcludeCallback.size, 5);
- do_check_eq(placesRootWithoutTheMenu.children.length, 3);
-});
diff --git a/toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js b/toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js
deleted file mode 100644
index 01fb3eef9..000000000
--- a/toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_resolveNullBookmarkTitles() {
- let uri1 = uri("http://foo.tld/");
- let uri2 = uri("https://bar.tld/");
-
- PlacesTestUtils.addVisits([
- { uri: uri1, title: "foo title" },
- { uri: uri2, title: "bar title" }
- ]).then(function () {
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
- uri1,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- null);
- PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId,
- uri2,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- null);
-
- PlacesUtils.tagging.tagURI(uri1, ["tag 1"]);
- PlacesUtils.tagging.tagURI(uri2, ["tag 2"]);
-
- let options = PlacesUtils.history.getNewQueryOptions();
- options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
- options.resultType = options.RESULTS_AS_TAG_CONTENTS;
-
- let query = PlacesUtils.history.getNewQuery();
- // if we don't set a tag folder, RESULTS_AS_TAG_CONTENTS will return all
- // tagged URIs
- let root = PlacesUtils.history.executeQuery(query, options).root;
- root.containerOpen = true;
- do_check_eq(root.childCount, 2);
- // actually RESULTS_AS_TAG_CONTENTS return results ordered by place_id DESC
- // so they are reversed
- do_check_eq(root.getChild(0).title, "bar title");
- do_check_eq(root.getChild(1).title, "foo title");
- root.containerOpen = false;
-
- run_next_test();
- });
-});
diff --git a/toolkit/components/places/tests/unit/test_result_sort.js b/toolkit/components/places/tests/unit/test_result_sort.js
deleted file mode 100644
index 35405ac50..000000000
--- a/toolkit/components/places/tests/unit/test_result_sort.js
+++ /dev/null
@@ -1,139 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const NHQO = Ci.nsINavHistoryQueryOptions;
-
-/**
- * Waits for onItemVisited notifications to be received.
- */
-function promiseOnItemVisited() {
- let defer = Promise.defer();
- let bookmarksObserver = {
- __proto__: NavBookmarkObserver.prototype,
- onItemVisited: function BO_onItemVisited() {
- PlacesUtils.bookmarks.removeObserver(this);
- // Enqueue to be sure that all onItemVisited notifications ran.
- do_execute_soon(defer.resolve);
- }
- };
- PlacesUtils.bookmarks.addObserver(bookmarksObserver, false);
- return defer.promise;
-}
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* test() {
- let testFolder = PlacesUtils.bookmarks.createFolder(
- PlacesUtils.bookmarks.placesRoot,
- "Result-sort functionality tests root",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
-
- let uri1 = NetUtil.newURI("http://foo.tld/a");
- let uri2 = NetUtil.newURI("http://foo.tld/b");
-
- let id1 = PlacesUtils.bookmarks.insertBookmark(
- testFolder, uri1, PlacesUtils.bookmarks.DEFAULT_INDEX, "b");
- let id2 = PlacesUtils.bookmarks.insertBookmark(
- testFolder, uri2, PlacesUtils.bookmarks.DEFAULT_INDEX, "a");
- // url of id1, title of id2
- let id3 = PlacesUtils.bookmarks.insertBookmark(
- testFolder, uri1, PlacesUtils.bookmarks.DEFAULT_INDEX, "a");
-
- // query with natural order
- let result = PlacesUtils.getFolderContents(testFolder);
- let root = result.root;
-
- do_check_eq(root.childCount, 3);
-
- function checkOrder(a, b, c) {
- do_check_eq(root.getChild(0).itemId, a);
- do_check_eq(root.getChild(1).itemId, b);
- do_check_eq(root.getChild(2).itemId, c);
- }
-
- // natural order
- do_print("Natural order");
- checkOrder(id1, id2, id3);
-
- // title: id3 should precede id2 since we fall-back to URI-based sorting
- do_print("Sort by title asc");
- result.sortingMode = NHQO.SORT_BY_TITLE_ASCENDING;
- checkOrder(id3, id2, id1);
-
- // In reverse
- do_print("Sort by title desc");
- result.sortingMode = NHQO.SORT_BY_TITLE_DESCENDING;
- checkOrder(id1, id2, id3);
-
- // uri sort: id1 should precede id3 since we fall-back to natural order
- do_print("Sort by uri asc");
- result.sortingMode = NHQO.SORT_BY_URI_ASCENDING;
- checkOrder(id1, id3, id2);
-
- // test live update
- do_print("Change bookmark uri liveupdate");
- PlacesUtils.bookmarks.changeBookmarkURI(id1, uri2);
- checkOrder(id3, id1, id2);
- PlacesUtils.bookmarks.changeBookmarkURI(id1, uri1);
- checkOrder(id1, id3, id2);
-
- // keyword sort
- do_print("Sort by keyword asc");
- result.sortingMode = NHQO.SORT_BY_KEYWORD_ASCENDING;
- checkOrder(id3, id2, id1); // no keywords set - falling back to title sort
- yield PlacesUtils.keywords.insert({ url: uri1.spec, keyword: "a" });
- yield PlacesUtils.keywords.insert({ url: uri2.spec, keyword: "z" });
- checkOrder(id3, id1, id2);
-
- // XXXtodo: test history sortings (visit count, visit date)
- // XXXtodo: test different item types once folderId and bookmarkId are merged.
- // XXXtodo: test sortingAnnotation functionality with non-bookmark nodes
-
- do_print("Sort by annotation desc");
- PlacesUtils.annotations.setItemAnnotation(id1, "testAnno", "a", 0, 0);
- PlacesUtils.annotations.setItemAnnotation(id3, "testAnno", "b", 0, 0);
- result.sortingAnnotation = "testAnno";
- result.sortingMode = NHQO.SORT_BY_ANNOTATION_DESCENDING;
-
- // id1 precedes id2 per title-descending fallback
- checkOrder(id3, id1, id2);
-
- // XXXtodo: test dateAdded sort
- // XXXtodo: test lastModified sort
-
- // test live update
- do_print("Annotation liveupdate");
- PlacesUtils.annotations.setItemAnnotation(id1, "testAnno", "c", 0, 0);
- checkOrder(id1, id3, id2);
-
- // Add a visit, then check frecency ordering.
-
- // When the bookmarks service gets onVisit, it asynchronously fetches all
- // items for that visit, and then notifies onItemVisited. Thus we must
- // explicitly wait for that.
- let waitForVisited = promiseOnItemVisited();
- yield PlacesTestUtils.addVisits({ uri: uri2, transition: TRANSITION_TYPED });
- yield waitForVisited;
-
- do_print("Sort by frecency desc");
- result.sortingMode = NHQO.SORT_BY_FRECENCY_DESCENDING;
- for (let i = 0; i < root.childCount; ++i) {
- print(root.getChild(i).uri + " " + root.getChild(i).title);
- }
- // For id1 and id3, since they have same frecency and no visits, fallback
- // to sort by the newest bookmark.
- checkOrder(id2, id3, id1);
- do_print("Sort by frecency asc");
- result.sortingMode = NHQO.SORT_BY_FRECENCY_ASCENDING;
- for (let i = 0; i < root.childCount; ++i) {
- print(root.getChild(i).uri + " " + root.getChild(i).title);
- }
- checkOrder(id1, id3, id2);
-
- root.containerOpen = false;
-});
diff --git a/toolkit/components/places/tests/unit/test_resultsAsVisit_details.js b/toolkit/components/places/tests/unit/test_resultsAsVisit_details.js
deleted file mode 100644
index 8e71ffd0d..000000000
--- a/toolkit/components/places/tests/unit/test_resultsAsVisit_details.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-
-const {bookmarks, history} = PlacesUtils
-
-add_task(function* test_addVisitCheckFields() {
- let uri = NetUtil.newURI("http://test4.com/");
- yield PlacesTestUtils.addVisits([
- { uri },
- { uri, referrer: uri },
- { uri, transition: history.TRANSITION_TYPED },
- ]);
-
-
- let options = history.getNewQueryOptions();
- let query = history.getNewQuery();
-
- query.uri = uri;
-
-
- // Check RESULTS_AS_VISIT node.
- options.resultType = options.RESULTS_AS_VISIT;
-
- let root = history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- equal(root.childCount, 3);
-
- let child = root.getChild(0);
- equal(child.visitType, history.TRANSITION_LINK, "Visit type should be TRANSITION_LINK");
- equal(child.visitId, 1, "Visit ID should be 1");
- equal(child.fromVisitId, -1, "Should have no referrer visit ID");
-
- child = root.getChild(1);
- equal(child.visitType, history.TRANSITION_LINK, "Visit type should be TRANSITION_LINK");
- equal(child.visitId, 2, "Visit ID should be 2");
- equal(child.fromVisitId, 1, "First visit should be the referring visit");
-
- child = root.getChild(2);
- equal(child.visitType, history.TRANSITION_TYPED, "Visit type should be TRANSITION_TYPED");
- equal(child.visitId, 3, "Visit ID should be 3");
- equal(child.fromVisitId, -1, "Should have no referrer visit ID");
-
- root.containerOpen = false;
-
-
- // Check RESULTS_AS_URI node.
- options.resultType = options.RESULTS_AS_URI;
-
- root = history.executeQuery(query, options).root;
- root.containerOpen = true;
-
- equal(root.childCount, 1);
-
- child = root.getChild(0);
- equal(child.visitType, 0, "Visit type should be 0");
- equal(child.visitId, -1, "Visit ID should be -1");
- equal(child.fromVisitId, -1, "Referrer visit id should be -1");
-
- root.containerOpen = false;
-
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* test_bookmarkFields() {
- let folder = bookmarks.createFolder(bookmarks.placesRoot, "test folder", bookmarks.DEFAULT_INDEX);
- bookmarks.insertBookmark(folder, uri("http://test4.com/"),
- bookmarks.DEFAULT_INDEX, "test4 title");
-
- let root = PlacesUtils.getFolderContents(folder).root;
- equal(root.childCount, 1);
-
- equal(root.visitType, 0, "Visit type should be 0");
- equal(root.visitId, -1, "Visit ID should be -1");
- equal(root.fromVisitId, -1, "Referrer visit id should be -1");
-
- let child = root.getChild(0);
- equal(child.visitType, 0, "Visit type should be 0");
- equal(child.visitId, -1, "Visit ID should be -1");
- equal(child.fromVisitId, -1, "Referrer visit id should be -1");
-
- root.containerOpen = false;
-
- yield bookmarks.eraseEverything();
-});
diff --git a/toolkit/components/places/tests/unit/test_sql_guid_functions.js b/toolkit/components/places/tests/unit/test_sql_guid_functions.js
deleted file mode 100644
index 41e6bab9e..000000000
--- a/toolkit/components/places/tests/unit/test_sql_guid_functions.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * This file tests that the guid function generates a guid of the proper length,
- * with no invalid characters.
- */
-
-/**
- * Checks all our invariants about our guids for a given result.
- *
- * @param aGuid
- * The guid to check.
- */
-function check_invariants(aGuid)
-{
- do_print("Checking guid '" + aGuid + "'");
-
- do_check_valid_places_guid(aGuid);
-}
-
-// Test Functions
-
-function test_guid_invariants()
-{
- const kExpectedChars = 64;
- const kAllowedChars =
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
- do_check_eq(kAllowedChars.length, kExpectedChars);
- const kGuidLength = 12;
-
- let checkedChars = [];
- for (let i = 0; i < kGuidLength; i++) {
- checkedChars[i] = {};
- for (let j = 0; j < kAllowedChars; j++) {
- checkedChars[i][kAllowedChars[j]] = false;
- }
- }
-
- // We run this until we've seen every character that we expect to see in every
- // position.
- let seenChars = 0;
- let stmt = DBConn().createStatement("SELECT GENERATE_GUID()");
- while (seenChars != (kExpectedChars * kGuidLength)) {
- do_check_true(stmt.executeStep());
- let guid = stmt.getString(0);
- check_invariants(guid);
-
- for (let i = 0; i < guid.length; i++) {
- let character = guid[i];
- if (!checkedChars[i][character]) {
- checkedChars[i][character] = true;
- seenChars++;
- }
- }
- stmt.reset();
- }
- stmt.finalize();
-
- // One last reality check - make sure all of our characters were seen.
- for (let i = 0; i < kGuidLength; i++) {
- for (let j = 0; j < kAllowedChars; j++) {
- do_check_true(checkedChars[i][kAllowedChars[j]]);
- }
- }
-
- run_next_test();
-}
-
-function test_guid_on_background()
-{
- // We should not assert if we execute this asynchronously.
- let stmt = DBConn().createAsyncStatement("SELECT GENERATE_GUID()");
- let checked = false;
- stmt.executeAsync({
- handleResult: function(aResult) {
- try {
- let row = aResult.getNextRow();
- check_invariants(row.getResultByIndex(0));
- do_check_eq(aResult.getNextRow(), null);
- checked = true;
- }
- catch (e) {
- do_throw(e);
- }
- },
- handleCompletion: function(aReason) {
- do_check_eq(aReason, Ci.mozIStorageStatementCallback.REASON_FINISHED);
- do_check_true(checked);
- run_next_test();
- }
- });
- stmt.finalize();
-}
-
-// Test Runner
-
-[
- test_guid_invariants,
- test_guid_on_background,
-].forEach(add_test);
-
-function run_test()
-{
- run_next_test();
-}
diff --git a/toolkit/components/places/tests/unit/test_svg_favicon.js b/toolkit/components/places/tests/unit/test_svg_favicon.js
deleted file mode 100644
index cec40ddef..000000000
--- a/toolkit/components/places/tests/unit/test_svg_favicon.js
+++ /dev/null
@@ -1,31 +0,0 @@
-const PAGEURI = NetUtil.newURI("http://deliciousbacon.com/");
-
-add_task(function* () {
- // First, add a history entry or else Places can't save a favicon.
- yield PlacesTestUtils.addVisits({
- uri: PAGEURI,
- transition: TRANSITION_LINK,
- visitDate: Date.now() * 1000
- });
-
- yield new Promise(resolve => {
- function onSetComplete(aURI, aDataLen, aData, aMimeType) {
- equal(aURI.spec, SMALLSVG_DATA_URI.spec, "setFavicon aURI check");
- equal(aDataLen, 263, "setFavicon aDataLen check");
- equal(aMimeType, "image/svg+xml", "setFavicon aMimeType check");
- resolve();
- }
-
- PlacesUtils.favicons.setAndFetchFaviconForPage(PAGEURI, SMALLSVG_DATA_URI,
- false,
- PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
- onSetComplete,
- Services.scriptSecurityManager.getSystemPrincipal());
- });
-
- let data = yield PlacesUtils.promiseFaviconData(PAGEURI.spec);
- equal(data.uri.spec, SMALLSVG_DATA_URI.spec, "getFavicon aURI check");
- equal(data.dataLen, 263, "getFavicon aDataLen check");
- equal(data.mimeType, "image/svg+xml", "getFavicon aMimeType check");
-});
-
diff --git a/toolkit/components/places/tests/unit/test_sync_utils.js b/toolkit/components/places/tests/unit/test_sync_utils.js
deleted file mode 100644
index f8c7e6b58..000000000
--- a/toolkit/components/places/tests/unit/test_sync_utils.js
+++ /dev/null
@@ -1,1150 +0,0 @@
-Cu.import("resource://gre/modules/PlacesSyncUtils.jsm");
-Cu.import("resource://testing-common/httpd.js");
-Cu.importGlobalProperties(["crypto", "URLSearchParams"]);
-
-const DESCRIPTION_ANNO = "bookmarkProperties/description";
-const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar";
-const SYNC_PARENT_ANNO = "sync/parent";
-
-function makeGuid() {
- return ChromeUtils.base64URLEncode(crypto.getRandomValues(new Uint8Array(9)), {
- pad: false,
- });
-}
-
-function makeLivemarkServer() {
- let server = new HttpServer();
- server.registerPrefixHandler("/feed/", do_get_file("./livemark.xml"));
- server.start(-1);
- return {
- server,
- get site() {
- let { identity } = server;
- let host = identity.primaryHost.includes(":") ?
- `[${identity.primaryHost}]` : identity.primaryHost;
- return `${identity.primaryScheme}://${host}:${identity.primaryPort}`;
- },
- stopServer() {
- return new Promise(resolve => server.stop(resolve));
- },
- };
-}
-
-function shuffle(array) {
- let results = [];
- for (let i = 0; i < array.length; ++i) {
- let randomIndex = Math.floor(Math.random() * (i + 1));
- results[i] = results[randomIndex];
- results[randomIndex] = array[i];
- }
- return results;
-}
-
-function compareAscending(a, b) {
- if (a > b) {
- return 1;
- }
- if (a < b) {
- return -1;
- }
- return 0;
-}
-
-function assertTagForURLs(tag, urls, message) {
- let taggedURLs = PlacesUtils.tagging.getURIsForTag(tag).map(uri => uri.spec);
- deepEqual(taggedURLs.sort(compareAscending), urls.sort(compareAscending), message);
-}
-
-function assertURLHasTags(url, tags, message) {
- let actualTags = PlacesUtils.tagging.getTagsForURI(uri(url));
- deepEqual(actualTags.sort(compareAscending), tags, message);
-}
-
-var populateTree = Task.async(function* populate(parentGuid, ...items) {
- let guids = {};
-
- for (let index = 0; index < items.length; index++) {
- let item = items[index];
- let guid = makeGuid();
-
- switch (item.kind) {
- case "bookmark":
- case "query":
- yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: item.url,
- title: item.title,
- parentGuid, guid, index,
- });
- break;
-
- case "separator":
- yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_SEPARATOR,
- parentGuid, guid,
- });
- break;
-
- case "folder":
- yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: item.title,
- parentGuid, guid,
- });
- if (item.children) {
- Object.assign(guids, yield* populate(guid, ...item.children));
- }
- break;
-
- default:
- throw new Error(`Unsupported item type: ${item.type}`);
- }
-
- if (item.exclude) {
- let itemId = yield PlacesUtils.promiseItemId(guid);
- PlacesUtils.annotations.setItemAnnotation(
- itemId, PlacesUtils.EXCLUDE_FROM_BACKUP_ANNO, "Don't back this up", 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- }
-
- guids[item.title] = guid;
- }
-
- return guids;
-});
-
-var syncIdToId = Task.async(function* syncIdToId(syncId) {
- let guid = yield PlacesSyncUtils.bookmarks.syncIdToGuid(syncId);
- return PlacesUtils.promiseItemId(guid);
-});
-
-add_task(function* test_order() {
- do_print("Insert some bookmarks");
- let guids = yield populateTree(PlacesUtils.bookmarks.menuGuid, {
- kind: "bookmark",
- title: "childBmk",
- url: "http://getfirefox.com",
- }, {
- kind: "bookmark",
- title: "siblingBmk",
- url: "http://getthunderbird.com",
- }, {
- kind: "folder",
- title: "siblingFolder",
- }, {
- kind: "separator",
- title: "siblingSep",
- });
-
- do_print("Reorder inserted bookmarks");
- {
- let order = [guids.siblingFolder, guids.siblingSep, guids.childBmk,
- guids.siblingBmk];
- yield PlacesSyncUtils.bookmarks.order(PlacesUtils.bookmarks.menuGuid, order);
- let childSyncIds = yield PlacesSyncUtils.bookmarks.fetchChildSyncIds(PlacesUtils.bookmarks.menuGuid);
- deepEqual(childSyncIds, order, "New bookmarks should be reordered according to array");
- }
-
- do_print("Reorder with unspecified children");
- {
- yield PlacesSyncUtils.bookmarks.order(PlacesUtils.bookmarks.menuGuid, [
- guids.siblingSep, guids.siblingBmk,
- ]);
- let childSyncIds = yield PlacesSyncUtils.bookmarks.fetchChildSyncIds(
- PlacesUtils.bookmarks.menuGuid);
- deepEqual(childSyncIds, [guids.siblingSep, guids.siblingBmk,
- guids.siblingFolder, guids.childBmk],
- "Unordered children should be moved to end");
- }
-
- do_print("Reorder with nonexistent children");
- {
- yield PlacesSyncUtils.bookmarks.order(PlacesUtils.bookmarks.menuGuid, [
- guids.childBmk, makeGuid(), guids.siblingBmk, guids.siblingSep,
- makeGuid(), guids.siblingFolder, makeGuid()]);
- let childSyncIds = yield PlacesSyncUtils.bookmarks.fetchChildSyncIds(
- PlacesUtils.bookmarks.menuGuid);
- deepEqual(childSyncIds, [guids.childBmk, guids.siblingBmk, guids.siblingSep,
- guids.siblingFolder], "Nonexistent children should be ignored");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_changeGuid_invalid() {
- yield rejects(PlacesSyncUtils.bookmarks.changeGuid(makeGuid()),
- "Should require a new GUID");
- yield rejects(PlacesSyncUtils.bookmarks.changeGuid(makeGuid(), "!@#$"),
- "Should reject invalid GUIDs");
- yield rejects(PlacesSyncUtils.bookmarks.changeGuid(makeGuid(), makeGuid()),
- "Should reject nonexistent item GUIDs");
- yield rejects(
- PlacesSyncUtils.bookmarks.changeGuid(PlacesUtils.bookmarks.menuGuid,
- makeGuid()),
- "Should reject roots");
-});
-
-add_task(function* test_changeGuid() {
- let item = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "https://mozilla.org",
- });
- let id = yield PlacesUtils.promiseItemId(item.guid);
-
- let newGuid = makeGuid();
- let result = yield PlacesSyncUtils.bookmarks.changeGuid(item.guid, newGuid);
- equal(result, newGuid, "Should return new GUID");
-
- equal(yield PlacesUtils.promiseItemId(newGuid), id, "Should map ID to new GUID");
- yield rejects(PlacesUtils.promiseItemId(item.guid), "Should not map ID to old GUID");
- equal(yield PlacesUtils.promiseItemGuid(id), newGuid, "Should map new GUID to ID");
-});
-
-add_task(function* test_order_roots() {
- let oldOrder = yield PlacesSyncUtils.bookmarks.fetchChildSyncIds(
- PlacesUtils.bookmarks.rootGuid);
- yield PlacesSyncUtils.bookmarks.order(PlacesUtils.bookmarks.rootGuid,
- shuffle(oldOrder));
- let newOrder = yield PlacesSyncUtils.bookmarks.fetchChildSyncIds(
- PlacesUtils.bookmarks.rootGuid);
- deepEqual(oldOrder, newOrder, "Should ignore attempts to reorder roots");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_update_tags() {
- do_print("Insert item without tags");
- let item = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- url: "https://mozilla.org",
- syncId: makeGuid(),
- parentSyncId: "menu",
- });
-
- do_print("Add tags");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- tags: ["foo", "bar"],
- });
- deepEqual(updatedItem.tags, ["foo", "bar"], "Should return new tags");
- assertURLHasTags("https://mozilla.org", ["bar", "foo"],
- "Should set new tags for URL");
- }
-
- do_print("Add new tag, remove existing tag");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- tags: ["foo", "baz"],
- });
- deepEqual(updatedItem.tags, ["foo", "baz"], "Should return updated tags");
- assertURLHasTags("https://mozilla.org", ["baz", "foo"],
- "Should update tags for URL");
- assertTagForURLs("bar", [], "Should remove existing tag");
- }
-
- do_print("Tags with whitespace");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- tags: [" leading", "trailing ", " baz ", " "],
- });
- deepEqual(updatedItem.tags, ["leading", "trailing", "baz"],
- "Should return filtered tags");
- assertURLHasTags("https://mozilla.org", ["baz", "leading", "trailing"],
- "Should trim whitespace and filter blank tags");
- }
-
- do_print("Remove all tags");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- tags: null,
- });
- deepEqual(updatedItem.tags, [], "Should return empty tag array");
- assertURLHasTags("https://mozilla.org", [],
- "Should remove all existing tags");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_update_keyword() {
- do_print("Insert item without keyword");
- let item = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- parentSyncId: "menu",
- url: "https://mozilla.org",
- syncId: makeGuid(),
- });
-
- do_print("Add item keyword");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- keyword: "moz",
- });
- equal(updatedItem.keyword, "moz", "Should return new keyword");
- let entryByKeyword = yield PlacesUtils.keywords.fetch("moz");
- equal(entryByKeyword.url.href, "https://mozilla.org/",
- "Should set new keyword for URL");
- let entryByURL = yield PlacesUtils.keywords.fetch({
- url: "https://mozilla.org",
- });
- equal(entryByURL.keyword, "moz", "Looking up URL should return new keyword");
- }
-
- do_print("Change item keyword");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- keyword: "m",
- });
- equal(updatedItem.keyword, "m", "Should return updated keyword");
- let newEntry = yield PlacesUtils.keywords.fetch("m");
- equal(newEntry.url.href, "https://mozilla.org/", "Should update keyword for URL");
- let oldEntry = yield PlacesUtils.keywords.fetch("moz");
- ok(!oldEntry, "Should remove old keyword");
- }
-
- do_print("Remove existing keyword");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- keyword: null,
- });
- ok(!updatedItem.keyword,
- "Should not include removed keyword in properties");
- let entry = yield PlacesUtils.keywords.fetch({
- url: "https://mozilla.org",
- });
- ok(!entry, "Should remove new keyword from URL");
- }
-
- do_print("Remove keyword for item without keyword");
- {
- yield PlacesSyncUtils.bookmarks.update({
- syncId: item.syncId,
- keyword: null,
- });
- let entry = yield PlacesUtils.keywords.fetch({
- url: "https://mozilla.org",
- });
- ok(!entry,
- "Removing keyword for URL without existing keyword should succeed");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_update_annos() {
- let guids = yield populateTree(PlacesUtils.bookmarks.menuGuid, {
- kind: "folder",
- title: "folder",
- }, {
- kind: "bookmark",
- title: "bmk",
- url: "https://example.com",
- });
-
- do_print("Add folder description");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: guids.folder,
- description: "Folder description",
- });
- equal(updatedItem.description, "Folder description",
- "Should return new description");
- let id = yield syncIdToId(updatedItem.syncId);
- equal(PlacesUtils.annotations.getItemAnnotation(id, DESCRIPTION_ANNO),
- "Folder description", "Should set description anno");
- }
-
- do_print("Clear folder description");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: guids.folder,
- description: null,
- });
- ok(!updatedItem.description, "Should not return cleared description");
- let id = yield syncIdToId(updatedItem.syncId);
- ok(!PlacesUtils.annotations.itemHasAnnotation(id, DESCRIPTION_ANNO),
- "Should remove description anno");
- }
-
- do_print("Add bookmark sidebar anno");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: guids.bmk,
- loadInSidebar: true,
- });
- ok(updatedItem.loadInSidebar, "Should return sidebar anno");
- let id = yield syncIdToId(updatedItem.syncId);
- ok(PlacesUtils.annotations.itemHasAnnotation(id, LOAD_IN_SIDEBAR_ANNO),
- "Should set sidebar anno for existing bookmark");
- }
-
- do_print("Clear bookmark sidebar anno");
- {
- let updatedItem = yield PlacesSyncUtils.bookmarks.update({
- syncId: guids.bmk,
- loadInSidebar: false,
- });
- ok(!updatedItem.loadInSidebar, "Should not return cleared sidebar anno");
- let id = yield syncIdToId(updatedItem.syncId);
- ok(!PlacesUtils.annotations.itemHasAnnotation(id, LOAD_IN_SIDEBAR_ANNO),
- "Should clear sidebar anno for existing bookmark");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_update_move_root() {
- do_print("Move root to same parent");
- {
- // This should be a no-op.
- let sameRoot = yield PlacesSyncUtils.bookmarks.update({
- syncId: "menu",
- parentSyncId: "places",
- });
- equal(sameRoot.syncId, "menu",
- "Menu root GUID should not change");
- equal(sameRoot.parentSyncId, "places",
- "Parent Places root GUID should not change");
- }
-
- do_print("Try reparenting root");
- yield rejects(PlacesSyncUtils.bookmarks.update({
- syncId: "menu",
- parentSyncId: "toolbar",
- }));
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert() {
- do_print("Insert bookmark");
- {
- let item = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- syncId: makeGuid(),
- parentSyncId: "menu",
- url: "https://example.org",
- });
- let { type } = yield PlacesUtils.bookmarks.fetch({ guid: item.syncId });
- equal(type, PlacesUtils.bookmarks.TYPE_BOOKMARK,
- "Bookmark should have correct type");
- }
-
- do_print("Insert query");
- {
- let item = yield PlacesSyncUtils.bookmarks.insert({
- kind: "query",
- syncId: makeGuid(),
- parentSyncId: "menu",
- url: "place:terms=term&folder=TOOLBAR&queryType=1",
- folder: "Saved search",
- });
- let { type } = yield PlacesUtils.bookmarks.fetch({ guid: item.syncId });
- equal(type, PlacesUtils.bookmarks.TYPE_BOOKMARK,
- "Queries should be stored as bookmarks");
- }
-
- do_print("Insert folder");
- {
- let item = yield PlacesSyncUtils.bookmarks.insert({
- kind: "folder",
- syncId: makeGuid(),
- parentSyncId: "menu",
- title: "New folder",
- });
- let { type } = yield PlacesUtils.bookmarks.fetch({ guid: item.syncId });
- equal(type, PlacesUtils.bookmarks.TYPE_FOLDER,
- "Folder should have correct type");
- }
-
- do_print("Insert separator");
- {
- let item = yield PlacesSyncUtils.bookmarks.insert({
- kind: "separator",
- syncId: makeGuid(),
- parentSyncId: "menu",
- });
- let { type } = yield PlacesUtils.bookmarks.fetch({ guid: item.syncId });
- equal(type, PlacesUtils.bookmarks.TYPE_SEPARATOR,
- "Separator should have correct type");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert_livemark() {
- let { site, stopServer } = makeLivemarkServer();
-
- try {
- do_print("Insert livemark with feed URL");
- {
- let livemark = yield PlacesSyncUtils.bookmarks.insert({
- kind: "livemark",
- syncId: makeGuid(),
- feed: site + "/feed/1",
- parentSyncId: "menu",
- });
- let bmk = yield PlacesUtils.bookmarks.fetch({
- guid: yield PlacesSyncUtils.bookmarks.syncIdToGuid(livemark.syncId),
- })
- equal(bmk.type, PlacesUtils.bookmarks.TYPE_FOLDER,
- "Livemarks should be stored as folders");
- }
-
- let livemarkSyncId;
- do_print("Insert livemark with site and feed URLs");
- {
- let livemark = yield PlacesSyncUtils.bookmarks.insert({
- kind: "livemark",
- syncId: makeGuid(),
- site,
- feed: site + "/feed/1",
- parentSyncId: "menu",
- });
- livemarkSyncId = livemark.syncId;
- }
-
- do_print("Try inserting livemark into livemark");
- {
- let livemark = yield PlacesSyncUtils.bookmarks.insert({
- kind: "livemark",
- syncId: makeGuid(),
- site,
- feed: site + "/feed/1",
- parentSyncId: livemarkSyncId,
- });
- ok(!livemark, "Should not insert livemark as child of livemark");
- }
- } finally {
- yield stopServer();
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_update_livemark() {
- let { site, stopServer } = makeLivemarkServer();
- let feedURI = uri(site + "/feed/1");
-
- try {
- // We shouldn't reinsert the livemark if the URLs are the same.
- do_print("Update livemark with same URLs");
- {
- let livemark = yield PlacesUtils.livemarks.addLivemark({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- feedURI,
- siteURI: uri(site),
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- });
-
- yield PlacesSyncUtils.bookmarks.update({
- syncId: livemark.guid,
- feed: feedURI,
- });
- // `nsLivemarkService` returns references to `Livemark` instances, so we
- // can compare them with `==` to make sure they haven't been replaced.
- equal(yield PlacesUtils.livemarks.getLivemark({
- guid: livemark.guid,
- }), livemark, "Livemark with same feed URL should not be replaced");
-
- yield PlacesSyncUtils.bookmarks.update({
- syncId: livemark.guid,
- site,
- });
- equal(yield PlacesUtils.livemarks.getLivemark({
- guid: livemark.guid,
- }), livemark, "Livemark with same site URL should not be replaced");
-
- yield PlacesSyncUtils.bookmarks.update({
- syncId: livemark.guid,
- feed: feedURI,
- site,
- });
- equal(yield PlacesUtils.livemarks.getLivemark({
- guid: livemark.guid,
- }), livemark, "Livemark with same feed and site URLs should not be replaced");
- }
-
- do_print("Change livemark feed URL");
- {
- let livemark = yield PlacesUtils.livemarks.addLivemark({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- feedURI,
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- });
-
- // Since we're reinserting, we need to pass all properties required
- // for a new livemark. `update` won't merge the old and new ones.
- yield rejects(PlacesSyncUtils.bookmarks.update({
- syncId: livemark.guid,
- feed: site + "/feed/2",
- }), "Reinserting livemark with changed feed URL requires full record");
-
- let newLivemark = yield PlacesSyncUtils.bookmarks.update({
- kind: "livemark",
- parentSyncId: "menu",
- syncId: livemark.guid,
- feed: site + "/feed/2",
- });
- equal(newLivemark.syncId, livemark.guid,
- "GUIDs should match for reinserted livemark with changed feed URL");
- equal(newLivemark.feed.href, site + "/feed/2",
- "Reinserted livemark should have changed feed URI");
- }
-
- do_print("Add livemark site URL");
- {
- let livemark = yield PlacesUtils.livemarks.addLivemark({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- feedURI,
- });
- ok(livemark.feedURI.equals(feedURI), "Livemark feed URI should match");
- ok(!livemark.siteURI, "Livemark should not have site URI");
-
- yield rejects(PlacesSyncUtils.bookmarks.update({
- syncId: livemark.guid,
- site,
- }), "Reinserting livemark with new site URL requires full record");
-
- let newLivemark = yield PlacesSyncUtils.bookmarks.update({
- kind: "livemark",
- parentSyncId: "menu",
- syncId: livemark.guid,
- feed: feedURI,
- site,
- });
- notEqual(newLivemark, livemark,
- "Livemark with new site URL should replace old livemark");
- equal(newLivemark.syncId, livemark.guid,
- "GUIDs should match for reinserted livemark with new site URL");
- equal(newLivemark.site.href, site + "/",
- "Reinserted livemark should have new site URI");
- equal(newLivemark.feed.href, feedURI.spec,
- "Reinserted livemark with new site URL should have same feed URI");
- }
-
- do_print("Remove livemark site URL");
- {
- let livemark = yield PlacesUtils.livemarks.addLivemark({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- feedURI,
- siteURI: uri(site),
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- });
-
- yield rejects(PlacesSyncUtils.bookmarks.update({
- syncId: livemark.guid,
- site: null,
- }), "Reinserting livemark witout site URL requires full record");
-
- let newLivemark = yield PlacesSyncUtils.bookmarks.update({
- kind: "livemark",
- parentSyncId: "menu",
- syncId: livemark.guid,
- feed: feedURI,
- site: null,
- });
- notEqual(newLivemark, livemark,
- "Livemark without site URL should replace old livemark");
- equal(newLivemark.syncId, livemark.guid,
- "GUIDs should match for reinserted livemark without site URL");
- ok(!newLivemark.site, "Reinserted livemark should not have site URI");
- }
-
- do_print("Change livemark site URL");
- {
- let livemark = yield PlacesUtils.livemarks.addLivemark({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- feedURI,
- siteURI: uri(site),
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- });
-
- yield rejects(PlacesSyncUtils.bookmarks.update({
- syncId: livemark.guid,
- site: site + "/new",
- }), "Reinserting livemark with changed site URL requires full record");
-
- let newLivemark = yield PlacesSyncUtils.bookmarks.update({
- kind: "livemark",
- parentSyncId: "menu",
- syncId: livemark.guid,
- feed:feedURI,
- site: site + "/new",
- });
- notEqual(newLivemark, livemark,
- "Livemark with changed site URL should replace old livemark");
- equal(newLivemark.syncId, livemark.guid,
- "GUIDs should match for reinserted livemark with changed site URL");
- equal(newLivemark.site.href, site + "/new",
- "Reinserted livemark should have changed site URI");
- }
-
- // Livemarks are stored as folders, but have different kinds. We should
- // remove the folder and insert a livemark with the same GUID instead of
- // trying to update the folder in-place.
- do_print("Replace folder with livemark");
- {
- let folder = yield PlacesUtils.bookmarks.insert({
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- title: "Plain folder",
- });
- let livemark = yield PlacesSyncUtils.bookmarks.update({
- kind: "livemark",
- parentSyncId: "menu",
- syncId: folder.guid,
- feed: feedURI,
- });
- equal(livemark.guid, folder.syncId,
- "Livemark should have same GUID as replaced folder");
- }
- } finally {
- yield stopServer();
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert_tags() {
- yield Promise.all([{
- kind: "bookmark",
- url: "https://example.com",
- syncId: makeGuid(),
- parentSyncId: "menu",
- tags: ["foo", "bar"],
- }, {
- kind: "bookmark",
- url: "https://example.org",
- syncId: makeGuid(),
- parentSyncId: "toolbar",
- tags: ["foo", "baz"],
- }, {
- kind: "query",
- url: "place:queryType=1&sort=12&maxResults=10",
- syncId: makeGuid(),
- parentSyncId: "toolbar",
- folder: "bar",
- tags: ["baz", "qux"],
- title: "bar",
- }].map(info => PlacesSyncUtils.bookmarks.insert(info)));
-
- assertTagForURLs("foo", ["https://example.com/", "https://example.org/"],
- "2 URLs with new tag");
- assertTagForURLs("bar", ["https://example.com/"], "1 URL with existing tag");
- assertTagForURLs("baz", ["https://example.org/",
- "place:queryType=1&sort=12&maxResults=10"],
- "Should support tagging URLs and tag queries");
- assertTagForURLs("qux", ["place:queryType=1&sort=12&maxResults=10"],
- "Should support tagging tag queries");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert_tags_whitespace() {
- do_print("Untrimmed and blank tags");
- let taggedBlanks = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- url: "https://example.org",
- syncId: makeGuid(),
- parentSyncId: "menu",
- tags: [" untrimmed ", " ", "taggy"],
- });
- deepEqual(taggedBlanks.tags, ["untrimmed", "taggy"],
- "Should not return empty tags");
- assertURLHasTags("https://example.org/", ["taggy", "untrimmed"],
- "Should set trimmed tags and ignore dupes");
-
- do_print("Dupe tags");
- let taggedDupes = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- url: "https://example.net",
- syncId: makeGuid(),
- parentSyncId: "toolbar",
- tags: [" taggy", "taggy ", " taggy ", "taggy"],
- });
- deepEqual(taggedDupes.tags, ["taggy", "taggy", "taggy", "taggy"],
- "Should return trimmed and dupe tags");
- assertURLHasTags("https://example.net/", ["taggy"],
- "Should ignore dupes when setting tags");
-
- assertTagForURLs("taggy", ["https://example.net/", "https://example.org/"],
- "Should exclude falsy tags");
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert_keyword() {
- do_print("Insert item with new keyword");
- {
- yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- parentSyncId: "menu",
- url: "https://example.com",
- keyword: "moz",
- syncId: makeGuid(),
- });
- let entry = yield PlacesUtils.keywords.fetch("moz");
- equal(entry.url.href, "https://example.com/",
- "Should add keyword for item");
- }
-
- do_print("Insert item with existing keyword");
- {
- yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- parentSyncId: "menu",
- url: "https://mozilla.org",
- keyword: "moz",
- syncId: makeGuid(),
- });
- let entry = yield PlacesUtils.keywords.fetch("moz");
- equal(entry.url.href, "https://mozilla.org/",
- "Should reassign keyword to new item");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert_annos() {
- do_print("Bookmark with description");
- let descBmk = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- url: "https://example.com",
- syncId: makeGuid(),
- parentSyncId: "menu",
- description: "Bookmark description",
- });
- {
- equal(descBmk.description, "Bookmark description",
- "Should return new bookmark description");
- let id = yield syncIdToId(descBmk.syncId);
- equal(PlacesUtils.annotations.getItemAnnotation(id, DESCRIPTION_ANNO),
- "Bookmark description", "Should set new bookmark description");
- }
-
- do_print("Folder with description");
- let descFolder = yield PlacesSyncUtils.bookmarks.insert({
- kind: "folder",
- syncId: makeGuid(),
- parentSyncId: "menu",
- description: "Folder description",
- });
- {
- equal(descFolder.description, "Folder description",
- "Should return new folder description");
- let id = yield syncIdToId(descFolder.syncId);
- equal(PlacesUtils.annotations.getItemAnnotation(id, DESCRIPTION_ANNO),
- "Folder description", "Should set new folder description");
- }
-
- do_print("Bookmark with sidebar anno");
- let sidebarBmk = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- url: "https://example.com",
- syncId: makeGuid(),
- parentSyncId: "menu",
- loadInSidebar: true,
- });
- {
- ok(sidebarBmk.loadInSidebar, "Should return sidebar anno for new bookmark");
- let id = yield syncIdToId(sidebarBmk.syncId);
- ok(PlacesUtils.annotations.itemHasAnnotation(id, LOAD_IN_SIDEBAR_ANNO),
- "Should set sidebar anno for new bookmark");
- }
-
- do_print("Bookmark without sidebar anno");
- let noSidebarBmk = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- url: "https://example.org",
- syncId: makeGuid(),
- parentSyncId: "toolbar",
- loadInSidebar: false,
- });
- {
- ok(!noSidebarBmk.loadInSidebar,
- "Should not return sidebar anno for new bookmark");
- let id = yield syncIdToId(noSidebarBmk.syncId);
- ok(!PlacesUtils.annotations.itemHasAnnotation(id, LOAD_IN_SIDEBAR_ANNO),
- "Should not set sidebar anno for new bookmark");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert_tag_query() {
- let tagFolder = -1;
-
- do_print("Insert tag query for new tag");
- {
- deepEqual(PlacesUtils.tagging.allTags, [], "New tag should not exist yet");
- let query = yield PlacesSyncUtils.bookmarks.insert({
- kind: "query",
- syncId: makeGuid(),
- parentSyncId: "toolbar",
- url: "place:type=7&folder=90",
- folder: "taggy",
- title: "Tagged stuff",
- });
- notEqual(query.url.href, "place:type=7&folder=90",
- "Tag query URL for new tag should differ");
-
- [, tagFolder] = /\bfolder=(\d+)\b/.exec(query.url.pathname);
- ok(tagFolder > 0, "New tag query URL should contain valid folder");
- deepEqual(PlacesUtils.tagging.allTags, ["taggy"], "New tag should exist");
- }
-
- do_print("Insert tag query for existing tag");
- {
- let url = "place:type=7&folder=90&maxResults=15";
- let query = yield PlacesSyncUtils.bookmarks.insert({
- kind: "query",
- url,
- folder: "taggy",
- title: "Sorted and tagged",
- syncId: makeGuid(),
- parentSyncId: "menu",
- });
- notEqual(query.url.href, url, "Tag query URL for existing tag should differ");
- let params = new URLSearchParams(query.url.pathname);
- equal(params.get("type"), "7", "Should preserve query type");
- equal(params.get("maxResults"), "15", "Should preserve additional params");
- equal(params.get("folder"), tagFolder, "Should update tag folder");
- deepEqual(PlacesUtils.tagging.allTags, ["taggy"], "Should not duplicate existing tags");
- }
-
- do_print("Use the public tagging API to ensure we added the tag correctly");
- {
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- type: PlacesUtils.bookmarks.TYPE_BOOKMARK,
- url: "https://mozilla.org",
- title: "Mozilla",
- });
- PlacesUtils.tagging.tagURI(uri("https://mozilla.org"), ["taggy"]);
- assertURLHasTags("https://mozilla.org/", ["taggy"],
- "Should set tags using the tagging API");
- }
-
- do_print("Removing the tag should clean up the tag folder");
- {
- PlacesUtils.tagging.untagURI(uri("https://mozilla.org"), null);
- deepEqual(PlacesUtils.tagging.allTags, [],
- "Should remove tag folder once last item is untagged");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_insert_orphans() {
- let grandParentGuid = makeGuid();
- let parentGuid = makeGuid();
- let childGuid = makeGuid();
- let childId;
-
- do_print("Insert an orphaned child");
- {
- let child = yield PlacesSyncUtils.bookmarks.insert({
- kind: "bookmark",
- parentSyncId: parentGuid,
- syncId: childGuid,
- url: "https://mozilla.org",
- });
- equal(child.syncId, childGuid,
- "Should insert orphan with requested GUID");
- equal(child.parentSyncId, "unfiled",
- "Should reparent orphan to unfiled");
-
- childId = yield PlacesUtils.promiseItemId(childGuid);
- equal(PlacesUtils.annotations.getItemAnnotation(childId, SYNC_PARENT_ANNO),
- parentGuid, "Should set anno to missing parent GUID");
- }
-
- do_print("Insert the grandparent");
- {
- yield PlacesSyncUtils.bookmarks.insert({
- kind: "folder",
- parentSyncId: "menu",
- syncId: grandParentGuid,
- });
- equal(PlacesUtils.annotations.getItemAnnotation(childId, SYNC_PARENT_ANNO),
- parentGuid, "Child should still have orphan anno");
- }
-
- // Note that only `PlacesSyncUtils` reparents orphans, though Sync adds an
- // observer that removes the orphan anno if the orphan is manually moved.
- do_print("Insert the missing parent");
- {
- let parent = yield PlacesSyncUtils.bookmarks.insert({
- kind: "folder",
- parentSyncId: grandParentGuid,
- syncId: parentGuid,
- });
- equal(parent.syncId, parentGuid, "Should insert parent with requested GUID");
- equal(parent.parentSyncId, grandParentGuid,
- "Parent should be child of grandparent");
- ok(!PlacesUtils.annotations.itemHasAnnotation(childId, SYNC_PARENT_ANNO),
- "Orphan anno should be removed after reparenting");
-
- let child = yield PlacesUtils.bookmarks.fetch({ guid: childGuid });
- equal(child.parentGuid, parentGuid,
- "Should reparent child after inserting missing parent");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_fetch() {
- let folder = yield PlacesSyncUtils.bookmarks.insert({
- syncId: makeGuid(),
- parentSyncId: "menu",
- kind: "folder",
- description: "Folder description",
- });
- let bmk = yield PlacesSyncUtils.bookmarks.insert({
- syncId: makeGuid(),
- parentSyncId: "menu",
- kind: "bookmark",
- url: "https://example.com",
- description: "Bookmark description",
- loadInSidebar: true,
- tags: ["taggy"],
- });
- let folderBmk = yield PlacesSyncUtils.bookmarks.insert({
- syncId: makeGuid(),
- parentSyncId: folder.syncId,
- kind: "bookmark",
- url: "https://example.org",
- keyword: "kw",
- });
- let folderSep = yield PlacesSyncUtils.bookmarks.insert({
- syncId: makeGuid(),
- parentSyncId: folder.syncId,
- kind: "separator",
- });
- let tagQuery = yield PlacesSyncUtils.bookmarks.insert({
- kind: "query",
- syncId: makeGuid(),
- parentSyncId: "toolbar",
- url: "place:type=7&folder=90",
- folder: "taggy",
- title: "Tagged stuff",
- });
- let [, tagFolderId] = /\bfolder=(\d+)\b/.exec(tagQuery.url.pathname);
- let smartBmk = yield PlacesSyncUtils.bookmarks.insert({
- kind: "query",
- syncId: makeGuid(),
- parentSyncId: "toolbar",
- url: "place:folder=TOOLBAR",
- query: "BookmarksToolbar",
- title: "Bookmarks toolbar query",
- });
-
- do_print("Fetch empty folder with description");
- {
- let item = yield PlacesSyncUtils.bookmarks.fetch(folder.syncId);
- deepEqual(item, {
- syncId: folder.syncId,
- kind: "folder",
- parentSyncId: "menu",
- description: "Folder description",
- childSyncIds: [folderBmk.syncId, folderSep.syncId],
- parentTitle: "Bookmarks Menu",
- title: "",
- }, "Should include description, children, title, and parent title in folder");
- }
-
- do_print("Fetch bookmark with description, sidebar anno, and tags");
- {
- let item = yield PlacesSyncUtils.bookmarks.fetch(bmk.syncId);
- deepEqual(Object.keys(item).sort(), ["syncId", "kind", "parentSyncId",
- "url", "tags", "description", "loadInSidebar", "parentTitle", "title"].sort(),
- "Should include bookmark-specific properties");
- equal(item.syncId, bmk.syncId, "Sync ID should match");
- equal(item.url.href, "https://example.com/", "Should return URL");
- equal(item.parentSyncId, "menu", "Should return parent sync ID");
- deepEqual(item.tags, ["taggy"], "Should return tags");
- equal(item.description, "Bookmark description", "Should return bookmark description");
- strictEqual(item.loadInSidebar, true, "Should return sidebar anno");
- equal(item.parentTitle, "Bookmarks Menu", "Should return parent title");
- strictEqual(item.title, "", "Should return empty title");
- }
-
- do_print("Fetch bookmark with keyword; without parent title or annos");
- {
- let item = yield PlacesSyncUtils.bookmarks.fetch(folderBmk.syncId);
- deepEqual(Object.keys(item).sort(), ["syncId", "kind", "parentSyncId",
- "url", "keyword", "tags", "loadInSidebar", "parentTitle", "title"].sort(),
- "Should omit blank bookmark-specific properties");
- strictEqual(item.loadInSidebar, false, "Should not load bookmark in sidebar");
- deepEqual(item.tags, [], "Tags should be empty");
- equal(item.keyword, "kw", "Should return keyword");
- strictEqual(item.parentTitle, "", "Should include parent title even if empty");
- strictEqual(item.title, "", "Should include bookmark title even if empty");
- }
-
- do_print("Fetch separator");
- {
- let item = yield PlacesSyncUtils.bookmarks.fetch(folderSep.syncId);
- strictEqual(item.index, 1, "Should return separator position");
- }
-
- do_print("Fetch tag query");
- {
- let item = yield PlacesSyncUtils.bookmarks.fetch(tagQuery.syncId);
- deepEqual(Object.keys(item).sort(), ["syncId", "kind", "parentSyncId",
- "url", "title", "folder", "parentTitle"].sort(),
- "Should include query-specific properties");
- equal(item.url.href, `place:type=7&folder=${tagFolderId}`, "Should not rewrite outgoing tag queries");
- equal(item.folder, "taggy", "Should return tag name for tag queries");
- }
-
- do_print("Fetch smart bookmark");
- {
- let item = yield PlacesSyncUtils.bookmarks.fetch(smartBmk.syncId);
- deepEqual(Object.keys(item).sort(), ["syncId", "kind", "parentSyncId",
- "url", "title", "query", "parentTitle"].sort(),
- "Should include smart bookmark-specific properties");
- equal(item.query, "BookmarksToolbar", "Should return query name for smart bookmarks");
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
-
-add_task(function* test_fetch_livemark() {
- let { site, stopServer } = makeLivemarkServer();
-
- try {
- do_print("Create livemark");
- let livemark = yield PlacesUtils.livemarks.addLivemark({
- parentGuid: PlacesUtils.bookmarks.menuGuid,
- feedURI: uri(site + "/feed/1"),
- siteURI: uri(site),
- index: PlacesUtils.bookmarks.DEFAULT_INDEX,
- });
- PlacesUtils.annotations.setItemAnnotation(livemark.id, DESCRIPTION_ANNO,
- "Livemark description", 0, PlacesUtils.annotations.EXPIRE_NEVER);
-
- do_print("Fetch livemark");
- let item = yield PlacesSyncUtils.bookmarks.fetch(livemark.guid);
- deepEqual(Object.keys(item).sort(), ["syncId", "kind", "parentSyncId",
- "description", "feed", "site", "parentTitle", "title"].sort(),
- "Should include livemark-specific properties");
- equal(item.description, "Livemark description", "Should return description");
- equal(item.feed.href, site + "/feed/1", "Should return feed URL");
- equal(item.site.href, site + "/", "Should return site URL");
- strictEqual(item.title, "", "Should include livemark title even if empty");
- } finally {
- yield stopServer();
- }
-
- yield PlacesUtils.bookmarks.eraseEverything();
-});
diff --git a/toolkit/components/places/tests/unit/test_tag_autocomplete_search.js b/toolkit/components/places/tests/unit/test_tag_autocomplete_search.js
deleted file mode 100644
index 92930e329..000000000
--- a/toolkit/components/places/tests/unit/test_tag_autocomplete_search.js
+++ /dev/null
@@ -1,137 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var current_test = 0;
-
-function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
-}
-AutoCompleteInput.prototype = {
- constructor: AutoCompleteInput,
-
- searches: null,
-
- minResultsForPopup: 0,
- timeout: 10,
- searchParam: "",
- textValue: "",
- disableAutoComplete: false,
- completeDefaultIndex: false,
-
- get searchCount() {
- return this.searches.length;
- },
-
- getSearchAt: function(aIndex) {
- return this.searches[aIndex];
- },
-
- onSearchBegin: function() {},
- onSearchComplete: function() {},
-
- popupOpen: false,
-
- popup: {
- setSelectedIndex: function(aIndex) {},
- invalidate: function() {},
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompletePopup))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
- },
-
- // nsISupports implementation
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIAutoCompleteInput))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-// Get tagging service
-try {
- var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
-} catch (ex) {
- do_throw("Could not get tagging service\n");
-}
-
-function ensure_tag_results(results, searchTerm)
-{
- var controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
-
- // Make an AutoCompleteInput that uses our searches
- // and confirms results on search complete
- var input = new AutoCompleteInput(["places-tag-autocomplete"]);
-
- controller.input = input;
-
- var numSearchesStarted = 0;
- input.onSearchBegin = function input_onSearchBegin() {
- numSearchesStarted++;
- do_check_eq(numSearchesStarted, 1);
- };
-
- input.onSearchComplete = function input_onSearchComplete() {
- do_check_eq(numSearchesStarted, 1);
- if (results.length)
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH);
- else
- do_check_eq(controller.searchStatus,
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
-
- do_check_eq(controller.matchCount, results.length);
- for (var i=0; i<controller.matchCount; i++) {
- do_check_eq(controller.getValueAt(i), results[i]);
- }
-
- if (current_test < (tests.length - 1)) {
- current_test++;
- tests[current_test]();
- }
- else {
- // finish once all tests have run
- do_test_finished();
- }
- };
-
- controller.startSearch(searchTerm);
-}
-
-var uri1 = uri("http://site.tld/1");
-
-var tests = [
- function test1() { ensure_tag_results(["bar", "Baz", "boo"], "b"); },
- function test2() { ensure_tag_results(["bar", "Baz"], "ba"); },
- function test3() { ensure_tag_results(["bar", "Baz"], "Ba"); },
- function test4() { ensure_tag_results(["bar"], "bar"); },
- function test5() { ensure_tag_results(["Baz"], "Baz"); },
- function test6() { ensure_tag_results([], "barb"); },
- function test7() { ensure_tag_results([], "foo"); },
- function test8() { ensure_tag_results(["first tag, bar", "first tag, Baz"], "first tag, ba"); },
- function test9() { ensure_tag_results(["first tag; bar", "first tag; Baz"], "first tag; ba"); }
-];
-
-/**
- * Test tag autocomplete
- */
-function run_test() {
- // Search is asynchronous, so don't let the test finish immediately
- do_test_pending();
-
- tagssvc.tagURI(uri1, ["bar", "Baz", "boo", "*nix"]);
-
- tests[0]();
-}
diff --git a/toolkit/components/places/tests/unit/test_tagging.js b/toolkit/components/places/tests/unit/test_tagging.js
deleted file mode 100644
index ccb287050..000000000
--- a/toolkit/components/places/tests/unit/test_tagging.js
+++ /dev/null
@@ -1,189 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Notice we use createInstance because later we will have to terminate the
-// service and restart it.
-var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- createInstance().QueryInterface(Ci.nsITaggingService);
-
-function run_test() {
- var options = PlacesUtils.history.getNewQueryOptions();
- var query = PlacesUtils.history.getNewQuery();
-
- query.setFolders([PlacesUtils.tagsFolderId], 1);
- var result = PlacesUtils.history.executeQuery(query, options);
- var tagRoot = result.root;
- tagRoot.containerOpen = true;
-
- do_check_eq(tagRoot.childCount, 0);
-
- var uri1 = uri("http://foo.tld/");
- var uri2 = uri("https://bar.tld/");
-
- // this also tests that the multiple folders are not created for the same tag
- tagssvc.tagURI(uri1, ["tag 1"]);
- tagssvc.tagURI(uri2, ["tag 1"]);
- do_check_eq(tagRoot.childCount, 1);
-
- var tag1node = tagRoot.getChild(0)
- .QueryInterface(Ci.nsINavHistoryContainerResultNode);
- var tag1itemId = tag1node.itemId;
-
- do_check_eq(tag1node.title, "tag 1");
- tag1node.containerOpen = true;
- do_check_eq(tag1node.childCount, 2);
-
- // Tagging the same url twice (or even thrice!) with the same tag should be a
- // no-op
- tagssvc.tagURI(uri1, ["tag 1"]);
- do_check_eq(tag1node.childCount, 2);
- tagssvc.tagURI(uri1, [tag1itemId]);
- do_check_eq(tag1node.childCount, 2);
- do_check_eq(tagRoot.childCount, 1);
-
- // also tests bug 407575
- tagssvc.tagURI(uri1, [tag1itemId, "tag 1", "tag 2", "Tag 1", "Tag 2"]);
- do_check_eq(tagRoot.childCount, 2);
- do_check_eq(tag1node.childCount, 2);
-
- // test getTagsForURI
- var uri1tags = tagssvc.getTagsForURI(uri1);
- do_check_eq(uri1tags.length, 2);
- do_check_eq(uri1tags[0], "Tag 1");
- do_check_eq(uri1tags[1], "Tag 2");
- var uri2tags = tagssvc.getTagsForURI(uri2);
- do_check_eq(uri2tags.length, 1);
- do_check_eq(uri2tags[0], "Tag 1");
-
- // test getURIsForTag
- var tag1uris = tagssvc.getURIsForTag("tag 1");
- do_check_eq(tag1uris.length, 2);
- do_check_true(tag1uris[0].equals(uri1));
- do_check_true(tag1uris[1].equals(uri2));
-
- // test allTags attribute
- var allTags = tagssvc.allTags;
- do_check_eq(allTags.length, 2);
- do_check_eq(allTags[0], "Tag 1");
- do_check_eq(allTags[1], "Tag 2");
-
- // test untagging
- tagssvc.untagURI(uri1, ["tag 1"]);
- do_check_eq(tag1node.childCount, 1);
-
- // removing the last uri from a tag should remove the tag-container
- tagssvc.untagURI(uri2, ["tag 1"]);
- do_check_eq(tagRoot.childCount, 1);
-
- // cleanup
- tag1node.containerOpen = false;
-
- // get array of tag folder ids => title
- // for testing tagging with mixed folder ids and tags
- var child = tagRoot.getChild(0);
- var tagId = child.itemId;
- var tagTitle = child.title;
-
- // test mixed id/name tagging
- // as well as non-id numeric tags
- var uri3 = uri("http://testuri/3");
- tagssvc.tagURI(uri3, [tagId, "tag 3", "456"]);
- var tags = tagssvc.getTagsForURI(uri3);
- do_check_true(tags.includes(tagTitle));
- do_check_true(tags.includes("tag 3"));
- do_check_true(tags.includes("456"));
-
- // test mixed id/name tagging
- tagssvc.untagURI(uri3, [tagId, "tag 3", "456"]);
- tags = tagssvc.getTagsForURI(uri3);
- do_check_eq(tags.length, 0);
-
- // Terminate tagging service, fire up a new instance and check that existing
- // tags are there. This will ensure that any internal caching system is
- // correctly filled at startup and we are not losing previously existing tags.
- var uri4 = uri("http://testuri/4");
- tagssvc.tagURI(uri4, [tagId, "tag 3", "456"]);
- tagssvc = null;
- tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
- getService(Ci.nsITaggingService);
- var uri4Tags = tagssvc.getTagsForURI(uri4);
- do_check_eq(uri4Tags.length, 3);
- do_check_true(uri4Tags.includes(tagTitle));
- do_check_true(uri4Tags.includes("tag 3"));
- do_check_true(uri4Tags.includes("456"));
-
- // Test sparse arrays.
- let curChildCount = tagRoot.childCount;
-
- try {
- tagssvc.tagURI(uri1, [, "tagSparse"]);
- do_check_eq(tagRoot.childCount, curChildCount + 1);
- } catch (ex) {
- do_throw("Passing a sparse array should not throw");
- }
- try {
- tagssvc.untagURI(uri1, [, "tagSparse"]);
- do_check_eq(tagRoot.childCount, curChildCount);
- } catch (ex) {
- do_throw("Passing a sparse array should not throw");
- }
-
- // Test that the API throws for bad arguments.
- try {
- tagssvc.tagURI(uri1, ["", "test"]);
- do_throw("Passing a bad tags array should throw");
- } catch (ex) {
- do_check_eq(ex.name, "NS_ERROR_ILLEGAL_VALUE");
- }
- try {
- tagssvc.untagURI(uri1, ["", "test"]);
- do_throw("Passing a bad tags array should throw");
- } catch (ex) {
- do_check_eq(ex.name, "NS_ERROR_ILLEGAL_VALUE");
- }
- try {
- tagssvc.tagURI(uri1, [0, "test"]);
- do_throw("Passing a bad tags array should throw");
- } catch (ex) {
- do_check_eq(ex.name, "NS_ERROR_ILLEGAL_VALUE");
- }
- try {
- tagssvc.tagURI(uri1, [0, "test"]);
- do_throw("Passing a bad tags array should throw");
- } catch (ex) {
- do_check_eq(ex.name, "NS_ERROR_ILLEGAL_VALUE");
- }
-
- // Tag name length should be limited to nsITaggingService.MAX_TAG_LENGTH (bug407821)
- try {
-
- // generate a long tag name. i.e. looooo...oong_tag
- var n = Ci.nsITaggingService.MAX_TAG_LENGTH;
- var someOos = new Array(n).join('o');
- var longTagName = "l" + someOos + "ng_tag";
-
- tagssvc.tagURI(uri1, ["short_tag", longTagName]);
- do_throw("Passing a bad tags array should throw");
-
- } catch (ex) {
- do_check_eq(ex.name, "NS_ERROR_ILLEGAL_VALUE");
- }
-
- // cleanup
- tagRoot.containerOpen = false;
-
- // Tagging service should trim tags (Bug967196)
- let exampleURI = uri("http://www.example.com/");
- PlacesUtils.tagging.tagURI(exampleURI, [ " test " ]);
-
- let exampleTags = PlacesUtils.tagging.getTagsForURI(exampleURI);
- do_check_eq(exampleTags.length, 1);
- do_check_eq(exampleTags[0], "test");
-
- PlacesUtils.tagging.untagURI(exampleURI, [ "test" ]);
- exampleTags = PlacesUtils.tagging.getTagsForURI(exampleURI);
- do_check_eq(exampleTags.length, 0);
-}
diff --git a/toolkit/components/places/tests/unit/test_telemetry.js b/toolkit/components/places/tests/unit/test_telemetry.js
deleted file mode 100644
index 99f36d78c..000000000
--- a/toolkit/components/places/tests/unit/test_telemetry.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Tests common Places telemetry probes by faking the telemetry service.
-
-Components.utils.import("resource://gre/modules/PlacesDBUtils.jsm");
-
-var histograms = {
- PLACES_PAGES_COUNT: val => do_check_eq(val, 1),
- PLACES_BOOKMARKS_COUNT: val => do_check_eq(val, 1),
- PLACES_TAGS_COUNT: val => do_check_eq(val, 1),
- PLACES_KEYWORDS_COUNT: val => do_check_eq(val, 1),
- PLACES_SORTED_BOOKMARKS_PERC: val => do_check_eq(val, 100),
- PLACES_TAGGED_BOOKMARKS_PERC: val => do_check_eq(val, 100),
- PLACES_DATABASE_FILESIZE_MB: val => do_check_true(val > 0),
- PLACES_DATABASE_PAGESIZE_B: val => do_check_eq(val, 32768),
- PLACES_DATABASE_SIZE_PER_PAGE_B: val => do_check_true(val > 0),
- PLACES_EXPIRATION_STEPS_TO_CLEAN2: val => do_check_true(val > 1),
- // PLACES_AUTOCOMPLETE_1ST_RESULT_TIME_MS: val => do_check_true(val > 1),
- PLACES_IDLE_FRECENCY_DECAY_TIME_MS: val => do_check_true(val >= 0),
- PLACES_IDLE_MAINTENANCE_TIME_MS: val => do_check_true(val > 0),
- // One from the `setItemAnnotation` call; the other from the mobile root.
- // This can be removed along with the anno in bug 1306445.
- PLACES_ANNOS_BOOKMARKS_COUNT: val => do_check_eq(val, 2),
- PLACES_ANNOS_PAGES_COUNT: val => do_check_eq(val, 1),
- PLACES_MAINTENANCE_DAYSFROMLAST: val => do_check_true(val >= 0),
-}
-
-/**
- * Forces an expiration run.
- *
- * @param [optional] aLimit
- * Limit for the expiration. Pass -1 for unlimited.
- * Any other non-positive value will just expire orphans.
- *
- * @return {Promise}
- * @resolves When expiration finishes.
- * @rejects Never.
- */
-function promiseForceExpirationStep(aLimit) {
- let promise = promiseTopicObserved(PlacesUtils.TOPIC_EXPIRATION_FINISHED);
- let expire = Cc["@mozilla.org/places/expiration;1"].getService(Ci.nsIObserver);
- expire.observe(null, "places-debug-start-expiration", aLimit);
- return promise;
-}
-
-/**
- * Returns a PRTime in the past usable to add expirable visits.
- *
- * param [optional] daysAgo
- * Expiration ignores any visit added in the last 7 days, so by default
- * this will be set to 7.
- * @note to be safe against DST issues we go back one day more.
- */
-function getExpirablePRTime(daysAgo = 7) {
- let dateObj = new Date();
- // Normalize to midnight
- dateObj.setHours(0);
- dateObj.setMinutes(0);
- dateObj.setSeconds(0);
- dateObj.setMilliseconds(0);
- dateObj = new Date(dateObj.getTime() - (daysAgo + 1) * 86400000);
- return dateObj.getTime() * 1000;
-}
-
-add_task(function* test_execute()
-{
- // Put some trash in the database.
- let uri = NetUtil.newURI("http://moz.org/");
-
- let folderId = PlacesUtils.bookmarks.createFolder(PlacesUtils.unfiledBookmarksFolderId,
- "moz test",
- PlacesUtils.bookmarks.DEFAULT_INDEX);
- let itemId = PlacesUtils.bookmarks.insertBookmark(folderId,
- uri,
- PlacesUtils.bookmarks.DEFAULT_INDEX,
- "moz test");
- PlacesUtils.tagging.tagURI(uri, ["tag"]);
- yield PlacesUtils.keywords.insert({ url: uri.spec, keyword: "keyword"});
-
- // Set a large annotation.
- let content = "";
- while (content.length < 1024) {
- content += "0";
- }
- PlacesUtils.annotations.setItemAnnotation(itemId, "test-anno", content, 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
- PlacesUtils.annotations.setPageAnnotation(uri, "test-anno", content, 0,
- PlacesUtils.annotations.EXPIRE_NEVER);
-
- // Request to gather telemetry data.
- Cc["@mozilla.org/places/categoriesStarter;1"]
- .getService(Ci.nsIObserver)
- .observe(null, "gather-telemetry", null);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
-
- // Test expiration probes.
- let timeInMicroseconds = getExpirablePRTime(8);
-
- function newTimeInMicroseconds() {
- timeInMicroseconds = timeInMicroseconds + 1000;
- return timeInMicroseconds;
- }
-
- for (let i = 0; i < 3; i++) {
- yield PlacesTestUtils.addVisits({
- uri: NetUtil.newURI("http://" + i + ".moz.org/"),
- visitDate: newTimeInMicroseconds()
- });
- }
- Services.prefs.setIntPref("places.history.expiration.max_pages", 0);
- yield promiseForceExpirationStep(2);
- yield promiseForceExpirationStep(2);
-
- // Test autocomplete probes.
- /*
- // This is useful for manual testing by changing the minimum time for
- // autocomplete telemetry to 0, but there is no way to artificially delay
- // autocomplete by more than 50ms in a realiable way.
- Services.prefs.setIntPref("browser.urlbar.search.sources", 3);
- Services.prefs.setIntPref("browser.urlbar.default.behavior", 0);
- function AutoCompleteInput(aSearches) {
- this.searches = aSearches;
- }
- AutoCompleteInput.prototype = {
- timeout: 10,
- textValue: "",
- searchParam: "",
- popupOpen: false,
- minResultsForPopup: 0,
- invalidate: function() {},
- disableAutoComplete: false,
- completeDefaultIndex: false,
- get popup() { return this; },
- onSearchBegin: function() {},
- onSearchComplete: function() {},
- setSelectedIndex: function() {},
- get searchCount() { return this.searches.length; },
- getSearchAt: function(aIndex) { return this.searches[aIndex]; },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIAutoCompleteInput,
- Ci.nsIAutoCompletePopup,
- ])
- };
- let controller = Cc["@mozilla.org/autocomplete/controller;1"].
- getService(Ci.nsIAutoCompleteController);
- controller.input = new AutoCompleteInput(["unifiedcomplete"]);
- controller.startSearch("moz");
- */
-
- // Test idle probes.
- PlacesUtils.history.QueryInterface(Ci.nsIObserver)
- .observe(null, "idle-daily", null);
- PlacesDBUtils.maintenanceOnIdle();
-
- yield promiseTopicObserved("places-maintenance-finished");
-
- for (let histogramId in histograms) {
- do_print("checking histogram " + histogramId);
- let validate = histograms[histogramId];
- let snapshot = Services.telemetry.getHistogramById(histogramId).snapshot();
- validate(snapshot.sum);
- do_check_true(snapshot.counts.reduce((a, b) => a + b) > 0);
- }
-});
diff --git a/toolkit/components/places/tests/unit/test_update_frecency_after_delete.js b/toolkit/components/places/tests/unit/test_update_frecency_after_delete.js
deleted file mode 100644
index 662ea0841..000000000
--- a/toolkit/components/places/tests/unit/test_update_frecency_after_delete.js
+++ /dev/null
@@ -1,151 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Bug 455315
- * https://bugzilla.mozilla.org/show_bug.cgi?id=412132
- *
- * Ensures that the frecency of a bookmark's URI is what it should be after the
- * bookmark is deleted.
- */
-
-add_task(function* removed_bookmark() {
- do_print("After removing bookmark, frecency of bookmark's URI should be " +
- "zero if URI is unvisited and no longer bookmarked.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "bookmark title",
- url: TEST_URI
- });
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.remove(bm);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("Unvisited URI no longer bookmarked => frecency should = 0");
- do_check_eq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* removed_but_visited_bookmark() {
- do_print("After removing bookmark, frecency of bookmark's URI should " +
- "not be zero if URI is visited.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- let bm = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "bookmark title",
- url: TEST_URI
- });
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesTestUtils.addVisits(TEST_URI);
- yield PlacesUtils.bookmarks.remove(bm);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("*Visited* URI no longer bookmarked => frecency should != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* remove_bookmark_still_bookmarked() {
- do_print("After removing bookmark, frecency of bookmark's URI should " +
- "not be zero if URI is still bookmarked.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- let bm1 = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "bookmark 1 title",
- url: TEST_URI
- });
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "bookmark 2 title",
- url: TEST_URI
- });
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.remove(bm1);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("URI still bookmarked => frecency should != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* cleared_parent_of_visited_bookmark() {
- do_print("After removing all children from bookmark's parent, frecency " +
- "of bookmark's URI should not be zero if URI is visited.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- title: "bookmark title",
- url: TEST_URI
- });
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesTestUtils.addVisits(TEST_URI);
- PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("*Visited* URI no longer bookmarked => frecency should != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
-
-add_task(function* cleared_parent_of_bookmark_still_bookmarked() {
- do_print("After removing all children from bookmark's parent, frecency " +
- "of bookmark's URI should not be zero if URI is still " +
- "bookmarked.");
- const TEST_URI = NetUtil.newURI("http://example.com/1");
- yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.toolbarGuid,
- title: "bookmark 1 title",
- url: TEST_URI
- });
-
- let folder = yield PlacesUtils.bookmarks.insert({
- parentGuid: PlacesUtils.bookmarks.unfiledGuid,
- type: PlacesUtils.bookmarks.TYPE_FOLDER,
- title: "bookmark 2 folder"
- });
- yield PlacesUtils.bookmarks.insert({
- title: "bookmark 2 title",
- parentGuid: folder.guid,
- url: TEST_URI
- });
-
- yield PlacesTestUtils.promiseAsyncUpdates();
- do_print("Bookmarked => frecency of URI should be != 0");
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.remove(folder);
- yield PlacesTestUtils.promiseAsyncUpdates();
- // URI still bookmarked => frecency should != 0.
- do_check_neq(frecencyForUrl(TEST_URI), 0);
-
- yield PlacesUtils.bookmarks.eraseEverything();
- yield PlacesTestUtils.clearHistory();
-});
diff --git a/toolkit/components/places/tests/unit/test_utils_backups_create.js b/toolkit/components/places/tests/unit/test_utils_backups_create.js
deleted file mode 100644
index a30589c44..000000000
--- a/toolkit/components/places/tests/unit/test_utils_backups_create.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Check for correct functionality of bookmarks backups
- */
-
-const NUMBER_OF_BACKUPS = 10;
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function* () {
- // Generate random dates.
- let dateObj = new Date();
- let dates = [];
- while (dates.length < NUMBER_OF_BACKUPS) {
- // Use last year to ensure today's backup is the newest.
- let randomDate = new Date(dateObj.getFullYear() - 1,
- Math.floor(12 * Math.random()),
- Math.floor(28 * Math.random()));
- if (!dates.includes(randomDate.getTime()))
- dates.push(randomDate.getTime());
- }
- // Sort dates from oldest to newest.
- dates.sort();
-
- // Get and cleanup the backups folder.
- let backupFolderPath = yield PlacesBackups.getBackupFolder();
- let bookmarksBackupDir = new FileUtils.File(backupFolderPath);
-
- // Fake backups are created backwards to ensure we won't consider file
- // creation time.
- // Create fake backups for the newest dates.
- for (let i = dates.length - 1; i >= 0; i--) {
- let backupFilename = PlacesBackups.getFilenameForDate(new Date(dates[i]));
- let backupFile = bookmarksBackupDir.clone();
- backupFile.append(backupFilename);
- backupFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, parseInt("0666", 8));
- do_print("Creating fake backup " + backupFile.leafName);
- if (!backupFile.exists())
- do_throw("Unable to create fake backup " + backupFile.leafName);
- }
-
- yield PlacesBackups.create(NUMBER_OF_BACKUPS);
- // Add today's backup.
- dates.push(dateObj.getTime());
-
- // Check backups. We have 11 dates but we the max number is 10 so the
- // oldest backup should have been removed.
- for (let i = 0; i < dates.length; i++) {
- let backupFilename;
- let shouldExist;
- let backupFile;
- if (i > 0) {
- let files = bookmarksBackupDir.directoryEntries;
- while (files.hasMoreElements()) {
- let entry = files.getNext().QueryInterface(Ci.nsIFile);
- if (PlacesBackups.filenamesRegex.test(entry.leafName)) {
- backupFilename = entry.leafName;
- backupFile = entry;
- break;
- }
- }
- shouldExist = true;
- }
- else {
- backupFilename = PlacesBackups.getFilenameForDate(new Date(dates[i]));
- backupFile = bookmarksBackupDir.clone();
- backupFile.append(backupFilename);
- shouldExist = false;
- }
- if (backupFile.exists() != shouldExist)
- do_throw("Backup should " + (shouldExist ? "" : "not") + " exist: " + backupFilename);
- }
-
- // Cleanup backups folder.
- // XXX: Can't use bookmarksBackupDir.remove(true) because file lock happens
- // on WIN XP.
- let files = bookmarksBackupDir.directoryEntries;
- while (files.hasMoreElements()) {
- let entry = files.getNext().QueryInterface(Ci.nsIFile);
- entry.remove(false);
- }
- do_check_false(bookmarksBackupDir.directoryEntries.hasMoreElements());
-});
diff --git a/toolkit/components/places/tests/unit/test_utils_getURLsForContainerNode.js b/toolkit/components/places/tests/unit/test_utils_getURLsForContainerNode.js
deleted file mode 100644
index 3e2f88c21..000000000
--- a/toolkit/components/places/tests/unit/test_utils_getURLsForContainerNode.js
+++ /dev/null
@@ -1,181 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Check for correct functionality of PlacesUtils.getURLsForContainerNode and
- * PlacesUtils.hasChildURIs (those helpers share almost all of their code)
- */
-
-var PU = PlacesUtils;
-var hs = PU.history;
-var bs = PU.bookmarks;
-
-var tests = [
-
-function() {
- dump("\n\n*** TEST: folder\n");
- // This is the folder we will check for children.
- var folderId = bs.createFolder(bs.toolbarFolder, "folder", bs.DEFAULT_INDEX);
-
- // Create a folder and a query node inside it, these should not be considered
- // uri nodes.
- bs.createFolder(folderId, "inside folder", bs.DEFAULT_INDEX);
- bs.insertBookmark(folderId, uri("place:sort=1"),
- bs.DEFAULT_INDEX, "inside query");
-
- var query = hs.getNewQuery();
- query.setFolders([bs.toolbarFolder], 1);
- var options = hs.getNewQueryOptions();
-
- dump("Check folder without uri nodes\n");
- check_uri_nodes(query, options, 0);
-
- dump("Check folder with uri nodes\n");
- // Add an uri node, this should be considered.
- bs.insertBookmark(folderId, uri("http://www.mozilla.org/"),
- bs.DEFAULT_INDEX, "bookmark");
- check_uri_nodes(query, options, 1);
-},
-
-function() {
- dump("\n\n*** TEST: folder in an excludeItems root\n");
- // This is the folder we will check for children.
- var folderId = bs.createFolder(bs.toolbarFolder, "folder", bs.DEFAULT_INDEX);
-
- // Create a folder and a query node inside it, these should not be considered
- // uri nodes.
- bs.createFolder(folderId, "inside folder", bs.DEFAULT_INDEX);
- bs.insertBookmark(folderId, uri("place:sort=1"), bs.DEFAULT_INDEX, "inside query");
-
- var query = hs.getNewQuery();
- query.setFolders([bs.toolbarFolder], 1);
- var options = hs.getNewQueryOptions();
- options.excludeItems = true;
-
- dump("Check folder without uri nodes\n");
- check_uri_nodes(query, options, 0);
-
- dump("Check folder with uri nodes\n");
- // Add an uri node, this should be considered.
- bs.insertBookmark(folderId, uri("http://www.mozilla.org/"),
- bs.DEFAULT_INDEX, "bookmark");
- check_uri_nodes(query, options, 1);
-},
-
-function() {
- dump("\n\n*** TEST: query\n");
- // This is the query we will check for children.
- bs.insertBookmark(bs.toolbarFolder, uri("place:folder=BOOKMARKS_MENU&sort=1"),
- bs.DEFAULT_INDEX, "inside query");
-
- // Create a folder and a query node inside it, these should not be considered
- // uri nodes.
- bs.createFolder(bs.bookmarksMenuFolder, "inside folder", bs.DEFAULT_INDEX);
- bs.insertBookmark(bs.bookmarksMenuFolder, uri("place:sort=1"),
- bs.DEFAULT_INDEX, "inside query");
-
- var query = hs.getNewQuery();
- query.setFolders([bs.toolbarFolder], 1);
- var options = hs.getNewQueryOptions();
-
- dump("Check query without uri nodes\n");
- check_uri_nodes(query, options, 0);
-
- dump("Check query with uri nodes\n");
- // Add an uri node, this should be considered.
- bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://www.mozilla.org/"),
- bs.DEFAULT_INDEX, "bookmark");
- check_uri_nodes(query, options, 1);
-},
-
-function() {
- dump("\n\n*** TEST: excludeItems Query\n");
- // This is the query we will check for children.
- bs.insertBookmark(bs.toolbarFolder, uri("place:folder=BOOKMARKS_MENU&sort=8"),
- bs.DEFAULT_INDEX, "inside query");
-
- // Create a folder and a query node inside it, these should not be considered
- // uri nodes.
- bs.createFolder(bs.bookmarksMenuFolder, "inside folder", bs.DEFAULT_INDEX);
- bs.insertBookmark(bs.bookmarksMenuFolder, uri("place:sort=1"),
- bs.DEFAULT_INDEX, "inside query");
-
- var query = hs.getNewQuery();
- query.setFolders([bs.toolbarFolder], 1);
- var options = hs.getNewQueryOptions();
- options.excludeItems = true;
-
- dump("Check folder without uri nodes\n");
- check_uri_nodes(query, options, 0);
-
- dump("Check folder with uri nodes\n");
- // Add an uri node, this should be considered.
- bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://www.mozilla.org/"),
- bs.DEFAULT_INDEX, "bookmark");
- check_uri_nodes(query, options, 1);
-},
-
-function() {
- dump("\n\n*** TEST: !expandQueries Query\n");
- // This is the query we will check for children.
- bs.insertBookmark(bs.toolbarFolder, uri("place:folder=BOOKMARKS_MENU&sort=8"),
- bs.DEFAULT_INDEX, "inside query");
-
- // Create a folder and a query node inside it, these should not be considered
- // uri nodes.
- bs.createFolder(bs.bookmarksMenuFolder, "inside folder", bs.DEFAULT_INDEX);
- bs.insertBookmark(bs.bookmarksMenuFolder, uri("place:sort=1"),
- bs.DEFAULT_INDEX, "inside query");
-
- var query = hs.getNewQuery();
- query.setFolders([bs.toolbarFolder], 1);
- var options = hs.getNewQueryOptions();
- options.expandQueries = false;
-
- dump("Check folder without uri nodes\n");
- check_uri_nodes(query, options, 0);
-
- dump("Check folder with uri nodes\n");
- // Add an uri node, this should be considered.
- bs.insertBookmark(bs.bookmarksMenuFolder, uri("http://www.mozilla.org/"),
- bs.DEFAULT_INDEX, "bookmark");
- check_uri_nodes(query, options, 1);
-}
-
-];
-
-/**
- * Executes a query and checks number of uri nodes in the first container in
- * query's results. To correctly test a container ensure that the query will
- * return only your container in the first level.
- *
- * @param aQuery
- * nsINavHistoryQuery object defining the query
- * @param aOptions
- * nsINavHistoryQueryOptions object defining the query's options
- * @param aExpectedURINodes
- * number of expected uri nodes
- */
-function check_uri_nodes(aQuery, aOptions, aExpectedURINodes) {
- var result = hs.executeQuery(aQuery, aOptions);
- var root = result.root;
- root.containerOpen = true;
- var node = root.getChild(0);
- do_check_eq(PU.hasChildURIs(node), aExpectedURINodes > 0);
- do_check_eq(PU.hasChildURIs(node, true), aExpectedURINodes > 1);
- do_check_eq(PU.getURLsForContainerNode(node).length, aExpectedURINodes);
- root.containerOpen = false;
-}
-
-add_task(function* () {
- for (let test of tests) {
- yield PlacesUtils.bookmarks.eraseEverything();
- test();
- }
-
- // Cleanup.
- yield PlacesUtils.bookmarks.eraseEverything();
-});
diff --git a/toolkit/components/places/tests/unit/test_utils_setAnnotationsFor.js b/toolkit/components/places/tests/unit/test_utils_setAnnotationsFor.js
deleted file mode 100644
index 62947620d..000000000
--- a/toolkit/components/places/tests/unit/test_utils_setAnnotationsFor.js
+++ /dev/null
@@ -1,79 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
- /**
- * Check for correct functionality of PlacesUtils.setAnnotationsForItem/URI
- */
-
-var hs = PlacesUtils.history;
-var bs = PlacesUtils.bookmarks;
-var as = PlacesUtils.annotations;
-
-const TEST_URL = "http://test.mozilla.org/";
-
-function run_test() {
- var testURI = uri(TEST_URL);
- // add a bookmark
- var itemId = bs.insertBookmark(bs.unfiledBookmarksFolder, testURI,
- bs.DEFAULT_INDEX, "test");
-
- // create annotations array
- var testAnnos = [{ name: "testAnno/test0",
- flags: 0,
- value: "test0",
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER },
- { name: "testAnno/test1",
- flags: 0,
- value: "test1",
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER },
- { name: "testAnno/test2",
- flags: 0,
- value: "test2",
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER },
- { name: "testAnno/test3",
- flags: 0,
- value: 0,
- expires: Ci.nsIAnnotationService.EXPIRE_NEVER }];
-
- // Add item annotations
- PlacesUtils.setAnnotationsForItem(itemId, testAnnos);
- // Check for correct addition
- testAnnos.forEach(function(anno) {
- do_check_true(as.itemHasAnnotation(itemId, anno.name));
- do_check_eq(as.getItemAnnotation(itemId, anno.name), anno.value);
- });
-
- // Add page annotations
- PlacesUtils.setAnnotationsForURI(testURI, testAnnos);
- // Check for correct addition
- testAnnos.forEach(function(anno) {
- do_check_true(as.pageHasAnnotation(testURI, anno.name));
- do_check_eq(as.getPageAnnotation(testURI, anno.name), anno.value);
- });
-
- // To unset annotations we unset their values or set them to
- // null/undefined
- testAnnos[0].value = null;
- testAnnos[1].value = undefined;
- delete testAnnos[2].value;
- delete testAnnos[3].value;
-
- // Unset all item annotations
- PlacesUtils.setAnnotationsForItem(itemId, testAnnos);
- // Check for correct removal
- testAnnos.forEach(function(anno) {
- do_check_false(as.itemHasAnnotation(itemId, anno.name));
- // sanity: page annotations should not be removed here
- do_check_true(as.pageHasAnnotation(testURI, anno.name));
- });
-
- // Unset all page annotations
- PlacesUtils.setAnnotationsForURI(testURI, testAnnos);
- // Check for correct removal
- testAnnos.forEach(function(anno) {
- do_check_false(as.pageHasAnnotation(testURI, anno.name));
- });
-}
diff --git a/toolkit/components/places/tests/unit/test_visitsInDB.js b/toolkit/components/places/tests/unit/test_visitsInDB.js
deleted file mode 100644
index 3cab39ed9..000000000
--- a/toolkit/components/places/tests/unit/test_visitsInDB.js
+++ /dev/null
@@ -1,12 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-
-add_task(function* test_execute() {
- const TEST_URI = uri("http://mozilla.com");
-
- do_check_eq(0, yield PlacesTestUtils.visitsInDB(TEST_URI));
- yield PlacesTestUtils.addVisits({uri: TEST_URI});
- do_check_eq(1, yield PlacesTestUtils.visitsInDB(TEST_URI));
- yield PlacesTestUtils.addVisits({uri: TEST_URI});
- do_check_eq(2, yield PlacesTestUtils.visitsInDB(TEST_URI));
-});
diff --git a/toolkit/components/places/tests/unit/xpcshell.ini b/toolkit/components/places/tests/unit/xpcshell.ini
deleted file mode 100644
index 60bba4758..000000000
--- a/toolkit/components/places/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,163 +0,0 @@
-[DEFAULT]
-head = head_bookmarks.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-support-files =
- bookmarks.corrupt.html
- bookmarks.json
- bookmarks.preplaces.html
- bookmarks_html_singleframe.html
- bug476292.sqlite
- corruptDB.sqlite
- default.sqlite
- livemark.xml
- mobile_bookmarks_folder_import.json
- mobile_bookmarks_folder_merge.json
- mobile_bookmarks_multiple_folders.json
- mobile_bookmarks_root_import.json
- mobile_bookmarks_root_merge.json
- nsDummyObserver.js
- nsDummyObserver.manifest
- places.sparse.sqlite
-
-[test_000_frecency.js]
-[test_317472.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_331487.js]
-[test_384370.js]
-[test_385397.js]
-# Bug 676989: test fails consistently on Android
-fail-if = os == "android"
-[test_399264_query_to_string.js]
-[test_399264_string_to_query.js]
-[test_399266.js]
-# Bug 676989: test fails consistently on Android
-fail-if = os == "android"
-# Bug 821781: test fails intermittently on Linux
-skip-if = os == "linux"
-[test_402799.js]
-[test_405497.js]
-[test_408221.js]
-[test_412132.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_413784.js]
-[test_415460.js]
-[test_415757.js]
-[test_418643_removeFolderChildren.js]
-[test_419731.js]
-[test_419792_node_tags_property.js]
-[test_425563.js]
-[test_429505_remove_shortcuts.js]
-[test_433317_query_title_update.js]
-[test_433525_hasChildren_crash.js]
-[test_452777.js]
-[test_454977.js]
-[test_463863.js]
-[test_485442_crash_bug_nsNavHistoryQuery_GetUri.js]
-[test_486978_sort_by_date_queries.js]
-[test_536081.js]
-[test_1085291.js]
-[test_1105208.js]
-[test_1105866.js]
-[test_adaptive.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_adaptive_bug527311.js]
-[test_analyze.js]
-[test_annotations.js]
-[test_asyncExecuteLegacyQueries.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_async_history_api.js]
-[test_async_in_batchmode.js]
-[test_async_transactions.js]
-skip-if = (os == "win" && os_version == "5.1") # Bug 1158887
-[test_autocomplete_stopSearch_no_throw.js]
-[test_bookmark_catobs.js]
-[test_bookmarks_json.js]
-[test_bookmarks_html.js]
-[test_bookmarks_html_corrupt.js]
-[test_bookmarks_html_import_tags.js]
-[test_bookmarks_html_singleframe.js]
-[test_bookmarks_restore_notification.js]
-[test_bookmarks_setNullTitle.js]
-[test_broken_folderShortcut_result.js]
-[test_browserhistory.js]
-[test_bug636917_isLivemark.js]
-[test_childlessTags.js]
-[test_corrupt_telemetry.js]
-[test_crash_476292.js]
-[test_database_replaceOnStartup.js]
-[test_download_history.js]
-# Bug 676989: test fails consistently on Android
-fail-if = os == "android"
-[test_frecency.js]
-[test_frecency_zero_updated.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_getChildIndex.js]
-[test_getPlacesInfo.js]
-[test_history.js]
-[test_history_autocomplete_tags.js]
-[test_history_catobs.js]
-[test_history_clear.js]
-[test_history_notifications.js]
-[test_history_observer.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_history_sidebar.js]
-[test_hosts_triggers.js]
-[test_import_mobile_bookmarks.js]
-[test_isPageInDB.js]
-[test_isURIVisited.js]
-[test_isvisited.js]
-[test_keywords.js]
-[test_lastModified.js]
-[test_markpageas.js]
-[test_mozIAsyncLivemarks.js]
-[test_multi_queries.js]
-# Bug 676989: test fails consistently on Android
-fail-if = os == "android"
-[test_multi_word_tags.js]
-[test_nsINavHistoryViewer.js]
-# Bug 902248: intermittent timeouts on all platforms
-skip-if = true
-[test_null_interfaces.js]
-[test_onItemChanged_tags.js]
-[test_pageGuid_bookmarkGuid.js]
-[test_frecency_observers.js]
-[test_placeURIs.js]
-[test_PlacesSearchAutocompleteProvider.js]
-[test_PlacesUtils_asyncGetBookmarkIds.js]
-[test_PlacesUtils_invalidateCachedGuidFor.js]
-[test_PlacesUtils_lazyobservers.js]
-[test_placesTxn.js]
-[test_preventive_maintenance.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_preventive_maintenance_checkAndFixDatabase.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_preventive_maintenance_runTasks.js]
-[test_promiseBookmarksTree.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_resolveNullBookmarkTitles.js]
-[test_result_sort.js]
-[test_resultsAsVisit_details.js]
-[test_sql_guid_functions.js]
-[test_svg_favicon.js]
-[test_sync_utils.js]
-[test_tag_autocomplete_search.js]
-[test_tagging.js]
-[test_telemetry.js]
-[test_update_frecency_after_delete.js]
-# Bug 676989: test hangs consistently on Android
-skip-if = os == "android"
-[test_utils_backups_create.js]
-[test_utils_getURLsForContainerNode.js]
-[test_utils_setAnnotationsFor.js]
-[test_visitsInDB.js]
diff --git a/toolkit/components/printing/moz.build b/toolkit/components/printing/moz.build
index dc8204b8c..aac3a838c 100644
--- a/toolkit/components/printing/moz.build
+++ b/toolkit/components/printing/moz.build
@@ -5,10 +5,3 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
JAR_MANIFESTS += ['jar.mn']
-
-BROWSER_CHROME_MANIFESTS += [
- 'tests/browser.ini'
-]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Printing')
diff --git a/toolkit/components/printing/tests/browser.ini b/toolkit/components/printing/tests/browser.ini
deleted file mode 100644
index 5f2867189..000000000
--- a/toolkit/components/printing/tests/browser.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[browser_page_change_print_original.js]
-support-files =
- file_page_change_print_original_1.html
- file_page_change_print_original_2.html
-skip-if = os == "mac"
diff --git a/toolkit/components/printing/tests/browser_page_change_print_original.js b/toolkit/components/printing/tests/browser_page_change_print_original.js
deleted file mode 100644
index 864150451..000000000
--- a/toolkit/components/printing/tests/browser_page_change_print_original.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Verify that if the page contents change after print preview is initialized,
- * and we re-initialize print preview (e.g. by changing page orientation),
- * we still show (and will therefore print) the original contents.
- */
-const TEST_PATH = getRootDirectory(gTestPath)
- .replace("chrome://mochitests/content", "http://example.com");
-
-add_task(function* pp_after_orientation_change() {
- const URI = TEST_PATH + "file_page_change_print_original_1.html";
- // Can only do something if we have a print preview UI:
- if (AppConstants.platform != "win" && AppConstants.platform != "linux") {
- ok(true, "Can't test if there's no print preview.");
- return;
- }
-
- // Ensure we get a browserStopped for this browser
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URI, false, true);
- let browserToPrint = tab.linkedBrowser;
- let ppBrowser = PrintPreviewListener.getPrintPreviewBrowser();
-
- // Get a promise now that resolves when the original tab's location changes.
- let originalTabNavigated = BrowserTestUtils.browserStopped(browserToPrint);
-
- // Enter print preview:
- let printPreviewEntered = BrowserTestUtils.waitForMessage(ppBrowser.messageManager, "Printing:Preview:Entered");
- document.getElementById("cmd_printPreview").doCommand();
- yield printPreviewEntered;
-
- // Assert that we are showing the original page
- yield ContentTask.spawn(ppBrowser, null, function* () {
- is(content.document.body.textContent.trim(), "INITIAL PAGE", "Should have initial page print previewed.");
- });
-
- yield originalTabNavigated;
-
- // Change orientation and wait for print preview to re-enter:
- let orient = PrintUtils.getPrintSettings().orientation;
- let orientToSwitchTo = orient != Ci.nsIPrintSettings.kPortraitOrientation ?
- "portrait" : "landscape";
- let printPreviewToolbar = document.querySelector("toolbar[printpreview=true]");
-
- printPreviewEntered = BrowserTestUtils.waitForMessage(ppBrowser.messageManager, "Printing:Preview:Entered");
- printPreviewToolbar.orient(orientToSwitchTo);
- yield printPreviewEntered;
-
- // Check that we're still showing the original page.
- yield ContentTask.spawn(ppBrowser, null, function* () {
- is(content.document.body.textContent.trim(), "INITIAL PAGE", "Should still have initial page print previewed.");
- });
-
- // Check that the other tab is definitely showing the new page:
- yield ContentTask.spawn(browserToPrint, null, function* () {
- is(content.document.body.textContent.trim(), "REPLACED PAGE!", "Original page should have changed.");
- });
-
- PrintUtils.exitPrintPreview();
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/toolkit/components/printing/tests/file_page_change_print_original_1.html b/toolkit/components/printing/tests/file_page_change_print_original_1.html
deleted file mode 100644
index 76e3be137..000000000
--- a/toolkit/components/printing/tests/file_page_change_print_original_1.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<script>
-window.onafterprint = function() {
- setTimeout(function() {
- window.location = "file_page_change_print_original_2.html"
- }, 0);
-}
-</script>
-<pre>INITIAL PAGE</pre>
diff --git a/toolkit/components/printing/tests/file_page_change_print_original_2.html b/toolkit/components/printing/tests/file_page_change_print_original_2.html
deleted file mode 100644
index 44f33281c..000000000
--- a/toolkit/components/printing/tests/file_page_change_print_original_2.html
+++ /dev/null
@@ -1 +0,0 @@
-REPLACED PAGE!
diff --git a/toolkit/components/promiseworker/moz.build b/toolkit/components/promiseworker/moz.build
index 44a90e679..1c771464d 100644
--- a/toolkit/components/promiseworker/moz.build
+++ b/toolkit/components/promiseworker/moz.build
@@ -4,15 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-DIRS += [
- 'worker'
-]
+DIRS += ['worker']
-EXTRA_JS_MODULES += [
- 'PromiseWorker.jsm',
-]
-
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Async Tooling')
+EXTRA_JS_MODULES += ['PromiseWorker.jsm']
diff --git a/toolkit/components/promiseworker/tests/xpcshell/.eslintrc.js b/toolkit/components/promiseworker/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/promiseworker/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/promiseworker/tests/xpcshell/data/chrome.manifest b/toolkit/components/promiseworker/tests/xpcshell/data/chrome.manifest
deleted file mode 100644
index 9e5dd29b2..000000000
--- a/toolkit/components/promiseworker/tests/xpcshell/data/chrome.manifest
+++ /dev/null
@@ -1 +0,0 @@
-content promiseworker ./
diff --git a/toolkit/components/promiseworker/tests/xpcshell/data/worker.js b/toolkit/components/promiseworker/tests/xpcshell/data/worker.js
deleted file mode 100644
index b4750788b..000000000
--- a/toolkit/components/promiseworker/tests/xpcshell/data/worker.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-// Trivial worker definition
-
-importScripts("resource://gre/modules/workers/require.js");
-var PromiseWorker = require("resource://gre/modules/workers/PromiseWorker.js");
-
-var worker = new PromiseWorker.AbstractWorker();
-worker.dispatch = function(method, args = []) {
- return Agent[method](...args);
-},
-worker.postMessage = function(...args) {
- self.postMessage(...args);
-};
-worker.close = function() {
- self.close();
-};
-worker.log = function(...args) {
- dump("Worker: " + args.join(" ") + "\n");
-};
-self.addEventListener("message", msg => worker.handleMessage(msg));
-
-var Agent = {
- bounce: function(...args) {
- return args;
- },
-
- throwError: function(msg, ...args) {
- throw new Error(msg);
- },
-};
diff --git a/toolkit/components/promiseworker/tests/xpcshell/test_Promise.js b/toolkit/components/promiseworker/tests/xpcshell/test_Promise.js
deleted file mode 100644
index 70f49e92e..000000000
--- a/toolkit/components/promiseworker/tests/xpcshell/test_Promise.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var Cu = Components.utils;
-
-Cu.import("resource://gre/modules/PromiseWorker.jsm", this);
-Cu.import("resource://gre/modules/Timer.jsm", this);
-
-// Worker must be loaded from a chrome:// uri, not a file://
-// uri, so we first need to load it.
-
-var WORKER_SOURCE_URI = "chrome://promiseworker/content/worker.js";
-do_load_manifest("data/chrome.manifest");
-var worker = new BasePromiseWorker(WORKER_SOURCE_URI);
-worker.log = function(...args) {
- do_print("Controller: " + args.join(" "));
-};
-
-// Test that simple messages work
-add_task(function* test_simple_args() {
- let message = ["test_simple_args", Math.random()];
- let result = yield worker.post("bounce", message);
- Assert.equal(JSON.stringify(result), JSON.stringify(message));
-});
-
-// Test that it works when we don't provide a message
-add_task(function* test_no_args() {
- let result = yield worker.post("bounce");
- Assert.equal(JSON.stringify(result), JSON.stringify([]));
-});
-
-// Test that messages with promise work
-add_task(function* test_promise_args() {
- let message = ["test_promise_args", Promise.resolve(Math.random())];
- let stringified = JSON.stringify((yield Promise.resolve(Promise.all(message))));
- let result = yield worker.post("bounce", message);
- Assert.equal(JSON.stringify(result), stringified);
-});
-
-// Test that messages with delayed promise work
-add_task(function* test_delayed_promise_args() {
- let promise = new Promise(resolve => setTimeout(() => resolve(Math.random()), 10));
- let message = ["test_delayed_promise_args", promise];
- let stringified = JSON.stringify((yield Promise.resolve(Promise.all(message))));
- let result = yield worker.post("bounce", message);
- Assert.equal(JSON.stringify(result), stringified);
-});
-
-// Test that messages with rejected promise cause appropriate errors
-add_task(function* test_rejected_promise_args() {
- let error = new Error();
- let message = ["test_promise_args", Promise.reject(error)];
- try {
- yield worker.post("bounce", message);
- do_throw("I shound have thrown an error by now");
- } catch (ex) {
- if (ex != error)
- throw ex;
- do_print("I threw the right error");
- }
-});
-
-// Test that we can transfer to the worker using argument `transfer`
-add_task(function* test_transfer_args() {
- let array = new Uint8Array(4);
- for (let i = 0; i < 4; ++i) {
- array[i] = i;
- }
- Assert.equal(array.buffer.byteLength, 4, "The buffer is not detached yet");
-
- let result = (yield worker.post("bounce", [array.buffer], [], [array.buffer]))[0];
-
- // Check that the buffer has been sent
- Assert.equal(array.buffer.byteLength, 0, "The buffer has been detached");
-
- // Check that the result is correct
- Assert.equal(result.byteLength, 4, "The result has the right size");
- let array2 = new Uint8Array(result);
- for (let i = 0; i < 4; ++i) {
- Assert.equal(array2[i], i);
- }
-});
-
-// Test that we can transfer to the worker using an instance of `Meta`
-add_task(function* test_transfer_with_meta() {
- let array = new Uint8Array(4);
- for (let i = 0; i < 4; ++i) {
- array[i] = i;
- }
- Assert.equal(array.buffer.byteLength, 4, "The buffer is not detached yet");
-
- let message = new BasePromiseWorker.Meta(array, {transfers: [array.buffer]});
- let result = (yield worker.post("bounce", [message]))[0];
-
- // Check that the buffer has been sent
- Assert.equal(array.buffer.byteLength, 0, "The buffer has been detached");
-
- // Check that the result is correct
- Assert.equal(Object.prototype.toString.call(result), "[object Uint8Array]",
- "The result appears to be a Typed Array");
- Assert.equal(result.byteLength, 4, "The result has the right size");
-
- for (let i = 0; i < 4; ++i) {
- Assert.equal(result[i], i);
- }
-});
-
-add_task(function* test_throw_error() {
- try {
- yield worker.post("throwError", ["error message"]);
- Assert.ok(false, "should have thrown");
- } catch (ex) {
- Assert.equal(ex.message, "Error: error message");
- }
-});
diff --git a/toolkit/components/promiseworker/tests/xpcshell/xpcshell.ini b/toolkit/components/promiseworker/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index 1efcd8c9e..000000000
--- a/toolkit/components/promiseworker/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,9 +0,0 @@
-[DEFAULT]
-head=
-tail=
-skip-if = toolkit == 'android'
-support-files=
- data/worker.js
- data/chrome.manifest
-
-[test_Promise.js]
diff --git a/toolkit/components/prompts/moz.build b/toolkit/components/prompts/moz.build
index 1dc21cca6..b827a11b6 100644
--- a/toolkit/components/prompts/moz.build
+++ b/toolkit/components/prompts/moz.build
@@ -6,6 +6,4 @@
DIRS += ['src']
-MOCHITEST_MANIFESTS += ['test/mochitest.ini']
-
JAR_MANIFESTS += ['jar.mn']
diff --git a/toolkit/components/prompts/test/.eslintrc.js b/toolkit/components/prompts/test/.eslintrc.js
deleted file mode 100644
index 3c788d6d6..000000000
--- a/toolkit/components/prompts/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/mochitest.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/prompts/test/bug619644_inner.html b/toolkit/components/prompts/test/bug619644_inner.html
deleted file mode 100644
index f929c5649..000000000
--- a/toolkit/components/prompts/test/bug619644_inner.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<head></head><body><p>Original content</p>
-<script>
- window.opener.postMessage("", "*");
- confirm ("Message");
- document.write ("Extra content");
- window.opener.postMessage(document.documentElement.innerHTML, "*");
-</script></body>
diff --git a/toolkit/components/prompts/test/bug625187_iframe.html b/toolkit/components/prompts/test/bug625187_iframe.html
deleted file mode 100644
index 740d59a61..000000000
--- a/toolkit/components/prompts/test/bug625187_iframe.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<html>
-<head>
- <title>Test for Bug 625187 - the iframe</title>
-<!--
- - Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/
- -
- - Contributor(s):
- - Mihai Sucan <mihai.sucan@gmail.com>
- -->
-</head>
-<body>
-<p><button id="btn1" onclick="alert('hello world 2')">Button 2</button></p>
-<p><button id="btn2" onclick="window.parent.alert('hello world 3')">Button 3</button></p>
-</body>
-</html>
diff --git a/toolkit/components/prompts/test/chromeScript.js b/toolkit/components/prompts/test/chromeScript.js
deleted file mode 100644
index 7b2d37100..000000000
--- a/toolkit/components/prompts/test/chromeScript.js
+++ /dev/null
@@ -1,241 +0,0 @@
-const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/Timer.jsm");
-
-// Define these to make EventUtils happy.
-let window = this;
-let parent = {};
-
-let EventUtils = {};
-Services.scriptloader.loadSubScript(
- "chrome://mochikit/content/tests/SimpleTest/EventUtils.js",
- EventUtils
-);
-
-addMessageListener("handlePrompt", msg => {
- handlePromptWhenItAppears(msg.action, msg.isTabModal, msg.isSelect);
-});
-
-function handlePromptWhenItAppears(action, isTabModal, isSelect) {
- let interval = setInterval(() => {
- if (handlePrompt(action, isTabModal, isSelect)) {
- clearInterval(interval);
- }
- }, 100);
-}
-
-function handlePrompt(action, isTabModal, isSelect) {
- let ui;
-
- if (isTabModal) {
- let browserWin = Services.wm.getMostRecentWindow("navigator:browser");
- let gBrowser = browserWin.gBrowser;
- let promptManager = gBrowser.getTabModalPromptBox(gBrowser.selectedBrowser);
- let prompts = promptManager.listPrompts();
- if (!prompts.length) {
- return false; // try again in a bit
- }
-
- ui = prompts[0].Dialog.ui;
- } else {
- let doc = getDialogDoc();
- if (!doc) {
- return false; // try again in a bit
- }
-
- if (isSelect)
- ui = doc;
- else
- ui = doc.defaultView.Dialog.ui;
-
- }
-
- let promptState;
- if (isSelect) {
- promptState = getSelectState(ui);
- dismissSelect(ui, action);
- } else {
- promptState = getPromptState(ui);
- dismissPrompt(ui, action);
- }
- sendAsyncMessage("promptHandled", { promptState: promptState });
- return true;
-}
-
-function getSelectState(ui) {
- let listbox = ui.getElementById("list");
-
- let state = {};
- state.msg = ui.getElementById("info.txt").value;
- state.selectedIndex = listbox.selectedIndex;
- state.items = [];
-
- for (let i = 0; i < listbox.itemCount; i++) {
- let item = listbox.getItemAtIndex(i).label;
- state.items.push(item);
- }
-
- return state;
-}
-
-function getPromptState(ui) {
- let state = {};
- state.msg = ui.infoBody.textContent;
- state.titleHidden = ui.infoTitle.getAttribute("hidden") == "true";
- state.textHidden = ui.loginContainer.hidden;
- state.passHidden = ui.password1Container.hidden;
- state.checkHidden = ui.checkboxContainer.hidden;
- state.checkMsg = ui.checkbox.label;
- state.checked = ui.checkbox.checked;
- // tab-modal prompts don't have an infoIcon
- state.iconClass = ui.infoIcon ? ui.infoIcon.className : null;
- state.textValue = ui.loginTextbox.getAttribute("value");
- state.passValue = ui.password1Textbox.getAttribute("value");
-
- state.butt0Label = ui.button0.label;
- state.butt1Label = ui.button1.label;
- state.butt2Label = ui.button2.label;
-
- state.butt0Disabled = ui.button0.disabled;
- state.butt1Disabled = ui.button1.disabled;
- state.butt2Disabled = ui.button2.disabled;
-
- function isDefaultButton(b) {
- return (b.hasAttribute("default") &&
- b.getAttribute("default") == "true");
- }
- state.defButton0 = isDefaultButton(ui.button0);
- state.defButton1 = isDefaultButton(ui.button1);
- state.defButton2 = isDefaultButton(ui.button2);
-
- let fm = Cc["@mozilla.org/focus-manager;1"].
- getService(Ci.nsIFocusManager);
- let e = fm.focusedElement;
-
- if (e == null) {
- state.focused = null;
- } else if (ui.button0.isSameNode(e)) {
- state.focused = "button0";
- } else if (ui.button1.isSameNode(e)) {
- state.focused = "button1";
- } else if (ui.button2.isSameNode(e)) {
- state.focused = "button2";
- } else if (ui.loginTextbox.inputField.isSameNode(e)) {
- state.focused = "textField";
- } else if (ui.password1Textbox.inputField.isSameNode(e)) {
- state.focused = "passField";
- } else if (ui.infoBody.isSameNode(e)) {
- state.focused = "infoBody";
- } else {
- state.focused = "ERROR: unexpected element focused: " + (e ? e.localName : "<null>");
- }
-
- return state;
-}
-
-function dismissSelect(ui, action) {
- let dialog = ui.getElementsByTagName("dialog")[0];
- let listbox = ui.getElementById("list");
-
- if (action.selectItem) {
- listbox.selectedIndex = 1;
- }
-
- if (action.buttonClick == "ok") {
- dialog.acceptDialog();
- } else if (action.buttonClick == "cancel") {
- dialog.cancelDialog();
- }
-}
-
-function dismissPrompt(ui, action) {
- if (action.setCheckbox) {
- // Annoyingly, the prompt code is driven by oncommand.
- ui.checkbox.setChecked(true);
- ui.checkbox.doCommand();
- }
-
- if ("textField" in action) {
- ui.loginTextbox.setAttribute("value", action.textField);
- }
-
- if ("passField" in action) {
- ui.password1Textbox.setAttribute("value", action.passField);
- }
-
- switch (action.buttonClick) {
- case "ok":
- case 0:
- ui.button0.click();
- break;
- case "cancel":
- case 1:
- ui.button1.click();
- break;
- case 2:
- ui.button2.click();
- break;
- case "ESC":
- // XXX This is assuming tab-modal.
- let browserWin = Services.wm.getMostRecentWindow("navigator:browser");
- EventUtils.synthesizeKey("KEY_Escape", { code: "Escape" }, browserWin);
- break;
- case "pollOK":
- // Buttons are disabled at the moment, poll until they're reenabled.
- // Can't use setInterval here, because the window's in a modal state
- // and thus DOM events are suppressed.
- let interval = setInterval(() => {
- if (ui.button0.disabled)
- return;
- ui.button0.click();
- clearInterval(interval);
- }, 100);
- break;
-
- default:
- throw "dismissPrompt action listed unknown button.";
- }
-}
-
-function getDialogDoc() {
- // Trudge through all the open windows, until we find the one
- // that has either commonDialog.xul or selectDialog.xul loaded.
- var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
- getService(Ci.nsIWindowMediator);
- // var enumerator = wm.getEnumerator("navigator:browser");
- var enumerator = wm.getXULWindowEnumerator(null);
-
- while (enumerator.hasMoreElements()) {
- var win = enumerator.getNext();
- var windowDocShell = win.QueryInterface(Ci.nsIXULWindow).docShell;
-
- var containedDocShells = windowDocShell.getDocShellEnumerator(
- Ci.nsIDocShellTreeItem.typeChrome,
- Ci.nsIDocShell.ENUMERATE_FORWARDS);
- while (containedDocShells.hasMoreElements()) {
- // Get the corresponding document for this docshell
- var childDocShell = containedDocShells.getNext();
- // We don't want it if it's not done loading.
- if (childDocShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE)
- continue;
- var childDoc = childDocShell.QueryInterface(Ci.nsIDocShell)
- .contentViewer
- .DOMDocument;
-
- if (childDoc.location.href != "chrome://global/content/commonDialog.xul" &&
- childDoc.location.href != "chrome://global/content/selectDialog.xul")
- continue;
-
- // We're expecting the dialog to be focused. If it's not yet, try later.
- // (In particular, this is needed on Linux to reliably check focused elements.)
- let fm = Cc["@mozilla.org/focus-manager;1"].
- getService(Ci.nsIFocusManager);
- if (fm.focusedWindow != childDoc.defaultView)
- continue;
-
- return childDoc;
- }
- }
-
- return null;
-}
diff --git a/toolkit/components/prompts/test/mochitest.ini b/toolkit/components/prompts/test/mochitest.ini
deleted file mode 100644
index 7f87650d6..000000000
--- a/toolkit/components/prompts/test/mochitest.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[DEFAULT]
-support-files =
- ../../passwordmgr/test/authenticate.sjs
- bug619644_inner.html
- bug625187_iframe.html
- prompt_common.js
- chromeScript.js
-
-[test_bug619644.html]
-[test_bug620145.html]
-skip-if = toolkit == 'android' #TIMED_OUT
-[test_subresources_prompts.html]
-skip-if = toolkit == 'android'
-[test_dom_prompts.html]
-skip-if = toolkit == 'android' #android: bug 1267092
-[test_modal_prompts.html]
-skip-if = toolkit == 'android' || (os == 'linux' && (debug || asan)) #android: TIMED_OUT (For Linux : 950636)
-[test_modal_select.html]
-skip-if = toolkit == 'android' #android: TIMED_OUT
diff --git a/toolkit/components/prompts/test/prompt_common.js b/toolkit/components/prompts/test/prompt_common.js
deleted file mode 100644
index e3a69b347..000000000
--- a/toolkit/components/prompts/test/prompt_common.js
+++ /dev/null
@@ -1,158 +0,0 @@
-const Ci = SpecialPowers.Ci;
-const Cc = SpecialPowers.Cc;
-ok(Ci != null, "Access Ci");
-ok(Cc != null, "Access Cc");
-
-function hasTabModalPrompts() {
- var prefName = "prompts.tab_modal.enabled";
- var Services = SpecialPowers.Cu.import("resource://gre/modules/Services.jsm").Services;
- return Services.prefs.getPrefType(prefName) == Services.prefs.PREF_BOOL &&
- Services.prefs.getBoolPref(prefName);
-}
-var isTabModal = hasTabModalPrompts();
-var isSelectDialog = false;
-var isOSX = ("nsILocalFileMac" in SpecialPowers.Ci);
-var isE10S = SpecialPowers.Services.appinfo.processType == 2;
-
-
-var gChromeScript = SpecialPowers.loadChromeScript(SimpleTest.getTestFileURL("chromeScript.js"));
-SimpleTest.registerCleanupFunction(() => gChromeScript.destroy());
-
-function onloadPromiseFor(id) {
- var iframe = document.getElementById(id);
- return new Promise(resolve => {
- iframe.addEventListener("load", function onload(e) {
- iframe.removeEventListener("load", onload);
- resolve(true);
- });
- });
-}
-
-function handlePrompt(state, action) {
- return new Promise(resolve => {
- gChromeScript.addMessageListener("promptHandled", function handled(msg) {
- gChromeScript.removeMessageListener("promptHandled", handled);
- checkPromptState(msg.promptState, state);
- resolve(true);
- });
- gChromeScript.sendAsyncMessage("handlePrompt", { action: action, isTabModal: isTabModal});
- });
-}
-
-function checkPromptState(promptState, expectedState) {
- // XXX check title? OS X has title in content
- is(promptState.msg, expectedState.msg, "Checking expected message");
- if (isOSX && !isTabModal)
- ok(!promptState.titleHidden, "Checking title always visible on OS X");
- else
- is(promptState.titleHidden, expectedState.titleHidden, "Checking title visibility");
- is(promptState.textHidden, expectedState.textHidden, "Checking textbox visibility");
- is(promptState.passHidden, expectedState.passHidden, "Checking passbox visibility");
- is(promptState.checkHidden, expectedState.checkHidden, "Checking checkbox visibility");
- is(promptState.checkMsg, expectedState.checkMsg, "Checking checkbox label");
- is(promptState.checked, expectedState.checked, "Checking checkbox checked");
- if (!isTabModal)
- is(promptState.iconClass, "spaced " + expectedState.iconClass, "Checking expected icon CSS class");
- is(promptState.textValue, expectedState.textValue, "Checking textbox value");
- is(promptState.passValue, expectedState.passValue, "Checking passbox value");
-
- if (expectedState.butt0Label) {
- is(promptState.butt0Label, expectedState.butt0Label, "Checking accept-button label");
- }
- if (expectedState.butt1Label) {
- is(promptState.butt1Label, expectedState.butt1Label, "Checking cancel-button label");
- }
- if (expectedState.butt2Label) {
- is(promptState.butt2Label, expectedState.butt2Label, "Checking extra1-button label");
- }
-
- // For prompts with a time-delay button.
- if (expectedState.butt0Disabled) {
- is(promptState.butt0Disabled, true, "Checking accept-button is disabled");
- is(promptState.butt1Disabled, false, "Checking cancel-button isn't disabled");
- }
-
- is(promptState.defButton0, expectedState.defButton == "button0", "checking button0 default");
- is(promptState.defButton1, expectedState.defButton == "button1", "checking button1 default");
- is(promptState.defButton2, expectedState.defButton == "button2", "checking button2 default");
-
- if (isOSX && expectedState.focused && expectedState.focused.startsWith("button")) {
- is(promptState.focused, "infoBody", "buttons don't focus on OS X, but infoBody does instead");
- } else {
- is(promptState.focused, expectedState.focused, "Checking focused element");
- }
-}
-
-function checkEchoedAuthInfo(expectedState, doc) {
- // The server echos back the HTTP auth info it received.
- let username = doc.getElementById("user").textContent;
- let password = doc.getElementById("pass").textContent;
- let authok = doc.getElementById("ok").textContent;
-
- is(authok, "PASS", "Checking for successful authentication");
- is(username, expectedState.user, "Checking for echoed username");
- is(password, expectedState.pass, "Checking for echoed password");
-}
-
-/**
- * Create a Proxy to relay method calls on an nsIAuthPrompt[2] prompter to a chrome script which can
- * perform the calls in the parent. Out and inout params will be copied back from the parent to
- * content.
- *
- * @param chromeScript The reference to the chrome script that will listen to `proxyPrompter`
- * messages in the parent and call the `methodName` method.
- * The return value from the message handler should be an object with properties:
- * `rv` - containing the return value of the method call.
- * `args` - containing the array of arguments passed to the method since out or inout ones could have
- * been modified.
- */
-function PrompterProxy(chromeScript) {
- return new Proxy({}, {
- get(target, prop, receiver) {
- return (...args) => {
- // Array of indices of out/inout params to copy from the parent back to the caller.
- let outParams = [];
-
- switch (prop) {
- case "prompt": {
- outParams = [/* result */ 5];
- break;
- }
- case "promptAuth": {
- outParams = [];
- break;
- }
- case "promptPassword": {
- outParams = [/* pwd */ 4];
- break;
- }
- case "promptUsernameAndPassword": {
- outParams = [/* user */ 4, /* pwd */ 5];
- break;
- }
- default: {
- throw new Error("Unknown nsIAuthPrompt method");
- }
- }
-
- let result = chromeScript.sendSyncMessage("proxyPrompter", {
- args,
- methodName: prop,
- })[0][0];
-
- for (let outParam of outParams) {
- // Copy the out or inout param value over the original
- args[outParam].value = result.args[outParam].value;
- }
-
- if (prop == "promptAuth") {
- args[2].username = result.args[2].username;
- args[2].password = result.args[2].password;
- args[2].domain = result.args[2].domain;
- }
-
- return result.rv;
- };
- },
- });
-}
diff --git a/toolkit/components/prompts/test/test_bug619644.html b/toolkit/components/prompts/test/test_bug619644.html
deleted file mode 100644
index 9f61eb18b..000000000
--- a/toolkit/components/prompts/test/test_bug619644.html
+++ /dev/null
@@ -1,76 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=619644
--->
-<head>
- <title>Test for Bug 619644</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=619644">Mozilla Bug 619644</a>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-// This is a little yucky, but it works
-// The contents of bug619644_inner.html
-const expectedFinalDoc =
-"<head><\/head><body><p>Original content<\/p>\n<script>\n window.opener.postMessage(\"\", \"*\");\n confirm (\"Message\");\n document.write (\"Extra content\");\n window.opener.postMessage(document.documentElement.innerHTML, \"*\");\n<\/script>Extra content<\/body>";
-
-if (!isTabModal) {
- todo(false, "Test disabled when tab modal prompts are not enabled.");
-} else {
- inittest();
-}
-
-var promptDone;
-
-function inittest() {
- window.addEventListener("message", runtest, false);
- window.open("bug619644_inner.html", "619644");
-
- SimpleTest.waitForExplicitFinish();
-}
-
-function runtest(e) {
- window.removeEventListener("message", runtest, false);
- window.addEventListener("message", checktest, false);
-
- let state = {
- msg : "Message",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- let action = {
- buttonClick: "ESC",
- };
-
- promptDone = handlePrompt(state, action);
-}
-
-function checktest(e) {
- is(e.data, expectedFinalDoc, "ESC press should not abort document load");
- e.source.close();
- promptDone.then(endtest);
-}
-
-function endtest() {
- info("Ending test");
- SimpleTest.finish();
-}
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/prompts/test/test_bug620145.html b/toolkit/components/prompts/test/test_bug620145.html
deleted file mode 100644
index bb4470259..000000000
--- a/toolkit/components/prompts/test/test_bug620145.html
+++ /dev/null
@@ -1,105 +0,0 @@
-<html>
-<head>
- <title>Test for Bug 620145</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=620145">Mozilla Bug 620145</a>
-<pre id="test">
-</pre>
-
-<div id="text" style="max-width: 100px" onmouseup="openAlert()">
- This is a short piece of text used for testing that mouse selecting is
- stopped when an alert appears.
-</div>
-<div id="text2" style="max-width: 100px">
- This is another short piece of text used for testing that mouse selecting is
- stopped when an alert appears.
-</div>
-<button id="button" onmouseup="openAlert()">Button</button>
-
-<script class="testbody" type="text/javascript">
-var selectionTest = false;
-
-function openAlert() {
- info("opening alert...");
- alert("hello!");
- info("...alert done.");
-}
-
-add_task(function* runTest() {
- var state, action;
- // The <button> in this test's HTML opens a prompt when clicked.
- // Here we send the events to simulate clicking it.
- info("isTabModal? " + isTabModal);
- selectionTest = isTabModal;
-
- state = {
- msg : "hello!",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- var button = $("button");
- dispatchMouseEvent(button, "mousedown");
- dispatchMouseEvent(button, "mouseup");
- // alert appears at this point, to be closed by the chrome script.
-
- yield promptDone;
- checkSelection();
-
- // using same state and action.
- promptDone = handlePrompt(state, action);
-
- var text = $("text");
- dispatchMouseEvent(text, "mousedown");
- dispatchMouseEvent(text, "mouseup");
- // alert appears at this point, to be closed by the chrome script.
-
- yield promptDone;
- checkSelection();
-});
-
-function dispatchMouseEvent(target, type)
-{
- var win = target.ownerDocument.defaultView;
- e = document.createEvent("MouseEvent");
- e.initEvent(type, false, false, win, 0, 1, 1, 1, 1,
- false, false, false, false, 0, null);
- var utils = SpecialPowers.getDOMWindowUtils(win);
- utils.dispatchDOMEventViaPresShell(target, e, true);
- ok(true, type + " sent to " + target.id);
-}
-
-function checkSelection()
-{
- if (!selectionTest) {
- todo(false, "Selection test is disabled when tab modal prompts are not enabled.");
- } else {
- synthesizeMouse($("text"), 25, 55, { type: "mousemove" });
- is(window.getSelection().toString(), "", "selection not made");
- }
-}
-</script>
-
-</body>
-</html>
diff --git a/toolkit/components/prompts/test/test_dom_prompts.html b/toolkit/components/prompts/test/test_dom_prompts.html
deleted file mode 100644
index 413ed8fd5..000000000
--- a/toolkit/components/prompts/test/test_dom_prompts.html
+++ /dev/null
@@ -1,208 +0,0 @@
-<html>
-<head>
- <title>Test for DOM prompts</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<pre id="test">
-</pre>
-
-<script class="testbody" type="text/javascript">
-var rv;
-var state, action;
-
-add_task(function* test_alert_ok() {
- info("Starting test: Alert");
- state = {
- msg : "This is the alert text.",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- alert("This is the alert text.");
-
- yield promptDone;
-});
-
-// bug 861605 made the arguments to alert/confirm optional (prompt already was).
-add_task(function* test_alert_noargs() {
- info("Starting test: Alert with no args");
- state = {
- msg : "",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- try {
- alert();
- ok(true, "alert() without arguments should not throw!");
- } catch (e) {
- ok(false, "alert() without arguments should not throw!");
- }
-
- yield promptDone;
-});
-
-
-add_task(function* test_confirm_ok() {
- info("Starting test: Confirm");
- state = {
- msg : "This is the confirm text.",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- rv = confirm("This is the confirm text.");
- is(rv, true, "check prompt return value");
-
- yield promptDone;
-});
-
-// bug 861605 made the arguments to alert/confirm optional (prompt already was).
-add_task(function* test_confirm_noargs() {
- info("Starting test: Confirm with no args");
- state = {
- msg : "",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- try {
- rv = confirm();
- ok(true, "confirm() without arguments should not throw!");
- } catch (e) {
- ok(false, "confirm() without arguments should not throw!");
- }
- is(rv, true, "check prompt return value");
-
- yield promptDone;
-});
-
-
-add_task(function* test_prompt_ok() {
- info("Starting test: Prompt");
- state = {
- msg : "This is the Prompt text.",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- rv = prompt("This is the Prompt text.");
- is(rv, "", "check prompt return value");
-
- yield promptDone;
-});
-
-// bug 861605 made the arguments to alert/confirm optional (prompt already was).
-add_task(function* test_prompt_noargs() {
- info("Starting test: Prompt with no args");
- state = {
- msg : "",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- try {
- rv = prompt();
- ok(true, "prompt() without arguments should not throw!");
- } catch (e) {
- ok(false, "prompt() without arguments should not throw!");
- }
- is(rv, "", "check prompt return value");
-
- yield promptDone;
-});
-
-</script>
-
-</body>
-</html>
diff --git a/toolkit/components/prompts/test/test_modal_prompts.html b/toolkit/components/prompts/test/test_modal_prompts.html
deleted file mode 100644
index 42e6be52c..000000000
--- a/toolkit/components/prompts/test/test_modal_prompts.html
+++ /dev/null
@@ -1,1184 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Modal Prompts Test</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Prompter tests: modal prompts
-<p id="display"></p>
-
-<div id="content" style="display: none">
- <iframe id="iframe"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.8">
-
-function* runTests() {
- const { NetUtil } = SpecialPowers.Cu.import('resource://gre/modules/NetUtil.jsm');
- let state, action;
- ok(true, "Running tests (isTabModal=" + isTabModal + ", usePromptService=" + usePromptService + ")");
-
- let prompter, promptArgs;
- if (usePromptService) {
- prompter = Cc["@mozilla.org/embedcomp/prompt-service;1"].
- getService(Ci.nsIPromptService2);
- } else {
- prompter = Cc["@mozilla.org/prompter;1"].
- getService(Ci.nsIPromptFactory).
- getPrompt(window, Ci.nsIPrompt);
- if (isTabModal) {
- let bag = prompter.QueryInterface(Ci.nsIWritablePropertyBag2);
- bag.setPropertyAsBool("allowTabModal", true);
- }
- }
-
- let checkVal = {};
- let textVal = {};
- let passVal = {};
- let flags;
- let isOK, clickedButton;
-
- // =====
- info("Starting test: Alert");
- state = {
- msg : "This is the alert text.",
- title : "TestTitle",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- promptArgs = ["TestTitle", "This is the alert text."];
- if (usePromptService)
- promptArgs.unshift(window);
- prompter.alert.apply(null, promptArgs);
-
- yield promptDone;
-
- // =====
- info("Starting test: AlertCheck (null checkbox label, so it's hidden)");
- state = {
- msg : "This is the alertCheck text.",
- title : "TestTitle",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- promptArgs = ["TestTitle", "This is the alertCheck text.", null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- prompter.alertCheck.apply(null, promptArgs);
-
- yield promptDone;
-
- // =====
- info("Starting test: AlertCheck");
- state = {
- msg : "This is the alertCheck text.",
- title : "TestTitle",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the alertCheck text.", "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- prompter.alertCheck.apply(null, promptArgs);
- is(checkVal.value, true, "checkbox was checked");
-
- yield promptDone;
-
- // =====
- info("Starting test: Confirm (ok)");
- state = {
- msg : "This is the confirm text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- promptArgs = ["TestTitle", "This is the confirm text."];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.confirm.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
-
- yield promptDone;
-
- // =====
- info("Starting test: Confirm (cancel)");
- state = {
- msg : "This is the confirm text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "cancel",
- };
-
- promptDone = handlePrompt(state, action);
-
- promptArgs = ["TestTitle", "This is the confirm text."];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.confirm.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmCheck (ok, null checkbox label)");
- state = {
- msg : "This is the confirmCheck text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- promptArgs = ["TestTitle", "This is the confirmCheck text.", null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.confirmCheck.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmCheck (cancel, null checkbox label)");
- state = {
- msg : "This is the confirmCheck text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "cancel",
- };
-
- promptDone = handlePrompt(state, action);
-
- promptArgs = ["TestTitle", "This is the confirmCheck text.", null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.confirmCheck.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmCheck (ok)");
- state = {
- msg : "This is the confirmCheck text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the confirmCheck text.", "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.confirmCheck.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmCheck (cancel)");
- state = {
- msg : "This is the confirmCheck text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "cancel",
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the confirmCheck text.", "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.confirmCheck.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: Prompt (ok, no default text)");
- state = {
- msg : "This is the prompt text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- textField : "bacon",
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "";
- promptArgs = ["TestTitle", "This is the prompt text.", textVal, null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.prompt.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
- is(textVal.value, "bacon", "checking expected text value");
-
- yield promptDone;
-
- // =====
- info("Starting test: Prompt (ok, default text)");
- state = {
- msg : "This is the prompt text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- textValue : "kittens",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "kittens";
- promptArgs = ["TestTitle", "This is the prompt text.", textVal, null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.prompt.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
- is(textVal.value, "kittens", "checking expected text value");
-
- yield promptDone;
-
- // =====
- info("Starting test: Prompt (cancel, default text)");
- state = {
- msg : "This is the prompt text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- textValue : "puppies",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick: "cancel",
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "puppies";
- promptArgs = ["TestTitle", "This is the prompt text.", textVal, null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.prompt.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
- is(textVal.value, "puppies", "checking expected text value");
-
- yield promptDone;
-
- // =====
- info("Starting test: Prompt (cancel, default text modified)");
- state = {
- msg : "This is the prompt text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : true,
- textValue : "puppies",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "cancel",
- textField : "bacon",
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "puppies";
- promptArgs = ["TestTitle", "This is the prompt text.", textVal, null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.prompt.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
- is(textVal.value, "puppies", "checking expected text value");
-
- yield promptDone;
-
- // =====
- info("Starting test: Prompt (ok, with checkbox)");
- state = {
- msg : "This is the prompt text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : false,
- textValue : "tribbles",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "tribbles";
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the prompt text.", textVal, "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.prompt.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
- is(textVal.value, "tribbles", "checking expected text value");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: Prompt (cancel, with checkbox)");
- state = {
- msg : "This is the prompt text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : true,
- checkHidden : false,
- textValue : "tribbles",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick: "cancel",
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "tribbles";
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the prompt text.", textVal, "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.prompt.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
- is(textVal.value, "tribbles", "checking expected text value");
- is(checkVal.value, false, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- // Just two tests for this, since password manager already tests this extensively.
- info("Starting test: PromptUsernameAndPassword (ok)");
- state = {
- msg : "This is the pUAP text.",
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- textValue : "usr",
- passValue : "ssh",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- setCheckbox: true,
- textField: "newusr",
- passField: "newssh",
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "usr";
- passVal.value = "ssh";
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the pUAP text.", textVal, passVal, "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.promptUsernameAndPassword.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
- is(textVal.value, "newusr", "checking expected text value");
- is(passVal.value, "newssh", "checking expected pass value");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: PromptUsernameAndPassword (cancel)");
- state = {
- msg : "This is the pUAP text.",
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- textValue : "usr",
- passValue : "ssh",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "cancel",
- setCheckbox : true,
- textField : "newusr",
- passField : "newssh",
- };
-
- promptDone = handlePrompt(state, action);
-
- textVal.value = "usr";
- passVal.value = "ssh";
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the pUAP text.", textVal, passVal, "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.promptUsernameAndPassword.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
- is(textVal.value, "usr", "checking expected text value");
- is(passVal.value, "ssh", "checking expected pass value");
- is(checkVal.value, false, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: PromptPassword (ok)");
- state = {
- msg : "This is the promptPassword text.",
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : false,
- textValue : "",
- passValue : "ssh",
- checkMsg : "Check me out!",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- setCheckbox : true,
- passField : "newssh",
- };
-
- promptDone = handlePrompt(state, action);
-
- passVal.value = "ssh";
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the promptPassword text.", passVal, "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.promptPassword.apply(null, promptArgs);
- is(isOK, true, "checked expected retval");
- is(passVal.value, "newssh", "checking expected pass value");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: PromptPassword (cancel)");
- state = {
- msg : "This is the promptPassword text.",
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : false,
- checkHidden : false,
- textValue : "",
- passValue : "ssh",
- checkMsg : "Check me out!",
- checked : false,
- focused : "passField",
- defButton : "button0",
- };
- action = {
- buttonClick : "cancel",
- setCheckbox : true,
- passField : "newssh",
- };
-
- promptDone = handlePrompt(state, action);
-
- passVal.value = "ssh";
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the promptPassword text.", passVal, "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- isOK = prompter.promptPassword.apply(null, promptArgs);
- is(isOK, false, "checked expected retval");
- is(passVal.value, "ssh", "checking expected pass value");
- is(checkVal.value, false, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmEx (ok/cancel, ok)");
- state = {
- msg : "This is the confirmEx text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- butt0Label : "OK",
- butt1Label : "Cancel",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- flags = Ci.nsIPromptService.STD_OK_CANCEL_BUTTONS;
- promptArgs = ["TestTitle", "This is the confirmEx text.", flags, null, null, null, null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- clickedButton = prompter.confirmEx.apply(null, promptArgs);
- is(clickedButton, 0, "checked expected button num click");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmEx (yes/no, cancel)");
- state = {
- msg : "This is the confirmEx text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- butt0Label : "Yes",
- butt1Label : "No",
- };
- action = {
- buttonClick: "cancel",
- };
-
- promptDone = handlePrompt(state, action);
-
- flags = Ci.nsIPromptService.STD_YES_NO_BUTTONS;
- promptArgs = ["TestTitle", "This is the confirmEx text.", flags, null, null, null, null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- clickedButton = prompter.confirmEx.apply(null, promptArgs);
- is(clickedButton, 1, "checked expected button num click");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmEx (buttons from args, checkbox, ok)");
- state = {
- msg : "This is the confirmEx text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "button0",
- defButton : "button0",
- butt0Label : "butt0",
- butt1Label : "butt1",
- butt2Label : "butt2",
- };
- action = {
- buttonClick: "ok",
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- let b = Ci.nsIPromptService.BUTTON_TITLE_IS_STRING;
- flags = b * Ci.nsIPromptService.BUTTON_POS_2 +
- b * Ci.nsIPromptService.BUTTON_POS_1 +
- b * Ci.nsIPromptService.BUTTON_POS_0;
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the confirmEx text.", flags,
- "butt0", "butt1", "butt2", "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- clickedButton = prompter.confirmEx.apply(null, promptArgs);
- is(clickedButton, 0, "checked expected button num click");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmEx (buttons from args, checkbox, cancel)");
- state = {
- msg : "This is the confirmEx text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "button1", // Default changed!
- defButton : "button1",
- butt0Label : "butt0",
- butt1Label : "butt1",
- butt2Label : "butt2",
- };
- action = {
- buttonClick: "cancel",
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- b = Ci.nsIPromptService.BUTTON_TITLE_IS_STRING;
- flags = b * Ci.nsIPromptService.BUTTON_POS_2 +
- b * Ci.nsIPromptService.BUTTON_POS_1 +
- b * Ci.nsIPromptService.BUTTON_POS_0;
- flags ^= Ci.nsIPromptService.BUTTON_POS_1_DEFAULT;
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the confirmEx text.", flags,
- "butt0", "butt1", "butt2", "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- clickedButton = prompter.confirmEx.apply(null, promptArgs);
- is(clickedButton, 1, "checked expected button num click");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- info("Starting test: ConfirmEx (buttons from args, checkbox, button3)");
- state = {
- msg : "This is the confirmEx text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "button2", // Default changed!
- defButton : "button2",
- butt0Label : "butt0",
- butt1Label : "butt1",
- butt2Label : "butt2",
- };
- action = {
- buttonClick: 2,
- setCheckbox: true,
- };
-
- promptDone = handlePrompt(state, action);
-
- b = Ci.nsIPromptService.BUTTON_TITLE_IS_STRING;
- flags = b * Ci.nsIPromptService.BUTTON_POS_2 +
- b * Ci.nsIPromptService.BUTTON_POS_1 +
- b * Ci.nsIPromptService.BUTTON_POS_0;
- flags ^= Ci.nsIPromptService.BUTTON_POS_2_DEFAULT;
- checkVal.value = false;
- promptArgs = ["TestTitle", "This is the confirmEx text.", flags,
- "butt0", "butt1", "butt2", "Check me out!", checkVal];
- if (usePromptService)
- promptArgs.unshift(window);
- clickedButton = prompter.confirmEx.apply(null, promptArgs);
- is(clickedButton, 2, "checked expected button num click");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
-
- // =====
- // (skipped for E10S and tabmodal tests: window is required)
- info("Starting test: Alert, no window");
- state = {
- msg : "This is the alert text.",
- title : "TestTitle",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
- if (!isTabModal && !isE10S) {
- promptDone = handlePrompt(state, action);
-
- promptArgs = ["TestTitle", "This is the alert text."];
- if (usePromptService)
- promptArgs.unshift(null);
- prompter.alert.apply(null, promptArgs);
-
- yield promptDone;
- }
-
-
- // =====
- // (skipped for tabmodal tests: delay not supported)
- info("Starting test: ConfirmEx (delay, ok)");
- state = {
- msg : "This is the confirmEx delay text.",
- title : "TestTitle",
- iconClass : "question-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : null, // nothing focused until after delay fires
- defButton : "button0",
- butt0Label : "OK",
- butt1Label : "Cancel",
- butt0Disabled: true,
- };
-
- // OS X doesn't initially focus the button, but rather the infoBody.
- // The focus stays there even after the button-enable delay has fired.
- if (isOSX)
- state.focused = "infoBody";
-
- action = {
- buttonClick: "pollOK",
- };
- if (!isTabModal) {
- promptDone = handlePrompt(state, action);
-
- flags = (Ci.nsIPromptService.STD_OK_CANCEL_BUTTONS | Ci.nsIPromptService.BUTTON_DELAY_ENABLE);
- promptArgs = ["TestTitle", "This is the confirmEx delay text.", flags, null, null, null, null, {}];
- if (usePromptService)
- promptArgs.unshift(window);
- clickedButton = prompter.confirmEx.apply(null, promptArgs);
- is(clickedButton, 0, "checked expected button num click");
-
- yield promptDone;
- }
-
- // promptAuth already tested via password manager but do a few specific things here.
- var channel = NetUtil.newChannel({
- uri: "http://example.com",
- loadUsingSystemPrincipal: true
- });
-
- var level = Ci.nsIAuthPrompt2.LEVEL_NONE;
- var authinfo = {
- username : "",
- password : "",
- domain : "",
- flags : Ci.nsIAuthInformation.AUTH_HOST,
- authenticationScheme : "basic",
- realm : ""
- };
-
-
- // =====
- // (promptAuth is only accessible from the prompt service)
- info("Starting test: promptAuth with empty realm");
- state = {
- msg : 'http://example.com is requesting your username and password.',
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- setCheckbox : true,
- textField : "username",
- passField : "password",
- };
- if (usePromptService) {
- promptDone = handlePrompt(state, action);
-
- checkVal.value = false;
- isOK = prompter.promptAuth(window, channel, level, authinfo, "Check me out!", checkVal);
- is(isOK, true, "checked expected retval");
- is(authinfo.username, "username", "checking filled username");
- is(authinfo.password, "password", "checking filled password");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
- }
-
-
- // =====
- // (promptAuth is only accessible from the prompt service)
- info("Starting test: promptAuth with long realm");
- state = {
- msg : 'http://example.com is requesting your username and password. The site ' +
- 'says: \u201cabcdefghi abcdefghi abcdefghi abcdefghi abcdefghi abcdefghi abcdefghi ' +
- 'abcdefghi abcdefghi abcdefghi abcdefghi abcdefghi abcdefghi abcdefghi ' +
- 'abcdefghi \u2026\u201d',
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- setCheckbox : true,
- textField : "username",
- passField : "password",
- };
- if (usePromptService) {
- promptDone = handlePrompt(state, action);
-
- checkVal.value = false;
- var longString = "";
- for (var i = 0; i < 20; i++)
- longString += "abcdefghi "; // 200 chars long
- authinfo.realm = longString;
- authinfo.username = "";
- authinfo.password = "";
- isOK = prompter.promptAuth(window, channel, level, authinfo, "Check me out!", checkVal);
- is(isOK, true, "checked expected retval");
- is(authinfo.username, "username", "checking filled username");
- is(authinfo.password, "password", "checking filled password");
- is(checkVal.value, true, "expected checkbox setting");
-
- yield promptDone;
- }
-
- info("Starting test: promptAuth for a cross-origin and a empty realm");
- authinfo = {
- username : "",
- password : "",
- domain : "",
- flags : Ci. nsIAuthInformation.AUTH_HOST |
- Ci.nsIAuthInformation.CROSS_ORIGIN_SUB_RESOURCE,
- authenticationScheme : "basic",
- realm : ""
- }
- state = {
- msg : 'http://example.com is requesting your username and password. ' +
- 'WARNING: Your password will not be sent to the website you are currently visiting!',
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- setCheckbox : false,
- textField : "username",
- passField : "password",
- };
- if (usePromptService) {
- promptDone = handlePrompt(state, action);
- checkVal.value = false;
- isOK = prompter.promptAuth(window, channel, level, authinfo, "Check me out!", checkVal);
- is(isOK, true, "checked expected retval");
- is(authinfo.username, "username", "checking filled username");
- is(authinfo.password, "password", "checking filled password");
- is(checkVal.value, false, "expected checkbox setting");
-
- yield promptDone;
- }
-
- info("Starting test: promptAuth for a cross-origin with realm");
- authinfo = {
- username : "",
- password : "",
- domain : "",
- flags : Ci. nsIAuthInformation.AUTH_HOST | Ci.nsIAuthInformation.CROSS_ORIGIN_SUB_RESOURCE,
- authenticationScheme : "basic",
- realm : "Something!!!"
- }
- state = {
- msg : 'http://example.com is requesting your username and password. ' +
- 'WARNING: Your password will not be sent to the website you are currently visiting!',
- title : "TestTitle",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : false,
- textValue : "",
- passValue : "",
- checkMsg : "Check me out!",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
- action = {
- buttonClick : "ok",
- setCheckbox : false,
- textField : "username",
- passField : "password",
- };
- if (usePromptService) {
- promptDone = handlePrompt(state, action);
-
- checkVal.value = false;
- isOK = prompter.promptAuth(window, channel, level, authinfo, "Check me out!", checkVal);
- is(isOK, true, "checked expected retval");
- is(authinfo.username, "username", "checking filled username");
- is(authinfo.password, "password", "checking filled password");
- is(checkVal.value, false, "expected checkbox setting");
-
- yield promptDone;
- }
-}
-
-let usePromptService;
-
-/*
- * Run the body of the 3 times:
- * - 1st pass: with window-modal prompts, using nsIPromptService
- * - 2nd pass: still window-modal, using nsIPrompt directly (via nsIPromptFactory)
- * - 3rd pass: with tab-modal prompts. Can't opt into these via * nsIPromptService.
- */
-
-add_task(function* runPromptTests() {
- info("Process type: " + SpecialPowers.Services.appinfo.processType);
-
- isTabModal = false; usePromptService = true;
- info("Running tests with: isTabModal=" + isTabModal + ", usePromptService=" + usePromptService);
- yield* runTests();
-
- isTabModal = false; usePromptService = false;
- info("Running tests with: isTabModal=" + isTabModal + ", usePromptService=" + usePromptService);
- yield* runTests();
-
- if (SpecialPowers.getBoolPref("prompts.tab_modal.enabled")) {
- isTabModal = true; usePromptService = false;
- info("Running tests with: isTabModal=" + isTabModal + ", usePromptService=" + usePromptService);
- yield* runTests();
- }
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/prompts/test/test_modal_select.html b/toolkit/components/prompts/test/test_modal_select.html
deleted file mode 100644
index 1e008d0f4..000000000
--- a/toolkit/components/prompts/test/test_modal_select.html
+++ /dev/null
@@ -1,146 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Modal Prompts Test</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Prompter tests: modal prompts
-<p id="display"></p>
-
-<div id="content" style="display: none">
- <iframe id="iframe"></iframe>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.8">
-
-let prompter = Cc["@mozilla.org/embedcomp/prompt-service;1"].
- getService(Ci.nsIPromptService2);
-
-function checkPromptState(promptState, expectedState) {
- // XXX check title? OS X has title in content
- // XXX check focused element
- // XXX check button labels?
-
- is(promptState.msg, expectedState.msg, "Checking expected message");
-
- // Compare listbox contents
- is(promptState.items.length, expectedState.items.length, "Checking listbox length");
-
- if (promptState.items.length)
- is(promptState.selectedIndex, 0, "Checking selected index");
-
- for (let i = 0; i < promptState.items; i++) {
- is(promptState.items[i], expectedState.items[i], "Checking list item #" + i);
- }
-}
-
-let selectVal = {};
-let isOK;
-let state, action;
-
-function handlePrompt(state, action) {
- return new Promise(resolve => {
- gChromeScript.addMessageListener("promptHandled", function handled(msg) {
- gChromeScript.removeMessageListener("promptHandled", handled);
- checkPromptState(msg.promptState, state);
- resolve(true);
- });
- gChromeScript.sendAsyncMessage("handlePrompt", { action: action, isSelect: true});
- });
-}
-
-
-// =====
-add_task(function* test_select_empty_list() {
- info("Starting test: Select (0 items, ok)");
- state = {
- msg : "This is the select text.",
- title : "TestTitle",
- items : [],
- };
- action = {
- buttonClick: "ok",
- };
- promptDone = handlePrompt(state, action);
- items = [];
- selectVal.value = null; // outparam, just making sure.
- isOK = prompter.select(window, "TestTitle", "This is the select text.", items.length, items, selectVal);
- is(isOK, true, "checked expected retval");
- is(selectVal.value, -1, "checking selected index");
-
- yield promptDone;
-});
-
-// =====
-add_task(function* test_select_ok() {
- info("Starting test: Select (3 items, ok)");
- state = {
- msg : "This is the select text.",
- title : "TestTitle",
- items : ["one", "two", "three"],
- };
- action = {
- buttonClick: "ok",
- };
- promptDone = handlePrompt(state, action);
- items = ["one", "two", "three"];
- selectVal.value = null; // outparam, just making sure.
- isOK = prompter.select(window, "TestTitle", "This is the select text.", items.length, items, selectVal);
- is(isOK, true, "checked expected retval");
- is(selectVal.value, 0, "checking selected index");
-
- yield promptDone;
-});
-
-// =====
-add_task(function* test_select_item() {
- info("Starting test: Select (3 items, selection changed, ok)");
- state = {
- msg : "This is the select text.",
- title : "TestTitle",
- items : ["one", "two", "three"],
- };
- action = {
- buttonClick: "ok",
- selectItem: 1,
- };
- promptDone = handlePrompt(state, action);
- items = ["one", "two", "three"];
- selectVal.value = null; // outparam, just making sure.
- isOK = prompter.select(window, "TestTitle", "This is the select text.", items.length, items, selectVal);
- is(isOK, true, "checked expected retval");
- is(selectVal.value, 1, "checking selected index");
-
- yield promptDone;
-});
-
-// =====
-add_task(function* test_cancel_prompt() {
- info("Starting test: Select (3 items, cancel)");
- state = {
- msg : "This is the select text.",
- title : "TestTitle",
- items : ["one", "two", "three"],
- };
- action = {
- buttonClick: "cancel",
- };
- promptDone = handlePrompt(state, action);
- items = ["one", "two", "three"];
- selectVal.value = null; // outparam, just making sure.
- isOK = prompter.select(window, "TestTitle", "This is the select text.", items.length, items, selectVal);
- is(isOK, false, "checked expected retval");
- is(selectVal.value, 0, "checking selected index");
-
- yield promptDone;
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/prompts/test/test_subresources_prompts.html b/toolkit/components/prompts/test/test_subresources_prompts.html
deleted file mode 100644
index 241ce430f..000000000
--- a/toolkit/components/prompts/test/test_subresources_prompts.html
+++ /dev/null
@@ -1,202 +0,0 @@
-<html>
-<head>
- <title>Test subresources prompts (Bug 625187 and bug 1230462)</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="prompt_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
-<!--
- - Any copyright is dedicated to the Public Domain.
- - http://creativecommons.org/publicdomain/zero/1.0/
- -
- - Contributor(s):
- - Mihai Sucan <mihai.sucan@gmail.com>
- -->
-</head>
-<body>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=625187">Mozilla Bug 625187</a>
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1230462">Mozilla Bug 1230462</a>
-
-<p><button onclick="alert('hello world')">Button</button></p>
-
-<iframe id="iframe_diff_origin" src="http://example.com/tests/toolkit/components/prompts/test/bug625187_iframe.html"></iframe>
-
-<iframe id="iframe_same_origin" src="bug625187_iframe.html"></iframe>
-
-<iframe id="iframe_prompt"></iframe>
-
-<pre id="test"></pre>
-
-<script class="testbody" type="text/javascript">
-var iframe1Loaded = onloadPromiseFor("iframe_diff_origin");
-var iframe2Loaded = onloadPromiseFor("iframe_same_origin");
-var iframe_prompt = document.getElementById("iframe_prompt");
-
-add_task(function* runTest()
-{
- // This test depends on tab modal prompts being enabled.
- if (!isTabModal) {
- todo(false, "Test disabled when tab modal prompts are not enabled.");
- return;
- }
-
- info("Ensuring iframe1 has loaded...");
- yield iframe1Loaded;
- info("Ensuring iframe2 has loaded...");
- yield iframe2Loaded;
- let state, action;
-
- state = {
- msg : "hello world",
- iconClass : "alert-icon",
- titleHidden : true,
- textHidden : true,
- passHidden : true,
- checkHidden : true,
- textValue : "",
- passValue : "",
- checkMsg : "",
- checked : false,
- focused : "button0",
- defButton : "button0",
- };
- action = {
- buttonClick: "ok",
- };
-
- promptDone = handlePrompt(state, action);
-
- var button = document.querySelector("button");
- dispatchMouseEvent(button, "click");
-
- yield promptDone;
-
-
- // mostly reusing same state/action
- state.titleHidden = false;
- state.msg = "hello world 2";
- promptDone = handlePrompt(state, action);
-
- var iframe = document.getElementById("iframe_diff_origin");
- button = SpecialPowers.wrap(iframe.contentWindow).document.getElementById("btn1");
- dispatchMouseEvent(button, "click");
-
- yield promptDone;
-
-
- // mostly reusing same state/action
- state.titleHidden = true;
- state.msg = "hello world 2";
- promptDone = handlePrompt(state, action);
-
- iframe = document.getElementById("iframe_same_origin");
- button = iframe.contentWindow.document.getElementById("btn1");
- dispatchMouseEvent(button, "click");
-
- yield promptDone;
-
-
- // mostly reusing same state/action
- state.msg = "hello world 3";
- promptDone = handlePrompt(state, action);
-
- button = iframe.contentWindow.document.getElementById("btn2");
- dispatchMouseEvent(button, "click");
-
- yield promptDone;
-});
-
-add_task(function* runTestAuth()
-{
- // Following tests chack prompt message for a cross-origin and not
- // cross-origin subresources load
-
- // Force parent to not look for tab-modal prompts, as they're not
- // used for auth prompts.
- isTabModal = false;
-
- state = {
- msg : "http://mochi.test:8888 is requesting your username " +
- "and password. The site says: “mochitest”",
- title : "Authentication Required",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
-
- action = {
- buttonClick : "ok",
- setCheckbox : false,
- textField : "mochiuser1",
- passField : "mochipass1",
- };
-
- promptDone = handlePrompt(state, action);
-
- var iframe3Loaded = onloadPromiseFor("iframe_prompt");
- iframe_prompt.src = "authenticate.sjs?user=mochiuser1&pass=mochipass1";
- yield promptDone;
- yield iframe3Loaded;
- checkEchoedAuthInfo({user: "mochiuser1", pass: "mochipass1"},
- iframe_prompt.contentDocument);
-
- // Cross-origin subresourse test.
-
- // Force parent to not look for tab-modal prompts, as they're not used for auth prompts.
- isTabModal =false;
- state = {
- msg : "http://example.com is requesting your username and password. " +
- "WARNING: Your password will not be sent to the website you are currently visiting!",
- title : "Authentication Required",
- textValue : "",
- passValue : "",
- iconClass : "authentication-icon question-icon",
- titleHidden : true,
- textHidden : false,
- passHidden : false,
- checkHidden : true,
- checkMsg : "",
- checked : false,
- focused : "textField",
- defButton : "button0",
- };
-
- action = {
- buttonClick : "ok",
- setCheckbox : false,
- textField : "mochiuser2",
- passField : "mochipass2",
- };
-
- promptDone = handlePrompt(state, action);
-
- iframe3Loaded = onloadPromiseFor("iframe_prompt");
- iframe_prompt.src = "http://example.com/tests/toolkit/components/prompts/test/authenticate.sjs?user=mochiuser2&pass=mochipass2&realm=mochitest";
- yield promptDone;
- yield iframe3Loaded;
- checkEchoedAuthInfo({user: "mochiuser2", pass: "mochipass2"},
- SpecialPowers.wrap(iframe_prompt.contentWindow).document);
-});
-
-function dispatchMouseEvent(target, type)
-{
- var win = SpecialPowers.unwrap(target.ownerDocument.defaultView);
- var e = document.createEvent("MouseEvent");
- e.initEvent(type, false, false, win, 0, 1, 1, 1, 1,
- false, false, false, false, 0, null);
- var utils = SpecialPowers.getDOMWindowUtils(win);
- utils.dispatchDOMEventViaPresShell(SpecialPowers.unwrap(target), e, true);
-}
-</script>
-</body>
-</html>
diff --git a/toolkit/components/reader/moz.build b/toolkit/components/reader/moz.build
index d49bda14f..4ffca0421 100644
--- a/toolkit/components/reader/moz.build
+++ b/toolkit/components/reader/moz.build
@@ -11,9 +11,7 @@ EXTRA_JS_MODULES += [
'ReaderMode.jsm'
]
-EXTRA_PP_JS_MODULES += [
- 'Readerable.jsm'
-]
+EXTRA_PP_JS_MODULES += ['Readerable.jsm']
EXTRA_JS_MODULES.reader = [
'JSDOMParser.js',
@@ -21,10 +19,3 @@ EXTRA_JS_MODULES.reader = [
'ReaderWorker.js',
'ReaderWorker.jsm'
]
-
-BROWSER_CHROME_MANIFESTS += [
- 'test/browser.ini'
-]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Reader Mode')
diff --git a/toolkit/components/reader/test/browser.ini b/toolkit/components/reader/test/browser.ini
deleted file mode 100644
index 4f9df23b3..000000000
--- a/toolkit/components/reader/test/browser.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-support-files = head.js
-[browser_readerMode.js]
-support-files =
- readerModeArticle.html
- readerModeArticleHiddenNodes.html
-[browser_readerMode_hidden_nodes.js]
-support-files =
- readerModeArticleHiddenNodes.html
-[browser_readerMode_with_anchor.js]
-support-files =
- readerModeArticle.html
-[browser_bug1124271_readerModePinnedTab.js]
-support-files =
- readerModeArticle.html
diff --git a/toolkit/components/reader/test/browser_bug1124271_readerModePinnedTab.js b/toolkit/components/reader/test/browser_bug1124271_readerModePinnedTab.js
deleted file mode 100644
index 39913aa3e..000000000
--- a/toolkit/components/reader/test/browser_bug1124271_readerModePinnedTab.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-// Test that the reader mode button won't open in a new tab when clicked from a pinned tab
-
-const PREF = "reader.parse-on-load.enabled";
-
-const TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
-
-var readerButton = document.getElementById("reader-mode-button");
-
-add_task(function* () {
- registerCleanupFunction(function() {
- Services.prefs.clearUserPref(PREF);
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
- });
-
- // Enable the reader mode button.
- Services.prefs.setBoolPref(PREF, true);
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- gBrowser.pinTab(tab);
-
- let initialTabsCount = gBrowser.tabs.length;
-
- // Point tab to a test page that is reader-able.
- let url = TEST_PATH + "readerModeArticle.html";
- yield promiseTabLoadEvent(tab, url);
- yield promiseWaitForCondition(() => !readerButton.hidden);
-
- readerButton.click();
- yield promiseTabLoadEvent(tab);
-
- // Ensure no new tabs are opened when exiting reader mode in a pinned tab
- is(gBrowser.tabs.length, initialTabsCount, "No additional tabs were opened.");
-
- let pageShownPromise = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- readerButton.click();
- yield pageShownPromise;
- // Ensure no new tabs are opened when exiting reader mode in a pinned tab
- is(gBrowser.tabs.length, initialTabsCount, "No additional tabs were opened.");
-
- gBrowser.removeCurrentTab();
-});
diff --git a/toolkit/components/reader/test/browser_readerMode.js b/toolkit/components/reader/test/browser_readerMode.js
deleted file mode 100644
index 70290c3b5..000000000
--- a/toolkit/components/reader/test/browser_readerMode.js
+++ /dev/null
@@ -1,220 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 the reader mode button appears and works properly on
- * reader-able content.
- */
-const TEST_PREFS = [
- ["reader.parse-on-load.enabled", true],
-];
-
-const TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
-
-var readerButton = document.getElementById("reader-mode-button");
-
-add_task(function* test_reader_button() {
- registerCleanupFunction(function() {
- // Reset test prefs.
- TEST_PREFS.forEach(([name, value]) => {
- Services.prefs.clearUserPref(name);
- });
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
- });
-
- // Set required test prefs.
- TEST_PREFS.forEach(([name, value]) => {
- Services.prefs.setBoolPref(name, value);
- });
- Services.prefs.setBoolPref("browser.reader.detectedFirstArticle", false);
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- is_element_hidden(readerButton, "Reader mode button is not present on a new tab");
- ok(!UITour.isInfoOnTarget(window, "readerMode-urlBar"),
- "Info panel shouldn't appear without the reader mode button");
- ok(!Services.prefs.getBoolPref("browser.reader.detectedFirstArticle"),
- "Shouldn't have detected the first article");
-
- // We're going to show the reader mode intro popup, make sure we wait for it:
- let tourPopupShownPromise =
- BrowserTestUtils.waitForEvent(document.getElementById("UITourTooltip"), "popupshown");
- // Point tab to a test page that is reader-able.
- let url = TEST_PATH + "readerModeArticle.html";
- yield promiseTabLoadEvent(tab, url);
- yield promiseWaitForCondition(() => !readerButton.hidden);
- yield tourPopupShownPromise;
- is_element_visible(readerButton, "Reader mode button is present on a reader-able page");
- ok(UITour.isInfoOnTarget(window, "readerMode-urlBar"),
- "Info panel should be anchored at the reader mode button");
- ok(Services.prefs.getBoolPref("browser.reader.detectedFirstArticle"),
- "Should have detected the first article");
-
- // Switch page into reader mode.
- readerButton.click();
- yield promiseTabLoadEvent(tab);
- ok(!UITour.isInfoOnTarget(window, "readerMode-urlBar"), "Info panel should have closed");
-
- let readerUrl = gBrowser.selectedBrowser.currentURI.spec;
- ok(readerUrl.startsWith("about:reader"), "about:reader loaded after clicking reader mode button");
- is_element_visible(readerButton, "Reader mode button is present on about:reader");
-
- is(gURLBar.value, readerUrl, "gURLBar value is about:reader URL");
- is(gURLBar.textValue, url.substring("http://".length), "gURLBar is displaying original article URL");
-
- // Check selected value for URL bar
- yield new Promise((resolve, reject) => {
- waitForClipboard(url, function () {
- gURLBar.focus();
- gURLBar.select();
- goDoCommand("cmd_copy");
- }, resolve, reject);
- });
-
- info("Got correct URL when copying");
-
- // Switch page back out of reader mode.
- let promisePageShow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- readerButton.click();
- yield promisePageShow;
- is(gBrowser.selectedBrowser.currentURI.spec, url,
- "Back to the original page after clicking active reader mode button");
- ok(gBrowser.selectedBrowser.canGoForward,
- "Moved one step back in the session history.");
-
- // Load a new tab that is NOT reader-able.
- let newTab = gBrowser.selectedTab = gBrowser.addTab();
- yield promiseTabLoadEvent(newTab, "about:robots");
- yield promiseWaitForCondition(() => readerButton.hidden);
- is_element_hidden(readerButton, "Reader mode button is not present on a non-reader-able page");
-
- // Switch back to the original tab to make sure reader mode button is still visible.
- gBrowser.removeCurrentTab();
- yield promiseWaitForCondition(() => !readerButton.hidden);
- is_element_visible(readerButton, "Reader mode button is present on a reader-able page");
-});
-
-add_task(function* test_getOriginalUrl() {
- let { ReaderMode } = Cu.import("resource://gre/modules/ReaderMode.jsm", {});
- let url = "http://foo.com/article.html";
-
- is(ReaderMode.getOriginalUrl("about:reader?url=" + encodeURIComponent(url)), url, "Found original URL from encoded URL");
- is(ReaderMode.getOriginalUrl("about:reader?foobar"), null, "Did not find original URL from malformed reader URL");
- is(ReaderMode.getOriginalUrl(url), null, "Did not find original URL from non-reader URL");
-
- let badUrl = "http://foo.com/?;$%^^";
- is(ReaderMode.getOriginalUrl("about:reader?url=" + encodeURIComponent(badUrl)), badUrl, "Found original URL from encoded malformed URL");
- is(ReaderMode.getOriginalUrl("about:reader?url=" + badUrl), badUrl, "Found original URL from non-encoded malformed URL");
-});
-
-add_task(function* test_reader_view_element_attribute_transform() {
- registerCleanupFunction(function() {
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
- });
-
- function observeAttribute(element, attribute, triggerFn, checkFn) {
- return new Promise(resolve => {
- let observer = new MutationObserver((mutations) => {
- mutations.forEach( mu => {
- if (element.getAttribute(attribute) !== mu.oldValue) {
- checkFn();
- resolve();
- observer.disconnect();
- }
- });
- });
-
- observer.observe(element, {
- attributes: true,
- attributeOldValue: true,
- attributeFilter: [attribute]
- });
-
- triggerFn();
- });
- }
-
- let command = document.getElementById("View:ReaderView");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
- is(command.hidden, true, "Command element should have the hidden attribute");
-
- info("Navigate a reader-able page");
- let waitForPageshow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- yield observeAttribute(command, "hidden",
- () => {
- let url = TEST_PATH + "readerModeArticle.html";
- tab.linkedBrowser.loadURI(url);
- },
- () => {
- is(command.hidden, false, "Command's hidden attribute should be false on a reader-able page");
- }
- );
- yield waitForPageshow;
-
- info("Navigate a non-reader-able page");
- waitForPageshow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- yield observeAttribute(command, "hidden",
- () => {
- let url = TEST_PATH + "readerModeArticleHiddenNodes.html";
- tab.linkedBrowser.loadURI(url);
- },
- () => {
- is(command.hidden, true, "Command's hidden attribute should be true on a non-reader-able page");
- }
- );
- yield waitForPageshow;
-
- info("Navigate a reader-able page");
- waitForPageshow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- yield observeAttribute(command, "hidden",
- () => {
- let url = TEST_PATH + "readerModeArticle.html";
- tab.linkedBrowser.loadURI(url);
- },
- () => {
- is(command.hidden, false, "Command's hidden attribute should be false on a reader-able page");
- }
- );
- yield waitForPageshow;
-
- info("Enter Reader Mode");
- waitForPageshow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- yield observeAttribute(readerButton, "readeractive",
- () => {
- readerButton.click();
- },
- () => {
- is(readerButton.getAttribute("readeractive"), "true", "readerButton's readeractive attribute should be true when entering reader mode");
- }
- );
- yield waitForPageshow;
-
- info("Exit Reader Mode");
- waitForPageshow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- yield observeAttribute(readerButton, "readeractive",
- () => {
- readerButton.click();
- },
- () => {
- is(readerButton.getAttribute("readeractive"), "", "readerButton's readeractive attribute should be empty when reader mode is exited");
- }
- );
- yield waitForPageshow;
-
- info("Navigate a non-reader-able page");
- waitForPageshow = BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "pageshow");
- yield observeAttribute(command, "hidden",
- () => {
- let url = TEST_PATH + "readerModeArticleHiddenNodes.html";
- tab.linkedBrowser.loadURI(url);
- },
- () => {
- is(command.hidden, true, "Command's hidden attribute should be true on a non-reader-able page");
- }
- );
- yield waitForPageshow;
-});
diff --git a/toolkit/components/reader/test/browser_readerMode_hidden_nodes.js b/toolkit/components/reader/test/browser_readerMode_hidden_nodes.js
deleted file mode 100644
index b73eab58d..000000000
--- a/toolkit/components/reader/test/browser_readerMode_hidden_nodes.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Test that the reader mode button appears and works properly on
- * reader-able content.
- */
-const TEST_PREFS = [
- ["reader.parse-on-load.enabled", true],
- ["browser.reader.detectedFirstArticle", false],
-];
-
-const TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
-
-var readerButton = document.getElementById("reader-mode-button");
-
-add_task(function* test_reader_button() {
- registerCleanupFunction(function() {
- // Reset test prefs.
- TEST_PREFS.forEach(([name, value]) => {
- Services.prefs.clearUserPref(name);
- });
- while (gBrowser.tabs.length > 1) {
- gBrowser.removeCurrentTab();
- }
- });
-
- // Set required test prefs.
- TEST_PREFS.forEach(([name, value]) => {
- Services.prefs.setBoolPref(name, value);
- });
-
- let tab = gBrowser.selectedTab = gBrowser.addTab();
- is_element_hidden(readerButton, "Reader mode button is not present on a new tab");
- // Point tab to a test page that is not reader-able due to hidden nodes.
- let url = TEST_PATH + "readerModeArticleHiddenNodes.html";
- let paintPromise = ContentTask.spawn(tab.linkedBrowser, "", function() {
- return new Promise(resolve => {
- addEventListener("DOMContentLoaded", function onDCL() {
- removeEventListener("DOMContentLoaded", onDCL);
- addEventListener("MozAfterPaint", function onPaint() {
- removeEventListener("MozAfterPaint", onPaint);
- resolve();
- });
- });
- });
- });
- tab.linkedBrowser.loadURI(url);
- yield paintPromise;
-
- is_element_hidden(readerButton, "Reader mode button is still not present on tab with unreadable content.");
-});
diff --git a/toolkit/components/reader/test/browser_readerMode_with_anchor.js b/toolkit/components/reader/test/browser_readerMode_with_anchor.js
deleted file mode 100644
index 24c23c49f..000000000
--- a/toolkit/components/reader/test/browser_readerMode_with_anchor.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 TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
-
-add_task(function* () {
- yield BrowserTestUtils.withNewTab(TEST_PATH + "readerModeArticle.html#foo", function* (browser) {
- let pageShownPromise = BrowserTestUtils.waitForContentEvent(browser, "AboutReaderContentReady");
- let readerButton = document.getElementById("reader-mode-button");
- readerButton.click();
- yield pageShownPromise;
- yield ContentTask.spawn(browser, null, function* () {
- // Check if offset != 0
- ok(content.document.getElementById("foo") !== null, "foo element should be in document");
- ok(content.pageYOffset != 0, "pageYOffset should be > 0");
- });
- });
-});
diff --git a/toolkit/components/reader/test/head.js b/toolkit/components/reader/test/head.js
deleted file mode 100644
index 3d8d989bc..000000000
--- a/toolkit/components/reader/test/head.js
+++ /dev/null
@@ -1,126 +0,0 @@
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-
-/* exported promiseTabLoadEvent, promiseWaitForCondition, is_element_visible, is_element_hidden */
-
-/**
- * Waits for a load (or custom) event to finish in a given tab. If provided
- * load an uri into the tab.
- *
- * @param tab
- * The tab to load into.
- * @param [optional] url
- * The url to load, or the current url.
- * @return {Promise} resolved when the event is handled.
- * @resolves to the received event
- * @rejects if a valid load event is not received within a meaningful interval
- */
-function promiseTabLoadEvent(tab, url) {
- let deferred = Promise.defer();
- info("Wait tab event: load");
-
- function handle(loadedUrl) {
- if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) {
- info(`Skipping spurious load event for ${loadedUrl}`);
- return false;
- }
-
- info("Tab event received: load");
- return true;
- }
-
- // Create two promises: one resolved from the content process when the page
- // loads and one that is rejected if we take too long to load the url.
- let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle);
-
- let timeout = setTimeout(() => {
- deferred.reject(new Error("Timed out while waiting for a 'load' event"));
- }, 30000);
-
- loaded.then(() => {
- clearTimeout(timeout);
- deferred.resolve();
- });
-
- if (url)
- BrowserTestUtils.loadURI(tab.linkedBrowser, url);
-
- // Promise.all rejects if either promise rejects (i.e. if we time out) and
- // if our loaded promise resolves before the timeout, then we resolve the
- // timeout promise as well, causing the all promise to resolve.
- return Promise.all([deferred.promise, loaded]);
-}
-
-function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
- retryTimes = typeof retryTimes !== 'undefined' ? retryTimes : 30;
- var tries = 0;
- var interval = setInterval(function() {
- if (tries >= retryTimes) {
- ok(false, errorMsg);
- moveOn();
- }
- var conditionPassed;
- try {
- conditionPassed = condition();
- } catch (e) {
- ok(false, e + "\n" + e.stack);
- conditionPassed = false;
- }
- if (conditionPassed) {
- moveOn();
- }
- tries++;
- }, 100);
- var moveOn = function() {
- clearInterval(interval);
- nextTest();
- };
-}
-
-function promiseWaitForCondition(aConditionFn) {
- let deferred = Promise.defer();
- waitForCondition(aConditionFn, deferred.resolve, "Condition didn't pass.");
- return deferred.promise;
-}
-
-function is_element_visible(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_visible(element), msg || "Element should be visible");
-
-}
-function is_element_hidden(element, msg) {
- isnot(element, null, "Element should not be null, when checking visibility");
- ok(is_hidden(element), msg || "Element should be hidden");
-}
-
-function is_visible(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return false;
- if (style.visibility != "visible")
- return false;
- if (style.display == "-moz-popup" && element.state != "open")
- return false;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_visible(element.parentNode);
-
- return true;
-}
-
-function is_hidden(element) {
- var style = element.ownerGlobal.getComputedStyle(element);
- if (style.display == "none")
- return true;
- if (style.visibility != "visible")
- return true;
- if (style.display == "-moz-popup")
- return ["hiding", "closed"].indexOf(element.state) != -1;
-
- // Hiding a parent element will hide all its children
- if (element.parentNode != element.ownerDocument)
- return is_hidden(element.parentNode);
-
- return false;
-}
diff --git a/toolkit/components/reader/test/readerModeArticle.html b/toolkit/components/reader/test/readerModeArticle.html
deleted file mode 100644
index 7c5033d5b..000000000
--- a/toolkit/components/reader/test/readerModeArticle.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<title>Article title</title>
-<meta name="description" content="This is the article description." />
-</head>
-<body>
-<header>Site header</header>
-<div>
-<h1>Article title</h1>
-<h2 class="author">by Jane Doe</h2>
-<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<div id="foo">by John Doe</div>
-<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-</div>
-</body>
-</html>
diff --git a/toolkit/components/reader/test/readerModeArticleHiddenNodes.html b/toolkit/components/reader/test/readerModeArticleHiddenNodes.html
deleted file mode 100644
index 92441b797..000000000
--- a/toolkit/components/reader/test/readerModeArticleHiddenNodes.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
-<title>Article title</title>
-<meta name="description" content="This is the article description." />
-</head>
-<body>
-<style>
-p { display: none }
-</style>
-<header>Site header</header>
-<div>
-<h1>Article title</h1>
-<h2 class="author">by Jane Doe</h2>
-<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p>
-</div>
-</body>
-</html>
diff --git a/toolkit/components/remotebrowserutils/moz.build b/toolkit/components/remotebrowserutils/moz.build
index 9cfc4a976..47ee6a483 100644
--- a/toolkit/components/remotebrowserutils/moz.build
+++ b/toolkit/components/remotebrowserutils/moz.build
@@ -8,5 +8,3 @@ EXTRA_COMPONENTS += [
'remotebrowserutils.manifest',
'RemoteWebNavigation.js',
]
-
-BROWSER_CHROME_MANIFESTS += ['tests/browser/browser.ini']
diff --git a/toolkit/components/remotebrowserutils/tests/browser/.eslintrc.js b/toolkit/components/remotebrowserutils/tests/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/remotebrowserutils/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/remotebrowserutils/tests/browser/browser.ini b/toolkit/components/remotebrowserutils/tests/browser/browser.ini
deleted file mode 100644
index 916d0f9cb..000000000
--- a/toolkit/components/remotebrowserutils/tests/browser/browser.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-run-if = e10s
-support-files =
- dummy_page.html
-
-[browser_RemoteWebNavigation.js]
diff --git a/toolkit/components/remotebrowserutils/tests/browser/browser_RemoteWebNavigation.js b/toolkit/components/remotebrowserutils/tests/browser/browser_RemoteWebNavigation.js
deleted file mode 100644
index 106758e81..000000000
--- a/toolkit/components/remotebrowserutils/tests/browser/browser_RemoteWebNavigation.js
+++ /dev/null
@@ -1,156 +0,0 @@
-/* eslint-env mozilla/frame-script */
-
-const DUMMY1 = "http://example.com/browser/toolkit/modules/tests/browser/dummy_page.html";
-const DUMMY2 = "http://example.org/browser/toolkit/modules/tests/browser/dummy_page.html"
-
-function waitForLoad(uri) {
- return BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, uri);
-}
-
-function waitForPageShow(browser = gBrowser.selectedBrowser) {
- return BrowserTestUtils.waitForContentEvent(browser, "pageshow", true);
-}
-
-function makeURI(url) {
- return Cc["@mozilla.org/network/io-service;1"].
- getService(Ci.nsIIOService).
- newURI(url, null, null);
-}
-
-// Tests that loadURI accepts a referrer and it is included in the load.
-add_task(function* test_referrer() {
- gBrowser.selectedTab = gBrowser.addTab();
- let browser = gBrowser.selectedBrowser;
-
- browser.webNavigation.loadURI(DUMMY1,
- Ci.nsIWebNavigation.LOAD_FLAGS_NONE,
- makeURI(DUMMY2),
- null, null);
- yield waitForLoad(DUMMY1);
-
- yield ContentTask.spawn(browser, [ DUMMY1, DUMMY2 ], function([dummy1, dummy2]) {
- is(content.location.href, dummy1, "Should have loaded the right URL");
- is(content.document.referrer, dummy2, "Should have the right referrer");
- });
-
- gBrowser.removeCurrentTab();
-});
-
-// Tests that remote access to webnavigation.sessionHistory works.
-add_task(function* test_history() {
- function checkHistoryIndex(browser, n) {
- return ContentTask.spawn(browser, n, function(n) {
- let history = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
- is(history.index, n, "Should be at the right place in history");
- });
- }
- gBrowser.selectedTab = gBrowser.addTab();
- let browser = gBrowser.selectedBrowser;
-
- browser.webNavigation.loadURI(DUMMY1,
- Ci.nsIWebNavigation.LOAD_FLAGS_NONE,
- null, null, null);
- yield waitForLoad(DUMMY1);
-
- browser.webNavigation.loadURI(DUMMY2,
- Ci.nsIWebNavigation.LOAD_FLAGS_NONE,
- null, null, null);
- yield waitForLoad(DUMMY2);
-
- yield ContentTask.spawn(browser, [DUMMY1, DUMMY2], function([dummy1, dummy2]) {
- let history = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
- is(history.count, 2, "Should be two history items");
- is(history.index, 1, "Should be at the right place in history");
- let entry = history.getEntryAtIndex(0, false);
- is(entry.URI.spec, dummy1, "Should have the right history entry");
- entry = history.getEntryAtIndex(1, false);
- is(entry.URI.spec, dummy2, "Should have the right history entry");
- });
-
- let promise = waitForPageShow();
- browser.webNavigation.goBack();
- yield promise;
- yield checkHistoryIndex(browser, 0);
-
- promise = waitForPageShow();
- browser.webNavigation.goForward();
- yield promise;
- yield checkHistoryIndex(browser, 1);
-
- promise = waitForPageShow();
- browser.webNavigation.gotoIndex(0);
- yield promise;
- yield checkHistoryIndex(browser, 0);
-
- gBrowser.removeCurrentTab();
-});
-
-// Tests that load flags are passed through to the content process.
-add_task(function* test_flags() {
- function checkHistory(browser, { count, index }) {
- return ContentTask.spawn(browser, [ DUMMY2, count, index ],
- function([ dummy2, count, index ]) {
- let history = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsISHistory);
- is(history.count, count, "Should be one history item");
- is(history.index, index, "Should be at the right place in history");
- let entry = history.getEntryAtIndex(index, false);
- is(entry.URI.spec, dummy2, "Should have the right history entry");
- });
- }
-
- gBrowser.selectedTab = gBrowser.addTab();
- let browser = gBrowser.selectedBrowser;
-
- browser.webNavigation.loadURI(DUMMY1,
- Ci.nsIWebNavigation.LOAD_FLAGS_NONE,
- null, null, null);
- yield waitForLoad(DUMMY1);
-
- browser.webNavigation.loadURI(DUMMY2,
- Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY,
- null, null, null);
- yield waitForLoad(DUMMY2);
- yield checkHistory(browser, { count: 1, index: 0 });
-
- browser.webNavigation.loadURI(DUMMY1,
- Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY,
- null, null, null);
- yield waitForLoad(DUMMY1);
- yield checkHistory(browser, { count: 1, index: 0 });
-
- gBrowser.removeCurrentTab();
-});
-
-// Tests that attempts to use unsupported arguments throw an exception.
-add_task(function* test_badarguments() {
- if (!gMultiProcessBrowser)
- return;
-
- gBrowser.selectedTab = gBrowser.addTab();
- let browser = gBrowser.selectedBrowser;
-
- try {
- browser.webNavigation.loadURI(DUMMY1,
- Ci.nsIWebNavigation.LOAD_FLAGS_NONE,
- null, {}, null);
- ok(false, "Should have seen an exception from trying to pass some postdata");
- }
- catch (e) {
- ok(true, "Should have seen an exception from trying to pass some postdata");
- }
-
- try {
- browser.webNavigation.loadURI(DUMMY1,
- Ci.nsIWebNavigation.LOAD_FLAGS_NONE,
- null, null, {});
- ok(false, "Should have seen an exception from trying to pass some headers");
- }
- catch (e) {
- ok(true, "Should have seen an exception from trying to pass some headers");
- }
-
- gBrowser.removeCurrentTab();
-});
diff --git a/toolkit/components/remotebrowserutils/tests/browser/dummy_page.html b/toolkit/components/remotebrowserutils/tests/browser/dummy_page.html
deleted file mode 100644
index c1c9a4e04..000000000
--- a/toolkit/components/remotebrowserutils/tests/browser/dummy_page.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<!DOCTYPE html>
-
-<html>
-<body>
-<p>Page</p>
-</body>
-</html>
diff --git a/toolkit/components/satchel/moz.build b/toolkit/components/satchel/moz.build
index 883ee9f23..920f4afff 100644
--- a/toolkit/components/satchel/moz.build
+++ b/toolkit/components/satchel/moz.build
@@ -4,10 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-MOCHITEST_MANIFESTS += ['test/mochitest.ini']
-XPCSHELL_TESTS_MANIFESTS += ['test/unit/xpcshell.ini']
-BROWSER_CHROME_MANIFESTS += ['test/browser/browser.ini']
-
XPIDL_SOURCES += [
'nsIFormAutoComplete.idl',
'nsIFormFillController.idl',
@@ -17,13 +13,9 @@ XPIDL_SOURCES += [
XPIDL_MODULE = 'satchel'
-SOURCES += [
- 'nsFormFillController.cpp',
-]
+SOURCES += ['nsFormFillController.cpp']
-LOCAL_INCLUDES += [
- '../build',
-]
+LOCAL_INCLUDES += ['../build']
EXTRA_COMPONENTS += [
'FormHistoryStartup.js',
diff --git a/toolkit/components/satchel/test/.eslintrc.js b/toolkit/components/satchel/test/.eslintrc.js
deleted file mode 100644
index 3c788d6d6..000000000
--- a/toolkit/components/satchel/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/mochitest.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/satchel/test/browser/.eslintrc.js b/toolkit/components/satchel/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/satchel/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/satchel/test/browser/browser.ini b/toolkit/components/satchel/test/browser/browser.ini
deleted file mode 100644
index 6a3fc452e..000000000
--- a/toolkit/components/satchel/test/browser/browser.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-[DEFAULT]
-support-files =
- !/toolkit/components/satchel/test/subtst_privbrowsing.html
-
-[browser_privbrowsing_perwindowpb.js]
diff --git a/toolkit/components/satchel/test/browser/browser_privbrowsing_perwindowpb.js b/toolkit/components/satchel/test/browser/browser_privbrowsing_perwindowpb.js
deleted file mode 100644
index 982480648..000000000
--- a/toolkit/components/satchel/test/browser/browser_privbrowsing_perwindowpb.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 FormHistory = (Components.utils.import("resource://gre/modules/FormHistory.jsm", {})).FormHistory;
-
-/** Test for Bug 472396 **/
-add_task(function* test() {
- // initialization
- let windowsToClose = [];
- let testURI =
- "http://example.com/tests/toolkit/components/satchel/test/subtst_privbrowsing.html";
-
- function* doTest(aShouldValueExist, aWindow) {
- let browser = aWindow.gBrowser.selectedBrowser;
- BrowserTestUtils.loadURI(browser, testURI);
- yield BrowserTestUtils.browserLoaded(browser);
-
- // Wait for the page to reload itself.
- yield BrowserTestUtils.browserLoaded(browser);
-
- let count = 0;
- let doneCounting = {};
- doneCounting.promise = new Promise(resolve => doneCounting.resolve = resolve);
- FormHistory.count({ fieldname: "field", value: "value" },
- {
- handleResult(result) {
- count = result;
- },
- handleError(error) {
- do_throw("Error occurred searching form history: " + error);
- },
- handleCompletion(num) {
- if (aShouldValueExist) {
- is(count, 1, "In non-PB mode, we add a single entry");
- } else {
- is(count, 0, "In PB mode, we don't add any entries");
- }
-
- doneCounting.resolve();
- }
- });
- yield doneCounting.promise;
- }
-
- function testOnWindow(aOptions, aCallback) {
- return BrowserTestUtils.openNewBrowserWindow(aOptions)
- .then(win => { windowsToClose.push(win); return win; });
- }
-
-
- yield testOnWindow({private: true}).then((aWin) => {
- return Task.spawn(doTest(false, aWin));
- });
-
- // Test when not on private mode after visiting a site on private
- // mode. The form history should not exist.
- yield testOnWindow({}).then((aWin) => {
- return Task.spawn(doTest(true, aWin));
- });
-
- yield Promise.all(windowsToClose.map(win => BrowserTestUtils.closeWindow(win)));
-});
diff --git a/toolkit/components/satchel/test/mochitest.ini b/toolkit/components/satchel/test/mochitest.ini
deleted file mode 100644
index 5a65baeb6..000000000
--- a/toolkit/components/satchel/test/mochitest.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[DEFAULT]
-skip-if = toolkit == 'android' || os == 'linux' # linux - bug 1022386
-support-files =
- satchel_common.js
- subtst_form_submission_1.html
- subtst_privbrowsing.html
- parent_utils.js
-
-[test_bug_511615.html]
-[test_bug_787624.html]
-[test_datalist_with_caching.html]
-[test_form_autocomplete.html]
-[test_form_autocomplete_with_list.html]
-[test_form_submission.html]
-[test_form_submission_cap.html]
-[test_form_submission_cap2.html]
-[test_password_autocomplete.html]
-[test_popup_direction.html]
-[test_popup_enter_event.html]
diff --git a/toolkit/components/satchel/test/parent_utils.js b/toolkit/components/satchel/test/parent_utils.js
deleted file mode 100644
index 87738bdb5..000000000
--- a/toolkit/components/satchel/test/parent_utils.js
+++ /dev/null
@@ -1,149 +0,0 @@
-const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/FormHistory.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://testing-common/ContentTaskUtils.jsm");
-
-var gAutocompletePopup = Services.ww.activeWindow.
- document.
- getElementById("PopupAutoComplete");
-assert.ok(gAutocompletePopup, "Got autocomplete popup");
-
-var ParentUtils = {
- getMenuEntries() {
- let entries = [];
- let numRows = gAutocompletePopup.view.matchCount;
- for (let i = 0; i < numRows; i++) {
- entries.push(gAutocompletePopup.view.getValueAt(i));
- }
- return entries;
- },
-
- cleanUpFormHist() {
- FormHistory.update({ op: "remove" });
- },
-
- updateFormHistory(changes) {
- let handler = {
- handleError: function (error) {
- assert.ok(false, error);
- sendAsyncMessage("formHistoryUpdated", { ok: false });
- },
- handleCompletion: function (reason) {
- if (!reason)
- sendAsyncMessage("formHistoryUpdated", { ok: true });
- },
- };
- FormHistory.update(changes, handler);
- },
-
- popupshownListener() {
- let results = this.getMenuEntries();
- sendAsyncMessage("onpopupshown", { results });
- },
-
- countEntries(name, value) {
- let obj = {};
- if (name)
- obj.fieldname = name;
- if (value)
- obj.value = value;
-
- let count = 0;
- let listener = {
- handleResult(result) { count = result },
- handleError(error) {
- assert.ok(false, error);
- sendAsyncMessage("entriesCounted", { ok: false });
- },
- handleCompletion(reason) {
- if (!reason) {
- sendAsyncMessage("entriesCounted", { ok: true, count });
- }
- }
- };
-
- FormHistory.count(obj, listener);
- },
-
- checkRowCount(expectedCount, expectedFirstValue = null) {
- ContentTaskUtils.waitForCondition(() => {
- // This may be called before gAutocompletePopup has initialised
- // which causes it to throw
- try {
- return gAutocompletePopup.view.matchCount === expectedCount &&
- (!expectedFirstValue ||
- expectedCount <= 1 ||
- gAutocompletePopup.view.getValueAt(0) === expectedFirstValue);
- } catch (e) {
- return false;
- }
- }, "Waiting for row count change: " + expectedCount + " First value: " + expectedFirstValue).then(() => {
- let results = this.getMenuEntries();
- sendAsyncMessage("gotMenuChange", { results });
- });
- },
-
- checkSelectedIndex(expectedIndex) {
- ContentTaskUtils.waitForCondition(() => {
- return gAutocompletePopup.popupOpen &&
- gAutocompletePopup.selectedIndex === expectedIndex;
- }, "Checking selected index").then(() => {
- sendAsyncMessage("gotSelectedIndex");
- });
- },
-
- getPopupState() {
- sendAsyncMessage("gotPopupState", {
- open: gAutocompletePopup.popupOpen,
- selectedIndex: gAutocompletePopup.selectedIndex,
- direction: gAutocompletePopup.style.direction,
- });
- },
-
- observe(subject, topic, data) {
- assert.ok(topic === "satchel-storage-changed");
- sendAsyncMessage("satchel-storage-changed", { subject: null, topic, data });
- },
-
- cleanup() {
- gAutocompletePopup.removeEventListener("popupshown", this._popupshownListener);
- this.cleanUpFormHist();
- }
-};
-
-ParentUtils._popupshownListener =
- ParentUtils.popupshownListener.bind(ParentUtils);
-gAutocompletePopup.addEventListener("popupshown", ParentUtils._popupshownListener);
-ParentUtils.cleanUpFormHist();
-
-addMessageListener("updateFormHistory", (msg) => {
- ParentUtils.updateFormHistory(msg.changes);
-});
-
-addMessageListener("countEntries", ({ name, value }) => {
- ParentUtils.countEntries(name, value);
-});
-
-addMessageListener("waitForMenuChange", ({ expectedCount, expectedFirstValue }) => {
- ParentUtils.checkRowCount(expectedCount, expectedFirstValue);
-});
-
-addMessageListener("waitForSelectedIndex", ({ expectedIndex }) => {
- ParentUtils.checkSelectedIndex(expectedIndex);
-});
-
-addMessageListener("getPopupState", () => {
- ParentUtils.getPopupState();
-});
-
-addMessageListener("addObserver", () => {
- Services.obs.addObserver(ParentUtils, "satchel-storage-changed", false);
-});
-addMessageListener("removeObserver", () => {
- Services.obs.removeObserver(ParentUtils, "satchel-storage-changed");
-});
-
-addMessageListener("cleanup", () => {
- ParentUtils.cleanup();
-});
diff --git a/toolkit/components/satchel/test/satchel_common.js b/toolkit/components/satchel/test/satchel_common.js
deleted file mode 100644
index c047f40af..000000000
--- a/toolkit/components/satchel/test/satchel_common.js
+++ /dev/null
@@ -1,274 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 gPopupShownExpected = false;
-var gPopupShownListener;
-var gLastAutoCompleteResults;
-var gChromeScript;
-
-/*
- * Returns the element with the specified |name| attribute.
- */
-function $_(formNum, name) {
- var form = document.getElementById("form" + formNum);
- if (!form) {
- ok(false, "$_ couldn't find requested form " + formNum);
- return null;
- }
-
- var element = form.elements.namedItem(name);
- if (!element) {
- ok(false, "$_ couldn't find requested element " + name);
- return null;
- }
-
- // Note that namedItem is a bit stupid, and will prefer an
- // |id| attribute over a |name| attribute when looking for
- // the element.
-
- if (element.hasAttribute("name") && element.getAttribute("name") != name) {
- ok(false, "$_ got confused.");
- return null;
- }
-
- return element;
-}
-
-// Mochitest gives us a sendKey(), but it's targeted to a specific element.
-// This basically sends an untargeted key event, to whatever's focused.
-function doKey(aKey, modifier) {
- var keyName = "DOM_VK_" + aKey.toUpperCase();
- var key = SpecialPowers.Ci.nsIDOMKeyEvent[keyName];
-
- // undefined --> null
- if (!modifier)
- modifier = null;
-
- // Window utils for sending fake key events.
- var wutils = SpecialPowers.getDOMWindowUtils(window);
-
- if (wutils.sendKeyEvent("keydown", key, 0, modifier)) {
- wutils.sendKeyEvent("keypress", key, 0, modifier);
- }
- wutils.sendKeyEvent("keyup", key, 0, modifier);
-}
-
-function registerPopupShownListener(listener) {
- if (gPopupShownListener) {
- ok(false, "got too many popupshownlisteners");
- return;
- }
- gPopupShownListener = listener;
-}
-
-function getMenuEntries() {
- if (!gLastAutoCompleteResults) {
- throw new Error("no autocomplete results");
- }
-
- var results = gLastAutoCompleteResults;
- gLastAutoCompleteResults = null;
- return results;
-}
-
-function checkArrayValues(actualValues, expectedValues, msg) {
- is(actualValues.length, expectedValues.length, "Checking array values: " + msg);
- for (var i = 0; i < expectedValues.length; i++)
- is(actualValues[i], expectedValues[i], msg + " Checking array entry #" + i);
-}
-
-var checkObserver = {
- verifyStack: [],
- callback: null,
-
- init() {
- gChromeScript.sendAsyncMessage("addObserver");
- gChromeScript.addMessageListener("satchel-storage-changed", this.observe.bind(this));
- },
-
- uninit() {
- gChromeScript.sendAsyncMessage("removeObserver");
- },
-
- waitForChecks: function(callback) {
- if (this.verifyStack.length == 0)
- callback();
- else
- this.callback = callback;
- },
-
- observe: function({ subject, topic, data }) {
- if (data != "formhistory-add" && data != "formhistory-update")
- return;
- ok(this.verifyStack.length > 0, "checking if saved form data was expected");
-
- // Make sure that every piece of data we expect to be saved is saved, and no
- // more. Here it is assumed that for every entry satchel saves or modifies, a
- // message is sent.
- //
- // We don't actually check the content of the message, but just that the right
- // quantity of messages is received.
- // - if there are too few messages, test will time out
- // - if there are too many messages, test will error out here
- //
- var expected = this.verifyStack.shift();
-
- countEntries(expected.name, expected.value,
- function(num) {
- ok(num > 0, expected.message);
- if (checkObserver.verifyStack.length == 0) {
- var callback = checkObserver.callback;
- checkObserver.callback = null;
- callback();
- }
- });
- }
-};
-
-function checkForSave(name, value, message) {
- checkObserver.verifyStack.push({ name : name, value: value, message: message });
-}
-
-function getFormSubmitButton(formNum) {
- var form = $("form" + formNum); // by id, not name
- ok(form != null, "getting form " + formNum);
-
- // we can't just call form.submit(), because that doesn't seem to
- // invoke the form onsubmit handler.
- var button = form.firstChild;
- while (button && button.type != "submit") { button = button.nextSibling; }
- ok(button != null, "getting form submit button");
-
- return button;
-}
-
-// Count the number of entries with the given name and value, and call then(number)
-// when done. If name or value is null, then the value of that field does not matter.
-function countEntries(name, value, then = null) {
- return new Promise(resolve => {
- gChromeScript.sendAsyncMessage("countEntries", { name, value });
- gChromeScript.addMessageListener("entriesCounted", function counted(data) {
- gChromeScript.removeMessageListener("entriesCounted", counted);
- if (!data.ok) {
- ok(false, "Error occurred counting form history");
- SimpleTest.finish();
- return;
- }
-
- if (then) {
- then(data.count);
- }
- resolve(data.count);
- });
- });
-}
-
-// Wrapper around FormHistory.update which handles errors. Calls then() when done.
-function updateFormHistory(changes, then = null) {
- return new Promise(resolve => {
- gChromeScript.sendAsyncMessage("updateFormHistory", { changes });
- gChromeScript.addMessageListener("formHistoryUpdated", function updated({ ok }) {
- gChromeScript.removeMessageListener("formHistoryUpdated", updated);
- if (!ok) {
- ok(false, "Error occurred updating form history");
- SimpleTest.finish();
- return;
- }
-
- if (then) {
- then();
- }
- resolve();
- });
- });
-}
-
-function notifyMenuChanged(expectedCount, expectedFirstValue, then = null) {
- return new Promise(resolve => {
- gChromeScript.sendAsyncMessage("waitForMenuChange",
- { expectedCount,
- expectedFirstValue });
- gChromeScript.addMessageListener("gotMenuChange", function changed({ results }) {
- gChromeScript.removeMessageListener("gotMenuChange", changed);
- gLastAutoCompleteResults = results;
- if (then) {
- then(results);
- }
- resolve(results);
- });
- });
-}
-
-function notifySelectedIndex(expectedIndex, then = null) {
- return new Promise(resolve => {
- gChromeScript.sendAsyncMessage("waitForSelectedIndex", { expectedIndex });
- gChromeScript.addMessageListener("gotSelectedIndex", function changed() {
- gChromeScript.removeMessageListener("gotSelectedIndex", changed);
- if (then) {
- then();
- }
- resolve();
- });
- });
-}
-
-function getPopupState(then = null) {
- return new Promise(resolve => {
- gChromeScript.sendAsyncMessage("getPopupState");
- gChromeScript.addMessageListener("gotPopupState", function listener(state) {
- gChromeScript.removeMessageListener("gotPopupState", listener);
- if (then) {
- then(state);
- }
- resolve(state);
- });
- });
-}
-
-function listenForUnexpectedPopupShown() {
- gPopupShownListener = function onPopupShown() {
- if (!gPopupShownExpected) {
- ok(false, "Unexpected autocomplete popupshown event");
- }
- };
-}
-
-function* promiseNoUnexpectedPopupShown() {
- gPopupShownExpected = false;
- listenForUnexpectedPopupShown();
- SimpleTest.requestFlakyTimeout("Giving a chance for an unexpected popupshown to occur");
- yield new Promise(resolve => setTimeout(resolve, 1000));
-}
-
-/**
- * Resolve at the next popupshown event for the autocomplete popup
- * @return {Promise} with the results
- */
-function promiseACShown() {
- gPopupShownExpected = true;
- return new Promise(resolve => {
- gPopupShownListener = ({ results }) => {
- gPopupShownExpected = false;
- resolve(results);
- };
- });
-}
-
-function satchelCommonSetup() {
- var chromeURL = SimpleTest.getTestFileURL("parent_utils.js");
- gChromeScript = SpecialPowers.loadChromeScript(chromeURL);
- gChromeScript.addMessageListener("onpopupshown", ({ results }) => {
- gLastAutoCompleteResults = results;
- if (gPopupShownListener)
- gPopupShownListener({results});
- });
-
- SimpleTest.registerCleanupFunction(() => {
- gChromeScript.sendAsyncMessage("cleanup");
- gChromeScript.destroy();
- });
-}
-
-
-satchelCommonSetup();
diff --git a/toolkit/components/satchel/test/subtst_form_submission_1.html b/toolkit/components/satchel/test/subtst_form_submission_1.html
deleted file mode 100644
index f7441668a..000000000
--- a/toolkit/components/satchel/test/subtst_form_submission_1.html
+++ /dev/null
@@ -1,38 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-
-<head>
-</head>
-
-<body>
-
-<form id="subform1" onsubmit="return checkSubmit(21)">
- <input id="subtest1" type="text" name="subtest1">
- <button type="submit">Submit</button>
-</form>
-
-<form id="subform2" onsubmit="return checkSubmit(100)">
- <input id="subtest2" type="text" name="subtest2">
- <button type="submit">Submit</button>
-</form>
-
-<script>
- function checkSubmit(num) {
- netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
- return parent.checkSubmit(num);
- }
-
- function clickButton(num) {
- if (num == 21)
- document.querySelectorAll("button")[0].click();
- else if (num == 100)
- document.querySelectorAll("button")[1].click();
- }
-
- // set the input's value (can't use a default value, as satchel will ignore it)
- document.getElementById("subtest1").value = "subtestValue";
- document.getElementById("subtest2").value = "subtestValue";
-</script>
-
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/subtst_privbrowsing.html b/toolkit/components/satchel/test/subtst_privbrowsing.html
deleted file mode 100644
index b53e0b229..000000000
--- a/toolkit/components/satchel/test/subtst_privbrowsing.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<html>
-<head>
- <meta charset=UTF-8>
- <title>Subtest for bug 472396</title>
- <script>
- function submitForm() {
- if (location.search.indexOf("field") == -1) {
- var form = document.getElementById("form");
- var field = document.getElementById("field");
- field.value = "value";
- form.submit();
- }
- }
- </script>
-</head>
-<body onload="submitForm();">
- <h2>Subtest for bug 472396</h2>
- <form id="form">
- <input name="field" id="field">
- </form>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_bug_511615.html b/toolkit/components/satchel/test/test_bug_511615.html
deleted file mode 100644
index 66972d9b3..000000000
--- a/toolkit/components/satchel/test/test_bug_511615.html
+++ /dev/null
@@ -1,194 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Form History Autocomplete Untrusted Events: Bug 511615</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Test for Form History Autocomplete Untrusted Events: Bug 511615
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
- <!-- normal, basic form -->
- <form id="form1" onsubmit="return false;">
- <input type="text" name="field1">
- <button type="submit">Submit</button>
- </form>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-var resolvePopupShownListener;
-registerPopupShownListener(() => resolvePopupShownListener());
-
-function waitForNextPopup() {
- return new Promise(resolve => { resolvePopupShownListener = resolve; });
-}
-
-/**
- * Indicates the time to wait before checking that the state of the autocomplete
- * popup, including whether it is open, has not changed in response to events.
- *
- * Manual testing on a fast machine revealed that 80ms was still unreliable,
- * while 100ms detected a simulated failure reliably. Unfortunately, this means
- * that to take into account slower machines we should use a larger value.
- *
- * Note that if a machine takes more than this time to show the popup, this
- * would not cause a failure, conversely the machine would not be able to detect
- * whether the test should have failed. In other words, this use of timeouts is
- * never expected to cause intermittent failures with test automation.
- */
-const POPUP_RESPONSE_WAIT_TIME_MS = 200;
-
-SimpleTest.requestFlakyTimeout("Must ensure that an event does not happen.");
-
-/**
- * Checks that the popup does not open in response to the given function.
- */
-function expectPopupDoesNotOpen(triggerFn) {
- let popupShown = waitForNextPopup();
- triggerFn();
- return Promise.race([
- popupShown.then(() => Promise.reject("Popup opened unexpectedly.")),
- new Promise(resolve => setTimeout(resolve, POPUP_RESPONSE_WAIT_TIME_MS)),
- ]);
-}
-
-/**
- * Checks that the selected index in the popup still matches the given value.
- */
-function checkSelectedIndexAfterResponseTime(expectedIndex) {
- return new Promise(resolve => {
- setTimeout(() => getPopupState(resolve), POPUP_RESPONSE_WAIT_TIME_MS);
- }).then(popupState => {
- is(popupState.open, true, "Popup should still be open.");
- is(popupState.selectedIndex, expectedIndex, "Selected index should match.");
- });
-}
-
-function doKeyUnprivileged(key) {
- let keyName = "DOM_VK_" + key.toUpperCase();
- let keycode, charcode;
-
- if (key.length == 1) {
- keycode = 0;
- charcode = key.charCodeAt(0);
- alwaysval = charcode;
- } else {
- keycode = KeyEvent[keyName];
- if (!keycode)
- throw "invalid keyname in test";
- charcode = 0;
- alwaysval = keycode;
- }
-
- let dnEvent = document.createEvent('KeyboardEvent');
- let prEvent = document.createEvent('KeyboardEvent');
- let upEvent = document.createEvent('KeyboardEvent');
-
- dnEvent.initKeyEvent("keydown", true, true, null, false, false, false, false, alwaysval, 0);
- prEvent.initKeyEvent("keypress", true, true, null, false, false, false, false, keycode, charcode);
- upEvent.initKeyEvent("keyup", true, true, null, false, false, false, false, alwaysval, 0);
-
- input.dispatchEvent(dnEvent);
- input.dispatchEvent(prEvent);
- input.dispatchEvent(upEvent);
-}
-
-function doClickWithMouseEventUnprivileged() {
- let dnEvent = document.createEvent('MouseEvent');
- let upEvent = document.createEvent('MouseEvent');
- let ckEvent = document.createEvent('MouseEvent');
-
- dnEvent.initMouseEvent("mousedown", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
- upEvent.initMouseEvent("mouseup", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
- ckEvent.initMouseEvent("mouseclick", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
-
- input.dispatchEvent(dnEvent);
- input.dispatchEvent(upEvent);
- input.dispatchEvent(ckEvent);
-}
-
-let input = $_(1, "field1");
-
-add_task(function* test_initialize() {
- yield new Promise(resolve => updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "value1" },
- { op : "add", fieldname : "field1", value : "value2" },
- { op : "add", fieldname : "field1", value : "value3" },
- { op : "add", fieldname : "field1", value : "value4" },
- { op : "add", fieldname : "field1", value : "value5" },
- { op : "add", fieldname : "field1", value : "value6" },
- { op : "add", fieldname : "field1", value : "value7" },
- { op : "add", fieldname : "field1", value : "value8" },
- { op : "add", fieldname : "field1", value : "value9" },
- ], resolve));
-});
-
-add_task(function* test_untrusted_events_ignored() {
- // The autocomplete popup should not open from untrusted events.
- for (let triggerFn of [
- () => input.focus(),
- () => input.click(),
- () => doClickWithMouseEventUnprivileged(),
- () => doKeyUnprivileged("down"),
- () => doKeyUnprivileged("page_down"),
- () => doKeyUnprivileged("return"),
- () => doKeyUnprivileged("v"),
- () => doKeyUnprivileged(" "),
- () => doKeyUnprivileged("back_space"),
- ]) {
- // We must wait for the entire timeout for each individual test, because the
- // next event in the list might prevent the popup from opening.
- yield expectPopupDoesNotOpen(triggerFn);
- }
-
- // A privileged key press will actually open the popup.
- let popupShown = waitForNextPopup();
- doKey("down");
- yield popupShown;
-
- // The selected autocomplete item should not change from untrusted events.
- for (let triggerFn of [
- () => doKeyUnprivileged("down"),
- () => doKeyUnprivileged("page_down"),
- ]) {
- triggerFn();
- yield checkSelectedIndexAfterResponseTime(-1);
- }
-
- // A privileged key press will actually change the selected index.
- let indexChanged = new Promise(resolve => notifySelectedIndex(0, resolve));
- doKey("down");
- yield indexChanged;
-
- // The selected autocomplete item should not change and it should not be
- // possible to use it from untrusted events.
- for (let triggerFn of [
- () => doKeyUnprivileged("down"),
- () => doKeyUnprivileged("page_down"),
- () => doKeyUnprivileged("right"),
- () => doKeyUnprivileged(" "),
- () => doKeyUnprivileged("back_space"),
- () => doKeyUnprivileged("back_space"),
- () => doKeyUnprivileged("return"),
- ]) {
- triggerFn();
- yield checkSelectedIndexAfterResponseTime(0);
- is(input.value, "", "The selected item should not have been used.");
- }
-
- // Close the popup.
- input.blur();
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_bug_787624.html b/toolkit/components/satchel/test/test_bug_787624.html
deleted file mode 100644
index 6ca5136cd..000000000
--- a/toolkit/components/satchel/test/test_bug_787624.html
+++ /dev/null
@@ -1,88 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Layout of Form History Autocomplete: Bug 787624</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
- <style>
- .container {
- border: 1px solid #333;
- width: 80px;
- height: 26px;
- position: absolute;
- z-index: 2;
- }
-
- .subcontainer {
- width: 100%;
- overflow: hidden;
- }
-
- .subcontainer input {
- width: 120px;
- margin: 2px 6px;
- padding-right: 4px;
- border: none;
- height: 22px;
- z-index: 1;
- outline: 1px dashed #555
- }
- </style>
-</head>
-<body>
-Form History Layout test: form field autocomplete: Bug 787624
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
- <!-- in this form, the input field is partially hidden and can scroll -->
- <div class="container">
- <div class="subcontainer">
- <form id="form1" onsubmit="return false;">
- <input type="text" name="field1">
- <button type="submit">Submit</button>
- </form>
- </div>
- </div>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Form History autocomplete Layout: Bug 787624 **/
-
-var resolvePopupShownListener;
-registerPopupShownListener(() => resolvePopupShownListener());
-
-function waitForNextPopup() {
- return new Promise(resolve => { resolvePopupShownListener = resolve; });
-}
-
-add_task(function* test_popup_not_move_input() {
- var input = $_(1, "field1");
- var rect = input.getBoundingClientRect();
-
- yield new Promise(resolve => updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "value1" },
- { op : "add", fieldname : "field1", value : "value2" },
- ], resolve));
-
- let popupShown = waitForNextPopup();
- input.focus();
- doKey("down");
- yield popupShown;
-
- var newRect = input.getBoundingClientRect();
- is(newRect.left, rect.left,
- "autocomplete popup does not disturb the input position");
- is(newRect.top, rect.top,
- "autocomplete popup does not disturb the input position");
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_datalist_with_caching.html b/toolkit/components/satchel/test/test_datalist_with_caching.html
deleted file mode 100644
index 8445cb159..000000000
--- a/toolkit/components/satchel/test/test_datalist_with_caching.html
+++ /dev/null
@@ -1,139 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Form History Autocomplete</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Form History test: form field autocomplete
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
-
- <!-- normal, basic form -->
- <form id="form1" onsubmit="return false;">
- <input list="suggest" type="text" name="field1">
- <button type="submit">Submit</button>
- </form>
-
- <datalist id="suggest">
- <option value="First"></option>
- <option value="Second"></option>
- <option value="Secomundo"></option>
- </datalist>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-var input = $_(1, "field1");
-
-function setupFormHistory(aCallback) {
- updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "Sec" },
- ], () => {
- spawn_task(aCallback);
- });
-}
-
-function setForm(value) {
- input.value = value;
- input.focus();
-}
-
-// Restore the form to the default state.
-function restoreForm() {
- setForm("");
-}
-
-// Check for expected form data.
-function checkForm(expectedValue) {
- var formID = input.parentNode.id;
- is(input.value, expectedValue, "Checking " + formID + " input");
-}
-
-SimpleTest.waitForExplicitFinish();
-
-var expectingPopup = null;
-
-function expectPopup() {
- info("expecting a popup");
- return new Promise(resolve => {
- expectingPopup = resolve;
- });
-}
-
-var testNum = 0;
-
-function popupShownListener() {
- info("popup shown for test " + testNum);
- if (expectingPopup) {
- expectingPopup();
- expectingPopup = null;
- }
- else {
- ok(false, "Autocomplete popup not expected during test " + testNum);
- }
-}
-
-function waitForMenuChange(expectedCount) {
- return new Promise(resolve => {
- notifyMenuChanged(expectedCount, null, resolve);
- });
-}
-
-registerPopupShownListener(popupShownListener);
-
-function checkMenuEntries(expectedValues) {
- var actualValues = getMenuEntries();
- is(actualValues.length, expectedValues.length, testNum + " Checking length of expected menu");
- for (var i = 0; i < expectedValues.length; i++)
- is(actualValues[i], expectedValues[i], testNum + " Checking menu entry #"+i);
-}
-
-function* runTests() {
- testNum++;
- restoreForm();
- doKey("down");
- yield expectPopup();
-
- checkMenuEntries(["Sec", "First", "Second", "Secomundo"]);
- doKey("down");
- doKey("return");
- checkForm("Sec");
-
- testNum++;
- restoreForm();
- sendString("Sec");
- doKey("down");
- yield expectPopup();
-
- testNum++;
- checkMenuEntries(["Sec", "Second", "Secomundo"]);
- sendString("o");
- yield waitForMenuChange(2);
-
- testNum++;
- checkMenuEntries(["Second", "Secomundo"]);
- doKey("down");
- doKey("return");
- checkForm("Second");
- SimpleTest.finish();
-}
-
-function startTest() {
- setupFormHistory(runTests);
-}
-
-window.onload = startTest;
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_form_autocomplete.html b/toolkit/components/satchel/test/test_form_autocomplete.html
deleted file mode 100644
index d2c22a3db..000000000
--- a/toolkit/components/satchel/test/test_form_autocomplete.html
+++ /dev/null
@@ -1,1074 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Form History Autocomplete</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Form History test: form field autocomplete
-<p id="display"></p>
-
-<!-- We presumably can't hide the content for this test. The large top padding is to allow
- listening for scrolls to occur. -->
-<div id="content" style="padding-top: 20000px;">
-
- <!-- normal, basic form -->
- <form id="form1" onsubmit="return false;">
- <input type="text" name="field1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- normal, basic form (new fieldname) -->
- <form id="form2" onsubmit="return false;">
- <input type="text" name="field2">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with autocomplete=off on input -->
- <form id="form3" onsubmit="return false;">
- <input type="text" name="field2" autocomplete="off">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with autocomplete=off on form -->
- <form id="form4" autocomplete="off" onsubmit="return false;">
- <input type="text" name="field2">
- <button type="submit">Submit</button>
- </form>
-
- <!-- normal form for testing filtering -->
- <form id="form5" onsubmit="return false;">
- <input type="text" name="field3">
- <button type="submit">Submit</button>
- </form>
-
- <!-- normal form for testing word boundary filtering -->
- <form id="form6" onsubmit="return false;">
- <input type="text" name="field4">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with maxlength attribute on input -->
- <form id="form7" onsubmit="return false;">
- <input type="text" name="field5" maxlength="10">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='email' -->
- <form id="form8" onsubmit="return false;">
- <input type="email" name="field6">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='tel' -->
- <form id="form9" onsubmit="return false;">
- <input type="tel" name="field7">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='url' -->
- <form id="form10" onsubmit="return false;">
- <input type="url" name="field8">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='search' -->
- <form id="form11" onsubmit="return false;">
- <input type="search" name="field9">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='number' -->
- <form id="form12" onsubmit="return false;">
- <input type="text" name="field10"> <!-- TODO: change back to type=number -->
- <button type="submit">Submit</button>
- </form>
-
- <!-- normal, basic form (with fieldname='searchbar-history') -->
- <form id="form13" onsubmit="return false;">
- <input type="text" name="searchbar-history">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='date' -->
- <form id="form14" onsubmit="return false;">
- <input type="date" name="field11">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='time' -->
- <form id="form15" onsubmit="return false;">
- <input type="time" name="field12">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='range' -->
- <form id="form16" onsubmit="return false;">
- <input type="range" name="field13" max="64">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='color' -->
- <form id="form17" onsubmit="return false;">
- <input type="color" name="field14">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='month' -->
- <form id="form18" onsubmit="return false;">
- <input type="month" name="field15">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='week' -->
- <form id="form19" onsubmit="return false;">
- <input type="week" name="field16">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with input type='datetime-local' -->
- <form id="form20" onsubmit="return false;">
- <input type="datetime-local" name="field17">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Form History autocomplete **/
-
-var input = $_(1, "field1");
-const shiftModifier = Event.SHIFT_MASK;
-
-function setupFormHistory(aCallback) {
- updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "value1" },
- { op : "add", fieldname : "field1", value : "value2" },
- { op : "add", fieldname : "field1", value : "value3" },
- { op : "add", fieldname : "field1", value : "value4" },
- { op : "add", fieldname : "field2", value : "value1" },
- { op : "add", fieldname : "field3", value : "a" },
- { op : "add", fieldname : "field3", value : "aa" },
- { op : "add", fieldname : "field3", value : "aaz" },
- { op : "add", fieldname : "field3", value : "aa\xe6" }, // 0xae == latin ae pair (0xc6 == AE)
- { op : "add", fieldname : "field3", value : "az" },
- { op : "add", fieldname : "field3", value : "z" },
- { op : "add", fieldname : "field4", value : "a\xe6" },
- { op : "add", fieldname : "field4", value : "aa a\xe6" },
- { op : "add", fieldname : "field4", value : "aba\xe6" },
- { op : "add", fieldname : "field4", value : "bc d\xe6" },
- { op : "add", fieldname : "field5", value : "1" },
- { op : "add", fieldname : "field5", value : "12" },
- { op : "add", fieldname : "field5", value : "123" },
- { op : "add", fieldname : "field5", value : "1234" },
- { op : "add", fieldname : "field6", value : "value" },
- { op : "add", fieldname : "field7", value : "value" },
- { op : "add", fieldname : "field8", value : "value" },
- { op : "add", fieldname : "field9", value : "value" },
- { op : "add", fieldname : "field10", value : "42" },
- { op : "add", fieldname : "field11", value : "2010-10-10" }, // not used, since type=date doesn't have autocomplete currently
- { op : "add", fieldname : "field12", value : "21:21" }, // not used, since type=time doesn't have autocomplete currently
- { op : "add", fieldname : "field13", value : "32" }, // not used, since type=range doesn't have a drop down menu
- { op : "add", fieldname : "field14", value : "#ffffff" }, // not used, since type=color doesn't have autocomplete currently
- { op : "add", fieldname : "field15", value : "2016-08" },
- { op : "add", fieldname : "field16", value : "2016-W32" },
- { op : "add", fieldname : "field17", value : "2016-10-21T10:10" },
- { op : "add", fieldname : "searchbar-history", value : "blacklist test" },
- ], aCallback);
-}
-
-function setForm(value) {
- input.value = value;
- input.focus();
-}
-
-// Restore the form to the default state.
-function restoreForm() {
- setForm("");
-}
-
-// Check for expected form data.
-function checkForm(expectedValue) {
- var formID = input.parentNode.id;
- is(input.value, expectedValue, "Checking " + formID + " input");
-}
-
-var testNum = 0;
-var expectingPopup = false;
-
-function expectPopup()
-{
- info("expecting popup for test " + testNum);
- expectingPopup = true;
-}
-
-function popupShownListener()
-{
- info("popup shown for test " + testNum);
- if (expectingPopup) {
- expectingPopup = false;
- SimpleTest.executeSoon(runTest);
- }
- else {
- ok(false, "Autocomplete popup not expected during test " + testNum);
- }
-}
-
-registerPopupShownListener(popupShownListener);
-
-/*
- * Main section of test...
- *
- * This is a bit hacky, as many operations happen asynchronously.
- * Various mechanisms call runTests as a result of operations:
- * - set expectingPopup to true, and the next test will occur when the autocomplete popup is shown
- * - call waitForMenuChange(x) to run the next test when the autocomplete popup to have x items in it
- * - addEntry calls runs the test when an entry has been added
- * - some tests scroll the window. This is because the form fill controller happens to scroll
- * the field into view near the end of the search, and there isn't any other good notification
- * to listen to for when the search is complete.
- * - some items still use setTimeout
- */
-function runTest() {
- testNum++;
-
- ok(true, "Starting test #" + testNum);
-
- switch (testNum) {
- case 1:
- // Make sure initial form is empty.
- checkForm("");
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 2:
- checkMenuEntries(["value1", "value2", "value3", "value4"], testNum);
- // Check first entry
- doKey("down");
- checkForm(""); // value shouldn't update
- doKey("return"); // not "enter"!
- checkForm("value1");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 3:
- // Check second entry
- doKey("down");
- doKey("down");
- doKey("return"); // not "enter"!
- checkForm("value2");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 4:
- // Check third entry
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("value3");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 5:
- // Check fourth entry
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("value4");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 6:
- // Check first entry (wraparound)
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("down"); // deselects
- doKey("down");
- doKey("return");
- checkForm("value1");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 7:
- // Check the last entry via arrow-up
- doKey("up");
- doKey("return");
- checkForm("value4");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 8:
- // Check the last entry via arrow-up
- doKey("down"); // select first entry
- doKey("up"); // selects nothing!
- doKey("up"); // select last entry
- doKey("return");
- checkForm("value4");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 9:
- // Check the last entry via arrow-up (wraparound)
- doKey("down");
- doKey("up"); // deselects
- doKey("up"); // last entry
- doKey("up");
- doKey("up");
- doKey("up"); // first entry
- doKey("up"); // deselects
- doKey("up"); // last entry
- doKey("return");
- checkForm("value4");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 10:
- // Set first entry w/o triggering autocomplete
- doKey("down");
- doKey("right");
- checkForm("value1");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 11:
- // Set first entry w/o triggering autocomplete
- doKey("down");
- doKey("left");
- checkForm("value1");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 12:
- // Check first entry (page up)
- doKey("down");
- doKey("down");
- doKey("page_up");
- doKey("return");
- checkForm("value1");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 13:
- // Check last entry (page down)
- doKey("down");
- doKey("page_down");
- doKey("return");
- checkForm("value4");
-
- // Trigger autocomplete popup
- testNum = 49;
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- /* Test removing entries from the dropdown */
-
- case 50:
- checkMenuEntries(["value1", "value2", "value3", "value4"], testNum);
- // Delete the first entry (of 4)
- setForm("value");
- doKey("down");
-
- // On OS X, shift-backspace and shift-delete work, just delete does not.
- // On Win/Linux, shift-backspace does not work, delete and shift-delete do.
- if (SpecialPowers.OS == "Darwin")
- doKey("back_space", shiftModifier);
- else
- doKey("delete", shiftModifier);
-
- // This tests that on OS X shift-backspace didn't delete the last character
- // in the input (bug 480262).
- waitForMenuChange(3);
- break;
-
- case 51:
- checkForm("value");
- countEntries("field1", "value1",
- function (num) {
- ok(!num, testNum + " checking that f1/v1 was deleted");
- runTest();
- });
- break;
-
- case 52:
- doKey("return");
- checkForm("value2");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 53:
- checkMenuEntries(["value2", "value3", "value4"], testNum);
- // Check the new first entry (of 3)
- doKey("down");
- doKey("return");
- checkForm("value2");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 54:
- // Delete the second entry (of 3)
- doKey("down");
- doKey("down");
- doKey("delete", shiftModifier);
- waitForMenuChange(2);
- break;
-
- case 55:
- checkForm("");
- countEntries("field1", "value3",
- function (num) {
- ok(!num, testNum + " checking that f1/v3 was deleted");
- runTest();
- });
- break;
-
- case 56:
- doKey("return");
- checkForm("value4")
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 57:
- checkMenuEntries(["value2", "value4"], testNum);
- // Check the new first entry (of 2)
- doKey("down");
- doKey("return");
- checkForm("value2");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 58:
- // Delete the last entry (of 2)
- doKey("down");
- doKey("down");
- doKey("delete", shiftModifier);
- checkForm("");
- waitForMenuChange(1);
- break;
-
- case 59:
- countEntries("field1", "value4",
- function (num) {
- ok(!num, testNum + " checking that f1/v4 was deleted");
- runTest();
- });
- break;
-
- case 60:
- doKey("return");
- checkForm("value2");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 61:
- checkMenuEntries(["value2"], testNum);
- // Check the new first entry (of 1)
- doKey("down");
- doKey("return");
- checkForm("value2");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 62:
- // Delete the only remaining entry
- doKey("down");
- doKey("delete", shiftModifier);
- waitForMenuChange(0);
- break;
-
- case 63:
- checkForm("");
- countEntries("field1", "value2",
- function (num) {
- ok(!num, testNum + " checking that f1/v2 was deleted");
- runTest();
- });
- break;
-
- case 64:
- // Look at form 2, trigger autocomplete popup
- input = $_(2, "field2");
- testNum = 99;
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- /* Test entries with autocomplete=off */
-
- case 100:
- // Select first entry
- doKey("down");
- doKey("return");
- checkForm("value1");
-
- // Look at form 3, try to trigger autocomplete popup
- input = $_(3, "field2");
- restoreForm();
- // Sometimes, this will fail if scrollTo(0, 0) is called, so that doesn't
- // happen here. Fortunately, a different input is used from the last test,
- // so a scroll should still occur.
- doKey("down");
- waitForScroll();
- break;
-
- case 101:
- // Ensure there's no autocomplete dropdown (autocomplete=off is present)
- doKey("down");
- doKey("return");
- checkForm("");
-
- // Look at form 4, try to trigger autocomplete popup
- input = $_(4, "field2");
- restoreForm();
- doKey("down");
- waitForMenuChange(0);
- break;
-
- case 102:
- // Ensure there's no autocomplete dropdown (autocomplete=off is present)
- doKey("down");
- doKey("return");
- checkForm("");
-
- // Look at form 5, try to trigger autocomplete popup
- input = $_(5, "field3");
- restoreForm();
- testNum = 199;
- expectPopup();
- input.focus();
- sendChar("a");
- break;
-
- /* Test filtering as characters are typed. */
-
- case 200:
- checkMenuEntries(["a", "aa", "aaz", "aa\xe6", "az"], testNum);
- input.focus();
- sendChar("a");
- waitForMenuChange(3);
- break;
-
- case 201:
- checkMenuEntries(["aa", "aaz", "aa\xe6"], testNum);
- input.focus();
- sendChar("\xc6");
- waitForMenuChange(1);
- break;
-
- case 202:
- checkMenuEntries(["aa\xe6"], testNum);
- doKey("back_space");
- waitForMenuChange(3);
- break;
-
- case 203:
- checkMenuEntries(["aa", "aaz", "aa\xe6"], testNum);
- doKey("back_space");
- waitForMenuChange(5);
- break;
-
- case 204:
- checkMenuEntries(["a", "aa", "aaz", "aa\xe6", "az"], testNum);
- input.focus();
- sendChar("z");
- waitForMenuChange(2);
- break;
-
- case 205:
- checkMenuEntries(["az", "aaz"], testNum);
- input.focus();
- doKey("left");
- expectPopup();
- // Check case-insensitivity.
- sendChar("A");
- break;
-
- case 206:
- checkMenuEntries(["aaz"], testNum);
- addEntry("field3", "aazq");
- break;
-
- case 207:
- // check that results were cached
- input.focus();
- doKey("right");
- sendChar("q");
- waitForMenuChange(0);
- break;
-
- case 208:
- // check that results were cached
- checkMenuEntries([], testNum);
- addEntry("field3", "aazqq");
- break;
-
- case 209:
- input.focus();
- window.scrollTo(0, 0);
- sendChar("q");
- waitForMenuChange(0);
- break;
-
- case 210:
- // check that empty results were cached - bug 496466
- checkMenuEntries([], testNum);
- doKey("escape");
-
- // Look at form 6, try to trigger autocomplete popup
- input = $_(6, "field4");
- restoreForm();
- testNum = 249;
- expectPopup();
- input.focus();
- sendChar("a");
- break;
-
- /* Test substring matches and word boundary bonuses */
-
- case 250:
- // alphabetical results for first character
- checkMenuEntries(["aa a\xe6", "aba\xe6", "a\xe6"], testNum);
- input.focus();
-
- sendChar("\xe6");
- waitForMenuChange(3, "a\xe6");
- break;
-
- case 251:
- // prefix match comes first, then word boundary match
- // followed by substring match
- checkMenuEntries(["a\xe6", "aa a\xe6", "aba\xe6"], testNum);
-
- restoreForm();
- input.focus();
- sendChar("b");
- waitForMenuChange(1, "bc d\xe6");
- break;
-
- case 252:
- checkMenuEntries(["bc d\xe6"], testNum);
- input.focus();
- sendChar(" ");
- waitForMenuChange(1);
- break;
-
- case 253:
- // check that trailing space has no effect after single char.
- checkMenuEntries(["bc d\xe6"], testNum);
- input.focus();
- sendChar("\xc6");
- waitForMenuChange(2);
- break;
-
- case 254:
- // check multi-word substring matches
- checkMenuEntries(["bc d\xe6", "aba\xe6"]);
- input.focus();
- expectPopup();
- doKey("left");
- sendChar("d");
- break;
-
- case 255:
- // check inserting in multi-word searches
- checkMenuEntries(["bc d\xe6"], testNum);
- input.focus();
- sendChar("z");
- waitForMenuChange(0);
- break;
-
- case 256:
- checkMenuEntries([], testNum);
-
- // Look at form 7, try to trigger autocomplete popup
- input = $_(7, "field5");
- testNum = 299;
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 300:
- checkMenuEntries(["1", "12", "123", "1234"], testNum);
- input.maxLength = 4;
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 301:
- checkMenuEntries(["1", "12", "123", "1234"], testNum);
- input.maxLength = 3;
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 302:
- checkMenuEntries(["1", "12", "123"], testNum);
- input.maxLength = 2;
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 303:
- checkMenuEntries(["1", "12"], testNum);
- input.maxLength = 1;
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 304:
- checkMenuEntries(["1"], testNum);
- input.maxLength = 0;
- doKey("escape");
- doKey("down");
- waitForMenuChange(0);
- break;
-
- case 305:
- checkMenuEntries([], testNum);
- input.maxLength = 4;
-
- // now again with a character typed
- input.focus();
- sendChar("1");
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 306:
- checkMenuEntries(["1", "12", "123", "1234"], testNum);
- input.maxLength = 3;
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 307:
- checkMenuEntries(["1", "12", "123"], testNum);
- input.maxLength = 2;
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 308:
- checkMenuEntries(["1", "12"], testNum);
- input.maxLength = 1;
- expectPopup();
- doKey("escape");
- doKey("down");
- break;
-
- case 309:
- checkMenuEntries(["1"], testNum);
- input.maxLength = 0;
- doKey("escape");
- doKey("down");
- waitForMenuChange(0);
- break;
-
- case 310:
- checkMenuEntries([], testNum);
-
- input = $_(8, "field6");
- testNum = 399;
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 400:
- case 401:
- case 402:
- case 403:
- checkMenuEntries(["value"], testNum);
- doKey("down");
- doKey("return");
- checkForm("value");
-
- if (testNum == 400) {
- input = $_(9, "field7");
- } else if (testNum == 401) {
- input = $_(10, "field8");
- } else if (testNum == 402) {
- input = $_(11, "field9");
- } else if (testNum == 403) {
- todo(false, "Fix input type=number");
- input = $_(12, "field10");
- }
-
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 404:
- checkMenuEntries(["42"], testNum);
- doKey("down");
- doKey("return");
- checkForm("42");
-
- input = $_(14, "field11");
- restoreForm();
- waitForMenuChange(0);
- break;
-
- case 405:
- checkMenuEntries([]); // type=date with it's own control frame does not
- // have a drop down menu for now
- checkForm("");
-
- input = $_(15, "field12");
- restoreForm();
- waitForMenuChange(0);
- break;
-
- case 406:
- checkMenuEntries([]); // type=time with it's own control frame does not
- // have a drop down menu for now
- checkForm("");
-
- input = $_(16, "field13");
- restoreForm();
- doKey("down");
- waitForMenuChange(0);
- break;
-
- case 407:
- checkMenuEntries([]); // type=range does not have a drop down menu
- doKey("down");
- doKey("return");
- checkForm("30"); // default (midway between minimum (0) and maximum (64)) - step
-
- input = $_(17, "field14");
- restoreForm();
- waitForMenuChange(0);
- break;
-
- case 408:
- checkMenuEntries([]); // type=color does not have a drop down menu
- checkForm("#000000"); // default color value
-
- input = $_(18, "field15");
- restoreForm();
- expectPopup();
- doKey("down");
- break;
-
- case 409:
- checkMenuEntries(["2016-08"]);
- doKey("down");
- doKey("return");
- checkForm("2016-08");
-
- input = $_(19, "field16");
- restoreForm();
- expectPopup();
- doKey("down");
- break;
-
- case 410:
- checkMenuEntries(["2016-W32"]);
- doKey("down");
- doKey("return");
- checkForm("2016-W32");
-
- input = $_(20, "field17");
- restoreForm();
- expectPopup();
- doKey("down");
- break;
-
- case 411:
- checkMenuEntries(["2016-10-21T10:10"]);
- doKey("down");
- doKey("return");
- checkForm("2016-10-21T10:10");
-
- addEntry("field1", "value1");
- break;
-
- case 412:
- input = $_(1, "field1");
- // Go to test 500.
- testNum = 499;
-
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- // Check that the input event is fired.
- case 500:
- input.addEventListener("input", function(event) {
- input.removeEventListener("input", arguments.callee, false);
- ok(true, testNum + " oninput should have been received");
- ok(event.bubbles, testNum + " input event should bubble");
- ok(event.cancelable, testNum + " input event should be cancelable");
- }, false);
-
- doKey("down");
- checkForm("");
- doKey("return");
- checkForm("value1");
- testNum = 599;
- setTimeout(runTest, 100);
- break;
-
- case 600:
- // check we don't show autocomplete for searchbar-history
- input = $_(13, "searchbar-history");
-
- // Trigger autocomplete popup
- checkForm("");
- restoreForm();
- doKey("down");
- waitForMenuChange(0);
- break;
-
- case 601:
- checkMenuEntries([], testNum);
- input.blur();
- SimpleTest.finish();
- return;
-
- default:
- ok(false, "Unexpected invocation of test #" + testNum);
- SimpleTest.finish();
- return;
- }
-}
-
-function addEntry(name, value)
-{
- updateFormHistory({ op : "add", fieldname : name, value: value }, runTest);
-}
-
-// Runs the next test when scroll event occurs
-function waitForScroll()
-{
- addEventListener("scroll", function() {
- if (!window.pageYOffset)
- return;
-
- removeEventListener("scroll", arguments.callee, false);
- setTimeout(runTest, 100);
- }, false);
-}
-
-function waitForMenuChange(expectedCount, expectedFirstValue)
-{
- notifyMenuChanged(expectedCount, expectedFirstValue, runTest);
-}
-
-function checkMenuEntries(expectedValues, testNumber) {
- var actualValues = getMenuEntries();
- is(actualValues.length, expectedValues.length, testNumber + " Checking length of expected menu");
- for (var i = 0; i < expectedValues.length; i++)
- is(actualValues[i], expectedValues[i], testNumber + " Checking menu entry #"+i);
-}
-
-function startTest() {
- setupFormHistory(function() {
- runTest();
- });
-}
-
-window.onload = startTest;
-
-SimpleTest.waitForExplicitFinish();
-SimpleTest.requestFlakyTimeout("untriaged");
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/toolkit/components/satchel/test/test_form_autocomplete_with_list.html b/toolkit/components/satchel/test/test_form_autocomplete_with_list.html
deleted file mode 100644
index 04fb080c9..000000000
--- a/toolkit/components/satchel/test/test_form_autocomplete_with_list.html
+++ /dev/null
@@ -1,506 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Form History Autocomplete</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Form History test: form field autocomplete
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
-
- <!-- normal, basic form -->
- <form id="form1" onsubmit="return false;">
- <input list="suggest" type="text" name="field1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with autocomplete=off on input -->
- <form id="form3" onsubmit="return false;">
- <input list="suggest" type="text" name="field2" autocomplete="off">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form with autocomplete=off on form -->
- <form id="form4" autocomplete="off" onsubmit="return false;">
- <input list="suggest" type="text" name="field2">
- <button type="submit">Submit</button>
- </form>
-
- <datalist id="suggest">
- <option value="Google" label="PASS1">FAIL</option>
- <option value="Reddit">PASS2</option>
- <option value="final"></option>
- </datalist>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/** Test for Form History autocomplete **/
-
-var input = $_(1, "field1");
-const shiftModifier = Components.interfaces.nsIDOMEvent.SHIFT_MASK;
-
-function setupFormHistory(aCallback) {
- updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "historyvalue" },
- { op : "add", fieldname : "field2", value : "othervalue" },
- ], aCallback);
-}
-
-function setForm(value) {
- input.value = value;
- input.focus();
-}
-
-// Restore the form to the default state.
-function restoreForm() {
- setForm("");
-}
-
-// Check for expected form data.
-function checkForm(expectedValue) {
- var formID = input.parentNode.id;
- is(input.value, expectedValue, "Checking " + formID + " input");
-}
-
-var testNum = 0;
-var prevValue;
-var expectingPopup = false;
-
-function expectPopup() {
- info("expecting popup for test " + testNum);
- expectingPopup = true;
-}
-
-function popupShownListener() {
- info("popup shown for test " + testNum);
- if (expectingPopup) {
- expectingPopup = false;
- SimpleTest.executeSoon(runTest);
- }
- else {
- ok(false, "Autocomplete popup not expected during test " + testNum);
- }
-}
-
-registerPopupShownListener(popupShownListener);
-
-/*
-* Main section of test...
-*
-* This is a bit hacky, as many operations happen asynchronously.
-* Various mechanisms call runTests as a result of operations:
-* - set expectingPopup to true, and the next test will occur when the autocomplete popup is shown
-* - call waitForMenuChange(x) to run the next test when the autocomplete popup to have x items in it
-*/
-function runTest() {
- testNum++;
-
- info("Starting test #" + testNum);
-
- switch (testNum) {
- case 1:
- // Make sure initial form is empty.
- checkForm("");
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
- case 2:
- checkMenuEntries(["historyvalue", "PASS1", "PASS2", "final"], testNum);
- // Check first entry
- doKey("down");
- checkForm(""); // value shouldn't update
- doKey("return"); // not "enter"!
- checkForm("historyvalue");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 3:
- // Check second entry
- doKey("down");
- doKey("down");
- doKey("return"); // not "enter"!
- checkForm("Google");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 4:
- // Check third entry
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("Reddit");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 5:
- // Check fourth entry
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("final");
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 6:
- // Delete the first entry (of 3)
- doKey("down");
- doKey("delete", shiftModifier);
- waitForMenuChange(3);
- break;
-
- case 7:
- checkForm("");
- countEntries("field1", "historyvalue",
- function (num) {
- ok(!num, testNum + " checking that form history value was deleted");
- runTest();
- });
- break;
-
- case 8:
- doKey("return");
- checkForm("Google")
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 9:
- // Test deletion
- checkMenuEntries(["PASS1", "PASS2", "final"], testNum);
- // Check the new first entry (of 3)
- doKey("down");
- doKey("return");
- checkForm("Google");
-
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 10:
- // Test autocompletion of datalists with cached results.
- sendString("PAS");
- waitForMenuChange(2);
- break;
-
- case 11:
- // Continuation of test 10
- sendString("S1");
- waitForMenuChange(1);
- break;
-
- case 12:
- doKey("down");
- doKey("return");
- checkForm("Google");
-
- // Trigger autocomplete popup
- // Look at form 3, try to trigger autocomplete popup
- input.value = "";
- input = $_(3, "field2");
- testNum = 99;
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 100:
- checkMenuEntries(["PASS1", "PASS2", "final"], testNum);
- // Check first entry
- doKey("down");
- checkForm(""); // value shouldn't update
- doKey("return"); // not "enter"!
- checkForm("Google");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 101:
- // Check second entry
- doKey("down");
- doKey("down");
- doKey("return"); // not "enter"!
- checkForm("Reddit");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 102:
- // Check third entry
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("final");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 103:
- checkMenuEntries(["PASS1", "PASS2", "final"], testNum);
- // Check first entry
- doKey("down");
- checkForm(""); // value shouldn't update
- doKey("return"); // not "enter"!
- checkForm("Google");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 104:
- // Check second entry
- doKey("down");
- doKey("down");
- doKey("return"); // not "enter"!
- checkForm("Reddit");
-
- // Trigger autocomplete popup
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 105:
- // Check third entry
- doKey("down");
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("final");
-
- testNum = 199;
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- // Test dynamic updates.
- // For some reasons, when there is an update of the list, the selection is
- // lost so we need to go down like if we were at the beginning of the list
- // again.
- case 200:
- // Removing the second element while on the first then going down and
- // push enter. Value should be one from the third suggesion.
- doKey("down");
- var datalist = document.getElementById('suggest');
- var toRemove = datalist.children[1]
- datalist.removeChild(toRemove);
-
- SimpleTest.executeSoon(function() {
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("final");
-
- // Restore the element.
- datalist.insertBefore(toRemove, datalist.children[1]);
- expectPopup();
- restoreForm();
- doKey("down");
- });
- break;
-
- case 201:
- // Adding an attribute after the first one while on the first then going
- // down and push enter. Value should be the on from the new suggestion.
- doKey("down");
- datalist = document.getElementById('suggest');
- var added = new Option("Foo");
- datalist.insertBefore(added, datalist.children[1]);
- waitForMenuChange(4);
- break;
-
- case 202:
- doKey("down");
- doKey("down");
- doKey("return");
- checkForm("Foo");
-
- // Remove the element.
- datalist = document.getElementById('suggest');
- datalist.removeChild(datalist.children[1]);
- waitForMenuChange(0);
- break;
-
- case 203:
- // Change the first element value attribute.
- restoreForm();
- datalist = document.getElementById('suggest');
- prevValue = datalist.children[0].value;
- datalist.children[0].value = "foo";
- expectPopup();
- break;
-
- case 204:
- doKey("down");
- doKey("return");
- checkForm("foo");
-
- datalist = document.getElementById('suggest');
- datalist.children[0].value = prevValue;
- waitForMenuChange(0);
- break;
-
- case 205:
- // Change the textContent to update the value attribute.
- restoreForm();
- datalist = document.getElementById('suggest');
- prevValue = datalist.children[0].getAttribute('value');
- datalist.children[0].removeAttribute('value');
- datalist.children[0].textContent = "foobar";
- expectPopup();
- break;
-
- case 206:
- doKey("down");
- doKey("return");
- checkForm("foobar");
-
- datalist = document.getElementById('suggest');
- datalist.children[0].setAttribute('value', prevValue);
- testNum = 299;
- waitForMenuChange(0);
- break;
-
- // Tests for filtering (or not).
- case 300:
- // Filters with first letter of the word.
- restoreForm();
- synthesizeKey("f", {});
- expectPopup();
- break;
-
- case 301:
- doKey("down");
- doKey("return");
- checkForm("final");
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 302:
- // Filter with a letter in the middle of the word.
- synthesizeKey("i", {});
- synthesizeKey("n", {});
- waitForMenuChange(1);
- break;
-
- case 303:
- // Continuation of test 302.
- doKey("down");
- doKey("return");
- checkForm("final");
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 304:
- // Filter is disabled with mozNoFilter.
- input.setAttribute('mozNoFilter', 'true');
- synthesizeKey("f", {});
- waitForMenuChange(3); // no change
- break;
-
- case 305:
- // Continuation of test 304.
- doKey("down");
- doKey("return");
- checkForm("Google");
- input.removeAttribute('mozNoFilter');
- testNum = 399;
- expectPopup();
- restoreForm();
- doKey("down");
- break;
-
- case 400:
- // Check that the input event is fired.
- input.addEventListener("input", function(event) {
- input.removeEventListener("input", arguments.callee, false);
- ok(true, "oninput should have been received");
- ok(event.bubbles, "input event should bubble");
- ok(event.cancelable, "input event should be cancelable");
- checkForm("Google");
- input.blur();
- SimpleTest.finish();
- }, false);
-
- doKey("down");
- checkForm("");
- doKey("return");
- break;
-
- default:
- ok(false, "Unexpected invocation of test #" + testNum);
- SimpleTest.finish();
- return;
- }
-}
-
-function waitForMenuChange(expectedCount) {
- notifyMenuChanged(expectedCount, null, runTest);
-}
-
-function checkMenuEntries(expectedValues, testNumber) {
- var actualValues = getMenuEntries();
- is(actualValues.length, expectedValues.length, testNumber + " Checking length of expected menu");
- for (var i = 0; i < expectedValues.length; i++)
- is(actualValues[i], expectedValues[i], testNumber + " Checking menu entry #"+i);
-}
-
-function startTest() {
- setupFormHistory(runTest);
-}
-
-window.onload = startTest;
-
-SimpleTest.waitForExplicitFinish();
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_form_submission.html b/toolkit/components/satchel/test/test_form_submission.html
deleted file mode 100644
index ecccabcaf..000000000
--- a/toolkit/components/satchel/test/test_form_submission.html
+++ /dev/null
@@ -1,537 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Satchel Test for Form Submisstion</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-<iframe id="iframe" src="https://example.com/tests/toolkit/components/satchel/test/subtst_form_submission_1.html"></iframe>
-<div id="content" style="display: none">
-
- <!-- ===== Things that should not be saved. ===== -->
-
- <!-- autocomplete=off for input -->
- <form id="form1" onsubmit="return checkSubmit(1)">
- <input type="text" name="test1" autocomplete="off">
- <button type="submit">Submit</button>
- </form>
-
- <!-- autocomplete=off for form -->
- <form id="form2" onsubmit="return checkSubmit(2)" autocomplete="off">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- don't save type=hidden -->
- <form id="form3" onsubmit="return checkSubmit(3)">
- <input type="hidden" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- don't save type=checkbox -->
- <form id="form4" onsubmit="return checkSubmit(4)">
- <input type="checkbox" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- Don't save empty values. -->
- <form id="form5" onsubmit="return checkSubmit(5)">
- <input type="text" name="test1" value="originalValue">
- <button type="submit">Submit</button>
- </form>
-
- <!-- Don't save unchanged values. -->
- <form id="form6" onsubmit="return checkSubmit(6)">
- <input type="text" name="test1" value="dontSaveThis">
- <button type="submit">Submit</button>
- </form>
-
- <!-- Don't save unchanged values. (.value not touched) -->
- <form id="form7" onsubmit="return checkSubmit(7)">
- <input type="text" name="test1" value="dontSaveThis">
- <button type="submit">Submit</button>
- </form>
-
- <!-- No field name or ID. -->
- <form id="form8" onsubmit="return checkSubmit(8)">
- <input type="text">
- <button type="submit">Submit</button>
- </form>
-
- <!-- Nothing to save! -->
- <form id="form9" onsubmit="return checkSubmit(9)">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with name too long (300 chars.) -->
- <form id="form10" onsubmit="return checkSubmit(10)">
- <input type="text" name="12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with value too long (300 chars.) -->
- <form id="form11" onsubmit="return checkSubmit(11)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with value of one space (which should be trimmed) -->
- <form id="form12" onsubmit="return checkSubmit(12)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- password field -->
- <form id="form13" onsubmit="return checkSubmit(13)">
- <input type="password" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- password field (type changed after pageload) -->
- <form id="form14" onsubmit="return checkSubmit(14)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with sensitive data (16 digit credit card number) -->
- <form id="form15" onsubmit="return checkSubmit(15)">
- <script type="text/javascript">
- var form = document.getElementById('form15');
- for (let i = 0; i != 10; i++)
- {
- let input = document.createElement('input');
- input.type = 'text';
- input.name = 'test' + (i + 1);
- form.appendChild(input);
- }
- </script>
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with sensitive data (15 digit credit card number) -->
- <form id="form16" onsubmit="return checkSubmit(16)">
- <script type="text/javascript">
- form = document.getElementById('form16');
- for (let i = 0; i != 10; i++)
- {
- let input = document.createElement('input');
- input.type = 'text';
- input.name = 'test' + (i + 1);
- form.appendChild(input);
- }
- </script>
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with sensitive data (9 digit credit card number) -->
- <form id="form17" onsubmit="return checkSubmit(17)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with sensitive data (16 digit hyphenated credit card number) -->
- <form id="form18" onsubmit="return checkSubmit(18)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with sensitive data (15 digit whitespace-separated credit card number) -->
- <form id="form19" onsubmit="return checkSubmit(19)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- form data submitted through HTTPS, when browser.formfill.saveHttpsForms is false -->
- <form id="form20" action="https://www.example.com/" onsubmit="return checkSubmit(20)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- Form 21 is submitted into an iframe, not declared here. -->
-
- <!-- Don't save values if the form is invalid. -->
- <form id="form22" onsubmit="return checkSubmit(22);">
- <input type='email' name='test1' oninvalid="return checkSubmit(22);">
- <button type='submit'>Submit</button>
- </form>
-
- <!-- Don't save values if the form is invalid. -->
- <form id="form23" onsubmit="return checkSubmit(23);">
- <input type='email' value='foo' oninvalid="return checkSubmit(23);">
- <input type='text' name='test1'>
- <button type='submit'>Submit</button>
- </form>
-
- <!-- Don't save values if the input name is 'searchbar-history' -->
- <form id="form24" onsubmit="return checkSubmit(24);">
- <input type='text' name='searchbar-history'>
- <button type='submit'>Submit</button>
- </form>
-
- <!-- ===== Things that should be saved ===== -->
-
- <!-- Form 100 is submitted into an iframe, not declared here. -->
-
- <!-- input with no default value -->
- <form id="form101" onsubmit="return checkSubmit(101)">
- <input type="text" name="test1">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with a default value -->
- <form id="form102" onsubmit="return checkSubmit(102)">
- <input type="text" name="test2" value="originalValue">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input uses id but not name -->
- <form id="form103" onsubmit="return checkSubmit(103)">
- <input type="text" id="test3">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with leading and trailing space -->
- <form id="form104" onsubmit="return checkSubmit(104)">
- <input type="text" name="test4">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input with leading and trailing whitespace -->
- <form id="form105" onsubmit="return checkSubmit(105)">
- <input type="text" name="test5">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input that looks like sensitive data but doesn't
- satisfy the requirements (incorrect length) -->
- <form id="form106" onsubmit="return checkSubmit(106)">
- <input type="text" name="test6">
- <button type="submit">Submit</button>
- </form>
-
- <!-- input that looks like sensitive data but doesn't
- satisfy the requirements (Luhn check fails for 16 chars) -->
- <form id="form107" onsubmit="return checkSubmit(107)">
- <script type="text/javascript">
- form = document.getElementById('form107');
- for (let i = 0; i != 10; i++)
- {
- let input = document.createElement('input');
- input.type = 'text';
- input.name = 'test7_' + (i + 1);
- form.appendChild(input);
- }
- </script>
- <button type="submit">Submit</button>
- </form>
-
- <!-- input that looks like sensitive data but doesn't
- satisfy the requirements (Luhn check fails for 15 chars) -->
- <form id="form108" onsubmit="return checkSubmit(108)">
- <script type="text/javascript">
- form = document.getElementById('form108');
- for (let i = 0; i != 10; i++)
- {
- let input = document.createElement('input');
- input.type = 'text';
- input.name = 'test8_' + (i + 1);
- form.appendChild(input);
- }
- </script>
- <button type="submit">Submit</button>
- </form>
-
- <!-- form data submitted through HTTPS, when browser.formfill.saveHttpsForms is true -->
- <form id="form109" action="https://www.example.com/" onsubmit="return checkSubmit(109)">
- <input type="text" name="test9">
- <button type="submit">Submit</button>
- </form>
-
- <!-- regular form data, when browser.formfill.saveHttpsForms is false -->
- <form id="form110" onsubmit="return checkSubmit(110)">
- <input type="text" name="test10">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-var numSubmittedForms = 0;
-
-var ccNumbers = {
- valid15: [
- "930771457288760", "474915027480942",
- "924894781317325", "714816113937185",
- "790466087343106", "474320195408363",
- "219211148122351", "633038472250799",
- "354236732906484", "095347810189325",
- ],
- valid16: [
- "3091269135815020", "5471839082338112",
- "0580828863575793", "5015290610002932",
- "9465714503078607", "4302068493801686",
- "2721398408985465", "6160334316984331",
- "8643619970075142", "0218246069710785"
- ],
- invalid15: [
- "526931005800649", "724952425140686",
- "379761391174135", "030551436468583",
- "947377014076746", "254848023655752",
- "226871580283345", "708025346034339",
- "917585839076788", "918632588027666"
- ],
- invalid16: [
- "9946177098017064", "4081194386488872",
- "3095975979578034", "3662215692222536",
- "6723210018630429", "4411962856225025",
- "8276996369036686", "4449796938248871",
- "3350852696538147", "5011802870046957"
- ],
-};
-
-function checkInitialState() {
- countEntries(null, null,
- function (num) {
- ok(!num, "checking for initially empty storage");
- startTest();
- });
-}
-
-function startTest() {
- // Fill in values for the various fields. We could just set the <input>'s
- // value attribute, but we don't save default form values (and we want to
- // ensure unsaved values are because of autocomplete=off or whatever).
- $_(1, "test1").value = "dontSaveThis";
- $_(2, "test1").value = "dontSaveThis";
- $_(3, "test1").value = "dontSaveThis";
- $_(4, "test1").value = "dontSaveThis";
- $_(5, "test1").value = "";
- $_(6, "test1").value = "dontSaveThis";
- // Form 7 deliberately left untouched.
- // Form 8 has an input with no name or input attribute.
- let input = document.getElementById("form8").elements[0];
- is(input.type, "text", "checking we got unidentified input");
- input.value = "dontSaveThis";
- // Form 9 has nothing to modify.
- $_(10, "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890").value = "dontSaveThis";
- $_(11, "test1").value = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
- $_(12, "test1").value = " ";
- $_(13, "test1").value = "dontSaveThis";
- $_(14, "test1").type = "password";
- $_(14, "test1").value = "dontSaveThis";
-
- var testData = ccNumbers.valid16;
- for (let i = 0; i != testData.length; i++) {
- $_(15, "test" + (i + 1)).value = testData[i];
- }
-
- testData = ccNumbers.valid15;
- for (let i = 0; i != testData.length; i++) {
- $_(16, "test" + (i + 1)).value = testData[i];
- }
- $_(17, "test1").value = "001064088";
- $_(18, "test1").value = "0000-0000-0080-4609";
- $_(19, "test1").value = "0000 0000 0222 331";
- $_(20, "test1").value = "dontSaveThis";
- $_(22, "test1").value = "dontSaveThis";
- $_(23, "test1").value = "dontSaveThis";
- $_(24, "searchbar-history").value = "dontSaveThis";
-
- $_(101, "test1").value = "savedValue";
- $_(102, "test2").value = "savedValue";
- $_(103, "test3").value = "savedValue";
- $_(104, "test4").value = " trimTrailingAndLeadingSpace ";
- $_(105, "test5").value = "\t trimTrailingAndLeadingWhitespace\t ";
- $_(106, "test6").value = "00000000109181";
-
- testData = ccNumbers.invalid16;
- for (let i = 0; i != testData.length; i++) {
- $_(107, "test7_" + (i + 1)).value = testData[i];
- }
-
- testData = ccNumbers.invalid15;
- for (let i = 0; i != testData.length; i++) {
- $_(108, "test8_" + (i + 1)).value = testData[i];
- }
-
- $_(109, "test9").value = "savedValue";
- $_(110, "test10").value = "savedValue";
-
- // submit the first form.
- var button = getFormSubmitButton(1);
- button.click();
-}
-
-
-// Called by each form's onsubmit handler.
-function checkSubmit(formNum) {
- netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
- ok(true, "form " + formNum + " submitted");
- numSubmittedForms++;
-
- // Check for expected storage state.
- switch (formNum) {
- // Test 1-24 should not save anything.
- case 1:
- case 2:
- case 3:
- case 4:
- case 5:
- case 6:
- case 7:
- case 8:
- case 9:
- case 10:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15:
- case 16:
- case 17:
- case 18:
- case 19:
- case 20:
- case 21:
- case 22:
- case 23:
- case 24:
- countEntries(null, null,
- function (num) {
- ok(!num, "checking for empty storage");
- submitForm(formNum);
- });
- return false;
- case 100:
- checkForSave("subtest2", "subtestValue", "checking saved subtest value");
- break;
- case 101:
- checkForSave("test1", "savedValue", "checking saved value");
- break;
- case 102:
- checkForSave("test2", "savedValue", "checking saved value");
- break;
- case 103:
- checkForSave("test3", "savedValue", "checking saved value");
- break;
- case 104:
- checkForSave("test4", "trimTrailingAndLeadingSpace", "checking saved value is trimmed on both sides");
- break;
- case 105:
- checkForSave("test5", "trimTrailingAndLeadingWhitespace", "checking saved value is trimmed on both sides");
- break;
- case 106:
- checkForSave("test6", "00000000109181", "checking saved value");
- break;
- case 107:
- for (let i = 0; i != ccNumbers.invalid16.length; i++) {
- checkForSave("test7_" + (i + 1), ccNumbers.invalid16[i], "checking saved value");
- }
- break;
- case 108:
- for (let i = 0; i != ccNumbers.invalid15.length; i++) {
- checkForSave("test8_" + (i + 1), ccNumbers.invalid15[i], "checking saved value");
- }
- break;
- case 109:
- checkForSave("test9", "savedValue", "checking saved value");
- break;
- case 110:
- checkForSave("test10", "savedValue", "checking saved value");
- break;
- default:
- ok(false, "Unexpected form submission");
- break;
- }
-
- return submitForm(formNum);
-}
-
-function submitForm(formNum)
-{
- // Forms 13 and 14 would trigger a save-password notification. Temporarily
- // disable pwmgr, then reenable it.
- if (formNum == 12)
- SpecialPowers.setBoolPref("signon.rememberSignons", false);
- if (formNum == 14)
- SpecialPowers.clearUserPref("signon.rememberSignons");
-
- // Forms 20 and 21 requires browser.formfill.saveHttpsForms to be false
- if (formNum == 19)
- SpecialPowers.setBoolPref("browser.formfill.saveHttpsForms", false);
- // Reset preference now that 20 and 21 are over
- if (formNum == 21)
- SpecialPowers.clearUserPref("browser.formfill.saveHttpsForms");
-
- // End the test now on SeaMonkey.
- if (formNum == 21 && navigator.userAgent.match(/ SeaMonkey\//)) {
- checkObserver.uninit();
- is(numSubmittedForms, 21, "Ensuring all forms were submitted.");
-
- todo(false, "Skipping remaining checks on SeaMonkey ftb. (Bug 589471)");
- // finish(), yet let the test actually end first, to be safe.
- SimpleTest.executeSoon(SimpleTest.finish);
-
- return false; // return false to cancel current form submission
- }
-
- // Form 109 requires browser.formfill.save_https_forms to be true;
- // Form 110 requires it to be false.
- if (formNum == 108)
- SpecialPowers.setBoolPref("browser.formfill.saveHttpsForms", true);
- if (formNum == 109)
- SpecialPowers.setBoolPref("browser.formfill.saveHttpsForms", false);
- if (formNum == 110)
- SpecialPowers.clearUserPref("browser.formfill.saveHttpsForms");
-
- // End the test at the last form.
- if (formNum == 110) {
- is(numSubmittedForms, 35, "Ensuring all forms were submitted.");
- checkObserver.uninit();
- SimpleTest.finish();
- return false; // return false to cancel current form submission
- }
-
- // This timeout is here so that button.click() is never called before this
- // function returns. If button.click() is called before returning, a long
- // chain of submits will happen recursively since the submit is dispatched
- // immediately.
- //
- // This in itself is fine, but if there are errors in the code, mochitests
- // will in some cases give you "server too busy", which is hard to debug!
- //
- setTimeout(function() {
- checkObserver.waitForChecks(function() {
- var nextFormNum = formNum == 24 ? 100 : (formNum + 1);
-
- // Submit the next form. Special cases are Forms 21 and 100, which happen
- // from an HTTPS domain in an iframe.
- if (nextFormNum == 21 || nextFormNum == 100) {
- ok(true, "submitting iframe test " + nextFormNum);
- document.getElementById("iframe").contentWindow.clickButton(nextFormNum);
- }
- else {
- var button = getFormSubmitButton(nextFormNum);
- button.click();
- }
- });
- }, 0);
-
- return false; // cancel current form submission
-}
-
-checkObserver.init();
-
-window.onload = checkInitialState;
-
-SimpleTest.waitForExplicitFinish();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_form_submission_cap.html b/toolkit/components/satchel/test/test_form_submission_cap.html
deleted file mode 100644
index 96112f1c1..000000000
--- a/toolkit/components/satchel/test/test_form_submission_cap.html
+++ /dev/null
@@ -1,85 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Satchel Test for Form Submisstion Field Cap</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-
- <form id="form1" onsubmit="return checkSubmit(1)">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-/* Test for bug 492701.
- Save only the first MAX_FIELDS_SAVED changed fields in a form.
- Generate numInputFields = MAX_FIELDS_SAVED + 1 fields, change all values,
- and test that only MAX_FIELDS_SAVED are actually saved and that
- field # numInputFields was not saved.
-*/
-
-var numSubmittedForms = 0;
-var numInputFields = 101;
-
-function checkInitialState() {
- countEntries(null, null,
- function (num) {
- ok(!num, "checking for initially empty storage");
- startTest();
- });
-}
-
-function startTest() {
- var form = document.getElementById("form1");
- for (i = 1; i <= numInputFields; i++) {
- var newField = document.createElement("input");
- newField.setAttribute("type", "text");
- newField.setAttribute("name", "test" + i);
- form.appendChild(newField);
- }
-
- // Fill in values for the various fields. We could just set the <input>'s
- // value attribute, but we don't save default form values (and we want to
- // ensure unsaved values are because of autocomplete=off or whatever).
- for (i = 1; i <= numInputFields; i++) {
- $_(1, "test" + i).value = i;
- }
-
- // submit the first form.
- var button = getFormSubmitButton(1);
- button.click();
-}
-
-
-// Called by each form's onsubmit handler.
-function checkSubmit(formNum) {
- ok(true, "form " + formNum + " submitted");
- numSubmittedForms++;
-
- // check that the first (numInputFields - 1) CHANGED fields are saved
- for (i = 1; i < numInputFields; i++) { // check all but last
- checkForSave("test" + i, i, "checking saved value " + i);
- }
-
- // End the test.
- is(numSubmittedForms, 1, "Ensuring all forms were submitted.");
- SimpleTest.finish();
- return false; // return false to cancel current form submission
-}
-
-
-window.onload = checkInitialState;
-
-SimpleTest.waitForExplicitFinish();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_form_submission_cap2.html b/toolkit/components/satchel/test/test_form_submission_cap2.html
deleted file mode 100644
index f51fb5f47..000000000
--- a/toolkit/components/satchel/test/test_form_submission_cap2.html
+++ /dev/null
@@ -1,190 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Satchel Test for Form Submisstion Field Cap</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-<!--
- Test for bug 492701.
- Only change field # numInputFields (= MAX_FIELDS_SAVED + 1)
- and test that it is actually saved and the other (unmodified) ones are not.
--->
- <form id="form1" onsubmit="return checkSubmit(1)">
- <input type="text" name="test1" value="1">
- <input type="text" name="test2" value="2">
- <input type="text" name="test3" value="3">
- <input type="text" name="test4" value="4">
- <input type="text" name="test5" value="5">
- <input type="text" name="test6" value="6">
- <input type="text" name="test7" value="7">
- <input type="text" name="test8" value="8">
- <input type="text" name="test9" value="9">
- <input type="text" name="test10" value="10">
- <input type="text" name="test11" value="11">
- <input type="text" name="test12" value="12">
- <input type="text" name="test13" value="13">
- <input type="text" name="test14" value="14">
- <input type="text" name="test15" value="15">
- <input type="text" name="test16" value="16">
- <input type="text" name="test17" value="17">
- <input type="text" name="test18" value="18">
- <input type="text" name="test19" value="19">
- <input type="text" name="test20" value="20">
- <input type="text" name="test21" value="21">
- <input type="text" name="test22" value="22">
- <input type="text" name="test23" value="23">
- <input type="text" name="test24" value="24">
- <input type="text" name="test25" value="25">
- <input type="text" name="test26" value="26">
- <input type="text" name="test27" value="27">
- <input type="text" name="test28" value="28">
- <input type="text" name="test29" value="29">
- <input type="text" name="test30" value="30">
- <input type="text" name="test31" value="31">
- <input type="text" name="test32" value="32">
- <input type="text" name="test33" value="33">
- <input type="text" name="test34" value="34">
- <input type="text" name="test35" value="35">
- <input type="text" name="test36" value="36">
- <input type="text" name="test37" value="37">
- <input type="text" name="test38" value="38">
- <input type="text" name="test39" value="39">
- <input type="text" name="test40" value="40">
- <input type="text" name="test41" value="41">
- <input type="text" name="test42" value="42">
- <input type="text" name="test43" value="43">
- <input type="text" name="test44" value="44">
- <input type="text" name="test45" value="45">
- <input type="text" name="test46" value="46">
- <input type="text" name="test47" value="47">
- <input type="text" name="test48" value="48">
- <input type="text" name="test49" value="49">
- <input type="text" name="test50" value="50">
- <input type="text" name="test51" value="51">
- <input type="text" name="test52" value="52">
- <input type="text" name="test53" value="53">
- <input type="text" name="test54" value="54">
- <input type="text" name="test55" value="55">
- <input type="text" name="test56" value="56">
- <input type="text" name="test57" value="57">
- <input type="text" name="test58" value="58">
- <input type="text" name="test59" value="59">
- <input type="text" name="test60" value="60">
- <input type="text" name="test61" value="61">
- <input type="text" name="test62" value="62">
- <input type="text" name="test63" value="63">
- <input type="text" name="test64" value="64">
- <input type="text" name="test65" value="65">
- <input type="text" name="test66" value="66">
- <input type="text" name="test67" value="67">
- <input type="text" name="test68" value="68">
- <input type="text" name="test69" value="69">
- <input type="text" name="test70" value="70">
- <input type="text" name="test71" value="71">
- <input type="text" name="test72" value="72">
- <input type="text" name="test73" value="73">
- <input type="text" name="test74" value="74">
- <input type="text" name="test75" value="75">
- <input type="text" name="test76" value="76">
- <input type="text" name="test77" value="77">
- <input type="text" name="test78" value="78">
- <input type="text" name="test79" value="79">
- <input type="text" name="test80" value="80">
- <input type="text" name="test81" value="81">
- <input type="text" name="test82" value="82">
- <input type="text" name="test83" value="83">
- <input type="text" name="test84" value="84">
- <input type="text" name="test85" value="85">
- <input type="text" name="test86" value="86">
- <input type="text" name="test87" value="87">
- <input type="text" name="test88" value="88">
- <input type="text" name="test89" value="89">
- <input type="text" name="test90" value="90">
- <input type="text" name="test91" value="91">
- <input type="text" name="test92" value="92">
- <input type="text" name="test93" value="93">
- <input type="text" name="test94" value="94">
- <input type="text" name="test95" value="95">
- <input type="text" name="test96" value="96">
- <input type="text" name="test97" value="97">
- <input type="text" name="test98" value="98">
- <input type="text" name="test99" value="99">
- <input type="text" name="test100" value="100">
- <input type="text" name="test101" value="101">
- <button type="submit">Submit</button>
- </form>
-
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-var numSubmittedForms = 0;
-var numInputFields = 101;
-
-function checkInitialState() {
- countEntries(null, null,
- function (num) {
- ok(!num, "checking for initially empty storage");
- startTest();
- });
-}
-
-function startTest() {
- // Fill in values for the various fields. We could just set the <input>'s
- // value attribute, but we don't save default form values (and we want to
- // ensure unsaved values are because of autocomplete=off or whatever).
- $_(1, "test" + numInputFields).value = numInputFields + " changed";
-
- // submit the first form.
- var button = getFormSubmitButton(1);
- button.click();
-}
-
-// Make sure that the first (numInputFields - 1) were not saved (as they were not changed).
-// Call done() when finished.
-function checkCountEntries(formNum, index, done)
-{
- countEntries("test" + index, index,
- function (num) {
- ok(!num, "checking unsaved value " + index);
- if (index < numInputFields) {
- checkCountEntries(formNum, index + 1, done);
- }
- else {
- done(formNum);
- }
- });
-}
-
-// Called by each form's onsubmit handler.
-function checkSubmit(formNum) {
- ok(true, "form " + formNum + " submitted");
- numSubmittedForms++;
-
- // make sure that the field # numInputFields was saved
- checkForSave("test" + numInputFields, numInputFields + " changed", "checking saved value " + numInputFields);
-
- checkCountEntries(formNum, 1, checkSubmitCounted);
-
- return false; // cancel current form submission
-}
-
-function checkSubmitCounted(formNum) {
- is(numSubmittedForms, 1, "Ensuring all forms were submitted.");
- SimpleTest.finish();
- return false;
-}
-
-window.onload = checkInitialState;
-
-SimpleTest.waitForExplicitFinish();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_password_autocomplete.html b/toolkit/components/satchel/test/test_password_autocomplete.html
deleted file mode 100644
index 82781ae35..000000000
--- a/toolkit/components/satchel/test/test_password_autocomplete.html
+++ /dev/null
@@ -1,107 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for form history on type=password</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
- Test for form history on type=password
- (based on test_bug_511615.html)
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
- <datalist id="datalist1">
- <option>value10</option>
- <option>value11</option>
- <option>value12</option>
- </datalist>
- <form id="form1" onsubmit="return false;">
- <!-- Don't set the type to password until rememberSignons is false since we
- want to test when rememberSignons is false. -->
- <input type="to-be-password" name="field1" list="datalist1">
- <button type="submit">Submit</button>
- </form>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-/* import-globals-from satchel_common.js */
-
-var resolvePopupShownListener;
-registerPopupShownListener(() => resolvePopupShownListener());
-
-function waitForNextPopup() {
- return new Promise(resolve => { resolvePopupShownListener = resolve; });
-}
-
-/**
- * Indicates the time to wait before checking that the state of the autocomplete
- * popup, including whether it is open, has not changed in response to events.
- *
- * Manual testing on a fast machine revealed that 80ms was still unreliable,
- * while 100ms detected a simulated failure reliably. Unfortunately, this means
- * that to take into account slower machines we should use a larger value.
- *
- * Note that if a machine takes more than this time to show the popup, this
- * would not cause a failure, conversely the machine would not be able to detect
- * whether the test should have failed. In other words, this use of timeouts is
- * never expected to cause intermittent failures with test automation.
- */
-const POPUP_RESPONSE_WAIT_TIME_MS = 200;
-
-SimpleTest.requestFlakyTimeout("Must ensure that an event does not happen.");
-
-/**
- * Checks that the popup does not open in response to the given function.
- */
-function expectPopupDoesNotOpen(triggerFn) {
- let popupShown = waitForNextPopup();
- triggerFn();
- return Promise.race([
- popupShown.then(() => Promise.reject("Popup opened unexpectedly.")),
- new Promise(resolve => setTimeout(resolve, POPUP_RESPONSE_WAIT_TIME_MS)),
- ]);
-}
-
-add_task(function* test_initialize() {
- yield SpecialPowers.pushPrefEnv({"set": [["signon.rememberSignons", false]]});
-
- // Now that rememberSignons is false, create the password field
- $_(1, "field1").type = "password";
-
- yield new Promise(resolve => updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "value1" },
- { op : "add", fieldname : "field1", value : "value2" },
- { op : "add", fieldname : "field1", value : "value3" },
- { op : "add", fieldname : "field1", value : "value4" },
- { op : "add", fieldname : "field1", value : "value5" },
- { op : "add", fieldname : "field1", value : "value6" },
- { op : "add", fieldname : "field1", value : "value7" },
- { op : "add", fieldname : "field1", value : "value8" },
- { op : "add", fieldname : "field1", value : "value9" },
- ], resolve));
-});
-
-add_task(function* test_insecure_focusWarning() {
- // The form is insecure so should show the warning even if password manager is disabled.
- let input = $_(1, "field1");
- let shownPromise = waitForNextPopup();
- input.focus();
- yield shownPromise;
-
- ok(getMenuEntries()[0].includes("Logins entered here could be compromised"),
- "Check warning is first")
-
- // Close the popup
- input.blur();
-});
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_popup_direction.html b/toolkit/components/satchel/test/test_popup_direction.html
deleted file mode 100644
index 02e044bbd..000000000
--- a/toolkit/components/satchel/test/test_popup_direction.html
+++ /dev/null
@@ -1,61 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test for Popup Direction</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Test for Popup Direction
-<p id="display"></p>
-
-<!-- we presumably can't hide the content for this test. -->
-<div id="content">
- <!-- normal, basic form -->
- <form id="form1" onsubmit="return false;">
- <input type="text" name="field1">
- <button type="submit">Submit</button>
- </form>
-</div>
-
-<pre id="test">
-<script class="testbody" type="text/javascript">
-
-var resolvePopupShownListener;
-registerPopupShownListener(() => resolvePopupShownListener());
-
-function waitForNextPopup() {
- return new Promise(resolve => { resolvePopupShownListener = resolve; });
-}
-
-add_task(function* test_popup_direction() {
- var input = $_(1, "field1");
-
- yield new Promise(resolve => updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "value1" },
- { op : "add", fieldname : "field1", value : "value2" },
- ], resolve));
-
- for (let direction of ["ltr", "rtl"]) {
- document.getElementById("content").style.direction = direction;
-
- let popupShown = waitForNextPopup();
- input.focus();
- doKey("down");
- yield popupShown;
-
- let popupState = yield new Promise(resolve => getPopupState(resolve));
- is(popupState.direction, direction, "Direction should match.");
-
- // Close the popup.
- input.blur();
- }
-});
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/test_popup_enter_event.html b/toolkit/components/satchel/test/test_popup_enter_event.html
deleted file mode 100644
index 1a7aa8c19..000000000
--- a/toolkit/components/satchel/test/test_popup_enter_event.html
+++ /dev/null
@@ -1,86 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test for events while the form history popup is open</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
- <script type="text/javascript" src="satchel_common.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-Form History test: Test for events while the form history popup is open
-<p id="display"></p>
-
-<div id="content">
- <form id="form1">
- <input type="text" name="field1">
- <button type="submit">Submit</button>
- </form>
-</div>
-
-<pre id="test">
-<script class="testbody">
-var form = document.getElementById("form1");
-var input = $_(1, "field1");
-var expectedValue = "value1";
-
-function setupFormHistory(aCallback) {
- updateFormHistory([
- { op : "remove" },
- { op : "add", fieldname : "field1", value : "value1" },
- ], aCallback);
-}
-
-registerPopupShownListener(popupShownListener);
-
-function handleEnter(evt) {
- if (evt.keyCode != KeyEvent.DOM_VK_RETURN) {
- return;
- }
-
- info("RETURN received for phase: " + evt.eventPhase);
- if (input.value == expectedValue) {
- ok(true, "RETURN should be received when the popup is closed");
- is(input.value, expectedValue, "Check input value when enter is pressed the 2nd time");
- info("form should submit with the default handler");
- } else {
- ok(false, "RETURN keypress shouldn't have been received when a popup item is selected");
- }
-}
-
-function popupShownListener(evt) {
- doKey("down");
- doKey("return"); // select the first entry in the popup
- doKey("return"); // try to submit the form with the filled value
-}
-
-function runTest() {
- input.addEventListener("keypress", handleEnter, true);
- form.addEventListener("submit", evt => {
- is(input.value, expectedValue, "Check input value in the submit handler");
- evt.preventDefault();
- SimpleTest.finish();
- });
-
- // Focus the input before adjusting.value so that the caret goes to the end
- // (since OS X doesn't show the dropdown otherwise).
- input.focus();
- input.value = "value"
- input.focus();
- doKey("down");
-}
-
-function startTest() {
- setupFormHistory(function() {
- runTest();
- });
-}
-
-window.onload = startTest;
-
-SimpleTest.waitForExplicitFinish();
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/satchel/test/unit/.eslintrc.js b/toolkit/components/satchel/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/satchel/test/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/satchel/test/unit/asyncformhistory_expire.sqlite b/toolkit/components/satchel/test/unit/asyncformhistory_expire.sqlite
deleted file mode 100644
index 07b43c209..000000000
--- a/toolkit/components/satchel/test/unit/asyncformhistory_expire.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/formhistory_1000.sqlite b/toolkit/components/satchel/test/unit/formhistory_1000.sqlite
deleted file mode 100644
index 5eeab074f..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_1000.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/formhistory_CORRUPT.sqlite b/toolkit/components/satchel/test/unit/formhistory_CORRUPT.sqlite
deleted file mode 100644
index 5f7498bfc..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_CORRUPT.sqlite
+++ /dev/null
@@ -1 +0,0 @@
-BACON
diff --git a/toolkit/components/satchel/test/unit/formhistory_apitest.sqlite b/toolkit/components/satchel/test/unit/formhistory_apitest.sqlite
deleted file mode 100644
index 00daf03c2..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_apitest.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/formhistory_autocomplete.sqlite b/toolkit/components/satchel/test/unit/formhistory_autocomplete.sqlite
deleted file mode 100644
index 724cff73f..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_autocomplete.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/formhistory_v3.sqlite b/toolkit/components/satchel/test/unit/formhistory_v3.sqlite
deleted file mode 100644
index e0e8fe246..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_v3.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/formhistory_v3v4.sqlite b/toolkit/components/satchel/test/unit/formhistory_v3v4.sqlite
deleted file mode 100644
index 8eab177e9..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_v3v4.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/formhistory_v999a.sqlite b/toolkit/components/satchel/test/unit/formhistory_v999a.sqlite
deleted file mode 100644
index 14279f05f..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_v999a.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/formhistory_v999b.sqlite b/toolkit/components/satchel/test/unit/formhistory_v999b.sqlite
deleted file mode 100644
index 21d9c1f1c..000000000
--- a/toolkit/components/satchel/test/unit/formhistory_v999b.sqlite
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/satchel/test/unit/head_satchel.js b/toolkit/components/satchel/test/unit/head_satchel.js
deleted file mode 100644
index 282d07ba5..000000000
--- a/toolkit/components/satchel/test/unit/head_satchel.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/. */
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://gre/modules/FormHistory.jsm");
-
-var Ci = Components.interfaces;
-var Cc = Components.classes;
-var Cu = Components.utils;
-
-const CURRENT_SCHEMA = 4;
-const PR_HOURS = 60 * 60 * 1000000;
-
-do_get_profile();
-
-var dirSvc = Cc["@mozilla.org/file/directory_service;1"].
- getService(Ci.nsIProperties);
-
-// Send the profile-after-change notification to the form history component to ensure
-// that it has been initialized.
-var formHistoryStartup = Cc["@mozilla.org/satchel/form-history-startup;1"].
- getService(Ci.nsIObserver);
-formHistoryStartup.observe(null, "profile-after-change", null);
-
-function getDBVersion(dbfile) {
- var ss = Cc["@mozilla.org/storage/service;1"].
- getService(Ci.mozIStorageService);
- var dbConnection = ss.openDatabase(dbfile);
- var version = dbConnection.schemaVersion;
- dbConnection.close();
-
- return version;
-}
-
-const isGUID = /[A-Za-z0-9\+\/]{16}/;
-
-// Find form history entries.
-function searchEntries(terms, params, iter) {
- let results = [];
- FormHistory.search(terms, params, { handleResult: result => results.push(result),
- handleError: function (error) {
- do_throw("Error occurred searching form history: " + error);
- },
- handleCompletion: function (reason) { if (!reason) iter.next(results); }
- });
-}
-
-// Count the number of entries with the given name and value, and call then(number)
-// when done. If name or value is null, then the value of that field does not matter.
-function countEntries(name, value, then) {
- var obj = {};
- if (name !== null)
- obj.fieldname = name;
- if (value !== null)
- obj.value = value;
-
- let count = 0;
- FormHistory.count(obj, { handleResult: result => count = result,
- handleError: function (error) {
- do_throw("Error occurred searching form history: " + error);
- },
- handleCompletion: function (reason) { if (!reason) then(count); }
- });
-}
-
-// Perform a single form history update and call then() when done.
-function updateEntry(op, name, value, then) {
- var obj = { op: op };
- if (name !== null)
- obj.fieldname = name;
- if (value !== null)
- obj.value = value;
- updateFormHistory(obj, then);
-}
-
-// Add a single form history entry with the current time and call then() when done.
-function addEntry(name, value, then) {
- let now = Date.now() * 1000;
- updateFormHistory({ op: "add", fieldname: name, value: value, timesUsed: 1,
- firstUsed: now, lastUsed: now }, then);
-}
-
-// Wrapper around FormHistory.update which handles errors. Calls then() when done.
-function updateFormHistory(changes, then) {
- FormHistory.update(changes, { handleError: function (error) {
- do_throw("Error occurred updating form history: " + error);
- },
- handleCompletion: function (reason) { if (!reason) then(); },
- });
-}
-
-/**
- * Logs info to the console in the standard way (includes the filename).
- *
- * @param aMessage
- * The message to log to the console.
- */
-function do_log_info(aMessage) {
- print("TEST-INFO | " + _TEST_FILE + " | " + aMessage);
-}
diff --git a/toolkit/components/satchel/test/unit/perf_autocomplete.js b/toolkit/components/satchel/test/unit/perf_autocomplete.js
deleted file mode 100644
index 6e8bb5125..000000000
--- a/toolkit/components/satchel/test/unit/perf_autocomplete.js
+++ /dev/null
@@ -1,140 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 testnum = 0;
-var fh;
-var fac;
-var prefs;
-
-function countAllEntries() {
- let stmt = fh.DBConnection.createStatement("SELECT COUNT(*) as numEntries FROM moz_formhistory");
- do_check_true(stmt.executeStep());
- let numEntries = stmt.row.numEntries;
- stmt.finalize();
- return numEntries;
-}
-
-function do_AC_search(searchTerm, previousResult) {
- var duration = 0;
- var searchCount = 5;
- var tempPrevious = null;
- var startTime;
- for (var i = 0; i < searchCount; i++) {
- if (previousResult !== null)
- tempPrevious = fac.autoCompleteSearch("searchbar-history", previousResult, null, null);
- startTime = Date.now();
- results = fac.autoCompleteSearch("searchbar-history", searchTerm, null, tempPrevious);
- duration += Date.now() - startTime;
- }
- dump("[autoCompleteSearch][test " + testnum + "] for '" + searchTerm + "' ");
- if (previousResult !== null)
- dump("with '" + previousResult + "' previous result ");
- else
- dump("w/o previous result ");
- dump("took " + duration + " ms with " + results.matchCount + " matches. ");
- dump("Average of " + Math.round(duration / searchCount) + " ms per search\n");
- return results;
-}
-
-function run_test() {
- try {
-
- // ===== test init =====
- var testfile = do_get_file("formhistory_1000.sqlite");
- var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
- var results;
-
- // Cleanup from any previous tests or failures.
- var destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
-
- fh = Cc["@mozilla.org/satchel/form-history;1"].
- getService(Ci.nsIFormHistory2);
- fac = Cc["@mozilla.org/satchel/form-autocomplete;1"].
- getService(Ci.nsIFormAutoComplete);
- prefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-
- timeGroupingSize = prefs.getIntPref("browser.formfill.timeGroupingSize") * 1000 * 1000;
- maxTimeGroupings = prefs.getIntPref("browser.formfill.maxTimeGroupings");
- bucketSize = prefs.getIntPref("browser.formfill.bucketSize");
-
- // ===== 1 =====
- // Check initial state is as expected
- testnum++;
- do_check_true(fh.hasEntries);
- do_check_eq(1000, countAllEntries());
- fac.autoCompleteSearch("searchbar-history", "zzzzzzzzzz", null, null); // warm-up search
- do_check_true(fh.nameExists("searchbar-history"));
-
- // ===== 2 =====
- // Search for '' with no previous result
- testnum++;
- results = do_AC_search("", null);
- do_check_true(results.matchCount > 0);
-
- // ===== 3 =====
- // Search for 'r' with no previous result
- testnum++;
- results = do_AC_search("r", null);
- do_check_true(results.matchCount > 0);
-
- // ===== 4 =====
- // Search for 'r' with '' previous result
- testnum++;
- results = do_AC_search("r", "");
- do_check_true(results.matchCount > 0);
-
- // ===== 5 =====
- // Search for 're' with no previous result
- testnum++;
- results = do_AC_search("re", null);
- do_check_true(results.matchCount > 0);
-
- // ===== 6 =====
- // Search for 're' with 'r' previous result
- testnum++;
- results = do_AC_search("re", "r");
- do_check_true(results.matchCount > 0);
-
- // ===== 7 =====
- // Search for 'rea' without previous result
- testnum++;
- results = do_AC_search("rea", null);
- let countREA = results.matchCount;
-
- // ===== 8 =====
- // Search for 'rea' with 're' previous result
- testnum++;
- results = do_AC_search("rea", "re");
- do_check_eq(countREA, results.matchCount);
-
- // ===== 9 =====
- // Search for 'real' with 'rea' previous result
- testnum++;
- results = do_AC_search("real", "rea");
- let countREAL = results.matchCount;
- do_check_true(results.matchCount <= countREA);
-
- // ===== 10 =====
- // Search for 'real' with 're' previous result
- testnum++;
- results = do_AC_search("real", "re");
- do_check_eq(countREAL, results.matchCount);
-
- // ===== 11 =====
- // Search for 'real' with no previous result
- testnum++;
- results = do_AC_search("real", null);
- do_check_eq(countREAL, results.matchCount);
-
-
- } catch (e) {
- throw "FAILED in test #" + testnum + " -- " + e;
- }
-}
diff --git a/toolkit/components/satchel/test/unit/test_async_expire.js b/toolkit/components/satchel/test/unit/test_async_expire.js
deleted file mode 100644
index 501cbdfe5..000000000
--- a/toolkit/components/satchel/test/unit/test_async_expire.js
+++ /dev/null
@@ -1,168 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 dbFile, oldSize;
-var currentTestIndex = 0;
-
-function triggerExpiration() {
- // We can't easily fake a "daily idle" event, so for testing purposes form
- // history listens for another notification to trigger an immediate
- // expiration.
- Services.obs.notifyObservers(null, "formhistory-expire-now", null);
-}
-
-var checkExists = function(num) { do_check_true(num > 0); next_test(); }
-var checkNotExists = function(num) { do_check_true(!num); next_test(); }
-
-var TestObserver = {
- QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
-
- observe : function (subject, topic, data) {
- do_check_eq(topic, "satchel-storage-changed");
-
- if (data == "formhistory-expireoldentries") {
- next_test();
- }
- }
-};
-
-function test_finished() {
- // Make sure we always reset prefs.
- if (Services.prefs.prefHasUserValue("browser.formfill.expire_days"))
- Services.prefs.clearUserPref("browser.formfill.expire_days");
-
- do_test_finished();
-}
-
-var iter = tests();
-
-function run_test()
-{
- do_test_pending();
- iter.next();
-}
-
-function next_test()
-{
- iter.next();
-}
-
-function* tests()
-{
- Services.obs.addObserver(TestObserver, "satchel-storage-changed", true);
-
- // ===== test init =====
- var testfile = do_get_file("asyncformhistory_expire.sqlite");
- var profileDir = do_get_profile();
-
- // Cleanup from any previous tests or failures.
- dbFile = profileDir.clone();
- dbFile.append("formhistory.sqlite");
- if (dbFile.exists())
- dbFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
- do_check_true(dbFile.exists());
-
- // We're going to clear this at the end, so it better have the default value now.
- do_check_false(Services.prefs.prefHasUserValue("browser.formfill.expire_days"));
-
- // Sanity check initial state
- yield countEntries(null, null, function(num) { do_check_eq(508, num); next_test(); });
- yield countEntries("name-A", "value-A", checkExists); // lastUsed == distant past
- yield countEntries("name-B", "value-B", checkExists); // lastUsed == distant future
-
- do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
-
- // Add a new entry
- yield countEntries("name-C", "value-C", checkNotExists);
- yield addEntry("name-C", "value-C", next_test);
- yield countEntries("name-C", "value-C", checkExists);
-
- // Update some existing entries to have ages relative to when the test runs.
- var now = 1000 * Date.now();
- let updateLastUsed = function updateLastUsedFn(results, age)
- {
- let lastUsed = now - age * 24 * PR_HOURS;
-
- let changes = [ ];
- for (let r = 0; r < results.length; r++) {
- changes.push({ op: "update", lastUsed: lastUsed, guid: results[r].guid });
- }
-
- return changes;
- }
-
- let results = yield searchEntries(["guid"], { lastUsed: 181 }, iter);
- yield updateFormHistory(updateLastUsed(results, 181), next_test);
-
- results = yield searchEntries(["guid"], { lastUsed: 179 }, iter);
- yield updateFormHistory(updateLastUsed(results, 179), next_test);
-
- results = yield searchEntries(["guid"], { lastUsed: 31 }, iter);
- yield updateFormHistory(updateLastUsed(results, 31), next_test);
-
- results = yield searchEntries(["guid"], { lastUsed: 29 }, iter);
- yield updateFormHistory(updateLastUsed(results, 29), next_test);
-
- results = yield searchEntries(["guid"], { lastUsed: 9999 }, iter);
- yield updateFormHistory(updateLastUsed(results, 11), next_test);
-
- results = yield searchEntries(["guid"], { lastUsed: 9 }, iter);
- yield updateFormHistory(updateLastUsed(results, 9), next_test);
-
- yield countEntries("name-A", "value-A", checkExists);
- yield countEntries("181DaysOld", "foo", checkExists);
- yield countEntries("179DaysOld", "foo", checkExists);
- yield countEntries(null, null, function(num) { do_check_eq(509, num); next_test(); });
-
- // 2 entries are expected to expire.
- triggerExpiration();
- yield;
-
- yield countEntries("name-A", "value-A", checkNotExists);
- yield countEntries("181DaysOld", "foo", checkNotExists);
- yield countEntries("179DaysOld", "foo", checkExists);
- yield countEntries(null, null, function(num) { do_check_eq(507, num); next_test(); });
-
- // And again. No change expected.
- triggerExpiration();
- yield;
-
- yield countEntries(null, null, function(num) { do_check_eq(507, num); next_test(); });
-
- // Set formfill pref to 30 days.
- Services.prefs.setIntPref("browser.formfill.expire_days", 30);
- yield countEntries("179DaysOld", "foo", checkExists);
- yield countEntries("bar", "31days", checkExists);
- yield countEntries("bar", "29days", checkExists);
- yield countEntries(null, null, function(num) { do_check_eq(507, num); next_test(); });
-
- triggerExpiration();
- yield;
-
- yield countEntries("179DaysOld", "foo", checkNotExists);
- yield countEntries("bar", "31days", checkNotExists);
- yield countEntries("bar", "29days", checkExists);
- yield countEntries(null, null, function(num) { do_check_eq(505, num); next_test(); });
-
- // Set override pref to 10 days and expire. This expires a large batch of
- // entries, and should trigger a VACCUM to reduce file size.
- Services.prefs.setIntPref("browser.formfill.expire_days", 10);
-
- yield countEntries("bar", "29days", checkExists);
- yield countEntries("9DaysOld", "foo", checkExists);
- yield countEntries(null, null, function(num) { do_check_eq(505, num); next_test(); });
-
- triggerExpiration();
- yield;
-
- yield countEntries("bar", "29days", checkNotExists);
- yield countEntries("9DaysOld", "foo", checkExists);
- yield countEntries("name-B", "value-B", checkExists);
- yield countEntries("name-C", "value-C", checkExists);
- yield countEntries(null, null, function(num) { do_check_eq(3, num); next_test(); });
-
- test_finished();
-}
diff --git a/toolkit/components/satchel/test/unit/test_autocomplete.js b/toolkit/components/satchel/test/unit/test_autocomplete.js
deleted file mode 100644
index 211753809..000000000
--- a/toolkit/components/satchel/test/unit/test_autocomplete.js
+++ /dev/null
@@ -1,266 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-var testnum = 0;
-var fac;
-var prefs;
-
-var numRecords, timeGroupingSize, now;
-
-const DEFAULT_EXPIRE_DAYS = 180;
-
-function padLeft(number, length) {
- var str = number + '';
- while (str.length < length)
- str = '0' + str;
- return str;
-}
-
-function getFormExpiryDays() {
- if (prefs.prefHasUserValue("browser.formfill.expire_days")) {
- return prefs.getIntPref("browser.formfill.expire_days");
- }
- return DEFAULT_EXPIRE_DAYS;
-}
-
-function run_test() {
- // ===== test init =====
- var testfile = do_get_file("formhistory_autocomplete.sqlite");
- var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
-
- // Cleanup from any previous tests or failures.
- var destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
-
- fac = Cc["@mozilla.org/satchel/form-autocomplete;1"].
- getService(Ci.nsIFormAutoComplete);
- prefs = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-
- timeGroupingSize = prefs.getIntPref("browser.formfill.timeGroupingSize") * 1000 * 1000;
-
- run_next_test();
-}
-
-add_test(function test0() {
- var maxTimeGroupings = prefs.getIntPref("browser.formfill.maxTimeGroupings");
- var bucketSize = prefs.getIntPref("browser.formfill.bucketSize");
-
- // ===== Tests with constant timesUsed and varying lastUsed date =====
- // insert 2 records per bucket to check alphabetical sort within
- now = 1000 * Date.now();
- numRecords = Math.ceil(maxTimeGroupings / bucketSize) * 2;
-
- let changes = [ ];
- for (let i = 0; i < numRecords; i+=2) {
- let useDate = now - (i/2 * bucketSize * timeGroupingSize);
-
- changes.push({ op : "add", fieldname: "field1", value: "value" + padLeft(numRecords - 1 - i, 2),
- timesUsed: 1, firstUsed: useDate, lastUsed: useDate });
- changes.push({ op : "add", fieldname: "field1", value: "value" + padLeft(numRecords - 2 - i, 2),
- timesUsed: 1, firstUsed: useDate, lastUsed: useDate });
- }
-
- updateFormHistory(changes, run_next_test);
-});
-
-add_test(function test1() {
- do_log_info("Check initial state is as expected");
-
- countEntries(null, null, function () {
- countEntries("field1", null, function (count) {
- do_check_true(count > 0);
- run_next_test();
- });
- });
-});
-
-add_test(function test2() {
- do_log_info("Check search contains all entries");
-
- fac.autoCompleteSearchAsync("field1", "", null, null, null, {
- onSearchCompletion : function(aResults) {
- do_check_eq(numRecords, aResults.matchCount);
- run_next_test();
- }
- });
-});
-
-add_test(function test3() {
- do_log_info("Check search result ordering with empty search term");
-
- let lastFound = numRecords;
- fac.autoCompleteSearchAsync("field1", "", null, null, null, {
- onSearchCompletion : function(aResults) {
- for (let i = 0; i < numRecords; i+=2) {
- do_check_eq(parseInt(aResults.getValueAt(i + 1).substr(5), 10), --lastFound);
- do_check_eq(parseInt(aResults.getValueAt(i).substr(5), 10), --lastFound);
- }
- run_next_test();
- }
- });
-});
-
-add_test(function test4() {
- do_log_info("Check search result ordering with \"v\"");
-
- let lastFound = numRecords;
- fac.autoCompleteSearchAsync("field1", "v", null, null, null, {
- onSearchCompletion : function(aResults) {
- for (let i = 0; i < numRecords; i+=2) {
- do_check_eq(parseInt(aResults.getValueAt(i + 1).substr(5), 10), --lastFound);
- do_check_eq(parseInt(aResults.getValueAt(i).substr(5), 10), --lastFound);
- }
- run_next_test();
- }
- });
-});
-
-const timesUsedSamples = 20;
-
-add_test(function test5() {
- do_log_info("Begin tests with constant use dates and varying timesUsed");
-
- let changes = [];
- for (let i = 0; i < timesUsedSamples; i++) {
- let timesUsed = (timesUsedSamples - i);
- let change = { op : "add", fieldname: "field2", value: "value" + (timesUsedSamples - 1 - i),
- timesUsed: timesUsed * timeGroupingSize, firstUsed: now, lastUsed: now };
- changes.push(change);
- }
- updateFormHistory(changes, run_next_test);
-});
-
-add_test(function test6() {
- do_log_info("Check search result ordering with empty search term");
-
- let lastFound = timesUsedSamples;
- fac.autoCompleteSearchAsync("field2", "", null, null, null, {
- onSearchCompletion : function(aResults) {
- for (let i = 0; i < timesUsedSamples; i++) {
- do_check_eq(parseInt(aResults.getValueAt(i).substr(5)), --lastFound);
- }
- run_next_test();
- }
- });
-});
-
-add_test(function test7() {
- do_log_info("Check search result ordering with \"v\"");
-
- let lastFound = timesUsedSamples;
- fac.autoCompleteSearchAsync("field2", "v", null, null, null, {
- onSearchCompletion : function(aResults) {
- for (let i = 0; i < timesUsedSamples; i++) {
- do_check_eq(parseInt(aResults.getValueAt(i).substr(5)), --lastFound);
- }
- run_next_test();
- }
- });
-});
-
-add_test(function test8() {
- do_log_info("Check that \"senior citizen\" entries get a bonus (browser.formfill.agedBonus)");
-
- let agedDate = 1000 * (Date.now() - getFormExpiryDays() * 24 * 60 * 60 * 1000);
-
- let changes = [ ];
- changes.push({ op : "add", fieldname: "field3", value: "old but not senior",
- timesUsed: 100, firstUsed: (agedDate + 60 * 1000 * 1000), lastUsed: now });
- changes.push({ op : "add", fieldname: "field3", value: "senior citizen",
- timesUsed: 100, firstUsed: (agedDate - 60 * 1000 * 1000), lastUsed: now });
- updateFormHistory(changes, run_next_test);
-});
-
-add_test(function test9() {
- fac.autoCompleteSearchAsync("field3", "", null, null, null, {
- onSearchCompletion : function(aResults) {
- do_check_eq(aResults.getValueAt(0), "senior citizen");
- do_check_eq(aResults.getValueAt(1), "old but not senior");
- run_next_test();
- }
- });
-});
-
-add_test(function test10() {
- do_log_info("Check entries that are really old or in the future");
-
- let changes = [ ];
- changes.push({ op : "add", fieldname: "field4", value: "date of 0",
- timesUsed: 1, firstUsed: 0, lastUsed: 0 });
- changes.push({ op : "add", fieldname: "field4", value: "in the future 1",
- timesUsed: 1, firstUsed: 0, lastUsed: now * 2 });
- changes.push({ op : "add", fieldname: "field4", value: "in the future 2",
- timesUsed: 1, firstUsed: now * 2, lastUsed: now * 2 });
- updateFormHistory(changes, run_next_test);
-});
-
-add_test(function test11() {
- fac.autoCompleteSearchAsync("field4", "", null, null, null, {
- onSearchCompletion : function(aResults) {
- do_check_eq(aResults.matchCount, 3);
- run_next_test();
- }
- });
-});
-
-var syncValues = ["sync1", "sync1a", "sync2", "sync3"]
-
-add_test(function test12() {
- do_log_info("Check old synchronous api");
-
- let changes = [ ];
- for (let value of syncValues) {
- changes.push({ op : "add", fieldname: "field5", value: value });
- }
- updateFormHistory(changes, run_next_test);
-});
-
-add_test(function test_token_limit_DB() {
- function test_token_limit_previousResult(previousResult) {
- do_log_info("Check that the number of tokens used in a search is not capped to " +
- "MAX_SEARCH_TOKENS when using a previousResult");
- // This provide more accuracy since performance is less of an issue.
- // Search for a string where the first 10 tokens match the previous value but the 11th does not
- // when re-using a previous result.
- fac.autoCompleteSearchAsync("field_token_cap",
- "a b c d e f g h i j .",
- null, previousResult, null, {
- onSearchCompletion : function(aResults) {
- do_check_eq(aResults.matchCount, 0,
- "All search tokens should be used with " +
- "previous results");
- run_next_test();
- }
- });
- }
-
- do_log_info("Check that the number of tokens used in a search is capped to MAX_SEARCH_TOKENS " +
- "for performance when querying the DB");
- let changes = [ ];
- changes.push({ op : "add", fieldname: "field_token_cap",
- // value with 15 unique tokens
- value: "a b c d e f g h i j k l m n o",
- timesUsed: 1, firstUsed: 0, lastUsed: 0 });
- updateFormHistory(changes, () => {
- // Search for a string where the first 10 tokens match the value above but the 11th does not
- // (which would prevent the result from being returned if the 11th term was used).
- fac.autoCompleteSearchAsync("field_token_cap",
- "a b c d e f g h i j .",
- null, null, null, {
- onSearchCompletion : function(aResults) {
- do_check_eq(aResults.matchCount, 1,
- "Only the first MAX_SEARCH_TOKENS tokens " +
- "should be used for DB queries");
- test_token_limit_previousResult(aResults);
- }
- });
- });
-});
diff --git a/toolkit/components/satchel/test/unit/test_db_corrupt.js b/toolkit/components/satchel/test/unit/test_db_corrupt.js
deleted file mode 100644
index a6fdc4c02..000000000
--- a/toolkit/components/satchel/test/unit/test_db_corrupt.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/. */
-
-var bakFile;
-
-function run_test() {
- // ===== test init =====
- let testfile = do_get_file("formhistory_CORRUPT.sqlite");
- let profileDir = dirSvc.get("ProfD", Ci.nsIFile);
-
- // Cleanup from any previous tests or failures.
- let destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- bakFile = profileDir.clone();
- bakFile.append("formhistory.sqlite.corrupt");
- if (bakFile.exists())
- bakFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
- run_next_test();
-}
-
-add_test(function test_corruptFormHistoryDB_lazyCorruptInit1() {
- do_log_info("ensure FormHistory backs up a corrupt DB on initialization.");
-
- // DB init is done lazily so the DB shouldn't be created yet.
- do_check_false(bakFile.exists());
- // Doing any request to the DB should create it.
- countEntries(null, null, run_next_test);
-});
-
-add_test(function test_corruptFormHistoryDB_lazyCorruptInit2() {
- do_check_true(bakFile.exists());
- bakFile.remove(false);
- run_next_test();
-});
-
-
-add_test(function test_corruptFormHistoryDB_emptyInit() {
- do_log_info("test that FormHistory initializes an empty DB in place of corrupt DB.");
-
- FormHistory.count({}, {
- handleResult : function(aNumEntries) {
- do_check_true(aNumEntries == 0);
- FormHistory.count({ fieldname : "name-A", value : "value-A" }, {
- handleResult : function(aNumEntries2) {
- do_check_true(aNumEntries2 == 0);
- run_next_test();
- },
- handleError : function(aError2) {
- do_throw("DB initialized after reading a corrupt DB file found an entry.");
- }
- });
- },
- handleError : function (aError) {
- do_throw("DB initialized after reading a corrupt DB file is not empty.");
- }
- });
-});
-
-add_test(function test_corruptFormHistoryDB_addEntry() {
- do_log_info("test adding an entry to the empty DB.");
-
- updateEntry("add", "name-A", "value-A",
- function() {
- countEntries("name-A", "value-A",
- function(count) {
- do_check_true(count == 1);
- run_next_test();
- });
- });
- });
-
-add_test(function test_corruptFormHistoryDB_removeEntry() {
- do_log_info("test removing an entry to the empty DB.");
-
- updateEntry("remove", "name-A", "value-A",
- function() {
- countEntries("name-A", "value-A",
- function(count) {
- do_check_true(count == 0);
- run_next_test();
- });
- });
- });
diff --git a/toolkit/components/satchel/test/unit/test_db_update_v4.js b/toolkit/components/satchel/test/unit/test_db_update_v4.js
deleted file mode 100644
index 84b17e8a0..000000000
--- a/toolkit/components/satchel/test/unit/test_db_update_v4.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-var testnum = 0;
-
-var iter;
-
-function run_test()
-{
- do_test_pending();
- iter = next_test();
- iter.next();
-}
-
-function* next_test()
-{
- try {
-
- // ===== test init =====
- var testfile = do_get_file("formhistory_v3.sqlite");
- var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
-
- // Cleanup from any previous tests or failures.
- var destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
- do_check_eq(3, getDBVersion(testfile));
-
- // ===== 1 =====
- testnum++;
-
- destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- let dbConnection = Services.storage.openUnsharedDatabase(destFile);
-
- // check for upgraded schema.
- do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
-
- // Check that the index was added
- do_check_true(dbConnection.tableExists("moz_deleted_formhistory"));
- dbConnection.close();
-
- // check for upgraded schema.
- do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
- // check that an entry still exists
- yield countEntries("name-A", "value-A",
- function (num) {
- do_check_true(num > 0);
- do_test_finished();
- }
- );
-
- } catch (e) {
- throw "FAILED in test #" + testnum + " -- " + e;
- }
-}
diff --git a/toolkit/components/satchel/test/unit/test_db_update_v4b.js b/toolkit/components/satchel/test/unit/test_db_update_v4b.js
deleted file mode 100644
index 356d34a48..000000000
--- a/toolkit/components/satchel/test/unit/test_db_update_v4b.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/. */
-
-var testnum = 0;
-
-var iter;
-
-function run_test()
-{
- do_test_pending();
- iter = next_test();
- iter.next();
-}
-
-function* next_test()
-{
- try {
-
- // ===== test init =====
- var testfile = do_get_file("formhistory_v3v4.sqlite");
- var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
-
- // Cleanup from any previous tests or failures.
- var destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
- do_check_eq(3, getDBVersion(testfile));
-
- // ===== 1 =====
- testnum++;
-
- destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- dbConnection = Services.storage.openUnsharedDatabase(destFile);
-
- // check for upgraded schema.
- do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
-
- // Check that the index was added
- do_check_true(dbConnection.tableExists("moz_deleted_formhistory"));
- dbConnection.close();
-
- // check that an entry still exists
- yield countEntries("name-A", "value-A",
- function (num) {
- do_check_true(num > 0);
- do_test_finished();
- }
- );
-
- } catch (e) {
- throw "FAILED in test #" + testnum + " -- " + e;
- }
-}
diff --git a/toolkit/components/satchel/test/unit/test_db_update_v999a.js b/toolkit/components/satchel/test/unit/test_db_update_v999a.js
deleted file mode 100644
index 0a44d06aa..000000000
--- a/toolkit/components/satchel/test/unit/test_db_update_v999a.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * This test uses a formhistory.sqlite with schema version set to 999 (a
- * future version). This exercies the code that allows using a future schema
- * version as long as the expected columns are present.
- *
- * Part A tests this when the columns do match, so the DB is used.
- * Part B tests this when the columns do *not* match, so the DB is reset.
- */
-
-var iter = tests();
-
-function run_test()
-{
- do_test_pending();
- iter.next();
-}
-
-function next_test()
-{
- iter.next();
-}
-
-function* tests()
-{
- try {
- var testnum = 0;
-
- // ===== test init =====
- var testfile = do_get_file("formhistory_v999a.sqlite");
- var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
-
- // Cleanup from any previous tests or failures.
- var destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
- do_check_eq(999, getDBVersion(testfile));
-
- let checkZero = function(num) { do_check_eq(num, 0); next_test(); }
- let checkOne = function(num) { do_check_eq(num, 1); next_test(); }
-
- // ===== 1 =====
- testnum++;
- // Check for expected contents.
- yield countEntries(null, null, function(num) { do_check_true(num > 0); next_test(); });
- yield countEntries("name-A", "value-A", checkOne);
- yield countEntries("name-B", "value-B", checkOne);
- yield countEntries("name-C", "value-C1", checkOne);
- yield countEntries("name-C", "value-C2", checkOne);
- yield countEntries("name-E", "value-E", checkOne);
-
- // check for downgraded schema.
- do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
-
- // ===== 2 =====
- testnum++;
- // Exercise adding and removing a name/value pair
- yield countEntries("name-D", "value-D", checkZero);
- yield updateEntry("add", "name-D", "value-D", next_test);
- yield countEntries("name-D", "value-D", checkOne);
- yield updateEntry("remove", "name-D", "value-D", next_test);
- yield countEntries("name-D", "value-D", checkZero);
-
- } catch (e) {
- throw "FAILED in test #" + testnum + " -- " + e;
- }
-
- do_test_finished();
-}
diff --git a/toolkit/components/satchel/test/unit/test_db_update_v999b.js b/toolkit/components/satchel/test/unit/test_db_update_v999b.js
deleted file mode 100644
index fb0ecd1b7..000000000
--- a/toolkit/components/satchel/test/unit/test_db_update_v999b.js
+++ /dev/null
@@ -1,92 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * This test uses a formhistory.sqlite with schema version set to 999 (a
- * future version). This exercies the code that allows using a future schema
- * version as long as the expected columns are present.
- *
- * Part A tests this when the columns do match, so the DB is used.
- * Part B tests this when the columns do *not* match, so the DB is reset.
- */
-
-var iter = tests();
-
-function run_test()
-{
- do_test_pending();
- iter.next();
-}
-
-function next_test()
-{
- iter.next();
-}
-
-function* tests()
-{
- try {
- var testnum = 0;
-
- // ===== test init =====
- var testfile = do_get_file("formhistory_v999b.sqlite");
- var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
-
- // Cleanup from any previous tests or failures.
- var destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- var bakFile = profileDir.clone();
- bakFile.append("formhistory.sqlite.corrupt");
- if (bakFile.exists())
- bakFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
- do_check_eq(999, getDBVersion(testfile));
-
- let checkZero = function(num) { do_check_eq(num, 0); next_test(); }
- let checkOne = function(num) { do_check_eq(num, 1); next_test(); }
-
- // ===== 1 =====
- testnum++;
-
- // Open the DB, ensure that a backup of the corrupt DB is made.
- // DB init is done lazily so the DB shouldn't be created yet.
- do_check_false(bakFile.exists());
- // Doing any request to the DB should create it.
- yield countEntries("", "", next_test);
-
- do_check_true(bakFile.exists());
- bakFile.remove(false);
-
- // ===== 2 =====
- testnum++;
- // File should be empty
- yield countEntries(null, null, function(num) { do_check_false(num); next_test(); });
- yield countEntries("name-A", "value-A", checkZero);
- // check for current schema.
- do_check_eq(CURRENT_SCHEMA, FormHistory.schemaVersion);
-
- // ===== 3 =====
- testnum++;
- // Try adding an entry
- yield updateEntry("add", "name-A", "value-A", next_test);
- yield countEntries(null, null, checkOne);
- yield countEntries("name-A", "value-A", checkOne);
-
- // ===== 4 =====
- testnum++;
- // Try removing an entry
- yield updateEntry("remove", "name-A", "value-A", next_test);
- yield countEntries(null, null, checkZero);
- yield countEntries("name-A", "value-A", checkZero);
-
- } catch (e) {
- throw "FAILED in test #" + testnum + " -- " + e;
- }
-
- do_test_finished();
-}
diff --git a/toolkit/components/satchel/test/unit/test_history_api.js b/toolkit/components/satchel/test/unit/test_history_api.js
deleted file mode 100644
index 753504183..000000000
--- a/toolkit/components/satchel/test/unit/test_history_api.js
+++ /dev/null
@@ -1,457 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 testnum = 0;
-var dbConnection; // used for deleted table tests
-
-Cu.import("resource://gre/modules/Promise.jsm");
-
-function countDeletedEntries(expected)
-{
- let deferred = Promise.defer();
- let stmt = dbConnection.createAsyncStatement("SELECT COUNT(*) AS numEntries FROM moz_deleted_formhistory");
- stmt.executeAsync({
- handleResult: function(resultSet) {
- do_check_eq(expected, resultSet.getNextRow().getResultByName("numEntries"));
- deferred.resolve();
- },
- handleError : function () {
- do_throw("Error occurred counting deleted entries: " + error);
- deferred.reject();
- },
- handleCompletion : function () {
- stmt.finalize();
- }
- });
- return deferred.promise;
-}
-
-function checkTimeDeleted(guid, checkFunction)
-{
- let deferred = Promise.defer();
- let stmt = dbConnection.createAsyncStatement("SELECT timeDeleted FROM moz_deleted_formhistory WHERE guid = :guid");
- stmt.params.guid = guid;
- stmt.executeAsync({
- handleResult: function(resultSet) {
- checkFunction(resultSet.getNextRow().getResultByName("timeDeleted"));
- deferred.resolve();
- },
- handleError : function () {
- do_throw("Error occurred getting deleted entries: " + error);
- deferred.reject();
- },
- handleCompletion : function () {
- stmt.finalize();
- }
- });
- return deferred.promise;
-}
-
-function promiseUpdateEntry(op, name, value)
-{
- var change = { op: op };
- if (name !== null)
- change.fieldname = name;
- if (value !== null)
- change.value = value;
- return promiseUpdate(change);
-}
-
-function promiseUpdate(change) {
- return new Promise((resolve, reject) => {
- FormHistory.update(change, {
- handleError(error) {
- this._error = error;
- },
- handleCompletion(reason) {
- if (reason) {
- reject(this._error);
- } else {
- resolve();
- }
- }
- });
- });
-}
-
-function promiseSearchEntries(terms, params)
-{
- let deferred = Promise.defer();
- let results = [];
- FormHistory.search(terms, params,
- { handleResult: result => results.push(result),
- handleError: function (error) {
- do_throw("Error occurred searching form history: " + error);
- deferred.reject(error);
- },
- handleCompletion: function (reason) { if (!reason) deferred.resolve(results); }
- });
- return deferred.promise;
-}
-
-function promiseCountEntries(name, value, checkFn)
-{
- let deferred = Promise.defer();
- countEntries(name, value, function (result) { checkFn(result); deferred.resolve(); } );
- return deferred.promise;
-}
-
-add_task(function* ()
-{
- let oldSupportsDeletedTable = FormHistory._supportsDeletedTable;
- FormHistory._supportsDeletedTable = true;
-
- try {
-
- // ===== test init =====
- var testfile = do_get_file("formhistory_apitest.sqlite");
- var profileDir = dirSvc.get("ProfD", Ci.nsIFile);
-
- // Cleanup from any previous tests or failures.
- var destFile = profileDir.clone();
- destFile.append("formhistory.sqlite");
- if (destFile.exists())
- destFile.remove(false);
-
- testfile.copyTo(profileDir, "formhistory.sqlite");
-
- function checkExists(num) { do_check_true(num > 0); }
- function checkNotExists(num) { do_check_true(num == 0); }
-
- // ===== 1 =====
- // Check initial state is as expected
- testnum++;
- yield promiseCountEntries("name-A", null, checkExists);
- yield promiseCountEntries("name-B", null, checkExists);
- yield promiseCountEntries("name-C", null, checkExists);
- yield promiseCountEntries("name-D", null, checkExists);
- yield promiseCountEntries("name-A", "value-A", checkExists);
- yield promiseCountEntries("name-B", "value-B1", checkExists);
- yield promiseCountEntries("name-B", "value-B2", checkExists);
- yield promiseCountEntries("name-C", "value-C", checkExists);
- yield promiseCountEntries("name-D", "value-D", checkExists);
- // time-A/B/C/D checked below.
-
- // Delete anything from the deleted table
- let dbFile = Services.dirsvc.get("ProfD", Ci.nsIFile).clone();
- dbFile.append("formhistory.sqlite");
- dbConnection = Services.storage.openUnsharedDatabase(dbFile);
-
- let deferred = Promise.defer();
-
- let stmt = dbConnection.createAsyncStatement("DELETE FROM moz_deleted_formhistory");
- stmt.executeAsync({
- handleResult: function(resultSet) { },
- handleError : function () {
- do_throw("Error occurred counting deleted all entries: " + error);
- },
- handleCompletion : function () {
- stmt.finalize();
- deferred.resolve();
- }
- });
- yield deferred.promise;
-
- // ===== 2 =====
- // Test looking for nonexistent / bogus data.
- testnum++;
- yield promiseCountEntries("blah", null, checkNotExists);
- yield promiseCountEntries("", null, checkNotExists);
- yield promiseCountEntries("name-A", "blah", checkNotExists);
- yield promiseCountEntries("name-A", "", checkNotExists);
- yield promiseCountEntries("name-A", null, checkExists);
- yield promiseCountEntries("blah", "value-A", checkNotExists);
- yield promiseCountEntries("", "value-A", checkNotExists);
- yield promiseCountEntries(null, "value-A", checkExists);
-
- // Cannot use promiseCountEntries when name and value are null because it treats null values as not set
- // and here a search should be done explicity for null.
- deferred = Promise.defer();
- yield FormHistory.count({ fieldname: null, value: null },
- { handleResult: result => checkNotExists(result),
- handleError: function (error) {
- do_throw("Error occurred searching form history: " + error);
- },
- handleCompletion: function(reason) { if (!reason) deferred.resolve() }
- });
- yield deferred.promise;
-
- // ===== 3 =====
- // Test removeEntriesForName with a single matching value
- testnum++;
- yield promiseUpdateEntry("remove", "name-A", null);
-
- yield promiseCountEntries("name-A", "value-A", checkNotExists);
- yield promiseCountEntries("name-B", "value-B1", checkExists);
- yield promiseCountEntries("name-B", "value-B2", checkExists);
- yield promiseCountEntries("name-C", "value-C", checkExists);
- yield promiseCountEntries("name-D", "value-D", checkExists);
- yield countDeletedEntries(1);
-
- // ===== 4 =====
- // Test removeEntriesForName with multiple matching values
- testnum++;
- yield promiseUpdateEntry("remove", "name-B", null);
-
- yield promiseCountEntries("name-A", "value-A", checkNotExists);
- yield promiseCountEntries("name-B", "value-B1", checkNotExists);
- yield promiseCountEntries("name-B", "value-B2", checkNotExists);
- yield promiseCountEntries("name-C", "value-C", checkExists);
- yield promiseCountEntries("name-D", "value-D", checkExists);
- yield countDeletedEntries(3);
-
- // ===== 5 =====
- // Test removing by time range (single entry, not surrounding entries)
- testnum++;
- yield promiseCountEntries("time-A", null, checkExists); // firstUsed=1000, lastUsed=1000
- yield promiseCountEntries("time-B", null, checkExists); // firstUsed=1000, lastUsed=1099
- yield promiseCountEntries("time-C", null, checkExists); // firstUsed=1099, lastUsed=1099
- yield promiseCountEntries("time-D", null, checkExists); // firstUsed=2001, lastUsed=2001
- yield promiseUpdate({ op : "remove", firstUsedStart: 1050, firstUsedEnd: 2000 });
-
- yield promiseCountEntries("time-A", null, checkExists);
- yield promiseCountEntries("time-B", null, checkExists);
- yield promiseCountEntries("time-C", null, checkNotExists);
- yield promiseCountEntries("time-D", null, checkExists);
- yield countDeletedEntries(4);
-
- // ===== 6 =====
- // Test removing by time range (multiple entries)
- testnum++;
- yield promiseUpdate({ op : "remove", firstUsedStart: 1000, firstUsedEnd: 2000 });
-
- yield promiseCountEntries("time-A", null, checkNotExists);
- yield promiseCountEntries("time-B", null, checkNotExists);
- yield promiseCountEntries("time-C", null, checkNotExists);
- yield promiseCountEntries("time-D", null, checkExists);
- yield countDeletedEntries(6);
-
- // ===== 7 =====
- // test removeAllEntries
- testnum++;
- yield promiseUpdateEntry("remove", null, null);
-
- yield promiseCountEntries("name-C", null, checkNotExists);
- yield promiseCountEntries("name-D", null, checkNotExists);
- yield promiseCountEntries("name-C", "value-C", checkNotExists);
- yield promiseCountEntries("name-D", "value-D", checkNotExists);
-
- yield promiseCountEntries(null, null, checkNotExists);
- yield countDeletedEntries(6);
-
- // ===== 8 =====
- // Add a single entry back
- testnum++;
- yield promiseUpdateEntry("add", "newname-A", "newvalue-A");
- yield promiseCountEntries("newname-A", "newvalue-A", checkExists);
-
- // ===== 9 =====
- // Remove the single entry
- testnum++;
- yield promiseUpdateEntry("remove", "newname-A", "newvalue-A");
- yield promiseCountEntries("newname-A", "newvalue-A", checkNotExists);
-
- // ===== 10 =====
- // Add a single entry
- testnum++;
- yield promiseUpdateEntry("add", "field1", "value1");
- yield promiseCountEntries("field1", "value1", checkExists);
-
- let processFirstResult = function processResults(results)
- {
- // Only handle the first result
- if (results.length > 0) {
- let result = results[0];
- return [result.timesUsed, result.firstUsed, result.lastUsed, result.guid];
- }
- return undefined;
- }
-
- results = yield promiseSearchEntries(["timesUsed", "firstUsed", "lastUsed"],
- { fieldname: "field1", value: "value1" });
- let [timesUsed, firstUsed, lastUsed] = processFirstResult(results);
- do_check_eq(1, timesUsed);
- do_check_true(firstUsed > 0);
- do_check_true(lastUsed > 0);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 1));
-
- // ===== 11 =====
- // Add another single entry
- testnum++;
- yield promiseUpdateEntry("add", "field1", "value1b");
- yield promiseCountEntries("field1", "value1", checkExists);
- yield promiseCountEntries("field1", "value1b", checkExists);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 2));
-
- // ===== 12 =====
- // Update a single entry
- testnum++;
-
- results = yield promiseSearchEntries(["guid"], { fieldname: "field1", value: "value1" });
- let guid = processFirstResult(results)[3];
-
- yield promiseUpdate({ op : "update", guid: guid, value: "modifiedValue" });
- yield promiseCountEntries("field1", "modifiedValue", checkExists);
- yield promiseCountEntries("field1", "value1", checkNotExists);
- yield promiseCountEntries("field1", "value1b", checkExists);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 2));
-
- // ===== 13 =====
- // Add a single entry with times
- testnum++;
- yield promiseUpdate({ op : "add", fieldname: "field2", value: "value2",
- timesUsed: 20, firstUsed: 100, lastUsed: 500 });
-
- results = yield promiseSearchEntries(["timesUsed", "firstUsed", "lastUsed"],
- { fieldname: "field2", value: "value2" });
- [timesUsed, firstUsed, lastUsed] = processFirstResult(results);
-
- do_check_eq(20, timesUsed);
- do_check_eq(100, firstUsed);
- do_check_eq(500, lastUsed);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 3));
-
- // ===== 14 =====
- // Bump an entry, which updates its lastUsed field
- testnum++;
- yield promiseUpdate({ op : "bump", fieldname: "field2", value: "value2",
- timesUsed: 20, firstUsed: 100, lastUsed: 500 });
- results = yield promiseSearchEntries(["timesUsed", "firstUsed", "lastUsed"],
- { fieldname: "field2", value: "value2" });
- [timesUsed, firstUsed, lastUsed] = processFirstResult(results);
- do_check_eq(21, timesUsed);
- do_check_eq(100, firstUsed);
- do_check_true(lastUsed > 500);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 3));
-
- // ===== 15 =====
- // Bump an entry that does not exist
- testnum++;
- yield promiseUpdate({ op : "bump", fieldname: "field3", value: "value3",
- timesUsed: 10, firstUsed: 50, lastUsed: 400 });
- results = yield promiseSearchEntries(["timesUsed", "firstUsed", "lastUsed"],
- { fieldname: "field3", value: "value3" });
- [timesUsed, firstUsed, lastUsed] = processFirstResult(results);
- do_check_eq(10, timesUsed);
- do_check_eq(50, firstUsed);
- do_check_eq(400, lastUsed);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 4));
-
- // ===== 16 =====
- // Bump an entry with a guid
- testnum++;
- results = yield promiseSearchEntries(["guid"], { fieldname: "field3", value: "value3" });
- guid = processFirstResult(results)[3];
- yield promiseUpdate({ op : "bump", guid: guid, timesUsed: 20, firstUsed: 55, lastUsed: 400 });
- results = yield promiseSearchEntries(["timesUsed", "firstUsed", "lastUsed"],
- { fieldname: "field3", value: "value3" });
- [timesUsed, firstUsed, lastUsed] = processFirstResult(results);
- do_check_eq(11, timesUsed);
- do_check_eq(50, firstUsed);
- do_check_true(lastUsed > 400);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 4));
-
- // ===== 17 =====
- // Remove an entry
- testnum++;
- yield countDeletedEntries(7);
-
- results = yield promiseSearchEntries(["guid"], { fieldname: "field1", value: "value1b" });
- guid = processFirstResult(results)[3];
-
- yield promiseUpdate({ op : "remove", guid: guid});
- yield promiseCountEntries("field1", "modifiedValue", checkExists);
- yield promiseCountEntries("field1", "value1b", checkNotExists);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 3));
-
- yield countDeletedEntries(8);
- yield checkTimeDeleted(guid, timeDeleted => do_check_true(timeDeleted > 10000));
-
- // ===== 18 =====
- // Add yet another single entry
- testnum++;
- yield promiseUpdate({ op : "add", fieldname: "field4", value: "value4",
- timesUsed: 5, firstUsed: 230, lastUsed: 600 });
- yield promiseCountEntries(null, null, num => do_check_eq(num, 4));
-
- // ===== 19 =====
- // Remove an entry by time
- testnum++;
- yield promiseUpdate({ op : "remove", firstUsedStart: 60, firstUsedEnd: 250 });
- yield promiseCountEntries("field1", "modifiedValue", checkExists);
- yield promiseCountEntries("field2", "value2", checkNotExists);
- yield promiseCountEntries("field3", "value3", checkExists);
- yield promiseCountEntries("field4", "value4", checkNotExists);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 2));
- yield countDeletedEntries(10);
-
- // ===== 20 =====
- // Bump multiple existing entries at once
- testnum++;
-
- yield promiseUpdate([{ op : "add", fieldname: "field5", value: "value5",
- timesUsed: 5, firstUsed: 230, lastUsed: 600 },
- { op : "add", fieldname: "field6", value: "value6",
- timesUsed: 12, firstUsed: 430, lastUsed: 700 }]);
- yield promiseCountEntries(null, null, num => do_check_eq(num, 4));
-
- yield promiseUpdate([
- { op : "bump", fieldname: "field5", value: "value5" },
- { op : "bump", fieldname: "field6", value: "value6" }]);
- results = yield promiseSearchEntries(["fieldname", "timesUsed", "firstUsed", "lastUsed"], { });
-
- do_check_eq(6, results[2].timesUsed);
- do_check_eq(13, results[3].timesUsed);
- do_check_eq(230, results[2].firstUsed);
- do_check_eq(430, results[3].firstUsed);
- do_check_true(results[2].lastUsed > 600);
- do_check_true(results[3].lastUsed > 700);
-
- yield promiseCountEntries(null, null, num => do_check_eq(num, 4));
-
- // ===== 21 =====
- // Check update fails if form history is disabled and the operation is not a
- // pure removal.
- testnum++;
- Services.prefs.setBoolPref("browser.formfill.enable", false);
-
- // Cannot use arrow functions, see bug 1237961.
- Assert.rejects(promiseUpdate(
- { op : "bump", fieldname: "field5", value: "value5" }),
- function(err) { return err.result == Ci.mozIStorageError.MISUSE; },
- "bumping when form history is disabled should fail");
- Assert.rejects(promiseUpdate(
- { op : "add", fieldname: "field5", value: "value5" }),
- function(err) { return err.result == Ci.mozIStorageError.MISUSE; },
- "Adding when form history is disabled should fail");
- Assert.rejects(promiseUpdate([
- { op : "update", fieldname: "field5", value: "value5" },
- { op : "remove", fieldname: "field5", value: "value5" }
- ]),
- function(err) { return err.result == Ci.mozIStorageError.MISUSE; },
- "mixed operations when form history is disabled should fail");
- Assert.rejects(promiseUpdate([
- null, undefined, "", 1, {},
- { op : "remove", fieldname: "field5", value: "value5" }
- ]),
- function(err) { return err.result == Ci.mozIStorageError.MISUSE; },
- "Invalid entries when form history is disabled should fail");
-
- // Remove should work though.
- yield promiseUpdate([{ op: "remove", fieldname: "field5", value: null },
- { op: "remove", fieldname: null, value: null }]);
- Services.prefs.clearUserPref("browser.formfill.enable");
-
- } catch (e) {
- throw "FAILED in test #" + testnum + " -- " + e;
- }
- finally {
- FormHistory._supportsDeletedTable = oldSupportsDeletedTable;
- dbConnection.asyncClose(do_test_finished);
- }
-});
-
-function run_test() {
- return run_next_test();
-}
diff --git a/toolkit/components/satchel/test/unit/test_notify.js b/toolkit/components/satchel/test/unit/test_notify.js
deleted file mode 100644
index 556ecd4b0..000000000
--- a/toolkit/components/satchel/test/unit/test_notify.js
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Test suite for satchel notifications
- *
- * Tests notifications dispatched when modifying form history.
- *
- */
-
-var expectedNotification;
-var expectedData;
-
-var TestObserver = {
- QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]),
-
- observe : function (subject, topic, data) {
- do_check_eq(topic, "satchel-storage-changed");
- do_check_eq(data, expectedNotification);
-
- switch (data) {
- case "formhistory-add":
- case "formhistory-update":
- do_check_true(subject instanceof Ci.nsISupportsString);
- do_check_true(isGUID.test(subject.toString()));
- break;
- case "formhistory-remove":
- do_check_eq(null, subject);
- break;
- default:
- do_throw("Unhandled notification: " + data + " / " + topic);
- }
-
- expectedNotification = null;
- expectedData = null;
- }
-};
-
-var testIterator = null;
-
-function run_test() {
- do_test_pending();
- testIterator = run_test_steps();
- testIterator.next();
-}
-
-function next_test()
-{
- testIterator.next();
-}
-
-function* run_test_steps() {
-
-try {
-
-var testnum = 0;
-var testdesc = "Setup of test form history entries";
-
-var entry1 = ["entry1", "value1"];
-
-/* ========== 1 ========== */
-testnum = 1;
-testdesc = "Initial connection to storage module"
-
-yield updateEntry("remove", null, null, next_test);
-yield countEntries(null, null, function (num) { do_check_false(num, "Checking initial DB is empty"); next_test(); });
-
-// Add the observer
-var os = Cc["@mozilla.org/observer-service;1"].
- getService(Ci.nsIObserverService);
-os.addObserver(TestObserver, "satchel-storage-changed", false);
-
-/* ========== 2 ========== */
-testnum++;
-testdesc = "addEntry";
-
-expectedNotification = "formhistory-add";
-expectedData = entry1;
-
-yield updateEntry("add", entry1[0], entry1[1], next_test);
-do_check_eq(expectedNotification, null); // check that observer got a notification
-
-yield countEntries(entry1[0], entry1[1], function (num) { do_check_true(num > 0); next_test(); });
-
-/* ========== 3 ========== */
-testnum++;
-testdesc = "modifyEntry";
-
-expectedNotification = "formhistory-update";
-expectedData = entry1;
-// will update previous entry
-yield updateEntry("update", entry1[0], entry1[1], next_test);
-yield countEntries(entry1[0], entry1[1], function (num) { do_check_true(num > 0); next_test(); });
-
-do_check_eq(expectedNotification, null);
-
-/* ========== 4 ========== */
-testnum++;
-testdesc = "removeEntry";
-
-expectedNotification = "formhistory-remove";
-expectedData = entry1;
-yield updateEntry("remove", entry1[0], entry1[1], next_test);
-
-do_check_eq(expectedNotification, null);
-yield countEntries(entry1[0], entry1[1], function(num) { do_check_false(num, "doesn't exist after remove"); next_test(); });
-
-/* ========== 5 ========== */
-testnum++;
-testdesc = "removeAllEntries";
-
-expectedNotification = "formhistory-remove";
-expectedData = null; // no data expected
-yield updateEntry("remove", null, null, next_test);
-
-do_check_eq(expectedNotification, null);
-
-/* ========== 6 ========== */
-testnum++;
-testdesc = "removeAllEntries (again)";
-
-expectedNotification = "formhistory-remove";
-expectedData = null;
-yield updateEntry("remove", null, null, next_test);
-
-do_check_eq(expectedNotification, null);
-
-/* ========== 7 ========== */
-testnum++;
-testdesc = "removeEntriesForName";
-
-expectedNotification = "formhistory-remove";
-expectedData = "field2";
-yield updateEntry("remove", null, "field2", next_test);
-
-do_check_eq(expectedNotification, null);
-
-/* ========== 8 ========== */
-testnum++;
-testdesc = "removeEntriesByTimeframe";
-
-expectedNotification = "formhistory-remove";
-expectedData = [10, 99999999999];
-
-yield FormHistory.update({ op: "remove", firstUsedStart: expectedData[0], firstUsedEnd: expectedData[1] },
- { handleCompletion: function(reason) { if (!reason) next_test() },
- handleErrors: function (error) {
- do_throw("Error occurred updating form history: " + error);
- }
- });
-
-do_check_eq(expectedNotification, null);
-
-os.removeObserver(TestObserver, "satchel-storage-changed", false);
-
-do_test_finished();
-
-} catch (e) {
- throw "FAILED in test #" + testnum + " -- " + testdesc + ": " + e;
-}
-}
diff --git a/toolkit/components/satchel/test/unit/test_previous_result.js b/toolkit/components/satchel/test/unit/test_previous_result.js
deleted file mode 100644
index 06e5a385b..000000000
--- a/toolkit/components/satchel/test/unit/test_previous_result.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/. */
-
-var aaaListener = {
- onSearchResult: function(search, result) {
- do_check_eq(result.searchString, "aaa");
- do_test_finished();
- }
-};
-
-var aaListener = {
- onSearchResult: function(search, result) {
- do_check_eq(result.searchString, "aa");
- search.startSearch("aaa", "", result, aaaListener);
- }
-};
-
-function run_test()
-{
- do_test_pending();
- let search = Cc['@mozilla.org/autocomplete/search;1?name=form-history'].
- getService(Components.interfaces.nsIAutoCompleteSearch);
- search.startSearch("aa", "", null, aaListener);
-}
diff --git a/toolkit/components/satchel/test/unit/xpcshell.ini b/toolkit/components/satchel/test/unit/xpcshell.ini
deleted file mode 100644
index 4a41b47d6..000000000
--- a/toolkit/components/satchel/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,26 +0,0 @@
-[DEFAULT]
-head = head_satchel.js
-tail =
-skip-if = toolkit == 'android'
-support-files =
- asyncformhistory_expire.sqlite
- formhistory_1000.sqlite
- formhistory_CORRUPT.sqlite
- formhistory_apitest.sqlite
- formhistory_autocomplete.sqlite
- formhistory_v3.sqlite
- formhistory_v3v4.sqlite
- formhistory_v999a.sqlite
- formhistory_v999b.sqlite
- perf_autocomplete.js
-
-[test_async_expire.js]
-[test_autocomplete.js]
-[test_db_corrupt.js]
-[test_db_update_v4.js]
-[test_db_update_v4b.js]
-[test_db_update_v999a.js]
-[test_db_update_v999b.js]
-[test_history_api.js]
-[test_notify.js]
-[test_previous_result.js]
diff --git a/toolkit/components/social/test/xpcshell/.eslintrc.js b/toolkit/components/social/test/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/social/test/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/sqlite/moz.build b/toolkit/components/sqlite/moz.build
index bbe5b8b96..1235b5449 100644
--- a/toolkit/components/sqlite/moz.build
+++ b/toolkit/components/sqlite/moz.build
@@ -4,8 +4,4 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
-EXTRA_JS_MODULES.sqlite += [
- 'sqlite_internal.js',
-]
+EXTRA_JS_MODULES.sqlite += ['sqlite_internal.js']
diff --git a/toolkit/components/sqlite/tests/xpcshell/.eslintrc.js b/toolkit/components/sqlite/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/sqlite/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/sqlite/tests/xpcshell/data/chrome.manifest b/toolkit/components/sqlite/tests/xpcshell/data/chrome.manifest
deleted file mode 100644
index 92b9cf60b..000000000
--- a/toolkit/components/sqlite/tests/xpcshell/data/chrome.manifest
+++ /dev/null
@@ -1 +0,0 @@
-content test_sqlite_internal ./
diff --git a/toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_internal.js b/toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_internal.js
deleted file mode 100644
index 7f0b3af03..000000000
--- a/toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_internal.js
+++ /dev/null
@@ -1,279 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-importScripts("worker_sqlite_shared.js",
- "resource://gre/modules/workers/require.js");
-
-self.onmessage = function onmessage(msg) {
- try {
- run_test();
- } catch (ex) {
- let {message, moduleStack, moduleName, lineNumber} = ex;
- let error = new Error(message, moduleName, lineNumber);
- error.stack = moduleStack;
- dump("Uncaught error: " + error + "\n");
- dump("Full stack: " + moduleStack + "\n");
- throw error;
- }
-};
-
-var Sqlite;
-
-var SQLITE_OK; /* Successful result */
-var SQLITE_ROW; /* sqlite3_step() has another row ready */
-var SQLITE_DONE; /* sqlite3_step() has finished executing */
-
-function test_init() {
- do_print("Starting test_init");
- // Sqlite should be loaded.
- Sqlite = require("resource://gre/modules/sqlite/sqlite_internal.js");
- do_check_neq(typeof Sqlite, "undefined");
- do_check_neq(typeof Sqlite.Constants, "undefined");
- SQLITE_OK = Sqlite.Constants.SQLITE_OK;
- SQLITE_ROW = Sqlite.Constants.SQLITE_ROW;
- SQLITE_DONE = Sqlite.Constants.SQLITE_DONE;
-}
-
-/**
- * Clean up the database.
- * @param {sqlite3_ptr} db A pointer to the database.
- */
-function cleanupDB(db) {
- withQuery(db, "DROP TABLE IF EXISTS TEST;", SQLITE_DONE);
-}
-
-/**
- * Open and close sqlite3 database.
- * @param {String} open A name of the sqlite3 open function to be
- * used.
- * @param {Array} openArgs = [] Optional arguments to open function.
- * @param {Function} callback = null An optional callback to be run after the
- * database is opened but before it is
- * closed.
- */
-function withDB(open, openArgs = [], callback = null) {
- let db = Sqlite.Type.sqlite3_ptr.implementation();
- let dbPtr = db.address();
-
- // Open database.
- let result = Sqlite[open].apply(Sqlite, ["data/test.db", dbPtr].concat(
- openArgs));
- do_check_eq(result, SQLITE_OK);
-
- // Drop the test table if it already exists.
- cleanupDB(db);
-
- try {
- if (callback) {
- callback(db);
- }
- } catch (ex) {
- do_check_true(false);
- throw ex;
- } finally {
- // Drop the test table if it still exists.
- cleanupDB(db);
- // Close data base.
- result = Sqlite.close(db);
- do_check_eq(result, SQLITE_OK);
- }
-}
-
-/**
- * Execute an SQL query using sqlite3 API.
- * @param {sqlite3_ptr} db A pointer to the database.
- * @param {String} sql A SQL query string.
- * @param {Number} stepResult Expected result code after evaluating the
- * SQL statement.
- * @param {Function} bind An optional callback with SQL binding steps.
- * @param {Function} callback An optional callback that runs after the SQL
- * query completes.
- */
-function withQuery(db, sql, stepResult, bind, callback) {
- // Create an instance of a single SQL statement.
- let sqlStmt = Sqlite.Type.sqlite3_stmt_ptr.implementation();
- let sqlStmtPtr = sqlStmt.address();
-
- // Unused portion of an SQL query.
- let unused = Sqlite.Type.cstring.implementation();
- let unusedPtr = unused.address();
-
- // Compile an SQL statement.
- let result = Sqlite.prepare_v2(db, sql, sql.length, sqlStmtPtr, unusedPtr);
- do_check_eq(result, SQLITE_OK);
-
- try {
- if (bind) {
- bind(sqlStmt);
- }
-
- // Evaluate an SQL statement.
- result = Sqlite.step(sqlStmt);
- do_check_eq(result, stepResult);
-
- if (callback) {
- callback(sqlStmt);
- }
- } catch (ex) {
- do_check_true(false);
- throw ex;
- } finally {
- // Destroy a prepared statement object.
- result = Sqlite.finalize(sqlStmt);
- do_check_eq(result, SQLITE_OK);
- }
-}
-
-function test_open_close() {
- do_print("Starting test_open_close");
- do_check_eq(typeof Sqlite.open, "function");
- do_check_eq(typeof Sqlite.close, "function");
-
- withDB("open");
-}
-
-function test_open_v2_close() {
- do_print("Starting test_open_v2_close");
- do_check_eq(typeof Sqlite.open_v2, "function");
-
- withDB("open_v2", [0x02, null]);
-}
-
-function createTableOnOpen(db) {
- withQuery(db, "CREATE TABLE TEST(" +
- "ID INT PRIMARY KEY NOT NULL," +
- "FIELD1 INT," +
- "FIELD2 REAL," +
- "FIELD3 TEXT," +
- "FIELD4 TEXT," +
- "FIELD5 BLOB" +
- ");", SQLITE_DONE);
-}
-
-function test_create_table() {
- do_print("Starting test_create_table");
- do_check_eq(typeof Sqlite.prepare_v2, "function");
- do_check_eq(typeof Sqlite.step, "function");
- do_check_eq(typeof Sqlite.finalize, "function");
-
- withDB("open", [], createTableOnOpen);
-}
-
-/**
- * Read column values after evaluating the SQL SELECT statement.
- * @param {sqlite3_stmt_ptr} sqlStmt A pointer to the SQL statement.
- */
-function onSqlite3Step(sqlStmt) {
- // Get an int value from a query result from the ID (column 0).
- let field = Sqlite.column_int(sqlStmt, 0);
- do_check_eq(field, 3);
-
- // Get an int value from a query result from the column 1.
- field = Sqlite.column_int(sqlStmt, 1);
- do_check_eq(field, 2);
- // Get an int64 value from a query result from the column 1.
- field = Sqlite.column_int64(sqlStmt, 1);
- do_check_eq(field, 2);
-
- // Get a double value from a query result from the column 2.
- field = Sqlite.column_double(sqlStmt, 2);
- do_check_eq(field, 1.2);
-
- // Get a number of bytes of the value in the column 3.
- let bytes = Sqlite.column_bytes(sqlStmt, 3);
- do_check_eq(bytes, 4);
- // Get a text(cstring) value from a query result from the column 3.
- field = Sqlite.column_text(sqlStmt, 3);
- do_check_eq(field.readString(), "DATA");
-
- // Get a number of bytes of the UTF-16 value in the column 4.
- bytes = Sqlite.column_bytes16(sqlStmt, 4);
- do_check_eq(bytes, 8);
- // Get a text16(wstring) value from a query result from the column 4.
- field = Sqlite.column_text16(sqlStmt, 4);
- do_check_eq(field.readString(), "TADA");
-
- // Get a blob value from a query result from the column 5.
- field = Sqlite.column_blob(sqlStmt, 5);
- do_check_eq(ctypes.cast(field,
- Sqlite.Type.cstring.implementation).readString(), "BLOB");
-}
-
-function test_insert_select() {
- do_print("Starting test_insert_select");
- do_check_eq(typeof Sqlite.column_int, "function");
- do_check_eq(typeof Sqlite.column_int64, "function");
- do_check_eq(typeof Sqlite.column_double, "function");
- do_check_eq(typeof Sqlite.column_bytes, "function");
- do_check_eq(typeof Sqlite.column_text, "function");
- do_check_eq(typeof Sqlite.column_text16, "function");
- do_check_eq(typeof Sqlite.column_blob, "function");
-
- function onOpen(db) {
- createTableOnOpen(db);
- withQuery(db,
- "INSERT INTO TEST VALUES (3, 2, 1.2, \"DATA\", \"TADA\", \"BLOB\");",
- SQLITE_DONE);
- withQuery(db, "SELECT * FROM TEST;", SQLITE_ROW, null, onSqlite3Step);
- }
-
- withDB("open", [], onOpen);
-}
-
-function test_insert_bind_select() {
- do_print("Starting test_insert_bind_select");
- do_check_eq(typeof Sqlite.bind_int, "function");
- do_check_eq(typeof Sqlite.bind_int64, "function");
- do_check_eq(typeof Sqlite.bind_double, "function");
- do_check_eq(typeof Sqlite.bind_text, "function");
- do_check_eq(typeof Sqlite.bind_text16, "function");
- do_check_eq(typeof Sqlite.bind_blob, "function");
-
- function onBind(sqlStmt) {
- // Bind an int value to the ID (column 0).
- let result = Sqlite.bind_int(sqlStmt, 1, 3);
- do_check_eq(result, SQLITE_OK);
-
- // Bind an int64 value to the FIELD1 (column 1).
- result = Sqlite.bind_int64(sqlStmt, 2, 2);
- do_check_eq(result, SQLITE_OK);
-
- // Bind a double value to the FIELD2 (column 2).
- result = Sqlite.bind_double(sqlStmt, 3, 1.2);
- do_check_eq(result, SQLITE_OK);
-
- // Destructor.
- let destructor = Sqlite.Constants.SQLITE_TRANSIENT;
- // Bind a text value to the FIELD3 (column 3).
- result = Sqlite.bind_text(sqlStmt, 4, "DATA", 4, destructor);
- do_check_eq(result, SQLITE_OK);
-
- // Bind a text16 value to the FIELD4 (column 4).
- result = Sqlite.bind_text16(sqlStmt, 5, "TADA", 8, destructor);
- do_check_eq(result, SQLITE_OK);
-
- // Bind a blob value to the FIELD5 (column 5).
- result = Sqlite.bind_blob(sqlStmt, 6, ctypes.char.array()("BLOB"), 4,
- destructor);
- do_check_eq(result, SQLITE_OK);
- }
-
- function onOpen(db) {
- createTableOnOpen(db);
- withQuery(db, "INSERT INTO TEST VALUES (?, ?, ?, ?, ?, ?);", SQLITE_DONE,
- onBind);
- withQuery(db, "SELECT * FROM TEST;", SQLITE_ROW, null, onSqlite3Step);
- }
-
- withDB("open", [], onOpen);
-}
-
-function run_test() {
- test_init();
- test_open_close();
- test_open_v2_close();
- test_create_table();
- test_insert_select();
- test_insert_bind_select();
- do_test_complete();
-}
diff --git a/toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_shared.js b/toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_shared.js
deleted file mode 100644
index 54351a02a..000000000
--- a/toolkit/components/sqlite/tests/xpcshell/data/worker_sqlite_shared.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function send(message) {
- self.postMessage(message);
-}
-
-function do_test_complete() {
- send({kind: "do_test_complete", args: []});
-}
-
-function do_check_true(x) {
- send({kind: "do_check_true", args: [!!x]});
- if (x) {
- dump("TEST-PASS: " + x + "\n");
- } else {
- throw new Error("do_check_true failed");
- }
-}
-
-function do_check_eq(a, b) {
- let result = a == b;
- send({kind: "do_check_true", args: [result]});
- if (!result) {
- throw new Error("do_check_eq failed " + a + " != " + b);
- }
-}
-
-function do_check_neq(a, b) {
- let result = a != b;
- send({kind: "do_check_true", args: [result]});
- if (!result) {
- throw new Error("do_check_neq failed " + a + " == " + b);
- }
-}
-
-function do_print(x) {
- dump("TEST-INFO: " + x + "\n");
-}
diff --git a/toolkit/components/sqlite/tests/xpcshell/test_sqlite_internal.js b/toolkit/components/sqlite/tests/xpcshell/test_sqlite_internal.js
deleted file mode 100644
index 725cbfaea..000000000
--- a/toolkit/components/sqlite/tests/xpcshell/test_sqlite_internal.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/Promise.jsm");
-
-var WORKER_SOURCE_URI =
- "chrome://test_sqlite_internal/content/worker_sqlite_internal.js";
-do_load_manifest("data/chrome.manifest");
-
-function run_test() {
- run_next_test();
-}
-
-add_task(function() {
- let worker = new ChromeWorker(WORKER_SOURCE_URI);
- let deferred = Promise.defer();
- worker.onmessage = function(event) {
- let data = event.data;
- switch (data.kind) {
- case "do_check_true":
- try {
- do_check_true(data.args[0]);
- } catch (ex) {
- // Ignore errors
- }
- break;
- case "do_test_complete":
- deferred.resolve();
- worker.terminate();
- break;
- case "do_print":
- do_print(data.args[0]);
- break;
- }
- };
- worker.onerror = function(event) {
- let error = new Error(event.message, event.filename, event.lineno);
- worker.terminate();
- deferred.reject(error);
- };
- worker.postMessage("START");
- return deferred.promise;
-});
diff --git a/toolkit/components/sqlite/tests/xpcshell/xpcshell.ini b/toolkit/components/sqlite/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index d652dbb1d..000000000
--- a/toolkit/components/sqlite/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-head =
-tail =
-skip-if = toolkit == 'android' || (os == 'mac' && appname == 'thunderbird')
-support-files =
- data/worker_sqlite_shared.js
- data/worker_sqlite_internal.js
- data/chrome.manifest
-
-[test_sqlite_internal.js]
diff --git a/toolkit/components/startup/moz.build b/toolkit/components/startup/moz.build
index 5f290b783..6c9515c15 100644
--- a/toolkit/components/startup/moz.build
+++ b/toolkit/components/startup/moz.build
@@ -6,12 +6,7 @@
DIRS += ['public']
-EXPORTS.mozilla += [
- 'StartupTimeline.h',
-]
-
-BROWSER_CHROME_MANIFESTS += ['tests/browser/browser.ini']
-XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
+EXPORTS.mozilla += ['StartupTimeline.h']
UNIFIED_SOURCES += [
'nsAppStartup.cpp',
@@ -28,6 +23,3 @@ if CONFIG['MOZ_USERINFO']:
UNIFIED_SOURCES += ['nsUserInfoUnix.cpp']
FINAL_LIBRARY = 'xul'
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Startup and Profile System')
diff --git a/toolkit/components/startup/tests/browser/.eslintrc.js b/toolkit/components/startup/tests/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/startup/tests/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/startup/tests/browser/beforeunload.html b/toolkit/components/startup/tests/browser/beforeunload.html
deleted file mode 100644
index 93ddd5f14..000000000
--- a/toolkit/components/startup/tests/browser/beforeunload.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
- <script>
- window.onbeforeunload = function(event) {
- event.returnValue = 'Test beforeunload handler';
- }
- </script>
- <body>
- Test page
- </body>
-</html>
diff --git a/toolkit/components/startup/tests/browser/browser.ini b/toolkit/components/startup/tests/browser/browser.ini
deleted file mode 100644
index 0c02f73b6..000000000
--- a/toolkit/components/startup/tests/browser/browser.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- beforeunload.html
-
-[browser_bug511456.js]
-[browser_bug537449.js]
-[browser_crash_detection.js]
diff --git a/toolkit/components/startup/tests/browser/browser_bug511456.js b/toolkit/components/startup/tests/browser/browser_bug511456.js
deleted file mode 100644
index 652a34ea2..000000000
--- a/toolkit/components/startup/tests/browser/browser_bug511456.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const TEST_URL = "http://example.com/browser/toolkit/components/startup/tests/browser/beforeunload.html";
-
-SpecialPowers.pushPrefEnv({"set": [["dom.require_user_interaction_for_beforeunload", false]]});
-
-function test() {
- waitForExplicitFinish();
- ignoreAllUncaughtExceptions();
-
- let win2 = window.openDialog(location, "", "chrome,all,dialog=no", "about:blank");
- win2.addEventListener("load", function onLoad() {
- win2.removeEventListener("load", onLoad);
-
- gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
- let browser = gBrowser.selectedBrowser;
-
- whenBrowserLoaded(browser, function () {
- let seenDialog = false;
-
- // Cancel the prompt the first time.
- waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
- seenDialog = true;
- btnStay.click();
- });
-
- let appStartup = Cc['@mozilla.org/toolkit/app-startup;1'].
- getService(Ci.nsIAppStartup);
- appStartup.quit(Ci.nsIAppStartup.eAttemptQuit);
- ok(seenDialog, "Should have seen a prompt dialog");
- ok(!win2.closed, "Shouldn't have closed the additional window");
- win2.close();
-
- // Leave the page the second time.
- waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
- btnLeave.click();
- });
-
- gBrowser.removeTab(gBrowser.selectedTab);
- executeSoon(finish);
- });
- });
-}
diff --git a/toolkit/components/startup/tests/browser/browser_bug537449.js b/toolkit/components/startup/tests/browser/browser_bug537449.js
deleted file mode 100644
index ed3446f8d..000000000
--- a/toolkit/components/startup/tests/browser/browser_bug537449.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-//
-// Whitelisting this test.
-// As part of bug 1077403, the leaking uncaught rejection should be fixed.
-//
-thisTestLeaksUncaughtRejectionsAndShouldBeFixed("TypeError: this.docShell is null");
-
-SpecialPowers.pushPrefEnv({"set": [["dom.require_user_interaction_for_beforeunload", false]]});
-
-const TEST_URL = "http://example.com/browser/toolkit/components/startup/tests/browser/beforeunload.html";
-
-function test() {
- waitForExplicitFinish();
-
- gBrowser.selectedTab = gBrowser.addTab(TEST_URL);
- let browser = gBrowser.selectedBrowser;
-
- whenBrowserLoaded(browser, function () {
- let seenDialog = false;
-
- // Cancel the prompt the first time.
- waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
- seenDialog = true;
- btnStay.click();
- });
-
- let appStartup = Cc['@mozilla.org/toolkit/app-startup;1'].
- getService(Ci.nsIAppStartup);
- appStartup.quit(Ci.nsIAppStartup.eAttemptQuit);
- ok(seenDialog, "Should have seen a prompt dialog");
- ok(!window.closed, "Shouldn't have closed the window");
-
- let win2 = window.openDialog(location, "", "chrome,all,dialog=no", "about:blank");
- ok(win2 != null, "Should have been able to open a new window");
- win2.addEventListener("load", function onLoad() {
- win2.removeEventListener("load", onLoad);
- win2.close();
-
- // Leave the page the second time.
- waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
- btnLeave.click();
- });
-
- gBrowser.removeTab(gBrowser.selectedTab);
- executeSoon(finish);
- });
- });
-}
diff --git a/toolkit/components/startup/tests/browser/browser_crash_detection.js b/toolkit/components/startup/tests/browser/browser_crash_detection.js
deleted file mode 100644
index 039f80dde..000000000
--- a/toolkit/components/startup/tests/browser/browser_crash_detection.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function test() {
- function checkLastSuccess() {
- let lastSuccess = Services.prefs.getIntPref("toolkit.startup.last_success");
- let si = Services.startup.getStartupInfo();
- is(lastSuccess, parseInt(si["main"].getTime() / 1000, 10),
- "Startup tracking pref should be set after a delay at the end of startup");
- finish();
- }
-
- if (Services.prefs.getPrefType("toolkit.startup.max_resumed_crashes") == Services.prefs.PREF_INVALID) {
- info("Skipping this test since startup crash detection is disabled");
- return;
- }
-
- const startupCrashEndDelay = 35 * 1000;
- waitForExplicitFinish();
- requestLongerTimeout(2);
- setTimeout(checkLastSuccess, startupCrashEndDelay);
-}
diff --git a/toolkit/components/startup/tests/browser/head.js b/toolkit/components/startup/tests/browser/head.js
deleted file mode 100644
index c17da2ff7..000000000
--- a/toolkit/components/startup/tests/browser/head.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
-
-function whenBrowserLoaded(browser, callback) {
- return BrowserTestUtils.browserLoaded(browser).then(callback);
-}
-
-function waitForOnBeforeUnloadDialog(browser, callback) {
- browser.addEventListener("DOMWillOpenModalDialog", function onModalDialog(event) {
- if (Cu.isCrossProcessWrapper(event.target)) {
- // This event fires in both the content and chrome processes. We
- // want to ignore the one in the content process.
- return;
- }
-
- browser.removeEventListener("DOMWillOpenModalDialog", onModalDialog, true);
-
- executeSoon(() => {
- let stack = browser.parentNode;
- let dialogs = stack.getElementsByTagNameNS(XUL_NS, "tabmodalprompt");
- let {button0, button1} = dialogs[0].ui;
- callback(button0, button1);
- });
- }, true);
-}
diff --git a/toolkit/components/startup/tests/unit/.eslintrc.js b/toolkit/components/startup/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/startup/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/startup/tests/unit/head_startup.js b/toolkit/components/startup/tests/unit/head_startup.js
deleted file mode 100644
index 2466f70ee..000000000
--- a/toolkit/components/startup/tests/unit/head_startup.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const XULRUNTIME_CONTRACTID = "@mozilla.org/xre/runtime;1";
-const XULRUNTIME_CID = Components.ID("7685dac8-3637-4660-a544-928c5ec0e714}");
-
-Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var gAppInfo = null;
-
-function createAppInfo(ID, name, version, platformVersion="1.0") {
- let tmp = {};
- Components.utils.import("resource://testing-common/AppInfo.jsm", tmp);
- gAppInfo = tmp.newAppInfo({
- ID, name, version, platformVersion,
- crashReporter: true,
- replacedLockTime: 0,
- });
-
- let XULAppInfoFactory = {
- createInstance: function (outer, iid) {
- if (outer != null)
- throw Components.results.NS_ERROR_NO_AGGREGATION;
- return gAppInfo.QueryInterface(iid);
- }
- };
- let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
- registrar.registerFactory(XULRUNTIME_CID, "XULRuntime",
- XULRUNTIME_CONTRACTID, XULAppInfoFactory);
-}
diff --git a/toolkit/components/startup/tests/unit/test_startup_crash.js b/toolkit/components/startup/tests/unit/test_startup_crash.js
deleted file mode 100644
index 283633086..000000000
--- a/toolkit/components/startup/tests/unit/test_startup_crash.js
+++ /dev/null
@@ -1,300 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "10.0");
-
-var prefService = Services.prefs;
-var appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].
- getService(Ci.nsIAppStartup);
-
-const pref_last_success = "toolkit.startup.last_success";
-const pref_recent_crashes = "toolkit.startup.recent_crashes";
-const pref_max_resumed_crashes = "toolkit.startup.max_resumed_crashes";
-const pref_always_use_safe_mode = "toolkit.startup.always_use_safe_mode";
-
-function run_test() {
- prefService.setBoolPref(pref_always_use_safe_mode, true);
-
- resetTestEnv(0);
-
- test_trackStartupCrashBegin();
- test_trackStartupCrashEnd();
- test_trackStartupCrashBegin_safeMode();
- test_trackStartupCrashEnd_safeMode();
- test_maxResumed();
- resetTestEnv(0);
-
- prefService.clearUserPref(pref_always_use_safe_mode);
-}
-
-// reset prefs to default
-function resetTestEnv(replacedLockTime) {
- try {
- // call begin to reset mStartupCrashTrackingEnded
- appStartup.trackStartupCrashBegin();
- } catch (x) { }
- prefService.setIntPref(pref_max_resumed_crashes, 2);
- prefService.clearUserPref(pref_recent_crashes);
- gAppInfo.replacedLockTime = replacedLockTime;
- prefService.clearUserPref(pref_last_success);
-}
-
-function now_seconds() {
- return ms_to_s(Date.now());
-}
-
-function ms_to_s(ms) {
- return Math.floor(ms / 1000);
-}
-
-function test_trackStartupCrashBegin() {
- let max_resumed = prefService.getIntPref(pref_max_resumed_crashes);
- do_check_false(gAppInfo.inSafeMode);
-
- // first run with startup crash tracking - existing profile lock
- let replacedLockTime = Date.now();
- resetTestEnv(replacedLockTime);
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(prefService.prefHasUserValue(pref_last_success));
- do_check_eq(replacedLockTime, gAppInfo.replacedLockTime);
- try {
- do_check_false(appStartup.trackStartupCrashBegin());
- do_throw("Should have thrown since last_success is not set");
- } catch (x) { }
-
- do_check_false(prefService.prefHasUserValue(pref_last_success));
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // first run with startup crash tracking - no existing profile lock
- replacedLockTime = 0;
- resetTestEnv(replacedLockTime);
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(prefService.prefHasUserValue(pref_last_success));
- do_check_eq(replacedLockTime, gAppInfo.replacedLockTime);
- try {
- do_check_false(appStartup.trackStartupCrashBegin());
- do_throw("Should have thrown since last_success is not set");
- } catch (x) { }
-
- do_check_false(prefService.prefHasUserValue(pref_last_success));
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // normal startup - last startup was success
- replacedLockTime = Date.now();
- resetTestEnv(replacedLockTime);
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- do_check_eq(ms_to_s(replacedLockTime), prefService.getIntPref(pref_last_success));
- do_check_false(appStartup.trackStartupCrashBegin());
- do_check_eq(ms_to_s(replacedLockTime), prefService.getIntPref(pref_last_success));
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // normal startup with 1 recent crash
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_recent_crashes, 1);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- do_check_false(appStartup.trackStartupCrashBegin());
- do_check_eq(ms_to_s(replacedLockTime), prefService.getIntPref(pref_last_success));
- do_check_eq(1, prefService.getIntPref(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // normal startup with max_resumed_crashes crash
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_recent_crashes, max_resumed);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- do_check_false(appStartup.trackStartupCrashBegin());
- do_check_eq(ms_to_s(replacedLockTime), prefService.getIntPref(pref_last_success));
- do_check_eq(max_resumed, prefService.getIntPref(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // normal startup with too many recent crashes
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_recent_crashes, max_resumed + 1);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- do_check_true(appStartup.trackStartupCrashBegin());
- // should remain the same since the last startup was not a crash
- do_check_eq(max_resumed + 1, prefService.getIntPref(pref_recent_crashes));
- do_check_true(appStartup.automaticSafeModeNecessary);
-
- // normal startup with too many recent crashes and startup crash tracking disabled
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_max_resumed_crashes, -1);
- prefService.setIntPref(pref_recent_crashes, max_resumed + 1);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- do_check_false(appStartup.trackStartupCrashBegin());
- // should remain the same since the last startup was not a crash
- do_check_eq(max_resumed + 1, prefService.getIntPref(pref_recent_crashes));
- // returns false when disabled
- do_check_false(appStartup.automaticSafeModeNecessary);
- do_check_eq(-1, prefService.getIntPref(pref_max_resumed_crashes));
-
- // normal startup after 1 non-recent crash (1 year ago), no other recent
- replacedLockTime = Date.now() - 365 * 24 * 60 * 60 * 1000;
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime) - 365 * 24 * 60 * 60);
- do_check_false(appStartup.trackStartupCrashBegin());
- // recent crash count pref should be unset since the last crash was not recent
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // normal startup after 1 crash (1 minute ago), no other recent
- replacedLockTime = Date.now() - 60 * 1000;
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime) - 60 * 60); // last success - 1 hour ago
- do_check_false(appStartup.trackStartupCrashBegin());
- // recent crash count pref should be created with value 1
- do_check_eq(1, prefService.getIntPref(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // normal startup after another crash (1 minute ago), 1 already
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime) - 60 * 60); // last success - 1 hour ago
- replacedLockTime = Date.now() - 60 * 1000;
- gAppInfo.replacedLockTime = replacedLockTime;
- do_check_false(appStartup.trackStartupCrashBegin());
- // recent crash count pref should be incremented by 1
- do_check_eq(2, prefService.getIntPref(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // normal startup after another crash (1 minute ago), 2 already
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime) - 60 * 60); // last success - 1 hour ago
- do_check_true(appStartup.trackStartupCrashBegin());
- // recent crash count pref should be incremented by 1
- do_check_eq(3, prefService.getIntPref(pref_recent_crashes));
- do_check_true(appStartup.automaticSafeModeNecessary);
-
- // normal startup after 1 non-recent crash (1 year ago), 3 crashes already
- replacedLockTime = Date.now() - 365 * 24 * 60 * 60 * 1000;
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime) - 60 * 60); // last success - 1 hour ago
- do_check_false(appStartup.trackStartupCrashBegin());
- // recent crash count should be unset since the last crash was not recent
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-}
-
-function test_trackStartupCrashEnd() {
- // successful startup with no last_success (upgrade test)
- let replacedLockTime = Date.now() - 10 * 1000; // 10s ago
- resetTestEnv(replacedLockTime);
- try {
- appStartup.trackStartupCrashBegin(); // required to be called before end
- do_throw("Should have thrown since last_success is not set");
- } catch (x) { }
- appStartup.trackStartupCrashEnd();
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_false(prefService.prefHasUserValue(pref_last_success));
-
- // successful startup - should set last_success
- replacedLockTime = Date.now() - 10 * 1000; // 10s ago
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- appStartup.trackStartupCrashBegin(); // required to be called before end
- appStartup.trackStartupCrashEnd();
- // ensure last_success was set since we have declared a succesful startup
- // main timestamp doesn't get set in XPCShell so approximate with now
- do_check_true(prefService.getIntPref(pref_last_success) <= now_seconds());
- do_check_true(prefService.getIntPref(pref_last_success) >= now_seconds() - 4 * 60 * 60);
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
-
- // successful startup with 1 recent crash
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- prefService.setIntPref(pref_recent_crashes, 1);
- appStartup.trackStartupCrashBegin(); // required to be called before end
- appStartup.trackStartupCrashEnd();
- // ensure recent_crashes was cleared since we have declared a succesful startup
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
-}
-
-function test_trackStartupCrashBegin_safeMode() {
- gAppInfo.inSafeMode = true;
- resetTestEnv(0);
- let max_resumed = prefService.getIntPref(pref_max_resumed_crashes);
-
- // check manual safe mode doesn't change prefs without crash
- let replacedLockTime = Date.now() - 10 * 1000; // 10s ago
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
-
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_true(prefService.prefHasUserValue(pref_last_success));
- do_check_false(appStartup.automaticSafeModeNecessary);
- do_check_false(appStartup.trackStartupCrashBegin());
- do_check_false(prefService.prefHasUserValue(pref_recent_crashes));
- do_check_true(prefService.prefHasUserValue(pref_last_success));
- do_check_false(appStartup.automaticSafeModeNecessary);
-
- // check forced safe mode doesn't change prefs without crash
- replacedLockTime = Date.now() - 10 * 1000; // 10s ago
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime));
- prefService.setIntPref(pref_recent_crashes, max_resumed + 1);
-
- do_check_eq(max_resumed + 1, prefService.getIntPref(pref_recent_crashes));
- do_check_true(prefService.prefHasUserValue(pref_last_success));
- do_check_false(appStartup.automaticSafeModeNecessary);
- do_check_true(appStartup.trackStartupCrashBegin());
- do_check_eq(max_resumed + 1, prefService.getIntPref(pref_recent_crashes));
- do_check_true(prefService.prefHasUserValue(pref_last_success));
- do_check_true(appStartup.automaticSafeModeNecessary);
-
- // check forced safe mode after old crash
- replacedLockTime = Date.now() - 365 * 24 * 60 * 60 * 1000;
- resetTestEnv(replacedLockTime);
- // one year ago
- let last_success = ms_to_s(replacedLockTime) - 365 * 24 * 60 * 60;
- prefService.setIntPref(pref_last_success, last_success);
- prefService.setIntPref(pref_recent_crashes, max_resumed + 1);
- do_check_eq(max_resumed + 1, prefService.getIntPref(pref_recent_crashes));
- do_check_true(prefService.prefHasUserValue(pref_last_success));
- do_check_true(appStartup.automaticSafeModeNecessary);
- do_check_true(appStartup.trackStartupCrashBegin());
- do_check_eq(max_resumed + 1, prefService.getIntPref(pref_recent_crashes));
- do_check_eq(last_success, prefService.getIntPref(pref_last_success));
- do_check_true(appStartup.automaticSafeModeNecessary);
-}
-
-function test_trackStartupCrashEnd_safeMode() {
- gAppInfo.inSafeMode = true;
- let replacedLockTime = Date.now();
- resetTestEnv(replacedLockTime);
- let max_resumed = prefService.getIntPref(pref_max_resumed_crashes);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime) - 24 * 60 * 60);
-
- // ensure recent_crashes were not cleared in manual safe mode
- prefService.setIntPref(pref_recent_crashes, 1);
- appStartup.trackStartupCrashBegin(); // required to be called before end
- appStartup.trackStartupCrashEnd();
- do_check_eq(1, prefService.getIntPref(pref_recent_crashes));
-
- // recent_crashes should be set to max_resumed in forced safe mode to allow the user
- // to try and start in regular mode after making changes.
- prefService.setIntPref(pref_recent_crashes, max_resumed + 1);
- appStartup.trackStartupCrashBegin(); // required to be called before end
- appStartup.trackStartupCrashEnd();
- do_check_eq(max_resumed, prefService.getIntPref(pref_recent_crashes));
-}
-
-function test_maxResumed() {
- resetTestEnv(0);
- gAppInfo.inSafeMode = false;
- let max_resumed = prefService.getIntPref(pref_max_resumed_crashes);
- let replacedLockTime = Date.now();
- resetTestEnv(replacedLockTime);
- prefService.setIntPref(pref_max_resumed_crashes, -1);
-
- prefService.setIntPref(pref_recent_crashes, max_resumed + 1);
- prefService.setIntPref(pref_last_success, ms_to_s(replacedLockTime) - 24 * 60 * 60);
- appStartup.trackStartupCrashBegin();
- // should remain the same since the last startup was not a crash
- do_check_eq(max_resumed + 2, prefService.getIntPref(pref_recent_crashes));
- do_check_false(appStartup.automaticSafeModeNecessary);
-}
diff --git a/toolkit/components/startup/tests/unit/xpcshell.ini b/toolkit/components/startup/tests/unit/xpcshell.ini
deleted file mode 100644
index 294800ee3..000000000
--- a/toolkit/components/startup/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-head = head_startup.js
-tail =
-skip-if = toolkit == 'android'
-
-[test_startup_crash.js]
diff --git a/toolkit/components/telemetry/Makefile.in b/toolkit/components/telemetry/Makefile.in
deleted file mode 100644
index 52016707c..000000000
--- a/toolkit/components/telemetry/Makefile.in
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-include $(topsrcdir)/config/rules.mk
-
-# This is so hacky. Waiting on bug 988938.
-addondir = $(srcdir)/tests/addons
-testdir = $(topobjdir)/_tests/xpcshell/toolkit/components/telemetry/tests/unit
-
-misc:: $(call mkdir_deps,$(testdir))
- $(EXIT_ON_ERROR) \
- for dir in $(addondir)/*; do \
- base=`basename $$dir`; \
- (cd $$dir && zip -qr $(testdir)/$$base.xpi *); \
- done
diff --git a/toolkit/components/telemetry/moz.build b/toolkit/components/telemetry/moz.build
index 7765c59b4..712da7999 100644
--- a/toolkit/components/telemetry/moz.build
+++ b/toolkit/components/telemetry/moz.build
@@ -22,9 +22,6 @@ SPHINX_TREES['telemetry'] = 'docs'
if CONFIG['GNU_CXX']:
CXXFLAGS += ['-Wno-error=shadow']
-XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
-BROWSER_CHROME_MANIFESTS += ['tests/browser/browser.ini']
-
XPIDL_SOURCES += [
'nsITelemetry.idl',
]
@@ -71,10 +68,6 @@ EXTRA_JS_MODULES += [
'UITelemetry.jsm',
]
-TESTING_JS_MODULES += [
- 'tests/unit/TelemetryArchiveTesting.jsm',
-]
-
GENERATED_FILES = [
'TelemetryEventData.h',
'TelemetryEventEnums.h',
@@ -125,5 +118,3 @@ event_enums = GENERATED_FILES['TelemetryEventEnums.h']
event_enums.script = 'gen-event-enum.py'
event_enums.inputs = event_files
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Telemetry')
diff --git a/toolkit/components/telemetry/tests/addons/dictionary/install.rdf b/toolkit/components/telemetry/tests/addons/dictionary/install.rdf
deleted file mode 100644
index ff0039b39..000000000
--- a/toolkit/components/telemetry/tests/addons/dictionary/install.rdf
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>telemetry-dictionary@tests.mozilla.org</em:id>
- <em:version>1</em:version>
- <em:type>64</em:type>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>0</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <!-- Front End MetaData -->
- <em:name>Telemetry test dictionary</em:name>
- <em:description>A nice dictionary to prevent all typos for Telemetry.</em:description>
- <em:bootstrap>true</em:bootstrap>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/experiment/install.rdf b/toolkit/components/telemetry/tests/addons/experiment/install.rdf
deleted file mode 100644
index d12f06816..000000000
--- a/toolkit/components/telemetry/tests/addons/experiment/install.rdf
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>telemetry-experiment-1@tests.mozilla.org</em:id>
- <em:version>1</em:version>
- <em:type>128</em:type>
-
- <!-- Front End MetaData -->
- <em:name>Telemetry test experiment</em:name>
- <em:description>Yet another experiment that experiments experimentally.</em:description>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/extension-2/install.rdf b/toolkit/components/telemetry/tests/addons/extension-2/install.rdf
deleted file mode 100644
index ddb5904f8..000000000
--- a/toolkit/components/telemetry/tests/addons/extension-2/install.rdf
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>telemetry-ext-2@tests.mozilla.org</em:id>
- <em:version>2</em:version>
- <em:type>2</em:type>
-
- <!-- Front End MetaData -->
- <em:name>Telemetry test extension 2</em:name>
- <em:description>Yet another extension that extends twice.</em:description>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/extension/install.rdf b/toolkit/components/telemetry/tests/addons/extension/install.rdf
deleted file mode 100644
index 4b1bd2da7..000000000
--- a/toolkit/components/telemetry/tests/addons/extension/install.rdf
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>telemetry-ext-1@tests.mozilla.org</em:id>
- <em:version>1</em:version>
- <em:type>2</em:type>
-
- <!-- Front End MetaData -->
- <em:name>Telemetry test extension</em:name>
- <em:description>Yet another extension that extends.</em:description>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/long-fields/install.rdf b/toolkit/components/telemetry/tests/addons/long-fields/install.rdf
deleted file mode 100644
index 23ca7523c..000000000
--- a/toolkit/components/telemetry/tests/addons/long-fields/install.rdf
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>tel-longfields-xpi@tests.mozilla.org</em:id>
- <em:version>This is a really long addon version, that will get limited to 100 characters. We're much longer, we're at about 116.</em:version>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>0</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <!-- Front End MetaData -->
- <em:name>This is a really long addon name, that will get limited to 100 characters. We're much longer, we're at about 219. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nullam sodales. Yeah, Latin placeholder.</em:name>
- <em:description>This is a really long addon description, that will get limited to 100 characters. We're much longer, we're at about 200. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nullam sodales.</em:description>
- <em:bootstrap>true</em:bootstrap>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/restartless/install.rdf b/toolkit/components/telemetry/tests/addons/restartless/install.rdf
deleted file mode 100644
index f6cda9f25..000000000
--- a/toolkit/components/telemetry/tests/addons/restartless/install.rdf
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>tel-restartless-xpi@tests.mozilla.org</em:id>
- <em:version>1.0</em:version>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>0</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <!-- Front End MetaData -->
- <em:name>XPI Telemetry Restartless Test</em:name>
- <em:description>A restartless addon which gets enabled without a reboot.</em:description>
- <em:bootstrap>true</em:bootstrap>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/signed/META-INF/manifest.mf b/toolkit/components/telemetry/tests/addons/signed/META-INF/manifest.mf
deleted file mode 100644
index e6e279dbc..000000000
--- a/toolkit/components/telemetry/tests/addons/signed/META-INF/manifest.mf
+++ /dev/null
@@ -1,7 +0,0 @@
-Manifest-Version: 1.0
-
-Name: install.rdf
-Digest-Algorithms: MD5 SHA1
-MD5-Digest: YEilRfaecTg2bMNPoYqexQ==
-SHA1-Digest: GEnQKM8Coyw83phx/z1oNh327+0=
-
diff --git a/toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.rsa b/toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.rsa
deleted file mode 100644
index 8e5a92650..000000000
--- a/toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.rsa
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.sf b/toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.sf
deleted file mode 100644
index 21ce46081..000000000
--- a/toolkit/components/telemetry/tests/addons/signed/META-INF/mozilla.sf
+++ /dev/null
@@ -1,4 +0,0 @@
-Signature-Version: 1.0
-MD5-Digest-Manifest: Ko2bKTrwTXCdstWHWqCR4w==
-SHA1-Digest-Manifest: k6+jfNGFxXtDd1cSX0ZoIyQ1cww=
-
diff --git a/toolkit/components/telemetry/tests/addons/signed/install.rdf b/toolkit/components/telemetry/tests/addons/signed/install.rdf
deleted file mode 100644
index 5fdca172c..000000000
--- a/toolkit/components/telemetry/tests/addons/signed/install.rdf
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>tel-signed-xpi@tests.mozilla.org</em:id>
- <em:version>1.0</em:version>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>0</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <!-- Front End MetaData -->
- <em:name>XPI Telemetry Signed Test</em:name>
- <em:description>A signed addon which gets enabled without a reboot.</em:description>
- <em:bootstrap>true</em:bootstrap>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/system/install.rdf b/toolkit/components/telemetry/tests/addons/system/install.rdf
deleted file mode 100644
index 12cb143a7..000000000
--- a/toolkit/components/telemetry/tests/addons/system/install.rdf
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>tel-system-xpi@tests.mozilla.org</em:id>
- <em:version>1.0</em:version>
-
- <em:targetApplication>
- <Description>
- <em:id>toolkit@mozilla.org</em:id>
- <em:minVersion>0</em:minVersion>
- <em:maxVersion>*</em:maxVersion>
- </Description>
- </em:targetApplication>
-
- <!-- Front End MetaData -->
- <em:name>XPI Telemetry System Add-on Test</em:name>
- <em:description>A system addon which is shipped with Firefox.</em:description>
- <em:bootstrap>true</em:bootstrap>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/addons/theme/install.rdf b/toolkit/components/telemetry/tests/addons/theme/install.rdf
deleted file mode 100644
index a35249dba..000000000
--- a/toolkit/components/telemetry/tests/addons/theme/install.rdf
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
- <Description about="urn:mozilla:install-manifest">
- <em:id>telemetry-theme@tests.mozilla.org</em:id>
- <em:version>1</em:version>
- <em:type>4</em:type>
-
- <!-- Front End MetaData -->
- <em:name>Telemetry test theme</em:name>
- <em:description>A good looking test theme for Telemetry.</em:description>
-
- </Description>
-</RDF>
diff --git a/toolkit/components/telemetry/tests/browser/browser.ini b/toolkit/components/telemetry/tests/browser/browser.ini
deleted file mode 100644
index a1725d54d..000000000
--- a/toolkit/components/telemetry/tests/browser/browser.ini
+++ /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/.
-
-[browser_TelemetryGC.js]
diff --git a/toolkit/components/telemetry/tests/browser/browser_TelemetryGC.js b/toolkit/components/telemetry/tests/browser/browser_TelemetryGC.js
deleted file mode 100644
index 262fd69ff..000000000
--- a/toolkit/components/telemetry/tests/browser/browser_TelemetryGC.js
+++ /dev/null
@@ -1,193 +0,0 @@
-"use strict";
-
-/*
- *********************************************************************************
- * *
- * WARNING *
- * *
- * If you adjust any of the constants here (slice limit, number of keys, etc.) *
- * make sure to update the JSON schema at: *
- * https://github.com/mozilla-services/mozilla-pipeline-schemas/blob/master/ *
- * telemetry/main.schema.json *
- * *
- * Otherwise, pings may be dropped by the telemetry backend! *
- * *
- ********************************************************************************/
-
-const {GCTelemetry} = Cu.import("resource://gre/modules/GCTelemetry.jsm", {});
-
-function check(entries) {
- const FIELDS = ["random", "worst"];
-
- // Check that all FIELDS are in |entries|.
- for (let f of FIELDS) {
- ok(f in entries, `${f} found in entries`);
- }
-
- // Check that only FIELDS are in |entries|.
- for (let k of Object.keys(entries)) {
- ok(FIELDS.includes(k), `${k} found in FIELDS`);
- }
-
- let foundGCs = 0;
-
- for (let f of FIELDS) {
- ok(Array.isArray(entries[f]), "have an array of GCs");
-
- ok(entries[f].length <= 2, "not too many GCs");
-
- for (let gc of entries[f]) {
- ok(gc !== null, "GC is non-null");
-
- foundGCs++;
-
- ok(Object.keys(gc).length <= 25, "number of keys in GC is not too large");
-
- // Sanity check the GC data.
- ok("total_time" in gc, "total_time field present");
- ok("max_pause" in gc, "max_pause field present");
-
- ok("slices" in gc, "slices field present");
- ok(Array.isArray(gc.slices), "slices is an array");
- ok(gc.slices.length > 0, "slices array non-empty");
- ok(gc.slices.length <= 4, "slices array is not too long");
-
- ok("totals" in gc, "totals field present");
- ok(typeof(gc.totals) == "object", "totals is an object");
- ok(Object.keys(gc.totals).length <= 65, "totals array is not too long");
-
- // Make sure we don't skip any big objects.
- for (let key in gc) {
- if (key != "slices" && key != "totals") {
- ok(typeof(gc[key]) != "object", `${key} property should be primitive`);
- }
- }
-
- let phases = new Set();
-
- for (let slice of gc.slices) {
- ok(Object.keys(slice).length <= 15, "slice is not too large");
-
- ok("pause" in slice, "pause field present in slice");
- ok("reason" in slice, "reason field present in slice");
- ok("times" in slice, "times field present in slice");
-
- // Make sure we don't skip any big objects.
- for (let key in slice) {
- if (key != "times") {
- ok(typeof(slice[key]) != "object", `${key} property should be primitive`);
- }
- }
-
- ok(Object.keys(slice.times).length <= 65, "no more than 65 phases");
-
- for (let phase in slice.times) {
- phases.add(phase);
- ok(typeof(slice.times[phase]) == "number", `${phase} property should be a number`);
- }
- }
-
- let totals = gc.totals;
- // Make sure we don't skip any big objects.
- for (let phase in totals) {
- ok(typeof(totals[phase]) == "number", `${phase} property should be a number`);
- }
-
- for (let phase of phases) {
- ok(phase in totals, `${phase} is in totals`);
- }
- }
- }
-
- ok(foundGCs > 0, "saw at least one GC");
-}
-
-add_task(function* test() {
- let multiprocess = Services.appinfo.browserTabsRemoteAutostart;
-
- // Set these prefs to ensure that we get measurements.
- const prefs = {"set": [["javascript.options.mem.notify", true]]};
- yield new Promise(resolve => SpecialPowers.pushPrefEnv(prefs, resolve));
-
- function runRemote(f) {
- gBrowser.selectedBrowser.messageManager.loadFrameScript(`data:,(${f})()`, false);
- }
-
- function initScript() {
- const {GCTelemetry} = Components.utils.import("resource://gre/modules/GCTelemetry.jsm", {});
-
- /*
- * Don't shut down GC telemetry if it was already running before the test!
- * Note: We need to use a multiline comment here since this code is turned into a data: URI.
- */
- let shutdown = GCTelemetry.init();
-
- function listener() {
- removeMessageListener("GCTelemTest:Shutdown", listener);
- if (shutdown) {
- GCTelemetry.shutdown();
- }
- }
- addMessageListener("GCTelemTest:Shutdown", listener);
- }
-
- if (multiprocess) {
- runRemote(initScript);
- }
-
- // Don't shut down GC telemetry if it was already running before the test!
- let shutdown = GCTelemetry.init();
- registerCleanupFunction(() => {
- if (shutdown) {
- GCTelemetry.shutdown();
- }
-
- gBrowser.selectedBrowser.messageManager.sendAsyncMessage("GCTelemTest:Shutdown");
- });
-
- let localPromise = new Promise(resolve => {
- function obs() {
- Services.obs.removeObserver(obs, "garbage-collection-statistics");
- resolve();
- }
- Services.obs.addObserver(obs, "garbage-collection-statistics", false);
- });
-
- let remotePromise;
- if (multiprocess) {
- remotePromise = new Promise(resolve => {
- function obs() {
- Services.ppmm.removeMessageListener("Telemetry:GCStatistics", obs);
- resolve();
- }
- Services.ppmm.addMessageListener("Telemetry:GCStatistics", obs);
- });
- } else {
- remotePromise = Promise.resolve();
- }
-
- // Make sure we have a GC to work with in both processes.
- Cu.forceGC();
- if (multiprocess) {
- runRemote(() => Components.utils.forceGC());
- }
-
- info("Waiting for GCs");
-
- yield Promise.all([localPromise, remotePromise]);
-
- let localEntries = GCTelemetry.entries("main", true);
- let remoteEntries = multiprocess ? GCTelemetry.entries("content", true) : localEntries;
-
- check(localEntries);
- check(remoteEntries);
-
- localEntries = GCTelemetry.entries("main", false);
- remoteEntries = multiprocess ? GCTelemetry.entries("content", false) : localEntries;
-
- is(localEntries.random.length, 0, "no random GCs after reset");
- is(localEntries.worst.length, 0, "no worst GCs after reset");
-
- is(remoteEntries.random.length, 0, "no random GCs after reset");
- is(remoteEntries.worst.length, 0, "no worst GCs after reset");
-});
diff --git a/toolkit/components/telemetry/tests/search/chrome.manifest b/toolkit/components/telemetry/tests/search/chrome.manifest
deleted file mode 100644
index ec412e050..000000000
--- a/toolkit/components/telemetry/tests/search/chrome.manifest
+++ /dev/null
@@ -1,3 +0,0 @@
-locale testsearchplugin ar jar:jar:searchTest.jar!/chrome/searchTest.jar!/
-content testsearchplugin ./
-
diff --git a/toolkit/components/telemetry/tests/search/searchTest.jar b/toolkit/components/telemetry/tests/search/searchTest.jar
deleted file mode 100644
index b10fc0c3e..000000000
--- a/toolkit/components/telemetry/tests/search/searchTest.jar
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/telemetry/tests/unit/.eslintrc.js b/toolkit/components/telemetry/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/telemetry/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/telemetry/tests/unit/TelemetryArchiveTesting.jsm b/toolkit/components/telemetry/tests/unit/TelemetryArchiveTesting.jsm
deleted file mode 100644
index 9be82c883..000000000
--- a/toolkit/components/telemetry/tests/unit/TelemetryArchiveTesting.jsm
+++ /dev/null
@@ -1,86 +0,0 @@
-const {utils: Cu} = Components;
-Cu.import("resource://gre/modules/TelemetryArchive.jsm");
-Cu.import("resource://testing-common/Assert.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/TelemetryController.jsm");
-
-this.EXPORTED_SYMBOLS = [
- "TelemetryArchiveTesting",
-];
-
-function checkForProperties(ping, expected) {
- for (let [props, val] of expected) {
- let test = ping;
- for (let prop of props) {
- test = test[prop];
- if (test === undefined) {
- return false;
- }
- }
- if (test !== val) {
- return false;
- }
- }
- return true;
-}
-
-/**
- * A helper object that allows test code to check whether a telemetry ping
- * was properly saved. To use, first initialize to collect the starting pings
- * and then check for new ping data.
- */
-function Checker() {
-}
-Checker.prototype = {
- promiseInit: function() {
- this._pingMap = new Map();
- return TelemetryArchive.promiseArchivedPingList().then((plist) => {
- for (let ping of plist) {
- this._pingMap.set(ping.id, ping);
- }
- });
- },
-
- /**
- * Find and return a new ping with certain properties.
- *
- * @param expected: an array of [['prop'...], 'value'] to check
- * For example:
- * [
- * [['environment', 'build', 'applicationId'], '20150101010101'],
- * [['version'], 1],
- * [['metadata', 'OOMAllocationSize'], 123456789],
- * ]
- * @returns a matching ping if found, or null
- */
- promiseFindPing: Task.async(function*(type, expected) {
- let candidates = [];
- let plist = yield TelemetryArchive.promiseArchivedPingList();
- for (let ping of plist) {
- if (this._pingMap.has(ping.id)) {
- continue;
- }
- if (ping.type == type) {
- candidates.push(ping);
- }
- }
-
- for (let candidate of candidates) {
- let ping = yield TelemetryArchive.promiseArchivedPingById(candidate.id);
- if (checkForProperties(ping, expected)) {
- return ping;
- }
- }
- return null;
- }),
-};
-
-const TelemetryArchiveTesting = {
- setup: function() {
- Services.prefs.setCharPref("toolkit.telemetry.log.level", "Trace");
- Services.prefs.setBoolPref("toolkit.telemetry.archive.enabled", true);
- },
-
- Checker: Checker,
-};
diff --git a/toolkit/components/telemetry/tests/unit/engine.xml b/toolkit/components/telemetry/tests/unit/engine.xml
deleted file mode 100644
index 2304fcdd7..000000000
--- a/toolkit/components/telemetry/tests/unit/engine.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
-<ShortName>engine-telemetry</ShortName>
-<Url type="text/html" method="GET" template="http://www.example.com/search">
- <Param name="q" value="{searchTerms}"/>
-</Url>
-</SearchPlugin>
diff --git a/toolkit/components/telemetry/tests/unit/head.js b/toolkit/components/telemetry/tests/unit/head.js
deleted file mode 100644
index 87afd3617..000000000
--- a/toolkit/components/telemetry/tests/unit/head.js
+++ /dev/null
@@ -1,319 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var { classes: Cc, utils: Cu, interfaces: Ci, results: Cr } = Components;
-
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/PromiseUtils.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/FileUtils.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://testing-common/httpd.js", this);
-Cu.import("resource://gre/modules/AppConstants.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "AddonTestUtils",
- "resource://testing-common/AddonTestUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "OS",
- "resource://gre/modules/osfile.jsm");
-
-const gIsWindows = AppConstants.platform == "win";
-const gIsMac = AppConstants.platform == "macosx";
-const gIsAndroid = AppConstants.platform == "android";
-const gIsGonk = false;
-const gIsLinux = AppConstants.platform == "linux";
-
-const Telemetry = Cc["@mozilla.org/base/telemetry;1"].getService(Ci.nsITelemetry);
-
-const MILLISECONDS_PER_MINUTE = 60 * 1000;
-const MILLISECONDS_PER_HOUR = 60 * MILLISECONDS_PER_MINUTE;
-const MILLISECONDS_PER_DAY = 24 * MILLISECONDS_PER_HOUR;
-
-const PREF_TELEMETRY_ENABLED = "toolkit.telemetry.enabled";
-
-const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-var gGlobalScope = this;
-
-const PingServer = {
- _httpServer: null,
- _started: false,
- _defers: [ PromiseUtils.defer() ],
- _currentDeferred: 0,
-
- get port() {
- return this._httpServer.identity.primaryPort;
- },
-
- get started() {
- return this._started;
- },
-
- registerPingHandler: function(handler) {
- const wrapped = wrapWithExceptionHandler(handler);
- this._httpServer.registerPrefixHandler("/submit/telemetry/", wrapped);
- },
-
- resetPingHandler: function() {
- this.registerPingHandler((request, response) => {
- let deferred = this._defers[this._defers.length - 1];
- this._defers.push(PromiseUtils.defer());
- deferred.resolve(request);
- });
- },
-
- start: function() {
- this._httpServer = new HttpServer();
- this._httpServer.start(-1);
- this._started = true;
- this.clearRequests();
- this.resetPingHandler();
- },
-
- stop: function() {
- return new Promise(resolve => {
- this._httpServer.stop(resolve);
- this._started = false;
- });
- },
-
- clearRequests: function() {
- this._defers = [ PromiseUtils.defer() ];
- this._currentDeferred = 0;
- },
-
- promiseNextRequest: function() {
- const deferred = this._defers[this._currentDeferred++];
- // Send the ping to the consumer on the next tick, so that the completion gets
- // signaled to Telemetry.
- return new Promise(r => Services.tm.currentThread.dispatch(() => r(deferred.promise),
- Ci.nsIThread.DISPATCH_NORMAL));
- },
-
- promiseNextPing: function() {
- return this.promiseNextRequest().then(request => decodeRequestPayload(request));
- },
-
- promiseNextRequests: Task.async(function*(count) {
- let results = [];
- for (let i=0; i<count; ++i) {
- results.push(yield this.promiseNextRequest());
- }
-
- return results;
- }),
-
- promiseNextPings: function(count) {
- return this.promiseNextRequests(count).then(requests => {
- return Array.from(requests, decodeRequestPayload);
- });
- },
-};
-
-/**
- * Decode the payload of an HTTP request into a ping.
- * @param {Object} request The data representing an HTTP request (nsIHttpRequest).
- * @return {Object} The decoded ping payload.
- */
-function decodeRequestPayload(request) {
- let s = request.bodyInputStream;
- let payload = null;
- let decoder = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON)
-
- if (request.getHeader("content-encoding") == "gzip") {
- let observer = {
- buffer: "",
- onStreamComplete: function(loader, context, status, length, result) {
- this.buffer = String.fromCharCode.apply(this, result);
- }
- };
-
- let scs = Cc["@mozilla.org/streamConverters;1"]
- .getService(Ci.nsIStreamConverterService);
- let listener = Cc["@mozilla.org/network/stream-loader;1"]
- .createInstance(Ci.nsIStreamLoader);
- listener.init(observer);
- let converter = scs.asyncConvertData("gzip", "uncompressed",
- listener, null);
- converter.onStartRequest(null, null);
- converter.onDataAvailable(null, null, s, 0, s.available());
- converter.onStopRequest(null, null, null);
- let unicodeConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(Ci.nsIScriptableUnicodeConverter);
- unicodeConverter.charset = "UTF-8";
- let utf8string = unicodeConverter.ConvertToUnicode(observer.buffer);
- utf8string += unicodeConverter.Finish();
- payload = JSON.parse(utf8string);
- } else {
- payload = decoder.decodeFromStream(s, s.available());
- }
-
- return payload;
-}
-
-function wrapWithExceptionHandler(f) {
- function wrapper(...args) {
- try {
- f(...args);
- } catch (ex) {
- if (typeof(ex) != 'object') {
- throw ex;
- }
- dump("Caught exception: " + ex.message + "\n");
- dump(ex.stack);
- do_test_finished();
- }
- }
- return wrapper;
-}
-
-function loadAddonManager(...args) {
- AddonTestUtils.init(gGlobalScope);
- AddonTestUtils.overrideCertDB();
- createAppInfo(...args);
-
- // As we're not running in application, we need to setup the features directory
- // used by system add-ons.
- const distroDir = FileUtils.getDir("ProfD", ["sysfeatures", "app0"], true);
- AddonTestUtils.registerDirectory("XREAppFeat", distroDir);
- return AddonTestUtils.promiseStartupManager();
-}
-
-var gAppInfo = null;
-
-function createAppInfo(ID="xpcshell@tests.mozilla.org", name="XPCShell",
- version="1.0", platformVersion="1.0") {
- AddonTestUtils.createAppInfo(ID, name, version, platformVersion);
- gAppInfo = AddonTestUtils.appInfo;
-}
-
-// Fake the timeout functions for the TelemetryScheduler.
-function fakeSchedulerTimer(set, clear) {
- let session = Cu.import("resource://gre/modules/TelemetrySession.jsm");
- session.Policy.setSchedulerTickTimeout = set;
- session.Policy.clearSchedulerTickTimeout = clear;
-}
-
-/**
- * Fake the current date.
- * This passes all received arguments to a new Date constructor and
- * uses the resulting date to fake the time in Telemetry modules.
- *
- * @return Date The new faked date.
- */
-function fakeNow(...args) {
- const date = new Date(...args);
- const modules = [
- Cu.import("resource://gre/modules/TelemetrySession.jsm"),
- Cu.import("resource://gre/modules/TelemetryEnvironment.jsm"),
- Cu.import("resource://gre/modules/TelemetryController.jsm"),
- Cu.import("resource://gre/modules/TelemetryStorage.jsm"),
- Cu.import("resource://gre/modules/TelemetrySend.jsm"),
- Cu.import("resource://gre/modules/TelemetryReportingPolicy.jsm"),
- ];
-
- for (let m of modules) {
- m.Policy.now = () => date;
- }
-
- return new Date(date);
-}
-
-function fakeMonotonicNow(ms) {
- const m = Cu.import("resource://gre/modules/TelemetrySession.jsm");
- m.Policy.monotonicNow = () => ms;
- return ms;
-}
-
-// Fake the timeout functions for TelemetryController sending.
-function fakePingSendTimer(set, clear) {
- let module = Cu.import("resource://gre/modules/TelemetrySend.jsm");
- let obj = Cu.cloneInto({set, clear}, module, {cloneFunctions:true});
- module.Policy.setSchedulerTickTimeout = obj.set;
- module.Policy.clearSchedulerTickTimeout = obj.clear;
-}
-
-function fakeMidnightPingFuzzingDelay(delayMs) {
- let module = Cu.import("resource://gre/modules/TelemetrySend.jsm");
- module.Policy.midnightPingFuzzingDelay = () => delayMs;
-}
-
-function fakeGeneratePingId(func) {
- let module = Cu.import("resource://gre/modules/TelemetryController.jsm");
- module.Policy.generatePingId = func;
-}
-
-function fakeCachedClientId(uuid) {
- let module = Cu.import("resource://gre/modules/TelemetryController.jsm");
- module.Policy.getCachedClientID = () => uuid;
-}
-
-// Return a date that is |offset| ms in the future from |date|.
-function futureDate(date, offset) {
- return new Date(date.getTime() + offset);
-}
-
-function truncateToDays(aMsec) {
- return Math.floor(aMsec / MILLISECONDS_PER_DAY);
-}
-
-// Returns a promise that resolves to true when the passed promise rejects,
-// false otherwise.
-function promiseRejects(promise) {
- return promise.then(() => false, () => true);
-}
-
-// Generates a random string of at least a specific length.
-function generateRandomString(length) {
- let string = "";
-
- while (string.length < length) {
- string += Math.random().toString(36);
- }
-
- return string.substring(0, length);
-}
-
-// Short-hand for retrieving the histogram with that id.
-function getHistogram(histogramId) {
- return Telemetry.getHistogramById(histogramId);
-}
-
-// Short-hand for retrieving the snapshot of the Histogram with that id.
-function getSnapshot(histogramId) {
- return Telemetry.getHistogramById(histogramId).snapshot();
-}
-
-// Helper for setting an empty list of Environment preferences to watch.
-function setEmptyPrefWatchlist() {
- let TelemetryEnvironment =
- Cu.import("resource://gre/modules/TelemetryEnvironment.jsm").TelemetryEnvironment;
- return TelemetryEnvironment.onInitialized().then(() => {
- TelemetryEnvironment.testWatchPreferences(new Map());
- });
-}
-
-if (runningInParent) {
- // Set logging preferences for all the tests.
- Services.prefs.setCharPref("toolkit.telemetry.log.level", "Trace");
- // Telemetry archiving should be on.
- Services.prefs.setBoolPref("toolkit.telemetry.archive.enabled", true);
- // Telemetry xpcshell tests cannot show the infobar.
- Services.prefs.setBoolPref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
- // FHR uploads should be enabled.
- Services.prefs.setBoolPref("datareporting.healthreport.uploadEnabled", true);
-
- fakePingSendTimer((callback, timeout) => {
- Services.tm.mainThread.dispatch(() => callback(), Ci.nsIThread.DISPATCH_NORMAL);
- },
- () => {});
-
- do_register_cleanup(() => TelemetrySend.shutdown());
-}
-
-TelemetryController.testInitLogging();
-
-// Avoid timers interrupting test behavior.
-fakeSchedulerTimer(() => {}, () => {});
-// Make pind sending predictable.
-fakeMidnightPingFuzzingDelay(0);
diff --git a/toolkit/components/telemetry/tests/unit/test_ChildHistograms.js b/toolkit/components/telemetry/tests/unit/test_ChildHistograms.js
deleted file mode 100644
index 11d730499..000000000
--- a/toolkit/components/telemetry/tests/unit/test_ChildHistograms.js
+++ /dev/null
@@ -1,107 +0,0 @@
-
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-Cu.import("resource://gre/modules/PromiseUtils.jsm", this);
-Cu.import("resource://testing-common/ContentTaskUtils.jsm", this);
-
-const MESSAGE_TELEMETRY_PAYLOAD = "Telemetry:Payload";
-const MESSAGE_TELEMETRY_GET_CHILD_PAYLOAD = "Telemetry:GetChildPayload";
-const MESSAGE_CHILD_TEST_DONE = "ChildTest:Done";
-
-const PLATFORM_VERSION = "1.9.2";
-const APP_VERSION = "1";
-const APP_ID = "xpcshell@tests.mozilla.org";
-const APP_NAME = "XPCShell";
-
-function run_child_test() {
- // Setup histograms with some fixed values.
- let flagHist = Telemetry.getHistogramById("TELEMETRY_TEST_FLAG");
- flagHist.add(1);
- let countHist = Telemetry.getHistogramById("TELEMETRY_TEST_COUNT");
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_COUNT", false);
- countHist.add();
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_COUNT", true);
- countHist.add();
- countHist.add();
- let categHist = Telemetry.getHistogramById("TELEMETRY_TEST_CATEGORICAL");
- categHist.add("Label2");
- categHist.add("Label3");
-
- let flagKeyed = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_FLAG");
- flagKeyed.add("a", 1);
- flagKeyed.add("b", 1);
- let countKeyed = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_COUNT");
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_KEYED_COUNT", false);
- countKeyed.add("a");
- countKeyed.add("b");
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_KEYED_COUNT", true);
- countKeyed.add("a");
- countKeyed.add("b");
- countKeyed.add("b");
-}
-
-function check_histogram_values(payload) {
- const hs = payload.histograms;
- Assert.ok("TELEMETRY_TEST_COUNT" in hs, "Should have count test histogram.");
- Assert.ok("TELEMETRY_TEST_FLAG" in hs, "Should have flag test histogram.");
- Assert.ok("TELEMETRY_TEST_CATEGORICAL" in hs, "Should have categorical test histogram.");
- Assert.equal(hs["TELEMETRY_TEST_COUNT"].sum, 2,
- "Count test histogram should have the right value.");
- Assert.equal(hs["TELEMETRY_TEST_FLAG"].sum, 1,
- "Flag test histogram should have the right value.");
- Assert.equal(hs["TELEMETRY_TEST_CATEGORICAL"].sum, 3,
- "Categorical test histogram should have the right sum.");
-
- const kh = payload.keyedHistograms;
- Assert.ok("TELEMETRY_TEST_KEYED_COUNT" in kh, "Should have keyed count test histogram.");
- Assert.ok("TELEMETRY_TEST_KEYED_FLAG" in kh, "Should have keyed flag test histogram.");
- Assert.equal(kh["TELEMETRY_TEST_KEYED_COUNT"]["a"].sum, 1,
- "Keyed count test histogram should have the right value.");
- Assert.equal(kh["TELEMETRY_TEST_KEYED_COUNT"]["b"].sum, 2,
- "Keyed count test histogram should have the right value.");
- Assert.equal(kh["TELEMETRY_TEST_KEYED_FLAG"]["a"].sum, 1,
- "Keyed flag test histogram should have the right value.");
- Assert.equal(kh["TELEMETRY_TEST_KEYED_FLAG"]["b"].sum, 1,
- "Keyed flag test histogram should have the right value.");
-}
-
-add_task(function*() {
- if (!runningInParent) {
- TelemetryController.testSetupContent();
- run_child_test();
- dump("... done with child test\n");
- do_send_remote_message(MESSAGE_CHILD_TEST_DONE);
- return;
- }
-
- // Setup.
- do_get_profile(true);
- loadAddonManager(APP_ID, APP_NAME, APP_VERSION, PLATFORM_VERSION);
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
- yield TelemetryController.testSetup();
- if (runningInParent) {
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
- }
-
- // Run test in child, don't wait for it to finish.
- run_test_in_child("test_ChildHistograms.js");
- yield do_await_remote_message(MESSAGE_CHILD_TEST_DONE);
-
- yield ContentTaskUtils.waitForCondition(() => {
- let payload = TelemetrySession.getPayload("test-ping");
- return payload &&
- "processes" in payload &&
- "content" in payload.processes &&
- "histograms" in payload.processes.content &&
- "TELEMETRY_TEST_COUNT" in payload.processes.content.histograms;
- });
- const payload = TelemetrySession.getPayload("test-ping");
- Assert.ok("processes" in payload, "Should have processes section");
- Assert.ok("content" in payload.processes, "Should have child process section");
- Assert.ok("histograms" in payload.processes.content, "Child process section should have histograms.");
- Assert.ok("keyedHistograms" in payload.processes.content, "Child process section should have keyed histograms.");
- check_histogram_values(payload.processes.content);
-
- do_test_finished();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_PingAPI.js b/toolkit/components/telemetry/tests/unit/test_PingAPI.js
deleted file mode 100644
index d4d79aad4..000000000
--- a/toolkit/components/telemetry/tests/unit/test_PingAPI.js
+++ /dev/null
@@ -1,502 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-
-// This tests the public Telemetry API for submitting pings.
-
-"use strict";
-
-Cu.import("resource://gre/modules/ClientID.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetryArchive.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-XPCOMUtils.defineLazyGetter(this, "gPingsArchivePath", function() {
- return OS.Path.join(OS.Constants.Path.profileDir, "datareporting", "archived");
-});
-
-/**
- * Fakes the archive storage quota.
- * @param {Integer} aArchiveQuota The new quota, in bytes.
- */
-function fakeStorageQuota(aArchiveQuota) {
- let storage = Cu.import("resource://gre/modules/TelemetryStorage.jsm");
- storage.Policy.getArchiveQuota = () => aArchiveQuota;
-}
-
-/**
- * Lists all the valid archived pings and their metadata, sorted by creation date.
- *
- * @param aFileName {String} The filename.
- * @return {Object[]} A list of objects with the extracted data in the form:
- * { timestamp: <number>,
- * id: <string>,
- * type: <string>,
- * size: <integer> }
- */
-var getArchivedPingsInfo = Task.async(function*() {
- let dirIterator = new OS.File.DirectoryIterator(gPingsArchivePath);
- let subdirs = (yield dirIterator.nextBatch()).filter(e => e.isDir);
- let archivedPings = [];
-
- // Iterate through the subdirs of |gPingsArchivePath|.
- for (let dir of subdirs) {
- let fileIterator = new OS.File.DirectoryIterator(dir.path);
- let files = (yield fileIterator.nextBatch()).filter(e => !e.isDir);
-
- // Then get a list of the files for the current subdir.
- for (let f of files) {
- let pingInfo = TelemetryStorage._testGetArchivedPingDataFromFileName(f.name);
- if (!pingInfo) {
- // This is not a valid archived ping, skip it.
- continue;
- }
- // Find the size of the ping and then add the info to the array.
- pingInfo.size = (yield OS.File.stat(f.path)).size;
- archivedPings.push(pingInfo);
- }
- }
-
- // Sort the list by creation date and then return it.
- archivedPings.sort((a, b) => b.timestamp - a.timestamp);
- return archivedPings;
-});
-
-add_task(function* test_setup() {
- do_get_profile(true);
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
-});
-
-add_task(function* test_archivedPings() {
- // TelemetryController should not be fully initialized at this point.
- // Submitting pings should still work fine.
-
- const PINGS = [
- {
- type: "test-ping-api-1",
- payload: { foo: "bar"},
- dateCreated: new Date(2010, 1, 1, 10, 0, 0),
- },
- {
- type: "test-ping-api-2",
- payload: { moo: "meh"},
- dateCreated: new Date(2010, 2, 1, 10, 0, 0),
- },
- ];
-
- // Submit pings and check the ping list.
- let expectedPingList = [];
-
- for (let data of PINGS) {
- fakeNow(data.dateCreated);
- data.id = yield TelemetryController.submitExternalPing(data.type, data.payload);
- let list = yield TelemetryArchive.promiseArchivedPingList();
-
- expectedPingList.push({
- id: data.id,
- type: data.type,
- timestampCreated: data.dateCreated.getTime(),
- });
- Assert.deepEqual(list, expectedPingList, "Archived ping list should contain submitted pings");
- }
-
- // Check loading the archived pings.
- let checkLoadingPings = Task.async(function*() {
- for (let data of PINGS) {
- let ping = yield TelemetryArchive.promiseArchivedPingById(data.id);
- Assert.equal(ping.id, data.id, "Archived ping should have matching id");
- Assert.equal(ping.type, data.type, "Archived ping should have matching type");
- Assert.equal(ping.creationDate, data.dateCreated.toISOString(),
- "Archived ping should have matching creation date");
- }
- });
-
- yield checkLoadingPings();
-
- // Check that we find the archived pings again by scanning after a restart.
- yield TelemetryController.testReset();
-
- let pingList = yield TelemetryArchive.promiseArchivedPingList();
- Assert.deepEqual(expectedPingList, pingList,
- "Should have submitted pings in archive list after restart");
- yield checkLoadingPings();
-
- // Write invalid pings into the archive with both valid and invalid names.
- let writeToArchivedDir = Task.async(function*(dirname, filename, content, compressed) {
- const dirPath = OS.Path.join(gPingsArchivePath, dirname);
- yield OS.File.makeDir(dirPath, { ignoreExisting: true });
- const filePath = OS.Path.join(dirPath, filename);
- const options = { tmpPath: filePath + ".tmp", noOverwrite: false };
- if (compressed) {
- options.compression = "lz4";
- }
- yield OS.File.writeAtomic(filePath, content, options);
- });
-
- const FAKE_ID1 = "10000000-0123-0123-0123-0123456789a1";
- const FAKE_ID2 = "20000000-0123-0123-0123-0123456789a2";
- const FAKE_ID3 = "20000000-0123-0123-0123-0123456789a3";
- const FAKE_TYPE = "foo";
-
- // These should get rejected.
- yield writeToArchivedDir("xx", "foo.json", "{}");
- yield writeToArchivedDir("2010-02", "xx.xx.xx.json", "{}");
- // This one should get picked up...
- yield writeToArchivedDir("2010-02", "1." + FAKE_ID1 + "." + FAKE_TYPE + ".json", "{}");
- // ... but get overwritten by this one.
- yield writeToArchivedDir("2010-02", "2." + FAKE_ID1 + "." + FAKE_TYPE + ".json", "");
- // This should get picked up fine.
- yield writeToArchivedDir("2010-02", "3." + FAKE_ID2 + "." + FAKE_TYPE + ".json", "");
- // This compressed ping should get picked up fine as well.
- yield writeToArchivedDir("2010-02", "4." + FAKE_ID3 + "." + FAKE_TYPE + ".jsonlz4", "");
-
- expectedPingList.push({
- id: FAKE_ID1,
- type: "foo",
- timestampCreated: 2,
- });
- expectedPingList.push({
- id: FAKE_ID2,
- type: "foo",
- timestampCreated: 3,
- });
- expectedPingList.push({
- id: FAKE_ID3,
- type: "foo",
- timestampCreated: 4,
- });
- expectedPingList.sort((a, b) => a.timestampCreated - b.timestampCreated);
-
- // Reset the TelemetryArchive so we scan the archived dir again.
- yield TelemetryController.testReset();
-
- // Check that we are still picking up the valid archived pings on disk,
- // plus the valid ones above.
- pingList = yield TelemetryArchive.promiseArchivedPingList();
- Assert.deepEqual(expectedPingList, pingList, "Should have picked up valid archived pings");
- yield checkLoadingPings();
-
- // Now check that we fail to load the two invalid pings from above.
- Assert.ok((yield promiseRejects(TelemetryArchive.promiseArchivedPingById(FAKE_ID1))),
- "Should have rejected invalid ping");
- Assert.ok((yield promiseRejects(TelemetryArchive.promiseArchivedPingById(FAKE_ID2))),
- "Should have rejected invalid ping");
-});
-
-add_task(function* test_archiveCleanup() {
- const PING_TYPE = "foo";
-
- // Empty the archive.
- yield OS.File.removeDir(gPingsArchivePath);
-
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SCAN_PING_COUNT").clear();
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_DIRECTORIES_COUNT").clear();
- // Also reset these histograms to make sure normal sized pings don't get counted.
- Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_ARCHIVED").clear();
- Telemetry.getHistogramById("TELEMETRY_DISCARDED_ARCHIVED_PINGS_SIZE_MB").clear();
-
- // Build the cache. Nothing should be evicted as there's no ping directory.
- yield TelemetryController.testReset();
- yield TelemetryStorage.testCleanupTaskPromise();
- yield TelemetryArchive.promiseArchivedPingList();
-
- let h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SCAN_PING_COUNT").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must report 0 pings scanned if no archive dir exists.");
- // One directory out of four was removed as well.
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTED_OLD_DIRS").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must report 0 evicted dirs if no archive dir exists.");
-
- let expectedPrunedInfo = [];
- let expectedNotPrunedInfo = [];
-
- let checkArchive = Task.async(function*() {
- // Check that the pruned pings are not on disk anymore.
- for (let prunedInfo of expectedPrunedInfo) {
- yield Assert.rejects(TelemetryArchive.promiseArchivedPingById(prunedInfo.id),
- "Ping " + prunedInfo.id + " should have been pruned.");
- const pingPath =
- TelemetryStorage._testGetArchivedPingPath(prunedInfo.id, prunedInfo.creationDate, PING_TYPE);
- Assert.ok(!(yield OS.File.exists(pingPath)), "The ping should not be on the disk anymore.");
- }
-
- // Check that the expected pings are there.
- for (let expectedInfo of expectedNotPrunedInfo) {
- Assert.ok((yield TelemetryArchive.promiseArchivedPingById(expectedInfo.id)),
- "Ping" + expectedInfo.id + " should be in the archive.");
- }
- });
-
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SESSION_PING_COUNT").clear();
-
- // Create a ping which should be pruned because it is past the retention period.
- let date = fakeNow(2010, 1, 1, 1, 0, 0);
- let firstDate = date;
- let pingId = yield TelemetryController.submitExternalPing(PING_TYPE, {}, {});
- expectedPrunedInfo.push({ id: pingId, creationDate: date });
-
- // Create a ping which should be kept because it is within the retention period.
- const oldestDirectoryDate = fakeNow(2010, 2, 1, 1, 0, 0);
- pingId = yield TelemetryController.submitExternalPing(PING_TYPE, {}, {});
- expectedNotPrunedInfo.push({ id: pingId, creationDate: oldestDirectoryDate });
-
- // Create 20 other pings which are within the retention period, but would be affected
- // by the disk quota.
- for (let month of [3, 4]) {
- for (let minute = 0; minute < 10; minute++) {
- date = fakeNow(2010, month, 1, 1, minute, 0);
- pingId = yield TelemetryController.submitExternalPing(PING_TYPE, {}, {});
- expectedNotPrunedInfo.push({ id: pingId, creationDate: date });
- }
- }
-
- // We expect all the pings we archived to be in this histogram.
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SESSION_PING_COUNT");
- Assert.equal(h.snapshot().sum, 22, "All the pings must be live-accumulated in the histogram.");
- // Reset the histogram that will be populated by the archive scan.
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTED_OLD_DIRS").clear();
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_OLDEST_DIRECTORY_AGE").clear();
-
- // Move the current date 60 days ahead of the first ping.
- fakeNow(futureDate(firstDate, 60 * MILLISECONDS_PER_DAY));
- // Reset TelemetryArchive and TelemetryController to start the startup cleanup.
- yield TelemetryController.testReset();
- // Wait for the cleanup to finish.
- yield TelemetryStorage.testCleanupTaskPromise();
- // Then scan the archived dir.
- yield TelemetryArchive.promiseArchivedPingList();
-
- // Check that the archive is in the correct state.
- yield checkArchive();
-
- // Make sure the ping count is correct after the scan (one ping was removed).
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SCAN_PING_COUNT").snapshot();
- Assert.equal(h.sum, 21, "The histogram must count all the pings in the archive.");
- // One directory out of four was removed as well.
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTED_OLD_DIRS").snapshot();
- Assert.equal(h.sum, 1, "Telemetry must correctly report removed archive directories.");
- // Check that the remaining directories are correctly counted.
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_DIRECTORIES_COUNT").snapshot();
- Assert.equal(h.sum, 3, "Telemetry must correctly report the remaining archive directories.");
- // Check that the remaining directories are correctly counted.
- const oldestAgeInMonths = 1;
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_OLDEST_DIRECTORY_AGE").snapshot();
- Assert.equal(h.sum, oldestAgeInMonths,
- "Telemetry must correctly report age of the oldest directory in the archive.");
-
- // We need to test the archive size before we hit the quota, otherwise a special
- // value is recorded.
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SIZE_MB").clear();
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTED_OVER_QUOTA").clear();
- Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTING_OVER_QUOTA_MS").clear();
-
- // Move the current date 60 days ahead of the second ping.
- fakeNow(futureDate(oldestDirectoryDate, 60 * MILLISECONDS_PER_DAY));
- // Reset TelemetryController and TelemetryArchive.
- yield TelemetryController.testReset();
- // Wait for the cleanup to finish.
- yield TelemetryStorage.testCleanupTaskPromise();
- // Then scan the archived dir again.
- yield TelemetryArchive.promiseArchivedPingList();
-
- // Move the oldest ping to the unexpected pings list.
- expectedPrunedInfo.push(expectedNotPrunedInfo.shift());
- // Check that the archive is in the correct state.
- yield checkArchive();
-
- // Find how much disk space the archive takes.
- const archivedPingsInfo = yield getArchivedPingsInfo();
- let archiveSizeInBytes =
- archivedPingsInfo.reduce((lastResult, element) => lastResult + element.size, 0);
-
- // Check that the correct values for quota probes are reported when no quota is hit.
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SIZE_MB").snapshot();
- Assert.equal(h.sum, Math.round(archiveSizeInBytes / 1024 / 1024),
- "Telemetry must report the correct archive size.");
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTED_OVER_QUOTA").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must report 0 evictions if quota is not hit.");
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTING_OVER_QUOTA_MS").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must report a null elapsed time if quota is not hit.");
-
- // Set the quota to 80% of the space.
- const testQuotaInBytes = archiveSizeInBytes * 0.8;
- fakeStorageQuota(testQuotaInBytes);
-
- // The storage prunes archived pings until we reach 90% of the requested storage quota.
- // Based on that, find how many pings should be kept.
- const safeQuotaSize = testQuotaInBytes * 0.9;
- let sizeInBytes = 0;
- let pingsWithinQuota = [];
- let pingsOutsideQuota = [];
-
- for (let pingInfo of archivedPingsInfo) {
- sizeInBytes += pingInfo.size;
- if (sizeInBytes >= safeQuotaSize) {
- pingsOutsideQuota.push({ id: pingInfo.id, creationDate: new Date(pingInfo.timestamp) });
- continue;
- }
- pingsWithinQuota.push({ id: pingInfo.id, creationDate: new Date(pingInfo.timestamp) });
- }
-
- expectedNotPrunedInfo = pingsWithinQuota;
- expectedPrunedInfo = expectedPrunedInfo.concat(pingsOutsideQuota);
-
- // Reset TelemetryArchive and TelemetryController to start the startup cleanup.
- yield TelemetryController.testReset();
- yield TelemetryStorage.testCleanupTaskPromise();
- yield TelemetryArchive.promiseArchivedPingList();
- // Check that the archive is in the correct state.
- yield checkArchive();
-
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_EVICTED_OVER_QUOTA").snapshot();
- Assert.equal(h.sum, pingsOutsideQuota.length,
- "Telemetry must correctly report the over quota pings evicted from the archive.");
- h = Telemetry.getHistogramById("TELEMETRY_ARCHIVE_SIZE_MB").snapshot();
- Assert.equal(h.sum, 300, "Archive quota was hit, a special size must be reported.");
-
- // Trigger a cleanup again and make sure we're not removing anything.
- yield TelemetryController.testReset();
- yield TelemetryStorage.testCleanupTaskPromise();
- yield TelemetryArchive.promiseArchivedPingList();
- yield checkArchive();
-
- const OVERSIZED_PING_ID = "9b21ec8f-f762-4d28-a2c1-44e1c4694f24";
- // Create and archive an oversized, uncompressed, ping.
- const OVERSIZED_PING = {
- id: OVERSIZED_PING_ID,
- type: PING_TYPE,
- creationDate: (new Date()).toISOString(),
- // Generate a ~2MB string to use as the payload.
- payload: generateRandomString(2 * 1024 * 1024)
- };
- yield TelemetryArchive.promiseArchivePing(OVERSIZED_PING);
-
- // Get the size of the archived ping.
- const oversizedPingPath =
- TelemetryStorage._testGetArchivedPingPath(OVERSIZED_PING.id, new Date(OVERSIZED_PING.creationDate), PING_TYPE) + "lz4";
- const archivedPingSizeMB = Math.floor((yield OS.File.stat(oversizedPingPath)).size / 1024 / 1024);
-
- // We expect the oversized ping to be pruned when scanning the archive.
- expectedPrunedInfo.push({ id: OVERSIZED_PING_ID, creationDate: new Date(OVERSIZED_PING.creationDate) });
-
- // Scan the archive.
- yield TelemetryController.testReset();
- yield TelemetryStorage.testCleanupTaskPromise();
- yield TelemetryArchive.promiseArchivedPingList();
- // The following also checks that non oversized pings are not removed.
- yield checkArchive();
-
- // Make sure we're correctly updating the related histograms.
- h = Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_ARCHIVED").snapshot();
- Assert.equal(h.sum, 1, "Telemetry must report 1 oversized ping in the archive.");
- h = Telemetry.getHistogramById("TELEMETRY_DISCARDED_ARCHIVED_PINGS_SIZE_MB").snapshot();
- Assert.equal(h.counts[archivedPingSizeMB], 1,
- "Telemetry must report the correct size for the oversized ping.");
-});
-
-add_task(function* test_clientId() {
- // Check that a ping submitted after the delayed telemetry initialization completed
- // should get a valid client id.
- yield TelemetryController.testReset();
- const clientId = yield ClientID.getClientID();
-
- let id = yield TelemetryController.submitExternalPing("test-type", {}, {addClientId: true});
- let ping = yield TelemetryArchive.promiseArchivedPingById(id);
-
- Assert.ok(!!ping, "Should have loaded the ping.");
- Assert.ok("clientId" in ping, "Ping should have a client id.");
- Assert.ok(UUID_REGEX.test(ping.clientId), "Client id is in UUID format.");
- Assert.equal(ping.clientId, clientId, "Ping client id should match the global client id.");
-
- // We should have cached the client id now. Lets confirm that by
- // checking the client id on a ping submitted before the async
- // controller setup is finished.
- let promiseSetup = TelemetryController.testReset();
- id = yield TelemetryController.submitExternalPing("test-type", {}, {addClientId: true});
- ping = yield TelemetryArchive.promiseArchivedPingById(id);
- Assert.equal(ping.clientId, clientId);
-
- // Finish setup.
- yield promiseSetup;
-});
-
-add_task(function* test_InvalidPingType() {
- const TYPES = [
- "a",
- "-",
- "¿€€€?",
- "-foo-",
- "-moo",
- "zoo-",
- ".bar",
- "asfd.asdf",
- ];
-
- for (let type of TYPES) {
- let histogram = Telemetry.getKeyedHistogramById("TELEMETRY_INVALID_PING_TYPE_SUBMITTED");
- Assert.equal(histogram.snapshot(type).sum, 0,
- "Should not have counted this invalid ping yet: " + type);
- Assert.ok(promiseRejects(TelemetryController.submitExternalPing(type, {})),
- "Ping type should have been rejected.");
- Assert.equal(histogram.snapshot(type).sum, 1,
- "Should have counted this as an invalid ping type.");
- }
-});
-
-add_task(function* test_InvalidPayloadType() {
- const PAYLOAD_TYPES = [
- 19,
- "string",
- [1, 2, 3, 4],
- null,
- undefined,
- ];
-
- let histogram = Telemetry.getHistogramById("TELEMETRY_INVALID_PAYLOAD_SUBMITTED");
- for (let i = 0; i < PAYLOAD_TYPES.length; i++) {
- histogram.clear();
- Assert.equal(histogram.snapshot().sum, 0,
- "Should not have counted this invalid payload yet: " + JSON.stringify(PAYLOAD_TYPES[i]));
- Assert.ok(yield promiseRejects(TelemetryController.submitExternalPing("payload-test", PAYLOAD_TYPES[i])),
- "Payload type should have been rejected.");
- Assert.equal(histogram.snapshot().sum, 1,
- "Should have counted this as an invalid payload type.");
- }
-});
-
-add_task(function* test_currentPingData() {
- yield TelemetryController.testSetup();
-
- // Setup test data.
- let h = Telemetry.getHistogramById("TELEMETRY_TEST_RELEASE_OPTOUT");
- h.clear();
- h.add(1);
- let k = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT");
- k.clear();
- k.add("a", 1);
-
- // Get current ping data objects and check that their data is sane.
- for (let subsession of [true, false]) {
- let ping = TelemetryController.getCurrentPingData(subsession);
-
- Assert.ok(!!ping, "Should have gotten a ping.");
- Assert.equal(ping.type, "main", "Ping should have correct type.");
- const expectedReason = subsession ? "gather-subsession-payload" : "gather-payload";
- Assert.equal(ping.payload.info.reason, expectedReason, "Ping should have the correct reason.");
-
- let id = "TELEMETRY_TEST_RELEASE_OPTOUT";
- Assert.ok(id in ping.payload.histograms, "Payload should have test count histogram.");
- Assert.equal(ping.payload.histograms[id].sum, 1, "Test count value should match.");
- id = "TELEMETRY_TEST_KEYED_RELEASE_OPTOUT";
- Assert.ok(id in ping.payload.keyedHistograms, "Payload should have keyed test histogram.");
- Assert.equal(ping.payload.keyedHistograms[id]["a"].sum, 1, "Keyed test value should match.");
- }
-});
-
-add_task(function* test_shutdown() {
- yield TelemetryController.testShutdown();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_SubsessionChaining.js b/toolkit/components/telemetry/tests/unit/test_SubsessionChaining.js
deleted file mode 100644
index c86fb0499..000000000
--- a/toolkit/components/telemetry/tests/unit/test_SubsessionChaining.js
+++ /dev/null
@@ -1,236 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-
-Cu.import("resource://gre/modules/Preferences.jsm", this);
-Cu.import("resource://gre/modules/Promise.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/TelemetryArchive.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetryEnvironment.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-
-const MS_IN_ONE_HOUR = 60 * 60 * 1000;
-const MS_IN_ONE_DAY = 24 * MS_IN_ONE_HOUR;
-
-const PREF_BRANCH = "toolkit.telemetry.";
-const PREF_ARCHIVE_ENABLED = PREF_BRANCH + "archive.enabled";
-
-const REASON_ABORTED_SESSION = "aborted-session";
-const REASON_DAILY = "daily";
-const REASON_ENVIRONMENT_CHANGE = "environment-change";
-const REASON_SHUTDOWN = "shutdown";
-
-XPCOMUtils.defineLazyGetter(this, "DATAREPORTING_PATH", function() {
- return OS.Path.join(OS.Constants.Path.profileDir, "datareporting");
-});
-
-var promiseValidateArchivedPings = Task.async(function*(aExpectedReasons) {
- // The list of ping reasons which mark the session end (and must reset the subsession
- // count).
- const SESSION_END_PING_REASONS = new Set([ REASON_ABORTED_SESSION, REASON_SHUTDOWN ]);
-
- let list = yield TelemetryArchive.promiseArchivedPingList();
-
- // We're just interested in the "main" pings.
- list = list.filter(p => p.type == "main");
-
- Assert.equal(aExpectedReasons.length, list.length, "All the expected pings must be received.");
-
- let previousPing = yield TelemetryArchive.promiseArchivedPingById(list[0].id);
- Assert.equal(aExpectedReasons.shift(), previousPing.payload.info.reason,
- "Telemetry should only get pings with expected reasons.");
- Assert.equal(previousPing.payload.info.previousSessionId, null,
- "The first session must report a null previous session id.");
- Assert.equal(previousPing.payload.info.previousSubsessionId, null,
- "The first subsession must report a null previous subsession id.");
- Assert.equal(previousPing.payload.info.profileSubsessionCounter, 1,
- "profileSubsessionCounter must be 1 the first time.");
- Assert.equal(previousPing.payload.info.subsessionCounter, 1,
- "subsessionCounter must be 1 the first time.");
-
- let expectedSubsessionCounter = 1;
- let expectedPreviousSessionId = previousPing.payload.info.sessionId;
-
- for (let i = 1; i < list.length; i++) {
- let currentPing = yield TelemetryArchive.promiseArchivedPingById(list[i].id);
- let currentInfo = currentPing.payload.info;
- let previousInfo = previousPing.payload.info;
- do_print("Archive entry " + i + " - id: " + currentPing.id + ", reason: " + currentInfo.reason);
-
- Assert.equal(aExpectedReasons.shift(), currentInfo.reason,
- "Telemetry should only get pings with expected reasons.");
- Assert.equal(currentInfo.previousSessionId, expectedPreviousSessionId,
- "Telemetry must correctly chain session identifiers.");
- Assert.equal(currentInfo.previousSubsessionId, previousInfo.subsessionId,
- "Telemetry must correctly chain subsession identifiers.");
- Assert.equal(currentInfo.profileSubsessionCounter, previousInfo.profileSubsessionCounter + 1,
- "Telemetry must correctly track the profile subsessions count.");
- Assert.equal(currentInfo.subsessionCounter, expectedSubsessionCounter,
- "The subsession counter should be monotonically increasing.");
-
- // Store the current ping as previous.
- previousPing = currentPing;
- // Reset the expected subsession counter, if required. Otherwise increment the expected
- // subsession counter.
- // If this is the final subsession of a session we need to update expected values accordingly.
- if (SESSION_END_PING_REASONS.has(currentInfo.reason)) {
- expectedSubsessionCounter = 1;
- expectedPreviousSessionId = currentInfo.sessionId;
- } else {
- expectedSubsessionCounter++;
- }
- }
-});
-
-add_task(function* test_setup() {
- do_test_pending();
-
- // Addon manager needs a profile directory
- do_get_profile();
- loadAddonManager("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9.2");
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- Preferences.set(PREF_TELEMETRY_ENABLED, true);
-});
-
-add_task(function* test_subsessionsChaining() {
- if (gIsAndroid) {
- // We don't support subsessions yet on Android, so skip the next checks.
- return;
- }
-
- const PREF_TEST = PREF_BRANCH + "test.pref1";
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_VALUE}],
- ]);
- Preferences.reset(PREF_TEST);
-
- // Fake the clock data to manually trigger an aborted-session ping and a daily ping.
- // This is also helpful to make sure we get the archived pings in an expected order.
- let now = fakeNow(2009, 9, 18, 0, 0, 0);
- let monotonicNow = fakeMonotonicNow(1000);
-
- let moveClockForward = (minutes) => {
- let ms = minutes * MILLISECONDS_PER_MINUTE;
- now = fakeNow(futureDate(now, ms));
- monotonicNow = fakeMonotonicNow(monotonicNow + ms);
- }
-
- // Keep track of the ping reasons we're expecting in this test.
- let expectedReasons = [];
-
- // Start and shut down Telemetry. We expect a shutdown ping with profileSubsessionCounter: 1,
- // subsessionCounter: 1, subsessionId: A, and previousSubsessionId: null to be archived.
- yield TelemetryController.testSetup();
- yield TelemetryController.testShutdown();
- expectedReasons.push(REASON_SHUTDOWN);
-
- // Start Telemetry but don't wait for it to initialise before shutting down. We expect a
- // shutdown ping with profileSubsessionCounter: 2, subsessionCounter: 1, subsessionId: B
- // and previousSubsessionId: A to be archived.
- moveClockForward(30);
- TelemetryController.testReset();
- yield TelemetryController.testShutdown();
- expectedReasons.push(REASON_SHUTDOWN);
-
- // Start Telemetry and simulate an aborted-session ping. We expect an aborted-session ping
- // with profileSubsessionCounter: 3, subsessionCounter: 1, subsessionId: C and
- // previousSubsessionId: B to be archived.
- let schedulerTickCallback = null;
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
- moveClockForward(6);
- // Trigger the an aborted session ping save. When testing,we are not saving the aborted-session
- // ping as soon as Telemetry starts, otherwise we would end up with unexpected pings being
- // sent when calling |TelemetryController.testReset()|, thus breaking some tests.
- Assert.ok(!!schedulerTickCallback);
- yield schedulerTickCallback();
- expectedReasons.push(REASON_ABORTED_SESSION);
-
- // Start Telemetry and trigger an environment change through a pref modification. We expect
- // an environment-change ping with profileSubsessionCounter: 4, subsessionCounter: 1,
- // subsessionId: D and previousSubsessionId: C to be archived.
- moveClockForward(30);
- yield TelemetryController.testReset();
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
- moveClockForward(30);
- Preferences.set(PREF_TEST, 1);
- expectedReasons.push(REASON_ENVIRONMENT_CHANGE);
-
- // Shut down Telemetry. We expect a shutdown ping with profileSubsessionCounter: 5,
- // subsessionCounter: 2, subsessionId: E and previousSubsessionId: D to be archived.
- moveClockForward(30);
- yield TelemetryController.testShutdown();
- expectedReasons.push(REASON_SHUTDOWN);
-
- // Start Telemetry and trigger a daily ping. We expect a daily ping with
- // profileSubsessionCounter: 6, subsessionCounter: 1, subsessionId: F and
- // previousSubsessionId: E to be archived.
- moveClockForward(30);
- yield TelemetryController.testReset();
-
- // Delay the callback around midnight.
- now = fakeNow(futureDate(now, MS_IN_ONE_DAY));
- // Trigger the daily ping.
- yield schedulerTickCallback();
- expectedReasons.push(REASON_DAILY);
-
- // Trigger an environment change ping. We expect an environment-changed ping with
- // profileSubsessionCounter: 7, subsessionCounter: 2, subsessionId: G and
- // previousSubsessionId: F to be archived.
- moveClockForward(30);
- Preferences.set(PREF_TEST, 0);
- expectedReasons.push(REASON_ENVIRONMENT_CHANGE);
-
- // Shut down Telemetry and trigger a shutdown ping.
- moveClockForward(30);
- yield TelemetryController.testShutdown();
- expectedReasons.push(REASON_SHUTDOWN);
-
- // Start Telemetry and trigger an environment change.
- yield TelemetryController.testReset();
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
- moveClockForward(30);
- Preferences.set(PREF_TEST, 1);
- expectedReasons.push(REASON_ENVIRONMENT_CHANGE);
-
- // Don't shut down, instead trigger an aborted-session ping.
- moveClockForward(6);
- // Trigger the an aborted session ping save.
- yield schedulerTickCallback();
- expectedReasons.push(REASON_ABORTED_SESSION);
-
- // Start Telemetry and trigger a daily ping.
- moveClockForward(30);
- yield TelemetryController.testReset();
- // Delay the callback around midnight.
- now = futureDate(now, MS_IN_ONE_DAY);
- fakeNow(now);
- // Trigger the daily ping.
- yield schedulerTickCallback();
- expectedReasons.push(REASON_DAILY);
-
- // Trigger an environment change.
- moveClockForward(30);
- Preferences.set(PREF_TEST, 0);
- expectedReasons.push(REASON_ENVIRONMENT_CHANGE);
-
- // And an aborted-session ping again.
- moveClockForward(6);
- // Trigger the an aborted session ping save.
- yield schedulerTickCallback();
- expectedReasons.push(REASON_ABORTED_SESSION);
-
- // Make sure the aborted-session ping gets archived.
- yield TelemetryController.testReset();
-
- yield promiseValidateArchivedPings(expectedReasons);
-});
-
-add_task(function* () {
- yield TelemetryController.testShutdown();
- do_test_finished();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryController.js b/toolkit/components/telemetry/tests/unit/test_TelemetryController.js
deleted file mode 100644
index b383de6bf..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryController.js
+++ /dev/null
@@ -1,507 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-/* This testcase triggers two telemetry pings.
- *
- * Telemetry code keeps histograms of past telemetry pings. The first
- * ping populates these histograms. One of those histograms is then
- * checked in the second request.
- */
-
-Cu.import("resource://gre/modules/ClientID.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetryStorage.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySend.jsm", this);
-Cu.import("resource://gre/modules/TelemetryArchive.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/Promise.jsm", this);
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-const PING_FORMAT_VERSION = 4;
-const DELETION_PING_TYPE = "deletion";
-const TEST_PING_TYPE = "test-ping-type";
-
-const PLATFORM_VERSION = "1.9.2";
-const APP_VERSION = "1";
-const APP_NAME = "XPCShell";
-
-const PREF_BRANCH = "toolkit.telemetry.";
-const PREF_ENABLED = PREF_BRANCH + "enabled";
-const PREF_ARCHIVE_ENABLED = PREF_BRANCH + "archive.enabled";
-const PREF_FHR_UPLOAD_ENABLED = "datareporting.healthreport.uploadEnabled";
-const PREF_UNIFIED = PREF_BRANCH + "unified";
-
-var gClientID = null;
-
-function sendPing(aSendClientId, aSendEnvironment) {
- if (PingServer.started) {
- TelemetrySend.setServer("http://localhost:" + PingServer.port);
- } else {
- TelemetrySend.setServer("http://doesnotexist");
- }
-
- let options = {
- addClientId: aSendClientId,
- addEnvironment: aSendEnvironment,
- };
- return TelemetryController.submitExternalPing(TEST_PING_TYPE, {}, options);
-}
-
-function checkPingFormat(aPing, aType, aHasClientId, aHasEnvironment) {
- const MANDATORY_PING_FIELDS = [
- "type", "id", "creationDate", "version", "application", "payload"
- ];
-
- const APPLICATION_TEST_DATA = {
- buildId: gAppInfo.appBuildID,
- name: APP_NAME,
- version: APP_VERSION,
- displayVersion: AppConstants.MOZ_APP_VERSION_DISPLAY,
- vendor: "Mozilla",
- platformVersion: PLATFORM_VERSION,
- xpcomAbi: "noarch-spidermonkey",
- };
-
- // Check that the ping contains all the mandatory fields.
- for (let f of MANDATORY_PING_FIELDS) {
- Assert.ok(f in aPing, f + " must be available.");
- }
-
- Assert.equal(aPing.type, aType, "The ping must have the correct type.");
- Assert.equal(aPing.version, PING_FORMAT_VERSION, "The ping must have the correct version.");
-
- // Test the application section.
- for (let f in APPLICATION_TEST_DATA) {
- Assert.equal(aPing.application[f], APPLICATION_TEST_DATA[f],
- f + " must have the correct value.");
- }
-
- // We can't check the values for channel and architecture. Just make
- // sure they are in.
- Assert.ok("architecture" in aPing.application,
- "The application section must have an architecture field.");
- Assert.ok("channel" in aPing.application,
- "The application section must have a channel field.");
-
- // Check the clientId and environment fields, as needed.
- Assert.equal("clientId" in aPing, aHasClientId);
- Assert.equal("environment" in aPing, aHasEnvironment);
-}
-
-add_task(function* test_setup() {
- // Addon manager needs a profile directory
- do_get_profile();
- loadAddonManager("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9.2");
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- Services.prefs.setBoolPref(PREF_ENABLED, true);
- Services.prefs.setBoolPref(PREF_FHR_UPLOAD_ENABLED, true);
-
- yield new Promise(resolve =>
- Telemetry.asyncFetchTelemetryData(wrapWithExceptionHandler(resolve)));
-});
-
-add_task(function* asyncSetup() {
- yield TelemetryController.testSetup();
-});
-
-// Ensure that not overwriting an existing file fails silently
-add_task(function* test_overwritePing() {
- let ping = {id: "foo"};
- yield TelemetryStorage.savePing(ping, true);
- yield TelemetryStorage.savePing(ping, false);
- yield TelemetryStorage.cleanupPingFile(ping);
-});
-
-// Checks that a sent ping is correctly received by a dummy http server.
-add_task(function* test_simplePing() {
- PingServer.start();
- // Update the Telemetry Server preference with the address of the local server.
- // Otherwise we might end up sending stuff to a non-existing server after
- // |TelemetryController.testReset| is called.
- Preferences.set(TelemetryController.Constants.PREF_SERVER, "http://localhost:" + PingServer.port);
-
- yield sendPing(false, false);
- let request = yield PingServer.promiseNextRequest();
-
- // Check that we have a version query parameter in the URL.
- Assert.notEqual(request.queryString, "");
-
- // Make sure the version in the query string matches the new ping format version.
- let params = request.queryString.split("&");
- Assert.ok(params.find(p => p == ("v=" + PING_FORMAT_VERSION)));
-
- let ping = decodeRequestPayload(request);
- checkPingFormat(ping, TEST_PING_TYPE, false, false);
-});
-
-add_task(function* test_disableDataUpload() {
- const isUnified = Preferences.get(PREF_UNIFIED, false);
- if (!isUnified) {
- // Skipping the test if unified telemetry is off, as no deletion ping will
- // be generated.
- return;
- }
-
- // Disable FHR upload: this should trigger a deletion ping.
- Preferences.set(PREF_FHR_UPLOAD_ENABLED, false);
-
- let ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, DELETION_PING_TYPE, true, false);
- // Wait on ping activity to settle.
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- // Restore FHR Upload.
- Preferences.set(PREF_FHR_UPLOAD_ENABLED, true);
-
- // Simulate a failure in sending the deletion ping by disabling the HTTP server.
- yield PingServer.stop();
-
- // Try to send a ping. It will be saved as pending and get deleted when disabling upload.
- TelemetryController.submitExternalPing(TEST_PING_TYPE, {});
-
- // Disable FHR upload to send a deletion ping again.
- Preferences.set(PREF_FHR_UPLOAD_ENABLED, false);
-
- // Wait on sending activity to settle, as |TelemetryController.testReset()| doesn't do that.
- yield TelemetrySend.testWaitOnOutgoingPings();
- // Wait for the pending pings to be deleted. Resetting TelemetryController doesn't
- // trigger the shutdown, so we need to call it ourselves.
- yield TelemetryStorage.shutdown();
- // Simulate a restart, and spin the send task.
- yield TelemetryController.testReset();
-
- // Disabling Telemetry upload must clear out all the pending pings.
- let pendingPings = yield TelemetryStorage.loadPendingPingList();
- Assert.equal(pendingPings.length, 1,
- "All the pending pings but the deletion ping should have been deleted");
-
- // Enable the ping server again.
- PingServer.start();
- // We set the new server using the pref, otherwise it would get reset with
- // |TelemetryController.testReset|.
- Preferences.set(TelemetryController.Constants.PREF_SERVER, "http://localhost:" + PingServer.port);
-
- // Stop the sending task and then start it again.
- yield TelemetrySend.shutdown();
- // Reset the controller to spin the ping sending task.
- yield TelemetryController.testReset();
- ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, DELETION_PING_TYPE, true, false);
-
- // Wait on ping activity to settle before moving on to the next test. If we were
- // to shut down telemetry, even though the PingServer caught the expected pings,
- // TelemetrySend could still be processing them (clearing pings would happen in
- // a couple of ticks). Shutting down would cancel the request and save them as
- // pending pings.
- yield TelemetrySend.testWaitOnOutgoingPings();
- // Restore FHR Upload.
- Preferences.set(PREF_FHR_UPLOAD_ENABLED, true);
-});
-
-add_task(function* test_pingHasClientId() {
- const PREF_CACHED_CLIENTID = "toolkit.telemetry.cachedClientID";
-
- // Make sure we have no cached client ID for this test: we'll try to send
- // a ping with it while Telemetry is being initialized.
- Preferences.reset(PREF_CACHED_CLIENTID);
- yield TelemetryController.testShutdown();
- yield ClientID._reset();
- yield TelemetryStorage.testClearPendingPings();
- // And also clear the counter histogram since we're here.
- let h = Telemetry.getHistogramById("TELEMETRY_PING_SUBMISSION_WAITING_CLIENTID");
- h.clear();
-
- // Init telemetry and try to send a ping with a client ID.
- let promisePingSetup = TelemetryController.testReset();
- yield sendPing(true, false);
- Assert.equal(h.snapshot().sum, 1,
- "We must have a ping waiting for the clientId early during startup.");
- // Wait until we are fully initialized. Pings will be assembled but won't get
- // sent before then.
- yield promisePingSetup;
-
- let ping = yield PingServer.promiseNextPing();
- // Fetch the client ID after initializing and fetching the the ping, so we
- // don't unintentionally trigger its loading. We'll still need the client ID
- // to see if the ping looks sane.
- gClientID = yield ClientID.getClientID();
-
- checkPingFormat(ping, TEST_PING_TYPE, true, false);
- Assert.equal(ping.clientId, gClientID, "The correct clientId must be reported.");
-
- // Shutdown Telemetry so we can safely restart it.
- yield TelemetryController.testShutdown();
- yield TelemetryStorage.testClearPendingPings();
-
- // We should have cached the client ID now. Lets confirm that by checking it before
- // the async ping setup is finished.
- h.clear();
- promisePingSetup = TelemetryController.testReset();
- yield sendPing(true, false);
- yield promisePingSetup;
-
- // Check that we received the cached client id.
- Assert.equal(h.snapshot().sum, 0, "We must have used the cached clientId.");
- ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, TEST_PING_TYPE, true, false);
- Assert.equal(ping.clientId, gClientID,
- "Telemetry should report the correct cached clientId.");
-
- // Check that sending a ping without relying on the cache, after the
- // initialization, still works.
- Preferences.reset(PREF_CACHED_CLIENTID);
- yield TelemetryController.testShutdown();
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testReset();
- yield sendPing(true, false);
- ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, TEST_PING_TYPE, true, false);
- Assert.equal(ping.clientId, gClientID, "The correct clientId must be reported.");
- Assert.equal(h.snapshot().sum, 0, "No ping should have been waiting for a clientId.");
-});
-
-add_task(function* test_pingHasEnvironment() {
- // Send a ping with the environment data.
- yield sendPing(false, true);
- let ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, TEST_PING_TYPE, false, true);
-
- // Test a field in the environment build section.
- Assert.equal(ping.application.buildId, ping.environment.build.buildId);
-});
-
-add_task(function* test_pingHasEnvironmentAndClientId() {
- // Send a ping with the environment data and client id.
- yield sendPing(true, true);
- let ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, TEST_PING_TYPE, true, true);
-
- // Test a field in the environment build section.
- Assert.equal(ping.application.buildId, ping.environment.build.buildId);
- // Test that we have the correct clientId.
- Assert.equal(ping.clientId, gClientID, "The correct clientId must be reported.");
-});
-
-add_task(function* test_archivePings() {
- let now = new Date(2009, 10, 18, 12, 0, 0);
- fakeNow(now);
-
- // Disable ping upload so that pings don't get sent.
- // With unified telemetry the FHR upload pref controls this,
- // with non-unified telemetry the Telemetry enabled pref.
- const isUnified = Preferences.get(PREF_UNIFIED, false);
- const uploadPref = isUnified ? PREF_FHR_UPLOAD_ENABLED : PREF_ENABLED;
- Preferences.set(uploadPref, false);
-
- // If we're using unified telemetry, disabling ping upload will generate a "deletion"
- // ping. Catch it.
- if (isUnified) {
- let ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, DELETION_PING_TYPE, true, false);
- }
-
- // Register a new Ping Handler that asserts if a ping is received, then send a ping.
- PingServer.registerPingHandler(() => Assert.ok(false, "Telemetry must not send pings if not allowed to."));
- let pingId = yield sendPing(true, true);
-
- // Check that the ping was archived, even with upload disabled.
- let ping = yield TelemetryArchive.promiseArchivedPingById(pingId);
- Assert.equal(ping.id, pingId, "TelemetryController should still archive pings.");
-
- // Check that pings don't get archived if not allowed to.
- now = new Date(2010, 10, 18, 12, 0, 0);
- fakeNow(now);
- Preferences.set(PREF_ARCHIVE_ENABLED, false);
- pingId = yield sendPing(true, true);
- let promise = TelemetryArchive.promiseArchivedPingById(pingId);
- Assert.ok((yield promiseRejects(promise)),
- "TelemetryController should not archive pings if the archive pref is disabled.");
-
- // Enable archiving and the upload so that pings get sent and archived again.
- Preferences.set(uploadPref, true);
- Preferences.set(PREF_ARCHIVE_ENABLED, true);
-
- now = new Date(2014, 6, 18, 22, 0, 0);
- fakeNow(now);
- // Restore the non asserting ping handler.
- PingServer.resetPingHandler();
- pingId = yield sendPing(true, true);
-
- // Check that we archive pings when successfully sending them.
- yield PingServer.promiseNextPing();
- ping = yield TelemetryArchive.promiseArchivedPingById(pingId);
- Assert.equal(ping.id, pingId,
- "TelemetryController should still archive pings if ping upload is enabled.");
-});
-
-// Test that we fuzz the submission time around midnight properly
-// to avoid overloading the telemetry servers.
-add_task(function* test_midnightPingSendFuzzing() {
- const fuzzingDelay = 60 * 60 * 1000;
- fakeMidnightPingFuzzingDelay(fuzzingDelay);
- let now = new Date(2030, 5, 1, 11, 0, 0);
- fakeNow(now);
-
- let waitForTimer = () => new Promise(resolve => {
- fakePingSendTimer((callback, timeout) => {
- resolve([callback, timeout]);
- }, () => {});
- });
-
- PingServer.clearRequests();
- yield TelemetryController.testReset();
-
- // A ping after midnight within the fuzzing delay should not get sent.
- now = new Date(2030, 5, 2, 0, 40, 0);
- fakeNow(now);
- PingServer.registerPingHandler((req, res) => {
- Assert.ok(false, "No ping should be received yet.");
- });
- let timerPromise = waitForTimer();
- yield sendPing(true, true);
- let [timerCallback, timerTimeout] = yield timerPromise;
- Assert.ok(!!timerCallback);
- Assert.deepEqual(futureDate(now, timerTimeout), new Date(2030, 5, 2, 1, 0, 0));
-
- // A ping just before the end of the fuzzing delay should not get sent.
- now = new Date(2030, 5, 2, 0, 59, 59);
- fakeNow(now);
- timerPromise = waitForTimer();
- yield sendPing(true, true);
- [timerCallback, timerTimeout] = yield timerPromise;
- Assert.deepEqual(timerTimeout, 1 * 1000);
-
- // Restore the previous ping handler.
- PingServer.resetPingHandler();
-
- // Setting the clock to after the fuzzing delay, we should trigger the two ping sends
- // with the timer callback.
- now = futureDate(now, timerTimeout);
- fakeNow(now);
- yield timerCallback();
- const pings = yield PingServer.promiseNextPings(2);
- for (let ping of pings) {
- checkPingFormat(ping, TEST_PING_TYPE, true, true);
- }
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- // Moving the clock further we should still send pings immediately.
- now = futureDate(now, 5 * 60 * 1000);
- yield sendPing(true, true);
- let ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, TEST_PING_TYPE, true, true);
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- // Check that pings shortly before midnight are immediately sent.
- now = fakeNow(2030, 5, 3, 23, 59, 0);
- yield sendPing(true, true);
- ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, TEST_PING_TYPE, true, true);
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- // Clean-up.
- fakeMidnightPingFuzzingDelay(0);
- fakePingSendTimer(() => {}, () => {});
-});
-
-add_task(function* test_changePingAfterSubmission() {
- // Submit a ping with a custom payload.
- let payload = { canary: "test" };
- let pingPromise = TelemetryController.submitExternalPing(TEST_PING_TYPE, payload, options);
-
- // Change the payload with a predefined value.
- payload.canary = "changed";
-
- // Wait for the ping to be archived.
- const pingId = yield pingPromise;
-
- // Make sure our changes didn't affect the submitted payload.
- let archivedCopy = yield TelemetryArchive.promiseArchivedPingById(pingId);
- Assert.equal(archivedCopy.payload.canary, "test",
- "The payload must not be changed after being submitted.");
-});
-
-add_task(function* test_telemetryEnabledUnexpectedValue() {
- // Remove the default value for toolkit.telemetry.enabled from the default prefs.
- // Otherwise, we wouldn't be able to set the pref to a string.
- let defaultPrefBranch = Services.prefs.getDefaultBranch(null);
- defaultPrefBranch.deleteBranch(PREF_ENABLED);
-
- // Set the preferences controlling the Telemetry status to a string.
- Preferences.set(PREF_ENABLED, "false");
- // Check that Telemetry is not enabled.
- yield TelemetryController.testReset();
- Assert.equal(Telemetry.canRecordExtended, false,
- "Invalid values must not enable Telemetry recording.");
-
- // Delete the pref again.
- defaultPrefBranch.deleteBranch(PREF_ENABLED);
-
- // Make sure that flipping it to true works.
- Preferences.set(PREF_ENABLED, true);
- yield TelemetryController.testReset();
- Assert.equal(Telemetry.canRecordExtended, true,
- "True must enable Telemetry recording.");
-
- // Also check that the false works as well.
- Preferences.set(PREF_ENABLED, false);
- yield TelemetryController.testReset();
- Assert.equal(Telemetry.canRecordExtended, false,
- "False must disable Telemetry recording.");
-});
-
-add_task(function* test_telemetryCleanFHRDatabase() {
- const FHR_DBNAME_PREF = "datareporting.healthreport.dbName";
- const CUSTOM_DB_NAME = "unlikely.to.be.used.sqlite";
- const DEFAULT_DB_NAME = "healthreport.sqlite";
-
- // Check that we're able to remove a FHR DB with a custom name.
- const CUSTOM_DB_PATHS = [
- OS.Path.join(OS.Constants.Path.profileDir, CUSTOM_DB_NAME),
- OS.Path.join(OS.Constants.Path.profileDir, CUSTOM_DB_NAME + "-wal"),
- OS.Path.join(OS.Constants.Path.profileDir, CUSTOM_DB_NAME + "-shm"),
- ];
- Preferences.set(FHR_DBNAME_PREF, CUSTOM_DB_NAME);
-
- // Write fake DB files to the profile directory.
- for (let dbFilePath of CUSTOM_DB_PATHS) {
- yield OS.File.writeAtomic(dbFilePath, "some data");
- }
-
- // Trigger the cleanup and check that the files were removed.
- yield TelemetryStorage.removeFHRDatabase();
- for (let dbFilePath of CUSTOM_DB_PATHS) {
- Assert.ok(!(yield OS.File.exists(dbFilePath)), "The DB must not be on the disk anymore: " + dbFilePath);
- }
-
- // We should not break anything if there's no DB file.
- yield TelemetryStorage.removeFHRDatabase();
-
- // Check that we're able to remove a FHR DB with the default name.
- Preferences.reset(FHR_DBNAME_PREF);
-
- const DEFAULT_DB_PATHS = [
- OS.Path.join(OS.Constants.Path.profileDir, DEFAULT_DB_NAME),
- OS.Path.join(OS.Constants.Path.profileDir, DEFAULT_DB_NAME + "-wal"),
- OS.Path.join(OS.Constants.Path.profileDir, DEFAULT_DB_NAME + "-shm"),
- ];
-
- // Write fake DB files to the profile directory.
- for (let dbFilePath of DEFAULT_DB_PATHS) {
- yield OS.File.writeAtomic(dbFilePath, "some data");
- }
-
- // Trigger the cleanup and check that the files were removed.
- yield TelemetryStorage.removeFHRDatabase();
- for (let dbFilePath of DEFAULT_DB_PATHS) {
- Assert.ok(!(yield OS.File.exists(dbFilePath)), "The DB must not be on the disk anymore: " + dbFilePath);
- }
-});
-
-add_task(function* stopServer() {
- yield PingServer.stop();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryControllerBuildID.js b/toolkit/components/telemetry/tests/unit/test_TelemetryControllerBuildID.js
deleted file mode 100644
index b8a88afa2..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryControllerBuildID.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-/* Test inclusion of previous build ID in telemetry pings when build ID changes.
- * bug 841028
- *
- * Cases to cover:
- * 1) Run with no "previousBuildID" stored in prefs:
- * -> no previousBuildID in telemetry system info, new value set in prefs.
- * 2) previousBuildID in prefs, equal to current build ID:
- * -> no previousBuildID in telemetry, prefs not updated.
- * 3) previousBuildID in prefs, not equal to current build ID:
- * -> previousBuildID in telemetry, new value set in prefs.
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-// Force the Telemetry enabled preference so that TelemetrySession.testReset() doesn't exit early.
-Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
-
-// Set up our dummy AppInfo object so we can control the appBuildID.
-Cu.import("resource://testing-common/AppInfo.jsm", this);
-updateAppInfo();
-
-// Check that when run with no previous build ID stored, we update the pref but do not
-// put anything into the metadata.
-add_task(function* test_firstRun() {
- yield TelemetryController.testReset();
- let metadata = TelemetrySession.getMetadata();
- do_check_false("previousBuildID" in metadata);
- let appBuildID = getAppInfo().appBuildID;
- let buildIDPref = Services.prefs.getCharPref(TelemetrySession.Constants.PREF_PREVIOUS_BUILDID);
- do_check_eq(appBuildID, buildIDPref);
-});
-
-// Check that a subsequent run with the same build ID does not put prev build ID in
-// metadata. Assumes testFirstRun() has already been called to set the previousBuildID pref.
-add_task(function* test_secondRun() {
- yield TelemetryController.testReset();
- let metadata = TelemetrySession.getMetadata();
- do_check_false("previousBuildID" in metadata);
-});
-
-// Set up telemetry with a different app build ID and check that the old build ID
-// is returned in the metadata and the pref is updated to the new build ID.
-// Assumes testFirstRun() has been called to set the previousBuildID pref.
-const NEW_BUILD_ID = "20130314";
-add_task(function* test_newBuild() {
- let info = getAppInfo();
- let oldBuildID = info.appBuildID;
- info.appBuildID = NEW_BUILD_ID;
- yield TelemetryController.testReset();
- let metadata = TelemetrySession.getMetadata();
- do_check_eq(metadata.previousBuildId, oldBuildID);
- let buildIDPref = Services.prefs.getCharPref(TelemetrySession.Constants.PREF_PREVIOUS_BUILDID);
- do_check_eq(NEW_BUILD_ID, buildIDPref);
-});
-
-
-function run_test() {
- // Make sure we have a profile directory.
- do_get_profile();
-
- run_next_test();
-}
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryControllerShutdown.js b/toolkit/components/telemetry/tests/unit/test_TelemetryControllerShutdown.js
deleted file mode 100644
index 391db0d9d..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryControllerShutdown.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test that TelemetryController sends close to shutdown don't lead
-// to AsyncShutdown timeouts.
-
-"use strict";
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySend.jsm", this);
-Cu.import("resource://gre/modules/Timer.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/AsyncShutdown.jsm", this);
-Cu.import("resource://testing-common/httpd.js", this);
-
-const PREF_BRANCH = "toolkit.telemetry.";
-const PREF_FHR_UPLOAD_ENABLED = "datareporting.healthreport.uploadEnabled";
-
-function contentHandler(metadata, response)
-{
- dump("contentHandler called for path: " + metadata._path + "\n");
- // We intentionally don't finish writing the response here to let the
- // client time out.
- response.processAsync();
- response.setHeader("Content-Type", "text/plain");
-}
-
-add_task(function* test_setup() {
- // Addon manager needs a profile directory
- do_get_profile();
- loadAddonManager("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9.2");
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
- Services.prefs.setBoolPref(PREF_FHR_UPLOAD_ENABLED, true);
-});
-
-/**
- * Ensures that TelemetryController does not hang processing shutdown
- * phases. Assumes that Telemetry shutdown routines do not take longer than
- * CRASH_TIMEOUT_MS to complete.
- */
-add_task(function* test_sendTelemetryShutsDownWithinReasonableTimeout() {
- const CRASH_TIMEOUT_MS = 5 * 1000;
- // Enable testing mode for AsyncShutdown, otherwise some testing-only functionality
- // is not available.
- Services.prefs.setBoolPref("toolkit.asyncshutdown.testing", true);
- // Reducing the max delay for waitiing on phases to complete from 1 minute
- // (standard) to 10 seconds to avoid blocking the tests in case of misbehavior.
- Services.prefs.setIntPref("toolkit.asyncshutdown.crash_timeout", CRASH_TIMEOUT_MS);
-
- let httpServer = new HttpServer();
- httpServer.registerPrefixHandler("/", contentHandler);
- httpServer.start(-1);
-
- yield TelemetryController.testSetup();
- TelemetrySend.setServer("http://localhost:" + httpServer.identity.primaryPort);
- let submissionPromise = TelemetryController.submitExternalPing("test-ping-type", {});
-
- // Trigger the AsyncShutdown phase TelemetryController hangs off.
- AsyncShutdown.profileBeforeChange._trigger();
- AsyncShutdown.sendTelemetry._trigger();
- // Now wait for the ping submission.
- yield submissionPromise;
-
- // If we get here, we didn't time out in the shutdown routines.
- Assert.ok(true, "Didn't time out on shutdown.");
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryController_idle.js b/toolkit/components/telemetry/tests/unit/test_TelemetryController_idle.js
deleted file mode 100644
index ca5d1820b..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryController_idle.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Check that TelemetrySession notifies correctly on idle-daily.
-
-Cu.import("resource://testing-common/httpd.js", this);
-Cu.import("resource://gre/modules/PromiseUtils.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/TelemetryStorage.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySend.jsm", this);
-
-const PREF_FHR_UPLOAD_ENABLED = "datareporting.healthreport.uploadEnabled";
-
-var gHttpServer = null;
-
-add_task(function* test_setup() {
- do_get_profile();
-
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
- Services.prefs.setBoolPref(PREF_FHR_UPLOAD_ENABLED, true);
-
- // Start the webserver to check if the pending ping correctly arrives.
- gHttpServer = new HttpServer();
- gHttpServer.start(-1);
-});
-
-add_task(function* testSendPendingOnIdleDaily() {
- // Create a valid pending ping.
- const PENDING_PING = {
- id: "2133234d-4ea1-44f4-909e-ce8c6c41e0fc",
- type: "test-ping",
- version: 4,
- application: {},
- payload: {},
- };
- yield TelemetryStorage.savePing(PENDING_PING, true);
-
- // Telemetry will not send this ping at startup, because it's not overdue.
- yield TelemetryController.testSetup();
- TelemetrySend.setServer("http://localhost:" + gHttpServer.identity.primaryPort);
-
- let pendingPromise = new Promise(resolve =>
- gHttpServer.registerPrefixHandler("/submit/telemetry/", request => resolve(request)));
-
- let gatherPromise = PromiseUtils.defer();
- Services.obs.addObserver(gatherPromise.resolve, "gather-telemetry", false);
-
- // Check that we are correctly receiving the gather-telemetry notification.
- TelemetrySession.observe(null, "idle-daily", null);
- yield gatherPromise;
- Assert.ok(true, "Received gather-telemetry notification.");
-
- Services.obs.removeObserver(gatherPromise.resolve, "gather-telemetry");
-
- // Check that the pending ping is correctly received.
- let ns = {};
- let module = Cu.import("resource://gre/modules/TelemetrySend.jsm", ns);
- module.TelemetrySendImpl.observe(null, "idle-daily", null);
- let request = yield pendingPromise;
- let ping = decodeRequestPayload(request);
-
- // Validate the ping data.
- Assert.equal(ping.id, PENDING_PING.id);
- Assert.equal(ping.type, PENDING_PING.type);
-
- yield new Promise(resolve => gHttpServer.stop(resolve));
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js b/toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js
deleted file mode 100644
index 2518a80ba..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js
+++ /dev/null
@@ -1,1522 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Cu.import("resource://gre/modules/AddonManager.jsm");
-Cu.import("resource://gre/modules/TelemetryEnvironment.jsm", this);
-Cu.import("resource://gre/modules/Preferences.jsm", this);
-Cu.import("resource://gre/modules/PromiseUtils.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://testing-common/AddonManagerTesting.jsm");
-Cu.import("resource://testing-common/httpd.js");
-Cu.import("resource://testing-common/MockRegistrar.jsm", this);
-Cu.import("resource://gre/modules/FileUtils.jsm");
-
-// AttributionCode is only needed for Firefox
-XPCOMUtils.defineLazyModuleGetter(this, "AttributionCode",
- "resource:///modules/AttributionCode.jsm");
-
-// Lazy load |LightweightThemeManager|, we won't be using it on Gonk.
-XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeManager",
- "resource://gre/modules/LightweightThemeManager.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "ProfileAge",
- "resource://gre/modules/ProfileAge.jsm");
-
-// The webserver hosting the addons.
-var gHttpServer = null;
-// The URL of the webserver root.
-var gHttpRoot = null;
-// The URL of the data directory, on the webserver.
-var gDataRoot = null;
-
-const PLATFORM_VERSION = "1.9.2";
-const APP_VERSION = "1";
-const APP_ID = "xpcshell@tests.mozilla.org";
-const APP_NAME = "XPCShell";
-
-const DISTRIBUTION_ID = "distributor-id";
-const DISTRIBUTION_VERSION = "4.5.6b";
-const DISTRIBUTOR_NAME = "Some Distributor";
-const DISTRIBUTOR_CHANNEL = "A Channel";
-const PARTNER_NAME = "test";
-const PARTNER_ID = "NicePartner-ID-3785";
-const DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC = "distribution-customization-complete";
-
-const GFX_VENDOR_ID = "0xabcd";
-const GFX_DEVICE_ID = "0x1234";
-
-// The profile reset date, in milliseconds (Today)
-const PROFILE_RESET_DATE_MS = Date.now();
-// The profile creation date, in milliseconds (Yesterday).
-const PROFILE_CREATION_DATE_MS = PROFILE_RESET_DATE_MS - MILLISECONDS_PER_DAY;
-
-const FLASH_PLUGIN_NAME = "Shockwave Flash";
-const FLASH_PLUGIN_DESC = "A mock flash plugin";
-const FLASH_PLUGIN_VERSION = "\u201c1.1.1.1\u201d";
-const PLUGIN_MIME_TYPE1 = "application/x-shockwave-flash";
-const PLUGIN_MIME_TYPE2 = "text/plain";
-
-const PLUGIN2_NAME = "Quicktime";
-const PLUGIN2_DESC = "A mock Quicktime plugin";
-const PLUGIN2_VERSION = "2.3";
-
-const PERSONA_ID = "3785";
-// Defined by LightweightThemeManager, it is appended to the PERSONA_ID.
-const PERSONA_ID_SUFFIX = "@personas.mozilla.org";
-const PERSONA_NAME = "Test Theme";
-const PERSONA_DESCRIPTION = "A nice theme/persona description.";
-
-const PLUGIN_UPDATED_TOPIC = "plugins-list-updated";
-
-// system add-ons are enabled at startup, so record date when the test starts
-const SYSTEM_ADDON_INSTALL_DATE = Date.now();
-
-// Valid attribution code to write so that settings.attribution can be tested.
-const ATTRIBUTION_CODE = "source%3Dgoogle.com";
-
-/**
- * Used to mock plugin tags in our fake plugin host.
- */
-function PluginTag(aName, aDescription, aVersion, aEnabled) {
- this.name = aName;
- this.description = aDescription;
- this.version = aVersion;
- this.disabled = !aEnabled;
-}
-
-PluginTag.prototype = {
- name: null,
- description: null,
- version: null,
- filename: null,
- fullpath: null,
- disabled: false,
- blocklisted: false,
- clicktoplay: true,
-
- mimeTypes: [ PLUGIN_MIME_TYPE1, PLUGIN_MIME_TYPE2 ],
-
- getMimeTypes: function(count) {
- count.value = this.mimeTypes.length;
- return this.mimeTypes;
- }
-};
-
-// A container for the plugins handled by the fake plugin host.
-var gInstalledPlugins = [
- new PluginTag("Java", "A mock Java plugin", "1.0", false /* Disabled */),
- new PluginTag(FLASH_PLUGIN_NAME, FLASH_PLUGIN_DESC, FLASH_PLUGIN_VERSION, true),
-];
-
-// A fake plugin host for testing plugin telemetry environment.
-var PluginHost = {
- getPluginTags: function(countRef) {
- countRef.value = gInstalledPlugins.length;
- return gInstalledPlugins;
- },
-
- QueryInterface: function(iid) {
- if (iid.equals(Ci.nsIPluginHost)
- || iid.equals(Ci.nsISupports))
- return this;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
- }
-}
-
-function registerFakePluginHost() {
- MockRegistrar.register("@mozilla.org/plugin/host;1", PluginHost);
-}
-
-var SysInfo = {
- overrides: {},
-
- getProperty(name) {
- // Assert.ok(false, "Mock SysInfo: " + name + ", " + JSON.stringify(this.overrides));
- if (name in this.overrides) {
- return this.overrides[name];
- }
- try {
- return this._genuine.getProperty(name);
- } catch (ex) {
- throw ex;
- }
- },
-
- get(name) {
- return this._genuine.get(name);
- },
-
- QueryInterface(iid) {
- if (iid.equals(Ci.nsIPropertyBag2)
- || iid.equals(Ci.nsISupports))
- return this;
-
- throw Cr.NS_ERROR_NO_INTERFACE;
- }
-};
-
-function registerFakeSysInfo() {
- MockRegistrar.register("@mozilla.org/system-info;1", SysInfo);
-}
-
-function MockAddonWrapper(aAddon) {
- this.addon = aAddon;
-}
-MockAddonWrapper.prototype = {
- get id() {
- return this.addon.id;
- },
-
- get type() {
- return "service";
- },
-
- get appDisabled() {
- return false;
- },
-
- get isCompatible() {
- return true;
- },
-
- get isPlatformCompatible() {
- return true;
- },
-
- get scope() {
- return AddonManager.SCOPE_PROFILE;
- },
-
- get foreignInstall() {
- return false;
- },
-
- get providesUpdatesSecurely() {
- return true;
- },
-
- get blocklistState() {
- return 0; // Not blocked.
- },
-
- get pendingOperations() {
- return AddonManager.PENDING_NONE;
- },
-
- get permissions() {
- return AddonManager.PERM_CAN_UNINSTALL | AddonManager.PERM_CAN_DISABLE;
- },
-
- get isActive() {
- return true;
- },
-
- get name() {
- return this.addon.name;
- },
-
- get version() {
- return this.addon.version;
- },
-
- get creator() {
- return new AddonManagerPrivate.AddonAuthor(this.addon.author);
- },
-
- get userDisabled() {
- return this.appDisabled;
- },
-};
-
-function createMockAddonProvider(aName) {
- let mockProvider = {
- _addons: [],
-
- get name() {
- return aName;
- },
-
- addAddon: function(aAddon) {
- this._addons.push(aAddon);
- AddonManagerPrivate.callAddonListeners("onInstalled", new MockAddonWrapper(aAddon));
- },
-
- getAddonsByTypes: function (aTypes, aCallback) {
- aCallback(this._addons.map(a => new MockAddonWrapper(a)));
- },
-
- shutdown() {
- return Promise.resolve();
- },
- };
-
- return mockProvider;
-}
-
-/**
- * Used to spoof the Persona Id.
- */
-function spoofTheme(aId, aName, aDesc) {
- return {
- id: aId,
- name: aName,
- description: aDesc,
- headerURL: "http://lwttest.invalid/a.png",
- footerURL: "http://lwttest.invalid/b.png",
- textcolor: Math.random().toString(),
- accentcolor: Math.random().toString()
- };
-}
-
-function spoofGfxAdapter() {
- try {
- let gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfoDebug);
- gfxInfo.spoofVendorID(GFX_VENDOR_ID);
- gfxInfo.spoofDeviceID(GFX_DEVICE_ID);
- } catch (x) {
- // If we can't test gfxInfo, that's fine, we'll note it later.
- }
-}
-
-function spoofProfileReset() {
- let profileAccessor = new ProfileAge();
-
- return profileAccessor.writeTimes({
- created: PROFILE_CREATION_DATE_MS,
- reset: PROFILE_RESET_DATE_MS
- });
-}
-
-function spoofPartnerInfo() {
- let prefsToSpoof = {};
- prefsToSpoof["distribution.id"] = DISTRIBUTION_ID;
- prefsToSpoof["distribution.version"] = DISTRIBUTION_VERSION;
- prefsToSpoof["app.distributor"] = DISTRIBUTOR_NAME;
- prefsToSpoof["app.distributor.channel"] = DISTRIBUTOR_CHANNEL;
- prefsToSpoof["app.partner.test"] = PARTNER_NAME;
- prefsToSpoof["mozilla.partner.id"] = PARTNER_ID;
-
- // Spoof the preferences.
- for (let pref in prefsToSpoof) {
- Preferences.set(pref, prefsToSpoof[pref]);
- }
-}
-
-function getAttributionFile() {
- let file = Services.dirsvc.get("LocalAppData", Ci.nsIFile);
- file.append("mozilla");
- file.append(AppConstants.MOZ_APP_NAME);
- file.append("postSigningData");
- return file;
-}
-
-function spoofAttributionData() {
- if (gIsWindows) {
- AttributionCode._clearCache();
- let stream = Cc["@mozilla.org/network/file-output-stream;1"].
- createInstance(Ci.nsIFileOutputStream);
- stream.init(getAttributionFile(), -1, -1, 0);
- stream.write(ATTRIBUTION_CODE, ATTRIBUTION_CODE.length);
- }
-}
-
-function cleanupAttributionData() {
- if (gIsWindows) {
- getAttributionFile().remove(false);
- AttributionCode._clearCache();
- }
-}
-
-/**
- * Check that a value is a string and not empty.
- *
- * @param aValue The variable to check.
- * @return True if |aValue| has type "string" and is not empty, False otherwise.
- */
-function checkString(aValue) {
- return (typeof aValue == "string") && (aValue != "");
-}
-
-/**
- * If value is non-null, check if it's a valid string.
- *
- * @param aValue The variable to check.
- * @return True if it's null or a valid string, false if it's non-null and an invalid
- * string.
- */
-function checkNullOrString(aValue) {
- if (aValue) {
- return checkString(aValue);
- } else if (aValue === null) {
- return true;
- }
-
- return false;
-}
-
-/**
- * If value is non-null, check if it's a boolean.
- *
- * @param aValue The variable to check.
- * @return True if it's null or a valid boolean, false if it's non-null and an invalid
- * boolean.
- */
-function checkNullOrBool(aValue) {
- return aValue === null || (typeof aValue == "boolean");
-}
-
-function checkBuildSection(data) {
- const expectedInfo = {
- applicationId: APP_ID,
- applicationName: APP_NAME,
- buildId: gAppInfo.appBuildID,
- version: APP_VERSION,
- vendor: "Mozilla",
- platformVersion: PLATFORM_VERSION,
- xpcomAbi: "noarch-spidermonkey",
- };
-
- Assert.ok("build" in data, "There must be a build section in Environment.");
-
- for (let f in expectedInfo) {
- Assert.ok(checkString(data.build[f]), f + " must be a valid string.");
- Assert.equal(data.build[f], expectedInfo[f], f + " must have the correct value.");
- }
-
- // Make sure architecture is in the environment.
- Assert.ok(checkString(data.build.architecture));
-
- if (gIsMac) {
- let macUtils = Cc["@mozilla.org/xpcom/mac-utils;1"].getService(Ci.nsIMacUtils);
- if (macUtils && macUtils.isUniversalBinary) {
- Assert.ok(checkString(data.build.architecturesInBinary));
- }
- }
-}
-
-function checkSettingsSection(data) {
- const EXPECTED_FIELDS_TYPES = {
- blocklistEnabled: "boolean",
- e10sEnabled: "boolean",
- e10sCohort: "string",
- telemetryEnabled: "boolean",
- locale: "string",
- update: "object",
- userPrefs: "object",
- };
-
- Assert.ok("settings" in data, "There must be a settings section in Environment.");
-
- for (let f in EXPECTED_FIELDS_TYPES) {
- Assert.equal(typeof data.settings[f], EXPECTED_FIELDS_TYPES[f],
- f + " must have the correct type.");
- }
-
- // Check "addonCompatibilityCheckEnabled" separately, as it is not available
- // on Gonk.
- if (gIsGonk) {
- Assert.ok(!("addonCompatibilityCheckEnabled" in data.settings), "Must not be available on Gonk.");
- } else {
- Assert.equal(data.settings.addonCompatibilityCheckEnabled, AddonManager.checkCompatibility);
- }
-
- // Check "isDefaultBrowser" separately, as it is not available on Android an can either be
- // null or boolean on other platforms.
- if (gIsAndroid) {
- Assert.ok(!("isDefaultBrowser" in data.settings), "Must not be available on Android.");
- } else {
- Assert.ok(checkNullOrBool(data.settings.isDefaultBrowser));
- }
-
- // Check "channel" separately, as it can either be null or string.
- let update = data.settings.update;
- Assert.ok(checkNullOrString(update.channel));
- Assert.equal(typeof update.enabled, "boolean");
- Assert.equal(typeof update.autoDownload, "boolean");
-
- // Check "defaultSearchEngine" separately, as it can either be undefined or string.
- if ("defaultSearchEngine" in data.settings) {
- checkString(data.settings.defaultSearchEngine);
- Assert.equal(typeof data.settings.defaultSearchEngineData, "object");
- }
-
- if ("attribution" in data.settings) {
- Assert.equal(typeof data.settings.attribution, "object");
- Assert.equal(data.settings.attribution.source, "google.com");
- }
-}
-
-function checkProfileSection(data) {
- Assert.ok("profile" in data, "There must be a profile section in Environment.");
- Assert.equal(data.profile.creationDate, truncateToDays(PROFILE_CREATION_DATE_MS));
- Assert.equal(data.profile.resetDate, truncateToDays(PROFILE_RESET_DATE_MS));
-}
-
-function checkPartnerSection(data, isInitial) {
- const EXPECTED_FIELDS = {
- distributionId: DISTRIBUTION_ID,
- distributionVersion: DISTRIBUTION_VERSION,
- partnerId: PARTNER_ID,
- distributor: DISTRIBUTOR_NAME,
- distributorChannel: DISTRIBUTOR_CHANNEL,
- };
-
- Assert.ok("partner" in data, "There must be a partner section in Environment.");
-
- for (let f in EXPECTED_FIELDS) {
- let expected = isInitial ? null : EXPECTED_FIELDS[f];
- Assert.strictEqual(data.partner[f], expected, f + " must have the correct value.");
- }
-
- // Check that "partnerNames" exists and contains the correct element.
- Assert.ok(Array.isArray(data.partner.partnerNames));
- if (isInitial) {
- Assert.equal(data.partner.partnerNames.length, 0);
- } else {
- Assert.ok(data.partner.partnerNames.includes(PARTNER_NAME));
- }
-}
-
-function checkGfxAdapter(data) {
- const EXPECTED_ADAPTER_FIELDS_TYPES = {
- description: "string",
- vendorID: "string",
- deviceID: "string",
- subsysID: "string",
- RAM: "number",
- driver: "string",
- driverVersion: "string",
- driverDate: "string",
- GPUActive: "boolean",
- };
-
- for (let f in EXPECTED_ADAPTER_FIELDS_TYPES) {
- Assert.ok(f in data, f + " must be available.");
-
- if (data[f]) {
- // Since we have a non-null value, check if it has the correct type.
- Assert.equal(typeof data[f], EXPECTED_ADAPTER_FIELDS_TYPES[f],
- f + " must have the correct type.");
- }
- }
-}
-
-function checkSystemSection(data) {
- const EXPECTED_FIELDS = [ "memoryMB", "cpu", "os", "hdd", "gfx" ];
- const EXPECTED_HDD_FIELDS = [ "profile", "binary", "system" ];
-
- Assert.ok("system" in data, "There must be a system section in Environment.");
-
- // Make sure we have all the top level sections and fields.
- for (let f of EXPECTED_FIELDS) {
- Assert.ok(f in data.system, f + " must be available.");
- }
-
- Assert.ok(Number.isFinite(data.system.memoryMB), "MemoryMB must be a number.");
-
- if (gIsWindows || gIsMac || gIsLinux) {
- let EXTRA_CPU_FIELDS = ["cores", "model", "family", "stepping",
- "l2cacheKB", "l3cacheKB", "speedMHz", "vendor"];
-
- for (let f of EXTRA_CPU_FIELDS) {
- // Note this is testing TelemetryEnvironment.js only, not that the
- // values are valid - null is the fallback.
- Assert.ok(f in data.system.cpu, f + " must be available under cpu.");
- }
-
- if (gIsWindows) {
- Assert.equal(typeof data.system.isWow64, "boolean",
- "isWow64 must be available on Windows and have the correct type.");
- Assert.ok("virtualMaxMB" in data.system, "virtualMaxMB must be available.");
- Assert.ok(Number.isFinite(data.system.virtualMaxMB),
- "virtualMaxMB must be a number.");
- }
-
- // We insist these are available
- for (let f of ["cores"]) {
- Assert.ok(!(f in data.system.cpu) ||
- Number.isFinite(data.system.cpu[f]),
- f + " must be a number if non null.");
- }
-
- // These should be numbers if they are not null
- for (let f of ["model", "family", "stepping", "l2cacheKB",
- "l3cacheKB", "speedMHz"]) {
- Assert.ok(!(f in data.system.cpu) ||
- data.system.cpu[f] === null ||
- Number.isFinite(data.system.cpu[f]),
- f + " must be a number if non null.");
- }
- }
-
- let cpuData = data.system.cpu;
- Assert.ok(Number.isFinite(cpuData.count), "CPU count must be a number.");
- Assert.ok(Array.isArray(cpuData.extensions), "CPU extensions must be available.");
-
- // Device data is only available on Android or Gonk.
- if (gIsAndroid || gIsGonk) {
- let deviceData = data.system.device;
- Assert.ok(checkNullOrString(deviceData.model));
- Assert.ok(checkNullOrString(deviceData.manufacturer));
- Assert.ok(checkNullOrString(deviceData.hardware));
- Assert.ok(checkNullOrBool(deviceData.isTablet));
- }
-
- let osData = data.system.os;
- Assert.ok(checkNullOrString(osData.name));
- Assert.ok(checkNullOrString(osData.version));
- Assert.ok(checkNullOrString(osData.locale));
-
- // Service pack is only available on Windows.
- if (gIsWindows) {
- Assert.ok(Number.isFinite(osData["servicePackMajor"]),
- "ServicePackMajor must be a number.");
- Assert.ok(Number.isFinite(osData["servicePackMinor"]),
- "ServicePackMinor must be a number.");
- if ("windowsBuildNumber" in osData) {
- // This might not be available on all Windows platforms.
- Assert.ok(Number.isFinite(osData["windowsBuildNumber"]),
- "windowsBuildNumber must be a number.");
- }
- if ("windowsUBR" in osData) {
- // This might not be available on all Windows platforms.
- Assert.ok((osData["windowsUBR"] === null) || Number.isFinite(osData["windowsUBR"]),
- "windowsUBR must be null or a number.");
- }
- } else if (gIsAndroid || gIsGonk) {
- Assert.ok(checkNullOrString(osData.kernelVersion));
- }
-
- let check = gIsWindows ? checkString : checkNullOrString;
- for (let disk of EXPECTED_HDD_FIELDS) {
- Assert.ok(check(data.system.hdd[disk].model));
- Assert.ok(check(data.system.hdd[disk].revision));
- }
-
- let gfxData = data.system.gfx;
- Assert.ok("D2DEnabled" in gfxData);
- Assert.ok("DWriteEnabled" in gfxData);
- // DWriteVersion is disabled due to main thread jank and will be enabled
- // again as part of bug 1154500.
- // Assert.ok("DWriteVersion" in gfxData);
- if (gIsWindows) {
- Assert.equal(typeof gfxData.D2DEnabled, "boolean");
- Assert.equal(typeof gfxData.DWriteEnabled, "boolean");
- // As above, will be enabled again as part of bug 1154500.
- // Assert.ok(checkString(gfxData.DWriteVersion));
- }
-
- Assert.ok("adapters" in gfxData);
- Assert.ok(gfxData.adapters.length > 0, "There must be at least one GFX adapter.");
- for (let adapter of gfxData.adapters) {
- checkGfxAdapter(adapter);
- }
- Assert.equal(typeof gfxData.adapters[0].GPUActive, "boolean");
- Assert.ok(gfxData.adapters[0].GPUActive, "The first GFX adapter must be active.");
-
- Assert.ok(Array.isArray(gfxData.monitors));
- if (gIsWindows || gIsMac) {
- Assert.ok(gfxData.monitors.length >= 1, "There is at least one monitor.");
- Assert.equal(typeof gfxData.monitors[0].screenWidth, "number");
- Assert.equal(typeof gfxData.monitors[0].screenHeight, "number");
- if (gIsWindows) {
- Assert.equal(typeof gfxData.monitors[0].refreshRate, "number");
- Assert.equal(typeof gfxData.monitors[0].pseudoDisplay, "boolean");
- }
- if (gIsMac) {
- Assert.equal(typeof gfxData.monitors[0].scale, "number");
- }
- }
-
- Assert.equal(typeof gfxData.features, "object");
- Assert.equal(typeof gfxData.features.compositor, "string");
-
- try {
- // If we've not got nsIGfxInfoDebug, then this will throw and stop us doing
- // this test.
- let gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfoDebug);
-
- if (gIsWindows || gIsMac) {
- Assert.equal(GFX_VENDOR_ID, gfxData.adapters[0].vendorID);
- Assert.equal(GFX_DEVICE_ID, gfxData.adapters[0].deviceID);
- }
-
- let features = gfxInfo.getFeatures();
- Assert.equal(features.compositor, gfxData.features.compositor);
- Assert.equal(features.opengl, gfxData.features.opengl);
- Assert.equal(features.webgl, gfxData.features.webgl);
- }
- catch (e) {}
-}
-
-function checkActiveAddon(data) {
- let signedState = mozinfo.addon_signing ? "number" : "undefined";
- // system add-ons have an undefined signState
- if (data.isSystem)
- signedState = "undefined";
-
- const EXPECTED_ADDON_FIELDS_TYPES = {
- blocklisted: "boolean",
- name: "string",
- userDisabled: "boolean",
- appDisabled: "boolean",
- version: "string",
- scope: "number",
- type: "string",
- foreignInstall: "boolean",
- hasBinaryComponents: "boolean",
- installDay: "number",
- updateDay: "number",
- signedState: signedState,
- isSystem: "boolean",
- };
-
- for (let f in EXPECTED_ADDON_FIELDS_TYPES) {
- Assert.ok(f in data, f + " must be available.");
- Assert.equal(typeof data[f], EXPECTED_ADDON_FIELDS_TYPES[f],
- f + " must have the correct type.");
- }
-
- // We check "description" separately, as it can be null.
- Assert.ok(checkNullOrString(data.description));
-}
-
-function checkPlugin(data) {
- const EXPECTED_PLUGIN_FIELDS_TYPES = {
- name: "string",
- version: "string",
- description: "string",
- blocklisted: "boolean",
- disabled: "boolean",
- clicktoplay: "boolean",
- updateDay: "number",
- };
-
- for (let f in EXPECTED_PLUGIN_FIELDS_TYPES) {
- Assert.ok(f in data, f + " must be available.");
- Assert.equal(typeof data[f], EXPECTED_PLUGIN_FIELDS_TYPES[f],
- f + " must have the correct type.");
- }
-
- Assert.ok(Array.isArray(data.mimeTypes));
- for (let type of data.mimeTypes) {
- Assert.ok(checkString(type));
- }
-}
-
-function checkTheme(data) {
- // "hasBinaryComponents" is not available when testing.
- const EXPECTED_THEME_FIELDS_TYPES = {
- id: "string",
- blocklisted: "boolean",
- name: "string",
- userDisabled: "boolean",
- appDisabled: "boolean",
- version: "string",
- scope: "number",
- foreignInstall: "boolean",
- installDay: "number",
- updateDay: "number",
- };
-
- for (let f in EXPECTED_THEME_FIELDS_TYPES) {
- Assert.ok(f in data, f + " must be available.");
- Assert.equal(typeof data[f], EXPECTED_THEME_FIELDS_TYPES[f],
- f + " must have the correct type.");
- }
-
- // We check "description" separately, as it can be null.
- Assert.ok(checkNullOrString(data.description));
-}
-
-function checkActiveGMPlugin(data) {
- // GMP plugin version defaults to null until GMPDownloader runs to update it.
- if (data.version) {
- Assert.equal(typeof data.version, "string");
- }
- Assert.equal(typeof data.userDisabled, "boolean");
- Assert.equal(typeof data.applyBackgroundUpdates, "number");
-}
-
-function checkAddonsSection(data, expectBrokenAddons) {
- const EXPECTED_FIELDS = [
- "activeAddons", "theme", "activePlugins", "activeGMPlugins", "activeExperiment",
- "persona",
- ];
-
- Assert.ok("addons" in data, "There must be an addons section in Environment.");
- for (let f of EXPECTED_FIELDS) {
- Assert.ok(f in data.addons, f + " must be available.");
- }
-
- // Check the active addons, if available.
- if (!expectBrokenAddons) {
- let activeAddons = data.addons.activeAddons;
- for (let addon in activeAddons) {
- checkActiveAddon(activeAddons[addon]);
- }
- }
-
- // Check "theme" structure.
- if (Object.keys(data.addons.theme).length !== 0) {
- checkTheme(data.addons.theme);
- }
-
- // Check the active plugins.
- Assert.ok(Array.isArray(data.addons.activePlugins));
- for (let plugin of data.addons.activePlugins) {
- checkPlugin(plugin);
- }
-
- // Check active GMPlugins
- let activeGMPlugins = data.addons.activeGMPlugins;
- for (let gmPlugin in activeGMPlugins) {
- checkActiveGMPlugin(activeGMPlugins[gmPlugin]);
- }
-
- // Check the active Experiment
- let experiment = data.addons.activeExperiment;
- if (Object.keys(experiment).length !== 0) {
- Assert.ok(checkString(experiment.id));
- Assert.ok(checkString(experiment.branch));
- }
-
- // Check persona
- Assert.ok(checkNullOrString(data.addons.persona));
-}
-
-function checkEnvironmentData(data, isInitial = false, expectBrokenAddons = false) {
- checkBuildSection(data);
- checkSettingsSection(data);
- checkProfileSection(data);
- checkPartnerSection(data, isInitial);
- checkSystemSection(data);
- checkAddonsSection(data, expectBrokenAddons);
-}
-
-add_task(function* setup() {
- // Load a custom manifest to provide search engine loading from JAR files.
- do_load_manifest("chrome.manifest");
- registerFakeSysInfo();
- spoofGfxAdapter();
- do_get_profile();
-
- // The system add-on must be installed before AddonManager is started.
- const distroDir = FileUtils.getDir("ProfD", ["sysfeatures", "app0"], true);
- do_get_file("system.xpi").copyTo(distroDir, "tel-system-xpi@tests.mozilla.org.xpi");
- let system_addon = FileUtils.File(distroDir.path);
- system_addon.append("tel-system-xpi@tests.mozilla.org.xpi");
- system_addon.lastModifiedTime = SYSTEM_ADDON_INSTALL_DATE;
- loadAddonManager(APP_ID, APP_NAME, APP_VERSION, PLATFORM_VERSION);
-
- // Spoof the persona ID, but not on Gonk.
- if (!gIsGonk) {
- LightweightThemeManager.currentTheme =
- spoofTheme(PERSONA_ID, PERSONA_NAME, PERSONA_DESCRIPTION);
- }
- // Register a fake plugin host for consistent flash version data.
- registerFakePluginHost();
-
- // Setup a webserver to serve Addons, Plugins, etc.
- gHttpServer = new HttpServer();
- gHttpServer.start(-1);
- let port = gHttpServer.identity.primaryPort;
- gHttpRoot = "http://localhost:" + port + "/";
- gDataRoot = gHttpRoot + "data/";
- gHttpServer.registerDirectory("/data/", do_get_cwd());
- do_register_cleanup(() => gHttpServer.stop(() => {}));
-
- // Create the attribution data file, so that settings.attribution will exist.
- // The attribution functionality only exists in Firefox.
- if (AppConstants.MOZ_BUILD_APP == "browser") {
- spoofAttributionData();
- do_register_cleanup(cleanupAttributionData);
- }
-
- yield spoofProfileReset();
- TelemetryEnvironment.delayedInit();
-});
-
-add_task(function* test_checkEnvironment() {
- let environmentData = yield TelemetryEnvironment.onInitialized();
- checkEnvironmentData(environmentData, true);
-
- spoofPartnerInfo();
- Services.obs.notifyObservers(null, DISTRIBUTION_CUSTOMIZATION_COMPLETE_TOPIC, null);
-
- environmentData = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(environmentData);
-});
-
-add_task(function* test_prefWatchPolicies() {
- const PREF_TEST_1 = "toolkit.telemetry.test.pref_new";
- const PREF_TEST_2 = "toolkit.telemetry.test.pref1";
- const PREF_TEST_3 = "toolkit.telemetry.test.pref2";
- const PREF_TEST_4 = "toolkit.telemetry.test.pref_old";
- const PREF_TEST_5 = "toolkit.telemetry.test.requiresRestart";
-
- const expectedValue = "some-test-value";
- const unexpectedValue = "unexpected-test-value";
-
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST_1, {what: TelemetryEnvironment.RECORD_PREF_VALUE}],
- [PREF_TEST_2, {what: TelemetryEnvironment.RECORD_PREF_STATE}],
- [PREF_TEST_3, {what: TelemetryEnvironment.RECORD_PREF_STATE}],
- [PREF_TEST_4, {what: TelemetryEnvironment.RECORD_PREF_VALUE}],
- [PREF_TEST_5, {what: TelemetryEnvironment.RECORD_PREF_VALUE, requiresRestart: true}],
- ]);
-
- Preferences.set(PREF_TEST_4, expectedValue);
- Preferences.set(PREF_TEST_5, expectedValue);
-
- // Set the Environment preferences to watch.
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
- let deferred = PromiseUtils.defer();
-
- // Check that the pref values are missing or present as expected
- Assert.strictEqual(TelemetryEnvironment.currentEnvironment.settings.userPrefs[PREF_TEST_1], undefined);
- Assert.strictEqual(TelemetryEnvironment.currentEnvironment.settings.userPrefs[PREF_TEST_4], expectedValue);
- Assert.strictEqual(TelemetryEnvironment.currentEnvironment.settings.userPrefs[PREF_TEST_5], expectedValue);
-
- TelemetryEnvironment.registerChangeListener("testWatchPrefs",
- (reason, data) => deferred.resolve(data));
- let oldEnvironmentData = TelemetryEnvironment.currentEnvironment;
-
- // Trigger a change in the watched preferences.
- Preferences.set(PREF_TEST_1, expectedValue);
- Preferences.set(PREF_TEST_2, false);
- Preferences.set(PREF_TEST_5, unexpectedValue);
- let eventEnvironmentData = yield deferred.promise;
-
- // Unregister the listener.
- TelemetryEnvironment.unregisterChangeListener("testWatchPrefs");
-
- // Check environment contains the correct data.
- Assert.deepEqual(oldEnvironmentData, eventEnvironmentData);
- let userPrefs = TelemetryEnvironment.currentEnvironment.settings.userPrefs;
-
- Assert.equal(userPrefs[PREF_TEST_1], expectedValue,
- "Environment contains the correct preference value.");
- Assert.equal(userPrefs[PREF_TEST_2], "<user-set>",
- "Report that the pref was user set but the value is not shown.");
- Assert.ok(!(PREF_TEST_3 in userPrefs),
- "Do not report if preference not user set.");
- Assert.equal(userPrefs[PREF_TEST_5], expectedValue,
- "The pref value in the environment data should still be the same");
-});
-
-add_task(function* test_prefWatch_prefReset() {
- const PREF_TEST = "toolkit.telemetry.test.pref1";
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_STATE}],
- ]);
-
- // Set the preference to a non-default value.
- Preferences.set(PREF_TEST, false);
-
- // Set the Environment preferences to watch.
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
- let deferred = PromiseUtils.defer();
- TelemetryEnvironment.registerChangeListener("testWatchPrefs_reset", deferred.resolve);
-
- Assert.strictEqual(TelemetryEnvironment.currentEnvironment.settings.userPrefs[PREF_TEST], "<user-set>");
-
- // Trigger a change in the watched preferences.
- Preferences.reset(PREF_TEST);
- yield deferred.promise;
-
- Assert.strictEqual(TelemetryEnvironment.currentEnvironment.settings.userPrefs[PREF_TEST], undefined);
-
- // Unregister the listener.
- TelemetryEnvironment.unregisterChangeListener("testWatchPrefs_reset");
-});
-
-add_task(function* test_addonsWatch_InterestingChange() {
- const ADDON_INSTALL_URL = gDataRoot + "restartless.xpi";
- const ADDON_ID = "tel-restartless-xpi@tests.mozilla.org";
- // We only expect a single notification for each install, uninstall, enable, disable.
- const EXPECTED_NOTIFICATIONS = 4;
-
- let receivedNotifications = 0;
-
- let registerCheckpointPromise = (aExpected) => {
- return new Promise(resolve => TelemetryEnvironment.registerChangeListener(
- "testWatchAddons_Changes" + aExpected, (reason, data) => {
- Assert.equal(reason, "addons-changed");
- receivedNotifications++;
- resolve();
- }));
- };
-
- let assertCheckpoint = (aExpected) => {
- Assert.equal(receivedNotifications, aExpected);
- TelemetryEnvironment.unregisterChangeListener("testWatchAddons_Changes" + aExpected);
- };
-
- // Test for receiving one notification after each change.
- let checkpointPromise = registerCheckpointPromise(1);
- yield AddonManagerTesting.installXPIFromURL(ADDON_INSTALL_URL);
- yield checkpointPromise;
- assertCheckpoint(1);
- Assert.ok(ADDON_ID in TelemetryEnvironment.currentEnvironment.addons.activeAddons);
-
- checkpointPromise = registerCheckpointPromise(2);
- let addon = yield AddonManagerTesting.getAddonById(ADDON_ID);
- addon.userDisabled = true;
- yield checkpointPromise;
- assertCheckpoint(2);
- Assert.ok(!(ADDON_ID in TelemetryEnvironment.currentEnvironment.addons.activeAddons));
-
- checkpointPromise = registerCheckpointPromise(3);
- addon.userDisabled = false;
- yield checkpointPromise;
- assertCheckpoint(3);
- Assert.ok(ADDON_ID in TelemetryEnvironment.currentEnvironment.addons.activeAddons);
-
- checkpointPromise = registerCheckpointPromise(4);
- yield AddonManagerTesting.uninstallAddonByID(ADDON_ID);
- yield checkpointPromise;
- assertCheckpoint(4);
- Assert.ok(!(ADDON_ID in TelemetryEnvironment.currentEnvironment.addons.activeAddons));
-
- Assert.equal(receivedNotifications, EXPECTED_NOTIFICATIONS,
- "We must only receive the notifications we expect.");
-});
-
-add_task(function* test_pluginsWatch_Add() {
- if (gIsAndroid) {
- Assert.ok(true, "Skipping: there is no Plugin Manager on Android.");
- return;
- }
-
- Assert.equal(TelemetryEnvironment.currentEnvironment.addons.activePlugins.length, 1);
-
- let newPlugin = new PluginTag(PLUGIN2_NAME, PLUGIN2_DESC, PLUGIN2_VERSION, true);
- gInstalledPlugins.push(newPlugin);
-
- let deferred = PromiseUtils.defer();
- let receivedNotifications = 0;
- let callback = (reason, data) => {
- receivedNotifications++;
- Assert.equal(reason, "addons-changed");
- deferred.resolve();
- };
- TelemetryEnvironment.registerChangeListener("testWatchPlugins_Add", callback);
-
- Services.obs.notifyObservers(null, PLUGIN_UPDATED_TOPIC, null);
- yield deferred.promise;
-
- Assert.equal(TelemetryEnvironment.currentEnvironment.addons.activePlugins.length, 2);
-
- TelemetryEnvironment.unregisterChangeListener("testWatchPlugins_Add");
-
- Assert.equal(receivedNotifications, 1, "We must only receive one notification.");
-});
-
-add_task(function* test_pluginsWatch_Remove() {
- if (gIsAndroid) {
- Assert.ok(true, "Skipping: there is no Plugin Manager on Android.");
- return;
- }
-
- // Find the test plugin.
- let plugin = gInstalledPlugins.find(p => (p.name == PLUGIN2_NAME));
- Assert.ok(plugin, "The test plugin must exist.");
-
- // Remove it from the PluginHost.
- gInstalledPlugins = gInstalledPlugins.filter(p => p != plugin);
-
- let deferred = PromiseUtils.defer();
- let receivedNotifications = 0;
- let callback = () => {
- receivedNotifications++;
- deferred.resolve();
- };
- TelemetryEnvironment.registerChangeListener("testWatchPlugins_Remove", callback);
-
- Services.obs.notifyObservers(null, PLUGIN_UPDATED_TOPIC, null);
- yield deferred.promise;
-
- TelemetryEnvironment.unregisterChangeListener("testWatchPlugins_Remove");
-
- Assert.equal(receivedNotifications, 1, "We must only receive one notification.");
-});
-
-add_task(function* test_addonsWatch_NotInterestingChange() {
- // We are not interested to dictionary addons changes.
- const DICTIONARY_ADDON_INSTALL_URL = gDataRoot + "dictionary.xpi";
- const INTERESTING_ADDON_INSTALL_URL = gDataRoot + "restartless.xpi";
-
- let receivedNotification = false;
- let deferred = PromiseUtils.defer();
- TelemetryEnvironment.registerChangeListener("testNotInteresting",
- () => {
- Assert.ok(!receivedNotification, "Should not receive multiple notifications");
- receivedNotification = true;
- deferred.resolve();
- });
-
- yield AddonManagerTesting.installXPIFromURL(DICTIONARY_ADDON_INSTALL_URL);
- yield AddonManagerTesting.installXPIFromURL(INTERESTING_ADDON_INSTALL_URL);
-
- yield deferred.promise;
- Assert.ok(!("telemetry-dictionary@tests.mozilla.org" in
- TelemetryEnvironment.currentEnvironment.addons.activeAddons),
- "Dictionaries should not appear in active addons.");
-
- TelemetryEnvironment.unregisterChangeListener("testNotInteresting");
-});
-
-add_task(function* test_addonsAndPlugins() {
- const ADDON_INSTALL_URL = gDataRoot + "restartless.xpi";
- const ADDON_ID = "tel-restartless-xpi@tests.mozilla.org";
- const ADDON_INSTALL_DATE = truncateToDays(Date.now());
- const EXPECTED_ADDON_DATA = {
- blocklisted: false,
- description: "A restartless addon which gets enabled without a reboot.",
- name: "XPI Telemetry Restartless Test",
- userDisabled: false,
- appDisabled: false,
- version: "1.0",
- scope: 1,
- type: "extension",
- foreignInstall: false,
- hasBinaryComponents: false,
- installDay: ADDON_INSTALL_DATE,
- updateDay: ADDON_INSTALL_DATE,
- signedState: mozinfo.addon_signing ? AddonManager.SIGNEDSTATE_SIGNED : AddonManager.SIGNEDSTATE_NOT_REQUIRED,
- isSystem: false,
- };
- const SYSTEM_ADDON_ID = "tel-system-xpi@tests.mozilla.org";
- const EXPECTED_SYSTEM_ADDON_DATA = {
- blocklisted: false,
- description: "A system addon which is shipped with Firefox.",
- name: "XPI Telemetry System Add-on Test",
- userDisabled: false,
- appDisabled: false,
- version: "1.0",
- scope: 1,
- type: "extension",
- foreignInstall: false,
- hasBinaryComponents: false,
- installDay: truncateToDays(SYSTEM_ADDON_INSTALL_DATE),
- updateDay: truncateToDays(SYSTEM_ADDON_INSTALL_DATE),
- signedState: undefined,
- isSystem: true,
- };
-
- const EXPECTED_PLUGIN_DATA = {
- name: FLASH_PLUGIN_NAME,
- version: FLASH_PLUGIN_VERSION,
- description: FLASH_PLUGIN_DESC,
- blocklisted: false,
- disabled: false,
- clicktoplay: true,
- };
-
- // Install an addon so we have some data.
- yield AddonManagerTesting.installXPIFromURL(ADDON_INSTALL_URL);
-
- let data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
-
- // Check addon data.
- Assert.ok(ADDON_ID in data.addons.activeAddons, "We must have one active addon.");
- let targetAddon = data.addons.activeAddons[ADDON_ID];
- for (let f in EXPECTED_ADDON_DATA) {
- Assert.equal(targetAddon[f], EXPECTED_ADDON_DATA[f], f + " must have the correct value.");
- }
-
- // Check system add-on data.
- Assert.ok(SYSTEM_ADDON_ID in data.addons.activeAddons, "We must have one active system addon.");
- let targetSystemAddon = data.addons.activeAddons[SYSTEM_ADDON_ID];
- for (let f in EXPECTED_SYSTEM_ADDON_DATA) {
- Assert.equal(targetSystemAddon[f], EXPECTED_SYSTEM_ADDON_DATA[f], f + " must have the correct value.");
- }
-
- // Check theme data.
- let theme = data.addons.theme;
- Assert.equal(theme.id, (PERSONA_ID + PERSONA_ID_SUFFIX));
- Assert.equal(theme.name, PERSONA_NAME);
- Assert.equal(theme.description, PERSONA_DESCRIPTION);
-
- // Check plugin data.
- Assert.equal(data.addons.activePlugins.length, 1, "We must have only one active plugin.");
- let targetPlugin = data.addons.activePlugins[0];
- for (let f in EXPECTED_PLUGIN_DATA) {
- Assert.equal(targetPlugin[f], EXPECTED_PLUGIN_DATA[f], f + " must have the correct value.");
- }
-
- // Check plugin mime types.
- Assert.ok(targetPlugin.mimeTypes.find(m => m == PLUGIN_MIME_TYPE1));
- Assert.ok(targetPlugin.mimeTypes.find(m => m == PLUGIN_MIME_TYPE2));
- Assert.ok(!targetPlugin.mimeTypes.find(m => m == "Not There."));
-
- let personaId = (gIsGonk) ? null : PERSONA_ID;
- Assert.equal(data.addons.persona, personaId, "The correct Persona Id must be reported.");
-
- // Uninstall the addon.
- yield AddonManagerTesting.uninstallAddonByID(ADDON_ID);
-});
-
-add_task(function* test_signedAddon() {
- const ADDON_INSTALL_URL = gDataRoot + "signed.xpi";
- const ADDON_ID = "tel-signed-xpi@tests.mozilla.org";
- const ADDON_INSTALL_DATE = truncateToDays(Date.now());
- const EXPECTED_ADDON_DATA = {
- blocklisted: false,
- description: "A signed addon which gets enabled without a reboot.",
- name: "XPI Telemetry Signed Test",
- userDisabled: false,
- appDisabled: false,
- version: "1.0",
- scope: 1,
- type: "extension",
- foreignInstall: false,
- hasBinaryComponents: false,
- installDay: ADDON_INSTALL_DATE,
- updateDay: ADDON_INSTALL_DATE,
- signedState: mozinfo.addon_signing ? AddonManager.SIGNEDSTATE_SIGNED : AddonManager.SIGNEDSTATE_NOT_REQUIRED,
- };
-
- let deferred = PromiseUtils.defer();
- TelemetryEnvironment.registerChangeListener("test_signedAddon", deferred.resolve);
-
- // Install the addon.
- yield AddonManagerTesting.installXPIFromURL(ADDON_INSTALL_URL);
-
- yield deferred.promise;
- // Unregister the listener.
- TelemetryEnvironment.unregisterChangeListener("test_signedAddon");
-
- let data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
-
- // Check addon data.
- Assert.ok(ADDON_ID in data.addons.activeAddons, "Add-on should be in the environment.");
- let targetAddon = data.addons.activeAddons[ADDON_ID];
- for (let f in EXPECTED_ADDON_DATA) {
- Assert.equal(targetAddon[f], EXPECTED_ADDON_DATA[f], f + " must have the correct value.");
- }
-});
-
-add_task(function* test_addonsFieldsLimit() {
- const ADDON_INSTALL_URL = gDataRoot + "long-fields.xpi";
- const ADDON_ID = "tel-longfields-xpi@tests.mozilla.org";
-
- // Install the addon and wait for the TelemetryEnvironment to pick it up.
- let deferred = PromiseUtils.defer();
- TelemetryEnvironment.registerChangeListener("test_longFieldsAddon", deferred.resolve);
- yield AddonManagerTesting.installXPIFromURL(ADDON_INSTALL_URL);
- yield deferred.promise;
- TelemetryEnvironment.unregisterChangeListener("test_longFieldsAddon");
-
- let data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
-
- // Check that the addon is available and that the string fields are limited.
- Assert.ok(ADDON_ID in data.addons.activeAddons, "Add-on should be in the environment.");
- let targetAddon = data.addons.activeAddons[ADDON_ID];
-
- // TelemetryEnvironment limits the length of string fields for activeAddons to 100 chars,
- // to mitigate misbehaving addons.
- Assert.lessOrEqual(targetAddon.version.length, 100,
- "The version string must have been limited");
- Assert.lessOrEqual(targetAddon.name.length, 100,
- "The name string must have been limited");
- Assert.lessOrEqual(targetAddon.description.length, 100,
- "The description string must have been limited");
-});
-
-add_task(function* test_collectionWithbrokenAddonData() {
- const BROKEN_ADDON_ID = "telemetry-test2.example.com@services.mozilla.org";
- const BROKEN_MANIFEST = {
- id: "telemetry-test2.example.com@services.mozilla.org",
- name: "telemetry broken addon",
- origin: "https://telemetry-test2.example.com",
- version: 1, // This is intentionally not a string.
- signedState: AddonManager.SIGNEDSTATE_SIGNED,
- };
-
- const ADDON_INSTALL_URL = gDataRoot + "restartless.xpi";
- const ADDON_ID = "tel-restartless-xpi@tests.mozilla.org";
- const ADDON_INSTALL_DATE = truncateToDays(Date.now());
- const EXPECTED_ADDON_DATA = {
- blocklisted: false,
- description: "A restartless addon which gets enabled without a reboot.",
- name: "XPI Telemetry Restartless Test",
- userDisabled: false,
- appDisabled: false,
- version: "1.0",
- scope: 1,
- type: "extension",
- foreignInstall: false,
- hasBinaryComponents: false,
- installDay: ADDON_INSTALL_DATE,
- updateDay: ADDON_INSTALL_DATE,
- signedState: mozinfo.addon_signing ? AddonManager.SIGNEDSTATE_MISSING :
- AddonManager.SIGNEDSTATE_NOT_REQUIRED,
- };
-
- let receivedNotifications = 0;
-
- let registerCheckpointPromise = (aExpected) => {
- return new Promise(resolve => TelemetryEnvironment.registerChangeListener(
- "testBrokenAddon_collection" + aExpected, (reason, data) => {
- Assert.equal(reason, "addons-changed");
- receivedNotifications++;
- resolve();
- }));
- };
-
- let assertCheckpoint = (aExpected) => {
- Assert.equal(receivedNotifications, aExpected);
- TelemetryEnvironment.unregisterChangeListener("testBrokenAddon_collection" + aExpected);
- };
-
- // Register the broken provider and install the broken addon.
- let checkpointPromise = registerCheckpointPromise(1);
- let brokenAddonProvider = createMockAddonProvider("Broken Extensions Provider");
- AddonManagerPrivate.registerProvider(brokenAddonProvider);
- brokenAddonProvider.addAddon(BROKEN_MANIFEST);
- yield checkpointPromise;
- assertCheckpoint(1);
-
- // Now install an addon which returns the correct information.
- checkpointPromise = registerCheckpointPromise(2);
- yield AddonManagerTesting.installXPIFromURL(ADDON_INSTALL_URL);
- yield checkpointPromise;
- assertCheckpoint(2);
-
- // Check that the new environment contains the Social addon installed with the broken
- // manifest and the rest of the data.
- let data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data, false, true /* expect broken addons*/);
-
- let activeAddons = data.addons.activeAddons;
- Assert.ok(BROKEN_ADDON_ID in activeAddons,
- "The addon with the broken manifest must be reported.");
- Assert.equal(activeAddons[BROKEN_ADDON_ID].version, null,
- "null should be reported for invalid data.");
- Assert.ok(ADDON_ID in activeAddons,
- "The valid addon must be reported.");
- Assert.equal(activeAddons[ADDON_ID].description, EXPECTED_ADDON_DATA.description,
- "The description for the valid addon should be correct.");
-
- // Unregister the broken provider so we don't mess with other tests.
- AddonManagerPrivate.unregisterProvider(brokenAddonProvider);
-
- // Uninstall the valid addon.
- yield AddonManagerTesting.uninstallAddonByID(ADDON_ID);
-});
-
-add_task(function* test_defaultSearchEngine() {
- // Check that no default engine is in the environment before the search service is
- // initialized.
- let data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
- Assert.ok(!("defaultSearchEngine" in data.settings));
- Assert.ok(!("defaultSearchEngineData" in data.settings));
-
- // Load the engines definitions from a custom JAR file: that's needed so that
- // the search provider reports an engine identifier.
- let url = "chrome://testsearchplugin/locale/searchplugins/";
- let resProt = Services.io.getProtocolHandler("resource")
- .QueryInterface(Ci.nsIResProtocolHandler);
- resProt.setSubstitution("search-plugins",
- Services.io.newURI(url, null, null));
-
- // Initialize the search service.
- yield new Promise(resolve => Services.search.init(resolve));
-
- // Our default engine from the JAR file has an identifier. Check if it is correctly
- // reported.
- data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
- Assert.equal(data.settings.defaultSearchEngine, "telemetrySearchIdentifier");
- let expectedSearchEngineData = {
- name: "telemetrySearchIdentifier",
- loadPath: "jar:[other]/searchTest.jar!testsearchplugin/telemetrySearchIdentifier.xml",
- origin: "default",
- submissionURL: "http://ar.wikipedia.org/wiki/%D8%AE%D8%A7%D8%B5:%D8%A8%D8%AD%D8%AB?search=&sourceid=Mozilla-search"
- };
- Assert.deepEqual(data.settings.defaultSearchEngineData, expectedSearchEngineData);
-
- // Remove all the search engines.
- for (let engine of Services.search.getEngines()) {
- Services.search.removeEngine(engine);
- }
- // The search service does not notify "engine-current" when removing a default engine.
- // Manually force the notification.
- // TODO: remove this when bug 1165341 is resolved.
- Services.obs.notifyObservers(null, "browser-search-engine-modified", "engine-current");
-
- // Then check that no default engine is reported if none is available.
- data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
- Assert.equal(data.settings.defaultSearchEngine, "NONE");
- Assert.deepEqual(data.settings.defaultSearchEngineData, {name:"NONE"});
-
- // Add a new search engine (this will have no engine identifier).
- const SEARCH_ENGINE_ID = "telemetry_default";
- const SEARCH_ENGINE_URL = "http://www.example.org/?search={searchTerms}";
- Services.search.addEngineWithDetails(SEARCH_ENGINE_ID, "", null, "", "get", SEARCH_ENGINE_URL);
-
- // Register a new change listener and then wait for the search engine change to be notified.
- let deferred = PromiseUtils.defer();
- TelemetryEnvironment.registerChangeListener("testWatch_SearchDefault", deferred.resolve);
- Services.search.defaultEngine = Services.search.getEngineByName(SEARCH_ENGINE_ID);
- yield deferred.promise;
-
- data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
-
- const EXPECTED_SEARCH_ENGINE = "other-" + SEARCH_ENGINE_ID;
- Assert.equal(data.settings.defaultSearchEngine, EXPECTED_SEARCH_ENGINE);
-
- const EXPECTED_SEARCH_ENGINE_DATA = {
- name: "telemetry_default",
- loadPath: "[other]addEngineWithDetails",
- origin: "verified"
- };
- Assert.deepEqual(data.settings.defaultSearchEngineData, EXPECTED_SEARCH_ENGINE_DATA);
- TelemetryEnvironment.unregisterChangeListener("testWatch_SearchDefault");
-
- // Cleanly install an engine from an xml file, and check if origin is
- // recorded as "verified".
- let promise = new Promise(resolve => {
- TelemetryEnvironment.registerChangeListener("testWatch_SearchDefault", resolve);
- });
- let engine = yield new Promise((resolve, reject) => {
- Services.obs.addObserver(function obs(obsSubject, obsTopic, obsData) {
- try {
- let searchEngine = obsSubject.QueryInterface(Ci.nsISearchEngine);
- do_print("Observed " + obsData + " for " + searchEngine.name);
- if (obsData != "engine-added" || searchEngine.name != "engine-telemetry") {
- return;
- }
-
- Services.obs.removeObserver(obs, "browser-search-engine-modified");
- resolve(searchEngine);
- } catch (ex) {
- reject(ex);
- }
- }, "browser-search-engine-modified", false);
- Services.search.addEngine("file://" + do_get_cwd().path + "/engine.xml",
- null, null, false);
- });
- Services.search.defaultEngine = engine;
- yield promise;
- TelemetryEnvironment.unregisterChangeListener("testWatch_SearchDefault");
- data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
- Assert.deepEqual(data.settings.defaultSearchEngineData,
- {"name":"engine-telemetry", "loadPath":"[other]/engine.xml", "origin":"verified"});
-
- // Now break this engine's load path hash.
- promise = new Promise(resolve => {
- TelemetryEnvironment.registerChangeListener("testWatch_SearchDefault", resolve);
- });
- engine.wrappedJSObject.setAttr("loadPathHash", "broken");
- Services.obs.notifyObservers(null, "browser-search-engine-modified", "engine-current");
- yield promise;
- TelemetryEnvironment.unregisterChangeListener("testWatch_SearchDefault");
- data = TelemetryEnvironment.currentEnvironment;
- Assert.equal(data.settings.defaultSearchEngineData.origin, "invalid");
- Services.search.removeEngine(engine);
-
- // Define and reset the test preference.
- const PREF_TEST = "toolkit.telemetry.test.pref1";
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_STATE}],
- ]);
- Preferences.reset(PREF_TEST);
-
- // Watch the test preference.
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
- deferred = PromiseUtils.defer();
- TelemetryEnvironment.registerChangeListener("testSearchEngine_pref", deferred.resolve);
- // Trigger an environment change.
- Preferences.set(PREF_TEST, 1);
- yield deferred.promise;
- TelemetryEnvironment.unregisterChangeListener("testSearchEngine_pref");
-
- // Check that the search engine information is correctly retained when prefs change.
- data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
- Assert.equal(data.settings.defaultSearchEngine, EXPECTED_SEARCH_ENGINE);
-
- // Check that by default we are not sending a cohort identifier...
- Assert.equal(data.settings.searchCohort, undefined);
-
- // ... but that if a cohort identifier is set, we send it.
- Services.prefs.setCharPref("browser.search.cohort", "testcohort");
- Services.obs.notifyObservers(null, "browser-search-service", "init-complete");
- data = TelemetryEnvironment.currentEnvironment;
- Assert.equal(data.settings.searchCohort, "testcohort");
-});
-
-add_task(function* test_osstrings() {
- // First test that numbers in sysinfo properties are converted to string fields
- // in system.os.
- SysInfo.overrides = {
- version: 1,
- name: 2,
- kernel_version: 3,
- };
-
- yield TelemetryEnvironment.testCleanRestart().onInitialized();
- let data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
-
- Assert.equal(data.system.os.version, "1");
- Assert.equal(data.system.os.name, "2");
- if (AppConstants.platform == "android") {
- Assert.equal(data.system.os.kernelVersion, "3");
- }
-
- // Check that null values are also handled.
- SysInfo.overrides = {
- version: null,
- name: null,
- kernel_version: null,
- };
-
- yield TelemetryEnvironment.testCleanRestart().onInitialized();
- data = TelemetryEnvironment.currentEnvironment;
- checkEnvironmentData(data);
-
- Assert.equal(data.system.os.version, null);
- Assert.equal(data.system.os.name, null);
- if (AppConstants.platform == "android") {
- Assert.equal(data.system.os.kernelVersion, null);
- }
-
- // Clean up.
- SysInfo.overrides = {};
- yield TelemetryEnvironment.testCleanRestart().onInitialized();
-});
-
-add_task(function* test_environmentShutdown() {
- // Define and reset the test preference.
- const PREF_TEST = "toolkit.telemetry.test.pref1";
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_STATE}],
- ]);
- Preferences.reset(PREF_TEST);
-
- // Set up the preferences and listener, then the trigger shutdown
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
- TelemetryEnvironment.registerChangeListener("test_environmentShutdownChange", () => {
- // Register a new change listener that asserts if change is propogated
- Assert.ok(false, "No change should be propagated after shutdown.");
- });
- TelemetryEnvironment.shutdown();
-
- // Flipping the test preference after shutdown should not trigger the listener
- Preferences.set(PREF_TEST, 1);
-
- // Unregister the listener.
- TelemetryEnvironment.unregisterChangeListener("test_environmentShutdownChange");
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryEvents.js b/toolkit/components/telemetry/tests/unit/test_TelemetryEvents.js
deleted file mode 100644
index 2bfb62c14..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryEvents.js
+++ /dev/null
@@ -1,249 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-
-const OPTIN = Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN;
-const OPTOUT = Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTOUT;
-
-function checkEventFormat(events) {
- Assert.ok(Array.isArray(events), "Events should be serialized to an array.");
- for (let e of events) {
- Assert.ok(Array.isArray(e), "Event should be an array.");
- Assert.greaterOrEqual(e.length, 4, "Event should have at least 4 elements.");
- Assert.lessOrEqual(e.length, 6, "Event should have at most 6 elements.");
-
- Assert.equal(typeof(e[0]), "number", "Element 0 should be a number.");
- Assert.equal(typeof(e[1]), "string", "Element 1 should be a string.");
- Assert.equal(typeof(e[2]), "string", "Element 2 should be a string.");
- Assert.equal(typeof(e[3]), "string", "Element 3 should be a string.");
-
- if (e.length > 4) {
- Assert.ok(e[4] === null || typeof(e[4]) == "string",
- "Event element 4 should be null or a string.");
- }
- if (e.length > 5) {
- Assert.ok(e[5] === null || typeof(e[5]) == "object",
- "Event element 5 should be null or an object.");
- }
-
- let extra = e[5];
- if (extra) {
- Assert.ok(Object.keys(extra).every(k => typeof(k) == "string"),
- "All extra keys should be strings.");
- Assert.ok(Object.values(extra).every(v => typeof(v) == "string"),
- "All extra values should be strings.");
- }
- }
-}
-
-add_task(function* test_recording() {
- Telemetry.clearEvents();
-
- // Record some events.
- let expected = [
- {optout: false, event: ["telemetry.test", "test1", "object1"]},
- {optout: false, event: ["telemetry.test", "test2", "object2"]},
-
- {optout: false, event: ["telemetry.test", "test1", "object1", "value"]},
- {optout: false, event: ["telemetry.test", "test1", "object1", "value", null]},
- {optout: false, event: ["telemetry.test", "test1", "object1", null, {"key1": "value1"}]},
- {optout: false, event: ["telemetry.test", "test1", "object1", "value", {"key1": "value1", "key2": "value2"}]},
-
- {optout: true, event: ["telemetry.test", "optout", "object1"]},
- {optout: false, event: ["telemetry.test.second", "test", "object1"]},
- {optout: false, event: ["telemetry.test.second", "test", "object1", null, {"key1": "value1"}]},
- ];
-
- for (let entry of expected) {
- entry.tsBefore = Math.floor(Telemetry.msSinceProcessStart());
- try {
- Telemetry.recordEvent(...entry.event);
- } catch (ex) {
- Assert.ok(false, `Failed to record event ${JSON.stringify(entry.event)}: ${ex}`);
- }
- entry.tsAfter = Math.floor(Telemetry.msSinceProcessStart());
- }
-
- // Strip off trailing null values to match the serialized events.
- for (let entry of expected) {
- let e = entry.event;
- while ((e.length >= 3) && (e[e.length - 1] === null)) {
- e.pop();
- }
- }
-
- // The following should not result in any recorded events.
- Assert.throws(() => Telemetry.recordEvent("unknown.category", "test1", "object1"),
- /Error: Unknown event: \["unknown.category", "test1", "object1"\]/,
- "Should throw on unknown category.");
- Assert.throws(() => Telemetry.recordEvent("telemetry.test", "unknown", "object1"),
- /Error: Unknown event: \["telemetry.test", "unknown", "object1"\]/,
- "Should throw on unknown method.");
- Assert.throws(() => Telemetry.recordEvent("telemetry.test", "test1", "unknown"),
- /Error: Unknown event: \["telemetry.test", "test1", "unknown"\]/,
- "Should throw on unknown object.");
-
- let checkEvents = (events, expectedEvents) => {
- checkEventFormat(events);
- Assert.equal(events.length, expectedEvents.length,
- "Snapshot should have the right number of events.");
-
- for (let i = 0; i < events.length; ++i) {
- let {tsBefore, tsAfter} = expectedEvents[i];
- let ts = events[i][0];
- Assert.greaterOrEqual(ts, tsBefore, "The recorded timestamp should be greater than the one before recording.");
- Assert.lessOrEqual(ts, tsAfter, "The recorded timestamp should be less than the one after recording.");
-
- let recordedData = events[i].slice(1);
- let expectedData = expectedEvents[i].event.slice();
- Assert.deepEqual(recordedData, expectedData, "The recorded event data should match.");
- }
- };
-
- // Check that the expected events were recorded.
- let events = Telemetry.snapshotBuiltinEvents(OPTIN, false);
- checkEvents(events, expected);
-
- // Check serializing only opt-out events.
- events = Telemetry.snapshotBuiltinEvents(OPTOUT, false);
- filtered = expected.filter(e => e.optout == true);
- checkEvents(events, filtered);
-});
-
-add_task(function* test_clear() {
- Telemetry.clearEvents();
-
- const COUNT = 10;
- for (let i = 0; i < COUNT; ++i) {
- Telemetry.recordEvent("telemetry.test", "test1", "object1");
- Telemetry.recordEvent("telemetry.test.second", "test", "object1");
- }
-
- // Check that events were recorded.
- // The events are cleared by passing the respective flag.
- let events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 2 * COUNT, `Should have recorded ${2 * COUNT} events.`);
-
- // Now the events should be cleared.
- events = Telemetry.snapshotBuiltinEvents(OPTIN, false);
- Assert.equal(events.length, 0, `Should have cleared the events.`);
-});
-
-add_task(function* test_expiry() {
- Telemetry.clearEvents();
-
- // Recording call with event that is expired by version.
- Telemetry.recordEvent("telemetry.test", "expired_version", "object1");
- let events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 0, "Should not record event with expired version.");
-
- // Recording call with event that is expired by date.
- Telemetry.recordEvent("telemetry.test", "expired_date", "object1");
- events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 0, "Should not record event with expired date.");
-
- // Recording call with event that has expiry_version and expiry_date in the future.
- Telemetry.recordEvent("telemetry.test", "not_expired_optout", "object1");
- events = Telemetry.snapshotBuiltinEvents(OPTOUT, true);
- Assert.equal(events.length, 1, "Should record event when date and version are not expired.");
-});
-
-add_task(function* test_invalidParams() {
- Telemetry.clearEvents();
-
- // Recording call with wrong type for value argument.
- Telemetry.recordEvent("telemetry.test", "test1", "object1", 1);
- let events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 0, "Should not record event when value argument with invalid type is passed.");
-
- // Recording call with wrong type for extra argument.
- Telemetry.recordEvent("telemetry.test", "test1", "object1", null, "invalid");
- events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 0, "Should not record event when extra argument with invalid type is passed.");
-
- // Recording call with unknown extra key.
- Telemetry.recordEvent("telemetry.test", "test1", "object1", null, {"key3": "x"});
- events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 0, "Should not record event when extra argument with invalid key is passed.");
-
- // Recording call with invalid value type.
- Telemetry.recordEvent("telemetry.test", "test1", "object1", null, {"key3": 1});
- events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 0, "Should not record event when extra argument with invalid value type is passed.");
-});
-
-add_task(function* test_storageLimit() {
- Telemetry.clearEvents();
-
- // Record more events than the storage limit allows.
- let LIMIT = 1000;
- let COUNT = LIMIT + 10;
- for (let i = 0; i < COUNT; ++i) {
- Telemetry.recordEvent("telemetry.test", "test1", "object1", String(i));
- }
-
- // Check that the right events were recorded.
- let events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, LIMIT, `Should have only recorded ${LIMIT} events`);
- Assert.ok(events.every((e, idx) => e[4] === String(idx)),
- "Should have recorded all events from before hitting the limit.");
-});
-
-add_task(function* test_valueLimits() {
- Telemetry.clearEvents();
-
- // Record values that are at or over the limits for string lengths.
- let LIMIT = 80;
- let expected = [
- ["telemetry.test", "test1", "object1", "a".repeat(LIMIT - 10), null],
- ["telemetry.test", "test1", "object1", "a".repeat(LIMIT ), null],
- ["telemetry.test", "test1", "object1", "a".repeat(LIMIT + 1), null],
- ["telemetry.test", "test1", "object1", "a".repeat(LIMIT + 10), null],
-
- ["telemetry.test", "test1", "object1", null, {key1: "a".repeat(LIMIT - 10)}],
- ["telemetry.test", "test1", "object1", null, {key1: "a".repeat(LIMIT )}],
- ["telemetry.test", "test1", "object1", null, {key1: "a".repeat(LIMIT + 1)}],
- ["telemetry.test", "test1", "object1", null, {key1: "a".repeat(LIMIT + 10)}],
- ];
-
- for (let event of expected) {
- Telemetry.recordEvent(...event);
- if (event[3]) {
- event[3] = event[3].substr(0, LIMIT);
- }
- if (event[4]) {
- event[4].key1 = event[4].key1.substr(0, LIMIT);
- }
- }
-
- // Strip off trailing null values to match the serialized events.
- for (let e of expected) {
- while ((e.length >= 3) && (e[e.length - 1] === null)) {
- e.pop();
- }
- }
-
- // Check that the right events were recorded.
- let events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, expected.length,
- "Should have recorded the expected number of events");
- for (let i = 0; i < expected.length; ++i) {
- Assert.deepEqual(events[i].slice(1), expected[i],
- "Should have recorded the expected event data.");
- }
-});
-
-add_task(function* test_unicodeValues() {
- Telemetry.clearEvents();
-
- // Record string values containing unicode characters.
- let value = "漢語";
- Telemetry.recordEvent("telemetry.test", "test1", "object1", value);
- Telemetry.recordEvent("telemetry.test", "test1", "object1", null, {"key1": value});
-
- // Check that the values were correctly recorded.
- let events = Telemetry.snapshotBuiltinEvents(OPTIN, true);
- Assert.equal(events.length, 2, "Should have recorded 2 events.");
- Assert.equal(events[0][4], value, "Should have recorded the right value.");
- Assert.equal(events[1][5]["key1"], value, "Should have recorded the right extra value.");
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryFlagClear.js b/toolkit/components/telemetry/tests/unit/test_TelemetryFlagClear.js
deleted file mode 100644
index 712aceb3b..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryFlagClear.js
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test()
-{
- let testFlag = Services.telemetry.getHistogramById("TELEMETRY_TEST_FLAG");
- equal(JSON.stringify(testFlag.snapshot().counts), "[1,0,0]", "Original value is correct");
- testFlag.add(1);
- equal(JSON.stringify(testFlag.snapshot().counts), "[0,1,0]", "Value is correct after ping.");
- testFlag.clear();
- equal(JSON.stringify(testFlag.snapshot().counts), "[1,0,0]", "Value is correct after calling clear()");
- testFlag.add(1);
- equal(JSON.stringify(testFlag.snapshot().counts), "[0,1,0]", "Value is correct after ping.");
-}
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js b/toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js
deleted file mode 100644
index f2b2b3bba..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js
+++ /dev/null
@@ -1,127 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-/* A testcase to make sure reading late writes stacks works. */
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-// Constants from prio.h for nsIFileOutputStream.init
-const PR_WRONLY = 0x2;
-const PR_CREATE_FILE = 0x8;
-const PR_TRUNCATE = 0x20;
-const RW_OWNER = parseInt("0600", 8);
-
-const STACK_SUFFIX1 = "stack1.txt";
-const STACK_SUFFIX2 = "stack2.txt";
-const STACK_BOGUS_SUFFIX = "bogus.txt";
-const LATE_WRITE_PREFIX = "Telemetry.LateWriteFinal-";
-
-// The names and IDs don't matter, but the format of the IDs does.
-const LOADED_MODULES = {
- '4759A7E6993548C89CAF716A67EC242D00': 'libtest.so',
- 'F77AF15BB8D6419FA875954B4A3506CA00': 'libxul.so',
- '1E2F7FB590424E8F93D60BB88D66B8C500': 'libc.so'
-};
-const N_MODULES = Object.keys(LOADED_MODULES).length;
-
-// Format of individual items is [index, offset-in-library].
-const STACK1 = [
- [ 0, 0 ],
- [ 1, 1 ],
- [ 2, 2 ]
-];
-const STACK2 = [
- [ 0, 0 ],
- [ 1, 5 ],
- [ 2, 10 ],
-];
-// XXX The only error checking is for a zero-sized stack.
-const STACK_BOGUS = [];
-
-function write_string_to_file(file, contents) {
- let ostream = Cc["@mozilla.org/network/safe-file-output-stream;1"]
- .createInstance(Ci.nsIFileOutputStream);
- ostream.init(file, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
- RW_OWNER, ostream.DEFER_OPEN);
- ostream.write(contents, contents.length);
- ostream.QueryInterface(Ci.nsISafeOutputStream).finish();
- ostream.close();
-}
-
-function construct_file(suffix) {
- let profileDirectory = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let file = profileDirectory.clone();
- file.append(LATE_WRITE_PREFIX + suffix);
- return file;
-}
-
-function write_late_writes_file(stack, suffix)
-{
- let file = construct_file(suffix);
- let contents = N_MODULES + "\n";
- for (let id in LOADED_MODULES) {
- contents += id + " " + LOADED_MODULES[id] + "\n";
- }
-
- contents += stack.length + "\n";
- for (let element of stack) {
- contents += element[0] + " " + element[1].toString(16) + "\n";
- }
-
- write_string_to_file(file, contents);
-}
-
-function run_test() {
- do_get_profile();
-
- write_late_writes_file(STACK1, STACK_SUFFIX1);
- write_late_writes_file(STACK2, STACK_SUFFIX2);
- write_late_writes_file(STACK_BOGUS, STACK_BOGUS_SUFFIX);
-
- let lateWrites = Telemetry.lateWrites;
- do_check_true("memoryMap" in lateWrites);
- do_check_eq(lateWrites.memoryMap.length, 0);
- do_check_true("stacks" in lateWrites);
- do_check_eq(lateWrites.stacks.length, 0);
-
- do_test_pending();
- Telemetry.asyncFetchTelemetryData(function () {
- actual_test();
- });
-}
-
-function actual_test() {
- do_check_false(construct_file(STACK_SUFFIX1).exists());
- do_check_false(construct_file(STACK_SUFFIX2).exists());
- do_check_false(construct_file(STACK_BOGUS_SUFFIX).exists());
-
- let lateWrites = Telemetry.lateWrites;
-
- do_check_true("memoryMap" in lateWrites);
- do_check_eq(lateWrites.memoryMap.length, N_MODULES);
- for (let id in LOADED_MODULES) {
- let matchingLibrary = lateWrites.memoryMap.filter(function(library, idx, array) {
- return library[1] == id;
- });
- do_check_eq(matchingLibrary.length, 1);
- let library = matchingLibrary[0]
- let name = library[0];
- do_check_eq(LOADED_MODULES[id], name);
- }
-
- do_check_true("stacks" in lateWrites);
- do_check_eq(lateWrites.stacks.length, 2);
- let uneval_STACKS = [uneval(STACK1), uneval(STACK2)];
- let first_stack = lateWrites.stacks[0];
- let second_stack = lateWrites.stacks[1];
- function stackChecker(canonicalStack) {
- let unevalCanonicalStack = uneval(canonicalStack);
- return function(obj, idx, array) {
- return unevalCanonicalStack == obj;
- }
- }
- do_check_eq(uneval_STACKS.filter(stackChecker(first_stack)).length, 1);
- do_check_eq(uneval_STACKS.filter(stackChecker(second_stack)).length, 1);
-
- do_test_finished();
-}
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryLockCount.js b/toolkit/components/telemetry/tests/unit/test_TelemetryLockCount.js
deleted file mode 100644
index 808f2f3ec..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryLockCount.js
+++ /dev/null
@@ -1,53 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-/* A testcase to make sure reading the failed profile lock count works. */
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-
-const LOCK_FILE_NAME = "Telemetry.FailedProfileLocks.txt";
-const N_FAILED_LOCKS = 10;
-
-// Constants from prio.h for nsIFileOutputStream.init
-const PR_WRONLY = 0x2;
-const PR_CREATE_FILE = 0x8;
-const PR_TRUNCATE = 0x20;
-const RW_OWNER = parseInt("0600", 8);
-
-function write_string_to_file(file, contents) {
- let ostream = Cc["@mozilla.org/network/safe-file-output-stream;1"]
- .createInstance(Ci.nsIFileOutputStream);
- ostream.init(file, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
- RW_OWNER, ostream.DEFER_OPEN);
- ostream.write(contents, contents.length);
- ostream.QueryInterface(Ci.nsISafeOutputStream).finish();
- ostream.close();
-}
-
-function construct_file() {
- let profileDirectory = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let file = profileDirectory.clone();
- file.append(LOCK_FILE_NAME);
- return file;
-}
-
-function run_test() {
- do_get_profile();
-
- do_check_eq(Telemetry.failedProfileLockCount, 0);
-
- write_string_to_file(construct_file(), N_FAILED_LOCKS.toString());
-
- // Make sure that we're not eagerly reading the count now that the
- // file exists.
- do_check_eq(Telemetry.failedProfileLockCount, 0);
-
- do_test_pending();
- Telemetry.asyncFetchTelemetryData(actual_test);
-}
-
-function actual_test() {
- do_check_eq(Telemetry.failedProfileLockCount, N_FAILED_LOCKS);
- do_check_false(construct_file().exists());
- do_test_finished();
-}
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryLog.js b/toolkit/components/telemetry/tests/unit/test_TelemetryLog.js
deleted file mode 100644
index ea37a1bc5..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryLog.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Cu.import("resource://gre/modules/TelemetryLog.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-
-const TEST_PREFIX = "TEST-";
-const TEST_REGEX = new RegExp("^" + TEST_PREFIX);
-
-function check_event(event, id, data)
-{
- do_print("Checking message " + id);
- do_check_eq(event[0], id);
- do_check_true(event[1] > 0);
-
- if (data === undefined) {
- do_check_true(event.length == 2);
- } else {
- do_check_eq(event.length, data.length + 2);
- for (var i = 0; i < data.length; ++i) {
- do_check_eq(typeof(event[i + 2]), "string");
- do_check_eq(event[i + 2], data[i]);
- }
- }
-}
-
-add_task(function* ()
-{
- do_get_profile();
- // TODO: After Bug 1254550 lands we should not need to set the pref here.
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
- yield TelemetryController.testSetup();
-
- TelemetryLog.log(TEST_PREFIX + "1", ["val", 123, undefined]);
- TelemetryLog.log(TEST_PREFIX + "2", []);
- TelemetryLog.log(TEST_PREFIX + "3");
-
- var log = TelemetrySession.getPayload().log.filter(function(e) {
- // Only want events that were generated by the test.
- return TEST_REGEX.test(e[0]);
- });
-
- do_check_eq(log.length, 3);
- check_event(log[0], TEST_PREFIX + "1", ["val", "123", "undefined"]);
- check_event(log[1], TEST_PREFIX + "2", []);
- check_event(log[2], TEST_PREFIX + "3", undefined);
- do_check_true(log[0][1] <= log[1][1]);
- do_check_true(log[1][1] <= log[2][1]);
-
- yield TelemetryController.testShutdown();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryReportingPolicy.js b/toolkit/components/telemetry/tests/unit/test_TelemetryReportingPolicy.js
deleted file mode 100644
index 68606a98e..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryReportingPolicy.js
+++ /dev/null
@@ -1,268 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Test that TelemetryController sends close to shutdown don't lead
-// to AsyncShutdown timeouts.
-
-"use strict";
-
-Cu.import("resource://gre/modules/Preferences.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySend.jsm", this);
-Cu.import("resource://gre/modules/TelemetryReportingPolicy.jsm", this);
-Cu.import("resource://gre/modules/TelemetryUtils.jsm", this);
-Cu.import("resource://gre/modules/Timer.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/UpdateUtils.jsm", this);
-
-const PREF_BRANCH = "toolkit.telemetry.";
-const PREF_SERVER = PREF_BRANCH + "server";
-
-const TEST_CHANNEL = "TestChannelABC";
-
-const PREF_POLICY_BRANCH = "datareporting.policy.";
-const PREF_BYPASS_NOTIFICATION = PREF_POLICY_BRANCH + "dataSubmissionPolicyBypassNotification";
-const PREF_DATA_SUBMISSION_ENABLED = PREF_POLICY_BRANCH + "dataSubmissionEnabled";
-const PREF_CURRENT_POLICY_VERSION = PREF_POLICY_BRANCH + "currentPolicyVersion";
-const PREF_MINIMUM_POLICY_VERSION = PREF_POLICY_BRANCH + "minimumPolicyVersion";
-const PREF_MINIMUM_CHANNEL_POLICY_VERSION = PREF_MINIMUM_POLICY_VERSION + ".channel-" + TEST_CHANNEL;
-const PREF_ACCEPTED_POLICY_VERSION = PREF_POLICY_BRANCH + "dataSubmissionPolicyAcceptedVersion";
-const PREF_ACCEPTED_POLICY_DATE = PREF_POLICY_BRANCH + "dataSubmissionPolicyNotifiedTime";
-
-function fakeShowPolicyTimeout(set, clear) {
- let reportingPolicy = Cu.import("resource://gre/modules/TelemetryReportingPolicy.jsm");
- reportingPolicy.Policy.setShowInfobarTimeout = set;
- reportingPolicy.Policy.clearShowInfobarTimeout = clear;
-}
-
-function fakeResetAcceptedPolicy() {
- Preferences.reset(PREF_ACCEPTED_POLICY_DATE);
- Preferences.reset(PREF_ACCEPTED_POLICY_VERSION);
-}
-
-function setMinimumPolicyVersion(aNewPolicyVersion) {
- const CHANNEL_NAME = UpdateUtils.getUpdateChannel(false);
- // We might have channel-dependent minimum policy versions.
- const CHANNEL_DEPENDENT_PREF = PREF_MINIMUM_POLICY_VERSION + ".channel-" + CHANNEL_NAME;
-
- // Does the channel-dependent pref exist? If so, set its value.
- if (Preferences.get(CHANNEL_DEPENDENT_PREF, undefined)) {
- Preferences.set(CHANNEL_DEPENDENT_PREF, aNewPolicyVersion);
- return;
- }
-
- // We don't have a channel specific minimu, so set the common one.
- Preferences.set(PREF_MINIMUM_POLICY_VERSION, aNewPolicyVersion);
-}
-
-add_task(function* test_setup() {
- // Addon manager needs a profile directory
- do_get_profile(true);
- loadAddonManager("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9.2");
-
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
- // Don't bypass the notifications in this test, we'll fake it.
- Services.prefs.setBoolPref(PREF_BYPASS_NOTIFICATION, false);
-
- TelemetryReportingPolicy.setup();
-});
-
-add_task(function* test_firstRun() {
- const PREF_FIRST_RUN = "toolkit.telemetry.reportingpolicy.firstRun";
- const FIRST_RUN_TIMEOUT_MSEC = 60 * 1000; // 60s
- const OTHER_RUNS_TIMEOUT_MSEC = 10 * 1000; // 10s
-
- Preferences.reset(PREF_FIRST_RUN);
-
- let startupTimeout = 0;
- fakeShowPolicyTimeout((callback, timeout) => startupTimeout = timeout, () => {});
- TelemetryReportingPolicy.reset();
-
- Services.obs.notifyObservers(null, "sessionstore-windows-restored", null);
- Assert.equal(startupTimeout, FIRST_RUN_TIMEOUT_MSEC,
- "The infobar display timeout should be 60s on the first run.");
-
- // Run again, and check that we actually wait only 10 seconds.
- TelemetryReportingPolicy.reset();
- Services.obs.notifyObservers(null, "sessionstore-windows-restored", null);
- Assert.equal(startupTimeout, OTHER_RUNS_TIMEOUT_MSEC,
- "The infobar display timeout should be 10s on other runs.");
-});
-
-add_task(function* test_prefs() {
- TelemetryReportingPolicy.reset();
-
- let now = fakeNow(2009, 11, 18);
-
- // If the date is not valid (earlier than 2012), we don't regard the policy as accepted.
- TelemetryReportingPolicy.testInfobarShown();
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified());
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_DATE, null), 0,
- "Invalid dates should not make the policy accepted.");
-
- // Check that the notification date and version are correctly saved to the prefs.
- now = fakeNow(2012, 11, 18);
- TelemetryReportingPolicy.testInfobarShown();
- Assert.equal(Preferences.get(PREF_ACCEPTED_POLICY_DATE, null), now.getTime(),
- "A valid date must correctly be saved.");
-
- // Now that user is notified, check if we are allowed to upload.
- Assert.ok(TelemetryReportingPolicy.canUpload(),
- "We must be able to upload after the policy is accepted.");
-
- // Disable submission and check that we're no longer allowed to upload.
- Preferences.set(PREF_DATA_SUBMISSION_ENABLED, false);
- Assert.ok(!TelemetryReportingPolicy.canUpload(),
- "We must not be able to upload if data submission is disabled.");
-
- // Turn the submission back on.
- Preferences.set(PREF_DATA_SUBMISSION_ENABLED, true);
- Assert.ok(TelemetryReportingPolicy.canUpload(),
- "We must be able to upload if data submission is enabled and the policy was accepted.");
-
- // Set a new minimum policy version and check that user is no longer notified.
- let newMinimum = Preferences.get(PREF_CURRENT_POLICY_VERSION, 1) + 1;
- setMinimumPolicyVersion(newMinimum);
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(),
- "A greater minimum policy version must invalidate the policy and disable upload.");
-
- // Eventually accept the policy and make sure user is notified.
- Preferences.set(PREF_CURRENT_POLICY_VERSION, newMinimum);
- TelemetryReportingPolicy.testInfobarShown();
- Assert.ok(TelemetryReportingPolicy.testIsUserNotified(),
- "Accepting the policy again should show the user as notified.");
- Assert.ok(TelemetryReportingPolicy.canUpload(),
- "Accepting the policy again should let us upload data.");
-
- // Set a new, per channel, minimum policy version. Start by setting a test current channel.
- let defaultPrefs = new Preferences({ defaultBranch: true });
- defaultPrefs.set("app.update.channel", TEST_CHANNEL);
-
- // Increase and set the new minimum version, then check that we're not notified anymore.
- newMinimum++;
- Preferences.set(PREF_MINIMUM_CHANNEL_POLICY_VERSION, newMinimum);
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(),
- "Increasing the minimum policy version should invalidate the policy.");
-
- // Eventually accept the policy and make sure user is notified.
- Preferences.set(PREF_CURRENT_POLICY_VERSION, newMinimum);
- TelemetryReportingPolicy.testInfobarShown();
- Assert.ok(TelemetryReportingPolicy.testIsUserNotified(),
- "Accepting the policy again should show the user as notified.");
- Assert.ok(TelemetryReportingPolicy.canUpload(),
- "Accepting the policy again should let us upload data.");
-});
-
-add_task(function* test_migratePrefs() {
- const DEPRECATED_FHR_PREFS = {
- "datareporting.policy.dataSubmissionPolicyAccepted": true,
- "datareporting.policy.dataSubmissionPolicyBypassAcceptance": true,
- "datareporting.policy.dataSubmissionPolicyResponseType": "foxyeah",
- "datareporting.policy.dataSubmissionPolicyResponseTime": Date.now().toString(),
- };
-
- // Make sure the preferences are set before setting up the policy.
- for (let name in DEPRECATED_FHR_PREFS) {
- Preferences.set(name, DEPRECATED_FHR_PREFS[name]);
- }
- // Set up the policy.
- TelemetryReportingPolicy.reset();
- // They should have been removed by now.
- for (let name in DEPRECATED_FHR_PREFS) {
- Assert.ok(!Preferences.has(name), name + " should have been removed.");
- }
-});
-
-add_task(function* test_userNotifiedOfCurrentPolicy() {
- fakeResetAcceptedPolicy();
- TelemetryReportingPolicy.reset();
-
- // User should be reported as not notified by default.
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(),
- "The initial state should be unnotified.");
-
- // Forcing a policy version should not automatically make the user notified.
- Preferences.set(PREF_ACCEPTED_POLICY_VERSION,
- TelemetryReportingPolicy.DEFAULT_DATAREPORTING_POLICY_VERSION);
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(),
- "The default state of the date should have a time of 0 and it should therefore fail");
-
- // Showing the notification bar should make the user notified.
- fakeNow(2012, 11, 11);
- TelemetryReportingPolicy.testInfobarShown();
- Assert.ok(TelemetryReportingPolicy.testIsUserNotified(),
- "Using the proper API causes user notification to report as true.");
-
- // It is assumed that later versions of the policy will incorporate previous
- // ones, therefore this should also return true.
- let newVersion =
- Preferences.get(PREF_CURRENT_POLICY_VERSION, 1) + 1;
- Preferences.set(PREF_ACCEPTED_POLICY_VERSION, newVersion);
- Assert.ok(TelemetryReportingPolicy.testIsUserNotified(),
- "A future version of the policy should pass.");
-
- newVersion =
- Preferences.get(PREF_CURRENT_POLICY_VERSION, 1) - 1;
- Preferences.set(PREF_ACCEPTED_POLICY_VERSION, newVersion);
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(),
- "A previous version of the policy should fail.");
-});
-
-add_task(function* test_canSend() {
- const TEST_PING_TYPE = "test-ping";
-
- PingServer.start();
- Preferences.set(PREF_SERVER, "http://localhost:" + PingServer.port);
-
- yield TelemetryController.testReset();
- TelemetryReportingPolicy.reset();
-
- // User should be reported as not notified by default.
- Assert.ok(!TelemetryReportingPolicy.testIsUserNotified(),
- "The initial state should be unnotified.");
-
- // Assert if we receive any ping before the policy is accepted.
- PingServer.registerPingHandler(() => Assert.ok(false, "Should not have received any pings now"));
- yield TelemetryController.submitExternalPing(TEST_PING_TYPE, {});
-
- // Reset the ping handler.
- PingServer.resetPingHandler();
-
- // Fake the infobar: this should also trigger the ping send task.
- TelemetryReportingPolicy.testInfobarShown();
- let ping = yield PingServer.promiseNextPings(1);
- Assert.equal(ping.length, 1, "We should have received one ping.");
- Assert.equal(ping[0].type, TEST_PING_TYPE,
- "We should have received the previous ping.");
-
- // Submit another ping, to make sure it gets sent.
- yield TelemetryController.submitExternalPing(TEST_PING_TYPE, {});
-
- // Get the ping and check its type.
- ping = yield PingServer.promiseNextPings(1);
- Assert.equal(ping.length, 1, "We should have received one ping.");
- Assert.equal(ping[0].type, TEST_PING_TYPE, "We should have received the new ping.");
-
- // Fake a restart with a pending ping.
- yield TelemetryController.addPendingPing(TEST_PING_TYPE, {});
- yield TelemetryController.testReset();
-
- // We should be immediately sending the ping out.
- ping = yield PingServer.promiseNextPings(1);
- Assert.equal(ping.length, 1, "We should have received one ping.");
- Assert.equal(ping[0].type, TEST_PING_TYPE, "We should have received the pending ping.");
-
- // Submit another ping, to make sure it gets sent.
- yield TelemetryController.submitExternalPing(TEST_PING_TYPE, {});
-
- // Get the ping and check its type.
- ping = yield PingServer.promiseNextPings(1);
- Assert.equal(ping.length, 1, "We should have received one ping.");
- Assert.equal(ping[0].type, TEST_PING_TYPE, "We should have received the new ping.");
-
- yield PingServer.stop();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js b/toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js
deleted file mode 100644
index 5914a4235..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js
+++ /dev/null
@@ -1,574 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-
-const UINT_SCALAR = "telemetry.test.unsigned_int_kind";
-const STRING_SCALAR = "telemetry.test.string_kind";
-const BOOLEAN_SCALAR = "telemetry.test.boolean_kind";
-const KEYED_UINT_SCALAR = "telemetry.test.keyed_unsigned_int";
-
-add_task(function* test_serializationFormat() {
- Telemetry.clearScalars();
-
- // Set the scalars to a known value.
- const expectedUint = 3785;
- const expectedString = "some value";
- Telemetry.scalarSet(UINT_SCALAR, expectedUint);
- Telemetry.scalarSet(STRING_SCALAR, expectedString);
- Telemetry.scalarSet(BOOLEAN_SCALAR, true);
- Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, "first_key", 1234);
-
- // Get a snapshot of the scalars.
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- // Check that they are serialized to the correct format.
- Assert.equal(typeof(scalars[UINT_SCALAR]), "number",
- UINT_SCALAR + " must be serialized to the correct format.");
- Assert.ok(Number.isInteger(scalars[UINT_SCALAR]),
- UINT_SCALAR + " must be a finite integer.");
- Assert.equal(scalars[UINT_SCALAR], expectedUint,
- UINT_SCALAR + " must have the correct value.");
- Assert.equal(typeof(scalars[STRING_SCALAR]), "string",
- STRING_SCALAR + " must be serialized to the correct format.");
- Assert.equal(scalars[STRING_SCALAR], expectedString,
- STRING_SCALAR + " must have the correct value.");
- Assert.equal(typeof(scalars[BOOLEAN_SCALAR]), "boolean",
- BOOLEAN_SCALAR + " must be serialized to the correct format.");
- Assert.equal(scalars[BOOLEAN_SCALAR], true,
- BOOLEAN_SCALAR + " must have the correct value.");
- Assert.ok(!(KEYED_UINT_SCALAR in scalars),
- "Keyed scalars must be reported in a separate section.");
-});
-
-add_task(function* test_keyedSerializationFormat() {
- Telemetry.clearScalars();
-
- const expectedKey = "first_key";
- const expectedOtherKey = "漢語";
- const expectedUint = 3785;
- const expectedOtherValue = 1107;
-
- Telemetry.scalarSet(UINT_SCALAR, expectedUint);
- Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, expectedKey, expectedUint);
- Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, expectedOtherKey, expectedOtherValue);
-
- // Get a snapshot of the scalars.
- const keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- Assert.ok(!(UINT_SCALAR in keyedScalars),
- UINT_SCALAR + " must not be serialized with the keyed scalars.");
- Assert.ok(KEYED_UINT_SCALAR in keyedScalars,
- KEYED_UINT_SCALAR + " must be serialized with the keyed scalars.");
- Assert.equal(Object.keys(keyedScalars[KEYED_UINT_SCALAR]).length, 2,
- "The keyed scalar must contain exactly 2 keys.");
- Assert.ok(expectedKey in keyedScalars[KEYED_UINT_SCALAR],
- KEYED_UINT_SCALAR + " must contain the expected keys.");
- Assert.ok(expectedOtherKey in keyedScalars[KEYED_UINT_SCALAR],
- KEYED_UINT_SCALAR + " must contain the expected keys.");
- Assert.ok(Number.isInteger(keyedScalars[KEYED_UINT_SCALAR][expectedKey]),
- KEYED_UINT_SCALAR + "." + expectedKey + " must be a finite integer.");
- Assert.equal(keyedScalars[KEYED_UINT_SCALAR][expectedKey], expectedUint,
- KEYED_UINT_SCALAR + "." + expectedKey + " must have the correct value.");
- Assert.equal(keyedScalars[KEYED_UINT_SCALAR][expectedOtherKey], expectedOtherValue,
- KEYED_UINT_SCALAR + "." + expectedOtherKey + " must have the correct value.");
-});
-
-add_task(function* test_nonexistingScalar() {
- const NON_EXISTING_SCALAR = "telemetry.test.non_existing";
-
- Telemetry.clearScalars();
-
- // Make sure we throw on any operation for non-existing scalars.
- Assert.throws(() => Telemetry.scalarAdd(NON_EXISTING_SCALAR, 11715),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Adding to a non existing scalar must throw.");
- Assert.throws(() => Telemetry.scalarSet(NON_EXISTING_SCALAR, 11715),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Setting a non existing scalar must throw.");
- Assert.throws(() => Telemetry.scalarSetMaximum(NON_EXISTING_SCALAR, 11715),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Setting the maximum of a non existing scalar must throw.");
-
- // Make sure we throw on any operation for non-existing scalars.
- Assert.throws(() => Telemetry.keyedScalarAdd(NON_EXISTING_SCALAR, "some_key", 11715),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Adding to a non existing keyed scalar must throw.");
- Assert.throws(() => Telemetry.keyedScalarSet(NON_EXISTING_SCALAR, "some_key", 11715),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Setting a non existing keyed scalar must throw.");
- Assert.throws(() => Telemetry.keyedScalarSetMaximum(NON_EXISTING_SCALAR, "some_key", 11715),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Setting the maximum of a non keyed existing scalar must throw.");
-
- // Get a snapshot of the scalars.
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- Assert.ok(!(NON_EXISTING_SCALAR in scalars), "The non existing scalar must not be persisted.");
-
- const keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- Assert.ok(!(NON_EXISTING_SCALAR in keyedScalars),
- "The non existing keyed scalar must not be persisted.");
-});
-
-add_task(function* test_expiredScalar() {
- const EXPIRED_SCALAR = "telemetry.test.expired";
- const EXPIRED_KEYED_SCALAR = "telemetry.test.keyed_expired";
- const UNEXPIRED_SCALAR = "telemetry.test.unexpired";
-
- Telemetry.clearScalars();
-
- // Try to set the expired scalar to some value. We will not be recording the value,
- // but we shouldn't throw.
- Telemetry.scalarAdd(EXPIRED_SCALAR, 11715);
- Telemetry.scalarSet(EXPIRED_SCALAR, 11715);
- Telemetry.scalarSetMaximum(EXPIRED_SCALAR, 11715);
- Telemetry.keyedScalarAdd(EXPIRED_KEYED_SCALAR, "some_key", 11715);
- Telemetry.keyedScalarSet(EXPIRED_KEYED_SCALAR, "some_key", 11715);
- Telemetry.keyedScalarSetMaximum(EXPIRED_KEYED_SCALAR, "some_key", 11715);
-
- // The unexpired scalar has an expiration version, but far away in the future.
- const expectedValue = 11716;
- Telemetry.scalarSet(UNEXPIRED_SCALAR, expectedValue);
-
- // Get a snapshot of the scalars.
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- const keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- Assert.ok(!(EXPIRED_SCALAR in scalars), "The expired scalar must not be persisted.");
- Assert.equal(scalars[UNEXPIRED_SCALAR], expectedValue,
- "The unexpired scalar must be persisted with the correct value.");
- Assert.ok(!(EXPIRED_KEYED_SCALAR in keyedScalars),
- "The expired keyed scalar must not be persisted.");
-});
-
-add_task(function* test_unsignedIntScalar() {
- let checkScalar = (expectedValue) => {
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(scalars[UINT_SCALAR], expectedValue,
- UINT_SCALAR + " must contain the expected value.");
- };
-
- Telemetry.clearScalars();
-
- // Let's start with an accumulation without a prior set.
- Telemetry.scalarAdd(UINT_SCALAR, 1);
- Telemetry.scalarAdd(UINT_SCALAR, 2);
- // Do we get what we expect?
- checkScalar(3);
-
- // Let's test setting the scalar to a value.
- Telemetry.scalarSet(UINT_SCALAR, 3785);
- checkScalar(3785);
- Telemetry.scalarAdd(UINT_SCALAR, 1);
- checkScalar(3786);
-
- // Does setMaximum work?
- Telemetry.scalarSet(UINT_SCALAR, 2);
- checkScalar(2);
- Telemetry.scalarSetMaximum(UINT_SCALAR, 5);
- checkScalar(5);
- // The value of the probe should still be 5, as the previous value
- // is greater than the one we want to set.
- Telemetry.scalarSetMaximum(UINT_SCALAR, 3);
- checkScalar(5);
-
- // Check that non-integer numbers get truncated and set.
- Telemetry.scalarSet(UINT_SCALAR, 3.785);
- checkScalar(3);
-
- // Setting or adding a negative number must report an error through
- // the console and drop the change (shouldn't throw).
- Telemetry.scalarAdd(UINT_SCALAR, -5);
- Telemetry.scalarSet(UINT_SCALAR, -5);
- Telemetry.scalarSetMaximum(UINT_SCALAR, -1);
- checkScalar(3);
-
- // What happens if we try to set a value of a different type?
- Telemetry.scalarSet(UINT_SCALAR, 1);
- Assert.throws(() => Telemetry.scalarSet(UINT_SCALAR, "unexpected value"),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Setting the scalar to an unexpected value type must throw.");
- Assert.throws(() => Telemetry.scalarAdd(UINT_SCALAR, "unexpected value"),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Adding an unexpected value type must throw.");
- Assert.throws(() => Telemetry.scalarSetMaximum(UINT_SCALAR, "unexpected value"),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Setting the scalar to an unexpected value type must throw.");
- // The stored value must not be compromised.
- checkScalar(1);
-});
-
-add_task(function* test_stringScalar() {
- let checkExpectedString = (expectedString) => {
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(scalars[STRING_SCALAR], expectedString,
- STRING_SCALAR + " must contain the expected string value.");
- };
-
- Telemetry.clearScalars();
-
- // Let's check simple strings...
- let expected = "test string";
- Telemetry.scalarSet(STRING_SCALAR, expected);
- checkExpectedString(expected);
- expected = "漢語";
- Telemetry.scalarSet(STRING_SCALAR, expected);
- checkExpectedString(expected);
-
- // We have some unsupported operations for strings.
- Assert.throws(() => Telemetry.scalarAdd(STRING_SCALAR, 1),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarAdd(STRING_SCALAR, "string value"),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarSetMaximum(STRING_SCALAR, 1),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarSetMaximum(STRING_SCALAR, "string value"),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarSet(STRING_SCALAR, 1),
- /NS_ERROR_ILLEGAL_VALUE/,
- "The string scalar must throw if we're not setting a string.");
-
- // Try to set the scalar to a string longer than the maximum length limit.
- const LONG_STRING = "browser.qaxfiuosnzmhlg.rpvxicawolhtvmbkpnludhedobxvkjwqyeyvmv";
- Telemetry.scalarSet(STRING_SCALAR, LONG_STRING);
- checkExpectedString(LONG_STRING.substr(0, 50));
-});
-
-add_task(function* test_booleanScalar() {
- let checkExpectedBool = (expectedBoolean) => {
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(scalars[BOOLEAN_SCALAR], expectedBoolean,
- BOOLEAN_SCALAR + " must contain the expected boolean value.");
- };
-
- Telemetry.clearScalars();
-
- // Set a test boolean value.
- let expected = false;
- Telemetry.scalarSet(BOOLEAN_SCALAR, expected);
- checkExpectedBool(expected);
- expected = true;
- Telemetry.scalarSet(BOOLEAN_SCALAR, expected);
- checkExpectedBool(expected);
-
- // Check that setting a numeric value implicitly converts to boolean.
- Telemetry.scalarSet(BOOLEAN_SCALAR, 1);
- checkExpectedBool(true);
- Telemetry.scalarSet(BOOLEAN_SCALAR, 0);
- checkExpectedBool(false);
- Telemetry.scalarSet(BOOLEAN_SCALAR, 1.0);
- checkExpectedBool(true);
- Telemetry.scalarSet(BOOLEAN_SCALAR, 0.0);
- checkExpectedBool(false);
-
- // Check that unsupported operations for booleans throw.
- Assert.throws(() => Telemetry.scalarAdd(BOOLEAN_SCALAR, 1),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarAdd(BOOLEAN_SCALAR, "string value"),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarSetMaximum(BOOLEAN_SCALAR, 1),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarSetMaximum(BOOLEAN_SCALAR, "string value"),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
- Assert.throws(() => Telemetry.scalarSet(BOOLEAN_SCALAR, "true"),
- /NS_ERROR_ILLEGAL_VALUE/,
- "The boolean scalar must throw if we're not setting a boolean.");
-});
-
-add_task(function* test_scalarRecording() {
- const OPTIN_SCALAR = "telemetry.test.release_optin";
- const OPTOUT_SCALAR = "telemetry.test.release_optout";
-
- let checkValue = (scalarName, expectedValue) => {
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(scalars[scalarName], expectedValue,
- scalarName + " must contain the expected value.");
- };
-
- let checkNotSerialized = (scalarName) => {
- const scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.ok(!(scalarName in scalars), scalarName + " was not recorded.");
- };
-
- Telemetry.canRecordBase = false;
- Telemetry.canRecordExtended = false;
- Telemetry.clearScalars();
-
- // Check that no scalar is recorded if both base and extended recording are off.
- Telemetry.scalarSet(OPTOUT_SCALAR, 3);
- Telemetry.scalarSet(OPTIN_SCALAR, 3);
- checkNotSerialized(OPTOUT_SCALAR);
- checkNotSerialized(OPTIN_SCALAR);
-
- // Check that opt-out scalars are recorded, while opt-in are not.
- Telemetry.canRecordBase = true;
- Telemetry.scalarSet(OPTOUT_SCALAR, 3);
- Telemetry.scalarSet(OPTIN_SCALAR, 3);
- checkValue(OPTOUT_SCALAR, 3);
- checkNotSerialized(OPTIN_SCALAR);
-
- // Check that both opt-out and opt-in scalars are recorded.
- Telemetry.canRecordExtended = true;
- Telemetry.scalarSet(OPTOUT_SCALAR, 5);
- Telemetry.scalarSet(OPTIN_SCALAR, 6);
- checkValue(OPTOUT_SCALAR, 5);
- checkValue(OPTIN_SCALAR, 6);
-});
-
-add_task(function* test_keyedScalarRecording() {
- const OPTIN_SCALAR = "telemetry.test.keyed_release_optin";
- const OPTOUT_SCALAR = "telemetry.test.keyed_release_optout";
- const testKey = "policy_key";
-
- let checkValue = (scalarName, expectedValue) => {
- const scalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(scalars[scalarName][testKey], expectedValue,
- scalarName + " must contain the expected value.");
- };
-
- let checkNotSerialized = (scalarName) => {
- const scalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.ok(!(scalarName in scalars), scalarName + " was not recorded.");
- };
-
- Telemetry.canRecordBase = false;
- Telemetry.canRecordExtended = false;
- Telemetry.clearScalars();
-
- // Check that no scalar is recorded if both base and extended recording are off.
- Telemetry.keyedScalarSet(OPTOUT_SCALAR, testKey, 3);
- Telemetry.keyedScalarSet(OPTIN_SCALAR, testKey, 3);
- checkNotSerialized(OPTOUT_SCALAR);
- checkNotSerialized(OPTIN_SCALAR);
-
- // Check that opt-out scalars are recorded, while opt-in are not.
- Telemetry.canRecordBase = true;
- Telemetry.keyedScalarSet(OPTOUT_SCALAR, testKey, 3);
- Telemetry.keyedScalarSet(OPTIN_SCALAR, testKey, 3);
- checkValue(OPTOUT_SCALAR, 3);
- checkNotSerialized(OPTIN_SCALAR);
-
- // Check that both opt-out and opt-in scalars are recorded.
- Telemetry.canRecordExtended = true;
- Telemetry.keyedScalarSet(OPTOUT_SCALAR, testKey, 5);
- Telemetry.keyedScalarSet(OPTIN_SCALAR, testKey, 6);
- checkValue(OPTOUT_SCALAR, 5);
- checkValue(OPTIN_SCALAR, 6);
-});
-
-add_task(function* test_subsession() {
- Telemetry.clearScalars();
-
- // Set the scalars to a known value.
- Telemetry.scalarSet(UINT_SCALAR, 3785);
- Telemetry.scalarSet(STRING_SCALAR, "some value");
- Telemetry.scalarSet(BOOLEAN_SCALAR, false);
- Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, "some_random_key", 12);
-
- // Get a snapshot and reset the subsession. The value we set must be there.
- let scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true);
- let keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true);
-
- Assert.equal(scalars[UINT_SCALAR], 3785,
- UINT_SCALAR + " must contain the expected value.");
- Assert.equal(scalars[STRING_SCALAR], "some value",
- STRING_SCALAR + " must contain the expected value.");
- Assert.equal(scalars[BOOLEAN_SCALAR], false,
- BOOLEAN_SCALAR + " must contain the expected value.");
- Assert.equal(keyedScalars[KEYED_UINT_SCALAR]["some_random_key"], 12,
- KEYED_UINT_SCALAR + " must contain the expected value.");
-
- // Get a new snapshot and reset the subsession again. Since no new value
- // was set, the scalars should not be reported.
- scalars =
- Telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true);
- keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true);
-
- Assert.ok(!(UINT_SCALAR in scalars), UINT_SCALAR + " must be empty and not reported.");
- Assert.ok(!(STRING_SCALAR in scalars), STRING_SCALAR + " must be empty and not reported.");
- Assert.ok(!(BOOLEAN_SCALAR in scalars), BOOLEAN_SCALAR + " must be empty and not reported.");
- Assert.ok(!(KEYED_UINT_SCALAR in keyedScalars), KEYED_UINT_SCALAR + " must be empty and not reported.");
-});
-
-add_task(function* test_keyed_uint() {
- Telemetry.clearScalars();
-
- const KEYS = [ "a_key", "another_key", "third_key" ];
- let expectedValues = [ 1, 1, 1 ];
-
- // Set all the keys to a baseline value.
- for (let key of KEYS) {
- Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, key, 1);
- }
-
- // Increment only one key.
- Telemetry.keyedScalarAdd(KEYED_UINT_SCALAR, KEYS[1], 1);
- expectedValues[1]++;
-
- // Use SetMaximum on the third key.
- Telemetry.keyedScalarSetMaximum(KEYED_UINT_SCALAR, KEYS[2], 37);
- expectedValues[2] = 37;
-
- // Get a snapshot of the scalars and make sure the keys contain
- // the correct values.
- const keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- for (let k = 0; k < 3; k++) {
- const keyName = KEYS[k];
- Assert.equal(keyedScalars[KEYED_UINT_SCALAR][keyName], expectedValues[k],
- KEYED_UINT_SCALAR + "." + keyName + " must contain the correct value.");
- }
-
- // Are we still throwing when doing unsupported things on uint keyed scalars?
- // Just test one single unsupported operation, the other are covered in the plain
- // unsigned scalar test.
- Assert.throws(() => Telemetry.scalarSet(KEYED_UINT_SCALAR, "new_key", "unexpected value"),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Setting the scalar to an unexpected value type must throw.");
-});
-
-add_task(function* test_keyed_boolean() {
- Telemetry.clearScalars();
-
- const KEYED_BOOLEAN_TYPE = "telemetry.test.keyed_boolean_kind";
- const first_key = "first_key";
- const second_key = "second_key";
-
- // Set the initial values.
- Telemetry.keyedScalarSet(KEYED_BOOLEAN_TYPE, first_key, true);
- Telemetry.keyedScalarSet(KEYED_BOOLEAN_TYPE, second_key, false);
-
- // Get a snapshot of the scalars and make sure the keys contain
- // the correct values.
- let keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(keyedScalars[KEYED_BOOLEAN_TYPE][first_key], true,
- "The key must contain the expected value.");
- Assert.equal(keyedScalars[KEYED_BOOLEAN_TYPE][second_key], false,
- "The key must contain the expected value.");
-
- // Now flip the values and make sure we get the expected values back.
- Telemetry.keyedScalarSet(KEYED_BOOLEAN_TYPE, first_key, false);
- Telemetry.keyedScalarSet(KEYED_BOOLEAN_TYPE, second_key, true);
-
- keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(keyedScalars[KEYED_BOOLEAN_TYPE][first_key], false,
- "The key must contain the expected value.");
- Assert.equal(keyedScalars[KEYED_BOOLEAN_TYPE][second_key], true,
- "The key must contain the expected value.");
-
- // Are we still throwing when doing unsupported things on a boolean keyed scalars?
- // Just test one single unsupported operation, the other are covered in the plain
- // boolean scalar test.
- Assert.throws(() => Telemetry.keyedScalarAdd(KEYED_BOOLEAN_TYPE, "somehey", 1),
- /NS_ERROR_NOT_AVAILABLE/,
- "Using an unsupported operation must throw.");
-});
-
-add_task(function* test_keyed_keys_length() {
- Telemetry.clearScalars();
-
- const LONG_KEY_STRING =
- "browser.qaxfiuosnzmhlg.rpvxicawolhtvmbkpnludhedobxvkjwqyeyvmv.somemoresowereach70chars";
- const NORMAL_KEY = "a_key";
-
- // Set the value for a key within the length limits.
- Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, NORMAL_KEY, 1);
-
- // Now try to set and modify the value for a very long key.
- Assert.throws(() => Telemetry.keyedScalarAdd(KEYED_UINT_SCALAR, LONG_KEY_STRING, 10),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Using keys longer than 70 characters must throw.");
- Assert.throws(() => Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, LONG_KEY_STRING, 1),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Using keys longer than 70 characters must throw.");
- Assert.throws(() => Telemetry.keyedScalarSetMaximum(KEYED_UINT_SCALAR, LONG_KEY_STRING, 10),
- /NS_ERROR_ILLEGAL_VALUE/,
- "Using keys longer than 70 characters must throw.");
-
- // Make sure the key with the right length contains the expected value.
- let keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- Assert.equal(Object.keys(keyedScalars[KEYED_UINT_SCALAR]).length, 1,
- "The keyed scalar must contain exactly 1 key.");
- Assert.ok(NORMAL_KEY in keyedScalars[KEYED_UINT_SCALAR],
- "The keyed scalar must contain the expected key.");
- Assert.equal(keyedScalars[KEYED_UINT_SCALAR][NORMAL_KEY], 1,
- "The key must contain the expected value.");
- Assert.ok(!(LONG_KEY_STRING in keyedScalars[KEYED_UINT_SCALAR]),
- "The data for the long key should not have been recorded.");
-});
-
-add_task(function* test_keyed_max_keys() {
- Telemetry.clearScalars();
-
- // Generate the names for the first 100 keys.
- let keyNamesSet = new Set();
- for (let k = 0; k < 100; k++) {
- keyNamesSet.add("key_" + k);
- }
-
- // Add 100 keys to an histogram and set their initial value.
- let valueToSet = 0;
- keyNamesSet.forEach(keyName => {
- Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, keyName, valueToSet++);
- });
-
- // Perform some operations on the 101th key. This should throw, as
- // we're not allowed to have more than 100 keys.
- const LAST_KEY_NAME = "overflowing_key";
- Assert.throws(() => Telemetry.keyedScalarAdd(KEYED_UINT_SCALAR, LAST_KEY_NAME, 10),
- /NS_ERROR_FAILURE/,
- "Using more than 100 keys must throw.");
- Assert.throws(() => Telemetry.keyedScalarSet(KEYED_UINT_SCALAR, LAST_KEY_NAME, 1),
- /NS_ERROR_FAILURE/,
- "Using more than 100 keys must throw.");
- Assert.throws(() => Telemetry.keyedScalarSetMaximum(KEYED_UINT_SCALAR, LAST_KEY_NAME, 10),
- /NS_ERROR_FAILURE/,
- "Using more than 100 keys must throw.");
-
- // Make sure all the keys except the last one are available and have the correct
- // values.
- let keyedScalars =
- Telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- // Check that the keyed scalar only contain the first 100 keys.
- const reportedKeysSet = new Set(Object.keys(keyedScalars[KEYED_UINT_SCALAR]));
- Assert.ok([...keyNamesSet].filter(x => reportedKeysSet.has(x)) &&
- [...reportedKeysSet].filter(x => keyNamesSet.has(x)),
- "The keyed scalar must contain all the 100 keys, and drop the others.");
-
- // Check that all the keys recorded the expected values.
- let expectedValue = 0;
- keyNamesSet.forEach(keyName => {
- Assert.equal(keyedScalars[KEYED_UINT_SCALAR][keyName], expectedValue++,
- "The key must contain the expected value.");
- });
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetrySend.js b/toolkit/components/telemetry/tests/unit/test_TelemetrySend.js
deleted file mode 100644
index 88ff8cf44..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetrySend.js
+++ /dev/null
@@ -1,427 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-
-// This tests the public Telemetry API for submitting pings.
-
-"use strict";
-
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySend.jsm", this);
-Cu.import("resource://gre/modules/TelemetryUtils.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/Preferences.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-
-const PREF_TELEMETRY_SERVER = "toolkit.telemetry.server";
-
-const MS_IN_A_MINUTE = 60 * 1000;
-
-function countPingTypes(pings) {
- let countByType = new Map();
- for (let p of pings) {
- countByType.set(p.type, 1 + (countByType.get(p.type) || 0));
- }
- return countByType;
-}
-
-function setPingLastModified(id, timestamp) {
- const path = OS.Path.join(TelemetryStorage.pingDirectoryPath, id);
- return OS.File.setDates(path, null, timestamp);
-}
-
-// Mock out the send timer activity.
-function waitForTimer() {
- return new Promise(resolve => {
- fakePingSendTimer((callback, timeout) => {
- resolve([callback, timeout]);
- }, () => {});
- });
-}
-
-// Allow easy faking of readable ping ids.
-// This helps with debugging issues with e.g. ordering in the send logic.
-function fakePingId(type, number) {
- const HEAD = "93bd0011-2c8f-4e1c-bee0-";
- const TAIL = "000000000000";
- const N = String(number);
- const id = HEAD + type + TAIL.slice(type.length, - N.length) + N;
- fakeGeneratePingId(() => id);
- return id;
-}
-
-var checkPingsSaved = Task.async(function* (pingIds) {
- let allFound = true;
- for (let id of pingIds) {
- const path = OS.Path.join(TelemetryStorage.pingDirectoryPath, id);
- let exists = false;
- try {
- exists = yield OS.File.exists(path);
- } catch (ex) {}
-
- if (!exists) {
- dump("checkPingsSaved - failed to find ping: " + path + "\n");
- allFound = false;
- }
- }
-
- return allFound;
-});
-
-function histogramValueCount(h) {
- return h.counts.reduce((a, b) => a + b);
-}
-
-add_task(function* test_setup() {
- // Trigger a proper telemetry init.
- do_get_profile(true);
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
-});
-
-// Test the ping sending logic.
-add_task(function* test_sendPendingPings() {
- const TYPE_PREFIX = "test-sendPendingPings-";
- const TEST_TYPE_A = TYPE_PREFIX + "A";
- const TEST_TYPE_B = TYPE_PREFIX + "B";
-
- const TYPE_A_COUNT = 20;
- const TYPE_B_COUNT = 5;
-
- let histSuccess = Telemetry.getHistogramById("TELEMETRY_SUCCESS");
- let histSendTimeSuccess = Telemetry.getHistogramById("TELEMETRY_SEND_SUCCESS");
- let histSendTimeFail = Telemetry.getHistogramById("TELEMETRY_SEND_FAILURE");
- histSuccess.clear();
- histSendTimeSuccess.clear();
- histSendTimeFail.clear();
-
- // Fake a current date.
- let now = TelemetryUtils.truncateToDays(new Date());
- now = fakeNow(futureDate(now, 10 * 60 * MS_IN_A_MINUTE));
-
- // Enable test-mode for TelemetrySend, otherwise we won't store pending pings
- // before the module is fully initialized later.
- TelemetrySend.setTestModeEnabled(true);
-
- // Submit some pings without the server and telemetry started yet.
- for (let i = 0; i < TYPE_A_COUNT; ++i) {
- fakePingId("a", i);
- const id = yield TelemetryController.submitExternalPing(TEST_TYPE_A, {});
- yield setPingLastModified(id, now.getTime() + (i * 1000));
- }
-
- Assert.equal(TelemetrySend.pendingPingCount, TYPE_A_COUNT,
- "Should have correct pending ping count");
-
- // Submit some more pings of a different type.
- now = fakeNow(futureDate(now, 5 * MS_IN_A_MINUTE));
- for (let i = 0; i < TYPE_B_COUNT; ++i) {
- fakePingId("b", i);
- const id = yield TelemetryController.submitExternalPing(TEST_TYPE_B, {});
- yield setPingLastModified(id, now.getTime() + (i * 1000));
- }
-
- Assert.equal(TelemetrySend.pendingPingCount, TYPE_A_COUNT + TYPE_B_COUNT,
- "Should have correct pending ping count");
-
- Assert.deepEqual(histSuccess.snapshot().counts, [0, 0, 0],
- "Should not have recorded any sending in histograms yet.");
- Assert.equal(histSendTimeSuccess.snapshot().sum, 0,
- "Should not have recorded any sending in histograms yet.");
- Assert.equal(histSendTimeFail.snapshot().sum, 0,
- "Should not have recorded any sending in histograms yet.");
-
- // Now enable sending to the ping server.
- now = fakeNow(futureDate(now, MS_IN_A_MINUTE));
- PingServer.start();
- Preferences.set(PREF_TELEMETRY_SERVER, "http://localhost:" + PingServer.port);
-
- let timerPromise = waitForTimer();
- yield TelemetryController.testReset();
- let [pingSendTimerCallback, pingSendTimeout] = yield timerPromise;
- Assert.ok(!!pingSendTimerCallback, "Should have a timer callback");
-
- // We should have received 10 pings from the first send batch:
- // 5 of type B and 5 of type A, as sending is newest-first.
- // The other pings should be delayed by the 10-pings-per-minute limit.
- let pings = yield PingServer.promiseNextPings(10);
- Assert.equal(TelemetrySend.pendingPingCount, TYPE_A_COUNT - 5,
- "Should have correct pending ping count");
- PingServer.registerPingHandler(() => Assert.ok(false, "Should not have received any pings now"));
- let countByType = countPingTypes(pings);
-
- Assert.equal(countByType.get(TEST_TYPE_B), TYPE_B_COUNT,
- "Should have received the correct amount of type B pings");
- Assert.equal(countByType.get(TEST_TYPE_A), 10 - TYPE_B_COUNT,
- "Should have received the correct amount of type A pings");
-
- Assert.deepEqual(histSuccess.snapshot().counts, [0, 10, 0],
- "Should have recorded sending success in histograms.");
- Assert.equal(histogramValueCount(histSendTimeSuccess.snapshot()), 10,
- "Should have recorded successful send times in histograms.");
- Assert.equal(histogramValueCount(histSendTimeFail.snapshot()), 0,
- "Should not have recorded any failed sending in histograms yet.");
-
- // As we hit the ping send limit and still have pending pings, a send tick should
- // be scheduled in a minute.
- Assert.ok(!!pingSendTimerCallback, "Timer callback should be set");
- Assert.equal(pingSendTimeout, MS_IN_A_MINUTE, "Send tick timeout should be correct");
-
- // Trigger the next tick - we should receive the next 10 type A pings.
- PingServer.resetPingHandler();
- now = fakeNow(futureDate(now, pingSendTimeout));
- timerPromise = waitForTimer();
- pingSendTimerCallback();
- [pingSendTimerCallback, pingSendTimeout] = yield timerPromise;
-
- pings = yield PingServer.promiseNextPings(10);
- PingServer.registerPingHandler(() => Assert.ok(false, "Should not have received any pings now"));
- countByType = countPingTypes(pings);
-
- Assert.equal(countByType.get(TEST_TYPE_A), 10, "Should have received the correct amount of type A pings");
-
- // We hit the ping send limit again and still have pending pings, a send tick should
- // be scheduled in a minute.
- Assert.equal(pingSendTimeout, MS_IN_A_MINUTE, "Send tick timeout should be correct");
-
- // Trigger the next tick - we should receive the remaining type A pings.
- PingServer.resetPingHandler();
- now = fakeNow(futureDate(now, pingSendTimeout));
- yield pingSendTimerCallback();
-
- pings = yield PingServer.promiseNextPings(5);
- PingServer.registerPingHandler(() => Assert.ok(false, "Should not have received any pings now"));
- countByType = countPingTypes(pings);
-
- Assert.equal(countByType.get(TEST_TYPE_A), 5, "Should have received the correct amount of type A pings");
-
- yield TelemetrySend.testWaitOnOutgoingPings();
- PingServer.resetPingHandler();
-});
-
-add_task(function* test_sendDateHeader() {
- fakeNow(new Date(Date.UTC(2011, 1, 1, 11, 0, 0)));
- yield TelemetrySend.reset();
-
- let pingId = yield TelemetryController.submitExternalPing("test-send-date-header", {});
- let req = yield PingServer.promiseNextRequest();
- let ping = decodeRequestPayload(req);
- Assert.equal(req.getHeader("Date"), "Tue, 01 Feb 2011 11:00:00 GMT",
- "Telemetry should send the correct Date header with requests.");
- Assert.equal(ping.id, pingId, "Should have received the correct ping id.");
-});
-
-// Test the backoff timeout behavior after send failures.
-add_task(function* test_backoffTimeout() {
- const TYPE_PREFIX = "test-backoffTimeout-";
- const TEST_TYPE_C = TYPE_PREFIX + "C";
- const TEST_TYPE_D = TYPE_PREFIX + "D";
- const TEST_TYPE_E = TYPE_PREFIX + "E";
-
- let histSuccess = Telemetry.getHistogramById("TELEMETRY_SUCCESS");
- let histSendTimeSuccess = Telemetry.getHistogramById("TELEMETRY_SEND_SUCCESS");
- let histSendTimeFail = Telemetry.getHistogramById("TELEMETRY_SEND_FAILURE");
-
- // Failing a ping send now should trigger backoff behavior.
- let now = fakeNow(2010, 1, 1, 11, 0, 0);
- yield TelemetrySend.reset();
- PingServer.stop();
-
- histSuccess.clear();
- histSendTimeSuccess.clear();
- histSendTimeFail.clear();
-
- fakePingId("c", 0);
- now = fakeNow(futureDate(now, MS_IN_A_MINUTE));
- let sendAttempts = 0;
- let timerPromise = waitForTimer();
- yield TelemetryController.submitExternalPing(TEST_TYPE_C, {});
- let [pingSendTimerCallback, pingSendTimeout] = yield timerPromise;
- Assert.equal(TelemetrySend.pendingPingCount, 1, "Should have one pending ping.");
- ++sendAttempts;
-
- const MAX_BACKOFF_TIMEOUT = 120 * MS_IN_A_MINUTE;
- for (let timeout = 2 * MS_IN_A_MINUTE; timeout <= MAX_BACKOFF_TIMEOUT; timeout *= 2) {
- Assert.ok(!!pingSendTimerCallback, "Should have received a timer callback");
- Assert.equal(pingSendTimeout, timeout, "Send tick timeout should be correct");
-
- let callback = pingSendTimerCallback;
- now = fakeNow(futureDate(now, pingSendTimeout));
- timerPromise = waitForTimer();
- yield callback();
- [pingSendTimerCallback, pingSendTimeout] = yield timerPromise;
- ++sendAttempts;
- }
-
- timerPromise = waitForTimer();
- yield pingSendTimerCallback();
- [pingSendTimerCallback, pingSendTimeout] = yield timerPromise;
- Assert.equal(pingSendTimeout, MAX_BACKOFF_TIMEOUT, "Tick timeout should be capped");
- ++sendAttempts;
-
- Assert.deepEqual(histSuccess.snapshot().counts, [sendAttempts, 0, 0],
- "Should have recorded sending failure in histograms.");
- Assert.equal(histSendTimeSuccess.snapshot().sum, 0,
- "Should not have recorded any sending success in histograms yet.");
- Assert.greater(histSendTimeFail.snapshot().sum, 0,
- "Should have recorded send failure times in histograms.");
- Assert.equal(histogramValueCount(histSendTimeFail.snapshot()), sendAttempts,
- "Should have recorded send failure times in histograms.");
-
- // Submitting a new ping should reset the backoff behavior.
- fakePingId("d", 0);
- now = fakeNow(futureDate(now, MS_IN_A_MINUTE));
- timerPromise = waitForTimer();
- yield TelemetryController.submitExternalPing(TEST_TYPE_D, {});
- [pingSendTimerCallback, pingSendTimeout] = yield timerPromise;
- Assert.equal(pingSendTimeout, 2 * MS_IN_A_MINUTE, "Send tick timeout should be correct");
- sendAttempts += 2;
-
- // With the server running again, we should send out the pending pings immediately
- // when a new ping is submitted.
- PingServer.start();
- TelemetrySend.setServer("http://localhost:" + PingServer.port);
- fakePingId("e", 0);
- now = fakeNow(futureDate(now, MS_IN_A_MINUTE));
- timerPromise = waitForTimer();
- yield TelemetryController.submitExternalPing(TEST_TYPE_E, {});
-
- let pings = yield PingServer.promiseNextPings(3);
- let countByType = countPingTypes(pings);
-
- Assert.equal(countByType.get(TEST_TYPE_C), 1, "Should have received the correct amount of type C pings");
- Assert.equal(countByType.get(TEST_TYPE_D), 1, "Should have received the correct amount of type D pings");
- Assert.equal(countByType.get(TEST_TYPE_E), 1, "Should have received the correct amount of type E pings");
-
- yield TelemetrySend.testWaitOnOutgoingPings();
- Assert.equal(TelemetrySend.pendingPingCount, 0, "Should have no pending pings left");
-
- Assert.deepEqual(histSuccess.snapshot().counts, [sendAttempts, 3, 0],
- "Should have recorded sending failure in histograms.");
- Assert.greater(histSendTimeSuccess.snapshot().sum, 0,
- "Should have recorded sending success in histograms.");
- Assert.equal(histogramValueCount(histSendTimeSuccess.snapshot()), 3,
- "Should have recorded sending success in histograms.");
- Assert.equal(histogramValueCount(histSendTimeFail.snapshot()), sendAttempts,
- "Should have recorded send failure times in histograms.");
-});
-
-add_task(function* test_discardBigPings() {
- const TEST_PING_TYPE = "test-ping-type";
-
- let histSizeExceeded = Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_SEND");
- let histDiscardedSize = Telemetry.getHistogramById("TELEMETRY_DISCARDED_SEND_PINGS_SIZE_MB");
- let histSuccess = Telemetry.getHistogramById("TELEMETRY_SUCCESS");
- let histSendTimeSuccess = Telemetry.getHistogramById("TELEMETRY_SEND_SUCCESS");
- let histSendTimeFail = Telemetry.getHistogramById("TELEMETRY_SEND_FAILURE");
- for (let h of [histSizeExceeded, histDiscardedSize, histSuccess, histSendTimeSuccess, histSendTimeFail]) {
- h.clear();
- }
-
- // Generate a 2MB string and create an oversized payload.
- const OVERSIZED_PAYLOAD = {"data": generateRandomString(2 * 1024 * 1024)};
-
- // Reset the histograms.
- Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_SEND").clear();
- Telemetry.getHistogramById("TELEMETRY_DISCARDED_SEND_PINGS_SIZE_MB").clear();
-
- // Submit a ping of a normal size and check that we don't count it in the histogram.
- yield TelemetryController.submitExternalPing(TEST_PING_TYPE, { test: "test" });
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- Assert.equal(histSizeExceeded.snapshot().sum, 0, "Telemetry must report no oversized ping submitted.");
- Assert.equal(histDiscardedSize.snapshot().sum, 0, "Telemetry must report no oversized pings.");
- Assert.deepEqual(histSuccess.snapshot().counts, [0, 1, 0], "Should have recorded sending success.");
- Assert.equal(histogramValueCount(histSendTimeSuccess.snapshot()), 1, "Should have recorded send success time.");
- Assert.greater(histSendTimeSuccess.snapshot().sum, 0, "Should have recorded send success time.");
- Assert.equal(histogramValueCount(histSendTimeFail.snapshot()), 0, "Should not have recorded send failure time.");
-
- // Submit an oversized ping and check that it gets discarded.
- yield TelemetryController.submitExternalPing(TEST_PING_TYPE, OVERSIZED_PAYLOAD);
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- Assert.equal(histSizeExceeded.snapshot().sum, 1, "Telemetry must report 1 oversized ping submitted.");
- Assert.equal(histDiscardedSize.snapshot().counts[2], 1, "Telemetry must report a 2MB, oversized, ping submitted.");
- Assert.deepEqual(histSuccess.snapshot().counts, [0, 1, 0], "Should have recorded sending success.");
- Assert.equal(histogramValueCount(histSendTimeSuccess.snapshot()), 1, "Should have recorded send success time.");
- Assert.greater(histSendTimeSuccess.snapshot().sum, 0, "Should have recorded send success time.");
- Assert.equal(histogramValueCount(histSendTimeFail.snapshot()), 0, "Should not have recorded send failure time.");
-});
-
-add_task(function* test_evictedOnServerErrors() {
- const TEST_TYPE = "test-evicted";
-
- yield TelemetrySend.reset();
-
- let histEvicted = Telemetry.getHistogramById("TELEMETRY_PING_EVICTED_FOR_SERVER_ERRORS");
- let histSuccess = Telemetry.getHistogramById("TELEMETRY_SUCCESS");
- let histSendTimeSuccess = Telemetry.getHistogramById("TELEMETRY_SEND_SUCCESS");
- let histSendTimeFail = Telemetry.getHistogramById("TELEMETRY_SEND_FAILURE");
- for (let h of [histEvicted, histSuccess, histSendTimeSuccess, histSendTimeFail]) {
- h.clear();
- }
-
- // Write a custom ping handler which will return 403. This will trigger ping eviction
- // on client side.
- PingServer.registerPingHandler((req, res) => {
- res.setStatusLine(null, 403, "Forbidden");
- res.processAsync();
- res.finish();
- });
-
- // Clear the histogram and submit a ping.
- let pingId = yield TelemetryController.submitExternalPing(TEST_TYPE, {});
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- Assert.equal(histEvicted.snapshot().sum, 1,
- "Telemetry must report a ping evicted due to server errors");
- Assert.deepEqual(histSuccess.snapshot().counts, [0, 1, 0]);
- Assert.equal(histogramValueCount(histSendTimeSuccess.snapshot()), 1);
- Assert.greater(histSendTimeSuccess.snapshot().sum, 0);
- Assert.equal(histogramValueCount(histSendTimeFail.snapshot()), 0);
-
- // The ping should not be persisted.
- yield Assert.rejects(TelemetryStorage.loadPendingPing(pingId), "The ping must not be persisted.");
-
- // Reset the ping handler and submit a new ping.
- PingServer.resetPingHandler();
- pingId = yield TelemetryController.submitExternalPing(TEST_TYPE, {});
-
- let ping = yield PingServer.promiseNextPings(1);
- Assert.equal(ping[0].id, pingId, "The correct ping must be received");
-
- // We should not have updated the error histogram.
- yield TelemetrySend.testWaitOnOutgoingPings();
- Assert.equal(histEvicted.snapshot().sum, 1, "Telemetry must report only one ping evicted due to server errors");
- Assert.deepEqual(histSuccess.snapshot().counts, [0, 2, 0]);
- Assert.equal(histogramValueCount(histSendTimeSuccess.snapshot()), 2);
- Assert.equal(histogramValueCount(histSendTimeFail.snapshot()), 0);
-});
-
-// Test that the current, non-persisted pending pings are properly saved on shutdown.
-add_task(function* test_persistCurrentPingsOnShutdown() {
- const TEST_TYPE = "test-persistCurrentPingsOnShutdown";
- const PING_COUNT = 5;
- yield TelemetrySend.reset();
- PingServer.stop();
- Assert.equal(TelemetrySend.pendingPingCount, 0, "Should have no pending pings yet");
-
- // Submit new pings that shouldn't be persisted yet.
- let ids = [];
- for (let i=0; i<5; ++i) {
- ids.push(fakePingId("f", i));
- TelemetryController.submitExternalPing(TEST_TYPE, {});
- }
-
- Assert.equal(TelemetrySend.pendingPingCount, PING_COUNT, "Should have the correct pending ping count");
-
- // Triggering a shutdown should persist the pings.
- yield TelemetrySend.shutdown();
- Assert.ok((yield checkPingsSaved(ids)), "All pending pings should have been persisted");
-
- // After a restart the pings should have been found when scanning.
- yield TelemetrySend.reset();
- Assert.equal(TelemetrySend.pendingPingCount, PING_COUNT, "Should have the correct pending ping count");
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetrySendOldPings.js b/toolkit/components/telemetry/tests/unit/test_TelemetrySendOldPings.js
deleted file mode 100644
index 221b6bcab..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetrySendOldPings.js
+++ /dev/null
@@ -1,547 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-
-/**
- * This test case populates the profile with some fake stored
- * pings, and checks that pending pings are immediatlely sent
- * after delayed init.
- */
-
-"use strict"
-
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/Promise.jsm", this);
-Cu.import("resource://gre/modules/TelemetryStorage.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySend.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-var {OS: {File, Path, Constants}} = Cu.import("resource://gre/modules/osfile.jsm", {});
-
-// We increment TelemetryStorage's MAX_PING_FILE_AGE and
-// OVERDUE_PING_FILE_AGE by 1 minute so that our test pings exceed
-// those points in time, even taking into account file system imprecision.
-const ONE_MINUTE_MS = 60 * 1000;
-const OVERDUE_PING_FILE_AGE = TelemetrySend.OVERDUE_PING_FILE_AGE + ONE_MINUTE_MS;
-
-const PING_SAVE_FOLDER = "saved-telemetry-pings";
-const PING_TIMEOUT_LENGTH = 5000;
-const OVERDUE_PINGS = 6;
-const OLD_FORMAT_PINGS = 4;
-const RECENT_PINGS = 4;
-
-const TOTAL_EXPECTED_PINGS = OVERDUE_PINGS + RECENT_PINGS + OLD_FORMAT_PINGS;
-
-const PREF_FHR_UPLOAD = "datareporting.healthreport.uploadEnabled";
-
-var gCreatedPings = 0;
-var gSeenPings = 0;
-
-/**
- * Creates some Telemetry pings for the and saves them to disk. Each ping gets a
- * unique ID based on an incrementor.
- *
- * @param {Array} aPingInfos An array of ping type objects. Each entry must be an
- * object containing a "num" field for the number of pings to create and
- * an "age" field. The latter representing the age in milliseconds to offset
- * from now. A value of 10 would make the ping 10ms older than now, for
- * example.
- * @returns Promise
- * @resolve an Array with the created pings ids.
- */
-var createSavedPings = Task.async(function* (aPingInfos) {
- let pingIds = [];
- let now = Date.now();
-
- for (let type in aPingInfos) {
- let num = aPingInfos[type].num;
- let age = now - (aPingInfos[type].age || 0);
- for (let i = 0; i < num; ++i) {
- let pingId = yield TelemetryController.addPendingPing("test-ping", {}, { overwrite: true });
- if (aPingInfos[type].age) {
- // savePing writes to the file synchronously, so we're good to
- // modify the lastModifedTime now.
- let filePath = getSavePathForPingId(pingId);
- yield File.setDates(filePath, null, age);
- }
- gCreatedPings++;
- pingIds.push(pingId);
- }
- }
-
- return pingIds;
-});
-
-/**
- * Deletes locally saved pings if they exist.
- *
- * @param aPingIds an Array of ping ids to delete.
- * @returns Promise
- */
-var clearPings = Task.async(function* (aPingIds) {
- for (let pingId of aPingIds) {
- yield TelemetryStorage.removePendingPing(pingId);
- }
-});
-
-/**
- * Fakes the pending pings storage quota.
- * @param {Integer} aPendingQuota The new quota, in bytes.
- */
-function fakePendingPingsQuota(aPendingQuota) {
- let storage = Cu.import("resource://gre/modules/TelemetryStorage.jsm");
- storage.Policy.getPendingPingsQuota = () => aPendingQuota;
-}
-
-/**
- * Returns a handle for the file that a ping should be
- * stored in locally.
- *
- * @returns path
- */
-function getSavePathForPingId(aPingId) {
- return Path.join(Constants.Path.profileDir, PING_SAVE_FOLDER, aPingId);
-}
-
-/**
- * Check if the number of Telemetry pings received by the HttpServer is not equal
- * to aExpectedNum.
- *
- * @param aExpectedNum the number of pings we expect to receive.
- */
-function assertReceivedPings(aExpectedNum) {
- do_check_eq(gSeenPings, aExpectedNum);
-}
-
-/**
- * Throws if any pings with the id in aPingIds is saved locally.
- *
- * @param aPingIds an Array of pings ids to check.
- * @returns Promise
- */
-var assertNotSaved = Task.async(function* (aPingIds) {
- let saved = 0;
- for (let id of aPingIds) {
- let filePath = getSavePathForPingId(id);
- if (yield File.exists(filePath)) {
- saved++;
- }
- }
- if (saved > 0) {
- do_throw("Found " + saved + " unexpected saved pings.");
- }
-});
-
-/**
- * Our handler function for the HttpServer that simply
- * increments the gSeenPings global when it successfully
- * receives and decodes a Telemetry payload.
- *
- * @param aRequest the HTTP request sent from HttpServer.
- */
-function pingHandler(aRequest) {
- gSeenPings++;
-}
-
-add_task(function* test_setup() {
- PingServer.start();
- PingServer.registerPingHandler(pingHandler);
- do_get_profile();
- loadAddonManager("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9.2");
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
- Services.prefs.setCharPref(TelemetryController.Constants.PREF_SERVER,
- "http://localhost:" + PingServer.port);
-});
-
-/**
- * Setup the tests by making sure the ping storage directory is available, otherwise
- * |TelemetryController.testSaveDirectoryToFile| could fail.
- */
-add_task(function* setupEnvironment() {
- // The following tests assume this pref to be true by default.
- Services.prefs.setBoolPref(PREF_FHR_UPLOAD, true);
-
- yield TelemetryController.testSetup();
-
- let directory = TelemetryStorage.pingDirectoryPath;
- yield File.makeDir(directory, { ignoreExisting: true, unixMode: OS.Constants.S_IRWXU });
-
- yield TelemetryStorage.testClearPendingPings();
-});
-
-/**
- * Test that really recent pings are sent on Telemetry initialization.
- */
-add_task(function* test_recent_pings_sent() {
- let pingTypes = [{ num: RECENT_PINGS }];
- yield createSavedPings(pingTypes);
-
- yield TelemetryController.testReset();
- yield TelemetrySend.testWaitOnOutgoingPings();
- assertReceivedPings(RECENT_PINGS);
-
- yield TelemetryStorage.testClearPendingPings();
-});
-
-/**
- * Create an overdue ping in the old format and try to send it.
- */
-add_task(function* test_overdue_old_format() {
- // A test ping in the old, standard format.
- const PING_OLD_FORMAT = {
- slug: "1234567abcd",
- reason: "test-ping",
- payload: {
- info: {
- reason: "test-ping",
- OS: "XPCShell",
- appID: "SomeId",
- appVersion: "1.0",
- appName: "XPCShell",
- appBuildID: "123456789",
- appUpdateChannel: "Test",
- platformBuildID: "987654321",
- },
- },
- };
-
- // A ping with no info section, but with a slug.
- const PING_NO_INFO = {
- slug: "1234-no-info-ping",
- reason: "test-ping",
- payload: {}
- };
-
- // A ping with no payload.
- const PING_NO_PAYLOAD = {
- slug: "5678-no-payload",
- reason: "test-ping",
- };
-
- // A ping with no info and no slug.
- const PING_NO_SLUG = {
- reason: "test-ping",
- payload: {}
- };
-
- const PING_FILES_PATHS = [
- getSavePathForPingId(PING_OLD_FORMAT.slug),
- getSavePathForPingId(PING_NO_INFO.slug),
- getSavePathForPingId(PING_NO_PAYLOAD.slug),
- getSavePathForPingId("no-slug-file"),
- ];
-
- // Write the ping to file and make it overdue.
- yield TelemetryStorage.savePing(PING_OLD_FORMAT, true);
- yield TelemetryStorage.savePing(PING_NO_INFO, true);
- yield TelemetryStorage.savePing(PING_NO_PAYLOAD, true);
- yield TelemetryStorage.savePingToFile(PING_NO_SLUG, PING_FILES_PATHS[3], true);
-
- for (let f in PING_FILES_PATHS) {
- yield File.setDates(PING_FILES_PATHS[f], null, Date.now() - OVERDUE_PING_FILE_AGE);
- }
-
- gSeenPings = 0;
- yield TelemetryController.testReset();
- yield TelemetrySend.testWaitOnOutgoingPings();
- assertReceivedPings(OLD_FORMAT_PINGS);
-
- // |TelemetryStorage.cleanup| doesn't know how to remove a ping with no slug or id,
- // so remove it manually so that the next test doesn't fail.
- yield OS.File.remove(PING_FILES_PATHS[3]);
-
- yield TelemetryStorage.testClearPendingPings();
-});
-
-add_task(function* test_corrupted_pending_pings() {
- const TEST_TYPE = "test_corrupted";
-
- Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_READ").clear();
- Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_PARSE").clear();
-
- // Save a pending ping and get its id.
- let pendingPingId = yield TelemetryController.addPendingPing(TEST_TYPE, {}, {});
-
- // Try to load it: there should be no error.
- yield TelemetryStorage.loadPendingPing(pendingPingId);
-
- let h = Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_READ").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must not report a pending ping load failure");
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_PARSE").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must not report a pending ping parse failure");
-
- // Delete it from the disk, so that its id will be kept in the cache but it will
- // fail loading the file.
- yield OS.File.remove(getSavePathForPingId(pendingPingId));
-
- // Try to load a pending ping which isn't there anymore.
- yield Assert.rejects(TelemetryStorage.loadPendingPing(pendingPingId),
- "Telemetry must fail loading a ping which isn't there");
-
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_READ").snapshot();
- Assert.equal(h.sum, 1, "Telemetry must report a pending ping load failure");
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_PARSE").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must not report a pending ping parse failure");
-
- // Save a new ping, so that it gets in the pending pings cache.
- pendingPingId = yield TelemetryController.addPendingPing(TEST_TYPE, {}, {});
- // Overwrite it with a corrupted JSON file and then try to load it.
- const INVALID_JSON = "{ invalid,JSON { {1}";
- yield OS.File.writeAtomic(getSavePathForPingId(pendingPingId), INVALID_JSON, { encoding: "utf-8" });
-
- // Try to load the ping with the corrupted JSON content.
- yield Assert.rejects(TelemetryStorage.loadPendingPing(pendingPingId),
- "Telemetry must fail loading a corrupted ping");
-
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_READ").snapshot();
- Assert.equal(h.sum, 1, "Telemetry must report a pending ping load failure");
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_LOAD_FAILURE_PARSE").snapshot();
- Assert.equal(h.sum, 1, "Telemetry must report a pending ping parse failure");
-
- let exists = yield OS.File.exists(getSavePathForPingId(pendingPingId));
- Assert.ok(!exists, "The unparseable ping should have been removed");
-
- yield TelemetryStorage.testClearPendingPings();
-});
-
-/**
- * Create some recent and overdue pings and verify that they get sent.
- */
-add_task(function* test_overdue_pings_trigger_send() {
- let pingTypes = [
- { num: RECENT_PINGS },
- { num: OVERDUE_PINGS, age: OVERDUE_PING_FILE_AGE },
- ];
- let pings = yield createSavedPings(pingTypes);
- let recentPings = pings.slice(0, RECENT_PINGS);
- let overduePings = pings.slice(-OVERDUE_PINGS);
-
- yield TelemetryController.testReset();
- yield TelemetrySend.testWaitOnOutgoingPings();
- assertReceivedPings(TOTAL_EXPECTED_PINGS);
-
- yield assertNotSaved(recentPings);
- yield assertNotSaved(overduePings);
-
- Assert.equal(TelemetrySend.overduePingsCount, overduePings.length,
- "Should have tracked the correct amount of overdue pings");
-
- yield TelemetryStorage.testClearPendingPings();
-});
-
-/**
- * Create a ping in the old format, send it, and make sure the request URL contains
- * the correct version query parameter.
- */
-add_task(function* test_overdue_old_format() {
- // A test ping in the old, standard format.
- const PING_OLD_FORMAT = {
- slug: "1234567abcd",
- reason: "test-ping",
- payload: {
- info: {
- reason: "test-ping",
- OS: "XPCShell",
- appID: "SomeId",
- appVersion: "1.0",
- appName: "XPCShell",
- appBuildID: "123456789",
- appUpdateChannel: "Test",
- platformBuildID: "987654321",
- },
- },
- };
-
- const filePath =
- Path.join(Constants.Path.profileDir, PING_SAVE_FOLDER, PING_OLD_FORMAT.slug);
-
- // Write the ping to file and make it overdue.
- yield TelemetryStorage.savePing(PING_OLD_FORMAT, true);
- yield File.setDates(filePath, null, Date.now() - OVERDUE_PING_FILE_AGE);
-
- let receivedPings = 0;
- // Register a new prefix handler to validate the URL.
- PingServer.registerPingHandler(request => {
- // Check that we have a version query parameter in the URL.
- Assert.notEqual(request.queryString, "");
-
- // Make sure the version in the query string matches the old ping format version.
- let params = request.queryString.split("&");
- Assert.ok(params.find(p => p == "v=1"));
-
- receivedPings++;
- });
-
- yield TelemetryController.testReset();
- yield TelemetrySend.testWaitOnOutgoingPings();
- Assert.equal(receivedPings, 1, "We must receive a ping in the old format.");
-
- yield TelemetryStorage.testClearPendingPings();
- PingServer.resetPingHandler();
-});
-
-add_task(function* test_pendingPingsQuota() {
- const PING_TYPE = "foo";
-
- // Disable upload so pings don't get sent and removed from the pending pings directory.
- Services.prefs.setBoolPref(PREF_FHR_UPLOAD, false);
-
- // Remove all the pending pings then startup and wait for the cleanup task to complete.
- // There should be nothing to remove.
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testReset();
- yield TelemetrySend.testWaitOnOutgoingPings();
- yield TelemetryStorage.testPendingQuotaTaskPromise();
-
- // Remove the pending deletion ping generated when flipping FHR upload off.
- yield TelemetryStorage.testClearPendingPings();
-
- let expectedPrunedPings = [];
- let expectedNotPrunedPings = [];
-
- let checkPendingPings = Task.async(function*() {
- // Check that the pruned pings are not on disk anymore.
- for (let prunedPingId of expectedPrunedPings) {
- yield Assert.rejects(TelemetryStorage.loadPendingPing(prunedPingId),
- "Ping " + prunedPingId + " should have been pruned.");
- const pingPath = getSavePathForPingId(prunedPingId);
- Assert.ok(!(yield OS.File.exists(pingPath)), "The ping should not be on the disk anymore.");
- }
-
- // Check that the expected pings are there.
- for (let expectedPingId of expectedNotPrunedPings) {
- Assert.ok((yield TelemetryStorage.loadPendingPing(expectedPingId)),
- "Ping" + expectedPingId + " should be among the pending pings.");
- }
- });
-
- let pendingPingsInfo = [];
- let pingsSizeInBytes = 0;
-
- // Create 10 pings to test the pending pings quota.
- for (let days = 1; days < 11; days++) {
- const date = fakeNow(2010, 1, days, 1, 1, 0);
- const pingId = yield TelemetryController.addPendingPing(PING_TYPE, {}, {});
-
- // Find the size of the ping.
- const pingFilePath = getSavePathForPingId(pingId);
- const pingSize = (yield OS.File.stat(pingFilePath)).size;
- // Add the info at the beginning of the array, so that most recent pings come first.
- pendingPingsInfo.unshift({id: pingId, size: pingSize, timestamp: date.getTime() });
-
- // Set the last modification date.
- yield OS.File.setDates(pingFilePath, null, date.getTime());
-
- // Add it to the pending ping directory size.
- pingsSizeInBytes += pingSize;
- }
-
- // We need to test the pending pings size before we hit the quota, otherwise a special
- // value is recorded.
- Telemetry.getHistogramById("TELEMETRY_PENDING_PINGS_SIZE_MB").clear();
- Telemetry.getHistogramById("TELEMETRY_PENDING_PINGS_EVICTED_OVER_QUOTA").clear();
- Telemetry.getHistogramById("TELEMETRY_PENDING_EVICTING_OVER_QUOTA_MS").clear();
-
- yield TelemetryController.testReset();
- yield TelemetryStorage.testPendingQuotaTaskPromise();
-
- // Check that the correct values for quota probes are reported when no quota is hit.
- let h = Telemetry.getHistogramById("TELEMETRY_PENDING_PINGS_SIZE_MB").snapshot();
- Assert.equal(h.sum, Math.round(pingsSizeInBytes / 1024 / 1024),
- "Telemetry must report the correct pending pings directory size.");
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_PINGS_EVICTED_OVER_QUOTA").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must report 0 evictions if quota is not hit.");
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_EVICTING_OVER_QUOTA_MS").snapshot();
- Assert.equal(h.sum, 0, "Telemetry must report a null elapsed time if quota is not hit.");
-
- // Set the quota to 80% of the space.
- const testQuotaInBytes = pingsSizeInBytes * 0.8;
- fakePendingPingsQuota(testQuotaInBytes);
-
- // The storage prunes pending pings until we reach 90% of the requested storage quota.
- // Based on that, find how many pings should be kept.
- const safeQuotaSize = Math.round(testQuotaInBytes * 0.9);
- let sizeInBytes = 0;
- let pingsWithinQuota = [];
- let pingsOutsideQuota = [];
-
- for (let pingInfo of pendingPingsInfo) {
- sizeInBytes += pingInfo.size;
- if (sizeInBytes >= safeQuotaSize) {
- pingsOutsideQuota.push(pingInfo.id);
- continue;
- }
- pingsWithinQuota.push(pingInfo.id);
- }
-
- expectedNotPrunedPings = pingsWithinQuota;
- expectedPrunedPings = pingsOutsideQuota;
-
- // Reset TelemetryController to start the pending pings cleanup.
- yield TelemetryController.testReset();
- yield TelemetryStorage.testPendingQuotaTaskPromise();
- yield checkPendingPings();
-
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_PINGS_EVICTED_OVER_QUOTA").snapshot();
- Assert.equal(h.sum, pingsOutsideQuota.length,
- "Telemetry must correctly report the over quota pings evicted from the pending pings directory.");
- h = Telemetry.getHistogramById("TELEMETRY_PENDING_PINGS_SIZE_MB").snapshot();
- Assert.equal(h.sum, 17, "Pending pings quota was hit, a special size must be reported.");
-
- // Trigger a cleanup again and make sure we're not removing anything.
- yield TelemetryController.testReset();
- yield TelemetryStorage.testPendingQuotaTaskPromise();
- yield checkPendingPings();
-
- const OVERSIZED_PING_ID = "9b21ec8f-f762-4d28-a2c1-44e1c4694f24";
- // Create a pending oversized ping.
- const OVERSIZED_PING = {
- id: OVERSIZED_PING_ID,
- type: PING_TYPE,
- creationDate: (new Date()).toISOString(),
- // Generate a 2MB string to use as the ping payload.
- payload: generateRandomString(2 * 1024 * 1024),
- };
- yield TelemetryStorage.savePendingPing(OVERSIZED_PING);
-
- // Reset the histograms.
- Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_PENDING").clear();
- Telemetry.getHistogramById("TELEMETRY_DISCARDED_PENDING_PINGS_SIZE_MB").clear();
-
- // Try to manually load the oversized ping.
- yield Assert.rejects(TelemetryStorage.loadPendingPing(OVERSIZED_PING_ID),
- "The oversized ping should have been pruned.");
- Assert.ok(!(yield OS.File.exists(getSavePathForPingId(OVERSIZED_PING_ID))),
- "The ping should not be on the disk anymore.");
-
- // Make sure we're correctly updating the related histograms.
- h = Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_PENDING").snapshot();
- Assert.equal(h.sum, 1, "Telemetry must report 1 oversized ping in the pending pings directory.");
- h = Telemetry.getHistogramById("TELEMETRY_DISCARDED_PENDING_PINGS_SIZE_MB").snapshot();
- Assert.equal(h.counts[2], 1, "Telemetry must report a 2MB, oversized, ping.");
-
- // Save the ping again to check if it gets pruned when scanning the pings directory.
- yield TelemetryStorage.savePendingPing(OVERSIZED_PING);
- expectedPrunedPings.push(OVERSIZED_PING_ID);
-
- // Scan the pending pings directory.
- yield TelemetryController.testReset();
- yield TelemetryStorage.testPendingQuotaTaskPromise();
- yield checkPendingPings();
-
- // Make sure we're correctly updating the related histograms.
- h = Telemetry.getHistogramById("TELEMETRY_PING_SIZE_EXCEEDED_PENDING").snapshot();
- Assert.equal(h.sum, 2, "Telemetry must report 1 oversized ping in the pending pings directory.");
- h = Telemetry.getHistogramById("TELEMETRY_DISCARDED_PENDING_PINGS_SIZE_MB").snapshot();
- Assert.equal(h.counts[2], 2, "Telemetry must report two 2MB, oversized, pings.");
-
- Services.prefs.setBoolPref(PREF_FHR_UPLOAD, true);
-});
-
-add_task(function* teardown() {
- yield PingServer.stop();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js b/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
deleted file mode 100644
index 698133162..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
+++ /dev/null
@@ -1,2029 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
-*/
-/* This testcase triggers two telemetry pings.
- *
- * Telemetry code keeps histograms of past telemetry pings. The first
- * ping populates these histograms. One of those histograms is then
- * checked in the second request.
- */
-
-Cu.import("resource://services-common/utils.js");
-Cu.import("resource://gre/modules/ClientID.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/LightweightThemeManager.jsm", this);
-Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-Cu.import("resource://gre/modules/TelemetryStorage.jsm", this);
-Cu.import("resource://gre/modules/TelemetryEnvironment.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySend.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-Cu.import("resource://gre/modules/Promise.jsm", this);
-Cu.import("resource://gre/modules/Preferences.jsm");
-Cu.import("resource://gre/modules/osfile.jsm", this);
-
-const PING_FORMAT_VERSION = 4;
-const PING_TYPE_MAIN = "main";
-const PING_TYPE_SAVED_SESSION = "saved-session";
-
-const REASON_ABORTED_SESSION = "aborted-session";
-const REASON_SAVED_SESSION = "saved-session";
-const REASON_SHUTDOWN = "shutdown";
-const REASON_TEST_PING = "test-ping";
-const REASON_DAILY = "daily";
-const REASON_ENVIRONMENT_CHANGE = "environment-change";
-
-const PLATFORM_VERSION = "1.9.2";
-const APP_VERSION = "1";
-const APP_ID = "xpcshell@tests.mozilla.org";
-const APP_NAME = "XPCShell";
-
-const IGNORE_HISTOGRAM_TO_CLONE = "MEMORY_HEAP_ALLOCATED";
-const IGNORE_CLONED_HISTOGRAM = "test::ignore_me_also";
-const ADDON_NAME = "Telemetry test addon";
-const ADDON_HISTOGRAM = "addon-histogram";
-// Add some unicode characters here to ensure that sending them works correctly.
-const SHUTDOWN_TIME = 10000;
-const FAILED_PROFILE_LOCK_ATTEMPTS = 2;
-
-// Constants from prio.h for nsIFileOutputStream.init
-const PR_WRONLY = 0x2;
-const PR_CREATE_FILE = 0x8;
-const PR_TRUNCATE = 0x20;
-const RW_OWNER = parseInt("0600", 8);
-
-const NUMBER_OF_THREADS_TO_LAUNCH = 30;
-var gNumberOfThreadsLaunched = 0;
-
-const MS_IN_ONE_HOUR = 60 * 60 * 1000;
-const MS_IN_ONE_DAY = 24 * MS_IN_ONE_HOUR;
-
-const PREF_BRANCH = "toolkit.telemetry.";
-const PREF_SERVER = PREF_BRANCH + "server";
-const PREF_FHR_UPLOAD_ENABLED = "datareporting.healthreport.uploadEnabled";
-
-const DATAREPORTING_DIR = "datareporting";
-const ABORTED_PING_FILE_NAME = "aborted-session-ping";
-const ABORTED_SESSION_UPDATE_INTERVAL_MS = 5 * 60 * 1000;
-
-XPCOMUtils.defineLazyGetter(this, "DATAREPORTING_PATH", function() {
- return OS.Path.join(OS.Constants.Path.profileDir, DATAREPORTING_DIR);
-});
-
-var gClientID = null;
-var gMonotonicNow = 0;
-
-function generateUUID() {
- let str = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID().toString();
- // strip {}
- return str.substring(1, str.length - 1);
-}
-
-function truncateDateToDays(date) {
- return new Date(date.getFullYear(),
- date.getMonth(),
- date.getDate(),
- 0, 0, 0, 0);
-}
-
-function sendPing() {
- TelemetrySession.gatherStartup();
- if (PingServer.started) {
- TelemetrySend.setServer("http://localhost:" + PingServer.port);
- return TelemetrySession.testPing();
- }
- TelemetrySend.setServer("http://doesnotexist");
- return TelemetrySession.testPing();
-}
-
-function fakeGenerateUUID(sessionFunc, subsessionFunc) {
- let session = Cu.import("resource://gre/modules/TelemetrySession.jsm");
- session.Policy.generateSessionUUID = sessionFunc;
- session.Policy.generateSubsessionUUID = subsessionFunc;
-}
-
-function fakeIdleNotification(topic) {
- let session = Cu.import("resource://gre/modules/TelemetrySession.jsm");
- return session.TelemetryScheduler.observe(null, topic, null);
-}
-
-function setupTestData() {
-
- Services.startup.interrupted = true;
- Telemetry.registerAddonHistogram(ADDON_NAME, ADDON_HISTOGRAM,
- Telemetry.HISTOGRAM_LINEAR,
- 1, 5, 6);
- let h1 = Telemetry.getAddonHistogram(ADDON_NAME, ADDON_HISTOGRAM);
- h1.add(1);
- let h2 = Telemetry.getHistogramById("TELEMETRY_TEST_COUNT");
- h2.add();
-
- let k1 = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_COUNT");
- k1.add("a");
- k1.add("a");
- k1.add("b");
-}
-
-function getSavedPingFile(basename) {
- let tmpDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let pingFile = tmpDir.clone();
- pingFile.append(basename);
- if (pingFile.exists()) {
- pingFile.remove(true);
- }
- do_register_cleanup(function () {
- try {
- pingFile.remove(true);
- } catch (e) {
- }
- });
- return pingFile;
-}
-
-function checkPingFormat(aPing, aType, aHasClientId, aHasEnvironment) {
- const MANDATORY_PING_FIELDS = [
- "type", "id", "creationDate", "version", "application", "payload"
- ];
-
- const APPLICATION_TEST_DATA = {
- buildId: gAppInfo.appBuildID,
- name: APP_NAME,
- version: APP_VERSION,
- vendor: "Mozilla",
- platformVersion: PLATFORM_VERSION,
- xpcomAbi: "noarch-spidermonkey",
- };
-
- // Check that the ping contains all the mandatory fields.
- for (let f of MANDATORY_PING_FIELDS) {
- Assert.ok(f in aPing, f + "must be available.");
- }
-
- Assert.equal(aPing.type, aType, "The ping must have the correct type.");
- Assert.equal(aPing.version, PING_FORMAT_VERSION, "The ping must have the correct version.");
-
- // Test the application section.
- for (let f in APPLICATION_TEST_DATA) {
- Assert.equal(aPing.application[f], APPLICATION_TEST_DATA[f],
- f + " must have the correct value.");
- }
-
- // We can't check the values for channel and architecture. Just make
- // sure they are in.
- Assert.ok("architecture" in aPing.application,
- "The application section must have an architecture field.");
- Assert.ok("channel" in aPing.application,
- "The application section must have a channel field.");
-
- // Check the clientId and environment fields, as needed.
- Assert.equal("clientId" in aPing, aHasClientId);
- Assert.equal("environment" in aPing, aHasEnvironment);
-}
-
-function checkPayloadInfo(data) {
- const ALLOWED_REASONS = [
- "environment-change", "shutdown", "daily", "saved-session", "test-ping"
- ];
- let numberCheck = arg => { return (typeof arg == "number"); };
- let positiveNumberCheck = arg => { return numberCheck(arg) && (arg >= 0); };
- let stringCheck = arg => { return (typeof arg == "string") && (arg != ""); };
- let revisionCheck = arg => {
- return (Services.appinfo.isOfficial) ? stringCheck(arg) : (typeof arg == "string");
- };
- let uuidCheck = arg => {
- return UUID_REGEX.test(arg);
- };
- let isoDateCheck = arg => {
- // We expect use of this version of the ISO format:
- // 2015-04-12T18:51:19.1+00:00
- const isoDateRegEx = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+[+-]\d{2}:\d{2}$/;
- return stringCheck(arg) && !Number.isNaN(Date.parse(arg)) &&
- isoDateRegEx.test(arg);
- };
-
- const EXPECTED_INFO_FIELDS_TYPES = {
- reason: stringCheck,
- revision: revisionCheck,
- timezoneOffset: numberCheck,
- sessionId: uuidCheck,
- subsessionId: uuidCheck,
- // Special cases: previousSessionId and previousSubsessionId are null on first run.
- previousSessionId: (arg) => { return (arg) ? uuidCheck(arg) : true; },
- previousSubsessionId: (arg) => { return (arg) ? uuidCheck(arg) : true; },
- subsessionCounter: positiveNumberCheck,
- profileSubsessionCounter: positiveNumberCheck,
- sessionStartDate: isoDateCheck,
- subsessionStartDate: isoDateCheck,
- subsessionLength: positiveNumberCheck,
- };
-
- for (let f in EXPECTED_INFO_FIELDS_TYPES) {
- Assert.ok(f in data, f + " must be available.");
-
- let checkFunc = EXPECTED_INFO_FIELDS_TYPES[f];
- Assert.ok(checkFunc(data[f]),
- f + " must have the correct type and valid data " + data[f]);
- }
-
- // Previous buildId is not mandatory.
- if (data.previousBuildId) {
- Assert.ok(stringCheck(data.previousBuildId));
- }
-
- Assert.ok(ALLOWED_REASONS.find(r => r == data.reason),
- "Payload must contain an allowed reason.");
-
- Assert.ok(Date.parse(data.subsessionStartDate) >= Date.parse(data.sessionStartDate));
- Assert.ok(data.profileSubsessionCounter >= data.subsessionCounter);
- Assert.ok(data.timezoneOffset >= -12*60, "The timezone must be in a valid range.");
- Assert.ok(data.timezoneOffset <= 12*60, "The timezone must be in a valid range.");
-}
-
-function checkScalars(processes) {
- // Check that the scalars section is available in the ping payload.
- const parentProcess = processes.parent;
- Assert.ok("scalars" in parentProcess, "The scalars section must be available in the parent process.");
- Assert.ok("keyedScalars" in parentProcess, "The keyedScalars section must be available in the parent process.");
- Assert.equal(typeof parentProcess.scalars, "object", "The scalars entry must be an object.");
- Assert.equal(typeof parentProcess.keyedScalars, "object", "The keyedScalars entry must be an object.");
-
- let checkScalar = function(scalar) {
- // Check if the value is of a supported type.
- const valueType = typeof(scalar);
- switch (valueType) {
- case "string":
- Assert.ok(scalar.length <= 50,
- "String values can't have more than 50 characters");
- break;
- case "number":
- Assert.ok(scalar >= 0,
- "We only support unsigned integer values in scalars.");
- break;
- case "boolean":
- Assert.ok(true,
- "Boolean scalar found.");
- break;
- default:
- Assert.ok(false,
- name + " contains an unsupported value type (" + valueType + ")");
- }
- }
-
- // Check that we have valid scalar entries.
- const scalars = parentProcess.scalars;
- for (let name in scalars) {
- Assert.equal(typeof name, "string", "Scalar names must be strings.");
- checkScalar(scalar[name]);
- }
-
- // Check that we have valid keyed scalar entries.
- const keyedScalars = parentProcess.keyedScalars;
- for (let name in keyedScalars) {
- Assert.equal(typeof name, "string", "Scalar names must be strings.");
- Assert.ok(Object.keys(keyedScalars[name]).length,
- "The reported keyed scalars must contain at least 1 key.");
- for (let key in keyedScalars[name]) {
- Assert.equal(typeof key, "string", "Keyed scalar keys must be strings.");
- Assert.ok(key.length <= 70, "Keyed scalar keys can't have more than 70 characters.");
- checkScalar(scalar[name][key]);
- }
- }
-}
-
-function checkEvents(processes) {
- // Check that the events section is available in the ping payload.
- const parent = processes.parent;
- Assert.ok("events" in parent, "The events section must be available in the parent process.");
-
- // Check that the events section has the right format.
- Assert.ok(Array.isArray(parent.events), "The events entry must be an array.");
- for (let [ts, category, method, object, value, extra] of parent.events) {
- Assert.equal(typeof(ts), "number", "Timestamp field should be a number.");
- Assert.greaterOrEqual(ts, 0, "Timestamp should be >= 0.");
-
- Assert.equal(typeof(category), "string", "Category should have the right type.");
- Assert.lessOrEqual(category.length, 100, "Category should have the right string length.");
-
- Assert.equal(typeof(method), "string", "Method should have the right type.");
- Assert.lessOrEqual(method.length, 40, "Method should have the right string length.");
-
- Assert.equal(typeof(object), "string", "Object should have the right type.");
- Assert.lessOrEqual(object.length, 40, "Object should have the right string length.");
-
- Assert.ok(value === null || typeof(value) === "string",
- "Value should be null or a string.");
- if (value) {
- Assert.lessOrEqual(value.length, 100, "Value should have the right string length.");
- }
-
- Assert.ok(extra === null || typeof(extra) === "object",
- "Extra should be null or an object.");
- if (extra) {
- let keys = Object.keys(extra);
- let keyTypes = keys.map(k => typeof(k));
- Assert.lessOrEqual(keys.length, 20, "Should not have too many extra keys.");
- Assert.ok(keyTypes.every(t => t === "string"),
- "All extra keys should be strings.");
- Assert.ok(keys.every(k => k.length <= 20),
- "All extra keys should have the right string length.");
-
- let values = Object.values(extra);
- let valueTypes = values.map(v => typeof(v));
- Assert.ok(valueTypes.every(t => t === "string"),
- "All extra values should be strings.");
- Assert.ok(values.every(v => v.length <= 100),
- "All extra values should have the right string length.");
- }
- }
-}
-
-function checkPayload(payload, reason, successfulPings, savedPings) {
- Assert.ok("info" in payload, "Payload must contain an info section.");
- checkPayloadInfo(payload.info);
-
- Assert.ok(payload.simpleMeasurements.totalTime >= 0);
- Assert.ok(payload.simpleMeasurements.uptime >= 0);
- Assert.equal(payload.simpleMeasurements.startupInterrupted, 1);
- Assert.equal(payload.simpleMeasurements.shutdownDuration, SHUTDOWN_TIME);
- Assert.equal(payload.simpleMeasurements.savedPings, savedPings);
- Assert.ok("maximalNumberOfConcurrentThreads" in payload.simpleMeasurements);
- Assert.ok(payload.simpleMeasurements.maximalNumberOfConcurrentThreads >= gNumberOfThreadsLaunched);
-
- let activeTicks = payload.simpleMeasurements.activeTicks;
- Assert.ok(activeTicks >= 0);
-
- Assert.equal(payload.simpleMeasurements.failedProfileLockCount,
- FAILED_PROFILE_LOCK_ATTEMPTS);
- let profileDirectory = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let failedProfileLocksFile = profileDirectory.clone();
- failedProfileLocksFile.append("Telemetry.FailedProfileLocks.txt");
- Assert.ok(!failedProfileLocksFile.exists());
-
-
- let isWindows = ("@mozilla.org/windows-registry-key;1" in Components.classes);
- if (isWindows) {
- Assert.ok(payload.simpleMeasurements.startupSessionRestoreReadBytes > 0);
- Assert.ok(payload.simpleMeasurements.startupSessionRestoreWriteBytes > 0);
- }
-
- const TELEMETRY_SEND_SUCCESS = "TELEMETRY_SEND_SUCCESS";
- const TELEMETRY_SUCCESS = "TELEMETRY_SUCCESS";
- const TELEMETRY_TEST_FLAG = "TELEMETRY_TEST_FLAG";
- const TELEMETRY_TEST_COUNT = "TELEMETRY_TEST_COUNT";
- const TELEMETRY_TEST_KEYED_FLAG = "TELEMETRY_TEST_KEYED_FLAG";
- const TELEMETRY_TEST_KEYED_COUNT = "TELEMETRY_TEST_KEYED_COUNT";
-
- if (successfulPings > 0) {
- Assert.ok(TELEMETRY_SEND_SUCCESS in payload.histograms);
- }
- Assert.ok(TELEMETRY_TEST_FLAG in payload.histograms);
- Assert.ok(TELEMETRY_TEST_COUNT in payload.histograms);
-
- Assert.ok(!(IGNORE_CLONED_HISTOGRAM in payload.histograms));
-
- // Flag histograms should automagically spring to life.
- const expected_flag = {
- range: [1, 2],
- bucket_count: 3,
- histogram_type: 3,
- values: {0:1, 1:0},
- sum: 0
- };
- let flag = payload.histograms[TELEMETRY_TEST_FLAG];
- Assert.equal(uneval(flag), uneval(expected_flag));
-
- // We should have a test count.
- const expected_count = {
- range: [1, 2],
- bucket_count: 3,
- histogram_type: 4,
- values: {0:1, 1:0},
- sum: 1,
- };
- let count = payload.histograms[TELEMETRY_TEST_COUNT];
- Assert.equal(uneval(count), uneval(expected_count));
-
- // There should be one successful report from the previous telemetry ping.
- if (successfulPings > 0) {
- const expected_tc = {
- range: [1, 2],
- bucket_count: 3,
- histogram_type: 2,
- values: {0:2, 1:successfulPings, 2:0},
- sum: successfulPings
- };
- let tc = payload.histograms[TELEMETRY_SUCCESS];
- Assert.equal(uneval(tc), uneval(expected_tc));
- }
-
- // The ping should include data from memory reporters. We can't check that
- // this data is correct, because we can't control the values returned by the
- // memory reporters. But we can at least check that the data is there.
- //
- // It's important to check for the presence of reporters with a mix of units,
- // because TelemetryController has separate logic for each one. But we can't
- // currently check UNITS_COUNT_CUMULATIVE or UNITS_PERCENTAGE because
- // Telemetry doesn't touch a memory reporter with these units that's
- // available on all platforms.
-
- Assert.ok('MEMORY_JS_GC_HEAP' in payload.histograms); // UNITS_BYTES
- Assert.ok('MEMORY_JS_COMPARTMENTS_SYSTEM' in payload.histograms); // UNITS_COUNT
-
- // We should have included addon histograms.
- Assert.ok("addonHistograms" in payload);
- Assert.ok(ADDON_NAME in payload.addonHistograms);
- Assert.ok(ADDON_HISTOGRAM in payload.addonHistograms[ADDON_NAME]);
-
- Assert.ok(("mainThread" in payload.slowSQL) &&
- ("otherThreads" in payload.slowSQL));
-
- Assert.ok(("IceCandidatesStats" in payload.webrtc) &&
- ("webrtc" in payload.webrtc.IceCandidatesStats));
-
- // Check keyed histogram payload.
-
- Assert.ok("keyedHistograms" in payload);
- let keyedHistograms = payload.keyedHistograms;
- Assert.ok(!(TELEMETRY_TEST_KEYED_FLAG in keyedHistograms));
- Assert.ok(TELEMETRY_TEST_KEYED_COUNT in keyedHistograms);
-
- const expected_keyed_count = {
- "a": {
- range: [1, 2],
- bucket_count: 3,
- histogram_type: 4,
- values: {0:2, 1:0},
- sum: 2,
- },
- "b": {
- range: [1, 2],
- bucket_count: 3,
- histogram_type: 4,
- values: {0:1, 1:0},
- sum: 1,
- },
- };
- Assert.deepEqual(expected_keyed_count, keyedHistograms[TELEMETRY_TEST_KEYED_COUNT]);
-
- Assert.ok("processes" in payload, "The payload must have a processes section.");
- Assert.ok("parent" in payload.processes, "There must be at least a parent process.");
- checkScalars(payload.processes);
- checkEvents(payload.processes);
-}
-
-function writeStringToFile(file, contents) {
- let ostream = Cc["@mozilla.org/network/safe-file-output-stream;1"]
- .createInstance(Ci.nsIFileOutputStream);
- ostream.init(file, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
- RW_OWNER, ostream.DEFER_OPEN);
- ostream.write(contents, contents.length);
- ostream.QueryInterface(Ci.nsISafeOutputStream).finish();
- ostream.close();
-}
-
-function write_fake_shutdown_file() {
- let profileDirectory = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let file = profileDirectory.clone();
- file.append("Telemetry.ShutdownTime.txt");
- let contents = "" + SHUTDOWN_TIME;
- writeStringToFile(file, contents);
-}
-
-function write_fake_failedprofilelocks_file() {
- let profileDirectory = Services.dirsvc.get("ProfD", Ci.nsIFile);
- let file = profileDirectory.clone();
- file.append("Telemetry.FailedProfileLocks.txt");
- let contents = "" + FAILED_PROFILE_LOCK_ATTEMPTS;
- writeStringToFile(file, contents);
-}
-
-add_task(function* test_setup() {
- // Addon manager needs a profile directory
- do_get_profile();
- loadAddonManager(APP_ID, APP_NAME, APP_VERSION, PLATFORM_VERSION);
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
- Services.prefs.setBoolPref(PREF_FHR_UPLOAD_ENABLED, true);
-
- // Make it look like we've previously failed to lock a profile a couple times.
- write_fake_failedprofilelocks_file();
-
- // Make it look like we've shutdown before.
- write_fake_shutdown_file();
-
- let currentMaxNumberOfThreads = Telemetry.maximalNumberOfConcurrentThreads;
- do_check_true(currentMaxNumberOfThreads > 0);
-
- // Try to augment the maximal number of threads currently launched
- let threads = [];
- try {
- for (let i = 0; i < currentMaxNumberOfThreads + 10; ++i) {
- threads.push(Services.tm.newThread(0));
- }
- } catch (ex) {
- // If memory is too low, it is possible that not all threads will be launched.
- }
- gNumberOfThreadsLaunched = threads.length;
-
- do_check_true(Telemetry.maximalNumberOfConcurrentThreads >= gNumberOfThreadsLaunched);
-
- do_register_cleanup(function() {
- threads.forEach(function(thread) {
- thread.shutdown();
- });
- });
-
- yield new Promise(resolve =>
- Telemetry.asyncFetchTelemetryData(wrapWithExceptionHandler(resolve)));
-});
-
-add_task(function* asyncSetup() {
- yield TelemetryController.testSetup();
- // Load the client ID from the client ID provider to check for pings sanity.
- gClientID = yield ClientID.getClientID();
-});
-
-// Ensures that expired histograms are not part of the payload.
-add_task(function* test_expiredHistogram() {
-
- let dummy = Telemetry.getHistogramById("TELEMETRY_TEST_EXPIRED");
-
- dummy.add(1);
-
- do_check_eq(TelemetrySession.getPayload()["histograms"]["TELEMETRY_TEST_EXPIRED"], undefined);
-});
-
-// Sends a ping to a non existing server. If we remove this test, we won't get
-// all the histograms we need in the main ping.
-add_task(function* test_noServerPing() {
- yield sendPing();
- // We need two pings in order to make sure STARTUP_MEMORY_STORAGE_SQLIE histograms
- // are initialised. See bug 1131585.
- yield sendPing();
- // Allowing Telemetry to persist unsent pings as pending. If omitted may cause
- // problems to the consequent tests.
- yield TelemetryController.testShutdown();
-});
-
-// Checks that a sent ping is correctly received by a dummy http server.
-add_task(function* test_simplePing() {
- yield TelemetryStorage.testClearPendingPings();
- PingServer.start();
- Preferences.set(PREF_SERVER, "http://localhost:" + PingServer.port);
-
- let now = new Date(2020, 1, 1, 12, 0, 0);
- let expectedDate = new Date(2020, 1, 1, 0, 0, 0);
- fakeNow(now);
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 5000);
-
- const expectedSessionUUID = "bd314d15-95bf-4356-b682-b6c4a8942202";
- const expectedSubsessionUUID = "3e2e5f6c-74ba-4e4d-a93f-a48af238a8c7";
- fakeGenerateUUID(() => expectedSessionUUID, () => expectedSubsessionUUID);
- yield TelemetryController.testReset();
-
- // Session and subsession start dates are faked during TelemetrySession setup. We can
- // now fake the session duration.
- const SESSION_DURATION_IN_MINUTES = 15;
- fakeNow(new Date(2020, 1, 1, 12, SESSION_DURATION_IN_MINUTES, 0));
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + SESSION_DURATION_IN_MINUTES * 60 * 1000);
-
- yield sendPing();
- let ping = yield PingServer.promiseNextPing();
-
- checkPingFormat(ping, PING_TYPE_MAIN, true, true);
-
- // Check that we get the data we expect.
- let payload = ping.payload;
- Assert.equal(payload.info.sessionId, expectedSessionUUID);
- Assert.equal(payload.info.subsessionId, expectedSubsessionUUID);
- let sessionStartDate = new Date(payload.info.sessionStartDate);
- Assert.equal(sessionStartDate.toISOString(), expectedDate.toISOString());
- let subsessionStartDate = new Date(payload.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), expectedDate.toISOString());
- Assert.equal(payload.info.subsessionLength, SESSION_DURATION_IN_MINUTES * 60);
-
- // Restore the UUID generator so we don't mess with other tests.
- fakeGenerateUUID(generateUUID, generateUUID);
-});
-
-// Saves the current session histograms, reloads them, performs a ping
-// and checks that the dummy http server received both the previously
-// saved ping and the new one.
-add_task(function* test_saveLoadPing() {
- // Let's start out with a defined state.
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testReset();
- PingServer.clearRequests();
-
- // Setup test data and trigger pings.
- setupTestData();
- yield TelemetrySession.testSavePendingPing();
- yield sendPing();
-
- // Get requests received by dummy server.
- const requests = yield PingServer.promiseNextRequests(2);
-
- for (let req of requests) {
- Assert.equal(req.getHeader("content-type"), "application/json; charset=UTF-8",
- "The request must have the correct content-type.");
- }
-
- // We decode both requests to check for the |reason|.
- let pings = Array.from(requests, decodeRequestPayload);
-
- // Check we have the correct two requests. Ordering is not guaranteed. The ping type
- // is encoded in the URL.
- if (pings[0].type != PING_TYPE_MAIN) {
- pings.reverse();
- }
-
- checkPingFormat(pings[0], PING_TYPE_MAIN, true, true);
- checkPayload(pings[0].payload, REASON_TEST_PING, 0, 1);
- checkPingFormat(pings[1], PING_TYPE_SAVED_SESSION, true, true);
- checkPayload(pings[1].payload, REASON_SAVED_SESSION, 0, 0);
-});
-
-add_task(function* test_checkSubsessionScalars() {
- if (gIsAndroid) {
- // We don't support subsessions yet on Android.
- return;
- }
-
- // Clear the scalars.
- Telemetry.clearScalars();
- yield TelemetryController.testReset();
-
- // Set some scalars.
- const UINT_SCALAR = "telemetry.test.unsigned_int_kind";
- const STRING_SCALAR = "telemetry.test.string_kind";
- let expectedUint = 37;
- let expectedString = "Test value. Yay.";
- Telemetry.scalarSet(UINT_SCALAR, expectedUint);
- Telemetry.scalarSet(STRING_SCALAR, expectedString);
-
- // Check that scalars are not available in classic pings but are in subsession
- // pings. Also clear the subsession.
- let classic = TelemetrySession.getPayload();
- let subsession = TelemetrySession.getPayload("environment-change", true);
-
- const TEST_SCALARS = [ UINT_SCALAR, STRING_SCALAR ];
- for (let name of TEST_SCALARS) {
- // Scalar must be reported in subsession pings (e.g. main).
- Assert.ok(name in subsession.processes.parent.scalars,
- name + " must be reported in a subsession ping.");
- }
- // No scalar must be reported in classic pings (e.g. saved-session).
- Assert.ok(Object.keys(classic.processes.parent.scalars).length == 0,
- "Scalars must not be reported in a classic ping.");
-
- // And make sure that we're getting the right values in the
- // subsession ping.
- Assert.equal(subsession.processes.parent.scalars[UINT_SCALAR], expectedUint,
- UINT_SCALAR + " must contain the expected value.");
- Assert.equal(subsession.processes.parent.scalars[STRING_SCALAR], expectedString,
- STRING_SCALAR + " must contain the expected value.");
-
- // Since we cleared the subsession in the last getPayload(), check that
- // breaking subsessions clears the scalars.
- subsession = TelemetrySession.getPayload("environment-change");
- for (let name of TEST_SCALARS) {
- Assert.ok(!(name in subsession.processes.parent.scalars),
- name + " must be cleared with the new subsession.");
- }
-
- // Check if setting the scalars again works as expected.
- expectedUint = 85;
- expectedString = "A creative different value";
- Telemetry.scalarSet(UINT_SCALAR, expectedUint);
- Telemetry.scalarSet(STRING_SCALAR, expectedString);
- subsession = TelemetrySession.getPayload("environment-change");
- Assert.equal(subsession.processes.parent.scalars[UINT_SCALAR], expectedUint,
- UINT_SCALAR + " must contain the expected value.");
- Assert.equal(subsession.processes.parent.scalars[STRING_SCALAR], expectedString,
- STRING_SCALAR + " must contain the expected value.");
-});
-
-add_task(function* test_checkSubsessionEvents() {
- if (gIsAndroid) {
- // We don't support subsessions yet on Android.
- return;
- }
-
- // Clear the events.
- Telemetry.clearEvents();
- yield TelemetryController.testReset();
-
- // Record some events.
- let expected = [
- ["telemetry.test", "test1", "object1", "a", null],
- ["telemetry.test", "test1", "object1", null, {key1: "value"}],
- ];
- for (let event of expected) {
- Telemetry.recordEvent(...event);
- }
-
- // Strip off trailing null values to match the serialized events.
- for (let e of expected) {
- while ((e.length >= 3) && (e[e.length - 1] === null)) {
- e.pop();
- }
- }
-
- // Check that events are not available in classic pings but are in subsession
- // pings. Also clear the subsession.
- let classic = TelemetrySession.getPayload();
- let subsession = TelemetrySession.getPayload("environment-change", true);
-
- Assert.ok("events" in classic.processes.parent, "Should have an events field in classic payload.");
- Assert.ok("events" in subsession.processes.parent, "Should have an events field in subsession payload.");
-
- // They should be empty in the classic payload.
- Assert.deepEqual(classic.processes.parent.events, [], "Events in classic payload should be empty.");
-
- // In the subsession payload, they should contain the recorded test events.
- let events = subsession.processes.parent.events.filter(e => e[1] === "telemetry.test");
- Assert.equal(events.length, expected.length, "Should have the right amount of events in the payload.");
- for (let i = 0; i < expected.length; ++i) {
- Assert.deepEqual(events[i].slice(1), expected[i],
- "Should have the right event data in the ping.");
- }
-
- // As we cleared the subsession above, the events entry should now be empty.
- subsession = TelemetrySession.getPayload("environment-change", false);
- Assert.ok("events" in subsession.processes.parent, "Should have an events field in subsession payload.");
- events = subsession.processes.parent.events.filter(e => e[1] === "telemetry.test");
- Assert.equal(events.length, 0, "Should have no test events in the subsession payload now.");
-});
-
-add_task(function* test_checkSubsessionHistograms() {
- if (gIsAndroid) {
- // We don't support subsessions yet on Android.
- return;
- }
-
- let now = new Date(2020, 1, 1, 12, 0, 0);
- let expectedDate = new Date(2020, 1, 1, 0, 0, 0);
- fakeNow(now);
- yield TelemetryController.testReset();
-
- const COUNT_ID = "TELEMETRY_TEST_COUNT";
- const KEYED_ID = "TELEMETRY_TEST_KEYED_COUNT";
- const count = Telemetry.getHistogramById(COUNT_ID);
- const keyed = Telemetry.getKeyedHistogramById(KEYED_ID);
- const registeredIds =
- new Set(Telemetry.registeredHistograms(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, []));
-
- const stableHistograms = new Set([
- "TELEMETRY_TEST_FLAG",
- "TELEMETRY_TEST_COUNT",
- "TELEMETRY_TEST_RELEASE_OPTOUT",
- "TELEMETRY_TEST_RELEASE_OPTIN",
- "STARTUP_CRASH_DETECTED",
- ]);
-
- const stableKeyedHistograms = new Set([
- "TELEMETRY_TEST_KEYED_FLAG",
- "TELEMETRY_TEST_KEYED_COUNT",
- "TELEMETRY_TEST_KEYED_RELEASE_OPTIN",
- "TELEMETRY_TEST_KEYED_RELEASE_OPTOUT",
- ]);
-
- // Compare the two sets of histograms.
- // The "subsession" histograms should match the registered
- // "classic" histograms. However, histograms can change
- // between us collecting the different payloads, so we only
- // check for deep equality on known stable histograms.
- checkHistograms = (classic, subsession) => {
- for (let id of Object.keys(classic)) {
- if (!registeredIds.has(id)) {
- continue;
- }
-
- Assert.ok(id in subsession);
- if (stableHistograms.has(id)) {
- Assert.deepEqual(classic[id],
- subsession[id]);
- } else {
- Assert.equal(classic[id].histogram_type,
- subsession[id].histogram_type);
- }
- }
- };
-
- // Same as above, except for keyed histograms.
- checkKeyedHistograms = (classic, subsession) => {
- for (let id of Object.keys(classic)) {
- if (!registeredIds.has(id)) {
- continue;
- }
-
- Assert.ok(id in subsession);
- if (stableKeyedHistograms.has(id)) {
- Assert.deepEqual(classic[id],
- subsession[id]);
- }
- }
- };
-
- // Both classic and subsession payload histograms should start the same.
- // The payloads should be identical for now except for the reason.
- count.clear();
- keyed.clear();
- let classic = TelemetrySession.getPayload();
- let subsession = TelemetrySession.getPayload("environment-change");
-
- Assert.equal(classic.info.reason, "gather-payload");
- Assert.equal(subsession.info.reason, "environment-change");
- Assert.ok(!(COUNT_ID in classic.histograms));
- Assert.ok(!(COUNT_ID in subsession.histograms));
- Assert.ok(!(KEYED_ID in classic.keyedHistograms));
- Assert.ok(!(KEYED_ID in subsession.keyedHistograms));
-
- checkHistograms(classic.histograms, subsession.histograms);
- checkKeyedHistograms(classic.keyedHistograms, subsession.keyedHistograms);
-
- // Adding values should get picked up in both.
- count.add(1);
- keyed.add("a", 1);
- keyed.add("b", 1);
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change");
-
- Assert.ok(COUNT_ID in classic.histograms);
- Assert.ok(COUNT_ID in subsession.histograms);
- Assert.ok(KEYED_ID in classic.keyedHistograms);
- Assert.ok(KEYED_ID in subsession.keyedHistograms);
- Assert.equal(classic.histograms[COUNT_ID].sum, 1);
- Assert.equal(classic.keyedHistograms[KEYED_ID]["a"].sum, 1);
- Assert.equal(classic.keyedHistograms[KEYED_ID]["b"].sum, 1);
-
- checkHistograms(classic.histograms, subsession.histograms);
- checkKeyedHistograms(classic.keyedHistograms, subsession.keyedHistograms);
-
- // Values should still reset properly.
- count.clear();
- keyed.clear();
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change");
-
- Assert.ok(!(COUNT_ID in classic.histograms));
- Assert.ok(!(COUNT_ID in subsession.histograms));
- Assert.ok(!(KEYED_ID in classic.keyedHistograms));
- Assert.ok(!(KEYED_ID in subsession.keyedHistograms));
-
- checkHistograms(classic.histograms, subsession.histograms);
- checkKeyedHistograms(classic.keyedHistograms, subsession.keyedHistograms);
-
- // Adding values should get picked up in both.
- count.add(1);
- keyed.add("a", 1);
- keyed.add("b", 1);
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change");
-
- Assert.ok(COUNT_ID in classic.histograms);
- Assert.ok(COUNT_ID in subsession.histograms);
- Assert.ok(KEYED_ID in classic.keyedHistograms);
- Assert.ok(KEYED_ID in subsession.keyedHistograms);
- Assert.equal(classic.histograms[COUNT_ID].sum, 1);
- Assert.equal(classic.keyedHistograms[KEYED_ID]["a"].sum, 1);
- Assert.equal(classic.keyedHistograms[KEYED_ID]["b"].sum, 1);
-
- checkHistograms(classic.histograms, subsession.histograms);
- checkKeyedHistograms(classic.keyedHistograms, subsession.keyedHistograms);
-
- // We should be able to reset only the subsession histograms.
- // First check that "snapshot and clear" still returns the old state...
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change", true);
-
- let subsessionStartDate = new Date(classic.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), expectedDate.toISOString());
- subsessionStartDate = new Date(subsession.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), expectedDate.toISOString());
- checkHistograms(classic.histograms, subsession.histograms);
- checkKeyedHistograms(classic.keyedHistograms, subsession.keyedHistograms);
-
- // ... then check that the next snapshot shows the subsession
- // histograms got reset.
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change");
-
- Assert.ok(COUNT_ID in classic.histograms);
- Assert.ok(COUNT_ID in subsession.histograms);
- Assert.equal(classic.histograms[COUNT_ID].sum, 1);
- Assert.equal(subsession.histograms[COUNT_ID].sum, 0);
-
- Assert.ok(KEYED_ID in classic.keyedHistograms);
- Assert.ok(!(KEYED_ID in subsession.keyedHistograms));
- Assert.equal(classic.keyedHistograms[KEYED_ID]["a"].sum, 1);
- Assert.equal(classic.keyedHistograms[KEYED_ID]["b"].sum, 1);
-
- // Adding values should get picked up in both again.
- count.add(1);
- keyed.add("a", 1);
- keyed.add("b", 1);
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change");
-
- Assert.ok(COUNT_ID in classic.histograms);
- Assert.ok(COUNT_ID in subsession.histograms);
- Assert.equal(classic.histograms[COUNT_ID].sum, 2);
- Assert.equal(subsession.histograms[COUNT_ID].sum, 1);
-
- Assert.ok(KEYED_ID in classic.keyedHistograms);
- Assert.ok(KEYED_ID in subsession.keyedHistograms);
- Assert.equal(classic.keyedHistograms[KEYED_ID]["a"].sum, 2);
- Assert.equal(classic.keyedHistograms[KEYED_ID]["b"].sum, 2);
- Assert.equal(subsession.keyedHistograms[KEYED_ID]["a"].sum, 1);
- Assert.equal(subsession.keyedHistograms[KEYED_ID]["b"].sum, 1);
-});
-
-add_task(function* test_checkSubsessionData() {
- if (gIsAndroid) {
- // We don't support subsessions yet on Android.
- return;
- }
-
- // Keep track of the active ticks count if the session recorder is available.
- let sessionRecorder = TelemetryController.getSessionRecorder();
- let activeTicksAtSubsessionStart = sessionRecorder.activeTicks;
- let expectedActiveTicks = activeTicksAtSubsessionStart;
-
- incrementActiveTicks = () => {
- sessionRecorder.incrementActiveTicks();
- ++expectedActiveTicks;
- }
-
- yield TelemetryController.testReset();
-
- // Both classic and subsession payload data should be the same on the first subsession.
- incrementActiveTicks();
- let classic = TelemetrySession.getPayload();
- let subsession = TelemetrySession.getPayload("environment-change");
- Assert.equal(classic.simpleMeasurements.activeTicks, expectedActiveTicks,
- "Classic pings must count active ticks since the beginning of the session.");
- Assert.equal(subsession.simpleMeasurements.activeTicks, expectedActiveTicks,
- "Subsessions must count active ticks as classic pings on the first subsession.");
-
- // Start a new subsession and check that the active ticks are correctly reported.
- incrementActiveTicks();
- activeTicksAtSubsessionStart = sessionRecorder.activeTicks;
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change", true);
- Assert.equal(classic.simpleMeasurements.activeTicks, expectedActiveTicks,
- "Classic pings must count active ticks since the beginning of the session.");
- Assert.equal(subsession.simpleMeasurements.activeTicks, expectedActiveTicks,
- "Pings must not loose the tick count when starting a new subsession.");
-
- // Get a new subsession payload without clearing the subsession.
- incrementActiveTicks();
- classic = TelemetrySession.getPayload();
- subsession = TelemetrySession.getPayload("environment-change");
- Assert.equal(classic.simpleMeasurements.activeTicks, expectedActiveTicks,
- "Classic pings must count active ticks since the beginning of the session.");
- Assert.equal(subsession.simpleMeasurements.activeTicks,
- expectedActiveTicks - activeTicksAtSubsessionStart,
- "Subsessions must count active ticks since the last new subsession.");
-});
-
-add_task(function* test_dailyCollection() {
- if (gIsAndroid) {
- // We don't do daily collections yet on Android.
- return;
- }
-
- let now = new Date(2030, 1, 1, 12, 0, 0);
- let nowDay = new Date(2030, 1, 1, 0, 0, 0);
- let schedulerTickCallback = null;
-
- PingServer.clearRequests();
-
- fakeNow(now);
-
- // Fake scheduler functions to control daily collection flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
-
- // Init and check timer.
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testSetup();
- TelemetrySend.setServer("http://localhost:" + PingServer.port);
-
- // Set histograms to expected state.
- const COUNT_ID = "TELEMETRY_TEST_COUNT";
- const KEYED_ID = "TELEMETRY_TEST_KEYED_COUNT";
- const count = Telemetry.getHistogramById(COUNT_ID);
- const keyed = Telemetry.getKeyedHistogramById(KEYED_ID);
-
- count.clear();
- keyed.clear();
- count.add(1);
- keyed.add("a", 1);
- keyed.add("b", 1);
- keyed.add("b", 1);
-
- // Make sure the daily ping gets triggered.
- let expectedDate = nowDay;
- now = futureDate(nowDay, MS_IN_ONE_DAY);
- fakeNow(now);
-
- Assert.ok(!!schedulerTickCallback);
- // Run a scheduler tick: it should trigger the daily ping.
- yield schedulerTickCallback();
-
- // Collect the daily ping.
- let ping = yield PingServer.promiseNextPing();
- Assert.ok(!!ping);
-
- Assert.equal(ping.type, PING_TYPE_MAIN);
- Assert.equal(ping.payload.info.reason, REASON_DAILY);
- let subsessionStartDate = new Date(ping.payload.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), expectedDate.toISOString());
-
- Assert.equal(ping.payload.histograms[COUNT_ID].sum, 1);
- Assert.equal(ping.payload.keyedHistograms[KEYED_ID]["a"].sum, 1);
- Assert.equal(ping.payload.keyedHistograms[KEYED_ID]["b"].sum, 2);
-
- // The daily ping is rescheduled for "tomorrow".
- expectedDate = futureDate(expectedDate, MS_IN_ONE_DAY);
- now = futureDate(now, MS_IN_ONE_DAY);
- fakeNow(now);
-
- // Run a scheduler tick. Trigger and collect another ping. The histograms should be reset.
- yield schedulerTickCallback();
-
- ping = yield PingServer.promiseNextPing();
- Assert.ok(!!ping);
-
- Assert.equal(ping.type, PING_TYPE_MAIN);
- Assert.equal(ping.payload.info.reason, REASON_DAILY);
- subsessionStartDate = new Date(ping.payload.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), expectedDate.toISOString());
-
- Assert.equal(ping.payload.histograms[COUNT_ID].sum, 0);
- Assert.ok(!(KEYED_ID in ping.payload.keyedHistograms));
-
- // Trigger and collect another daily ping, with the histograms being set again.
- count.add(1);
- keyed.add("a", 1);
- keyed.add("b", 1);
-
- // The daily ping is rescheduled for "tomorrow".
- expectedDate = futureDate(expectedDate, MS_IN_ONE_DAY);
- now = futureDate(now, MS_IN_ONE_DAY);
- fakeNow(now);
-
- yield schedulerTickCallback();
- ping = yield PingServer.promiseNextPing();
- Assert.ok(!!ping);
-
- Assert.equal(ping.type, PING_TYPE_MAIN);
- Assert.equal(ping.payload.info.reason, REASON_DAILY);
- subsessionStartDate = new Date(ping.payload.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), expectedDate.toISOString());
-
- Assert.equal(ping.payload.histograms[COUNT_ID].sum, 1);
- Assert.equal(ping.payload.keyedHistograms[KEYED_ID]["a"].sum, 1);
- Assert.equal(ping.payload.keyedHistograms[KEYED_ID]["b"].sum, 1);
-
- // Shutdown to cleanup the aborted-session if it gets created.
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_dailyDuplication() {
- if (gIsAndroid) {
- // We don't do daily collections yet on Android.
- return;
- }
-
- yield TelemetrySend.reset();
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
-
- let schedulerTickCallback = null;
- let now = new Date(2030, 1, 1, 0, 0, 0);
- fakeNow(now);
- // Fake scheduler functions to control daily collection flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
-
- // Make sure the daily ping gets triggered at midnight.
- // We need to make sure that we trigger this after the period where we wait for
- // the user to become idle.
- let firstDailyDue = new Date(2030, 1, 2, 0, 0, 0);
- fakeNow(firstDailyDue);
-
- // Run a scheduler tick: it should trigger the daily ping.
- Assert.ok(!!schedulerTickCallback);
- yield schedulerTickCallback();
-
- // Get the first daily ping.
- let ping = yield PingServer.promiseNextPing();
- Assert.ok(!!ping);
-
- Assert.equal(ping.type, PING_TYPE_MAIN);
- Assert.equal(ping.payload.info.reason, REASON_DAILY);
-
- // We don't expect to receive any other daily ping in this test, so assert if we do.
- PingServer.registerPingHandler((req, res) => {
- Assert.ok(false, "No more daily pings should be sent/received in this test.");
- });
-
- // Set the current time to a bit after midnight.
- let secondDailyDue = new Date(firstDailyDue);
- secondDailyDue.setHours(0);
- secondDailyDue.setMinutes(15);
- fakeNow(secondDailyDue);
-
- // Run a scheduler tick: it should NOT trigger the daily ping.
- Assert.ok(!!schedulerTickCallback);
- yield schedulerTickCallback();
-
- // Shutdown to cleanup the aborted-session if it gets created.
- PingServer.resetPingHandler();
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_dailyOverdue() {
- if (gIsAndroid) {
- // We don't do daily collections yet on Android.
- return;
- }
-
- let schedulerTickCallback = null;
- let now = new Date(2030, 1, 1, 11, 0, 0);
- fakeNow(now);
- // Fake scheduler functions to control daily collection flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testReset();
-
- // Skip one hour ahead: nothing should be due.
- now.setHours(now.getHours() + 1);
- fakeNow(now);
-
- // Assert if we receive something!
- PingServer.registerPingHandler((req, res) => {
- Assert.ok(false, "No daily ping should be received if not overdue!.");
- });
-
- // This tick should not trigger any daily ping.
- Assert.ok(!!schedulerTickCallback);
- yield schedulerTickCallback();
-
- // Restore the non asserting ping handler.
- PingServer.resetPingHandler();
- PingServer.clearRequests();
-
- // Simulate an overdue ping: we're not close to midnight, but the last daily ping
- // time is too long ago.
- let dailyOverdue = new Date(2030, 1, 2, 13, 0, 0);
- fakeNow(dailyOverdue);
-
- // Run a scheduler tick: it should trigger the daily ping.
- Assert.ok(!!schedulerTickCallback);
- yield schedulerTickCallback();
-
- // Get the first daily ping.
- let ping = yield PingServer.promiseNextPing();
- Assert.ok(!!ping);
-
- Assert.equal(ping.type, PING_TYPE_MAIN);
- Assert.equal(ping.payload.info.reason, REASON_DAILY);
-
- // Shutdown to cleanup the aborted-session if it gets created.
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_environmentChange() {
- if (gIsAndroid) {
- // We don't split subsessions on environment changes yet on Android.
- return;
- }
-
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
-
- let now = fakeNow(2040, 1, 1, 12, 0, 0);
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 10 * MILLISECONDS_PER_MINUTE);
-
- const PREF_TEST = "toolkit.telemetry.test.pref1";
- Preferences.reset(PREF_TEST);
-
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_VALUE}],
- ]);
-
- // Setup.
- yield TelemetryController.testReset();
- TelemetrySend.setServer("http://localhost:" + PingServer.port);
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
-
- // Set histograms to expected state.
- const COUNT_ID = "TELEMETRY_TEST_COUNT";
- const KEYED_ID = "TELEMETRY_TEST_KEYED_COUNT";
- const count = Telemetry.getHistogramById(COUNT_ID);
- const keyed = Telemetry.getKeyedHistogramById(KEYED_ID);
-
- count.clear();
- keyed.clear();
- count.add(1);
- keyed.add("a", 1);
- keyed.add("b", 1);
-
- // Trigger and collect environment-change ping.
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 10 * MILLISECONDS_PER_MINUTE);
- let startDay = truncateDateToDays(now);
- now = fakeNow(futureDate(now, 10 * MILLISECONDS_PER_MINUTE));
-
- Preferences.set(PREF_TEST, 1);
- let ping = yield PingServer.promiseNextPing();
- Assert.ok(!!ping);
-
- Assert.equal(ping.type, PING_TYPE_MAIN);
- Assert.equal(ping.environment.settings.userPrefs[PREF_TEST], undefined);
- Assert.equal(ping.payload.info.reason, REASON_ENVIRONMENT_CHANGE);
- let subsessionStartDate = new Date(ping.payload.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), startDay.toISOString());
-
- Assert.equal(ping.payload.histograms[COUNT_ID].sum, 1);
- Assert.equal(ping.payload.keyedHistograms[KEYED_ID]["a"].sum, 1);
-
- // Trigger and collect another ping. The histograms should be reset.
- startDay = truncateDateToDays(now);
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 10 * MILLISECONDS_PER_MINUTE);
- now = fakeNow(futureDate(now, 10 * MILLISECONDS_PER_MINUTE));
-
- Preferences.set(PREF_TEST, 2);
- ping = yield PingServer.promiseNextPing();
- Assert.ok(!!ping);
-
- Assert.equal(ping.type, PING_TYPE_MAIN);
- Assert.equal(ping.environment.settings.userPrefs[PREF_TEST], 1);
- Assert.equal(ping.payload.info.reason, REASON_ENVIRONMENT_CHANGE);
- subsessionStartDate = new Date(ping.payload.info.subsessionStartDate);
- Assert.equal(subsessionStartDate.toISOString(), startDay.toISOString());
-
- Assert.equal(ping.payload.histograms[COUNT_ID].sum, 0);
- Assert.ok(!(KEYED_ID in ping.payload.keyedHistograms));
-});
-
-add_task(function* test_savedPingsOnShutdown() {
- // On desktop, we expect both "saved-session" and "shutdown" pings. We only expect
- // the former on Android.
- const expectedPingCount = (gIsAndroid) ? 1 : 2;
- // Assure that we store the ping properly when saving sessions on shutdown.
- // We make the TelemetryController shutdown to trigger a session save.
- const dir = TelemetryStorage.pingDirectoryPath;
- yield OS.File.removeDir(dir, {ignoreAbsent: true});
- yield OS.File.makeDir(dir);
- yield TelemetryController.testShutdown();
-
- PingServer.clearRequests();
- yield TelemetryController.testReset();
-
- const pings = yield PingServer.promiseNextPings(expectedPingCount);
-
- for (let ping of pings) {
- Assert.ok("type" in ping);
-
- let expectedReason =
- (ping.type == PING_TYPE_SAVED_SESSION) ? REASON_SAVED_SESSION : REASON_SHUTDOWN;
-
- checkPingFormat(ping, ping.type, true, true);
- Assert.equal(ping.payload.info.reason, expectedReason);
- Assert.equal(ping.clientId, gClientID);
- }
-});
-
-add_task(function* test_savedSessionData() {
- // Create the directory which will contain the data file, if it doesn't already
- // exist.
- yield OS.File.makeDir(DATAREPORTING_PATH);
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_LOAD").clear();
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_PARSE").clear();
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").clear();
-
- // Write test data to the session data file.
- const dataFilePath = OS.Path.join(DATAREPORTING_PATH, "session-state.json");
- const sessionState = {
- sessionId: null,
- subsessionId: null,
- profileSubsessionCounter: 3785,
- };
- yield CommonUtils.writeJSON(sessionState, dataFilePath);
-
- const PREF_TEST = "toolkit.telemetry.test.pref1";
- Preferences.reset(PREF_TEST);
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_VALUE}],
- ]);
-
- // We expect one new subsession when starting TelemetrySession and one after triggering
- // an environment change.
- const expectedSubsessions = sessionState.profileSubsessionCounter + 2;
- const expectedSessionUUID = "ff602e52-47a1-b7e8-4c1a-ffffffffc87a";
- const expectedSubsessionUUID = "009fd1ad-b85e-4817-b3e5-000000003785";
- fakeGenerateUUID(() => expectedSessionUUID, () => expectedSubsessionUUID);
-
- if (gIsAndroid) {
- // We don't support subsessions yet on Android, so skip the next checks.
- return;
- }
-
- // Start TelemetrySession so that it loads the session data file.
- yield TelemetryController.testReset();
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_LOAD").sum);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_PARSE").sum);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").sum);
-
- // Watch a test preference, trigger and environment change and wait for it to propagate.
- // _watchPreferences triggers a subsession notification
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 10 * MILLISECONDS_PER_MINUTE);
- fakeNow(new Date(2050, 1, 1, 12, 0, 0));
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
- let changePromise = new Promise(resolve =>
- TelemetryEnvironment.registerChangeListener("test_fake_change", resolve));
- Preferences.set(PREF_TEST, 1);
- yield changePromise;
- TelemetryEnvironment.unregisterChangeListener("test_fake_change");
-
- let payload = TelemetrySession.getPayload();
- Assert.equal(payload.info.profileSubsessionCounter, expectedSubsessions);
- yield TelemetryController.testShutdown();
-
- // Restore the UUID generator so we don't mess with other tests.
- fakeGenerateUUID(generateUUID, generateUUID);
-
- // Load back the serialised session data.
- let data = yield CommonUtils.readJSON(dataFilePath);
- Assert.equal(data.profileSubsessionCounter, expectedSubsessions);
- Assert.equal(data.sessionId, expectedSessionUUID);
- Assert.equal(data.subsessionId, expectedSubsessionUUID);
-});
-
-add_task(function* test_sessionData_ShortSession() {
- if (gIsAndroid) {
- // We don't support subsessions yet on Android, so skip the next checks.
- return;
- }
-
- const SESSION_STATE_PATH = OS.Path.join(DATAREPORTING_PATH, "session-state.json");
-
- // Shut down Telemetry and remove the session state file.
- yield TelemetryController.testReset();
- yield OS.File.remove(SESSION_STATE_PATH, { ignoreAbsent: true });
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_LOAD").clear();
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_PARSE").clear();
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").clear();
-
- const expectedSessionUUID = "ff602e52-47a1-b7e8-4c1a-ffffffffc87a";
- const expectedSubsessionUUID = "009fd1ad-b85e-4817-b3e5-000000003785";
- fakeGenerateUUID(() => expectedSessionUUID, () => expectedSubsessionUUID);
-
- // We intentionally don't wait for the setup to complete and shut down to simulate
- // short sessions. We expect the profile subsession counter to be 1.
- TelemetryController.testReset();
- yield TelemetryController.testShutdown();
-
- Assert.equal(1, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_LOAD").sum);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_PARSE").sum);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").sum);
-
- // Restore the UUID generation functions.
- fakeGenerateUUID(generateUUID, generateUUID);
-
- // Start TelemetryController so that it loads the session data file. We expect the profile
- // subsession counter to be incremented by 1 again.
- yield TelemetryController.testReset();
-
- // We expect 2 profile subsession counter updates.
- let payload = TelemetrySession.getPayload();
- Assert.equal(payload.info.profileSubsessionCounter, 2);
- Assert.equal(payload.info.previousSessionId, expectedSessionUUID);
- Assert.equal(payload.info.previousSubsessionId, expectedSubsessionUUID);
- Assert.equal(1, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_LOAD").sum);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_PARSE").sum);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").sum);
-});
-
-add_task(function* test_invalidSessionData() {
- // Create the directory which will contain the data file, if it doesn't already
- // exist.
- yield OS.File.makeDir(DATAREPORTING_PATH);
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_LOAD").clear();
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_PARSE").clear();
- getHistogram("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").clear();
-
- // Write test data to the session data file. This should fail to parse.
- const dataFilePath = OS.Path.join(DATAREPORTING_PATH, "session-state.json");
- const unparseableData = "{asdf:@äü";
- OS.File.writeAtomic(dataFilePath, unparseableData,
- {encoding: "utf-8", tmpPath: dataFilePath + ".tmp"});
-
- // Start TelemetryController so that it loads the session data file.
- yield TelemetryController.testReset();
-
- // The session data file should not load. Only expect the current subsession.
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_LOAD").sum);
- Assert.equal(1, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_PARSE").sum);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").sum);
-
- // Write test data to the session data file. This should fail validation.
- const sessionState = {
- profileSubsessionCounter: "not-a-number?",
- someOtherField: 12,
- };
- yield CommonUtils.writeJSON(sessionState, dataFilePath);
-
- // The session data file should not load. Only expect the current subsession.
- const expectedSubsessions = 1;
- const expectedSessionUUID = "ff602e52-47a1-b7e8-4c1a-ffffffffc87a";
- const expectedSubsessionUUID = "009fd1ad-b85e-4817-b3e5-000000003785";
- fakeGenerateUUID(() => expectedSessionUUID, () => expectedSubsessionUUID);
-
- // Start TelemetryController so that it loads the session data file.
- yield TelemetryController.testReset();
-
- let payload = TelemetrySession.getPayload();
- Assert.equal(payload.info.profileSubsessionCounter, expectedSubsessions);
- Assert.equal(0, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_LOAD").sum);
- Assert.equal(1, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_PARSE").sum);
- Assert.equal(1, getSnapshot("TELEMETRY_SESSIONDATA_FAILED_VALIDATION").sum);
-
- yield TelemetryController.testShutdown();
-
- // Restore the UUID generator so we don't mess with other tests.
- fakeGenerateUUID(generateUUID, generateUUID);
-
- // Load back the serialised session data.
- let data = yield CommonUtils.readJSON(dataFilePath);
- Assert.equal(data.profileSubsessionCounter, expectedSubsessions);
- Assert.equal(data.sessionId, expectedSessionUUID);
- Assert.equal(data.subsessionId, expectedSubsessionUUID);
-});
-
-add_task(function* test_abortedSession() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session ping here.
- return;
- }
-
- const ABORTED_FILE = OS.Path.join(DATAREPORTING_PATH, ABORTED_PING_FILE_NAME);
-
- // Make sure the aborted sessions directory does not exist to test its creation.
- yield OS.File.removeDir(DATAREPORTING_PATH, { ignoreAbsent: true });
-
- let schedulerTickCallback = null;
- let now = new Date(2040, 1, 1, 0, 0, 0);
- fakeNow(now);
- // Fake scheduler functions to control aborted-session flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
-
- Assert.ok((yield OS.File.exists(DATAREPORTING_PATH)),
- "Telemetry must create the aborted session directory when starting.");
-
- // Fake now again so that the scheduled aborted-session save takes place.
- now = futureDate(now, ABORTED_SESSION_UPDATE_INTERVAL_MS);
- fakeNow(now);
- // The first aborted session checkpoint must take place right after the initialisation.
- Assert.ok(!!schedulerTickCallback);
- // Execute one scheduler tick.
- yield schedulerTickCallback();
- // Check that the aborted session is due at the correct time.
- Assert.ok((yield OS.File.exists(ABORTED_FILE)),
- "There must be an aborted session ping.");
-
- // This ping is not yet in the pending pings folder, so we can't access it using
- // TelemetryStorage.popPendingPings().
- let pingContent = yield OS.File.read(ABORTED_FILE, { encoding: "utf-8" });
- let abortedSessionPing = JSON.parse(pingContent);
-
- // Validate the ping.
- checkPingFormat(abortedSessionPing, PING_TYPE_MAIN, true, true);
- Assert.equal(abortedSessionPing.payload.info.reason, REASON_ABORTED_SESSION);
-
- // Trigger a another aborted-session ping and check that it overwrites the previous one.
- now = futureDate(now, ABORTED_SESSION_UPDATE_INTERVAL_MS);
- fakeNow(now);
- yield schedulerTickCallback();
-
- pingContent = yield OS.File.read(ABORTED_FILE, { encoding: "utf-8" });
- let updatedAbortedSessionPing = JSON.parse(pingContent);
- checkPingFormat(updatedAbortedSessionPing, PING_TYPE_MAIN, true, true);
- Assert.equal(updatedAbortedSessionPing.payload.info.reason, REASON_ABORTED_SESSION);
- Assert.notEqual(abortedSessionPing.id, updatedAbortedSessionPing.id);
- Assert.notEqual(abortedSessionPing.creationDate, updatedAbortedSessionPing.creationDate);
-
- yield TelemetryController.testShutdown();
- Assert.ok(!(yield OS.File.exists(ABORTED_FILE)),
- "No aborted session ping must be available after a shutdown.");
-
- // Write the ping to the aborted-session file. TelemetrySession will add it to the
- // saved pings directory when it starts.
- yield TelemetryStorage.savePingToFile(abortedSessionPing, ABORTED_FILE, false);
- Assert.ok((yield OS.File.exists(ABORTED_FILE)),
- "The aborted session ping must exist in the aborted session ping directory.");
-
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
- yield TelemetryController.testReset();
-
- Assert.ok(!(yield OS.File.exists(ABORTED_FILE)),
- "The aborted session ping must be removed from the aborted session ping directory.");
-
- // Restarting Telemetry again to trigger sending pings in TelemetrySend.
- yield TelemetryController.testReset();
-
- // We should have received an aborted-session ping.
- const receivedPing = yield PingServer.promiseNextPing();
- Assert.equal(receivedPing.type, PING_TYPE_MAIN, "Should have the correct type");
- Assert.equal(receivedPing.payload.info.reason, REASON_ABORTED_SESSION, "Ping should have the correct reason");
-
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_abortedSession_Shutdown() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session ping here.
- return;
- }
-
- const ABORTED_FILE = OS.Path.join(DATAREPORTING_PATH, ABORTED_PING_FILE_NAME);
-
- let schedulerTickCallback = null;
- let now = fakeNow(2040, 1, 1, 0, 0, 0);
- // Fake scheduler functions to control aborted-session flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
-
- Assert.ok((yield OS.File.exists(DATAREPORTING_PATH)),
- "Telemetry must create the aborted session directory when starting.");
-
- // Fake now again so that the scheduled aborted-session save takes place.
- fakeNow(futureDate(now, ABORTED_SESSION_UPDATE_INTERVAL_MS));
- // The first aborted session checkpoint must take place right after the initialisation.
- Assert.ok(!!schedulerTickCallback);
- // Execute one scheduler tick.
- yield schedulerTickCallback();
- // Check that the aborted session is due at the correct time.
- Assert.ok((yield OS.File.exists(ABORTED_FILE)), "There must be an aborted session ping.");
-
- // Remove the aborted session file and then shut down to make sure exceptions (e.g file
- // not found) do not compromise the shutdown.
- yield OS.File.remove(ABORTED_FILE);
-
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_abortedDailyCoalescing() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session or the daily ping here.
- return;
- }
-
- const ABORTED_FILE = OS.Path.join(DATAREPORTING_PATH, ABORTED_PING_FILE_NAME);
-
- // Make sure the aborted sessions directory does not exist to test its creation.
- yield OS.File.removeDir(DATAREPORTING_PATH, { ignoreAbsent: true });
-
- let schedulerTickCallback = null;
- PingServer.clearRequests();
-
- let nowDate = new Date(2009, 10, 18, 0, 0, 0);
- fakeNow(nowDate);
-
- // Fake scheduler functions to control aborted-session flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
- yield TelemetryController.testReset();
-
- Assert.ok((yield OS.File.exists(DATAREPORTING_PATH)),
- "Telemetry must create the aborted session directory when starting.");
-
- // Delay the callback around midnight so that the aborted-session ping gets merged with the
- // daily ping.
- let dailyDueDate = futureDate(nowDate, MS_IN_ONE_DAY);
- fakeNow(dailyDueDate);
- // Trigger both the daily ping and the saved-session.
- Assert.ok(!!schedulerTickCallback);
- // Execute one scheduler tick.
- yield schedulerTickCallback();
-
- // Wait for the daily ping.
- let dailyPing = yield PingServer.promiseNextPing();
- Assert.equal(dailyPing.payload.info.reason, REASON_DAILY);
-
- // Check that an aborted session ping was also written to disk.
- Assert.ok((yield OS.File.exists(ABORTED_FILE)),
- "There must be an aborted session ping.");
-
- // Read aborted session ping and check that the session/subsession ids equal the
- // ones in the daily ping.
- let pingContent = yield OS.File.read(ABORTED_FILE, { encoding: "utf-8" });
- let abortedSessionPing = JSON.parse(pingContent);
- Assert.equal(abortedSessionPing.payload.info.sessionId, dailyPing.payload.info.sessionId);
- Assert.equal(abortedSessionPing.payload.info.subsessionId, dailyPing.payload.info.subsessionId);
-
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_schedulerComputerSleep() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session or the daily ping here.
- return;
- }
-
- const ABORTED_FILE = OS.Path.join(DATAREPORTING_PATH, ABORTED_PING_FILE_NAME);
-
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testReset();
- PingServer.clearRequests();
-
- // Remove any aborted-session ping from the previous tests.
- yield OS.File.removeDir(DATAREPORTING_PATH, { ignoreAbsent: true });
-
- // Set a fake current date and start Telemetry.
- let nowDate = fakeNow(2009, 10, 18, 0, 0, 0);
- let schedulerTickCallback = null;
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
-
- // Set the current time 3 days in the future at midnight, before running the callback.
- nowDate = fakeNow(futureDate(nowDate, 3 * MS_IN_ONE_DAY));
- Assert.ok(!!schedulerTickCallback);
- // Execute one scheduler tick.
- yield schedulerTickCallback();
-
- let dailyPing = yield PingServer.promiseNextPing();
- Assert.equal(dailyPing.payload.info.reason, REASON_DAILY,
- "The wake notification should have triggered a daily ping.");
- Assert.equal(dailyPing.creationDate, nowDate.toISOString(),
- "The daily ping date should be correct.");
-
- Assert.ok((yield OS.File.exists(ABORTED_FILE)),
- "There must be an aborted session ping.");
-
- // Now also test if we are sending a daily ping if we wake up on the next
- // day even when the timer doesn't trigger.
- // This can happen due to timeouts not running out during sleep times,
- // see bug 1262386, bug 1204823 et al.
- // Note that we don't get wake notifications on Linux due to bug 758848.
- nowDate = fakeNow(futureDate(nowDate, 1 * MS_IN_ONE_DAY));
-
- // We emulate the mentioned timeout behavior by sending the wake notification
- // instead of triggering the timeout callback.
- // This should trigger a daily ping, because we passed midnight.
- Services.obs.notifyObservers(null, "wake_notification", null);
-
- dailyPing = yield PingServer.promiseNextPing();
- Assert.equal(dailyPing.payload.info.reason, REASON_DAILY,
- "The wake notification should have triggered a daily ping.");
- Assert.equal(dailyPing.creationDate, nowDate.toISOString(),
- "The daily ping date should be correct.");
-
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_schedulerEnvironmentReschedules() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session or the daily ping here.
- return;
- }
-
- // Reset the test preference.
- const PREF_TEST = "toolkit.telemetry.test.pref1";
- Preferences.reset(PREF_TEST);
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_VALUE}],
- ]);
-
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
- yield TelemetryController.testReset();
-
- // Set a fake current date and start Telemetry.
- let nowDate = fakeNow(2060, 10, 18, 0, 0, 0);
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 10 * MILLISECONDS_PER_MINUTE);
- let schedulerTickCallback = null;
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
-
- // Set the current time at midnight.
- fakeNow(futureDate(nowDate, MS_IN_ONE_DAY));
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 10 * MILLISECONDS_PER_MINUTE);
-
- // Trigger the environment change.
- Preferences.set(PREF_TEST, 1);
-
- // Wait for the environment-changed ping.
- yield PingServer.promiseNextPing();
-
- // We don't expect to receive any daily ping in this test, so assert if we do.
- PingServer.registerPingHandler((req, res) => {
- Assert.ok(false, "No ping should be sent/received in this test.");
- });
-
- // Execute one scheduler tick. It should not trigger a daily ping.
- Assert.ok(!!schedulerTickCallback);
- yield schedulerTickCallback();
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_schedulerNothingDue() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session or the daily ping here.
- return;
- }
-
- const ABORTED_FILE = OS.Path.join(DATAREPORTING_PATH, ABORTED_PING_FILE_NAME);
-
- // Remove any aborted-session ping from the previous tests.
- yield OS.File.removeDir(DATAREPORTING_PATH, { ignoreAbsent: true });
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testReset();
-
- // We don't expect to receive any ping in this test, so assert if we do.
- PingServer.registerPingHandler((req, res) => {
- Assert.ok(false, "No ping should be sent/received in this test.");
- });
-
- // Set a current date/time away from midnight, so that the daily ping doesn't get
- // sent.
- let nowDate = new Date(2009, 10, 18, 11, 0, 0);
- fakeNow(nowDate);
- let schedulerTickCallback = null;
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
-
- // Delay the callback execution to a time when no ping should be due.
- let nothingDueDate = futureDate(nowDate, ABORTED_SESSION_UPDATE_INTERVAL_MS / 2);
- fakeNow(nothingDueDate);
- Assert.ok(!!schedulerTickCallback);
- // Execute one scheduler tick.
- yield schedulerTickCallback();
-
- // Check that no aborted session ping was written to disk.
- Assert.ok(!(yield OS.File.exists(ABORTED_FILE)));
-
- yield TelemetryController.testShutdown();
- PingServer.resetPingHandler();
-});
-
-add_task(function* test_pingExtendedStats() {
- const EXTENDED_PAYLOAD_FIELDS = [
- "chromeHangs", "threadHangStats", "log", "slowSQL", "fileIOReports", "lateWrites",
- "addonHistograms", "addonDetails", "UIMeasurements", "webrtc"
- ];
-
- // Reset telemetry and disable sending extended statistics.
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
- yield TelemetryController.testReset();
- Telemetry.canRecordExtended = false;
-
- yield sendPing();
-
- let ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, PING_TYPE_MAIN, true, true);
-
- // Check that the payload does not contain extended statistics fields.
- for (let f in EXTENDED_PAYLOAD_FIELDS) {
- Assert.ok(!(EXTENDED_PAYLOAD_FIELDS[f] in ping.payload),
- EXTENDED_PAYLOAD_FIELDS[f] + " must not be in the payload if the extended set is off.");
- }
-
- // We check this one separately so that we can reuse EXTENDED_PAYLOAD_FIELDS below, since
- // slowSQLStartup might not be there.
- Assert.ok(!("slowSQLStartup" in ping.payload),
- "slowSQLStartup must not be sent if the extended set is off");
-
- Assert.ok(!("addonManager" in ping.payload.simpleMeasurements),
- "addonManager must not be sent if the extended set is off.");
- Assert.ok(!("UITelemetry" in ping.payload.simpleMeasurements),
- "UITelemetry must not be sent if the extended set is off.");
-
- // Restore the preference.
- Telemetry.canRecordExtended = true;
-
- // Send a new ping that should contain the extended data.
- yield sendPing();
- ping = yield PingServer.promiseNextPing();
- checkPingFormat(ping, PING_TYPE_MAIN, true, true);
-
- // Check that the payload now contains extended statistics fields.
- for (let f in EXTENDED_PAYLOAD_FIELDS) {
- Assert.ok(EXTENDED_PAYLOAD_FIELDS[f] in ping.payload,
- EXTENDED_PAYLOAD_FIELDS[f] + " must be in the payload if the extended set is on.");
- }
-
- Assert.ok("addonManager" in ping.payload.simpleMeasurements,
- "addonManager must be sent if the extended set is on.");
- Assert.ok("UITelemetry" in ping.payload.simpleMeasurements,
- "UITelemetry must be sent if the extended set is on.");
-});
-
-add_task(function* test_schedulerUserIdle() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session or the daily ping here.
- return;
- }
-
- const SCHEDULER_TICK_INTERVAL_MS = 5 * 60 * 1000;
- const SCHEDULER_TICK_IDLE_INTERVAL_MS = 60 * 60 * 1000;
-
- let now = new Date(2010, 1, 1, 11, 0, 0);
- fakeNow(now);
-
- let schedulerTimeout = 0;
- fakeSchedulerTimer((callback, timeout) => {
- schedulerTimeout = timeout;
- }, () => {});
- yield TelemetryController.testReset();
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
-
- // When not idle, the scheduler should have a 5 minutes tick interval.
- Assert.equal(schedulerTimeout, SCHEDULER_TICK_INTERVAL_MS);
-
- // Send an "idle" notification to the scheduler.
- fakeIdleNotification("idle");
-
- // When idle, the scheduler should have a 1hr tick interval.
- Assert.equal(schedulerTimeout, SCHEDULER_TICK_IDLE_INTERVAL_MS);
-
- // Send an "active" notification to the scheduler.
- fakeIdleNotification("active");
-
- // When user is back active, the scheduler tick should be 5 minutes again.
- Assert.equal(schedulerTimeout, SCHEDULER_TICK_INTERVAL_MS);
-
- // We should not miss midnight when going to idle.
- now.setHours(23);
- now.setMinutes(50);
- fakeNow(now);
- fakeIdleNotification("idle");
- Assert.equal(schedulerTimeout, 10 * 60 * 1000);
-
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_DailyDueAndIdle() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session or the daily ping here.
- return;
- }
-
- yield TelemetryStorage.testClearPendingPings();
- PingServer.clearRequests();
-
- let receivedPingRequest = null;
- // Register a ping handler that will assert when receiving multiple daily pings.
- PingServer.registerPingHandler(req => {
- Assert.ok(!receivedPingRequest, "Telemetry must only send one daily ping.");
- receivedPingRequest = req;
- });
-
- // Faking scheduler timer has to happen before resetting TelemetryController
- // to be effective.
- let schedulerTickCallback = null;
- let now = new Date(2030, 1, 1, 0, 0, 0);
- fakeNow(now);
- // Fake scheduler functions to control daily collection flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryController.testReset();
-
- // Trigger the daily ping.
- let firstDailyDue = new Date(2030, 1, 2, 0, 0, 0);
- fakeNow(firstDailyDue);
-
- // Run a scheduler tick: it should trigger the daily ping.
- Assert.ok(!!schedulerTickCallback);
- let tickPromise = schedulerTickCallback();
-
- // Send an idle and then an active user notification.
- fakeIdleNotification("idle");
- fakeIdleNotification("active");
-
- // Wait on the tick promise.
- yield tickPromise;
-
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- // Decode the ping contained in the request and check that's a daily ping.
- Assert.ok(receivedPingRequest, "Telemetry must send one daily ping.");
- const receivedPing = decodeRequestPayload(receivedPingRequest);
- checkPingFormat(receivedPing, PING_TYPE_MAIN, true, true);
- Assert.equal(receivedPing.payload.info.reason, REASON_DAILY);
-
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_userIdleAndSchedlerTick() {
- if (gIsAndroid || gIsGonk) {
- // We don't have the aborted session or the daily ping here.
- return;
- }
-
- let receivedPingRequest = null;
- // Register a ping handler that will assert when receiving multiple daily pings.
- PingServer.registerPingHandler(req => {
- Assert.ok(!receivedPingRequest, "Telemetry must only send one daily ping.");
- receivedPingRequest = req;
- });
-
- let schedulerTickCallback = null;
- let now = new Date(2030, 1, 1, 0, 0, 0);
- fakeNow(now);
- // Fake scheduler functions to control daily collection flow in tests.
- fakeSchedulerTimer(callback => schedulerTickCallback = callback, () => {});
- yield TelemetryStorage.testClearPendingPings();
- yield TelemetryController.testReset();
- PingServer.clearRequests();
-
- // Move the current date/time to midnight.
- let firstDailyDue = new Date(2030, 1, 2, 0, 0, 0);
- fakeNow(firstDailyDue);
-
- // The active notification should trigger a scheduler tick. The latter will send the
- // due daily ping.
- fakeIdleNotification("active");
-
- // Immediately running another tick should not send a daily ping again.
- Assert.ok(!!schedulerTickCallback);
- yield schedulerTickCallback();
-
- // A new "idle" notification should not send a new daily ping.
- fakeIdleNotification("idle");
-
- yield TelemetrySend.testWaitOnOutgoingPings();
-
- // Decode the ping contained in the request and check that's a daily ping.
- Assert.ok(receivedPingRequest, "Telemetry must send one daily ping.");
- const receivedPing = decodeRequestPayload(receivedPingRequest);
- checkPingFormat(receivedPing, PING_TYPE_MAIN, true, true);
- Assert.equal(receivedPing.payload.info.reason, REASON_DAILY);
-
- PingServer.resetPingHandler();
- yield TelemetryController.testShutdown();
-});
-
-add_task(function* test_changeThrottling() {
- if (gIsAndroid) {
- // We don't support subsessions yet on Android.
- return;
- }
-
- let getSubsessionCount = () => {
- return TelemetrySession.getPayload().info.subsessionCounter;
- };
-
- const PREF_TEST = "toolkit.telemetry.test.pref1";
- const PREFS_TO_WATCH = new Map([
- [PREF_TEST, {what: TelemetryEnvironment.RECORD_PREF_STATE}],
- ]);
- Preferences.reset(PREF_TEST);
-
- let now = fakeNow(2050, 1, 2, 0, 0, 0);
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 10 * MILLISECONDS_PER_MINUTE);
- yield TelemetryController.testReset();
- Assert.equal(getSubsessionCount(), 1);
-
- // Set the Environment preferences to watch.
- TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH);
-
- // The first pref change should not trigger a notification.
- Preferences.set(PREF_TEST, 1);
- Assert.equal(getSubsessionCount(), 1);
-
- // We should get a change notification after the 5min throttling interval.
- fakeNow(futureDate(now, 5 * MILLISECONDS_PER_MINUTE + 1));
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 5 * MILLISECONDS_PER_MINUTE + 1);
- Preferences.set(PREF_TEST, 2);
- Assert.equal(getSubsessionCount(), 2);
-
- // After that, changes should be throttled again.
- now = fakeNow(futureDate(now, 1 * MILLISECONDS_PER_MINUTE));
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 1 * MILLISECONDS_PER_MINUTE);
- Preferences.set(PREF_TEST, 3);
- Assert.equal(getSubsessionCount(), 2);
-
- // ... for 5min.
- now = fakeNow(futureDate(now, 4 * MILLISECONDS_PER_MINUTE + 1));
- gMonotonicNow = fakeMonotonicNow(gMonotonicNow + 4 * MILLISECONDS_PER_MINUTE + 1);
- Preferences.set(PREF_TEST, 4);
- Assert.equal(getSubsessionCount(), 3);
-
- // Unregister the listener.
- TelemetryEnvironment.unregisterChangeListener("testWatchPrefs_throttling");
-});
-
-add_task(function* stopServer() {
- yield PingServer.stop();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryTimestamps.js b/toolkit/components/telemetry/tests/unit/test_TelemetryTimestamps.js
deleted file mode 100644
index 75bf3157a..000000000
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryTimestamps.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/TelemetryController.jsm", this);
-Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-
-// The @mozilla/xre/app-info;1 XPCOM object provided by the xpcshell test harness doesn't
-// implement the nsIXULAppInfo interface, which is needed by Services.jsm and
-// TelemetrySession.jsm. updateAppInfo() creates and registers a minimal mock app-info.
-Cu.import("resource://testing-common/AppInfo.jsm");
-updateAppInfo();
-
-var gGlobalScope = this;
-
-function getSimpleMeasurementsFromTelemetryController() {
- return TelemetrySession.getPayload().simpleMeasurements;
-}
-
-add_task(function* test_setup() {
- // Telemetry needs the AddonManager.
- loadAddonManager();
- // Make profile available for |TelemetryController.testShutdown()|.
- do_get_profile();
-
- // Make sure we don't generate unexpected pings due to pref changes.
- yield setEmptyPrefWatchlist();
-
- yield new Promise(resolve =>
- Services.telemetry.asyncFetchTelemetryData(resolve));
-});
-
-add_task(function* actualTest() {
- yield TelemetryController.testSetup();
-
- // Test the module logic
- let tmp = {};
- Cu.import("resource://gre/modules/TelemetryTimestamps.jsm", tmp);
- let TelemetryTimestamps = tmp.TelemetryTimestamps;
- let now = Date.now();
- TelemetryTimestamps.add("foo");
- do_check_true(TelemetryTimestamps.get().foo != null); // foo was added
- do_check_true(TelemetryTimestamps.get().foo >= now); // foo has a reasonable value
-
- // Add timestamp with value
- // Use a value far in the future since TelemetryController substracts the time of
- // process initialization.
- const YEAR_4000_IN_MS = 64060588800000;
- TelemetryTimestamps.add("bar", YEAR_4000_IN_MS);
- do_check_eq(TelemetryTimestamps.get().bar, YEAR_4000_IN_MS); // bar has the right value
-
- // Can't add the same timestamp twice
- TelemetryTimestamps.add("bar", 2);
- do_check_eq(TelemetryTimestamps.get().bar, YEAR_4000_IN_MS); // bar wasn't overwritten
-
- let threw = false;
- try {
- TelemetryTimestamps.add("baz", "this isn't a number");
- } catch (ex) {
- threw = true;
- }
- do_check_true(threw); // adding non-number threw
- do_check_null(TelemetryTimestamps.get().baz); // no baz was added
-
- // Test that the data gets added to the telemetry ping properly
- let simpleMeasurements = getSimpleMeasurementsFromTelemetryController();
- do_check_true(simpleMeasurements != null); // got simple measurements from ping data
- do_check_true(simpleMeasurements.foo > 1); // foo was included
- do_check_true(simpleMeasurements.bar > 1); // bar was included
- do_check_eq(undefined, simpleMeasurements.baz); // baz wasn't included since it wasn't added
-
- yield TelemetryController.testShutdown();
-});
diff --git a/toolkit/components/telemetry/tests/unit/test_ThreadHangStats.js b/toolkit/components/telemetry/tests/unit/test_ThreadHangStats.js
deleted file mode 100644
index e8c9f868a..000000000
--- a/toolkit/components/telemetry/tests/unit/test_ThreadHangStats.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-function getMainThreadHangStats() {
- let threads = Services.telemetry.threadHangStats;
- return threads.find((thread) => (thread.name === "Gecko"));
-}
-
-function run_test() {
- let startHangs = getMainThreadHangStats();
-
- // We disable hang reporting in several situations (e.g. debug builds,
- // official releases). In those cases, we don't have hang stats available
- // and should exit the test early.
- if (!startHangs) {
- ok("Hang reporting not enabled.");
- return;
- }
-
- if (Services.appinfo.OS === 'Linux' || Services.appinfo.OS === 'Android') {
- // We use the rt_tgsigqueueinfo syscall on Linux which requires a
- // certain kernel version. It's not an error if the system running
- // the test is older than that.
- let kernel = Services.sysinfo.get('kernel_version') ||
- Services.sysinfo.get('version');
- if (Services.vc.compare(kernel, '2.6.31') < 0) {
- ok("Hang reporting not supported for old kernel.");
- return;
- }
- }
-
- // Run three events in the event loop:
- // the first event causes a transient hang;
- // the second event causes a permanent hang;
- // the third event checks results from previous events.
-
- do_execute_soon(() => {
- // Cause a hang lasting 1 second (transient hang).
- let startTime = Date.now();
- while ((Date.now() - startTime) < 1000);
- });
-
- do_execute_soon(() => {
- // Cause a hang lasting 10 seconds (permanent hang).
- let startTime = Date.now();
- while ((Date.now() - startTime) < 10000);
- });
-
- do_execute_soon(() => {
- do_test_pending();
-
- let check_results = () => {
- let endHangs = getMainThreadHangStats();
-
- // Because hangs are recorded asynchronously, if we don't see new hangs,
- // we should wait for pending hangs to be recorded. On the other hand,
- // if hang monitoring is broken, this test will time out.
- if (endHangs.hangs.length === startHangs.hangs.length) {
- do_timeout(100, check_results);
- return;
- }
-
- let check_histogram = (histogram) => {
- equal(typeof histogram, "object");
- equal(histogram.histogram_type, 0);
- equal(typeof histogram.min, "number");
- equal(typeof histogram.max, "number");
- equal(typeof histogram.sum, "number");
- ok(Array.isArray(histogram.ranges));
- ok(Array.isArray(histogram.counts));
- equal(histogram.counts.length, histogram.ranges.length);
- };
-
- // Make sure the hang stats structure is what we expect.
- equal(typeof endHangs, "object");
- check_histogram(endHangs.activity);
-
- ok(Array.isArray(endHangs.hangs));
- notEqual(endHangs.hangs.length, 0);
-
- ok(Array.isArray(endHangs.hangs[0].stack));
- notEqual(endHangs.hangs[0].stack.length, 0);
- equal(typeof endHangs.hangs[0].stack[0], "string");
-
- // Make sure one of the hangs is a permanent
- // hang containing a native stack.
- ok(endHangs.hangs.some((hang) => (
- Array.isArray(hang.nativeStack) &&
- hang.nativeStack.length !== 0 &&
- typeof hang.nativeStack[0] === "string"
- )));
-
- check_histogram(endHangs.hangs[0].histogram);
-
- do_test_finished();
- };
-
- check_results();
- });
-}
diff --git a/toolkit/components/telemetry/tests/unit/test_nsITelemetry.js b/toolkit/components/telemetry/tests/unit/test_nsITelemetry.js
deleted file mode 100644
index 8dc552604..000000000
--- a/toolkit/components/telemetry/tests/unit/test_nsITelemetry.js
+++ /dev/null
@@ -1,883 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const INT_MAX = 0x7FFFFFFF;
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/TelemetryUtils.jsm", this);
-
-// Return an array of numbers from lower up to, excluding, upper
-function numberRange(lower, upper)
-{
- let a = [];
- for (let i=lower; i<upper; ++i) {
- a.push(i);
- }
- return a;
-}
-
-function expect_fail(f) {
- let failed = false;
- try {
- f();
- failed = false;
- } catch (e) {
- failed = true;
- }
- do_check_true(failed);
-}
-
-function expect_success(f) {
- let succeeded = false;
- try {
- f();
- succeeded = true;
- } catch (e) {
- succeeded = false;
- }
- do_check_true(succeeded);
-}
-
-function compareHistograms(h1, h2) {
- let s1 = h1.snapshot();
- let s2 = h2.snapshot();
-
- do_check_eq(s1.histogram_type, s2.histogram_type);
- do_check_eq(s1.min, s2.min);
- do_check_eq(s1.max, s2.max);
- do_check_eq(s1.sum, s2.sum);
-
- do_check_eq(s1.counts.length, s2.counts.length);
- for (let i = 0; i < s1.counts.length; i++)
- do_check_eq(s1.counts[i], s2.counts[i]);
-
- do_check_eq(s1.ranges.length, s2.ranges.length);
- for (let i = 0; i < s1.ranges.length; i++)
- do_check_eq(s1.ranges[i], s2.ranges[i]);
-}
-
-function check_histogram(histogram_type, name, min, max, bucket_count) {
- var h = Telemetry.getHistogramById(name);
- var r = h.snapshot().ranges;
- var sum = 0;
- for (let i=0;i<r.length;i++) {
- var v = r[i];
- sum += v;
- h.add(v);
- }
- var s = h.snapshot();
- // verify properties
- do_check_eq(sum, s.sum);
-
- // there should be exactly one element per bucket
- for (let i of s.counts) {
- do_check_eq(i, 1);
- }
- var hgrams = Telemetry.histogramSnapshots
- let gh = hgrams[name]
- do_check_eq(gh.histogram_type, histogram_type);
-
- do_check_eq(gh.min, min)
- do_check_eq(gh.max, max)
-
- // Check that booleans work with nonboolean histograms
- h.add(false);
- h.add(true);
- s = h.snapshot().counts;
- do_check_eq(s[0], 2)
- do_check_eq(s[1], 2)
-
- // Check that clearing works.
- h.clear();
- s = h.snapshot();
- for (var i of s.counts) {
- do_check_eq(i, 0);
- }
- do_check_eq(s.sum, 0);
-
- h.add(0);
- h.add(1);
- var c = h.snapshot().counts;
- do_check_eq(c[0], 1);
- do_check_eq(c[1], 1);
-}
-
-// This MUST be the very first test of this file.
-add_task({
- skip_if: () => gIsAndroid
-},
-function* test_instantiate() {
- const ID = "TELEMETRY_TEST_COUNT";
- let h = Telemetry.getHistogramById(ID);
-
- // Instantiate the subsession histogram through |add| and make sure they match.
- // This MUST be the first use of "TELEMETRY_TEST_COUNT" in this file, otherwise
- // |add| will not instantiate the histogram.
- h.add(1);
- let snapshot = h.snapshot();
- let subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.equal(snapshot.sum, subsession[ID].sum,
- "Histogram and subsession histogram sum must match.");
- // Clear the histogram, so we don't void the assumptions from the other tests.
- h.clear();
-});
-
-add_task(function* test_parameterChecks() {
- let kinds = [Telemetry.HISTOGRAM_EXPONENTIAL, Telemetry.HISTOGRAM_LINEAR]
- let testNames = ["TELEMETRY_TEST_EXPONENTIAL", "TELEMETRY_TEST_LINEAR"]
- for (let i = 0; i < kinds.length; i++) {
- let histogram_type = kinds[i];
- let test_type = testNames[i];
- let [min, max, bucket_count] = [1, INT_MAX - 1, 10]
- check_histogram(histogram_type, test_type, min, max, bucket_count);
- }
-});
-
-add_task(function* test_noSerialization() {
- // Instantiate the storage for this histogram and make sure it doesn't
- // get reflected into JS, as it has no interesting data in it.
- Telemetry.getHistogramById("NEWTAB_PAGE_PINNED_SITES_COUNT");
- do_check_false("NEWTAB_PAGE_PINNED_SITES_COUNT" in Telemetry.histogramSnapshots);
-});
-
-add_task(function* test_boolean_histogram() {
- var h = Telemetry.getHistogramById("TELEMETRY_TEST_BOOLEAN");
- var r = h.snapshot().ranges;
- // boolean histograms ignore numeric parameters
- do_check_eq(uneval(r), uneval([0, 1, 2]))
- for (var i=0;i<r.length;i++) {
- var v = r[i];
- h.add(v);
- }
- h.add(true);
- h.add(false);
- var s = h.snapshot();
- do_check_eq(s.histogram_type, Telemetry.HISTOGRAM_BOOLEAN);
- // last bucket should always be 0 since .add parameters are normalized to either 0 or 1
- do_check_eq(s.counts[2], 0);
- do_check_eq(s.sum, 3);
- do_check_eq(s.counts[0], 2);
-});
-
-add_task(function* test_flag_histogram() {
- var h = Telemetry.getHistogramById("TELEMETRY_TEST_FLAG");
- var r = h.snapshot().ranges;
- // Flag histograms ignore numeric parameters.
- do_check_eq(uneval(r), uneval([0, 1, 2]));
- // Should already have a 0 counted.
- var c = h.snapshot().counts;
- var s = h.snapshot().sum;
- do_check_eq(uneval(c), uneval([1, 0, 0]));
- do_check_eq(s, 0);
- // Should switch counts.
- h.add(1);
- var c2 = h.snapshot().counts;
- var s2 = h.snapshot().sum;
- do_check_eq(uneval(c2), uneval([0, 1, 0]));
- do_check_eq(s2, 1);
- // Should only switch counts once.
- h.add(1);
- var c3 = h.snapshot().counts;
- var s3 = h.snapshot().sum;
- do_check_eq(uneval(c3), uneval([0, 1, 0]));
- do_check_eq(s3, 1);
- do_check_eq(h.snapshot().histogram_type, Telemetry.HISTOGRAM_FLAG);
-});
-
-add_task(function* test_count_histogram() {
- let h = Telemetry.getHistogramById("TELEMETRY_TEST_COUNT2");
- let s = h.snapshot();
- do_check_eq(uneval(s.ranges), uneval([0, 1, 2]));
- do_check_eq(uneval(s.counts), uneval([0, 0, 0]));
- do_check_eq(s.sum, 0);
- h.add();
- s = h.snapshot();
- do_check_eq(uneval(s.counts), uneval([1, 0, 0]));
- do_check_eq(s.sum, 1);
- h.add();
- s = h.snapshot();
- do_check_eq(uneval(s.counts), uneval([2, 0, 0]));
- do_check_eq(s.sum, 2);
-});
-
-add_task(function* test_categorical_histogram()
-{
- let h1 = Telemetry.getHistogramById("TELEMETRY_TEST_CATEGORICAL");
- for (let v of ["CommonLabel", "Label2", "Label3", "Label3", 0, 0, 1]) {
- h1.add(v);
- }
- for (let s of ["", "Label4", "1234"]) {
- Assert.throws(() => h1.add(s));
- }
-
- let snapshot = h1.snapshot();
- Assert.equal(snapshot.sum, 6);
- Assert.deepEqual(snapshot.ranges, [0, 1, 2, 3]);
- Assert.deepEqual(snapshot.counts, [3, 2, 2, 0]);
-
- let h2 = Telemetry.getHistogramById("TELEMETRY_TEST_CATEGORICAL_OPTOUT");
- for (let v of ["CommonLabel", "CommonLabel", "Label4", "Label5", "Label6", 0, 1]) {
- h2.add(v);
- }
- for (let s of ["", "Label3", "1234"]) {
- Assert.throws(() => h2.add(s));
- }
-
- snapshot = h2.snapshot();
- Assert.equal(snapshot.sum, 7);
- Assert.deepEqual(snapshot.ranges, [0, 1, 2, 3, 4]);
- Assert.deepEqual(snapshot.counts, [3, 2, 1, 1, 0]);
-});
-
-add_task(function* test_getHistogramById() {
- try {
- Telemetry.getHistogramById("nonexistent");
- do_throw("This can't happen");
- } catch (e) {
-
- }
- var h = Telemetry.getHistogramById("CYCLE_COLLECTOR");
- var s = h.snapshot();
- do_check_eq(s.histogram_type, Telemetry.HISTOGRAM_EXPONENTIAL);
- do_check_eq(s.min, 1);
- do_check_eq(s.max, 10000);
-});
-
-add_task(function* test_getSlowSQL() {
- var slow = Telemetry.slowSQL;
- do_check_true(("mainThread" in slow) && ("otherThreads" in slow));
-});
-
-add_task(function* test_getWebrtc() {
- var webrtc = Telemetry.webrtcStats;
- do_check_true("IceCandidatesStats" in webrtc);
- var icestats = webrtc.IceCandidatesStats;
- do_check_true("webrtc" in icestats);
-});
-
-// Check that telemetry doesn't record in private mode
-add_task(function* test_privateMode() {
- var h = Telemetry.getHistogramById("TELEMETRY_TEST_BOOLEAN");
- var orig = h.snapshot();
- Telemetry.canRecordExtended = false;
- h.add(1);
- do_check_eq(uneval(orig), uneval(h.snapshot()));
- Telemetry.canRecordExtended = true;
- h.add(1);
- do_check_neq(uneval(orig), uneval(h.snapshot()));
-});
-
-// Check that telemetry records only when it is suppose to.
-add_task(function* test_histogramRecording() {
- // Check that no histogram is recorded if both base and extended recording are off.
- Telemetry.canRecordBase = false;
- Telemetry.canRecordExtended = false;
-
- let h = Telemetry.getHistogramById("TELEMETRY_TEST_RELEASE_OPTOUT");
- h.clear();
- let orig = h.snapshot();
- h.add(1);
- Assert.equal(orig.sum, h.snapshot().sum);
-
- // Check that only base histograms are recorded.
- Telemetry.canRecordBase = true;
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "Histogram value should have incremented by 1 due to recording.");
-
- // Extended histograms should not be recorded.
- h = Telemetry.getHistogramById("TELEMETRY_TEST_RELEASE_OPTIN");
- orig = h.snapshot();
- h.add(1);
- Assert.equal(orig.sum, h.snapshot().sum,
- "Histograms should be equal after recording.");
-
- // Runtime created histograms should not be recorded.
- h = Telemetry.getHistogramById("TELEMETRY_TEST_BOOLEAN");
- orig = h.snapshot();
- h.add(1);
- Assert.equal(orig.sum, h.snapshot().sum,
- "Histograms should be equal after recording.");
-
- // Check that extended histograms are recorded when required.
- Telemetry.canRecordExtended = true;
-
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "Runtime histogram value should have incremented by 1 due to recording.");
-
- h = Telemetry.getHistogramById("TELEMETRY_TEST_RELEASE_OPTIN");
- orig = h.snapshot();
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "Histogram value should have incremented by 1 due to recording.");
-
- // Check that base histograms are still being recorded.
- h = Telemetry.getHistogramById("TELEMETRY_TEST_RELEASE_OPTOUT");
- h.clear();
- orig = h.snapshot();
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "Histogram value should have incremented by 1 due to recording.");
-});
-
-add_task(function* test_addons() {
- var addon_id = "testing-addon";
- var fake_addon_id = "fake-addon";
- var name1 = "testing-histogram1";
- var register = Telemetry.registerAddonHistogram;
- expect_success(() =>
- register(addon_id, name1, Telemetry.HISTOGRAM_LINEAR, 1, 5, 6));
- // Can't register the same histogram multiple times.
- expect_fail(() =>
- register(addon_id, name1, Telemetry.HISTOGRAM_LINEAR, 1, 5, 6));
- // Make sure we can't get at it with another name.
- expect_fail(() => Telemetry.getAddonHistogram(fake_addon_id, name1));
-
- // Check for reflection capabilities.
- var h1 = Telemetry.getAddonHistogram(addon_id, name1);
- // Verify that although we've created storage for it, we don't reflect it into JS.
- var snapshots = Telemetry.addonHistogramSnapshots;
- do_check_false(name1 in snapshots[addon_id]);
- h1.add(1);
- h1.add(3);
- var s1 = h1.snapshot();
- do_check_eq(s1.histogram_type, Telemetry.HISTOGRAM_LINEAR);
- do_check_eq(s1.min, 1);
- do_check_eq(s1.max, 5);
- do_check_eq(s1.counts[1], 1);
- do_check_eq(s1.counts[3], 1);
-
- var name2 = "testing-histogram2";
- expect_success(() =>
- register(addon_id, name2, Telemetry.HISTOGRAM_LINEAR, 2, 4, 4));
-
- var h2 = Telemetry.getAddonHistogram(addon_id, name2);
- h2.add(2);
- h2.add(3);
- var s2 = h2.snapshot();
- do_check_eq(s2.histogram_type, Telemetry.HISTOGRAM_LINEAR);
- do_check_eq(s2.min, 2);
- do_check_eq(s2.max, 4);
- do_check_eq(s2.counts[1], 1);
- do_check_eq(s2.counts[2], 1);
-
- // Check that we can register histograms for a different addon with
- // identical names.
- var extra_addon = "testing-extra-addon";
- expect_success(() =>
- register(extra_addon, name1, Telemetry.HISTOGRAM_BOOLEAN));
-
- // Check that we can register flag histograms.
- var flag_addon = "testing-flag-addon";
- var flag_histogram = "flag-histogram";
- expect_success(() =>
- register(flag_addon, flag_histogram, Telemetry.HISTOGRAM_FLAG));
- expect_success(() =>
- register(flag_addon, name2, Telemetry.HISTOGRAM_LINEAR, 2, 4, 4));
-
- // Check that we reflect registered addons and histograms.
- snapshots = Telemetry.addonHistogramSnapshots;
- do_check_true(addon_id in snapshots)
- do_check_true(extra_addon in snapshots);
- do_check_true(flag_addon in snapshots);
-
- // Check that we have data for our created histograms.
- do_check_true(name1 in snapshots[addon_id]);
- do_check_true(name2 in snapshots[addon_id]);
- var s1_alt = snapshots[addon_id][name1];
- var s2_alt = snapshots[addon_id][name2];
- do_check_eq(s1_alt.min, s1.min);
- do_check_eq(s1_alt.max, s1.max);
- do_check_eq(s1_alt.histogram_type, s1.histogram_type);
- do_check_eq(s2_alt.min, s2.min);
- do_check_eq(s2_alt.max, s2.max);
- do_check_eq(s2_alt.histogram_type, s2.histogram_type);
-
- // Even though we've registered it, it shouldn't show up until data is added to it.
- do_check_false(name1 in snapshots[extra_addon]);
-
- // Flag histograms should show up automagically.
- do_check_true(flag_histogram in snapshots[flag_addon]);
- do_check_false(name2 in snapshots[flag_addon]);
-
- // Check that we can remove addon histograms.
- Telemetry.unregisterAddonHistograms(addon_id);
- snapshots = Telemetry.addonHistogramSnapshots;
- do_check_false(addon_id in snapshots);
- // Make sure other addons are unaffected.
- do_check_true(extra_addon in snapshots);
-});
-
-add_task(function* test_expired_histogram() {
- var test_expired_id = "TELEMETRY_TEST_EXPIRED";
- var dummy = Telemetry.getHistogramById(test_expired_id);
- var rh = Telemetry.registeredHistograms(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, []);
- Assert.ok(!!rh);
-
- dummy.add(1);
-
- do_check_eq(Telemetry.histogramSnapshots["__expired__"], undefined);
- do_check_eq(Telemetry.histogramSnapshots[test_expired_id], undefined);
- do_check_eq(rh[test_expired_id], undefined);
-});
-
-add_task(function* test_keyed_histogram() {
- // Check that invalid names get rejected.
-
- let threw = false;
- try {
- Telemetry.getKeyedHistogramById("test::unknown histogram", "never", Telemetry.HISTOGRAM_BOOLEAN);
- } catch (e) {
- // This should throw as it is an unknown ID
- threw = true;
- }
- Assert.ok(threw, "getKeyedHistogramById should have thrown");
-});
-
-add_task(function* test_keyed_boolean_histogram() {
- const KEYED_ID = "TELEMETRY_TEST_KEYED_BOOLEAN";
- let KEYS = numberRange(0, 2).map(i => "key" + (i + 1));
- KEYS.push("漢語");
- let histogramBase = {
- "min": 1,
- "max": 2,
- "histogram_type": 2,
- "sum": 1,
- "ranges": [0, 1, 2],
- "counts": [0, 1, 0]
- };
- let testHistograms = numberRange(0, 3).map(i => JSON.parse(JSON.stringify(histogramBase)));
- let testKeys = [];
- let testSnapShot = {};
-
- let h = Telemetry.getKeyedHistogramById(KEYED_ID);
- for (let i=0; i<2; ++i) {
- let key = KEYS[i];
- h.add(key, true);
- testSnapShot[key] = testHistograms[i];
- testKeys.push(key);
-
- Assert.deepEqual(h.keys().sort(), testKeys);
- Assert.deepEqual(h.snapshot(), testSnapShot);
- }
-
- h = Telemetry.getKeyedHistogramById(KEYED_ID);
- Assert.deepEqual(h.keys().sort(), testKeys);
- Assert.deepEqual(h.snapshot(), testSnapShot);
-
- let key = KEYS[2];
- h.add(key, false);
- testKeys.push(key);
- testSnapShot[key] = testHistograms[2];
- testSnapShot[key].sum = 0;
- testSnapShot[key].counts = [1, 0, 0];
- Assert.deepEqual(h.keys().sort(), testKeys);
- Assert.deepEqual(h.snapshot(), testSnapShot);
-
- let allSnapshots = Telemetry.keyedHistogramSnapshots;
- Assert.deepEqual(allSnapshots[KEYED_ID], testSnapShot);
-
- h.clear();
- Assert.deepEqual(h.keys(), []);
- Assert.deepEqual(h.snapshot(), {});
-});
-
-add_task(function* test_keyed_count_histogram() {
- const KEYED_ID = "TELEMETRY_TEST_KEYED_COUNT";
- const KEYS = numberRange(0, 5).map(i => "key" + (i + 1));
- let histogramBase = {
- "min": 1,
- "max": 2,
- "histogram_type": 4,
- "sum": 0,
- "ranges": [0, 1, 2],
- "counts": [1, 0, 0]
- };
- let testHistograms = numberRange(0, 5).map(i => JSON.parse(JSON.stringify(histogramBase)));
- let testKeys = [];
- let testSnapShot = {};
-
- let h = Telemetry.getKeyedHistogramById(KEYED_ID);
- for (let i=0; i<4; ++i) {
- let key = KEYS[i];
- let value = i*2 + 1;
-
- for (let k=0; k<value; ++k) {
- h.add(key);
- }
- testHistograms[i].counts[0] = value;
- testHistograms[i].sum = value;
- testSnapShot[key] = testHistograms[i];
- testKeys.push(key);
-
- Assert.deepEqual(h.keys().sort(), testKeys);
- Assert.deepEqual(h.snapshot(key), testHistograms[i]);
- Assert.deepEqual(h.snapshot(), testSnapShot);
- }
-
- h = Telemetry.getKeyedHistogramById(KEYED_ID);
- Assert.deepEqual(h.keys().sort(), testKeys);
- Assert.deepEqual(h.snapshot(), testSnapShot);
-
- let key = KEYS[4];
- h.add(key);
- testKeys.push(key);
- testHistograms[4].counts[0] = 1;
- testHistograms[4].sum = 1;
- testSnapShot[key] = testHistograms[4];
-
- Assert.deepEqual(h.keys().sort(), testKeys);
- Assert.deepEqual(h.snapshot(), testSnapShot);
-
- let allSnapshots = Telemetry.keyedHistogramSnapshots;
- Assert.deepEqual(allSnapshots[KEYED_ID], testSnapShot);
-
- h.clear();
- Assert.deepEqual(h.keys(), []);
- Assert.deepEqual(h.snapshot(), {});
-});
-
-add_task(function* test_keyed_flag_histogram() {
- const KEYED_ID = "TELEMETRY_TEST_KEYED_FLAG";
- let h = Telemetry.getKeyedHistogramById(KEYED_ID);
-
- const KEY = "default";
- h.add(KEY, true);
-
- let testSnapshot = {};
- testSnapshot[KEY] = {
- "min": 1,
- "max": 2,
- "histogram_type": 3,
- "sum": 1,
- "ranges": [0, 1, 2],
- "counts": [0, 1, 0]
- };
-
- Assert.deepEqual(h.keys().sort(), [KEY]);
- Assert.deepEqual(h.snapshot(), testSnapshot);
-
- let allSnapshots = Telemetry.keyedHistogramSnapshots;
- Assert.deepEqual(allSnapshots[KEYED_ID], testSnapshot);
-
- h.clear();
- Assert.deepEqual(h.keys(), []);
- Assert.deepEqual(h.snapshot(), {});
-});
-
-add_task(function* test_keyed_histogram_recording() {
- // Check that no histogram is recorded if both base and extended recording are off.
- Telemetry.canRecordBase = false;
- Telemetry.canRecordExtended = false;
-
- const TEST_KEY = "record_foo";
- let h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT");
- h.clear();
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 0);
-
- // Check that only base histograms are recorded.
- Telemetry.canRecordBase = true;
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "The keyed histogram should record the correct value.");
-
- // Extended set keyed histograms should not be recorded.
- h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTIN");
- h.clear();
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 0,
- "The keyed histograms should not record any data.");
-
- // Check that extended histograms are recorded when required.
- Telemetry.canRecordExtended = true;
-
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "The runtime keyed histogram should record the correct value.");
-
- h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTIN");
- h.clear();
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "The keyed histogram should record the correct value.");
-
- // Check that base histograms are still being recorded.
- h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT");
- h.clear();
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1);
-});
-
-add_task(function* test_histogram_recording_enabled() {
- Telemetry.canRecordBase = true;
- Telemetry.canRecordExtended = true;
-
- // Check that a "normal" histogram respects recording-enabled on/off
- var h = Telemetry.getHistogramById("TELEMETRY_TEST_COUNT");
- var orig = h.snapshot();
-
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "add should record by default.");
-
- // Check that when recording is disabled - add is ignored
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_COUNT", false);
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "When recording is disabled add should not record.");
-
- // Check that we're back to normal after recording is enabled
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_COUNT", true);
- h.add(1);
- Assert.equal(orig.sum + 2, h.snapshot().sum,
- "When recording is re-enabled add should record.");
-
- // Check that we're correctly accumulating values other than 1.
- h.clear();
- h.add(3);
- Assert.equal(3, h.snapshot().sum, "Recording counts greater than 1 should work.");
-
- // Check that a histogram with recording disabled by default behaves correctly
- h = Telemetry.getHistogramById("TELEMETRY_TEST_COUNT_INIT_NO_RECORD");
- orig = h.snapshot();
-
- h.add(1);
- Assert.equal(orig.sum, h.snapshot().sum,
- "When recording is disabled by default, add should not record by default.");
-
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_COUNT_INIT_NO_RECORD", true);
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "When recording is enabled add should record.");
-
- // Restore to disabled
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_COUNT_INIT_NO_RECORD", false);
- h.add(1);
- Assert.equal(orig.sum + 1, h.snapshot().sum,
- "When recording is disabled add should not record.");
-});
-
-add_task(function* test_keyed_histogram_recording_enabled() {
- Telemetry.canRecordBase = true;
- Telemetry.canRecordExtended = true;
-
- // Check RecordingEnabled for keyed histograms which are recording by default
- const TEST_KEY = "record_foo";
- let h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT");
-
- h.clear();
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "Keyed histogram add should record by default");
-
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT", false);
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "Keyed histogram add should not record when recording is disabled");
-
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT", true);
- h.clear();
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "Keyed histogram add should record when recording is re-enabled");
-
- // Check that a histogram with recording disabled by default behaves correctly
- h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_COUNT_INIT_NO_RECORD");
- h.clear();
-
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 0,
- "Keyed histogram add should not record by default for histograms which don't record by default");
-
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_KEYED_COUNT_INIT_NO_RECORD", true);
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "Keyed histogram add should record when recording is enabled");
-
- // Restore to disabled
- Telemetry.setHistogramRecordingEnabled("TELEMETRY_TEST_KEYED_COUNT_INIT_NO_RECORD", false);
- h.add(TEST_KEY, 1);
- Assert.equal(h.snapshot(TEST_KEY).sum, 1,
- "Keyed histogram add should not record when recording is disabled");
-});
-
-add_task(function* test_datasets() {
- // Check that datasets work as expected.
-
- const RELEASE_CHANNEL_OPTOUT = Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTOUT;
- const RELEASE_CHANNEL_OPTIN = Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN;
-
- // Histograms should default to the extended dataset
- let h = Telemetry.getHistogramById("TELEMETRY_TEST_FLAG");
- Assert.equal(h.dataset(), RELEASE_CHANNEL_OPTIN);
- h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_FLAG");
- Assert.equal(h.dataset(), RELEASE_CHANNEL_OPTIN);
-
- // Check test histograms with explicit dataset definitions
- h = Telemetry.getHistogramById("TELEMETRY_TEST_RELEASE_OPTIN");
- Assert.equal(h.dataset(), RELEASE_CHANNEL_OPTIN);
- h = Telemetry.getHistogramById("TELEMETRY_TEST_RELEASE_OPTOUT");
- Assert.equal(h.dataset(), RELEASE_CHANNEL_OPTOUT);
- h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTIN");
- Assert.equal(h.dataset(), RELEASE_CHANNEL_OPTIN);
- h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT");
- Assert.equal(h.dataset(), RELEASE_CHANNEL_OPTOUT);
-
- // Check that registeredHistogram works properly
- let registered = Telemetry.registeredHistograms(RELEASE_CHANNEL_OPTIN, []);
- registered = new Set(registered);
- Assert.ok(registered.has("TELEMETRY_TEST_FLAG"));
- Assert.ok(registered.has("TELEMETRY_TEST_RELEASE_OPTIN"));
- Assert.ok(registered.has("TELEMETRY_TEST_RELEASE_OPTOUT"));
- registered = Telemetry.registeredHistograms(RELEASE_CHANNEL_OPTOUT, []);
- registered = new Set(registered);
- Assert.ok(!registered.has("TELEMETRY_TEST_FLAG"));
- Assert.ok(!registered.has("TELEMETRY_TEST_RELEASE_OPTIN"));
- Assert.ok(registered.has("TELEMETRY_TEST_RELEASE_OPTOUT"));
-
- // Check that registeredKeyedHistograms works properly
- registered = Telemetry.registeredKeyedHistograms(RELEASE_CHANNEL_OPTIN, []);
- registered = new Set(registered);
- Assert.ok(registered.has("TELEMETRY_TEST_KEYED_FLAG"));
- Assert.ok(registered.has("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT"));
- registered = Telemetry.registeredKeyedHistograms(RELEASE_CHANNEL_OPTOUT, []);
- registered = new Set(registered);
- Assert.ok(!registered.has("TELEMETRY_TEST_KEYED_FLAG"));
- Assert.ok(registered.has("TELEMETRY_TEST_KEYED_RELEASE_OPTOUT"));
-});
-
-add_task({
- skip_if: () => gIsAndroid
-},
-function* test_subsession() {
- const ID = "TELEMETRY_TEST_COUNT";
- const FLAG = "TELEMETRY_TEST_FLAG";
- let h = Telemetry.getHistogramById(ID);
- let flag = Telemetry.getHistogramById(FLAG);
-
- // Both original and duplicate should start out the same.
- h.clear();
- let snapshot = Telemetry.histogramSnapshots;
- let subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.ok(!(ID in snapshot));
- Assert.ok(!(ID in subsession));
-
- // They should instantiate and pick-up the count.
- h.add(1);
- snapshot = Telemetry.histogramSnapshots;
- subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.ok(ID in snapshot);
- Assert.ok(ID in subsession);
- Assert.equal(snapshot[ID].sum, 1);
- Assert.equal(subsession[ID].sum, 1);
-
- // They should still reset properly.
- h.clear();
- snapshot = Telemetry.histogramSnapshots;
- subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.ok(!(ID in snapshot));
- Assert.ok(!(ID in subsession));
-
- // Both should instantiate and pick-up the count.
- h.add(1);
- snapshot = Telemetry.histogramSnapshots;
- subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.equal(snapshot[ID].sum, 1);
- Assert.equal(subsession[ID].sum, 1);
-
- // Check that we are able to only reset the duplicate histogram.
- h.clear(true);
- snapshot = Telemetry.histogramSnapshots;
- subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.ok(ID in snapshot);
- Assert.ok(ID in subsession);
- Assert.equal(snapshot[ID].sum, 1);
- Assert.equal(subsession[ID].sum, 0);
-
- // Both should register the next count.
- h.add(1);
- snapshot = Telemetry.histogramSnapshots;
- subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.equal(snapshot[ID].sum, 2);
- Assert.equal(subsession[ID].sum, 1);
-
- // Retrieve a subsession snapshot and pass the flag to
- // clear subsession histograms too.
- h.clear();
- flag.clear();
- h.add(1);
- flag.add(1);
- snapshot = Telemetry.histogramSnapshots;
- subsession = Telemetry.snapshotSubsessionHistograms(true);
- Assert.ok(ID in snapshot);
- Assert.ok(ID in subsession);
- Assert.ok(FLAG in snapshot);
- Assert.ok(FLAG in subsession);
- Assert.equal(snapshot[ID].sum, 1);
- Assert.equal(subsession[ID].sum, 1);
- Assert.equal(snapshot[FLAG].sum, 1);
- Assert.equal(subsession[FLAG].sum, 1);
-
- // The next subsesssion snapshot should show the histograms
- // got reset.
- snapshot = Telemetry.histogramSnapshots;
- subsession = Telemetry.snapshotSubsessionHistograms();
- Assert.ok(ID in snapshot);
- Assert.ok(ID in subsession);
- Assert.ok(FLAG in snapshot);
- Assert.ok(FLAG in subsession);
- Assert.equal(snapshot[ID].sum, 1);
- Assert.equal(subsession[ID].sum, 0);
- Assert.equal(snapshot[FLAG].sum, 1);
- Assert.equal(subsession[FLAG].sum, 0);
-});
-
-add_task({
- skip_if: () => gIsAndroid
-},
-function* test_keyed_subsession() {
- let h = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_FLAG");
- const KEY = "foo";
-
- // Both original and subsession should start out the same.
- h.clear();
- Assert.ok(!(KEY in h.snapshot()));
- Assert.ok(!(KEY in h.subsessionSnapshot()));
- Assert.equal(h.snapshot(KEY).sum, 0);
- Assert.equal(h.subsessionSnapshot(KEY).sum, 0);
-
- // Both should register the flag.
- h.add(KEY, 1);
- Assert.ok(KEY in h.snapshot());
- Assert.ok(KEY in h.subsessionSnapshot());
- Assert.equal(h.snapshot(KEY).sum, 1);
- Assert.equal(h.subsessionSnapshot(KEY).sum, 1);
-
- // Check that we are able to only reset the subsession histogram.
- h.clear(true);
- Assert.ok(KEY in h.snapshot());
- Assert.ok(!(KEY in h.subsessionSnapshot()));
- Assert.equal(h.snapshot(KEY).sum, 1);
- Assert.equal(h.subsessionSnapshot(KEY).sum, 0);
-
- // Setting the flag again should make both match again.
- h.add(KEY, 1);
- Assert.ok(KEY in h.snapshot());
- Assert.ok(KEY in h.subsessionSnapshot());
- Assert.equal(h.snapshot(KEY).sum, 1);
- Assert.equal(h.subsessionSnapshot(KEY).sum, 1);
-
- // Check that "snapshot and clear" works properly.
- let snapshot = h.snapshot();
- let subsession = h.snapshotSubsessionAndClear();
- Assert.ok(KEY in snapshot);
- Assert.ok(KEY in subsession);
- Assert.equal(snapshot[KEY].sum, 1);
- Assert.equal(subsession[KEY].sum, 1);
-
- subsession = h.subsessionSnapshot();
- Assert.ok(!(KEY in subsession));
- Assert.equal(h.subsessionSnapshot(KEY).sum, 0);
-});
diff --git a/toolkit/components/telemetry/tests/unit/xpcshell.ini b/toolkit/components/telemetry/tests/unit/xpcshell.ini
deleted file mode 100644
index 224516f57..000000000
--- a/toolkit/components/telemetry/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,61 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-firefox-appdir = browser
-# The *.xpi files are only needed for test_TelemetryEnvironment.js, but
-# xpcshell fails to install tests if we move them under the test entry.
-support-files =
- ../search/chrome.manifest
- ../search/searchTest.jar
- dictionary.xpi
- experiment.xpi
- extension.xpi
- extension-2.xpi
- engine.xml
- system.xpi
- restartless.xpi
- theme.xpi
-generated-files =
- dictionary.xpi
- experiment.xpi
- extension.xpi
- extension-2.xpi
- system.xpi
- restartless.xpi
- theme.xpi
-
-[test_nsITelemetry.js]
-[test_SubsessionChaining.js]
-tags = addons
-[test_TelemetryEnvironment.js]
-skip-if = os == "android"
-tags = addons
-[test_PingAPI.js]
-skip-if = os == "android"
-[test_TelemetryFlagClear.js]
-[test_TelemetryLateWrites.js]
-[test_TelemetryLockCount.js]
-[test_TelemetryLog.js]
-[test_TelemetryController.js]
-tags = addons
-[test_TelemetryController_idle.js]
-[test_TelemetryControllerShutdown.js]
-tags = addons
-[test_TelemetryControllerBuildID.js]
-[test_TelemetrySendOldPings.js]
-skip-if = os == "android" # Disabled due to intermittent orange on Android
-tags = addons
-[test_TelemetrySession.js]
-tags = addons
-[test_ThreadHangStats.js]
-run-sequentially = Bug 1046307, test can fail intermittently when CPU load is high
-[test_TelemetrySend.js]
-[test_ChildHistograms.js]
-skip-if = os == "android"
-tags = addons
-[test_TelemetryReportingPolicy.js]
-tags = addons
-[test_TelemetryScalars.js]
-[test_TelemetryTimestamps.js]
-skip-if = toolkit == 'android'
-[test_TelemetryEvents.js]
diff --git a/toolkit/components/terminator/moz.build b/toolkit/components/terminator/moz.build
index 7e230ed4d..c0b2aa1c8 100644
--- a/toolkit/components/terminator/moz.build
+++ b/toolkit/components/terminator/moz.build
@@ -4,15 +4,9 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
+EXPORTS += ['nsTerminator.h']
-SOURCES += [
- 'nsTerminator.cpp',
-]
-
-EXPORTS += [
- 'nsTerminator.h',
-]
+SOURCES += ['nsTerminator.cpp']
EXTRA_COMPONENTS += [
'nsTerminatorTelemetry.js',
diff --git a/toolkit/components/terminator/tests/xpcshell/.eslintrc.js b/toolkit/components/terminator/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/terminator/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/terminator/tests/xpcshell/test_terminator_record.js b/toolkit/components/terminator/tests/xpcshell/test_terminator_record.js
deleted file mode 100644
index 248ead9ce..000000000
--- a/toolkit/components/terminator/tests/xpcshell/test_terminator_record.js
+++ /dev/null
@@ -1,108 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-
-// Test that the Shutdown Terminator records durations correctly
-
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Timer.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-
-var {Path, File, Constants} = OS;
-
-var PATH;
-var PATH_TMP;
-var terminator;
-
-add_task(function* init() {
- do_get_profile();
- PATH = Path.join(Constants.Path.localProfileDir, "ShutdownDuration.json");
- PATH_TMP = PATH + ".tmp";
-
- // Initialize the terminator
- // (normally, this is done through the manifest file, but xpcshell
- // doesn't take them into account).
- do_print("Initializing the Terminator");
- terminator = Cc["@mozilla.org/toolkit/shutdown-terminator;1"].
- createInstance(Ci.nsIObserver);
- terminator.observe(null, "profile-after-change", null);
-});
-
-var promiseShutdownDurationData = Task.async(function*() {
- // Wait until PATH exists.
- // Timeout if it is never created.
- do_print("Waiting for file creation: " + PATH);
- while (true) {
- if ((yield OS.File.exists(PATH))) {
- break;
- }
-
- do_print("The file does not exist yet. Waiting 1 second.");
- yield new Promise(resolve => setTimeout(resolve, 1000));
- }
-
- do_print("The file has been created");
- let raw = yield OS.File.read(PATH, { encoding: "utf-8"} );
- do_print(raw);
- return JSON.parse(raw);
-});
-
-add_task(function* test_record() {
- let PHASE0 = "profile-change-teardown";
- let PHASE1 = "profile-before-change";
- let PHASE2 = "xpcom-will-shutdown";
- let t0 = Date.now();
-
- do_print("Starting shutdown");
- terminator.observe(null, "profile-change-teardown", null);
-
- do_print("Moving to next phase");
- terminator.observe(null, PHASE1, null);
-
- let data = yield promiseShutdownDurationData();
-
- let t1 = Date.now();
-
- Assert.ok(PHASE0 in data, "The file contains the expected key");
- let duration = data[PHASE0];
- Assert.equal(typeof duration, "number");
- Assert.ok(duration >= 0, "Duration is a non-negative number");
- Assert.ok(duration <= Math.ceil((t1 - t0) / 1000) + 1,
- "Duration is reasonable");
-
- Assert.equal(Object.keys(data).length, 1, "Data does not contain other durations");
-
- do_print("Cleaning up and moving to next phase");
- yield File.remove(PATH);
- yield File.remove(PATH_TMP);
-
- do_print("Waiting at least one tick");
- let WAIT_MS = 2000;
- yield new Promise(resolve => setTimeout(resolve, WAIT_MS));
-
- terminator.observe(null, PHASE2, null);
- data = yield promiseShutdownDurationData();
-
- let t2 = Date.now();
-
- Assert.equal(Object.keys(data).sort().join(", "),
- [PHASE0, PHASE1].sort().join(", "),
- "The file contains the expected keys");
- Assert.equal(data[PHASE0], duration, "Duration of phase 0 hasn't changed");
- let duration2 = data[PHASE1];
- Assert.equal(typeof duration2, "number");
- Assert.ok(duration2 >= WAIT_MS / 2000, "We have waited at least " + (WAIT_MS / 2000) + " ticks");
- Assert.ok(duration2 <= Math.ceil((t2 - t1) / 1000) + 1,
- "Duration is reasonable");
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/terminator/tests/xpcshell/test_terminator_reload.js b/toolkit/components/terminator/tests/xpcshell/test_terminator_reload.js
deleted file mode 100644
index 1c16395b3..000000000
--- a/toolkit/components/terminator/tests/xpcshell/test_terminator_reload.js
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-
-// Test that the Shutdown Terminator reloads durations correctly
-
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-Cu.import("resource://gre/modules/Services.jsm", this);
-Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.import("resource://gre/modules/Timer.jsm", this);
-Cu.import("resource://gre/modules/Task.jsm", this);
-
-var {Path, File, Constants} = OS;
-
-var PATH;
-
-var HISTOGRAMS = {
- "quit-application": "SHUTDOWN_PHASE_DURATION_TICKS_QUIT_APPLICATION",
- "profile-change-teardown": "SHUTDOWN_PHASE_DURATION_TICKS_PROFILE_CHANGE_TEARDOWN",
- "profile-before-change": "SHUTDOWN_PHASE_DURATION_TICKS_PROFILE_BEFORE_CHANGE",
- "xpcom-will-shutdown": "SHUTDOWN_PHASE_DURATION_TICKS_XPCOM_WILL_SHUTDOWN",
-};
-
-add_task(function* init() {
- do_get_profile();
- PATH = Path.join(Constants.Path.localProfileDir, "ShutdownDuration.json");
-});
-
-add_task(function* test_reload() {
- do_print("Forging data");
- let data = {};
- let telemetrySnapshots = Services.telemetry.histogramSnapshots;
- let i = 0;
- for (let k of Object.keys(HISTOGRAMS)) {
- let id = HISTOGRAMS[k];
- data[k] = i++;
- Assert.equal(telemetrySnapshots[id] || undefined, undefined, "Histogram " + id + " is empty");
- }
-
-
- yield OS.File.writeAtomic(PATH, JSON.stringify(data));
-
- const TOPIC = "shutdown-terminator-telemetry-updated";
-
- let wait = new Promise(resolve =>
- Services.obs.addObserver(
- function observer() {
- do_print("Telemetry has been updated");
- Services.obs.removeObserver(observer, TOPIC);
- resolve();
- },
- TOPIC,
- false));
-
- do_print("Starting nsTerminatorTelemetry");
- let tt = Cc["@mozilla.org/toolkit/shutdown-terminator-telemetry;1"].
- createInstance(Ci.nsIObserver);
- tt.observe(null, "profile-after-change", "");
-
- do_print("Waiting until telemetry is updated");
- // Now wait until Telemetry is updated
- yield wait;
-
- telemetrySnapshots = Services.telemetry.histogramSnapshots;
- for (let k of Object.keys(HISTOGRAMS)) {
- let id = HISTOGRAMS[k];
- do_print("Testing histogram " + id);
- let snapshot = telemetrySnapshots[id];
- let count = 0;
- for (let x of snapshot.counts) {
- count += x;
- }
- Assert.equal(count, 1, "We have added one item");
- }
-
-});
-
-function run_test() {
- run_next_test();
-}
diff --git a/toolkit/components/terminator/tests/xpcshell/xpcshell.ini b/toolkit/components/terminator/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index 7f77938aa..000000000
--- a/toolkit/components/terminator/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-[DEFAULT]
-head=
-tail=
-
-[test_terminator_record.js]
-skip-if = debug # Disabled by bug 1242084, bug 1255484 will enable it again.
-[test_terminator_reload.js]
-skip-if = os == "android"
diff --git a/toolkit/components/thumbnails/moz.build b/toolkit/components/thumbnails/moz.build
index bd7c1d344..bd88532c0 100644
--- a/toolkit/components/thumbnails/moz.build
+++ b/toolkit/components/thumbnails/moz.build
@@ -4,9 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-BROWSER_CHROME_MANIFESTS += ['test/browser.ini']
-XPCSHELL_TESTS_MANIFESTS += ['test/xpcshell.ini']
-
EXTRA_COMPONENTS += [
'BrowserPageThumbs.manifest',
'PageThumbsProtocol.js',
@@ -22,5 +19,4 @@ EXTRA_PP_JS_MODULES += [
'PageThumbUtils.jsm',
]
-
JAR_MANIFESTS += ['jar.mn']
diff --git a/toolkit/components/thumbnails/test/.eslintrc.js b/toolkit/components/thumbnails/test/.eslintrc.js
deleted file mode 100644
index f6f8d62c2..000000000
--- a/toolkit/components/thumbnails/test/.eslintrc.js
+++ /dev/null
@@ -1,8 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js",
- "../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/thumbnails/test/authenticate.sjs b/toolkit/components/thumbnails/test/authenticate.sjs
deleted file mode 100644
index 58da655cf..000000000
--- a/toolkit/components/thumbnails/test/authenticate.sjs
+++ /dev/null
@@ -1,220 +0,0 @@
-function handleRequest(request, response)
-{
- try {
- reallyHandleRequest(request, response);
- } catch (e) {
- response.setStatusLine("1.0", 200, "AlmostOK");
- response.write("Error handling request: " + e);
- }
-}
-
-
-function reallyHandleRequest(request, response) {
- var match;
- var requestAuth = true, requestProxyAuth = true;
-
- // Allow the caller to drive how authentication is processed via the query.
- // Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
- // The extra ? allows the user/pass/realm checks to succeed if the name is
- // at the beginning of the query string.
- var query = "?" + request.queryString;
-
- var expected_user = "", expected_pass = "", realm = "mochitest";
- var proxy_expected_user = "", proxy_expected_pass = "", proxy_realm = "mochi-proxy";
- var huge = false, plugin = false, anonymous = false;
- var authHeaderCount = 1;
- // user=xxx
- match = /[^_]user=([^&]*)/.exec(query);
- if (match)
- expected_user = match[1];
-
- // pass=xxx
- match = /[^_]pass=([^&]*)/.exec(query);
- if (match)
- expected_pass = match[1];
-
- // realm=xxx
- match = /[^_]realm=([^&]*)/.exec(query);
- if (match)
- realm = match[1];
-
- // proxy_user=xxx
- match = /proxy_user=([^&]*)/.exec(query);
- if (match)
- proxy_expected_user = match[1];
-
- // proxy_pass=xxx
- match = /proxy_pass=([^&]*)/.exec(query);
- if (match)
- proxy_expected_pass = match[1];
-
- // proxy_realm=xxx
- match = /proxy_realm=([^&]*)/.exec(query);
- if (match)
- proxy_realm = match[1];
-
- // huge=1
- match = /huge=1/.exec(query);
- if (match)
- huge = true;
-
- // plugin=1
- match = /plugin=1/.exec(query);
- if (match)
- plugin = true;
-
- // multiple=1
- match = /multiple=([^&]*)/.exec(query);
- if (match)
- authHeaderCount = match[1]+0;
-
- // anonymous=1
- match = /anonymous=1/.exec(query);
- if (match)
- anonymous = true;
-
- // Look for an authentication header, if any, in the request.
- //
- // EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
- //
- // This test only supports Basic auth. The value sent by the client is
- // "username:password", obscured with base64 encoding.
-
- var actual_user = "", actual_pass = "", authHeader, authPresent = false;
- if (request.hasHeader("Authorization")) {
- authPresent = true;
- authHeader = request.getHeader("Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw "Couldn't parse auth header: " + authHeader;
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw "Couldn't decode auth header: " + userpass;
- actual_user = match[1];
- actual_pass = match[2];
- }
-
- var proxy_actual_user = "", proxy_actual_pass = "";
- if (request.hasHeader("Proxy-Authorization")) {
- authHeader = request.getHeader("Proxy-Authorization");
- match = /Basic (.+)/.exec(authHeader);
- if (match.length != 2)
- throw "Couldn't parse auth header: " + authHeader;
-
- var userpass = base64ToString(match[1]); // no atob() :-(
- match = /(.*):(.*)/.exec(userpass);
- if (match.length != 3)
- throw "Couldn't decode auth header: " + userpass;
- proxy_actual_user = match[1];
- proxy_actual_pass = match[2];
- }
-
- // Don't request authentication if the credentials we got were what we
- // expected.
- if (expected_user == actual_user &&
- expected_pass == actual_pass) {
- requestAuth = false;
- }
- if (proxy_expected_user == proxy_actual_user &&
- proxy_expected_pass == proxy_actual_pass) {
- requestProxyAuth = false;
- }
-
- if (anonymous) {
- if (authPresent) {
- response.setStatusLine("1.0", 400, "Unexpected authorization header found");
- } else {
- response.setStatusLine("1.0", 200, "Authorization header not found");
- }
- } else {
- if (requestProxyAuth) {
- response.setStatusLine("1.0", 407, "Proxy authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("Proxy-Authenticate", "basic realm=\"" + proxy_realm + "\"", true);
- } else if (requestAuth) {
- response.setStatusLine("1.0", 401, "Authentication required");
- for (i = 0; i < authHeaderCount; ++i)
- response.setHeader("WWW-Authenticate", "basic realm=\"" + realm + "\"", true);
- } else {
- response.setStatusLine("1.0", 200, "OK");
- }
- }
-
- response.setHeader("Content-Type", "application/xhtml+xml", false);
- response.write("<html xmlns='http://www.w3.org/1999/xhtml'>");
- response.write("<p>Login: <span id='ok'>" + (requestAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Proxy: <span id='proxy'>" + (requestProxyAuth ? "FAIL" : "PASS") + "</span></p>\n");
- response.write("<p>Auth: <span id='auth'>" + authHeader + "</span></p>\n");
- response.write("<p>User: <span id='user'>" + actual_user + "</span></p>\n");
- response.write("<p>Pass: <span id='pass'>" + actual_pass + "</span></p>\n");
-
- if (huge) {
- response.write("<div style='display: none'>");
- for (i = 0; i < 100000; i++) {
- response.write("123456789\n");
- }
- response.write("</div>");
- response.write("<span id='footnote'>This is a footnote after the huge content fill</span>");
- }
-
- if (plugin) {
- response.write("<embed id='embedtest' style='width: 400px; height: 100px;' " +
- "type='application/x-test'></embed>\n");
- }
-
- response.write("</html>");
-}
-
-
-// base64 decoder
-//
-// Yoinked from extensions/xml-rpc/src/nsXmlRpcClient.js because btoa()
-// doesn't seem to exist. :-(
-/* Convert Base64 data to a string */
-const toBinaryTable = [
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
-];
-const base64Pad = '=';
-
-function base64ToString(data) {
-
- var result = '';
- var leftbits = 0; // number of bits decoded, but yet to be appended
- var leftdata = 0; // bits decoded, but yet to be appended
-
- // Convert one by one.
- for (var i = 0; i < data.length; i++) {
- var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
- var padding = (data[i] == base64Pad);
- // Skip illegal characters and whitespace
- if (c == -1) continue;
-
- // Collect data into leftdata, update bitcount
- leftdata = (leftdata << 6) | c;
- leftbits += 6;
-
- // If we have 8 or more bits, append 8 bits to the result
- if (leftbits >= 8) {
- leftbits -= 8;
- // Append if not padding.
- if (!padding)
- result += String.fromCharCode((leftdata >> leftbits) & 0xff);
- leftdata &= (1 << leftbits) - 1;
- }
- }
-
- // If there are any bits left, the base64 string was corrupted
- if (leftbits)
- throw Components.Exception('Corrupted base64 string');
-
- return result;
-}
diff --git a/toolkit/components/thumbnails/test/background_red.html b/toolkit/components/thumbnails/test/background_red.html
deleted file mode 100644
index 95159dd29..000000000
--- a/toolkit/components/thumbnails/test/background_red.html
+++ /dev/null
@@ -1,3 +0,0 @@
-<html>
- <body bgcolor=ff0000></body>
-</html>
diff --git a/toolkit/components/thumbnails/test/background_red_redirect.sjs b/toolkit/components/thumbnails/test/background_red_redirect.sjs
deleted file mode 100644
index 5f0852e19..000000000
--- a/toolkit/components/thumbnails/test/background_red_redirect.sjs
+++ /dev/null
@@ -1,10 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function handleRequest(aRequest, aResponse) {
- // Set HTTP Status.
- aResponse.setStatusLine(aRequest.httpVersion, 301, "Moved Permanently");
-
- // Set redirect URI.
- aResponse.setHeader("Location", "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/background_red.html");
-}
diff --git a/toolkit/components/thumbnails/test/background_red_scroll.html b/toolkit/components/thumbnails/test/background_red_scroll.html
deleted file mode 100644
index 1e30bd3c6..000000000
--- a/toolkit/components/thumbnails/test/background_red_scroll.html
+++ /dev/null
@@ -1,3 +0,0 @@
-<html>
- <body bgcolor=ff0000 style="overflow: scroll;"></body>
-</html>
diff --git a/toolkit/components/thumbnails/test/browser.ini b/toolkit/components/thumbnails/test/browser.ini
deleted file mode 100644
index 3b87815ff..000000000
--- a/toolkit/components/thumbnails/test/browser.ini
+++ /dev/null
@@ -1,38 +0,0 @@
-[DEFAULT]
-support-files =
- authenticate.sjs
- background_red.html
- background_red_redirect.sjs
- background_red_scroll.html
- head.js
- privacy_cache_control.sjs
- thumbnails_background.sjs
- thumbnails_crash_content_helper.js
- thumbnails_update.sjs
-
-[browser_thumbnails_bg_bad_url.js]
-[browser_thumbnails_bg_crash_during_capture.js]
-skip-if = !crashreporter
-[browser_thumbnails_bg_crash_while_idle.js]
-skip-if = !crashreporter
-[browser_thumbnails_bg_basic.js]
-[browser_thumbnails_bg_queueing.js]
-[browser_thumbnails_bg_timeout.js]
-[browser_thumbnails_bg_redirect.js]
-[browser_thumbnails_bg_destroy_browser.js]
-[browser_thumbnails_bg_no_cookies_sent.js]
-[browser_thumbnails_bg_no_cookies_stored.js]
-[browser_thumbnails_bg_no_auth_prompt.js]
-[browser_thumbnails_bg_no_alert.js]
-[browser_thumbnails_bg_no_duplicates.js]
-[browser_thumbnails_bg_captureIfMissing.js]
-[browser_thumbnails_bug726727.js]
-[browser_thumbnails_bug727765.js]
-[browser_thumbnails_bug818225.js]
-[browser_thumbnails_capture.js]
-[browser_thumbnails_expiration.js]
-[browser_thumbnails_privacy.js]
-[browser_thumbnails_redirect.js]
-[browser_thumbnails_storage.js]
-[browser_thumbnails_storage_migrate3.js]
-[browser_thumbnails_update.js]
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_bad_url.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_bad_url.js
deleted file mode 100644
index df8ef8d96..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_bad_url.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let url = "invalid-protocol://ffggfsdfsdf/";
- ok(!thumbnailExists(url), "Thumbnail should not be cached already.");
- let numCalls = 0;
- BackgroundPageThumbs.capture(url, {
- onDone: function onDone(capturedURL) {
- is(capturedURL, url, "Captured URL should be URL passed to capture");
- is(numCalls++, 0, "onDone should be called only once");
- ok(!thumbnailExists(url),
- "Capture failed so thumbnail should not be cached");
- next();
- },
- });
- yield new Promise(resolve => {
- bgAddPageThumbObserver(url).catch(function(err) {
- ok(true, "page-thumbnail error produced");
- resolve();
- });
- });
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_basic.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_basic.js
deleted file mode 100644
index 027e0bfb7..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_basic.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let url = "http://www.example.com/";
- ok(!thumbnailExists(url), "Thumbnail should not be cached yet.");
-
- let capturePromise = new Promise(resolve => {
- bgAddPageThumbObserver(url).then(() => {
- ok(true, `page-thumbnail created for ${url}`);
- resolve();
- });
- });
- let capturedURL = yield bgCapture(url);
- is(capturedURL, url, "Captured URL should be URL passed to capture");
- yield capturePromise;
-
- ok(thumbnailExists(url), "Thumbnail should be cached after capture");
- removeThumbnail(url);
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_captureIfMissing.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_captureIfMissing.js
deleted file mode 100644
index cd1f1c5c2..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_captureIfMissing.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let numNotifications = 0;
- function observe(subject, topic, data) {
- is(topic, "page-thumbnail:create", "got expected topic");
- numNotifications += 1;
- }
-
- Services.obs.addObserver(observe, "page-thumbnail:create", false);
-
- let url = "http://example.com/";
- let file = thumbnailFile(url);
- ok(!file.exists(), "Thumbnail file should not already exist.");
-
- let capturedURL = yield bgCaptureIfMissing(url);
- is(numNotifications, 1, "got notification of item being created.");
- is(capturedURL, url, "Captured URL should be URL passed to capture");
- ok(file.exists(url), "Thumbnail should be cached after capture");
-
- let past = Date.now() - 1000000000;
- let pastFudge = past + 30000;
- file.lastModifiedTime = past;
- ok(file.lastModifiedTime < pastFudge, "Last modified time should stick!");
- capturedURL = yield bgCaptureIfMissing(url);
- is(numNotifications, 1, "still only 1 notification of item being created.");
- is(capturedURL, url, "Captured URL should be URL passed to second capture");
- ok(file.exists(), "Thumbnail should remain cached after second capture");
- ok(file.lastModifiedTime < pastFudge,
- "File should not have been overwritten");
-
- file.remove(false);
- Services.obs.removeObserver(observe, "page-thumbnail:create");
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_during_capture.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_during_capture.js
deleted file mode 100644
index db67a04a8..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_during_capture.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let crashObserver = bgAddCrashObserver();
-
- // make a good capture first - this ensures we have the <browser>
- let goodUrl = bgTestPageURL();
- yield bgCapture(goodUrl);
- ok(thumbnailExists(goodUrl), "Thumbnail should be cached after capture");
- removeThumbnail(goodUrl);
-
- // inject our content script.
- let mm = bgInjectCrashContentScript();
-
- // queue up 2 captures - the first has a wait, so this is the one that
- // will die. The second one should immediately capture after the crash.
- let waitUrl = bgTestPageURL({ wait: 30000 });
- let sawWaitUrlCapture = false;
- bgCapture(waitUrl, { onDone: () => {
- sawWaitUrlCapture = true;
- ok(!thumbnailExists(waitUrl), "Thumbnail should not have been saved due to the crash");
- }});
- bgCapture(goodUrl, { onDone: () => {
- ok(sawWaitUrlCapture, "waitUrl capture should have finished first");
- ok(thumbnailExists(goodUrl), "We should have recovered and completed the 2nd capture after the crash");
- removeThumbnail(goodUrl);
- // Test done.
- ok(crashObserver.crashed, "Saw a crash from this test");
- next();
- }});
- let crashPromise = new Promise(resolve => {
- bgAddPageThumbObserver(waitUrl).catch(function(err) {
- ok(true, `page-thumbnail error thrown for ${waitUrl}`);
- resolve();
- });
- });
- let capturePromise = new Promise(resolve => {
- bgAddPageThumbObserver(goodUrl).then(() => {
- ok(true, `page-thumbnail created for ${goodUrl}`);
- resolve();
- });
- });
-
- info("Crashing the thumbnail content process.");
- mm.sendAsyncMessage("thumbnails-test:crash");
- yield crashPromise;
- yield capturePromise;
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_while_idle.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_while_idle.js
deleted file mode 100644
index 8ff6a3509..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_crash_while_idle.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let crashObserver = bgAddCrashObserver();
-
- // make a good capture first - this ensures we have the <browser>
- let goodUrl = bgTestPageURL();
- yield bgCapture(goodUrl);
- ok(thumbnailExists(goodUrl), "Thumbnail should be cached after capture");
- removeThumbnail(goodUrl);
-
- // inject our content script.
- let mm = bgInjectCrashContentScript();
-
- // the observer for the crashing process is basically async, so it's hard
- // to know when the <browser> has actually seen it. Easist is to just add
- // our own observer.
- Services.obs.addObserver(function onCrash() {
- Services.obs.removeObserver(onCrash, "oop-frameloader-crashed");
- // spin the event loop to ensure the BPT observer was called.
- executeSoon(function() {
- // Now queue another capture and ensure it recovers.
- bgCapture(goodUrl, { onDone: () => {
- ok(thumbnailExists(goodUrl), "We should have recovered and handled new capture requests");
- removeThumbnail(goodUrl);
- // Test done.
- ok(crashObserver.crashed, "Saw a crash from this test");
- next();
- }});
- });
- }, "oop-frameloader-crashed", false);
-
- // Nothing is pending - crash the process.
- info("Crashing the thumbnail content process.");
- mm.sendAsyncMessage("thumbnails-test:crash");
- yield true;
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_destroy_browser.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_destroy_browser.js
deleted file mode 100644
index b83fdf583..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_destroy_browser.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- yield SpecialPowers.pushPrefEnv({
- set: [["dom.ipc.processCount", 1]]
- });
-
- let url1 = "http://example.com/1";
- ok(!thumbnailExists(url1), "First file should not exist yet.");
-
- let url2 = "http://example.com/2";
- ok(!thumbnailExists(url2), "Second file should not exist yet.");
-
- let defaultTimeout = BackgroundPageThumbs._destroyBrowserTimeout;
- BackgroundPageThumbs._destroyBrowserTimeout = 1000;
-
- yield bgCapture(url1);
- ok(thumbnailExists(url1), "First file should exist after capture.");
- removeThumbnail(url1);
-
- yield wait(2000);
- is(BackgroundPageThumbs._thumbBrowser, undefined,
- "Thumb browser should be destroyed after timeout.");
- BackgroundPageThumbs._destroyBrowserTimeout = defaultTimeout;
-
- yield bgCapture(url2);
- ok(thumbnailExists(url2), "Second file should exist after capture.");
- removeThumbnail(url2);
-
- isnot(BackgroundPageThumbs._thumbBrowser, undefined,
- "Thumb browser should exist immediately after capture.");
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_alert.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_alert.js
deleted file mode 100644
index 5d6bd81f8..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_alert.js
+++ /dev/null
@@ -1,13 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let url = "data:text/html,<script>try { alert('yo!'); } catch (e) {}</script>";
- ok(!thumbnailExists(url), "Thumbnail file should not already exist.");
-
- let capturedURL = yield bgCapture(url);
- is(capturedURL, url, "Captured URL should be URL passed to capture.");
- ok(thumbnailExists(url),
- "Thumbnail file should exist even though it alerted.");
- removeThumbnail(url);
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_auth_prompt.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_auth_prompt.js
deleted file mode 100644
index 0eb9df7a9..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_auth_prompt.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// the following tests attempt to display modal dialogs. The test just
-// relies on the fact that if the dialog was displayed the test will hang
-// and timeout. IOW - the tests would pass if the dialogs appear and are
-// manually closed by the user - so don't do that :) (obviously there is
-// noone available to do that when run via tbpl etc, so this should be safe,
-// and it's tricky to use the window-watcher to check a window *does not*
-// appear - how long should the watcher be active before assuming it's not
-// going to appear?)
-function* runTests() {
- let url = "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/authenticate.sjs?user=anyone";
- ok(!thumbnailExists(url), "Thumbnail file should not already exist.");
-
- let capturedURL = yield bgCapture(url);
- is(capturedURL, url, "Captured URL should be URL passed to capture.");
- ok(thumbnailExists(url),
- "Thumbnail file should exist even though it requires auth.");
- removeThumbnail(url);
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_sent.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_sent.js
deleted file mode 100644
index afbedb382..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_sent.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- // Visit the test page in the browser and tell it to set a cookie.
- let url = bgTestPageURL({ setGreenCookie: true });
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
- let browser = tab.linkedBrowser;
-
- // The root element of the page shouldn't be green yet.
- yield ContentTask.spawn(browser, null, function () {
- Assert.notEqual(content.document.documentElement.style.backgroundColor,
- "rgb(0, 255, 0)",
- "The page shouldn't be green yet.");
- });
-
- // Cookie should be set now. Reload the page to verify. Its root element
- // will be green if the cookie's set.
- browser.reload();
- yield BrowserTestUtils.browserLoaded(browser);
- yield ContentTask.spawn(browser, null, function () {
- Assert.equal(content.document.documentElement.style.backgroundColor,
- "rgb(0, 255, 0)",
- "The page should be green now.");
- });
-
- // Capture the page. Get the image data of the capture and verify it's not
- // green. (Checking only the first pixel suffices.)
- yield bgCapture(url);
- ok(thumbnailExists(url), "Thumbnail file should exist after capture.");
-
- retrieveImageDataForURL(url, function ([r, g, b]) {
- isnot([r, g, b].toString(), [0, 255, 0].toString(),
- "The captured page should not be green.");
- gBrowser.removeTab(tab);
- removeThumbnail(url);
- next();
- });
- yield true;
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_stored.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_stored.js
deleted file mode 100644
index 90a1a890b..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_cookies_stored.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// check that if a page captured in the background attempts to set a cookie,
-// that cookie is not saved for subsequent requests.
-function* runTests() {
- yield SpecialPowers.pushPrefEnv({
- set: [["privacy.usercontext.about_newtab_segregation.enabled", true]]
- });
- let url = bgTestPageURL({
- setRedCookie: true,
- iframe: bgTestPageURL({ setRedCookie: true}),
- xhr: bgTestPageURL({ setRedCookie: true})
- });
- ok(!thumbnailExists(url), "Thumbnail file should not exist before capture.");
- yield bgCapture(url);
- ok(thumbnailExists(url), "Thumbnail file should exist after capture.");
- removeThumbnail(url);
- // now load it up in a browser - it should *not* be red, otherwise the
- // cookie above was saved.
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url);
- let browser = tab.linkedBrowser;
-
- // The root element of the page shouldn't be red.
- yield ContentTask.spawn(browser, null, function() {
- Assert.notEqual(content.document.documentElement.style.backgroundColor,
- "rgb(255, 0, 0)",
- "The page shouldn't be red.");
- });
-
- gBrowser.removeTab(tab);
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_duplicates.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_duplicates.js
deleted file mode 100644
index 31b504335..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_no_duplicates.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let url = "http://example.com/1";
- ok(!thumbnailExists(url), "Thumbnail file should not already exist.");
- let numCallbacks = 0;
- let doneCallback = function(doneUrl) {
- is(doneUrl, url, "called back with correct url");
- numCallbacks += 1;
- // We will delete the file after the first callback, then check it
- // still doesn't exist on the second callback, which should give us
- // confidence that we didn't end up with 2 different captures happening
- // for the same url...
- if (numCallbacks == 1) {
- ok(thumbnailExists(url), "Thumbnail file should now exist.");
- removeThumbnail(url);
- return;
- }
- if (numCallbacks == 2) {
- ok(!thumbnailExists(url), "Thumbnail file should still be deleted.");
- // and that's all we expect, so we are done...
- next();
- return;
- }
- ok(false, "only expecting 2 callbacks");
- }
- BackgroundPageThumbs.capture(url, {onDone: doneCallback});
- BackgroundPageThumbs.capture(url, {onDone: doneCallback});
- yield true;
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_queueing.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_queueing.js
deleted file mode 100644
index 1426f6f4e..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_queueing.js
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let urls = [
- "http://www.example.com/0",
- "http://www.example.com/1",
- // an item that will timeout to ensure timeouts work and we resume.
- bgTestPageURL({ wait: 2002 }),
- "http://www.example.com/2",
- ];
- dontExpireThumbnailURLs(urls);
- urls.forEach(url => {
- ok(!thumbnailExists(url), "Thumbnail should not exist yet: " + url);
- let isTimeoutTest = url.indexOf("wait") >= 0;
- BackgroundPageThumbs.capture(url, {
- timeout: isTimeoutTest ? 100 : 30000,
- onDone: function onDone(capturedURL) {
- ok(urls.length > 0, "onDone called, so URLs should still remain");
- is(capturedURL, urls.shift(),
- "Captured URL should be currently expected URL (i.e., " +
- "capture() callbacks should be called in the correct order)");
- if (isTimeoutTest) {
- ok(!thumbnailExists(capturedURL),
- "Thumbnail shouldn't exist for timed out capture");
- } else {
- ok(thumbnailExists(capturedURL),
- "Thumbnail should be cached after capture");
- removeThumbnail(url);
- }
- if (!urls.length)
- // Test done.
- next();
- },
- });
- });
- yield true;
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_redirect.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_redirect.js
deleted file mode 100644
index baa1b6d68..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_redirect.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let finalURL = "http://example.com/redirected";
- let originalURL = bgTestPageURL({ redirect: finalURL });
-
- ok(!thumbnailExists(originalURL),
- "Thumbnail file for original URL should not exist yet.");
- ok(!thumbnailExists(finalURL),
- "Thumbnail file for final URL should not exist yet.");
-
- let captureOriginalPromise = new Promise(resolve => {
- bgAddPageThumbObserver(originalURL).then(() => {
- ok(true, `page-thumbnail created for ${originalURL}`);
- resolve();
- });
- });
-
- let captureFinalPromise = new Promise(resolve => {
- bgAddPageThumbObserver(finalURL).then(() => {
- ok(true, `page-thumbnail created for ${finalURL}`);
- resolve();
- });
- });
-
- let capturedURL = yield bgCapture(originalURL);
- is(capturedURL, originalURL,
- "Captured URL should be URL passed to capture");
- yield captureOriginalPromise;
- yield captureFinalPromise;
- ok(thumbnailExists(originalURL),
- "Thumbnail for original URL should be cached");
- ok(thumbnailExists(finalURL),
- "Thumbnail for final URL should be cached");
-
- removeThumbnail(originalURL);
- removeThumbnail(finalURL);
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bg_timeout.js b/toolkit/components/thumbnails/test/browser_thumbnails_bg_timeout.js
deleted file mode 100644
index da05b4355..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bg_timeout.js
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function* runTests() {
- let url = bgTestPageURL({ wait: 30000 });
- ok(!thumbnailExists(url), "Thumbnail should not be cached already.");
- let numCalls = 0;
- BackgroundPageThumbs.capture(url, {
- timeout: 0,
- onDone: function onDone(capturedURL) {
- is(capturedURL, url, "Captured URL should be URL passed to capture");
- is(numCalls++, 0, "onDone should be called only once");
- ok(!thumbnailExists(url),
- "Capture timed out so thumbnail should not be cached");
- next();
- },
- });
- yield new Promise(resolve => {
- bgAddPageThumbObserver(url).catch(function(err) {
- ok(true, `page-thumbnail error thrown for ${url}`);
- resolve();
- });
- });
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bug726727.js b/toolkit/components/thumbnails/test/browser_thumbnails_bug726727.js
deleted file mode 100644
index f7f1f3deb..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bug726727.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * These tests ensure that capturing a sites's thumbnail, saving it and
- * retrieving it from the cache works.
- */
-function* runTests() {
- // Create a tab that shows an error page.
- let tab = gBrowser.addTab("http://127.0.0.1:1/");
- let browser = tab.linkedBrowser;
- yield browser.addEventListener("DOMContentLoaded", function onLoad() {
- browser.removeEventListener("DOMContentLoaded", onLoad, false);
- PageThumbs.shouldStoreThumbnail(browser, (aResult) => {
- ok(!aResult, "we're not going to capture an error page");
- executeSoon(next);
- });
- }, false);
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bug727765.js b/toolkit/components/thumbnails/test/browser_thumbnails_bug727765.js
deleted file mode 100644
index c4faac685..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bug727765.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/" +
- "test/background_red_scroll.html";
-
-function isRedThumbnailFuzz(r, g, b, expectedR, expectedB, expectedG, aFuzz)
-{
- return (Math.abs(r - expectedR) <= aFuzz) &&
- (Math.abs(g - expectedG) <= aFuzz) &&
- (Math.abs(b - expectedB) <= aFuzz);
-}
-
-// Test for black borders caused by scrollbars.
-function* runTests() {
- // Create a tab with a page with a red background and scrollbars.
- yield addTab(URL);
- yield captureAndCheckColor(255, 0, 0, "we have a red thumbnail");
-
- // Check the thumbnail color of the bottom right pixel.
- yield whenFileExists(URL);
- yield retrieveImageDataForURL(URL, function (aData) {
- let [r, g, b] = [].slice.call(aData, -4);
- let fuzz = 2; // Windows 8 x64 blends with the scrollbar a bit.
- var message = "Expected red thumbnail rgb(255, 0, 0), got " + r + "," + g + "," + b;
- ok(isRedThumbnailFuzz(r, g, b, 255, 0, 0, fuzz), message);
- next();
- });
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js b/toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js
deleted file mode 100644
index a7e1caa04..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/" +
- "test/background_red.html?" + Date.now();
-
-// Test PageThumbs API function getThumbnailPath
-function* runTests() {
-
- let path = PageThumbs.getThumbnailPath(URL);
- yield testIfExists(path, false, "Thumbnail file does not exist");
-
- yield addVisitsAndRepopulateNewTabLinks(URL, next);
- yield createThumbnail(URL);
-
- path = PageThumbs.getThumbnailPath(URL);
- let expectedPath = PageThumbsStorage.getFilePathForURL(URL);
- is(path, expectedPath, "Thumbnail file has correct path");
-
- yield testIfExists(path, true, "Thumbnail file exists");
-
-}
-
-function createThumbnail(aURL) {
- addTab(aURL, function () {
- whenFileExists(aURL, function () {
- gBrowser.removeTab(gBrowser.selectedTab);
- next();
- });
- });
-}
-
-function testIfExists(aPath, aExpected, aMessage) {
- return OS.File.exists(aPath).then(
- function onSuccess(exists) {
- is(exists, aExpected, aMessage);
- },
- function onFailure(error) {
- ok(false, "OS.File.exists() failed " + error);
- }
- );
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_capture.js b/toolkit/components/thumbnails/test/browser_thumbnails_capture.js
deleted file mode 100644
index 47d94d31b..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_capture.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * These tests ensure that capturing a sites's thumbnail, saving it and
- * retrieving it from the cache works.
- */
-function* runTests() {
- // Create a tab with a red background.
- yield addTab("data:text/html,<body bgcolor=ff0000></body>");
- yield captureAndCheckColor(255, 0, 0, "we have a red thumbnail");
-
- // Load a page with a green background.
- yield navigateTo("data:text/html,<body bgcolor=00ff00></body>");
- yield captureAndCheckColor(0, 255, 0, "we have a green thumbnail");
-
- // Load a page with a blue background.
- yield navigateTo("data:text/html,<body bgcolor=0000ff></body>");
- yield captureAndCheckColor(0, 0, 255, "we have a blue thumbnail");
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_expiration.js b/toolkit/components/thumbnails/test/browser_thumbnails_expiration.js
deleted file mode 100644
index 4c73e17be..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_expiration.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const URL = "http://mochi.test:8888/?t=" + Date.now();
-const URL1 = URL + "#1";
-const URL2 = URL + "#2";
-const URL3 = URL + "#3";
-
-var tmp = {};
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("resource://gre/modules/PageThumbs.jsm", tmp);
-
-const EXPIRATION_MIN_CHUNK_SIZE = 50;
-const {PageThumbsExpiration} = tmp;
-
-function* runTests() {
- // Create dummy URLs.
- let dummyURLs = [];
- for (let i = 0; i < EXPIRATION_MIN_CHUNK_SIZE + 10; i++) {
- dummyURLs.push(URL + "#dummy" + i);
- }
-
- // Make sure our thumbnails aren't expired too early.
- dontExpireThumbnailURLs([URL1, URL2, URL3].concat(dummyURLs));
-
- // Create three thumbnails.
- yield createDummyThumbnail(URL1);
- ok(thumbnailExists(URL1), "first thumbnail created");
-
- yield createDummyThumbnail(URL2);
- ok(thumbnailExists(URL2), "second thumbnail created");
-
- yield createDummyThumbnail(URL3);
- ok(thumbnailExists(URL3), "third thumbnail created");
-
- // Remove the third thumbnail.
- yield expireThumbnails([URL1, URL2]);
- ok(thumbnailExists(URL1), "first thumbnail still exists");
- ok(thumbnailExists(URL2), "second thumbnail still exists");
- ok(!thumbnailExists(URL3), "third thumbnail has been removed");
-
- // Remove the second thumbnail.
- yield expireThumbnails([URL1]);
- ok(thumbnailExists(URL1), "first thumbnail still exists");
- ok(!thumbnailExists(URL2), "second thumbnail has been removed");
-
- // Remove all thumbnails.
- yield expireThumbnails([]);
- ok(!thumbnailExists(URL1), "all thumbnails have been removed");
-
- // Create some more files than the min chunk size.
- for (let url of dummyURLs) {
- yield createDummyThumbnail(url);
- }
-
- ok(dummyURLs.every(thumbnailExists), "all dummy thumbnails created");
-
- // Expire thumbnails and expect 10 remaining.
- yield expireThumbnails([]);
- let remainingURLs = dummyURLs.filter(thumbnailExists);
- is(remainingURLs.length, 10, "10 dummy thumbnails remaining");
-
- // Expire thumbnails again. All should be gone by now.
- yield expireThumbnails([]);
- remainingURLs = remainingURLs.filter(thumbnailExists);
- is(remainingURLs.length, 0, "no dummy thumbnails remaining");
-}
-
-function createDummyThumbnail(aURL) {
- info("Creating dummy thumbnail for " + aURL);
- let dummy = new Uint8Array(10);
- for (let i = 0; i < 10; ++i) {
- dummy[i] = i;
- }
- PageThumbsStorage.writeData(aURL, dummy).then(
- function onSuccess() {
- info("createDummyThumbnail succeeded");
- executeSoon(next);
- },
- function onFailure(error) {
- ok(false, "createDummyThumbnail failed " + error);
- }
- );
-}
-
-function expireThumbnails(aKeep) {
- PageThumbsExpiration.expireThumbnails(aKeep).then(
- function onSuccess() {
- info("expireThumbnails succeeded");
- executeSoon(next);
- },
- function onFailure(error) {
- ok(false, "expireThumbnails failed " + error);
- }
- );
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_privacy.js b/toolkit/components/thumbnails/test/browser_thumbnails_privacy.js
deleted file mode 100644
index e7dc7b4d5..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_privacy.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const PREF_DISK_CACHE_SSL = "browser.cache.disk_cache_ssl";
-const URL = "://example.com/browser/toolkit/components/thumbnails/" +
- "test/privacy_cache_control.sjs";
-
-function* runTests() {
- registerCleanupFunction(function () {
- Services.prefs.clearUserPref(PREF_DISK_CACHE_SSL);
- });
-
- let positive = [
- // A normal HTTP page without any Cache-Control header.
- {scheme: "http", cacheControl: null, diskCacheSSL: false},
-
- // A normal HTTP page with 'Cache-Control: private'.
- {scheme: "http", cacheControl: "private", diskCacheSSL: false},
-
- // Capture HTTPS pages if browser.cache.disk_cache_ssl == true.
- {scheme: "https", cacheControl: null, diskCacheSSL: true},
- {scheme: "https", cacheControl: "public", diskCacheSSL: true},
- {scheme: "https", cacheControl: "private", diskCacheSSL: true}
- ];
-
- let negative = [
- // Never capture pages with 'Cache-Control: no-store'.
- {scheme: "http", cacheControl: "no-store", diskCacheSSL: false},
- {scheme: "http", cacheControl: "no-store", diskCacheSSL: true},
- {scheme: "https", cacheControl: "no-store", diskCacheSSL: false},
- {scheme: "https", cacheControl: "no-store", diskCacheSSL: true},
-
- // Don't capture HTTPS pages by default.
- {scheme: "https", cacheControl: null, diskCacheSSL: false},
- {scheme: "https", cacheControl: "public", diskCacheSSL: false},
- {scheme: "https", cacheControl: "private", diskCacheSSL: false}
- ];
-
- yield checkCombinations(positive, true);
- yield checkCombinations(negative, false);
-}
-
-function checkCombinations(aCombinations, aResult) {
- let combi = aCombinations.shift();
- if (!combi) {
- next();
- return;
- }
-
- let url = combi.scheme + URL;
- if (combi.cacheControl)
- url += "?" + combi.cacheControl;
- Services.prefs.setBoolPref(PREF_DISK_CACHE_SSL, combi.diskCacheSSL);
-
- // Add the test page as a top link so it has a chance to be thumbnailed
- addVisitsAndRepopulateNewTabLinks(url, _ => {
- testCombination(combi, url, aCombinations, aResult);
- });
-}
-
-function testCombination(combi, url, aCombinations, aResult) {
- let tab = gBrowser.selectedTab = gBrowser.addTab(url);
- let browser = gBrowser.selectedBrowser;
-
- whenLoaded(browser, () => {
- let msg = JSON.stringify(combi) + " == " + aResult;
- PageThumbs.shouldStoreThumbnail(browser, (aIsSafeSite) => {
- is(aIsSafeSite, aResult, msg);
- gBrowser.removeTab(tab);
- // Continue with the next combination.
- checkCombinations(aCombinations, aResult);
- });
- });
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_redirect.js b/toolkit/components/thumbnails/test/browser_thumbnails_redirect.js
deleted file mode 100644
index 482dbc803..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_redirect.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/" +
- "test/background_red_redirect.sjs";
-// loading URL will redirect us to...
-const FINAL_URL = "http://mochi.test:8888/browser/toolkit/components/" +
- "thumbnails/test/background_red.html";
-
-/**
- * These tests ensure that we save and provide thumbnails for redirecting sites.
- */
-function* runTests() {
- dontExpireThumbnailURLs([URL, FINAL_URL]);
-
- // Kick off history by loading a tab first or the test fails in single mode.
- yield addTab(URL);
- gBrowser.removeTab(gBrowser.selectedTab);
-
- // Create a tab, redirecting to a page with a red background.
- yield addTab(URL);
- yield captureAndCheckColor(255, 0, 0, "we have a red thumbnail");
-
- // Wait until the referrer's thumbnail's file has been written.
- yield whenFileExists(URL);
- yield retrieveImageDataForURL(URL, function ([r, g, b]) {
- is("" + [r, g, b], "255,0,0", "referrer has a red thumbnail");
- next();
- });
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_storage.js b/toolkit/components/thumbnails/test/browser_thumbnails_storage.js
deleted file mode 100644
index 972f956e5..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_storage.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const URL = "http://mochi.test:8888/";
-const URL_COPY = URL + "#copy";
-
-XPCOMUtils.defineLazyGetter(this, "Sanitizer", function () {
- let tmp = {};
- Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("chrome://browser/content/sanitize.js", tmp);
- return tmp.Sanitizer;
-});
-
-/**
- * These tests ensure that the thumbnail storage is working as intended.
- * Newly captured thumbnails should be saved as files and they should as well
- * be removed when the user sanitizes their history.
- */
-function* runTests() {
- yield Task.spawn(function*() {
- dontExpireThumbnailURLs([URL, URL_COPY]);
-
- yield promiseClearHistory();
- yield promiseAddVisitsAndRepopulateNewTabLinks(URL);
- yield promiseCreateThumbnail();
-
- // Make sure Storage.copy() updates an existing file.
- yield PageThumbsStorage.copy(URL, URL_COPY);
- let copy = new FileUtils.File(PageThumbsStorage.getFilePathForURL(URL_COPY));
- let mtime = copy.lastModifiedTime -= 60;
-
- yield PageThumbsStorage.copy(URL, URL_COPY);
- isnot(new FileUtils.File(PageThumbsStorage.getFilePathForURL(URL_COPY)).lastModifiedTime, mtime,
- "thumbnail file was updated");
-
- let file = new FileUtils.File(PageThumbsStorage.getFilePathForURL(URL));
- let fileCopy = new FileUtils.File(PageThumbsStorage.getFilePathForURL(URL_COPY));
-
- // Clear the browser history. Retry until the files are gone because Windows
- // locks them sometimes.
- info("Clearing history");
- while (file.exists() || fileCopy.exists()) {
- yield promiseClearHistory();
- }
- info("History is clear");
-
- info("Repopulating");
- yield promiseAddVisitsAndRepopulateNewTabLinks(URL);
- yield promiseCreateThumbnail();
-
- info("Clearing the last 10 minutes of browsing history");
- // Clear the last 10 minutes of browsing history.
- yield promiseClearHistory(true);
-
- info("Attempt to clear file");
- // Retry until the file is gone because Windows locks it sometimes.
- yield promiseClearFile(file, URL);
-
- info("Done");
- });
-}
-
-var promiseClearFile = Task.async(function*(aFile, aURL) {
- if (!aFile.exists()) {
- return undefined;
- }
- // Re-add our URL to the history so that history observer's onDeleteURI()
- // is called again.
- yield PlacesTestUtils.addVisits(makeURI(aURL));
- yield promiseClearHistory(true);
- // Then retry.
- return promiseClearFile(aFile, aURL);
-});
-
-function promiseClearHistory(aUseRange) {
- let s = new Sanitizer();
- s.prefDomain = "privacy.cpd.";
-
- let prefs = gPrefService.getBranch(s.prefDomain);
- prefs.setBoolPref("history", true);
- prefs.setBoolPref("downloads", false);
- prefs.setBoolPref("cache", false);
- prefs.setBoolPref("cookies", false);
- prefs.setBoolPref("formdata", false);
- prefs.setBoolPref("offlineApps", false);
- prefs.setBoolPref("passwords", false);
- prefs.setBoolPref("sessions", false);
- prefs.setBoolPref("siteSettings", false);
-
- if (aUseRange) {
- let usec = Date.now() * 1000;
- s.range = [usec - 10 * 60 * 1000 * 1000, usec];
- s.ignoreTimespan = false;
- }
-
- return s.sanitize().then(() => {
- s.range = null;
- s.ignoreTimespan = true;
- });
-}
-
-function promiseCreateThumbnail() {
- return new Promise(resolve => {
- addTab(URL, function () {
- whenFileExists(URL, function () {
- gBrowser.removeTab(gBrowser.selectedTab);
- resolve();
- });
- });
- });
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_storage_migrate3.js b/toolkit/components/thumbnails/test/browser_thumbnails_storage_migrate3.js
deleted file mode 100644
index e7f150f87..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_storage_migrate3.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const URL = "http://mochi.test:8888/migration3";
-const URL2 = URL + "#2";
-const URL3 = URL + "#3";
-const THUMBNAIL_DIRECTORY = "thumbnails";
-const PREF_STORAGE_VERSION = "browser.pagethumbnails.storage_version";
-
-var tmp = {};
-Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader)
- .loadSubScript("resource://gre/modules/PageThumbs.jsm", tmp);
-var {PageThumbsStorageMigrator} = tmp;
-
-XPCOMUtils.defineLazyServiceGetter(this, "gDirSvc",
- "@mozilla.org/file/directory_service;1", "nsIProperties");
-
-/**
- * This test makes sure we correctly migrate to thumbnail storage version 3.
- * This means copying existing thumbnails from the roaming to the local profile
- * directory and should just apply to Linux.
- */
-function* runTests() {
- // Prepare a local profile directory.
- let localProfile = FileUtils.getDir("ProfD", ["local-test"], true);
- changeLocation("ProfLD", localProfile);
-
- let roaming = FileUtils.getDir("ProfD", [THUMBNAIL_DIRECTORY], true);
-
- // Set up some data in the roaming profile.
- let name = PageThumbsStorage.getLeafNameForURL(URL);
- let file = FileUtils.getFile("ProfD", [THUMBNAIL_DIRECTORY, name]);
- writeDummyFile(file);
-
- name = PageThumbsStorage.getLeafNameForURL(URL2);
- file = FileUtils.getFile("ProfD", [THUMBNAIL_DIRECTORY, name]);
- writeDummyFile(file);
-
- name = PageThumbsStorage.getLeafNameForURL(URL3);
- file = FileUtils.getFile("ProfD", [THUMBNAIL_DIRECTORY, name]);
- writeDummyFile(file);
-
- // Pretend to have one of the thumbnails
- // already in place at the new storage site.
- name = PageThumbsStorage.getLeafNameForURL(URL3);
- file = FileUtils.getFile("ProfLD", [THUMBNAIL_DIRECTORY, name]);
- writeDummyFile(file, "no-overwrite-plz");
-
- // Kick off thumbnail storage migration.
- PageThumbsStorageMigrator.migrateToVersion3(localProfile.path);
- ok(true, "migration finished");
-
- // Wait until the first thumbnail was moved to its new location.
- yield whenFileExists(URL);
- ok(true, "first thumbnail moved");
-
- // Wait for the second thumbnail to be moved as well.
- yield whenFileExists(URL2);
- ok(true, "second thumbnail moved");
-
- yield whenFileRemoved(roaming);
- ok(true, "roaming thumbnail directory removed");
-
- // Check that our existing thumbnail wasn't overwritten.
- is(getFileContents(file), "no-overwrite-plz",
- "existing thumbnail was not overwritten");
-
- // Sanity check: ensure that, until it is removed, deprecated
- // function |getFileForURL| points to the same path as
- // |getFilePathForURL|.
- if ("getFileForURL" in PageThumbsStorage) {
- file = PageThumbsStorage.getFileForURL(URL);
- is(file.path, PageThumbsStorage.getFilePathForURL(URL),
- "Deprecated getFileForURL and getFilePathForURL return the same path");
- }
-}
-
-function changeLocation(aLocation, aNewDir) {
- let oldDir = gDirSvc.get(aLocation, Ci.nsILocalFile);
- gDirSvc.undefine(aLocation);
- gDirSvc.set(aLocation, aNewDir);
-
- registerCleanupFunction(function () {
- gDirSvc.undefine(aLocation);
- gDirSvc.set(aLocation, oldDir);
- });
-}
-
-function writeDummyFile(aFile, aContents) {
- let fos = FileUtils.openSafeFileOutputStream(aFile);
- let data = aContents || "dummy";
- fos.write(data, data.length);
- FileUtils.closeSafeFileOutputStream(fos);
-}
-
-function getFileContents(aFile) {
- let istream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- istream.init(aFile, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0);
- return NetUtil.readInputStreamToString(istream, istream.available());
-}
diff --git a/toolkit/components/thumbnails/test/browser_thumbnails_update.js b/toolkit/components/thumbnails/test/browser_thumbnails_update.js
deleted file mode 100644
index 971a2994e..000000000
--- a/toolkit/components/thumbnails/test/browser_thumbnails_update.js
+++ /dev/null
@@ -1,169 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/**
- * These tests check the auto-update facility of the thumbnail service.
- */
-
-function* runTests() {
- // A "trampoline" - a generator that iterates over sub-iterators
- let tests = [
- simpleCaptureTest,
- capIfStaleErrorResponseUpdateTest,
- capIfStaleGoodResponseUpdateTest,
- regularCapErrorResponseUpdateTest,
- regularCapGoodResponseUpdateTest
- ];
- for (let test of tests) {
- info("Running subtest " + test.name);
- for (let iterator of test())
- yield iterator;
- }
-}
-
-function ensureThumbnailStale(url) {
- // We go behind the back of the thumbnail service and change the
- // mtime of the file to be in the past.
- let fname = PageThumbsStorage.getFilePathForURL(url);
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.initWithPath(fname);
- ok(file.exists(), fname + " should exist");
- // Set it as very stale...
- file.lastModifiedTime = Date.now() - 1000000000;
-}
-
-function getThumbnailModifiedTime(url) {
- let fname = PageThumbsStorage.getFilePathForURL(url);
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.initWithPath(fname);
- return file.lastModifiedTime;
-}
-
-// The tests!
-/* Check functionality of a normal captureAndStoreIfStale request */
-function* simpleCaptureTest() {
- let numNotifications = 0;
- const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/thumbnails_update.sjs?simple";
-
- function observe(subject, topic, data) {
- is(topic, "page-thumbnail:create", "got expected topic");
- is(data, URL, "data is our test URL");
- if (++numNotifications == 2) {
- // This is the final notification and signals test success...
- Services.obs.removeObserver(observe, "page-thumbnail:create");
- gBrowser.removeTab(gBrowser.selectedTab);
- next();
- }
- }
-
- Services.obs.addObserver(observe, "page-thumbnail:create", false);
- // Create a tab - we don't care what the content is.
- yield addTab(URL);
- let browser = gBrowser.selectedBrowser;
-
- // Capture the screenshot.
- PageThumbs.captureAndStore(browser, function () {
- // We've got a capture so should have seen the observer.
- is(numNotifications, 1, "got notification of item being created.");
- // The capture is now "fresh" - so requesting the URL should not cause
- // a new capture.
- PageThumbs.captureAndStoreIfStale(browser, function() {
- is(numNotifications, 1, "still only 1 notification of item being created.");
-
- ensureThumbnailStale(URL);
- // Ask for it to be updated.
- PageThumbs.captureAndStoreIfStale(browser);
- // But it's async, so wait - our observer above will call next() when
- // the notification comes.
- });
- });
- yield undefined // wait for callbacks to call 'next'...
-}
-
-/* Check functionality of captureAndStoreIfStale when there is an error response
- from the server.
- */
-function* capIfStaleErrorResponseUpdateTest() {
- const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/thumbnails_update.sjs?fail";
- yield addTab(URL);
-
- yield captureAndCheckColor(0, 255, 0, "we have a green thumbnail");
- // update the thumbnail to be stale, then re-request it. The server will
- // return a 400 response and a red thumbnail.
- // The service should not save the thumbnail - so we (a) check the thumbnail
- // remains green and (b) check the mtime of the file is < now.
- ensureThumbnailStale(URL);
- yield navigateTo(URL);
- // now() returns a higher-precision value than the modified time of a file.
- // As we set the thumbnail very stale, allowing 1 second of "slop" here
- // works around this while still keeping the test valid.
- let now = Date.now() - 1000 ;
- PageThumbs.captureAndStoreIfStale(gBrowser.selectedBrowser, () => {
- ok(getThumbnailModifiedTime(URL) < now, "modified time should be < now");
- retrieveImageDataForURL(URL, function ([r, g, b]) {
- is("" + [r, g, b], "" + [0, 255, 0], "thumbnail is still green");
- gBrowser.removeTab(gBrowser.selectedTab);
- next();
- });
- });
- yield undefined; // wait for callback to call 'next'...
-}
-
-/* Check functionality of captureAndStoreIfStale when there is a non-error
- response from the server. This test is somewhat redundant - although it is
- using a http:// URL instead of a data: url like most others.
- */
-function* capIfStaleGoodResponseUpdateTest() {
- const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/thumbnails_update.sjs?ok";
- yield addTab(URL);
- let browser = gBrowser.selectedBrowser;
-
- yield captureAndCheckColor(0, 255, 0, "we have a green thumbnail");
- // update the thumbnail to be stale, then re-request it. The server will
- // return a 200 response and a red thumbnail - so that new thumbnail should
- // end up captured.
- ensureThumbnailStale(URL);
- yield navigateTo(URL);
- // now() returns a higher-precision value than the modified time of a file.
- // As we set the thumbnail very stale, allowing 1 second of "slop" here
- // works around this while still keeping the test valid.
- let now = Date.now() - 1000 ;
- PageThumbs.captureAndStoreIfStale(browser, () => {
- ok(getThumbnailModifiedTime(URL) >= now, "modified time should be >= now");
- // the captureAndStoreIfStale request saw a 200 response with the red body,
- // so we expect to see the red version here.
- retrieveImageDataForURL(URL, function ([r, g, b]) {
- is("" + [r, g, b], "" + [255, 0, 0], "thumbnail is now red");
- next();
- });
- });
- yield undefined; // wait for callback to call 'next'...
-}
-
-/* Check functionality of captureAndStore when there is an error response
- from the server.
- */
-function* regularCapErrorResponseUpdateTest() {
- const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/thumbnails_update.sjs?fail";
- yield addTab(URL);
- yield captureAndCheckColor(0, 255, 0, "we have a green thumbnail");
- gBrowser.removeTab(gBrowser.selectedTab);
- // do it again - the server will return a 400, so the foreground service
- // should not update it.
- yield addTab(URL);
- yield captureAndCheckColor(0, 255, 0, "we still have a green thumbnail");
-}
-
-/* Check functionality of captureAndStore when there is an OK response
- from the server.
- */
-function* regularCapGoodResponseUpdateTest() {
- const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/thumbnails_update.sjs?ok";
- yield addTab(URL);
- yield captureAndCheckColor(0, 255, 0, "we have a green thumbnail");
- gBrowser.removeTab(gBrowser.selectedTab);
- // do it again - the server will return a 200, so the foreground service
- // should update it.
- yield addTab(URL);
- yield captureAndCheckColor(255, 0, 0, "we now have a red thumbnail");
-}
diff --git a/toolkit/components/thumbnails/test/head.js b/toolkit/components/thumbnails/test/head.js
deleted file mode 100644
index e8229508a..000000000
--- a/toolkit/components/thumbnails/test/head.js
+++ /dev/null
@@ -1,356 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var tmp = {};
-Cu.import("resource://gre/modules/PageThumbs.jsm", tmp);
-Cu.import("resource://gre/modules/BackgroundPageThumbs.jsm", tmp);
-Cu.import("resource://gre/modules/NewTabUtils.jsm", tmp);
-Cu.import("resource:///modules/sessionstore/SessionStore.jsm", tmp);
-Cu.import("resource://gre/modules/FileUtils.jsm", tmp);
-Cu.import("resource://gre/modules/osfile.jsm", tmp);
-var {PageThumbs, BackgroundPageThumbs, NewTabUtils, PageThumbsStorage, SessionStore, FileUtils, OS} = tmp;
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-var oldEnabledPref = Services.prefs.getBoolPref("browser.pagethumbnails.capturing_disabled");
-Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", false);
-
-registerCleanupFunction(function () {
- while (gBrowser.tabs.length > 1)
- gBrowser.removeTab(gBrowser.tabs[1]);
- Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", oldEnabledPref)
-});
-
-/**
- * Provide the default test function to start our test runner.
- */
-function test() {
- TestRunner.run();
-}
-
-/**
- * The test runner that controls the execution flow of our tests.
- */
-var TestRunner = {
- /**
- * Starts the test runner.
- */
- run: function () {
- waitForExplicitFinish();
-
- SessionStore.promiseInitialized.then(function () {
- this._iter = runTests();
- if (this._iter) {
- this.next();
- } else {
- finish();
- }
- }.bind(this));
- },
-
- /**
- * Runs the next available test or finishes if there's no test left.
- * @param aValue This value will be passed to the yielder via the runner's
- * iterator.
- */
- next: function (aValue) {
- let obj = TestRunner._iter.next(aValue);
- if (obj.done) {
- finish();
- return;
- }
-
- let value = obj.value || obj;
- if (value && typeof value.then == "function") {
- value.then(result => {
- next(result);
- }, error => {
- ok(false, error + "\n" + error.stack);
- });
- }
- }
-};
-
-/**
- * Continues the current test execution.
- * @param aValue This value will be passed to the yielder via the runner's
- * iterator.
- */
-function next(aValue) {
- TestRunner.next(aValue);
-}
-
-/**
- * Creates a new tab with the given URI.
- * @param aURI The URI that's loaded in the tab.
- * @param aCallback The function to call when the tab has loaded.
- */
-function addTab(aURI, aCallback) {
- let tab = gBrowser.selectedTab = gBrowser.addTab(aURI);
- whenLoaded(tab.linkedBrowser, aCallback);
-}
-
-/**
- * Loads a new URI into the currently selected tab.
- * @param aURI The URI to load.
- */
-function navigateTo(aURI) {
- let browser = gBrowser.selectedBrowser;
- whenLoaded(browser);
- browser.loadURI(aURI);
-}
-
-/**
- * Continues the current test execution when a load event for the given element
- * has been received.
- * @param aElement The DOM element to listen on.
- * @param aCallback The function to call when the load event was dispatched.
- */
-function whenLoaded(aElement, aCallback = next) {
- aElement.addEventListener("load", function onLoad() {
- aElement.removeEventListener("load", onLoad, true);
- executeSoon(aCallback);
- }, true);
-}
-
-/**
- * Captures a screenshot for the currently selected tab, stores it in the cache,
- * retrieves it from the cache and compares pixel color values.
- * @param aRed The red component's intensity.
- * @param aGreen The green component's intensity.
- * @param aBlue The blue component's intensity.
- * @param aMessage The info message to print when comparing the pixel color.
- */
-function captureAndCheckColor(aRed, aGreen, aBlue, aMessage) {
- let browser = gBrowser.selectedBrowser;
- // We'll get oranges if the expiration filter removes the file during the
- // test.
- dontExpireThumbnailURLs([browser.currentURI.spec]);
-
- // Capture the screenshot.
- PageThumbs.captureAndStore(browser, function () {
- retrieveImageDataForURL(browser.currentURI.spec, function ([r, g, b]) {
- is("" + [r, g, b], "" + [aRed, aGreen, aBlue], aMessage);
- next();
- });
- });
-}
-
-/**
- * For a given URL, loads the corresponding thumbnail
- * to a canvas and passes its image data to the callback.
- * Note, not compat with e10s!
- * @param aURL The url associated with the thumbnail.
- * @param aCallback The function to pass the image data to.
- */
-function retrieveImageDataForURL(aURL, aCallback) {
- let width = 100, height = 100;
- let thumb = PageThumbs.getThumbnailURL(aURL, width, height);
-
- let htmlns = "http://www.w3.org/1999/xhtml";
- let img = document.createElementNS(htmlns, "img");
- img.setAttribute("src", thumb);
-
- whenLoaded(img, function () {
- let canvas = document.createElementNS(htmlns, "canvas");
- canvas.setAttribute("width", width);
- canvas.setAttribute("height", height);
-
- // Draw the image to a canvas and compare the pixel color values.
- let ctx = canvas.getContext("2d");
- ctx.drawImage(img, 0, 0, width, height);
- let result = ctx.getImageData(0, 0, 100, 100).data;
- aCallback(result);
- });
-}
-
-/**
- * Returns the file of the thumbnail with the given URL.
- * @param aURL The URL of the thumbnail.
- */
-function thumbnailFile(aURL) {
- return new FileUtils.File(PageThumbsStorage.getFilePathForURL(aURL));
-}
-
-/**
- * Checks if a thumbnail for the given URL exists.
- * @param aURL The url associated to the thumbnail.
- */
-function thumbnailExists(aURL) {
- let file = thumbnailFile(aURL);
- return file.exists() && file.fileSize;
-}
-
-/**
- * Removes the thumbnail for the given URL.
- * @param aURL The URL associated with the thumbnail.
- */
-function removeThumbnail(aURL) {
- let file = thumbnailFile(aURL);
- file.remove(false);
-}
-
-/**
- * Calls addVisits, and then forces the newtab module to repopulate its links.
- * See addVisits for parameter descriptions.
- */
-function addVisitsAndRepopulateNewTabLinks(aPlaceInfo, aCallback) {
- PlacesTestUtils.addVisits(makeURI(aPlaceInfo)).then(() => {
- NewTabUtils.links.populateCache(aCallback, true);
- });
-}
-function promiseAddVisitsAndRepopulateNewTabLinks(aPlaceInfo) {
- return new Promise(resolve => addVisitsAndRepopulateNewTabLinks(aPlaceInfo, resolve));
-}
-
-/**
- * Calls a given callback when the thumbnail for a given URL has been found
- * on disk. Keeps trying until the thumbnail has been created.
- *
- * @param aURL The URL of the thumbnail's page.
- * @param [optional] aCallback
- * Function to be invoked on completion.
- */
-function whenFileExists(aURL, aCallback = next) {
- let callback = aCallback;
- if (!thumbnailExists(aURL)) {
- callback = () => whenFileExists(aURL, aCallback);
- }
-
- executeSoon(callback);
-}
-
-/**
- * Calls a given callback when the given file has been removed.
- * Keeps trying until the file is removed.
- *
- * @param aFile The file that is being removed
- * @param [optional] aCallback
- * Function to be invoked on completion.
- */
-function whenFileRemoved(aFile, aCallback) {
- let callback = aCallback;
- if (aFile.exists()) {
- callback = () => whenFileRemoved(aFile, aCallback);
- }
-
- executeSoon(callback || next);
-}
-
-function wait(aMillis) {
- setTimeout(next, aMillis);
-}
-
-/**
- * Makes sure that a given list of URLs is not implicitly expired.
- *
- * @param aURLs The list of URLs that should not be expired.
- */
-function dontExpireThumbnailURLs(aURLs) {
- let dontExpireURLs = (cb) => cb(aURLs);
- PageThumbs.addExpirationFilter(dontExpireURLs);
-
- registerCleanupFunction(function () {
- PageThumbs.removeExpirationFilter(dontExpireURLs);
- });
-}
-
-function bgCapture(aURL, aOptions) {
- bgCaptureWithMethod("capture", aURL, aOptions);
-}
-
-function bgCaptureIfMissing(aURL, aOptions) {
- bgCaptureWithMethod("captureIfMissing", aURL, aOptions);
-}
-
-function bgCaptureWithMethod(aMethodName, aURL, aOptions = {}) {
- // We'll get oranges if the expiration filter removes the file during the
- // test.
- dontExpireThumbnailURLs([aURL]);
- if (!aOptions.onDone)
- aOptions.onDone = next;
- BackgroundPageThumbs[aMethodName](aURL, aOptions);
-}
-
-function bgTestPageURL(aOpts = {}) {
- let TEST_PAGE_URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/test/thumbnails_background.sjs";
- return TEST_PAGE_URL + "?" + encodeURIComponent(JSON.stringify(aOpts));
-}
-
-function bgAddPageThumbObserver(url) {
- return new Promise((resolve, reject) => {
- function observe(subject, topic, data) { // jshint ignore:line
- if (data === url) {
- switch (topic) {
- case "page-thumbnail:create":
- resolve();
- break;
- case "page-thumbnail:error":
- reject(new Error("page-thumbnail:error"));
- break;
- }
- Services.obs.removeObserver(observe, "page-thumbnail:create");
- Services.obs.removeObserver(observe, "page-thumbnail:error");
- }
- }
- Services.obs.addObserver(observe, "page-thumbnail:create", false);
- Services.obs.addObserver(observe, "page-thumbnail:error", false);
- });
-}
-
-function bgAddCrashObserver() {
- let crashed = false;
- Services.obs.addObserver(function crashObserver(subject, topic, data) {
- is(topic, 'ipc:content-shutdown', 'Received correct observer topic.');
- ok(subject instanceof Components.interfaces.nsIPropertyBag2,
- 'Subject implements nsIPropertyBag2.');
- // we might see this called as the process terminates due to previous tests.
- // We are only looking for "abnormal" exits...
- if (!subject.hasKey("abnormal")) {
- info("This is a normal termination and isn't the one we are looking for...");
- return;
- }
- Services.obs.removeObserver(crashObserver, 'ipc:content-shutdown');
- crashed = true;
-
- var dumpID;
- if ('nsICrashReporter' in Components.interfaces) {
- dumpID = subject.getPropertyAsAString('dumpID');
- ok(dumpID, "dumpID is present and not an empty string");
- }
-
- if (dumpID) {
- var minidumpDirectory = getMinidumpDirectory();
- removeFile(minidumpDirectory, dumpID + '.dmp');
- removeFile(minidumpDirectory, dumpID + '.extra');
- }
- }, 'ipc:content-shutdown', false);
- return {
- get crashed() {
- return crashed;
- }
- };
-}
-
-function bgInjectCrashContentScript() {
- const TEST_CONTENT_HELPER = "chrome://mochitests/content/browser/toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js";
- let thumbnailBrowser = BackgroundPageThumbs._thumbBrowser;
- let mm = thumbnailBrowser.messageManager;
- mm.loadFrameScript(TEST_CONTENT_HELPER, false);
- return mm;
-}
-
-function getMinidumpDirectory() {
- var dir = Services.dirsvc.get('ProfD', Components.interfaces.nsIFile);
- dir.append("minidumps");
- return dir;
-}
-
-function removeFile(directory, filename) {
- var file = directory.clone();
- file.append(filename);
- if (file.exists()) {
- file.remove(false);
- }
-}
diff --git a/toolkit/components/thumbnails/test/privacy_cache_control.sjs b/toolkit/components/thumbnails/test/privacy_cache_control.sjs
deleted file mode 100644
index 6c7c16edb..000000000
--- a/toolkit/components/thumbnails/test/privacy_cache_control.sjs
+++ /dev/null
@@ -1,16 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function handleRequest(aRequest, aResponse) {
- // Set HTTP Status
- aResponse.setStatusLine(aRequest.httpVersion, 200, "OK");
-
- // Set Cache-Control header.
- let value = aRequest.queryString;
- if (value)
- aResponse.setHeader("Cache-Control", value);
-
- // Set the response body.
- aResponse.write("<!DOCTYPE html><html><body></body></html>");
-}
diff --git a/toolkit/components/thumbnails/test/test_thumbnails_interfaces.js b/toolkit/components/thumbnails/test/test_thumbnails_interfaces.js
deleted file mode 100644
index a8fe51418..000000000
--- a/toolkit/components/thumbnails/test/test_thumbnails_interfaces.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// tests to check that moz-page-thumb URLs correctly resolve as file:// URLS
-"use strict";
-
-const Cu = Components.utils;
-const Cc = Components.classes;
-const Cr = Components.results;
-const Ci = Components.interfaces;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-// need profile so that PageThumbsStorage can resolve the path to the underlying file
-do_get_profile();
-
-function run_test() {
- // first check the protocol handler implements the correct interface
- let handler = Services.io.getProtocolHandler("moz-page-thumb");
- ok(handler instanceof Ci.nsISubstitutingProtocolHandler,
- "moz-page-thumb handler provides substituting interface");
-
- // then check that the file URL resolution works
- let uri = Services.io.newURI("moz-page-thumb://thumbnail/?url=http%3A%2F%2Fwww.mozilla.org%2F",
- null, null);
- ok(uri instanceof Ci.nsIFileURL, "moz-page-thumb:// is a FileURL");
- ok(uri.file, "This moz-page-thumb:// object is backed by a file");
-}
diff --git a/toolkit/components/thumbnails/test/thumbnails_background.sjs b/toolkit/components/thumbnails/test/thumbnails_background.sjs
deleted file mode 100644
index f1cce96a0..000000000
--- a/toolkit/components/thumbnails/test/thumbnails_background.sjs
+++ /dev/null
@@ -1,79 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// The timer never fires if it's not declared and set to this variable outside
-// handleRequest, as if it's getting GC'ed when handleRequest's scope goes away.
-// Shouldn't the timer thread hold a strong reference to it?
-var timer;
-
-function handleRequest(req, resp) {
- resp.processAsync();
- resp.setHeader("Cache-Control", "no-cache, no-store", false);
- resp.setHeader("Content-Type", "text/html;charset=utf-8", false);
-
- let opts = {};
- try {
- opts = JSON.parse(decodeURIComponent(req.queryString));
- }
- catch (err) {}
-
- let setCookieScript = "";
- if (opts.setRedCookie) {
- resp.setHeader("Set-Cookie", "red", false);
- setCookieScript = '<script>document.cookie="red";</script>';
- }
-
- if (opts.setGreenCookie) {
- resp.setHeader("Set-Cookie", "green", false);
- setCookieScript = '<script>document.cookie="green";</script>';
- }
-
- if (opts.iframe) {
- setCookieScript += '<iframe src="' + opts.iframe + '" />';
- }
-
- if (opts.xhr) {
- setCookieScript += `
- <script>
- var req = new XMLHttpRequest();
- req.open("GET", "${opts.xhr}", true);
- req.send();
- </script>
- `;
- }
-
- if (req.hasHeader("Cookie") &&
- req.getHeader("Cookie").split(";").indexOf("red") >= 0) {
- resp.write('<html style="background: #f00;">' + setCookieScript + '</html>');
- resp.finish();
- return;
- }
-
- if (req.hasHeader("Cookie") &&
- req.getHeader("Cookie").split(";").indexOf("green") >= 0) {
- resp.write('<html style="background: #0f0;">' + setCookieScript + '</html>');
- resp.finish();
- return;
- }
-
- if (opts.redirect) {
- resp.setHeader("Location", opts.redirect);
- resp.setStatusLine(null, 303, null);
- resp.finish();
- return;
- }
-
- if (opts.wait) {
- resp.write("Waiting " + opts.wait + " ms... ");
- timer = Components.classes["@mozilla.org/timer;1"].
- createInstance(Components.interfaces.nsITimer);
- timer.init(function ding() {
- resp.write("OK!");
- resp.finish();
- }, opts.wait, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
- return;
- }
-
- resp.write("<pre>" + JSON.stringify(opts, undefined, 2) + "</pre>" + setCookieScript);
- resp.finish();
-}
diff --git a/toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js b/toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js
deleted file mode 100644
index 935175f86..000000000
--- a/toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
-* http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var Cu = Components.utils;
-
-// Ideally we would use CrashTestUtils.jsm, but that's only available for
-// xpcshell tests - so we just copy a ctypes crasher from it.
-Cu.import("resource://gre/modules/ctypes.jsm");
-var crash = function() { // this will crash when called.
- let zero = new ctypes.intptr_t(8);
- let badptr = ctypes.cast(zero, ctypes.PointerType(ctypes.int32_t));
- badptr.contents
-};
-
-
-var TestHelper = {
- init: function() {
- addMessageListener("thumbnails-test:crash", this);
- },
-
- receiveMessage: function(msg) {
- switch (msg.name) {
- case "thumbnails-test:crash":
- privateNoteIntentionalCrash();
- crash();
- break;
- }
- },
-}
-
-TestHelper.init();
diff --git a/toolkit/components/thumbnails/test/thumbnails_update.sjs b/toolkit/components/thumbnails/test/thumbnails_update.sjs
deleted file mode 100644
index 4d8ab406a..000000000
--- a/toolkit/components/thumbnails/test/thumbnails_update.sjs
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This server-side script is used for browser_thumbnails_update. One of the
-// main things it must do in all cases is ensure a Cache-Control: no-store
-// header, so the foreground capture doesn't interfere with the testing.
-
-// If the querystring is "simple", then all it does it return some content -
-// it doesn't really matter what that content is.
-
-// Otherwise, its main role is that it must return different *content* for the
-// second request than it did for the first.
-// Also, it should be able to return an error response when requested for the
-// second response.
-// So the basic tests will be to grab the thumbnail, then request it to be
-// grabbed again:
-// * If the second request succeeded, the new thumbnail should exist.
-// * If the second request is an error, the new thumbnail should be ignored.
-
-function handleRequest(aRequest, aResponse) {
- aResponse.setHeader("Content-Type", "text/html;charset=utf-8", false);
- // we want to disable gBrowserThumbnails on-load capture for these responses,
- // so set as a "no-store" response.
- aResponse.setHeader("Cache-Control", "no-store");
-
- // for the simple test - just return some content.
- if (aRequest.queryString == "simple") {
- aResponse.write("<html><body></body></html>");
- aResponse.setStatusLine(aRequest.httpVersion, 200, "Its simply OK");
- return;
- }
-
- // it's one of the more complex tests where the first request for the given
- // URL must return different content than the second, and possibly an error
- // response for the second
- let doneError = getState(aRequest.queryString);
- if (!doneError) {
- // first request - return a response with a green body and 200 response.
- aResponse.setStatusLine(aRequest.httpVersion, 200, "OK - It's green");
- aResponse.write("<html><body bgcolor=00ff00></body></html>");
- // set the state so the next request does the "second request" thing below.
- setState(aRequest.queryString, "yep");
- } else {
- // second request - this will be done by the b/g service.
- // We always return a red background, but depending on the query string we
- // return either a 200 or 401 response.
- if (aRequest.queryString == "fail")
- aResponse.setStatusLine(aRequest.httpVersion, 401, "Oh no you don't");
- else
- aResponse.setStatusLine(aRequest.httpVersion, 200, "OK - It's red");
- aResponse.write("<html><body bgcolor=ff0000></body></html>");
- // reset the error state incase this ends up being reused for the
- // same url and querystring.
- setState(aRequest.queryString, "");
- }
-}
diff --git a/toolkit/components/thumbnails/test/xpcshell.ini b/toolkit/components/thumbnails/test/xpcshell.ini
deleted file mode 100644
index 4dae8cced..000000000
--- a/toolkit/components/thumbnails/test/xpcshell.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-head =
-tail =
-
-[test_thumbnails_interfaces.js]
-skip-if = os == 'android' # xpcom interface not packaged
diff --git a/toolkit/components/timermanager/moz.build b/toolkit/components/timermanager/moz.build
index 9977df6b5..81ef3330b 100644
--- a/toolkit/components/timermanager/moz.build
+++ b/toolkit/components/timermanager/moz.build
@@ -6,16 +6,9 @@
XPIDL_MODULE = 'update'
-XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
-
-XPIDL_SOURCES += [
- 'nsIUpdateTimerManager.idl',
-]
+XPIDL_SOURCES += ['nsIUpdateTimerManager.idl']
EXTRA_COMPONENTS += [
'nsUpdateTimerManager.js',
'nsUpdateTimerManager.manifest',
]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Application Update')
diff --git a/toolkit/components/timermanager/tests/unit/.eslintrc.js b/toolkit/components/timermanager/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/timermanager/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/timermanager/tests/unit/consumerNotifications.js b/toolkit/components/timermanager/tests/unit/consumerNotifications.js
deleted file mode 100644
index b9926e11e..000000000
--- a/toolkit/components/timermanager/tests/unit/consumerNotifications.js
+++ /dev/null
@@ -1,519 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/.
- */
-
-/* General Update Timer Manager Tests */
-
-'use strict';
-
-const { classes: Cc, interfaces: Ci, manager: Cm, results: Cr,
- utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const CATEGORY_UPDATE_TIMER = "update-timer";
-
-const PREF_APP_UPDATE_TIMERMINIMUMDELAY = "app.update.timerMinimumDelay";
-const PREF_APP_UPDATE_TIMERFIRSTINTERVAL = "app.update.timerFirstInterval";
-const PREF_APP_UPDATE_LOG_ALL = "app.update.log.all";
-const PREF_BRANCH_LAST_UPDATE_TIME = "app.update.lastUpdateTime.";
-
-const MAIN_TIMER_INTERVAL = 1000; // milliseconds
-const CONSUMER_TIMER_INTERVAL = 1; // seconds
-
-const TESTS = [ {
- desc: "Test Timer Callback 0",
- timerID: "test0-update-timer",
- defaultInterval: "bogus",
- prefInterval: "test0.timer.interval",
- contractID: "@mozilla.org/test0/timercallback;1",
- method: "createInstance",
- classID: Components.ID("9c7ce81f-98bb-4729-adb4-4d0deb0f59e5"),
- notified: false
-}, {
- desc: "Test Timer Callback 1",
- timerID: "test1-update-timer",
- defaultInterval: 86400,
- prefInterval: "test1.timer.interval",
- contractID: "@mozilla.org/test2/timercallback;1",
- method: "createInstance",
- classID: Components.ID("512834f3-05bb-46be-84e0-81d881a140b7"),
- notified: false
-}, {
- desc: "Test Timer Callback 2",
- timerID: "test2-update-timer",
- defaultInterval: CONSUMER_TIMER_INTERVAL,
- prefInterval: "test2.timer.interval",
- contractID: "@mozilla.org/test2/timercallback;1",
- method: "createInstance",
- classID: Components.ID("c8ac5027-8d11-4471-9d7c-fd692501b437"),
- notified: false
-}, {
- desc: "Test Timer Callback 3",
- timerID: "test3-update-timer",
- defaultInterval: CONSUMER_TIMER_INTERVAL,
- prefInterval: "test3.timer.interval",
- contractID: "@mozilla.org/test3/timercallback;1",
- method: "createInstance",
- classID: Components.ID("6b0e79f3-4ab8-414c-8f14-dde10e185727"),
- notified: false
-}, {
- desc: "Test Timer Callback 4",
- timerID: "test4-update-timer",
- defaultInterval: CONSUMER_TIMER_INTERVAL,
- prefInterval: "test4.timer.interval",
- contractID: "@mozilla.org/test4/timercallback;1",
- method: "createInstance",
- classID: Components.ID("2f6b7b92-e40f-4874-bfbb-eeb2412c959d"),
- notified: false
-}, {
- desc: "Test Timer Callback 5",
- timerID: "test5-update-timer",
- defaultInterval: 86400,
- prefInterval: "test5.timer.interval",
- contractID: "@mozilla.org/test5/timercallback;1",
- method: "createInstance",
- classID: Components.ID("8a95f611-b2ac-4c7e-8b73-9748c4839731"),
- notified: false
-}, {
- desc: "Test Timer Callback 6",
- timerID: "test6-update-timer",
- defaultInterval: CONSUMER_TIMER_INTERVAL,
- prefInterval: "test6.timer.interval",
- contractID: "@mozilla.org/test6/timercallback;1",
- method: "createInstance",
- classID: Components.ID("2d091020-e23c-11e2-a28f-0800200c9a66"),
- notified: false
-}, {
- desc: "Test Timer Callback 7",
- timerID: "test7-update-timer",
- defaultInterval: 86400,
- maxInterval: CONSUMER_TIMER_INTERVAL,
- prefInterval: "test7.timer.interval",
- contractID: "@mozilla.org/test7/timercallback;1",
- method: "createInstance",
- classID: Components.ID("8e8633ae-1d70-4a7a-8bea-6e1e6c5d7742"),
- notified: false
-}, {
- desc: "Test Timer Callback 8",
- timerID: "test8-update-timer",
- defaultInterval: CONSUMER_TIMER_INTERVAL,
- contractID: "@mozilla.org/test8/timercallback;1",
- classID: Components.ID("af878d4b-1d12-41f6-9a90-4e687367ecc1"),
- notified: false,
- lastUpdateTime: 0
-}, {
- desc: "Test Timer Callback 9",
- timerID: "test9-update-timer",
- defaultInterval: CONSUMER_TIMER_INTERVAL,
- contractID: "@mozilla.org/test9/timercallback;1",
- classID: Components.ID("5136b201-d64c-4328-8cf1-1a63491cc117"),
- notified: false,
- lastUpdateTime: 0
-} ];
-
-var gUTM;
-var gNextFunc;
-
-XPCOMUtils.defineLazyServiceGetter(this, "gPref",
- "@mozilla.org/preferences-service;1",
- "nsIPrefBranch");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gCatMan",
- "@mozilla.org/categorymanager;1",
- "nsICategoryManager");
-
-XPCOMUtils.defineLazyGetter(this, "gCompReg", function () {
- return Cm.QueryInterface(Ci.nsIComponentRegistrar);
-});
-
-const gTest0TimerCallback = {
- notify: function T0CB_notify(aTimer) {
- // This can happen when another notification fails and this timer having
- // time to fire so check other timers are successful.
- do_throw("gTest0TimerCallback notify method should not have been called");
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest0Factory = {
- createInstance: function T0F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest0TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest1TimerCallback = {
- notify: function T1CB_notify(aTimer) {
- // This can happen when another notification fails and this timer having
- // time to fire so check other timers are successful.
- do_throw("gTest1TimerCallback notify method should not have been called");
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimer])
-};
-
-const gTest1Factory = {
- createInstance: function T1F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest1TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest2TimerCallback = {
- notify: function T2CB_notify(aTimer) {
- // This can happen when another notification fails and this timer having
- // time to fire so check other timers are successful.
- do_throw("gTest2TimerCallback notify method should not have been called");
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest2Factory = {
- createInstance: function T2F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest2TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest3TimerCallback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest3Factory = {
- createInstance: function T3F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest3TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest4TimerCallback = {
- notify: function T4CB_notify(aTimer) {
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[4].desc, true);
- TESTS[4].notified = true;
- finished_test0thru7();
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest4Factory = {
- createInstance: function T4F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest4TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest5TimerCallback = {
- notify: function T5CB_notify(aTimer) {
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[5].desc, true);
- TESTS[5].notified = true;
- finished_test0thru7();
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest5Factory = {
- createInstance: function T5F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest5TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest6TimerCallback = {
- notify: function T6CB_notify(aTimer) {
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[6].desc, true);
- TESTS[6].notified = true;
- finished_test0thru7();
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest6Factory = {
- createInstance: function T6F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest6TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest7TimerCallback = {
- notify: function T7CB_notify(aTimer) {
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[7].desc, true);
- TESTS[7].notified = true;
- finished_test0thru7();
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest7Factory = {
- createInstance: function T7F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest7TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest8TimerCallback = {
- notify: function T8CB_notify(aTimer) {
- TESTS[8].notified = true;
- TESTS[8].notifyTime = Date.now();
- do_execute_soon(function () {
- check_test8thru9(gTest8TimerCallback);
- });
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest8Factory = {
- createInstance: function T8F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest8TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-const gTest9TimerCallback = {
- notify: function T9CB_notify(aTimer) {
- TESTS[9].notified = true;
- TESTS[9].notifyTime = Date.now();
- do_execute_soon(function () {
- check_test8thru9(gTest9TimerCallback);
- });
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITimerCallback])
-};
-
-const gTest9Factory = {
- createInstance: function T9F_createInstance(aOuter, aIID) {
- if (aOuter == null) {
- return gTest9TimerCallback.QueryInterface(aIID);
- }
- throw Cr.NS_ERROR_NO_AGGREGATION;
- }
-};
-
-function run_test() {
- do_test_pending();
-
- // Set the timer to fire every second
- gPref.setIntPref(PREF_APP_UPDATE_TIMERMINIMUMDELAY, MAIN_TIMER_INTERVAL / 1000);
- gPref.setIntPref(PREF_APP_UPDATE_TIMERFIRSTINTERVAL, MAIN_TIMER_INTERVAL);
- gPref.setBoolPref(PREF_APP_UPDATE_LOG_ALL, true);
-
- // Remove existing update timers to prevent them from being notified
- let entries = gCatMan.enumerateCategory(CATEGORY_UPDATE_TIMER);
- while (entries.hasMoreElements()) {
- let entry = entries.getNext().QueryInterface(Ci.nsISupportsCString).data;
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, entry, false);
- }
-
- gUTM = Cc["@mozilla.org/updates/timer-manager;1"].
- getService(Ci.nsIUpdateTimerManager).
- QueryInterface(Ci.nsIObserver);
- gUTM.observe(null, "utm-test-init", "");
-
- do_execute_soon(run_test0thru7);
-}
-
-function end_test() {
- gUTM.observe(null, "xpcom-shutdown", "");
- do_test_finished();
-}
-
-function run_test0thru7() {
- gNextFunc = check_test0thru7;
- // bogus default interval
- gCompReg.registerFactory(TESTS[0].classID, TESTS[0].desc,
- TESTS[0].contractID, gTest0Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[0].desc,
- [TESTS[0].contractID, TESTS[0].method,
- TESTS[0].timerID, TESTS[0].prefInterval,
- TESTS[0].defaultInterval].join(","), false, true);
-
- // doesn't implement nsITimerCallback
- gCompReg.registerFactory(TESTS[1].classID, TESTS[1].desc,
- TESTS[1].contractID, gTest1Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[1].desc,
- [TESTS[1].contractID, TESTS[1].method,
- TESTS[1].timerID, TESTS[1].prefInterval,
- TESTS[1].defaultInterval].join(","), false, true);
-
- // has a last update time of now - 43200 which is half of its interval
- let lastUpdateTime = Math.round(Date.now() / 1000) - 43200;
- gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[2].timerID, lastUpdateTime);
- gCompReg.registerFactory(TESTS[2].classID, TESTS[2].desc,
- TESTS[2].contractID, gTest2Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[2].desc,
- [TESTS[2].contractID, TESTS[2].method,
- TESTS[2].timerID, TESTS[2].prefInterval,
- TESTS[2].defaultInterval].join(","), false, true);
-
- // doesn't have a notify method
- gCompReg.registerFactory(TESTS[3].classID, TESTS[3].desc,
- TESTS[3].contractID, gTest3Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[3].desc,
- [TESTS[3].contractID, TESTS[3].method,
- TESTS[3].timerID, TESTS[3].prefInterval,
- TESTS[3].defaultInterval].join(","), false, true);
-
- // already has a last update time
- gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[4].timerID, 1);
- gCompReg.registerFactory(TESTS[4].classID, TESTS[4].desc,
- TESTS[4].contractID, gTest4Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[4].desc,
- [TESTS[4].contractID, TESTS[4].method,
- TESTS[4].timerID, TESTS[4].prefInterval,
- TESTS[4].defaultInterval].join(","), false, true);
-
- // has an interval preference that overrides the default
- gPref.setIntPref(TESTS[5].prefInterval, CONSUMER_TIMER_INTERVAL);
- gCompReg.registerFactory(TESTS[5].classID, TESTS[5].desc,
- TESTS[5].contractID, gTest5Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[5].desc,
- [TESTS[5].contractID, TESTS[5].method,
- TESTS[5].timerID, TESTS[5].prefInterval,
- TESTS[5].defaultInterval].join(","), false, true);
-
- // has a next update time 24 hours from now
- let nextUpdateTime = Math.round(Date.now() / 1000) + 86400;
- gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[6].timerID, nextUpdateTime);
- gCompReg.registerFactory(TESTS[6].classID, TESTS[6].desc,
- TESTS[6].contractID, gTest6Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[6].desc,
- [TESTS[6].contractID, TESTS[6].method,
- TESTS[6].timerID, TESTS[6].prefInterval,
- TESTS[6].defaultInterval].join(","), false, true);
-
- // has a maximum interval set by the value of MAIN_TIMER_INTERVAL
- gPref.setIntPref(TESTS[7].prefInterval, 86400);
- gCompReg.registerFactory(TESTS[7].classID, TESTS[7].desc,
- TESTS[7].contractID, gTest7Factory);
- gCatMan.addCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[7].desc,
- [TESTS[7].contractID, TESTS[7].method,
- TESTS[7].timerID, TESTS[7].prefInterval,
- TESTS[7].defaultInterval,
- TESTS[7].maxInterval].join(","), false, true);
-}
-
-function finished_test0thru7() {
- if (TESTS[4].notified && TESTS[5].notified && TESTS[6].notified && TESTS[7].notified) {
- do_execute_soon(gNextFunc);
- }
-}
-
-function check_test0thru7() {
- Assert.ok(!TESTS[0].notified,
- "a category registered timer didn't fire due to an invalid " +
- "default interval");
-
- Assert.ok(!TESTS[1].notified,
- "a category registered timer didn't fire due to not implementing " +
- "nsITimerCallback");
-
- Assert.ok(!TESTS[2].notified,
- "a category registered timer didn't fire due to the next update " +
- "time being in the future");
-
- Assert.ok(!TESTS[3].notified,
- "a category registered timer didn't fire due to not having a " +
- "notify method");
-
- Assert.ok(TESTS[4].notified,
- "a category registered timer has fired");
-
- Assert.ok(TESTS[5].notified,
- "a category registered timer fired that has an interval " +
- "preference that overrides a default that wouldn't have fired yet");
-
- Assert.ok(TESTS[6].notified,
- "a category registered timer has fired due to the next update " +
- "time being reset due to a future last update time");
-
- Assert.ok(gPref.prefHasUserValue(PREF_BRANCH_LAST_UPDATE_TIME +
- TESTS[4].timerID),
- "first of two category registered timers last update time has " +
- "a user value");
- Assert.ok(gPref.prefHasUserValue(PREF_BRANCH_LAST_UPDATE_TIME +
- TESTS[5].timerID),
- "second of two category registered timers last update time has " +
- "a user value");
-
- // Remove the category timers that should have failed
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[0].desc, true);
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[1].desc, true);
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[2].desc, true);
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, TESTS[3].desc, true);
- let entries = gCatMan.enumerateCategory(CATEGORY_UPDATE_TIMER);
- while (entries.hasMoreElements()) {
- let entry = entries.getNext().QueryInterface(Ci.nsISupportsCString).data;
- gCatMan.deleteCategoryEntry(CATEGORY_UPDATE_TIMER, entry, false);
- }
-
- entries = gCatMan.enumerateCategory(CATEGORY_UPDATE_TIMER);
- Assert.ok(!entries.hasMoreElements(),
- "no " + CATEGORY_UPDATE_TIMER + " categories should still be " +
- "registered");
-
- do_execute_soon(run_test8thru9);
-}
-
-function run_test8thru9() {
- gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[8].timerID, 1);
- gCompReg.registerFactory(TESTS[8].classID, TESTS[8].desc,
- TESTS[8].contractID, gTest8Factory);
- gUTM.registerTimer(TESTS[8].timerID, gTest8TimerCallback,
- TESTS[8].defaultInterval);
- gPref.setIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[9].timerID, 1);
- gCompReg.registerFactory(TESTS[9].classID, TESTS[9].desc,
- TESTS[9].contractID, gTest9Factory);
- gUTM.registerTimer(TESTS[9].timerID, gTest9TimerCallback,
- TESTS[9].defaultInterval);
-}
-
-function check_test8thru9(aTestTimerCallback) {
- aTestTimerCallback.timesCalled = (aTestTimerCallback.timesCalled || 0) + 1;
- if (aTestTimerCallback.timesCalled < 2) {
- return;
- }
-
- Assert.ok(TESTS[8].notified,
- "first registerTimer registered timer should have fired");
-
- Assert.ok(TESTS[9].notified,
- "second registerTimer registered timer should have fired");
-
- // Check that 'staggering' has happened: even though the two events wanted to fire at
- // the same time, we waited a full MAIN_TIMER_INTERVAL between them.
- // (to avoid sensitivity to random timing issues, we fudge by a factor of 0.5 here)
- Assert.ok(Math.abs(TESTS[8].notifyTime - TESTS[9].notifyTime) >=
- MAIN_TIMER_INTERVAL * 0.5,
- "staggering between two timers that want to fire at the same " +
- "time should have occured");
-
- let time = gPref.getIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[8].timerID);
- Assert.notEqual(time, 1,
- "first registerTimer registered timer last update time " +
- "should have been updated");
-
- time = gPref.getIntPref(PREF_BRANCH_LAST_UPDATE_TIME + TESTS[9].timerID);
- Assert.notEqual(time, 1,
- "second registerTimer registered timer last update time " +
- "should have been updated");
-
- end_test();
-}
diff --git a/toolkit/components/timermanager/tests/unit/xpcshell.ini b/toolkit/components/timermanager/tests/unit/xpcshell.ini
deleted file mode 100644
index 89e192e94..000000000
--- a/toolkit/components/timermanager/tests/unit/xpcshell.ini
+++ /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/.
-
-[DEFAULT]
-head =
-tail =
-
-[consumerNotifications.js]
diff --git a/toolkit/components/tooltiptext/moz.build b/toolkit/components/tooltiptext/moz.build
index c75e6b7a4..3c5702ca4 100644
--- a/toolkit/components/tooltiptext/moz.build
+++ b/toolkit/components/tooltiptext/moz.build
@@ -4,12 +4,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-BROWSER_CHROME_MANIFESTS += ['tests/browser.ini']
-
EXTRA_COMPONENTS += [
'TooltipTextProvider.js',
'TooltipTextProvider.manifest',
]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'General')
diff --git a/toolkit/components/tooltiptext/tests/browser.ini b/toolkit/components/tooltiptext/tests/browser.ini
deleted file mode 100644
index 9896fcd2c..000000000
--- a/toolkit/components/tooltiptext/tests/browser.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[browser_bug329212.js]
-support-files = title_test.svg
-[browser_bug331772_xul_tooltiptext_in_html.js]
-support-files = xul_tooltiptext.xhtml
-[browser_bug561623.js]
-[browser_bug581947.js]
-[browser_input_file_tooltips.js]
diff --git a/toolkit/components/tooltiptext/tests/browser_bug329212.js b/toolkit/components/tooltiptext/tests/browser_bug329212.js
deleted file mode 100644
index b3434eff6..000000000
--- a/toolkit/components/tooltiptext/tests/browser_bug329212.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://mochi.test:8888/browser/toolkit/components/tooltiptext/tests/title_test.svg",
- }, function*(browser) {
- yield ContentTask.spawn(browser, "", function() {
- let tttp = Cc["@mozilla.org/embedcomp/default-tooltiptextprovider;1"]
- .getService(Ci.nsITooltipTextProvider);
- function checkElement(id, expectedTooltipText) {
- let el = content.document.getElementById(id);
- let textObj = {};
- let shouldHaveTooltip = expectedTooltipText !== null;
- is(tttp.getNodeText(el, textObj, {}), shouldHaveTooltip,
- "element " + id + " should " + (shouldHaveTooltip ? "" : "not ") + "have a tooltip");
- if (shouldHaveTooltip) {
- is(textObj.value, expectedTooltipText,
- "element " + id + " should have the right tooltip text");
- }
- }
- checkElement("svg1", "This is a non-root SVG element title");
- checkElement("text1", "\n\n\n This is a title\n\n ");
- checkElement("text2", null);
- checkElement("text3", null);
- checkElement("link1", "\n This is a title\n ");
- checkElement("text4", "\n This is a title\n ");
- checkElement("link2", null);
- checkElement("link3", "This is an xlink:title attribute");
- checkElement("link4", "This is an xlink:title attribute");
- checkElement("text5", null);
- });
- });
-});
-
diff --git a/toolkit/components/tooltiptext/tests/browser_bug331772_xul_tooltiptext_in_html.js b/toolkit/components/tooltiptext/tests/browser_bug331772_xul_tooltiptext_in_html.js
deleted file mode 100644
index 23d8c4a6e..000000000
--- a/toolkit/components/tooltiptext/tests/browser_bug331772_xul_tooltiptext_in_html.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * Tests that the tooltiptext attribute is used for XUL elements in an HTML doc.
- */
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://mochi.test:8888/browser/toolkit/components/tooltiptext/tests/xul_tooltiptext.xhtml",
- }, function*(browser) {
- yield ContentTask.spawn(browser, "", function() {
- let textObj = {};
- let tttp = Cc["@mozilla.org/embedcomp/default-tooltiptextprovider;1"]
- .getService(Ci.nsITooltipTextProvider);
- let xulToolbarButton = content.document.getElementById("xulToolbarButton");
- ok(tttp.getNodeText(xulToolbarButton, textObj, {}), "should get tooltiptext");
- is(textObj.value, "XUL tooltiptext");
- });
- });
-});
-
diff --git a/toolkit/components/tooltiptext/tests/browser_bug561623.js b/toolkit/components/tooltiptext/tests/browser_bug561623.js
deleted file mode 100644
index 49c51c4ba..000000000
--- a/toolkit/components/tooltiptext/tests/browser_bug561623.js
+++ /dev/null
@@ -1,24 +0,0 @@
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "data:text/html,<!DOCTYPE html><html><body><input id='i'></body></html>",
- }, function*(browser) {
- yield ContentTask.spawn(browser, "", function() {
- let tttp = Cc["@mozilla.org/embedcomp/default-tooltiptextprovider;1"]
- .getService(Ci.nsITooltipTextProvider);
- let i = content.document.getElementById("i");
-
- ok(!tttp.getNodeText(i, {}, {}),
- "No tooltip should be shown when @title is null");
-
- i.title = "foo";
- ok(tttp.getNodeText(i, {}, {}),
- "A tooltip should be shown when @title is not the empty string");
-
- i.pattern = "bar";
- ok(tttp.getNodeText(i, {}, {}),
- "A tooltip should be shown when @title is not the empty string");
- });
- });
-});
-
diff --git a/toolkit/components/tooltiptext/tests/browser_bug581947.js b/toolkit/components/tooltiptext/tests/browser_bug581947.js
deleted file mode 100644
index 034e0a4d1..000000000
--- a/toolkit/components/tooltiptext/tests/browser_bug581947.js
+++ /dev/null
@@ -1,87 +0,0 @@
-function check(aBrowser, aElementName, aBarred, aType) {
- return ContentTask.spawn(aBrowser, [aElementName, aBarred, aType], function*([aElementName, aBarred, aType]) {
- let e = content.document.createElement(aElementName);
- let contentElement = content.document.getElementById('content');
- contentElement.appendChild(e);
-
- if (aType) {
- e.type = aType;
- }
-
- let tttp = Cc["@mozilla.org/embedcomp/default-tooltiptextprovider;1"]
- .getService(Ci.nsITooltipTextProvider);
- ok(!tttp.getNodeText(e, {}, {}),
- "No tooltip should be shown when the element is valid");
-
- e.setCustomValidity('foo');
- if (aBarred) {
- ok(!tttp.getNodeText(e, {}, {}),
- "No tooltip should be shown when the element is barred from constraint validation");
- } else {
- ok(tttp.getNodeText(e, {}, {}),
- e.tagName + " " +"A tooltip should be shown when the element isn't valid");
- }
-
- e.setAttribute('title', '');
- ok (!tttp.getNodeText(e, {}, {}),
- "No tooltip should be shown if the title attribute is set");
-
- e.removeAttribute('title');
- contentElement.setAttribute('novalidate', '');
- ok (!tttp.getNodeText(e, {}, {}),
- "No tooltip should be shown if the novalidate attribute is set on the form owner");
- contentElement.removeAttribute('novalidate');
-
- e.remove();
- });
-}
-
-function todo_check(aBrowser, aElementName, aBarred) {
- return ContentTask.spawn(aBrowser, [aElementName, aBarred], function*([aElementName, aBarred]) {
- let e = content.document.createElement(aElementName);
- let contentElement = content.document.getElementById('content');
- contentElement.appendChild(e);
-
- let caught = false;
- try {
- e.setCustomValidity('foo');
- } catch (e) {
- caught = true;
- }
-
- todo(!caught, "setCustomValidity should exist for " + aElementName);
-
- e.remove();
- });
-}
-
-add_task(function*() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "data:text/html,<!DOCTYPE html><html><body><form id='content'></form></body></html>",
- }, function*(browser) {
- let testData = [
- /* element name, barred */
- [ 'input', false, null],
- [ 'textarea', false, null],
- [ 'button', true, 'button'],
- [ 'button', false, 'submit'],
- [ 'select', false, null],
- [ 'output', true, null],
- [ 'fieldset', true, null],
- [ 'object', true, null],
- ];
-
- for (let data of testData) {
- yield check(browser, data[0], data[1], data[2]);
- }
-
- let todo_testData = [
- [ 'keygen', 'false' ],
- ];
-
- for (let data of todo_testData) {
- yield todo_check(browser, data[0], data[1]);
- }
- });
-});
diff --git a/toolkit/components/tooltiptext/tests/browser_input_file_tooltips.js b/toolkit/components/tooltiptext/tests/browser_input_file_tooltips.js
deleted file mode 100644
index a1323095d..000000000
--- a/toolkit/components/tooltiptext/tests/browser_input_file_tooltips.js
+++ /dev/null
@@ -1,122 +0,0 @@
-
-let tempFile;
-add_task(function* setup() {
- yield new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": [["ui.tooltipDelay", 0]]}, resolve);
- });
- tempFile = createTempFile();
- registerCleanupFunction(function() {
- tempFile.remove(true);
- });
-});
-
-add_task(function* test_singlefile_selected() {
- yield do_test({value: true, result: "testfile_bug1251809"});
-});
-
-add_task(function* test_title_set() {
- yield do_test({title: "foo", result: "foo"});
-});
-
-add_task(function* test_nofile_selected() {
- yield do_test({result: "No file selected."});
-});
-
-add_task(function* test_multipleset_nofile_selected() {
- yield do_test({multiple: true, result: "No files selected."});
-});
-
-add_task(function* test_requiredset() {
- yield do_test({required: true, result: "Please select a file."});
-});
-
-function* do_test(test) {
- info(`starting test ${JSON.stringify(test)}`);
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
-
- info("Moving mouse out of the way.");
- yield new Promise(resolve => {
- EventUtils.synthesizeNativeMouseMove(tab.linkedBrowser, 300, 300, resolve);
- });
-
- info("creating input field");
- yield ContentTask.spawn(tab.linkedBrowser, test, function*(test) {
- let doc = content.document;
- let input = doc.createElement("input");
- doc.body.appendChild(input);
- input.id = "test_input";
- input.setAttribute("style", "position: absolute; top: 0; left: 0;");
- input.type = "file";
- if (test.title) {
- input.setAttribute("title", test.title);
- }
- if (test.multiple) {
- input.multiple = true;
- }
- if (test.required) {
- input.required = true;
- }
- });
-
- if (test.value) {
- info("Creating mock filepicker to select files");
- let MockFilePicker = SpecialPowers.MockFilePicker;
- MockFilePicker.init(window);
- MockFilePicker.returnValue = MockFilePicker.returnOK;
- MockFilePicker.displayDirectory = FileUtils.getDir("TmpD", [], false);
- MockFilePicker.returnFiles = [tempFile];
-
- try {
- // Open the File Picker dialog (MockFilePicker) to select
- // the files for the test.
- yield BrowserTestUtils.synthesizeMouseAtCenter("#test_input", {}, tab.linkedBrowser);
- info("Waiting for the input to have the requisite files");
- yield ContentTask.spawn(tab.linkedBrowser, {}, function*() {
- let input = content.document.querySelector("#test_input");
- yield ContentTaskUtils.waitForCondition(() => input.files.length,
- "The input should have at least one file selected");
- info(`The input has ${input.files.length} file(s) selected.`);
- });
- } finally {
- MockFilePicker.cleanup();
- }
- } else {
- info("No real file selection required.");
- }
-
- let awaitTooltipOpen = new Promise(resolve => {
- let tooltipId = Services.appinfo.browserTabsRemoteAutostart ?
- "remoteBrowserTooltip" :
- "aHTMLTooltip";
- let tooltip = document.getElementById(tooltipId);
- tooltip.addEventListener("popupshown", function onpopupshown(event) {
- tooltip.removeEventListener("popupshown", onpopupshown);
- resolve(event.target);
- });
- });
- info("Initial mouse move");
- yield new Promise(resolve => {
- EventUtils.synthesizeNativeMouseMove(tab.linkedBrowser, 50, 5, resolve);
- });
- info("Waiting");
- yield new Promise(resolve => setTimeout(resolve, 400));
- info("Second mouse move");
- yield new Promise(resolve => {
- EventUtils.synthesizeNativeMouseMove(tab.linkedBrowser, 70, 5, resolve);
- });
- info("Waiting for tooltip to open");
- let tooltip = yield awaitTooltipOpen;
-
- is(tooltip.getAttribute("label"), test.result, "tooltip label should match expectation");
-
- info("Closing tab");
- yield BrowserTestUtils.removeTab(tab);
-}
-
-function createTempFile() {
- let file = FileUtils.getDir("TmpD", [], false);
- file.append("testfile_bug1251809");
- file.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o644);
- return file;
-}
diff --git a/toolkit/components/tooltiptext/tests/title_test.svg b/toolkit/components/tooltiptext/tests/title_test.svg
deleted file mode 100644
index 7638fd5cc..000000000
--- a/toolkit/components/tooltiptext/tests/title_test.svg
+++ /dev/null
@@ -1,59 +0,0 @@
-<svg width="640px" height="480px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
- <title>This is a root SVG element's title</title>
- <foreignObject>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <body>
- <svg xmlns="http://www.w3.org/2000/svg" id="svg1">
- <title>This is a non-root SVG element title</title>
- </svg>
- </body>
- </html>
- </foreignObject>
- <text id="text1" x="10px" y="32px" font-size="24px">
- This contains only &lt;title&gt;
- <title>
-
-
- This is a title
-
- </title>
- </text>
- <text id="text2" x="10px" y="96px" font-size="24px">
- This contains only &lt;desc&gt;
- <desc>This is a desc</desc>
- </text>
- <text id="text3" x="10px" y="128px" font-size="24px" title="ignored for SVG">
- This contains nothing.
- </text>
- <a id="link1" xlink:href="#">
- This link contains &lt;title&gt;
- <title>
- This is a title
- </title>
- <text id="text4" x="10px" y="192px" font-size="24px">
- </text>
- </a>
- <a id="link2" xlink:href="#">
- <text x="10px" y="192px" font-size="24px">
- This text contains &lt;title&gt;
- <title>
- This is a title
- </title>
- </text>
- </a>
- <a id="link3" xlink:href="#" xlink:title="This is an xlink:title attribute">
- <text x="10px" y="224px" font-size="24px">
- This link contains &lt;title&gt; &amp; xlink:title attr.
- <title>This is a title</title>
- </text>
- </a>
- <a id="link4" xlink:href="#" xlink:title="This is an xlink:title attribute">
- <text x="10px" y="256px" font-size="24px">
- This link contains xlink:title attr.
- </text>
- </a>
- <text id="text5" x="10px" y="160px" font-size="24px"
- xlink:title="This is an xlink:title attribute but it isn't on a link" >
- This contains nothing.
- </text>
-</svg>
diff --git a/toolkit/components/tooltiptext/tests/xul_tooltiptext.xhtml b/toolkit/components/tooltiptext/tests/xul_tooltiptext.xhtml
deleted file mode 100644
index 4a80864dd..000000000
--- a/toolkit/components/tooltiptext/tests/xul_tooltiptext.xhtml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0"?>
-<html xmlns="http://www.w3.org/1999/xhtml"
- xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <xul:toolbox xmlns:html="http://www.w3.org/1999/xhtml"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <toolbar>
- <toolbarbutton id="xulToolbarButton"
- tooltiptext="XUL tooltiptext"
- title="XUL title"/>
- </toolbar>
- </xul:toolbox>
-</html>
-
-
diff --git a/toolkit/components/url-classifier/moz.build b/toolkit/components/url-classifier/moz.build
index d8856ee4a..b6e630abd 100644
--- a/toolkit/components/url-classifier/moz.build
+++ b/toolkit/components/url-classifier/moz.build
@@ -4,8 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-TEST_DIRS += ['tests']
-
XPIDL_SOURCES += [
'nsIUrlClassifierDBService.idl',
'nsIUrlClassifierHashCompleter.idl',
diff --git a/toolkit/components/url-classifier/tests/UrlClassifierTestUtils.jsm b/toolkit/components/url-classifier/tests/UrlClassifierTestUtils.jsm
deleted file mode 100644
index 615769473..000000000
--- a/toolkit/components/url-classifier/tests/UrlClassifierTestUtils.jsm
+++ /dev/null
@@ -1,98 +0,0 @@
-"use strict";
-
-this.EXPORTED_SYMBOLS = ["UrlClassifierTestUtils"];
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-const TRACKING_TABLE_NAME = "mochitest-track-simple";
-const TRACKING_TABLE_PREF = "urlclassifier.trackingTable";
-const WHITELIST_TABLE_NAME = "mochitest-trackwhite-simple";
-const WHITELIST_TABLE_PREF = "urlclassifier.trackingWhitelistTable";
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-this.UrlClassifierTestUtils = {
-
- addTestTrackers() {
- // Add some URLs to the tracking databases
- let trackingURL1 = "tracking.example.com/";
- let trackingURL2 = "itisatracker.org/";
- let trackingURL3 = "trackertest.org/";
- let whitelistedURL = "itisatrap.org/?resource=itisatracker.org";
-
- let trackingUpdate =
- "n:1000\ni:" + TRACKING_TABLE_NAME + "\nad:3\n" +
- "a:1:32:" + trackingURL1.length + "\n" +
- trackingURL1 + "\n" +
- "a:2:32:" + trackingURL2.length + "\n" +
- trackingURL2 + "\n" +
- "a:3:32:" + trackingURL3.length + "\n" +
- trackingURL3 + "\n";
- let whitelistUpdate =
- "n:1000\ni:" + WHITELIST_TABLE_NAME + "\nad:1\n" +
- "a:1:32:" + whitelistedURL.length + "\n" +
- whitelistedURL + "\n";
-
- var tables = [
- {
- pref: TRACKING_TABLE_PREF,
- name: TRACKING_TABLE_NAME,
- update: trackingUpdate
- },
- {
- pref: WHITELIST_TABLE_PREF,
- name: WHITELIST_TABLE_NAME,
- update: whitelistUpdate
- }
- ];
-
- return this.useTestDatabase(tables);
- },
-
- cleanupTestTrackers() {
- Services.prefs.clearUserPref(TRACKING_TABLE_PREF);
- Services.prefs.clearUserPref(WHITELIST_TABLE_PREF);
- },
-
- /**
- * Add some entries to a test tracking protection database, and resets
- * back to the default database after the test ends.
- *
- * @return {Promise}
- */
- useTestDatabase(tables) {
- for (var table of tables) {
- Services.prefs.setCharPref(table.pref, table.name);
- }
-
- return new Promise((resolve, reject) => {
- let dbService = Cc["@mozilla.org/url-classifier/dbservice;1"].
- getService(Ci.nsIUrlClassifierDBService);
- let listener = {
- QueryInterface: iid => {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIUrlClassifierUpdateObserver))
- return listener;
-
- throw Cr.NS_ERROR_NO_INTERFACE;
- },
- updateUrlRequested: url => { },
- streamFinished: status => { },
- updateError: errorCode => {
- reject("Couldn't update classifier.");
- },
- updateSuccess: requestedTimeout => {
- resolve();
- }
- };
-
- for (var table of tables) {
- dbService.beginUpdate(listener, table.name, "");
- dbService.beginStream("", "");
- dbService.updateStream(table.update);
- dbService.finishStream();
- dbService.finishUpdate();
- }
- });
- },
-};
diff --git a/toolkit/components/url-classifier/tests/gtest/Common.cpp b/toolkit/components/url-classifier/tests/gtest/Common.cpp
deleted file mode 100644
index b5f024b38..000000000
--- a/toolkit/components/url-classifier/tests/gtest/Common.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-#include "Common.h"
-#include "HashStore.h"
-#include "Classifier.h"
-#include "nsAppDirectoryServiceDefs.h"
-#include "nsTArray.h"
-#include "nsIThread.h"
-#include "nsThreadUtils.h"
-#include "nsUrlClassifierUtils.h"
-
-using namespace mozilla;
-using namespace mozilla::safebrowsing;
-
-template<typename Function>
-void RunTestInNewThread(Function&& aFunction) {
- nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction(mozilla::Forward<Function>(aFunction));
- nsCOMPtr<nsIThread> testingThread;
- nsresult rv = NS_NewThread(getter_AddRefs(testingThread), r);
- ASSERT_EQ(rv, NS_OK);
- testingThread->Shutdown();
-}
-
-already_AddRefed<nsIFile>
-GetFile(const nsTArray<nsString>& path)
-{
- nsCOMPtr<nsIFile> file;
- nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return nullptr;
- }
-
- for (uint32_t i = 0; i < path.Length(); i++) {
- file->Append(path[i]);
- }
- return file.forget();
-}
-
-void ApplyUpdate(nsTArray<TableUpdate*>& updates)
-{
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-
- UniquePtr<Classifier> classifier(new Classifier());
- classifier->Open(*file);
-
- {
- // Force nsIUrlClassifierUtils loading on main thread
- // because nsIUrlClassifierDBService will not run in advance
- // in gtest.
- nsresult rv;
- nsCOMPtr<nsIUrlClassifierUtils> dummy =
- do_GetService(NS_URLCLASSIFIERUTILS_CONTRACTID, &rv);
- ASSERT_TRUE(NS_SUCCEEDED(rv));
- }
-
- RunTestInNewThread([&] () -> void {
- classifier->ApplyUpdates(&updates);
- });
-}
-
-void ApplyUpdate(TableUpdate* update)
-{
- nsTArray<TableUpdate*> updates = { update };
- ApplyUpdate(updates);
-}
-
-void
-PrefixArrayToPrefixStringMap(const nsTArray<nsCString>& prefixArray,
- PrefixStringMap& out)
-{
- out.Clear();
-
- for (uint32_t i = 0; i < prefixArray.Length(); i++) {
- const nsCString& prefix = prefixArray[i];
- nsCString* prefixString = out.LookupOrAdd(prefix.Length());
- prefixString->Append(prefix.BeginReading(), prefix.Length());
- }
-}
-
diff --git a/toolkit/components/url-classifier/tests/gtest/Common.h b/toolkit/components/url-classifier/tests/gtest/Common.h
deleted file mode 100644
index c9a9cdf7e..000000000
--- a/toolkit/components/url-classifier/tests/gtest/Common.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "HashStore.h"
-#include "nsIFile.h"
-#include "nsTArray.h"
-#include "gtest/gtest.h"
-
-using namespace mozilla;
-using namespace mozilla::safebrowsing;
-
-template<typename Function>
-void RunTestInNewThread(Function&& aFunction);
-
-// Return nsIFile with root directory - NS_APP_USER_PROFILE_50_DIR
-// Sub-directories are passed in path argument.
-already_AddRefed<nsIFile>
-GetFile(const nsTArray<nsString>& path);
-
-// ApplyUpdate will call |ApplyUpdates| of Classifier within a new thread
-void ApplyUpdate(nsTArray<TableUpdate*>& updates);
-
-void ApplyUpdate(TableUpdate* update);
-
-// This function converts lexigraphic-sorted prefixes to a hashtable
-// which key is prefix size and value is concatenated prefix string.
-void PrefixArrayToPrefixStringMap(const nsTArray<nsCString>& prefixArray,
- PrefixStringMap& out);
-
diff --git a/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp b/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp
deleted file mode 100644
index dba2fc2c1..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <set>
-
-#include "gtest/gtest.h"
-#include "ChunkSet.h"
-#include "mozilla/ArrayUtils.h"
-
-TEST(UrlClassifierChunkSet, Empty)
-{
- mozilla::safebrowsing::ChunkSet chunkSet;
- mozilla::safebrowsing::ChunkSet removeSet;
-
- removeSet.Set(0);
-
- ASSERT_FALSE(chunkSet.Has(0));
- ASSERT_FALSE(chunkSet.Has(1));
- ASSERT_TRUE(chunkSet.Remove(removeSet) == NS_OK);
- ASSERT_TRUE(chunkSet.Length() == 0);
-
- chunkSet.Set(0);
-
- ASSERT_TRUE(chunkSet.Has(0));
- ASSERT_TRUE(chunkSet.Length() == 1);
- ASSERT_TRUE(chunkSet.Remove(removeSet) == NS_OK);
- ASSERT_FALSE(chunkSet.Has(0));
- ASSERT_TRUE(chunkSet.Length() == 0);
-}
-
-TEST(UrlClassifierChunkSet, Main)
-{
- static int testVals[] = {2, 1, 5, 6, 8, 7, 14, 10, 12, 13};
-
- mozilla::safebrowsing::ChunkSet chunkSet;
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- chunkSet.Set(testVals[i]);
- }
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- ASSERT_TRUE(chunkSet.Has(testVals[i]));
- }
-
- ASSERT_FALSE(chunkSet.Has(3));
- ASSERT_FALSE(chunkSet.Has(4));
- ASSERT_FALSE(chunkSet.Has(9));
- ASSERT_FALSE(chunkSet.Has(11));
-
- ASSERT_TRUE(chunkSet.Length() == MOZ_ARRAY_LENGTH(testVals));
-}
-
-TEST(UrlClassifierChunkSet, Merge)
-{
- static int testVals[] = {2, 1, 5, 6, 8, 7, 14, 10, 12, 13};
- static int mergeVals[] = {9, 3, 4, 20, 14, 16};
-
- mozilla::safebrowsing::ChunkSet chunkSet;
- mozilla::safebrowsing::ChunkSet mergeSet;
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- chunkSet.Set(testVals[i]);
- }
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- mergeSet.Set(mergeVals[i]);
- }
-
- chunkSet.Merge(mergeSet);
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- ASSERT_TRUE(chunkSet.Has(testVals[i]));
- }
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- ASSERT_TRUE(chunkSet.Has(mergeVals[i]));
- }
-
- // -1 because 14 is duplicated in both sets
- ASSERT_TRUE(chunkSet.Length() ==
- MOZ_ARRAY_LENGTH(testVals) + MOZ_ARRAY_LENGTH(mergeVals) - 1);
-
- ASSERT_FALSE(chunkSet.Has(11));
- ASSERT_FALSE(chunkSet.Has(15));
- ASSERT_FALSE(chunkSet.Has(17));
- ASSERT_FALSE(chunkSet.Has(18));
- ASSERT_FALSE(chunkSet.Has(19));
-}
-
-TEST(UrlClassifierChunkSet, Merge2)
-{
- static int testVals[] = {2, 1, 5, 6, 8, 7, 14, 10, 12, 13};
- static int mergeVals[] = {9, 3, 4, 20, 14, 16};
- static int mergeVals2[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
-
- mozilla::safebrowsing::ChunkSet chunkSet;
- mozilla::safebrowsing::ChunkSet mergeSet;
- mozilla::safebrowsing::ChunkSet mergeSet2;
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- chunkSet.Set(testVals[i]);
- }
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- mergeSet.Set(mergeVals[i]);
- }
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals2); i++) {
- mergeSet2.Set(mergeVals2[i]);
- }
-
- chunkSet.Merge(mergeSet);
- chunkSet.Merge(mergeSet2);
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- ASSERT_TRUE(chunkSet.Has(testVals[i]));
- }
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- ASSERT_TRUE(chunkSet.Has(mergeVals[i]));
- }
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals2); i++) {
- ASSERT_TRUE(chunkSet.Has(mergeVals2[i]));
- }
-
- ASSERT_FALSE(chunkSet.Has(15));
- ASSERT_FALSE(chunkSet.Has(17));
- ASSERT_FALSE(chunkSet.Has(18));
- ASSERT_FALSE(chunkSet.Has(19));
-}
-
-TEST(UrlClassifierChunkSet, Stress)
-{
- mozilla::safebrowsing::ChunkSet chunkSet;
- mozilla::safebrowsing::ChunkSet mergeSet;
- std::set<int> refSet;
- std::set<int> refMergeSet;
- static const int TEST_ITERS = 7000;
- static const int REMOVE_ITERS = 3000;
- static const int TEST_RANGE = 10000;
-
- // Construction by Set
- for (int i = 0; i < TEST_ITERS; i++) {
- int chunk = rand() % TEST_RANGE;
- chunkSet.Set(chunk);
- refSet.insert(chunk);
- }
-
- // Same elements as reference set
- for (auto it = refSet.begin(); it != refSet.end(); ++it) {
- ASSERT_TRUE(chunkSet.Has(*it));
- }
-
- // Hole punching via Remove
- for (int i = 0; i < REMOVE_ITERS; i++) {
- int chunk = rand() % TEST_RANGE;
- mozilla::safebrowsing::ChunkSet helpChunk;
- helpChunk.Set(chunk);
-
- chunkSet.Remove(helpChunk);
- refSet.erase(chunk);
-
- ASSERT_FALSE(chunkSet.Has(chunk));
- }
-
- // Should have chunks present in reference set
- // Should not have chunks absent in reference set
- for (int it = 0; it < TEST_RANGE; ++it) {
- auto found = refSet.find(it);
- if (chunkSet.Has(it)) {
- ASSERT_FALSE(found == refSet.end());
- } else {
- ASSERT_TRUE(found == refSet.end());
- }
- }
-
- // Construct set to merge with
- for (int i = 0; i < TEST_ITERS; i++) {
- int chunk = rand() % TEST_RANGE;
- mergeSet.Set(chunk);
- refMergeSet.insert(chunk);
- }
-
- // Merge set constructed correctly
- for (auto it = refMergeSet.begin(); it != refMergeSet.end(); ++it) {
- ASSERT_TRUE(mergeSet.Has(*it));
- }
-
- mozilla::safebrowsing::ChunkSet origSet;
- origSet = chunkSet;
-
- chunkSet.Merge(mergeSet);
- refSet.insert(refMergeSet.begin(), refMergeSet.end());
-
- // Check for presence of elements from both source
- // Should not have chunks absent in reference set
- for (int it = 0; it < TEST_RANGE; ++it) {
- auto found = refSet.find(it);
- if (chunkSet.Has(it)) {
- ASSERT_FALSE(found == refSet.end());
- } else {
- ASSERT_TRUE(found == refSet.end());
- }
- }
-
- // Unmerge
- chunkSet.Remove(origSet);
- for (int it = 0; it < TEST_RANGE; ++it) {
- if (origSet.Has(it)) {
- ASSERT_FALSE(chunkSet.Has(it));
- } else if (mergeSet.Has(it)) {
- ASSERT_TRUE(chunkSet.Has(it));
- }
- }
-}
-
-TEST(UrlClassifierChunkSet, RemoveClear)
-{
- static int testVals[] = {2, 1, 5, 6, 8, 7, 14, 10, 12, 13};
- static int mergeVals[] = {3, 4, 9, 16, 20};
-
- mozilla::safebrowsing::ChunkSet chunkSet;
- mozilla::safebrowsing::ChunkSet mergeSet;
- mozilla::safebrowsing::ChunkSet removeSet;
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- chunkSet.Set(testVals[i]);
- removeSet.Set(testVals[i]);
- }
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- mergeSet.Set(mergeVals[i]);
- }
-
- ASSERT_TRUE(chunkSet.Merge(mergeSet) == NS_OK);
- ASSERT_TRUE(chunkSet.Remove(removeSet) == NS_OK);
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- ASSERT_TRUE(chunkSet.Has(mergeVals[i]));
- }
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- ASSERT_FALSE(chunkSet.Has(testVals[i]));
- }
-
- chunkSet.Clear();
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- ASSERT_FALSE(chunkSet.Has(mergeVals[i]));
- }
-}
-
-TEST(UrlClassifierChunkSet, Serialize)
-{
- static int testVals[] = {2, 1, 5, 6, 8, 7, 14, 10, 12, 13};
- static int mergeVals[] = {3, 4, 9, 16, 20};
-
- mozilla::safebrowsing::ChunkSet chunkSet;
- mozilla::safebrowsing::ChunkSet mergeSet;
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(testVals); i++) {
- chunkSet.Set(testVals[i]);
- }
-
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mergeVals); i++) {
- mergeSet.Set(mergeVals[i]);
- }
-
- chunkSet.Merge(mergeSet);
-
- nsAutoCString mergeResult;
- chunkSet.Serialize(mergeResult);
-
- printf("mergeResult: %s\n", mergeResult.get());
-
- nsAutoCString expected(NS_LITERAL_CSTRING("1-10,12-14,16,20"));
-
- ASSERT_TRUE(mergeResult.Equals(expected));
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp b/toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp
deleted file mode 100644
index bdb9eebb0..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-#include "HashStore.h"
-#include "nsPrintfCString.h"
-#include "string.h"
-#include "gtest/gtest.h"
-#include "mozilla/Unused.h"
-
-using namespace mozilla;
-using namespace mozilla::safebrowsing;
-
-static const char* kFilesInV2[] = {".pset", ".sbstore"};
-static const char* kFilesInV4[] = {".pset", ".metadata"};
-
-#define V2_TABLE "gtest-malware-simple"
-#define V4_TABLE1 "goog-malware-proto"
-#define V4_TABLE2 "goog-phish-proto"
-
-#define ROOT_DIR NS_LITERAL_STRING("safebrowsing")
-#define SB_FILE(x, y) NS_ConvertUTF8toUTF16(nsPrintfCString("%s%s",x, y))
-
-template<typename T, size_t N>
-void CheckFileExist(const char* table, const T (&files)[N], bool expectExists)
-{
- for (uint32_t i = 0; i < N; i++) {
- // This is just a quick way to know if this is v4 table
- NS_ConvertUTF8toUTF16 SUB_DIR(strstr(table, "-proto") ? "google4" : "");
- nsCOMPtr<nsIFile> file =
- GetFile(nsTArray<nsString> { ROOT_DIR, SUB_DIR, SB_FILE(table, files[i]) });
-
- bool exists;
- file->Exists(&exists);
-
- nsAutoCString path;
- file->GetNativePath(path);
- ASSERT_EQ(expectExists, exists) << path.get();
- }
-}
-
-TEST(FailUpdate, CheckTableReset)
-{
- const bool FULL_UPDATE = true;
- const bool PARTIAL_UPDATE = false;
-
- // Apply V2 update
- {
- auto update = new TableUpdateV2(NS_LITERAL_CSTRING(V2_TABLE));
- Unused << update->NewAddChunk(1);
-
- ApplyUpdate(update);
-
- // A successful V2 update should create .pset & .sbstore files
- CheckFileExist(V2_TABLE, kFilesInV2, true);
- }
-
- // Helper function to generate table update data
- auto func = [](TableUpdateV4* update, bool full, const char* str) {
- update->SetFullUpdate(full);
- std::string prefix(str);
- update->NewPrefixes(prefix.length(), prefix);
- };
-
- // Apply V4 update for table1
- {
- auto update = new TableUpdateV4(NS_LITERAL_CSTRING(V4_TABLE1));
- func(update, FULL_UPDATE, "test_prefix");
-
- ApplyUpdate(update);
-
- // A successful V4 update should create .pset & .metadata files
- CheckFileExist(V4_TABLE1, kFilesInV4, true);
- }
-
- // Apply V4 update for table2
- {
- auto update = new TableUpdateV4(NS_LITERAL_CSTRING(V4_TABLE2));
- func(update, FULL_UPDATE, "test_prefix");
-
- ApplyUpdate(update);
-
- CheckFileExist(V4_TABLE2, kFilesInV4, true);
- }
-
- // Apply V4 update with the same prefix in previous full udpate
- // This should cause an update error.
- {
- auto update = new TableUpdateV4(NS_LITERAL_CSTRING(V4_TABLE1));
- func(update, PARTIAL_UPDATE, "test_prefix");
-
- ApplyUpdate(update);
-
- // A fail update should remove files for that table
- CheckFileExist(V4_TABLE1, kFilesInV4, false);
-
- // A fail update should NOT remove files for the other tables
- CheckFileExist(V2_TABLE, kFilesInV2, true);
- CheckFileExist(V4_TABLE2, kFilesInV4, true);
- }
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp b/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp
deleted file mode 100644
index 00525f704..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp
+++ /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/. */
-
-#include "LookupCacheV4.h"
-#include "Common.h"
-
-#define GTEST_SAFEBROWSING_DIR NS_LITERAL_CSTRING("safebrowsing")
-#define GTEST_TABLE NS_LITERAL_CSTRING("gtest-malware-proto")
-
-typedef nsCString _Fragment;
-typedef nsTArray<nsCString> _PrefixArray;
-
-// Generate a hash prefix from string
-static const nsCString
-GeneratePrefix(const _Fragment& aFragment, uint8_t aLength)
-{
- Completion complete;
- nsCOMPtr<nsICryptoHash> cryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID);
- complete.FromPlaintext(aFragment, cryptoHash);
-
- nsCString hash;
- hash.Assign((const char *)complete.buf, aLength);
- return hash;
-}
-
-static UniquePtr<LookupCacheV4>
-SetupLookupCacheV4(const _PrefixArray& prefixArray)
-{
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-
- file->AppendNative(GTEST_SAFEBROWSING_DIR);
-
- UniquePtr<LookupCacheV4> cache = MakeUnique<LookupCacheV4>(GTEST_TABLE, EmptyCString(), file);
- nsresult rv = cache->Init();
- EXPECT_EQ(rv, NS_OK);
-
- PrefixStringMap map;
- PrefixArrayToPrefixStringMap(prefixArray, map);
- rv = cache->Build(map);
- EXPECT_EQ(rv, NS_OK);
-
- return Move(cache);
-}
-
-void
-TestHasPrefix(const _Fragment& aFragment, bool aExpectedHas, bool aExpectedComplete)
-{
- _PrefixArray array = { GeneratePrefix(_Fragment("bravo.com/"), 32),
- GeneratePrefix(_Fragment("browsing.com/"), 8),
- GeneratePrefix(_Fragment("gound.com/"), 5),
- GeneratePrefix(_Fragment("small.com/"), 4)
- };
-
- RunTestInNewThread([&] () -> void {
- UniquePtr<LookupCache> cache = SetupLookupCacheV4(array);
-
- Completion lookupHash;
- nsCOMPtr<nsICryptoHash> cryptoHash = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID);
- lookupHash.FromPlaintext(aFragment, cryptoHash);
-
- bool has, complete;
- nsresult rv = cache->Has(lookupHash, &has, &complete);
-
- EXPECT_EQ(rv, NS_OK);
- EXPECT_EQ(has, aExpectedHas);
- EXPECT_EQ(complete, aExpectedComplete);
-
- cache->ClearAll();
- });
-
-}
-
-TEST(LookupCacheV4, HasComplete)
-{
- TestHasPrefix(_Fragment("bravo.com/"), true, true);
-}
-
-TEST(LookupCacheV4, HasPrefix)
-{
- TestHasPrefix(_Fragment("browsing.com/"), true, false);
-}
-
-TEST(LookupCacheV4, Nomatch)
-{
- TestHasPrefix(_Fragment("nomatch.com/"), false, false);
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestPerProviderDirectory.cpp b/toolkit/components/url-classifier/tests/gtest/TestPerProviderDirectory.cpp
deleted file mode 100644
index 72ff08a1e..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestPerProviderDirectory.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-#include "LookupCache.h"
-#include "LookupCacheV4.h"
-#include "HashStore.h"
-#include "gtest/gtest.h"
-#include "nsAppDirectoryServiceDefs.h"
-
-namespace mozilla {
-namespace safebrowsing {
-
-class PerProviderDirectoryTestUtils {
-public:
- template<typename T>
- static nsIFile* InspectStoreDirectory(const T& aT)
- {
- return aT.mStoreDirectory;
- }
-};
-
-} // end of namespace safebrowsing
-} // end of namespace mozilla
-
-using namespace mozilla;
-using namespace mozilla::safebrowsing;
-
-template<typename T>
-void VerifyPrivateStorePath(const char* aTableName,
- const char* aProvider,
- nsIFile* aRootDir,
- bool aUsePerProviderStore)
-{
- nsString rootStorePath;
- nsresult rv = aRootDir->GetPath(rootStorePath);
- EXPECT_EQ(rv, NS_OK);
-
- T target(nsCString(aTableName), nsCString(aProvider), aRootDir);
-
- nsIFile* privateStoreDirectory =
- PerProviderDirectoryTestUtils::InspectStoreDirectory(target);
-
- nsString privateStorePath;
- rv = privateStoreDirectory->GetPath(privateStorePath);
- ASSERT_EQ(rv, NS_OK);
-
- nsString expectedPrivateStorePath = rootStorePath;
-
- if (aUsePerProviderStore) {
- // Use API to append "provider" to the root directoy path
- nsCOMPtr<nsIFile> expectedPrivateStoreDir;
- rv = aRootDir->Clone(getter_AddRefs(expectedPrivateStoreDir));
- ASSERT_EQ(rv, NS_OK);
-
- expectedPrivateStoreDir->AppendNative(nsCString(aProvider));
- rv = expectedPrivateStoreDir->GetPath(expectedPrivateStorePath);
- ASSERT_EQ(rv, NS_OK);
- }
-
- printf("table: %s\nprovider: %s\nroot path: %s\nprivate path: %s\n\n",
- aTableName,
- aProvider,
- NS_ConvertUTF16toUTF8(rootStorePath).get(),
- NS_ConvertUTF16toUTF8(privateStorePath).get());
-
- ASSERT_TRUE(privateStorePath == expectedPrivateStorePath);
-}
-
-TEST(PerProviderDirectory, LookupCache)
-{
- RunTestInNewThread([] () -> void {
- nsCOMPtr<nsIFile> rootDir;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(rootDir));
-
- // For V2 tables (NOT ending with '-proto'), root directory should be
- // used as the private store.
- VerifyPrivateStorePath<LookupCacheV2>("goog-phish-shavar", "google", rootDir, false);
-
- // For V4 tables, if provider is found, use per-provider subdirectory;
- // If not found, use root directory.
- VerifyPrivateStorePath<LookupCacheV4>("goog-noprovider-proto", "", rootDir, false);
- VerifyPrivateStorePath<LookupCacheV4>("goog-phish-proto", "google4", rootDir, true);
- });
-}
-
-TEST(PerProviderDirectory, HashStore)
-{
- RunTestInNewThread([] () -> void {
- nsCOMPtr<nsIFile> rootDir;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(rootDir));
-
- // For V2 tables (NOT ending with '-proto'), root directory should be
- // used as the private store.
- VerifyPrivateStorePath<HashStore>("goog-phish-shavar", "google", rootDir, false);
-
- // For V4 tables, if provider is found, use per-provider subdirectory;
- // If not found, use root directory.
- VerifyPrivateStorePath<HashStore>("goog-noprovider-proto", "", rootDir, false);
- VerifyPrivateStorePath<HashStore>("goog-phish-proto", "google4", rootDir, true);
- });
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestProtocolParser.cpp b/toolkit/components/url-classifier/tests/gtest/TestProtocolParser.cpp
deleted file mode 100644
index ea6ffb5e6..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestProtocolParser.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-#include "gtest/gtest.h"
-#include "ProtocolParser.h"
-#include "mozilla/EndianUtils.h"
-
-using namespace mozilla;
-using namespace mozilla::safebrowsing;
-
-typedef FetchThreatListUpdatesResponse_ListUpdateResponse ListUpdateResponse;
-
-static bool
-InitUpdateResponse(ListUpdateResponse* aUpdateResponse,
- ThreatType aThreatType,
- const nsACString& aState,
- const nsACString& aChecksum,
- bool isFullUpdate,
- const nsTArray<uint32_t>& aFixedLengthPrefixes,
- bool aDoPrefixEncoding);
-
-static void
-DumpBinary(const nsACString& aBinary);
-
-TEST(ProtocolParser, UpdateWait)
-{
- // Top level response which contains a list of update response
- // for different lists.
- FetchThreatListUpdatesResponse response;
-
- auto r = response.mutable_list_update_responses()->Add();
- InitUpdateResponse(r, SOCIAL_ENGINEERING_PUBLIC,
- nsCString("sta\x00te", 6),
- nsCString("check\x0sum", 9),
- true,
- {0, 1, 2, 3},
- false /* aDoPrefixEncoding */ );
-
- // Set min wait duration.
- auto minWaitDuration = response.mutable_minimum_wait_duration();
- minWaitDuration->set_seconds(8);
- minWaitDuration->set_nanos(1 * 1000000000);
-
- std::string s;
- response.SerializeToString(&s);
-
- DumpBinary(nsCString(s.c_str(), s.length()));
-
- ProtocolParser* p = new ProtocolParserProtobuf();
- p->AppendStream(nsCString(s.c_str(), s.length()));
- p->End();
- ASSERT_EQ(p->UpdateWaitSec(), 9u);
- delete p;
-}
-
-TEST(ProtocolParser, SingleValueEncoding)
-{
- // Top level response which contains a list of update response
- // for different lists.
- FetchThreatListUpdatesResponse response;
-
- auto r = response.mutable_list_update_responses()->Add();
-
- const char* expectedPrefix = "\x00\x01\x02\x00";
- if (!InitUpdateResponse(r, SOCIAL_ENGINEERING_PUBLIC,
- nsCString("sta\x00te", 6),
- nsCString("check\x0sum", 9),
- true,
- // As per spec, we should interpret the prefix as uint32
- // in little endian before encoding.
- {LittleEndian::readUint32(expectedPrefix)},
- true /* aDoPrefixEncoding */ )) {
- printf("Failed to initialize update response.");
- ASSERT_TRUE(false);
- return;
- }
-
- // Set min wait duration.
- auto minWaitDuration = response.mutable_minimum_wait_duration();
- minWaitDuration->set_seconds(8);
- minWaitDuration->set_nanos(1 * 1000000000);
-
- std::string s;
- response.SerializeToString(&s);
-
- // Feed data to the protocol parser.
- ProtocolParser* p = new ProtocolParserProtobuf();
- p->SetRequestedTables({ nsCString("googpub-phish-proto") });
- p->AppendStream(nsCString(s.c_str(), s.length()));
- p->End();
-
- auto& tus = p->GetTableUpdates();
- auto tuv4 = TableUpdate::Cast<TableUpdateV4>(tus[0]);
- auto& prefixMap = tuv4->Prefixes();
- for (auto iter = prefixMap.Iter(); !iter.Done(); iter.Next()) {
- // This prefix map should contain only a single 4-byte prefixe.
- ASSERT_EQ(iter.Key(), 4u);
-
- // The fixed-length prefix string from ProtcolParser should
- // exactly match the expected prefix string.
- auto& prefix = iter.Data()->GetPrefixString();
- ASSERT_TRUE(prefix.Equals(nsCString(expectedPrefix, 4)));
- }
-
- delete p;
-}
-
-static bool
-InitUpdateResponse(ListUpdateResponse* aUpdateResponse,
- ThreatType aThreatType,
- const nsACString& aState,
- const nsACString& aChecksum,
- bool isFullUpdate,
- const nsTArray<uint32_t>& aFixedLengthPrefixes,
- bool aDoPrefixEncoding)
-{
- aUpdateResponse->set_threat_type(aThreatType);
- aUpdateResponse->set_new_client_state(aState.BeginReading(), aState.Length());
- aUpdateResponse->mutable_checksum()->set_sha256(aChecksum.BeginReading(), aChecksum.Length());
- aUpdateResponse->set_response_type(isFullUpdate ? ListUpdateResponse::FULL_UPDATE
- : ListUpdateResponse::PARTIAL_UPDATE);
-
- auto additions = aUpdateResponse->mutable_additions()->Add();
-
- if (!aDoPrefixEncoding) {
- additions->set_compression_type(RAW);
- auto rawHashes = additions->mutable_raw_hashes();
- rawHashes->set_prefix_size(4);
- auto prefixes = rawHashes->mutable_raw_hashes();
- for (auto p : aFixedLengthPrefixes) {
- char buffer[4];
- NativeEndian::copyAndSwapToBigEndian(buffer, &p, 1);
- prefixes->append(buffer, 4);
- }
- return true;
- }
-
- if (1 != aFixedLengthPrefixes.Length()) {
- printf("This function only supports single value encoding.\n");
- return false;
- }
-
- uint32_t firstValue = aFixedLengthPrefixes[0];
- additions->set_compression_type(RICE);
- auto riceHashes = additions->mutable_rice_hashes();
- riceHashes->set_first_value(firstValue);
- riceHashes->set_num_entries(0);
-
- return true;
-}
-
-static void DumpBinary(const nsACString& aBinary)
-{
- nsCString s;
- for (size_t i = 0; i < aBinary.Length(); i++) {
- s.AppendPrintf("\\x%.2X", (uint8_t)aBinary[i]);
- }
- printf("%s\n", s.get());
-} \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/gtest/TestRiceDeltaDecoder.cpp b/toolkit/components/url-classifier/tests/gtest/TestRiceDeltaDecoder.cpp
deleted file mode 100644
index f03d27358..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestRiceDeltaDecoder.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-#include "gtest/gtest.h"
-#include "RiceDeltaDecoder.h"
-#include "mozilla/ArrayUtils.h"
-
-using namespace mozilla;
-using namespace mozilla::safebrowsing;
-
-struct TestingData {
- std::vector<uint32_t> mExpectedDecoded;
- std::vector<uint8_t> mEncoded;
- uint32_t mRiceParameter;
-};
-
-static bool runOneTest(TestingData& aData);
-
-TEST(RiceDeltaDecoder, SingleEncodedValue) {
- TestingData td = { { 99 }, { 99 }, 0 };
-
- ASSERT_TRUE(runOneTest(td));
-}
-
-// In this batch of tests, the encoded data would be like
-// what we originally receive from the network. See comment
-// in |runOneTest| for more detail.
-TEST(RiceDeltaDecoder, Empty) {
-
- // The following structure and testing data is copied from Chromium source code:
- //
- // https://chromium.googlesource.com/chromium/src.git/+/950f9975599768b6a08c7146cb4befa161be87aa/components/safe_browsing_db/v4_rice_unittest.cc#75
- //
- // and will be translated to our own testing format.
-
- struct RiceDecodingTestInfo {
- uint32_t mRiceParameter;
- std::vector<uint32_t> mDeltas;
- std::string mEncoded;
-
- RiceDecodingTestInfo(uint32_t aRiceParameter,
- const std::vector<uint32_t>& aDeltas,
- const std::string& aEncoded)
- : mRiceParameter(aRiceParameter)
- , mDeltas(aDeltas)
- , mEncoded(aEncoded)
- {
- }
- };
-
- // Copyright 2016 The Chromium Authors. All rights reserved.
- // Use of this source code is governed by a BSD-style license that can be
- // found in the media/webrtc/trunk/webrtc/LICENSE.
-
- // ----- Start of Chromium test code ----
- const std::vector<RiceDecodingTestInfo> TESTING_DATA_CHROMIUM = {
- RiceDecodingTestInfo(2, {15, 9}, "\xf7\x2"),
- RiceDecodingTestInfo(
- 28, {1777762129, 2093280223, 924369848},
- "\xbf\xa8\x3f\xfb\xfc\xfb\x5e\x27\xe6\xc3\x1d\xc6\x38"),
- RiceDecodingTestInfo(
- 28, {62763050, 1046523781, 192522171, 1800511020, 4442775, 582142548},
- "\x54\x60\x7b\xe7\x0a\x5f\xc1\xdc\xee\x69\xde"
- "\xfe\x58\x3c\xa3\xd6\xa5\xf2\x10\x8c\x4a\x59"
- "\x56\x00"),
- RiceDecodingTestInfo(
- 28, {26067715, 344823336, 8420095, 399843890, 95029378, 731622412,
- 35811335, 1047558127, 1117722715, 78698892},
- "\x06\x86\x1b\x23\x14\xcb\x46\xf2\xaf\x07\x08\xc9\x88\x54\x1f\x41\x04"
- "\xd5\x1a\x03\xeb\xe6\x3a\x80\x13\x91\x7b\xbf\x83\xf3\xb7\x85\xf1\x29"
- "\x18\xb3\x61\x09"),
- RiceDecodingTestInfo(
- 27, {225846818, 328287420, 166748623, 29117720, 552397365, 350353215,
- 558267528, 4738273, 567093445, 28563065, 55077698, 73091685,
- 339246010, 98242620, 38060941, 63917830, 206319759, 137700744},
- "\x89\x98\xd8\x75\xbc\x44\x91\xeb\x39\x0c\x3e\x30\x9a\x78\xf3\x6a\xd4"
- "\xd9\xb1\x9f\xfb\x70\x3e\x44\x3e\xa3\x08\x67\x42\xc2\x2b\x46\x69\x8e"
- "\x3c\xeb\xd9\x10\x5a\x43\x9a\x32\xa5\x2d\x4e\x77\x0f\x87\x78\x20\xb6"
- "\xab\x71\x98\x48\x0c\x9e\x9e\xd7\x23\x0c\x13\x43\x2c\xa9\x01"),
- RiceDecodingTestInfo(
- 28, {339784008, 263128563, 63871877, 69723256, 826001074, 797300228,
- 671166008, 207712688},
- std::string("\x21\xc5\x02\x91\xf9\x82\xd7\x57\xb8\xe9\x3c\xf0\xc8\x4f"
- "\xe8\x64\x8d\x77\x62\x04\xd6\x85\x3f\x1c\x97\x00\x04\x1b"
- "\x17\xc6",
- 30)),
- RiceDecodingTestInfo(
- 28, {471820069, 196333855, 855579133, 122737976, 203433838, 85354544,
- 1307949392, 165938578, 195134475, 553930435, 49231136},
- "\x95\x9c\x7d\xb0\x8f\xe8\xd9\xbd\xfe\x8c\x7f\x81\x53\x0d\x75\xdc\x4e"
- "\x40\x18\x0c\x9a\x45\x3d\xa8\xdc\xfa\x26\x59\x40\x9e\x16\x08\x43\x77"
- "\xc3\x4e\x04\x01\xa4\xe6\x5d\x00"),
- RiceDecodingTestInfo(
- 27, {87336845, 129291033, 30906211, 433549264, 30899891, 53207875,
- 11959529, 354827862, 82919275, 489637251, 53561020, 336722992,
- 408117728, 204506246, 188216092, 9047110, 479817359, 230317256},
- "\x1a\x4f\x69\x2a\x63\x9a\xf6\xc6\x2e\xaf\x73\xd0\x6f\xd7\x31\xeb\x77"
- "\x1d\x43\xe3\x2b\x93\xce\x67\x8b\x59\xf9\x98\xd4\xda\x4f\x3c\x6f\xb0"
- "\xe8\xa5\x78\x8d\x62\x36\x18\xfe\x08\x1e\x78\xd8\x14\x32\x24\x84\x61"
- "\x1c\xf3\x37\x63\xc4\xa0\x88\x7b\x74\xcb\x64\xc8\x5c\xba\x05"),
- RiceDecodingTestInfo(
- 28, {297968956, 19709657, 259702329, 76998112, 1023176123, 29296013,
- 1602741145, 393745181, 177326295, 55225536, 75194472},
- "\xf1\x94\x0a\x87\x6c\x5f\x96\x90\xe3\xab\xf7\xc0\xcb\x2d\xe9\x76\xdb"
- "\xf8\x59\x63\xc1\x6f\x7c\x99\xe3\x87\x5f\xc7\x04\xde\xb9\x46\x8e\x54"
- "\xc0\xac\x4a\x03\x0d\x6c\x8f\x00"),
- RiceDecodingTestInfo(
- 28, {532220688, 780594691, 436816483, 163436269, 573044456, 1069604,
- 39629436, 211410997, 227714491, 381562898, 75610008, 196754597,
- 40310339, 15204118, 99010842},
- "\x41\x2c\xe4\xfe\x06\xdc\x0d\xbd\x31\xa5\x04\xd5\x6e\xdd\x9b\x43\xb7"
- "\x3f\x11\x24\x52\x10\x80\x4f\x96\x4b\xd4\x80\x67\xb2\xdd\x52\xc9\x4e"
- "\x02\xc6\xd7\x60\xde\x06\x92\x52\x1e\xdd\x35\x64\x71\x26\x2c\xfe\xcf"
- "\x81\x46\xb2\x79\x01"),
- RiceDecodingTestInfo(
- 28, {219354713, 389598618, 750263679, 554684211, 87381124, 4523497,
- 287633354, 801308671, 424169435, 372520475, 277287849},
- "\xb2\x2c\x26\x3a\xcd\x66\x9c\xdb\x5f\x07\x2e\x6f\xe6\xf9\x21\x10\x52"
- "\xd5\x94\xf4\x82\x22\x48\xf9\x9d\x24\xf6\xff\x2f\xfc\x6d\x3f\x21\x65"
- "\x1b\x36\x34\x56\xea\xc4\x21\x00"),
- };
-
- // ----- End of Chromium test code ----
-
- for (auto tdc : TESTING_DATA_CHROMIUM) {
- // Populate chromium testing data to our native testing data struct.
- TestingData d;
-
- d.mRiceParameter = tdc.mRiceParameter; // Populate rice parameter.
-
- // Populate encoded data from std::string to vector<uint8>.
- d.mEncoded.resize(tdc.mEncoded.size());
- memcpy(&d.mEncoded[0], tdc.mEncoded.c_str(), tdc.mEncoded.size());
-
- // Populate deltas to expected decoded data. The first value would be just
- // set to an arbitrary value, say 7, to avoid any assumption to the
- // first value in the implementation.
- d.mExpectedDecoded.resize(tdc.mDeltas.size() + 1);
- for (size_t i = 0; i < d.mExpectedDecoded.size(); i++) {
- if (0 == i) {
- d.mExpectedDecoded[i] = 7; // "7" is an arbitrary starting value
- } else {
- d.mExpectedDecoded[i] = d.mExpectedDecoded[i - 1] + tdc.mDeltas[i - 1];
- }
- }
-
- ASSERT_TRUE(runOneTest(d));
- }
-}
-
-static bool
-runOneTest(TestingData& aData)
-{
- RiceDeltaDecoder decoder(&aData.mEncoded[0], aData.mEncoded.size());
-
- std::vector<uint32_t> decoded(aData.mExpectedDecoded.size());
-
- uint32_t firstValue = aData.mExpectedDecoded[0];
- bool rv = decoder.Decode(aData.mRiceParameter,
- firstValue,
- decoded.size() - 1, // # of entries (first value not included).
- &decoded[0]);
-
- return rv && decoded == aData.mExpectedDecoded;
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestSafeBrowsingProtobuf.cpp b/toolkit/components/url-classifier/tests/gtest/TestSafeBrowsingProtobuf.cpp
deleted file mode 100644
index fe6f28960..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestSafeBrowsingProtobuf.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include "safebrowsing.pb.h"
-#include "gtest/gtest.h"
-
-TEST(SafeBrowsingProtobuf, Empty)
-{
- using namespace mozilla::safebrowsing;
-
- const std::string CLIENT_ID = "firefox";
-
- // Construct a simple update request.
- FetchThreatListUpdatesRequest r;
- r.set_allocated_client(new ClientInfo());
- r.mutable_client()->set_client_id(CLIENT_ID);
-
- // Then serialize.
- std::string s;
- r.SerializeToString(&s);
-
- // De-serialize.
- FetchThreatListUpdatesRequest r2;
- r2.ParseFromString(s);
-
- ASSERT_EQ(r2.client().client_id(), CLIENT_ID);
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestSafebrowsingHash.cpp b/toolkit/components/url-classifier/tests/gtest/TestSafebrowsingHash.cpp
deleted file mode 100644
index 89ed74be6..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestSafebrowsingHash.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-#include "Entries.h"
-#include "mozilla/EndianUtils.h"
-
-TEST(SafebrowsingHash, ToFromUint32)
-{
- using namespace mozilla::safebrowsing;
-
- // typedef SafebrowsingHash<PREFIX_SIZE, PrefixComparator> Prefix;
- // typedef nsTArray<Prefix> PrefixArray;
-
- const char PREFIX_RAW[4] = { 0x1, 0x2, 0x3, 0x4 };
- uint32_t PREFIX_UINT32;
- memcpy(&PREFIX_UINT32, PREFIX_RAW, 4);
-
- Prefix p;
- p.Assign(nsCString(PREFIX_RAW, 4));
- ASSERT_EQ(p.ToUint32(), PREFIX_UINT32);
-
- p.FromUint32(PREFIX_UINT32);
- ASSERT_EQ(memcmp(PREFIX_RAW, p.buf, 4), 0);
-}
-
-TEST(SafebrowsingHash, Compare)
-{
- using namespace mozilla;
- using namespace mozilla::safebrowsing;
-
- Prefix p1, p2, p3;
-
- // The order of p1,p2,p3 is "p1 == p3 < p2"
-#if MOZ_LITTLE_ENDIAN
- p1.Assign(nsCString("\x01\x00\x00\x00", 4));
- p2.Assign(nsCString("\x00\x00\x00\x01", 4));
- p3.Assign(nsCString("\x01\x00\x00\x00", 4));
-#else
- p1.Assign(nsCString("\x00\x00\x00\x01", 4));
- p2.Assign(nsCString("\x01\x00\x00\x00", 4));
- p3.Assign(nsCString("\x00\x00\x00\x01", 4));
-#endif
-
- // Make sure "p1 == p3 < p2" is true
- // on both little and big endian machine.
-
- ASSERT_EQ(p1.Compare(p2), -1);
- ASSERT_EQ(p1.Compare(p1), 0);
- ASSERT_EQ(p2.Compare(p1), 1);
- ASSERT_EQ(p1.Compare(p3), 0);
-
- ASSERT_TRUE(p1 < p2);
- ASSERT_TRUE(p1 == p1);
- ASSERT_TRUE(p1 == p3);
-} \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/gtest/TestTable.cpp b/toolkit/components/url-classifier/tests/gtest/TestTable.cpp
deleted file mode 100644
index 307587459..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestTable.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-#include "gtest/gtest.h"
-#include "nsUrlClassifierDBService.h"
-
-using namespace mozilla::safebrowsing;
-
-void
-TestResponseCode(const char* table, nsresult result)
-{
- nsCString tableName(table);
- ASSERT_EQ(TablesToResponse(tableName), result);
-}
-
-TEST(UrlClassifierTable, ResponseCode)
-{
- // malware URIs.
- TestResponseCode("goog-malware-shavar", NS_ERROR_MALWARE_URI);
- TestResponseCode("test-malware-simple", NS_ERROR_MALWARE_URI);
- TestResponseCode("goog-phish-shavar,test-malware-simple", NS_ERROR_MALWARE_URI);
- TestResponseCode("test-malware-simple,mozstd-track-digest256,mozplugin-block-digest256", NS_ERROR_MALWARE_URI);
-
- // phish URIs.
- TestResponseCode("goog-phish-shavar", NS_ERROR_PHISHING_URI);
- TestResponseCode("test-phish-simple", NS_ERROR_PHISHING_URI);
- TestResponseCode("test-phish-simple,mozplugin-block-digest256", NS_ERROR_PHISHING_URI);
- TestResponseCode("mozstd-track-digest256,test-phish-simple,goog-unwanted-shavar", NS_ERROR_PHISHING_URI);
-
- // unwanted URIs.
- TestResponseCode("goog-unwanted-shavar", NS_ERROR_UNWANTED_URI);
- TestResponseCode("test-unwanted-simple", NS_ERROR_UNWANTED_URI);
- TestResponseCode("mozplugin-unwanted-digest256,mozfull-track-digest256", NS_ERROR_UNWANTED_URI);
- TestResponseCode("test-block-simple,mozfull-track-digest256,test-unwanted-simple", NS_ERROR_UNWANTED_URI);
-
- // track URIs.
- TestResponseCode("test-track-simple", NS_ERROR_TRACKING_URI);
- TestResponseCode("mozstd-track-digest256", NS_ERROR_TRACKING_URI);
- TestResponseCode("test-block-simple,mozstd-track-digest256", NS_ERROR_TRACKING_URI);
-
- // block URIs
- TestResponseCode("test-block-simple", NS_ERROR_BLOCKED_URI);
- TestResponseCode("mozplugin-block-digest256", NS_ERROR_BLOCKED_URI);
- TestResponseCode("mozplugin2-block-digest256", NS_ERROR_BLOCKED_URI);
-
- TestResponseCode("test-trackwhite-simple", NS_OK);
- TestResponseCode("mozstd-trackwhite-digest256", NS_OK);
- TestResponseCode("goog-badbinurl-shavar", NS_OK);
- TestResponseCode("goog-downloadwhite-digest256", NS_OK);
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp b/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp
deleted file mode 100644
index 470a88ba2..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp
+++ /dev/null
@@ -1,755 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-#include "Common.h"
-#include "Classifier.h"
-#include "HashStore.h"
-#include "nsAppDirectoryServiceDefs.h"
-#include "nsIFile.h"
-#include "nsIThread.h"
-#include "string.h"
-#include "gtest/gtest.h"
-#include "nsThreadUtils.h"
-
-using namespace mozilla;
-using namespace mozilla::safebrowsing;
-
-typedef nsCString _Prefix;
-typedef nsTArray<_Prefix> _PrefixArray;
-
-#define GTEST_SAFEBROWSING_DIR NS_LITERAL_CSTRING("safebrowsing")
-#define GTEST_TABLE NS_LITERAL_CSTRING("gtest-malware-proto")
-#define GTEST_PREFIXFILE NS_LITERAL_CSTRING("gtest-malware-proto.pset")
-
-// This function removes common elements of inArray and outArray from
-// outArray. This is used by partial update testcase to ensure partial update
-// data won't contain prefixes we already have.
-static void
-RemoveIntersection(const _PrefixArray& inArray, _PrefixArray& outArray)
-{
- for (uint32_t i = 0; i < inArray.Length(); i++) {
- int32_t idx = outArray.BinaryIndexOf(inArray[i]);
- if (idx >= 0) {
- outArray.RemoveElementAt(idx);
- }
- }
-}
-
-// This fucntion removes elements from outArray by index specified in
-// removal array.
-static void
-RemoveElements(const nsTArray<uint32_t>& removal, _PrefixArray& outArray)
-{
- for (int32_t i = removal.Length() - 1; i >= 0; i--) {
- outArray.RemoveElementAt(removal[i]);
- }
-}
-
-static void
-MergeAndSortArray(const _PrefixArray& array1,
- const _PrefixArray& array2,
- _PrefixArray& output)
-{
- output.Clear();
- output.AppendElements(array1);
- output.AppendElements(array2);
- output.Sort();
-}
-
-static void
-CalculateCheckSum(_PrefixArray& prefixArray, nsCString& checksum)
-{
- prefixArray.Sort();
-
- nsresult rv;
- nsCOMPtr<nsICryptoHash> cryptoHash =
- do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv);
-
- cryptoHash->Init(nsICryptoHash::SHA256);
- for (uint32_t i = 0; i < prefixArray.Length(); i++) {
- const _Prefix& prefix = prefixArray[i];
- cryptoHash->Update(reinterpret_cast<uint8_t*>(
- const_cast<char*>(prefix.get())), prefix.Length());
- }
- cryptoHash->Finish(false, checksum);
-}
-
-// N: Number of prefixes, MIN/MAX: minimum/maximum prefix size
-// This function will append generated prefixes to outArray.
-static void
-CreateRandomSortedPrefixArray(uint32_t N,
- uint32_t MIN,
- uint32_t MAX,
- _PrefixArray& outArray)
-{
- outArray.SetCapacity(outArray.Length() + N);
-
- const uint32_t range = (MAX - MIN + 1);
-
- for (uint32_t i = 0; i < N; i++) {
- uint32_t prefixSize = (rand() % range) + MIN;
- _Prefix prefix;
- prefix.SetLength(prefixSize);
-
- while (true) {
- char* dst = prefix.BeginWriting();
- for (uint32_t j = 0; j < prefixSize; j++) {
- dst[j] = rand() % 256;
- }
-
- if (!outArray.Contains(prefix)) {
- outArray.AppendElement(prefix);
- break;
- }
- }
- }
-
- outArray.Sort();
-}
-
-// N: Number of removal indices, MAX: maximum index
-static void
-CreateRandomRemovalIndices(uint32_t N,
- uint32_t MAX,
- nsTArray<uint32_t>& outArray)
-{
- for (uint32_t i = 0; i < N; i++) {
- uint32_t idx = rand() % MAX;
- if (!outArray.Contains(idx)) {
- outArray.InsertElementSorted(idx);
- }
- }
-}
-
-// Function to generate TableUpdateV4.
-static void
-GenerateUpdateData(bool fullUpdate,
- PrefixStringMap& add,
- nsTArray<uint32_t>* removal,
- nsCString* checksum,
- nsTArray<TableUpdate*>& tableUpdates)
-{
- TableUpdateV4* tableUpdate = new TableUpdateV4(GTEST_TABLE);
- tableUpdate->SetFullUpdate(fullUpdate);
-
- for (auto iter = add.ConstIter(); !iter.Done(); iter.Next()) {
- nsCString* pstring = iter.Data();
- std::string str(pstring->BeginReading(), pstring->Length());
-
- tableUpdate->NewPrefixes(iter.Key(), str);
- }
-
- if (removal) {
- tableUpdate->NewRemovalIndices(removal->Elements(), removal->Length());
- }
-
- if (checksum) {
- std::string stdChecksum;
- stdChecksum.assign(const_cast<char*>(checksum->BeginReading()), checksum->Length());
-
- tableUpdate->NewChecksum(stdChecksum);
- }
-
- tableUpdates.AppendElement(tableUpdate);
-}
-
-static void
-VerifyPrefixSet(PrefixStringMap& expected)
-{
- // Verify the prefix set is written to disk.
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-
- file->AppendNative(GTEST_SAFEBROWSING_DIR);
- file->AppendNative(GTEST_PREFIXFILE);
-
- RefPtr<VariableLengthPrefixSet> load = new VariableLengthPrefixSet;
- load->Init(GTEST_TABLE);
-
- PrefixStringMap prefixesInFile;
- load->LoadFromFile(file);
- load->GetPrefixes(prefixesInFile);
-
- for (auto iter = expected.ConstIter(); !iter.Done(); iter.Next()) {
- nsCString* expectedPrefix = iter.Data();
- nsCString* resultPrefix = prefixesInFile.Get(iter.Key());
-
- ASSERT_TRUE(*resultPrefix == *expectedPrefix);
- }
-}
-
-static void
-Clear()
-{
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-
- UniquePtr<Classifier> classifier(new Classifier());
- classifier->Open(*file);
- classifier->Reset();
-}
-
-static void
-testUpdateFail(nsTArray<TableUpdate*>& tableUpdates)
-{
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-
- UniquePtr<Classifier> classifier(new Classifier());
- classifier->Open(*file);
-
- RunTestInNewThread([&] () -> void {
- nsresult rv = classifier->ApplyUpdates(&tableUpdates);
- ASSERT_TRUE(NS_FAILED(rv));
- });
-}
-
-static void
-testUpdate(nsTArray<TableUpdate*>& tableUpdates,
- PrefixStringMap& expected)
-{
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
-
- UniquePtr<Classifier> classifier(new Classifier());
- classifier->Open(*file);
-
- RunTestInNewThread([&] () -> void {
- nsresult rv = classifier->ApplyUpdates(&tableUpdates);
- ASSERT_TRUE(rv == NS_OK);
-
- VerifyPrefixSet(expected);
- });
-}
-
-static void
-testFullUpdate(PrefixStringMap& add, nsCString* checksum)
-{
- nsTArray<TableUpdate*> tableUpdates;
-
- GenerateUpdateData(true, add, nullptr, checksum, tableUpdates);
-
- testUpdate(tableUpdates, add);
-}
-
-static void
-testPartialUpdate(PrefixStringMap& add,
- nsTArray<uint32_t>* removal,
- nsCString* checksum,
- PrefixStringMap& expected)
-{
- nsTArray<TableUpdate*> tableUpdates;
- GenerateUpdateData(false, add, removal, checksum, tableUpdates);
-
- testUpdate(tableUpdates, expected);
-}
-
-static void
-testOpenLookupCache()
-{
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file));
- file->AppendNative(GTEST_SAFEBROWSING_DIR);
-
- RunTestInNewThread([&] () -> void {
- LookupCacheV4 cache(nsCString(GTEST_TABLE), EmptyCString(), file);
- nsresult rv = cache.Init();
- ASSERT_EQ(rv, NS_OK);
-
- rv = cache.Open();
- ASSERT_EQ(rv, NS_OK);
- });
-}
-
-// Tests start from here.
-TEST(UrlClassifierTableUpdateV4, FixLenghtPSetFullUpdate)
-{
- srand(time(NULL));
-
- _PrefixArray array;
- PrefixStringMap map;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(5000, 4, 4, array);
- PrefixArrayToPrefixStringMap(array, map);
- CalculateCheckSum(array, checksum);
-
- testFullUpdate(map, &checksum);
-
- Clear();
-}
-
-TEST(UrlClassifierTableUpdateV4, VariableLenghtPSetFullUpdate)
-{
- _PrefixArray array;
- PrefixStringMap map;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(5000, 5, 32, array);
- PrefixArrayToPrefixStringMap(array, map);
- CalculateCheckSum(array, checksum);
-
- testFullUpdate(map, &checksum);
-
- Clear();
-}
-
-// This test contain both variable length prefix set and fixed-length prefix set
-TEST(UrlClassifierTableUpdateV4, MixedPSetFullUpdate)
-{
- _PrefixArray array;
- PrefixStringMap map;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(5000, 4, 4, array);
- CreateRandomSortedPrefixArray(1000, 5, 32, array);
- PrefixArrayToPrefixStringMap(array, map);
- CalculateCheckSum(array, checksum);
-
- testFullUpdate(map, &checksum);
-
- Clear();
-}
-
-TEST(UrlClassifierTableUpdateV4, PartialUpdateWithRemoval)
-{
- _PrefixArray fArray;
-
- // Apply a full update first.
- {
- PrefixStringMap fMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
- CreateRandomSortedPrefixArray(2000, 5, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
- }
-
- // Apply a partial update with removal.
- {
- _PrefixArray pArray, mergedArray;
- PrefixStringMap pMap, mergedMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(5000, 4, 4, pArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
- RemoveIntersection(fArray, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- // Remove 1/5 of elements of original prefix set.
- nsTArray<uint32_t> removal;
- CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
- RemoveElements(removal, fArray);
-
- // Calculate the expected prefix map.
- MergeAndSortArray(fArray, pArray, mergedArray);
- PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
- CalculateCheckSum(mergedArray, checksum);
-
- testPartialUpdate(pMap, &removal, &checksum, mergedMap);
- }
-
- Clear();
-}
-
-TEST(UrlClassifierTableUpdateV4, PartialUpdateWithoutRemoval)
-{
- _PrefixArray fArray;
-
- // Apply a full update first.
- {
- PrefixStringMap fMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
- CreateRandomSortedPrefixArray(2000, 5, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
- }
-
- // Apply a partial update without removal
- {
- _PrefixArray pArray, mergedArray;
- PrefixStringMap pMap, mergedMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(5000, 4, 4, pArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
- RemoveIntersection(fArray, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- // Calculate the expected prefix map.
- MergeAndSortArray(fArray, pArray, mergedArray);
- PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
- CalculateCheckSum(mergedArray, checksum);
-
- testPartialUpdate(pMap, nullptr, &checksum, mergedMap);
- }
-
- Clear();
-}
-
-// Expect failure because partial update contains prefix already
-// in old prefix set.
-TEST(UrlClassifierTableUpdateV4, PartialUpdatePrefixAlreadyExist)
-{
- _PrefixArray fArray;
-
- // Apply a full update fist.
- {
- PrefixStringMap fMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
- }
-
- // Apply a partial update which contains a prefix in previous full update.
- // This should cause an update error.
- {
- _PrefixArray pArray;
- PrefixStringMap pMap;
- nsTArray<TableUpdate*> tableUpdates;
-
- // Pick one prefix from full update prefix and add it to partial update.
- // This should result a failure when call ApplyUpdates.
- pArray.AppendElement(fArray[rand() % fArray.Length()]);
- CreateRandomSortedPrefixArray(200, 4, 32, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- GenerateUpdateData(false, pMap, nullptr, nullptr, tableUpdates);
- testUpdateFail(tableUpdates);
- }
-
- Clear();
-}
-
-// Test apply partial update directly without applying an full update first.
-TEST(UrlClassifierTableUpdateV4, OnlyPartialUpdate)
-{
- _PrefixArray pArray;
- PrefixStringMap pMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(5000, 4, 4, pArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
- CalculateCheckSum(pArray, checksum);
-
- testPartialUpdate(pMap, nullptr, &checksum, pMap);
-
- Clear();
-}
-
-// Test partial update without any ADD prefixes, only removalIndices.
-TEST(UrlClassifierTableUpdateV4, PartialUpdateOnlyRemoval)
-{
- _PrefixArray fArray;
-
- // Apply a full update first.
- {
- PrefixStringMap fMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(5000, 4, 4, fArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
- }
-
- // Apply a partial update without add prefix, only contain removal indices.
- {
- _PrefixArray pArray;
- PrefixStringMap pMap, mergedMap;
- nsCString checksum;
-
- // Remove 1/5 of elements of original prefix set.
- nsTArray<uint32_t> removal;
- CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
- RemoveElements(removal, fArray);
-
- PrefixArrayToPrefixStringMap(fArray, mergedMap);
- CalculateCheckSum(fArray, checksum);
-
- testPartialUpdate(pMap, &removal, &checksum, mergedMap);
- }
-
- Clear();
-}
-
-// Test one tableupdate array contains full update and multiple partial updates.
-TEST(UrlClassifierTableUpdateV4, MultipleTableUpdates)
-{
- _PrefixArray fArray, pArray, mergedArray;
- PrefixStringMap fMap, pMap, mergedMap;
- nsCString checksum;
-
- nsTArray<TableUpdate*> tableUpdates;
-
- // Generate first full udpate
- CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
- CreateRandomSortedPrefixArray(2000, 5, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- GenerateUpdateData(true, fMap, nullptr, &checksum, tableUpdates);
-
- // Generate second partial update
- CreateRandomSortedPrefixArray(3000, 4, 4, pArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
- RemoveIntersection(fArray, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- MergeAndSortArray(fArray, pArray, mergedArray);
- CalculateCheckSum(mergedArray, checksum);
-
- GenerateUpdateData(false, pMap, nullptr, &checksum, tableUpdates);
-
- // Generate thrid partial update
- fArray.AppendElements(pArray);
- fArray.Sort();
- pArray.Clear();
- CreateRandomSortedPrefixArray(3000, 4, 4, pArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
- RemoveIntersection(fArray, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- // Remove 1/5 of elements of original prefix set.
- nsTArray<uint32_t> removal;
- CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
- RemoveElements(removal, fArray);
-
- MergeAndSortArray(fArray, pArray, mergedArray);
- PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
- CalculateCheckSum(mergedArray, checksum);
-
- GenerateUpdateData(false, pMap, &removal, &checksum, tableUpdates);
-
- testUpdate(tableUpdates, mergedMap);
-
- Clear();
-}
-
-// Test apply full update first, and then apply multiple partial updates
-// in one tableupdate array.
-TEST(UrlClassifierTableUpdateV4, MultiplePartialUpdateTableUpdates)
-{
- _PrefixArray fArray;
-
- // Apply a full update first
- {
- PrefixStringMap fMap;
- nsCString checksum;
-
- // Generate first full udpate
- CreateRandomSortedPrefixArray(10000, 4, 4, fArray);
- CreateRandomSortedPrefixArray(3000, 5, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
- }
-
- // Apply multiple partial updates in one table update
- {
- _PrefixArray pArray, mergedArray;
- PrefixStringMap pMap, mergedMap;
- nsCString checksum;
- nsTArray<uint32_t> removal;
- nsTArray<TableUpdate*> tableUpdates;
-
- // Generate first partial update
- CreateRandomSortedPrefixArray(3000, 4, 4, pArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
- RemoveIntersection(fArray, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- // Remove 1/5 of elements of original prefix set.
- CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
- RemoveElements(removal, fArray);
-
- MergeAndSortArray(fArray, pArray, mergedArray);
- CalculateCheckSum(mergedArray, checksum);
-
- GenerateUpdateData(false, pMap, &removal, &checksum, tableUpdates);
-
- fArray.AppendElements(pArray);
- fArray.Sort();
- pArray.Clear();
- removal.Clear();
-
- // Generate second partial update.
- CreateRandomSortedPrefixArray(2000, 4, 4, pArray);
- CreateRandomSortedPrefixArray(1000, 5, 32, pArray);
- RemoveIntersection(fArray, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- // Remove 1/5 of elements of original prefix set.
- CreateRandomRemovalIndices(fArray.Length() / 5, fArray.Length(), removal);
- RemoveElements(removal, fArray);
-
- MergeAndSortArray(fArray, pArray, mergedArray);
- PrefixArrayToPrefixStringMap(mergedArray, mergedMap);
- CalculateCheckSum(mergedArray, checksum);
-
- GenerateUpdateData(false, pMap, &removal, &checksum, tableUpdates);
-
- testUpdate(tableUpdates, mergedMap);
- }
-
- Clear();
-}
-
-// Test removal indices are larger than the original prefix set.
-TEST(UrlClassifierTableUpdateV4, RemovalIndexTooLarge)
-{
- _PrefixArray fArray;
-
- // Apply a full update first
- {
- PrefixStringMap fMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
- }
-
- // Apply a partial update with removal indice array larger than
- // old prefix set(fArray). This should cause an error.
- {
- _PrefixArray pArray;
- PrefixStringMap pMap;
- nsTArray<uint32_t> removal;
- nsTArray<TableUpdate*> tableUpdates;
-
- CreateRandomSortedPrefixArray(200, 4, 32, pArray);
- RemoveIntersection(fArray, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- for (uint32_t i = 0; i < fArray.Length() + 1 ;i++) {
- removal.AppendElement(i);
- }
-
- GenerateUpdateData(false, pMap, &removal, nullptr, tableUpdates);
- testUpdateFail(tableUpdates);
- }
-
- Clear();
-}
-
-TEST(UrlClassifierTableUpdateV4, ChecksumMismatch)
-{
- // Apply a full update first
- {
- _PrefixArray fArray;
- PrefixStringMap fMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
- }
-
- // Apply a partial update with incorrect checksum
- {
- _PrefixArray pArray;
- PrefixStringMap pMap;
- nsCString checksum;
- nsTArray<TableUpdate*> tableUpdates;
-
- CreateRandomSortedPrefixArray(200, 4, 32, pArray);
- PrefixArrayToPrefixStringMap(pArray, pMap);
-
- // Checksum should be calculated with both old prefix set and add prefix set,
- // here we only calculate checksum with add prefix set to check if applyUpdate
- // will return failure.
- CalculateCheckSum(pArray, checksum);
-
- GenerateUpdateData(false, pMap, nullptr, &checksum, tableUpdates);
- testUpdateFail(tableUpdates);
- }
-
- Clear();
-}
-
-TEST(UrlClassifierTableUpdateV4, ApplyUpdateThenLoad)
-{
- // Apply update with checksum
- {
- _PrefixArray fArray;
- PrefixStringMap fMap;
- nsCString checksum;
-
- CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
- CalculateCheckSum(fArray, checksum);
-
- testFullUpdate(fMap, &checksum);
-
- // Open lookup cache will load prefix set and verify the checksum
- testOpenLookupCache();
- }
-
- Clear();
-
- // Apply update without checksum
- {
- _PrefixArray fArray;
- PrefixStringMap fMap;
-
- CreateRandomSortedPrefixArray(1000, 4, 32, fArray);
- PrefixArrayToPrefixStringMap(fArray, fMap);
-
- testFullUpdate(fMap, nullptr);
-
- testOpenLookupCache();
- }
-
- Clear();
-}
-
-// This test is used to avoid an eror from nsICryptoHash
-TEST(UrlClassifierTableUpdateV4, ApplyUpdateWithFixedChecksum)
-{
- _PrefixArray fArray = { _Prefix("enus"), _Prefix("apollo"), _Prefix("mars"),
- _Prefix("Hecatonchires cyclopes"),
- _Prefix("vesta"), _Prefix("neptunus"), _Prefix("jupiter"),
- _Prefix("diana"), _Prefix("minerva"), _Prefix("ceres"),
- _Prefix("Aidos,Adephagia,Adikia,Aletheia"),
- _Prefix("hecatonchires"), _Prefix("alcyoneus"), _Prefix("hades"),
- _Prefix("vulcanus"), _Prefix("juno"), _Prefix("mercury"),
- _Prefix("Stheno, Euryale and Medusa")
- };
- fArray.Sort();
-
- PrefixStringMap fMap;
- PrefixArrayToPrefixStringMap(fArray, fMap);
-
- nsCString checksum("\xae\x18\x94\xd7\xd0\x83\x5f\xc1"
- "\x58\x59\x5c\x2c\x72\xb9\x6e\x5e"
- "\xf4\xe8\x0a\x6b\xff\x5e\x6b\x81"
- "\x65\x34\x06\x16\x06\x59\xa0\x67");
-
- testFullUpdate(fMap, &checksum);
-
- // Open lookup cache will load prefix set and verify the checksum
- testOpenLookupCache();
-
- Clear();
-}
-
diff --git a/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierUtils.cpp b/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierUtils.cpp
deleted file mode 100644
index fa5ce4f56..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierUtils.cpp
+++ /dev/null
@@ -1,276 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <stdio.h>
-#include <ctype.h>
-
-#include <mozilla/RefPtr.h>
-#include "nsString.h"
-#include "nsEscape.h"
-#include "nsUrlClassifierUtils.h"
-#include "stdlib.h"
-#include "gtest/gtest.h"
-
-static char int_to_hex_digit(int32_t i) {
- NS_ASSERTION((i >= 0) && (i <= 15), "int too big in int_to_hex_digit");
- return static_cast<char>(((i < 10) ? (i + '0') : ((i - 10) + 'A')));
-}
-
-static void CheckEquals(nsCString& expected, nsCString& actual)
-{
- ASSERT_TRUE((expected).Equals((actual)));
-}
-
-void TestUnescapeHelper(const char* in, const char* expected)
-{
- nsCString out, strIn(in), strExp(expected);
-
- NS_UnescapeURL(strIn.get(), strIn.Length(), esc_AlwaysCopy, out);
- CheckEquals(strExp, out);
-}
-
-// Make sure Unescape from nsEncode.h's unescape does what the server does.
-TEST(UrlClassifierUtils, Unescape)
-{
- // test empty string
- TestUnescapeHelper("\0", "\0");
-
- // Test docoding of all characters.
- nsCString allCharsEncoded, allCharsEncodedLowercase, allCharsAsString;
- for (int32_t i = 1; i < 256; ++i) {
- allCharsEncoded.Append('%');
- allCharsEncoded.Append(int_to_hex_digit(i / 16));
- allCharsEncoded.Append((int_to_hex_digit(i % 16)));
-
- allCharsEncodedLowercase.Append('%');
- allCharsEncodedLowercase.Append(tolower(int_to_hex_digit(i / 16)));
- allCharsEncodedLowercase.Append(tolower(int_to_hex_digit(i % 16)));
-
- allCharsAsString.Append(static_cast<char>(i));
- }
-
- nsCString out;
- NS_UnescapeURL(allCharsEncoded.get(),
- allCharsEncoded.Length(),
- esc_AlwaysCopy,
- out);
-
- CheckEquals(allCharsAsString, out);
-
- out.Truncate();
- NS_UnescapeURL(allCharsEncodedLowercase.get(),
- allCharsEncodedLowercase.Length(),
- esc_AlwaysCopy,
- out);
- CheckEquals(allCharsAsString, out);
-
- // Test %-related edge cases
- TestUnescapeHelper("%", "%");
- TestUnescapeHelper("%xx", "%xx");
- TestUnescapeHelper("%%", "%%");
- TestUnescapeHelper("%%%", "%%%");
- TestUnescapeHelper("%%%%", "%%%%");
- TestUnescapeHelper("%1", "%1");
- TestUnescapeHelper("%1z", "%1z");
- TestUnescapeHelper("a%1z", "a%1z");
- TestUnescapeHelper("abc%d%e%fg%hij%klmno%", "abc%d%e%fg%hij%klmno%");
-
- // A few more tests
- TestUnescapeHelper("%25", "%");
- TestUnescapeHelper("%25%32%35", "%25");
-}
-
-void TestEncodeHelper(const char* in, const char* expected)
-{
- nsCString out, strIn(in), strExp(expected);
- RefPtr<nsUrlClassifierUtils> utils = new nsUrlClassifierUtils;
- utils->Init();
-
- utils->SpecialEncode(strIn, true, out);
- CheckEquals(strExp, out);
-}
-
-TEST(UrlClassifierUtils, Enc)
-{
- // Test empty string
- TestEncodeHelper("", "");
-
- // Test that all characters we shouldn't encode ([33-36],[38,126]) are not.
- nsCString noenc;
- for (int32_t i = 33; i < 127; i++) {
- if (i != 37) { // skip %
- noenc.Append(static_cast<char>(i));
- }
- }
- RefPtr<nsUrlClassifierUtils> utils = new nsUrlClassifierUtils;
- utils->Init();
- nsCString out;
- utils->SpecialEncode(noenc, false, out);
- CheckEquals(noenc, out);
-
- // Test that all the chars that we should encode [0,32],37,[127,255] are
- nsCString yesAsString, yesExpectedString;
- for (int32_t i = 1; i < 256; i++) {
- if (i < 33 || i == 37 || i > 126) {
- yesAsString.Append(static_cast<char>(i));
- yesExpectedString.Append('%');
- yesExpectedString.Append(int_to_hex_digit(i / 16));
- yesExpectedString.Append(int_to_hex_digit(i % 16));
- }
- }
-
- out.Truncate();
- utils->SpecialEncode(yesAsString, false, out);
- CheckEquals(yesExpectedString, out);
-
- TestEncodeHelper("blah//blah", "blah/blah");
-}
-
-void TestCanonicalizeHelper(const char* in, const char* expected)
-{
- nsCString out, strIn(in), strExp(expected);
- RefPtr<nsUrlClassifierUtils> utils = new nsUrlClassifierUtils;
- utils->Init();
-
- utils->CanonicalizePath(strIn, out);
- CheckEquals(strExp, out);
-}
-
-TEST(UrlClassifierUtils, Canonicalize)
-{
- // Test repeated %-decoding. Note: %25 --> %, %32 --> 2, %35 --> 5
- TestCanonicalizeHelper("%25", "%25");
- TestCanonicalizeHelper("%25%32%35", "%25");
- TestCanonicalizeHelper("asdf%25%32%35asd", "asdf%25asd");
- TestCanonicalizeHelper("%%%25%32%35asd%%", "%25%25%25asd%25%25");
- TestCanonicalizeHelper("%25%32%35%25%32%35%25%32%35", "%25%25%25");
- TestCanonicalizeHelper("%25", "%25");
- TestCanonicalizeHelper("%257Ea%2521b%2540c%2523d%2524e%25f%255E00%252611%252A22%252833%252944_55%252B",
- "~a!b@c#d$e%25f^00&11*22(33)44_55+");
-
- TestCanonicalizeHelper("", "");
- TestCanonicalizeHelper("%31%36%38%2e%31%38%38%2e%39%39%2e%32%36/%2E%73%65%63%75%72%65/%77%77%77%2E%65%62%61%79%2E%63%6F%6D/",
- "168.188.99.26/.secure/www.ebay.com/");
- TestCanonicalizeHelper("195.127.0.11/uploads/%20%20%20%20/.verify/.eBaysecure=updateuserdataxplimnbqmn-xplmvalidateinfoswqpcmlx=hgplmcx/",
- "195.127.0.11/uploads/%20%20%20%20/.verify/.eBaysecure=updateuserdataxplimnbqmn-xplmvalidateinfoswqpcmlx=hgplmcx/");
- // Added in bug 489455. %00 should no longer be changed to %01.
- TestCanonicalizeHelper("%00", "%00");
-}
-
-void TestParseIPAddressHelper(const char *in, const char *expected)
-{
- nsCString out, strIn(in), strExp(expected);
- RefPtr<nsUrlClassifierUtils> utils = new nsUrlClassifierUtils;
- utils->Init();
-
- utils->ParseIPAddress(strIn, out);
- CheckEquals(strExp, out);
-}
-
-TEST(UrlClassifierUtils, ParseIPAddress)
-{
- TestParseIPAddressHelper("123.123.0.0.1", "");
- TestParseIPAddressHelper("255.0.0.1", "255.0.0.1");
- TestParseIPAddressHelper("12.0x12.01234", "12.18.2.156");
- TestParseIPAddressHelper("276.2.3", "20.2.0.3");
- TestParseIPAddressHelper("012.034.01.055", "10.28.1.45");
- TestParseIPAddressHelper("0x12.0x43.0x44.0x01", "18.67.68.1");
- TestParseIPAddressHelper("167838211", "10.1.2.3");
- TestParseIPAddressHelper("3279880203", "195.127.0.11");
- TestParseIPAddressHelper("0x12434401", "18.67.68.1");
- TestParseIPAddressHelper("413960661", "24.172.137.213");
- TestParseIPAddressHelper("03053104725", "24.172.137.213");
- TestParseIPAddressHelper("030.0254.0x89d5", "24.172.137.213");
- TestParseIPAddressHelper("1.234.4.0377", "1.234.4.255");
- TestParseIPAddressHelper("1.2.3.00x0", "");
- TestParseIPAddressHelper("10.192.95.89 xy", "10.192.95.89");
- TestParseIPAddressHelper("10.192.95.89 xyz", "");
- TestParseIPAddressHelper("1.2.3.0x0", "1.2.3.0");
- TestParseIPAddressHelper("1.2.3.4", "1.2.3.4");
-}
-
-void TestCanonicalNumHelper(const char *in, uint32_t bytes,
- bool allowOctal, const char *expected)
-{
- nsCString out, strIn(in), strExp(expected);
- RefPtr<nsUrlClassifierUtils> utils = new nsUrlClassifierUtils;
- utils->Init();
-
- utils->CanonicalNum(strIn, bytes, allowOctal, out);
- CheckEquals(strExp, out);
-}
-
-TEST(UrlClassifierUtils, CanonicalNum)
-{
- TestCanonicalNumHelper("", 1, true, "");
- TestCanonicalNumHelper("10", 0, true, "");
- TestCanonicalNumHelper("45", 1, true, "45");
- TestCanonicalNumHelper("0x10", 1, true, "16");
- TestCanonicalNumHelper("367", 2, true, "1.111");
- TestCanonicalNumHelper("012345", 3, true, "0.20.229");
- TestCanonicalNumHelper("0173", 1, true, "123");
- TestCanonicalNumHelper("09", 1, false, "9");
- TestCanonicalNumHelper("0x120x34", 2, true, "");
- TestCanonicalNumHelper("0x12fc", 2, true, "18.252");
- TestCanonicalNumHelper("3279880203", 4, true, "195.127.0.11");
- TestCanonicalNumHelper("0x0000059", 1, true, "89");
- TestCanonicalNumHelper("0x00000059", 1, true, "89");
- TestCanonicalNumHelper("0x0000067", 1, true, "103");
-}
-
-void TestHostnameHelper(const char *in, const char *expected)
-{
- nsCString out, strIn(in), strExp(expected);
- RefPtr<nsUrlClassifierUtils> utils = new nsUrlClassifierUtils;
- utils->Init();
-
- utils->CanonicalizeHostname(strIn, out);
- CheckEquals(strExp, out);
-}
-
-TEST(UrlClassifierUtils, Hostname)
-{
- TestHostnameHelper("abcd123;[]", "abcd123;[]");
- TestHostnameHelper("abc.123", "abc.123");
- TestHostnameHelper("abc..123", "abc.123");
- TestHostnameHelper("trailing.", "trailing");
- TestHostnameHelper("i love trailing dots....", "i%20love%20trailing%20dots");
- TestHostnameHelper(".leading", "leading");
- TestHostnameHelper("..leading", "leading");
- TestHostnameHelper(".dots.", "dots");
- TestHostnameHelper(".both.", "both");
- TestHostnameHelper(".both..", "both");
- TestHostnameHelper("..both.", "both");
- TestHostnameHelper("..both..", "both");
- TestHostnameHelper("..a.b.c.d..", "a.b.c.d");
- TestHostnameHelper("..127.0.0.1..", "127.0.0.1");
- TestHostnameHelper("asdf!@#$a", "asdf!@#$a");
- TestHostnameHelper("AB CD 12354", "ab%20cd%2012354");
- TestHostnameHelper("\1\2\3\4\112\177", "%01%02%03%04j%7F");
- TestHostnameHelper("<>.AS/-+", "<>.as/-+");
- // Added in bug 489455. %00 should no longer be changed to %01.
- TestHostnameHelper("%00", "%00");
-}
-
-TEST(UrlClassifierUtils, LongHostname)
-{
- static const int kTestSize = 1024 * 150;
- char *str = static_cast<char*>(malloc(kTestSize + 1));
- memset(str, 'x', kTestSize);
- str[kTestSize] = '\0';
-
- RefPtr<nsUrlClassifierUtils> utils = new nsUrlClassifierUtils;
- utils->Init();
-
- nsAutoCString out;
- nsDependentCString in(str);
- PRIntervalTime clockStart = PR_IntervalNow();
- utils->CanonicalizeHostname(in, out);
- PRIntervalTime clockEnd = PR_IntervalNow();
-
- CheckEquals(in, out);
-
- printf("CanonicalizeHostname on long string (%dms)\n",
- PR_IntervalToMilliseconds(clockEnd - clockStart));
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp b/toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp
deleted file mode 100644
index 9e380a9d3..000000000
--- a/toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp
+++ /dev/null
@@ -1,559 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <mozilla/RefPtr.h>
-#include "nsString.h"
-#include "nsTArray.h"
-#include "nsClassHashtable.h"
-#include "VariableLengthPrefixSet.h"
-#include "nsAppDirectoryServiceDefs.h"
-#include "nsIFile.h"
-#include "gtest/gtest.h"
-
-using namespace mozilla::safebrowsing;
-
-typedef nsCString _Prefix;
-typedef nsTArray<_Prefix> _PrefixArray;
-
-// Create fullhash by appending random characters.
-static nsCString* CreateFullHash(const nsACString& in)
-{
- nsCString* out = new nsCString(in);
- out->SetLength(32);
- for (size_t i = in.Length(); i < 32; i++) {
- out->SetCharAt(char(rand() % 256), i);
- }
-
- return out;
-}
-
-// This function generate N prefixes with size between MIN and MAX.
-// The output array will not be cleared, random result will append to it
-static void RandomPrefixes(uint32_t N, uint32_t MIN, uint32_t MAX, _PrefixArray& array)
-{
- array.SetCapacity(array.Length() + N);
-
- uint32_t range = (MAX - MIN + 1);
-
- for (uint32_t i = 0; i < N; i++) {
- uint32_t prefixSize = (rand() % range) + MIN;
- _Prefix prefix;
- prefix.SetLength(prefixSize);
-
- bool added = false;
- while(!added) {
- char* dst = prefix.BeginWriting();
- for (uint32_t j = 0; j < prefixSize; j++) {
- dst[j] = rand() % 256;
- }
-
- if (!array.Contains(prefix)) {
- array.AppendElement(prefix);
- added = true;
- }
- }
- }
-}
-
-static void CheckContent(VariableLengthPrefixSet* pset,
- PrefixStringMap& expected)
-{
- PrefixStringMap vlPSetMap;
- pset->GetPrefixes(vlPSetMap);
-
- for (auto iter = vlPSetMap.Iter(); !iter.Done(); iter.Next()) {
- nsCString* expectedPrefix = expected.Get(iter.Key());
- nsCString* resultPrefix = iter.Data();
-
- ASSERT_TRUE(resultPrefix->Equals(*expectedPrefix));
- }
-}
-
-// This test loops through all the prefixes and converts each prefix to
-// fullhash by appending random characters, each converted fullhash
-// should at least match its original length in the prefixSet.
-static void DoExpectedLookup(VariableLengthPrefixSet* pset,
- _PrefixArray& array)
-{
- uint32_t matchLength = 0;
- for (uint32_t i = 0; i < array.Length(); i++) {
- const nsCString& prefix = array[i];
- UniquePtr<nsCString> fullhash(CreateFullHash(prefix));
-
- // Find match for prefix-generated full hash
- pset->Matches(*fullhash, &matchLength);
- MOZ_ASSERT(matchLength != 0);
-
- if (matchLength != prefix.Length()) {
- // Return match size is not the same as prefix size.
- // In this case it could be because the generated fullhash match other
- // prefixes, check if this prefix exist.
- bool found = false;
-
- for (uint32_t j = 0; j < array.Length(); j++) {
- if (array[j].Length() != matchLength) {
- continue;
- }
-
- if (0 == memcmp(fullhash->BeginReading(),
- array[j].BeginReading(),
- matchLength)) {
- found = true;
- break;
- }
- }
- ASSERT_TRUE(found);
- }
- }
-}
-
-static void DoRandomLookup(VariableLengthPrefixSet* pset,
- uint32_t N,
- _PrefixArray& array)
-{
- for (uint32_t i = 0; i < N; i++) {
- // Random 32-bytes test fullhash
- char buf[32];
- for (uint32_t j = 0; j < 32; j++) {
- buf[j] = (char)(rand() % 256);
- }
-
- // Get the expected result.
- nsTArray<uint32_t> expected;
- for (uint32_t j = 0; j < array.Length(); j++) {
- const nsACString& str = array[j];
- if (0 == memcmp(buf, str.BeginReading(), str.Length())) {
- expected.AppendElement(str.Length());
- }
- }
-
- uint32_t matchLength = 0;
- pset->Matches(nsDependentCSubstring(buf, 32), &matchLength);
-
- ASSERT_TRUE(expected.IsEmpty() ? !matchLength : expected.Contains(matchLength));
- }
-}
-
-static void SetupPrefixMap(const _PrefixArray& array,
- PrefixStringMap& map)
-{
- map.Clear();
-
- // Buckets are keyed by prefix length and contain an array of
- // all prefixes of that length.
- nsClassHashtable<nsUint32HashKey, _PrefixArray> table;
-
- for (uint32_t i = 0; i < array.Length(); i++) {
- _PrefixArray* prefixes = table.Get(array[i].Length());
- if (!prefixes) {
- prefixes = new _PrefixArray();
- table.Put(array[i].Length(), prefixes);
- }
-
- prefixes->AppendElement(array[i]);
- }
-
- // The resulting map entries will be a concatenation of all
- // prefix data for the prefixes of a given size.
- for (auto iter = table.Iter(); !iter.Done(); iter.Next()) {
- uint32_t size = iter.Key();
- uint32_t count = iter.Data()->Length();
-
- _Prefix* str = new _Prefix();
- str->SetLength(size * count);
-
- char* dst = str->BeginWriting();
-
- iter.Data()->Sort();
- for (uint32_t i = 0; i < count; i++) {
- memcpy(dst, iter.Data()->ElementAt(i).get(), size);
- dst += size;
- }
-
- map.Put(size, str);
- }
-}
-
-
-// Test setting prefix set with only 4-bytes prefixes
-TEST(VariableLengthPrefixSet, FixedLengthSet)
-{
- srand(time(nullptr));
-
- RefPtr<VariableLengthPrefixSet> pset = new VariableLengthPrefixSet;
- pset->Init(NS_LITERAL_CSTRING("test"));
-
- PrefixStringMap map;
- _PrefixArray array = { _Prefix("alph"), _Prefix("brav"), _Prefix("char"),
- _Prefix("delt"), _Prefix("echo"), _Prefix("foxt"),
- };
-
- SetupPrefixMap(array, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array);
-
- DoRandomLookup(pset, 1000, array);
-
- CheckContent(pset, map);
-
- // Run random test
- array.Clear();
- map.Clear();
-
- RandomPrefixes(1500, 4, 4, array);
-
- SetupPrefixMap(array, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array);
-
- DoRandomLookup(pset, 1000, array);
-
- CheckContent(pset, map);
-}
-
-// Test setting prefix set with only 5~32 bytes prefixes
-TEST(VariableLengthPrefixSet, VariableLengthSet)
-{
- RefPtr<VariableLengthPrefixSet> pset = new VariableLengthPrefixSet;
- pset->Init(NS_LITERAL_CSTRING("test"));
-
- PrefixStringMap map;
- _PrefixArray array = { _Prefix("bravo"), _Prefix("charlie"), _Prefix("delta"),
- _Prefix("EchoEchoEchoEchoEcho"), _Prefix("foxtrot"),
- _Prefix("GolfGolfGolfGolfGolfGolfGolfGolf"),
- _Prefix("hotel"), _Prefix("november"),
- _Prefix("oscar"), _Prefix("quebec"), _Prefix("romeo"),
- _Prefix("sierrasierrasierrasierrasierra"),
- _Prefix("Tango"), _Prefix("whiskey"), _Prefix("yankee"),
- _Prefix("ZuluZuluZuluZulu")
- };
-
- SetupPrefixMap(array, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array);
-
- DoRandomLookup(pset, 1000, array);
-
- CheckContent(pset, map);
-
- // Run random test
- array.Clear();
- map.Clear();
-
- RandomPrefixes(1500, 5, 32, array);
-
- SetupPrefixMap(array, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array);
-
- DoRandomLookup(pset, 1000, array);
-
- CheckContent(pset, map);
-
-}
-
-// Test setting prefix set with both 4-bytes prefixes and 5~32 bytes prefixes
-TEST(VariableLengthPrefixSet, MixedPrefixSet)
-{
- RefPtr<VariableLengthPrefixSet> pset = new VariableLengthPrefixSet;
- pset->Init(NS_LITERAL_CSTRING("test"));
-
- PrefixStringMap map;
- _PrefixArray array = { _Prefix("enus"), _Prefix("apollo"), _Prefix("mars"),
- _Prefix("Hecatonchires cyclopes"),
- _Prefix("vesta"), _Prefix("neptunus"), _Prefix("jupiter"),
- _Prefix("diana"), _Prefix("minerva"), _Prefix("ceres"),
- _Prefix("Aidos,Adephagia,Adikia,Aletheia"),
- _Prefix("hecatonchires"), _Prefix("alcyoneus"), _Prefix("hades"),
- _Prefix("vulcanus"), _Prefix("juno"), _Prefix("mercury"),
- _Prefix("Stheno, Euryale and Medusa")
- };
-
- SetupPrefixMap(array, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array);
-
- DoRandomLookup(pset, 1000, array);
-
- CheckContent(pset, map);
-
- // Run random test
- array.Clear();
- map.Clear();
-
- RandomPrefixes(1500, 4, 32, array);
-
- SetupPrefixMap(array, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array);
-
- DoRandomLookup(pset, 1000, array);
-
- CheckContent(pset, map);
-}
-
-// Test resetting prefix set
-TEST(VariableLengthPrefixSet, ResetPrefix)
-{
- RefPtr<VariableLengthPrefixSet> pset = new VariableLengthPrefixSet;
- pset->Init(NS_LITERAL_CSTRING("test"));
-
- // First prefix set
- _PrefixArray array1 = { _Prefix("Iceland"), _Prefix("Peru"), _Prefix("Mexico"),
- _Prefix("Australia"), _Prefix("Japan"), _Prefix("Egypt"),
- _Prefix("America"), _Prefix("Finland"), _Prefix("Germany"),
- _Prefix("Italy"), _Prefix("France"), _Prefix("Taiwan"),
- };
- {
- PrefixStringMap map;
-
- SetupPrefixMap(array1, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array1);
- }
-
- // Second
- _PrefixArray array2 = { _Prefix("Pikachu"), _Prefix("Bulbasaur"), _Prefix("Charmander"),
- _Prefix("Blastoise"), _Prefix("Pidgey"), _Prefix("Mewtwo"),
- _Prefix("Jigglypuff"), _Prefix("Persian"), _Prefix("Tentacool"),
- _Prefix("Onix"), _Prefix("Eevee"), _Prefix("Jynx"),
- };
- {
- PrefixStringMap map;
-
- SetupPrefixMap(array2, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array2);
- }
-
- // Should not match any of the first prefix set
- uint32_t matchLength = 0;
- for (uint32_t i = 0; i < array1.Length(); i++) {
- UniquePtr<nsACString> fullhash(CreateFullHash(array1[i]));
-
- pset->Matches(*fullhash, &matchLength);
- ASSERT_TRUE(matchLength == 0);
- }
-}
-
-// Test only set one 4-bytes prefix and one full-length prefix
-TEST(VariableLengthPrefixSet, TinyPrefixSet)
-{
- RefPtr<VariableLengthPrefixSet> pset = new VariableLengthPrefixSet;
- pset->Init(NS_LITERAL_CSTRING("test"));
-
- PrefixStringMap map;
- _PrefixArray array = { _Prefix("AAAA"),
- _Prefix("11112222333344445555666677778888"),
- };
-
- SetupPrefixMap(array, map);
- pset->SetPrefixes(map);
-
- DoExpectedLookup(pset, array);
-
- DoRandomLookup(pset, 1000, array);
-
- CheckContent(pset, map);
-}
-
-// Test empty prefix set and IsEmpty function
-TEST(VariableLengthPrefixSet, EmptyPrefixSet)
-{
- RefPtr<VariableLengthPrefixSet> pset = new VariableLengthPrefixSet;
- pset->Init(NS_LITERAL_CSTRING("test"));
-
- bool empty;
- pset->IsEmpty(&empty);
- ASSERT_TRUE(empty);
-
- PrefixStringMap map;
- _PrefixArray array1;
-
- // Lookup an empty array should never match
- DoRandomLookup(pset, 100, array1);
-
- // Insert an 4-bytes prefix, then IsEmpty should return false
- _PrefixArray array2 = { _Prefix("test") };
- SetupPrefixMap(array2, map);
- pset->SetPrefixes(map);
-
- pset->IsEmpty(&empty);
- ASSERT_TRUE(!empty);
-
- _PrefixArray array3 = { _Prefix("test variable length") };
-
- // Insert an 5~32 bytes prefix, then IsEmpty should return false
- SetupPrefixMap(array3, map);
- pset->SetPrefixes(map);
-
- pset->IsEmpty(&empty);
- ASSERT_TRUE(!empty);
-}
-
-// Test prefix size should only between 4~32 bytes
-TEST(VariableLengthPrefixSet, MinMaxPrefixSet)
-{
- RefPtr<VariableLengthPrefixSet> pset = new VariableLengthPrefixSet;
- pset->Init(NS_LITERAL_CSTRING("test"));
-
- PrefixStringMap map;
- {
- _PrefixArray array = { _Prefix("1234"),
- _Prefix("ABCDEFGHIJKKMNOP"),
- _Prefix("1aaa2bbb3ccc4ddd5eee6fff7ggg8hhh") };
-
- SetupPrefixMap(array, map);
- nsresult rv = pset->SetPrefixes(map);
- ASSERT_TRUE(rv == NS_OK);
- }
-
- // Prefix size less than 4-bytes should fail
- {
- _PrefixArray array = { _Prefix("123") };
-
- SetupPrefixMap(array, map);
- nsresult rv = pset->SetPrefixes(map);
- ASSERT_TRUE(NS_FAILED(rv));
- }
-
- // Prefix size greater than 32-bytes should fail
- {
- _PrefixArray array = { _Prefix("1aaa2bbb3ccc4ddd5eee6fff7ggg8hhh9") };
-
- SetupPrefixMap(array, map);
- nsresult rv = pset->SetPrefixes(map);
- ASSERT_TRUE(NS_FAILED(rv));
- }
-}
-
-// Test save then load prefix set with only 4-bytes prefixes
-TEST(VariableLengthPrefixSet, LoadSaveFixedLengthPrefixSet)
-{
- RefPtr<VariableLengthPrefixSet> save = new VariableLengthPrefixSet;
- save->Init(NS_LITERAL_CSTRING("test-save"));
-
- _PrefixArray array;
- RandomPrefixes(10000, 4, 4, array);
-
- PrefixStringMap map;
- SetupPrefixMap(array, map);
- save->SetPrefixes(map);
-
- DoExpectedLookup(save, array);
-
- DoRandomLookup(save, 1000, array);
-
- CheckContent(save, map);
-
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
- getter_AddRefs(file));
- file->Append(NS_LITERAL_STRING("test.vlpset"));
-
- save->StoreToFile(file);
-
- RefPtr<VariableLengthPrefixSet> load = new VariableLengthPrefixSet;
- load->Init(NS_LITERAL_CSTRING("test-load"));
-
- load->LoadFromFile(file);
-
- DoExpectedLookup(load, array);
-
- DoRandomLookup(load, 1000, array);
-
- CheckContent(load, map);
-
- file->Remove(false);
-}
-
-// Test save then load prefix set with only 5~32 bytes prefixes
-TEST(VariableLengthPrefixSet, LoadSaveVariableLengthPrefixSet)
-{
- RefPtr<VariableLengthPrefixSet> save = new VariableLengthPrefixSet;
- save->Init(NS_LITERAL_CSTRING("test-save"));
-
- _PrefixArray array;
- RandomPrefixes(10000, 5, 32, array);
-
- PrefixStringMap map;
- SetupPrefixMap(array, map);
- save->SetPrefixes(map);
-
- DoExpectedLookup(save, array);
-
- DoRandomLookup(save, 1000, array);
-
- CheckContent(save, map);
-
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
- getter_AddRefs(file));
- file->Append(NS_LITERAL_STRING("test.vlpset"));
-
- save->StoreToFile(file);
-
- RefPtr<VariableLengthPrefixSet> load = new VariableLengthPrefixSet;
- load->Init(NS_LITERAL_CSTRING("test-load"));
-
- load->LoadFromFile(file);
-
- DoExpectedLookup(load, array);
-
- DoRandomLookup(load, 1000, array);
-
- CheckContent(load, map);
-
- file->Remove(false);
-}
-
-// Test save then load prefix with both 4 bytes prefixes and 5~32 bytes prefixes
-TEST(VariableLengthPrefixSet, LoadSavePrefixSet)
-{
- RefPtr<VariableLengthPrefixSet> save = new VariableLengthPrefixSet;
- save->Init(NS_LITERAL_CSTRING("test-save"));
-
- // Try to simulate the real case that most prefixes are 4bytes
- _PrefixArray array;
- RandomPrefixes(20000, 4, 4, array);
- RandomPrefixes(1000, 5, 32, array);
-
- PrefixStringMap map;
- SetupPrefixMap(array, map);
- save->SetPrefixes(map);
-
- DoExpectedLookup(save, array);
-
- DoRandomLookup(save, 1000, array);
-
- CheckContent(save, map);
-
- nsCOMPtr<nsIFile> file;
- NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
- getter_AddRefs(file));
- file->Append(NS_LITERAL_STRING("test.vlpset"));
-
- save->StoreToFile(file);
-
- RefPtr<VariableLengthPrefixSet> load = new VariableLengthPrefixSet;
- load->Init(NS_LITERAL_CSTRING("test-load"));
-
- load->LoadFromFile(file);
-
- DoExpectedLookup(load, array);
-
- DoRandomLookup(load, 1000, array);
-
- CheckContent(load, map);
-
- file->Remove(false);
-}
diff --git a/toolkit/components/url-classifier/tests/gtest/moz.build b/toolkit/components/url-classifier/tests/gtest/moz.build
deleted file mode 100644
index e66af9024..000000000
--- a/toolkit/components/url-classifier/tests/gtest/moz.build
+++ /dev/null
@@ -1,27 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-LOCAL_INCLUDES += [
- '../..',
-]
-
-UNIFIED_SOURCES += [
- 'Common.cpp',
- 'TestChunkSet.cpp',
- 'TestFailUpdate.cpp',
- 'TestLookupCacheV4.cpp',
- 'TestPerProviderDirectory.cpp',
- 'TestProtocolParser.cpp',
- 'TestRiceDeltaDecoder.cpp',
- 'TestSafebrowsingHash.cpp',
- 'TestSafeBrowsingProtobuf.cpp',
- 'TestTable.cpp',
- 'TestUrlClassifierTableUpdateV4.cpp',
- 'TestUrlClassifierUtils.cpp',
- 'TestVariableLengthPrefixSet.cpp',
-]
-
-FINAL_LIBRARY = 'xul-gtest'
diff --git a/toolkit/components/url-classifier/tests/jar.mn b/toolkit/components/url-classifier/tests/jar.mn
deleted file mode 100644
index 2264c2896..000000000
--- a/toolkit/components/url-classifier/tests/jar.mn
+++ /dev/null
@@ -1,2 +0,0 @@
-toolkit.jar:
- content/global/url-classifier/unittests.xul (unittests.xul)
diff --git a/toolkit/components/url-classifier/tests/mochitest/.eslintrc.js b/toolkit/components/url-classifier/tests/mochitest/.eslintrc.js
deleted file mode 100644
index 58b3df4a7..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/.eslintrc.js
+++ /dev/null
@@ -1,8 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/mochitest.eslintrc.js",
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/url-classifier/tests/mochitest/allowlistAnnotatedFrame.html b/toolkit/components/url-classifier/tests/mochitest/allowlistAnnotatedFrame.html
deleted file mode 100644
index 9aae1b841..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/allowlistAnnotatedFrame.html
+++ /dev/null
@@ -1,144 +0,0 @@
-<html>
-<head>
-<title></title>
-
-<script type="text/javascript">
-
-// Modified by evil.js
-var scriptItem;
-
-var scriptItem1 = "untouched";
-var imageItem1 = "untouched";
-var frameItem1 = "untouched";
-var scriptItem2 = "untouched";
-var imageItem2 = "untouched";
-var frameItem2 = "untouched";
-var xhrItem = "untouched";
-var fetchItem = "untouched";
-var mediaItem1 = "untouched";
-
-function checkLoads() {
- window.parent.is(scriptItem1, "spoiled", "Should not block tracking js 1");
- window.parent.is(scriptItem2, "spoiled", "Should not block tracking js 2");
- window.parent.is(imageItem1, "spoiled", "Should not block tracking img 1");
- window.parent.is(imageItem2, "spoiled", "Should not block tracking img 2");
- window.parent.is(frameItem1, "spoiled", "Should not block tracking iframe 1");
- window.parent.is(frameItem2, "spoiled", "Should not block tracking iframe 2");
- window.parent.is(mediaItem1, "loaded", "Should not block tracking video");
- window.parent.is(xhrItem, "loaded", "Should not block tracking XHR");
- window.parent.is(fetchItem, "loaded", "Should not block fetches from tracking domains");
- window.parent.is(window.document.blockedTrackingNodeCount, 0,
- "No elements should be blocked");
-
- // End (parent) test.
- window.parent.clearPermissions();
- window.parent.SimpleTest.finish();
-}
-
-var onloadCalled = false;
-var xhrFinished = false;
-var fetchFinished = false;
-var videoLoaded = false;
-function loaded(type) {
- if (type === "onload") {
- onloadCalled = true;
- } else if (type === "xhr") {
- xhrFinished = true;
- } else if (type === "fetch") {
- fetchFinished = true;
- } else if (type === "video") {
- videoLoaded = true;
- }
-
- if (onloadCalled && xhrFinished && fetchFinished && videoLoaded) {
- checkLoads();
- }
-}
-</script>
-
-</head>
-
-<body onload="loaded('onload')">
-
-<!-- Try loading from a tracking script URI (1) -->
-<script id="badscript1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js" onload="scriptItem1 = 'spoiled';"></script>
-
-<!-- Try loading from a tracking image URI (1) -->
-<img id="badimage1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/raptor.jpg" onload="imageItem1 = 'spoiled';"/>
-
-<!-- Try loading from a tracking frame URI (1) -->
-<iframe id="badframe1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/track.html" onload="frameItem1 = 'spoiled';"></iframe>
-
-<!-- Try loading from a tracking video URI -->
-<video id="badmedia1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/vp9.webm"></video>
-
-<script>
-var v = document.getElementById("badmedia1");
-v.addEventListener("loadedmetadata", function() {
- mediaItem1 = "loaded";
- loaded("video");
-}, true);
-v.addEventListener("error", function() {
- mediaItem1 = "error";
- loaded("video");
-}, true);
-
-// Try loading from a tracking script URI (2) - The loader may follow a
-// different path depending on whether the resource is loaded from JS or HTML.
-var newScript = document.createElement("script");
-newScript.id = "badscript2";
-newScript.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js";
-newScript.addEventListener("load", function onload() {scriptItem2 = 'spoiled';});
-document.body.appendChild(newScript);
-
-/// Try loading from a tracking image URI (2)
-var newImage = document.createElement("img");
-newImage.id = "badimage2";
-newImage.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/raptor.jpg";
-newImage.addEventListener("load", function onload() {imageItem2 = 'spoiled'});
-document.body.appendChild(newImage);
-
-// Try loading from a tracking iframe URI (2)
-var newFrame = document.createElement("iframe");
-newFrame.id = "badframe2";
-newFrame.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/track.html"
-newFrame.addEventListener("load", function onload() {frameItem2 = 'spoiled'});
-document.body.appendChild(newFrame);
-
-// Try doing an XHR against a tracking domain (bug 1216793)
-function reqListener() {
- xhrItem = "loaded";
- loaded("xhr");
-}
-function transferFailed() {
- xhrItem = "failed";
- loaded("xhr");
-}
-function transferCanceled() {
- xhrItem = "canceled";
- loaded("xhr");
-}
-var oReq = new XMLHttpRequest();
-oReq.addEventListener("load", reqListener);
-oReq.addEventListener("error", transferFailed);
-oReq.addEventListener("abort", transferCanceled);
-oReq.open("GET", "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js");
-oReq.send();
-
-// Fetch from a tracking domain
-fetch("http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js").then(function(response) {
- if(response.ok) {
- fetchItem = "loaded";
- loaded("fetch");
- } else {
- fetchItem = "badresponse";
- loaded("fetch");
- }
- }).catch(function(error) {
- fetchItem = "error";
- loaded("fetch");
-});
-</script>
-</body>
-</html>
-
diff --git a/toolkit/components/url-classifier/tests/mochitest/bad.css b/toolkit/components/url-classifier/tests/mochitest/bad.css
deleted file mode 100644
index f57b36a77..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/bad.css
+++ /dev/null
@@ -1 +0,0 @@
-#styleBad { visibility: hidden; }
diff --git a/toolkit/components/url-classifier/tests/mochitest/bad.css^headers^ b/toolkit/components/url-classifier/tests/mochitest/bad.css^headers^
deleted file mode 100644
index 4030ea1d3..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/bad.css^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Cache-Control: no-store
diff --git a/toolkit/components/url-classifier/tests/mochitest/basic.vtt b/toolkit/components/url-classifier/tests/mochitest/basic.vtt
deleted file mode 100644
index 7781790d0..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/basic.vtt
+++ /dev/null
@@ -1,27 +0,0 @@
-WEBVTT
-Region: id=testOne lines=2 width=30%
-Region: id=testTwo lines=4 width=20%
-
-1
-00:00.500 --> 00:00.700 region:testOne
-This
-
-2
-00:01.200 --> 00:02.400 region:testTwo
-Is
-
-2.5
-00:02.000 --> 00:03.500 region:testOne
-(Over here?!)
-
-3
-00:02.710 --> 00:02.910
-A
-
-4
-00:03.217 --> 00:03.989
-Test
-
-5
-00:03.217 --> 00:03.989
-And more!
diff --git a/toolkit/components/url-classifier/tests/mochitest/basic.vtt^headers^ b/toolkit/components/url-classifier/tests/mochitest/basic.vtt^headers^
deleted file mode 100644
index 23de552c1..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/basic.vtt^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Access-Control-Allow-Origin: * \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/mochitest/bug_1281083.html b/toolkit/components/url-classifier/tests/mochitest/bug_1281083.html
deleted file mode 100644
index cd5770177..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/bug_1281083.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<html>
-<head>
-<title></title>
-
-<script type="text/javascript">
-
-var scriptItem = "untouched";
-
-function checkLoads() {
- // Make sure the javascript did not load.
- window.parent.is(scriptItem, "untouched", "Should not load bad javascript");
-
- // Call parent.loadTestFrame again to test classification metadata in HTTP
- // cache entries.
- if (window.parent.firstLoad) {
- window.parent.info("Reloading from cache...");
- window.parent.firstLoad = false;
- window.parent.loadTestFrame();
- return;
- }
-
- // End (parent) test.
- window.parent.SimpleTest.finish();
-}
-
-</script>
-
-<!-- Try loading from a malware javascript URI -->
-<script type="text/javascript" src="http://bug1281083.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js"></script>
-
-</head>
-
-<body onload="checkLoads()">
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/chrome.ini b/toolkit/components/url-classifier/tests/mochitest/chrome.ini
deleted file mode 100644
index 1652e7421..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/chrome.ini
+++ /dev/null
@@ -1,23 +0,0 @@
-[DEFAULT]
-skip-if = os == 'android'
-support-files =
- allowlistAnnotatedFrame.html
- classifiedAnnotatedFrame.html
- classifiedAnnotatedPBFrame.html
- bug_1281083.html
-
-[test_lookup_system_principal.html]
-[test_classified_annotations.html]
-tags = trackingprotection
-skip-if = os == 'linux' && asan # Bug 1202548
-[test_allowlisted_annotations.html]
-tags = trackingprotection
-[test_privatebrowsing_trackingprotection.html]
-tags = trackingprotection
-[test_trackingprotection_bug1157081.html]
-tags = trackingprotection
-[test_trackingprotection_whitelist.html]
-tags = trackingprotection
-[test_safebrowsing_bug1272239.html]
-[test_donottrack.html]
-[test_classifier_changetablepref.html]
diff --git a/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedFrame.html b/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedFrame.html
deleted file mode 100644
index 8aab13dd3..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedFrame.html
+++ /dev/null
@@ -1,213 +0,0 @@
-<html>
-<head>
-<title></title>
-
-<script type="text/javascript">
-"use strict";
-
-var scriptItem = "untouched";
-var scriptItem1 = "untouched";
-var scriptItem2 = "untouched";
-var imageItem1 = "untouched";
-var imageItem2 = "untouched";
-var frameItem1 = "untouched";
-var frameItem2 = "untouched";
-var xhrItem = "untouched";
-var fetchItem = "untouched";
-var mediaItem1 = "untouched";
-
-var badids = [
- "badscript1",
- "badscript2",
- "badimage1",
- "badimage2",
- "badframe1",
- "badframe2",
- "badmedia1",
- "badcss"
-];
-
-function checkLoads() {
- window.parent.is(
- scriptItem1, "untouched", "Should not load tracking javascript");
- window.parent.is(
- scriptItem2, "untouched", "Should not load tracking javascript (2)");
-
- window.parent.is(
- imageItem1, "untouched", "Should not load tracking images");
- window.parent.is(
- imageItem2, "untouched", "Should not load tracking images (2)");
-
- window.parent.is(
- frameItem1, "untouched", "Should not load tracking iframes");
- window.parent.is(
- frameItem2, "untouched", "Should not load tracking iframes (2)");
- window.parent.is(
- mediaItem1, "error", "Should not load tracking videos");
- window.parent.is(
- xhrItem, "failed", "Should not load tracking XHRs");
- window.parent.is(
- fetchItem, "error", "Should not fetch from tracking URLs");
-
- var elt = document.getElementById("styleCheck");
- var style = document.defaultView.getComputedStyle(elt, "");
- window.parent.isnot(
- style.visibility, "hidden", "Should not load tracking css");
-
- window.parent.is(window.document.blockedTrackingNodeCount, badids.length,
- "Should identify all tracking elements");
-
- var blockedTrackingNodes = window.document.blockedTrackingNodes;
-
- // Make sure that every node in blockedTrackingNodes exists in the tree
- // (that may not always be the case but do not expect any nodes to disappear
- // from the tree here)
- var allNodeMatch = true;
- for (var i = 0; i < blockedTrackingNodes.length; i++) {
- var nodeMatch = false;
- for (var j = 0; j < badids.length && !nodeMatch; j++) {
- nodeMatch = nodeMatch ||
- (blockedTrackingNodes[i] == document.getElementById(badids[j]));
- }
-
- allNodeMatch = allNodeMatch && nodeMatch;
- }
- window.parent.ok(allNodeMatch,
- "All annotated nodes are expected in the tree");
-
- // Make sure that every node with a badid (see badids) is found in the
- // blockedTrackingNodes. This tells us if we are neglecting to annotate
- // some nodes
- allNodeMatch = true;
- for (var j = 0; j < badids.length; j++) {
- var nodeMatch = false;
- for (var i = 0; i < blockedTrackingNodes.length && !nodeMatch; i++) {
- nodeMatch = nodeMatch ||
- (blockedTrackingNodes[i] == document.getElementById(badids[j]));
- }
-
- if (!nodeMatch) {
- console.log(badids[j] + " was not found in blockedTrackingNodes");
- }
- allNodeMatch = allNodeMatch && nodeMatch;
- }
- window.parent.ok(allNodeMatch,
- "All tracking nodes are expected to be annotated as such");
-
- // Unset prefs, etc.
- window.parent.cleanup();
- // End (parent) test.
- window.parent.SimpleTest.finish();
-}
-
-var onloadCalled = false;
-var xhrFinished = false;
-var fetchFinished = false;
-var videoLoaded = false;
-function loaded(type) {
- if (type === "onload") {
- onloadCalled = true;
- } else if (type === "xhr") {
- xhrFinished = true;
- } else if (type === "fetch") {
- fetchFinished = true;
- } else if (type === "video") {
- videoLoaded = true;
- }
- if (onloadCalled && xhrFinished && fetchFinished && videoLoaded) {
- checkLoads();
- }
-}
-</script>
-
-<!-- Try loading from a tracking CSS URI -->
-<link id="badcss" rel="stylesheet" type="text/css" href="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.css"></link>
-
-</head>
-
-<body onload="loaded('onload')">
-
-<!-- Try loading from a tracking script URI (1): evil.js onload will have updated the scriptItem variable -->
-<script id="badscript1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js" onload="scriptItem1 = scriptItem;"></script>
-
-<!-- Try loading from a tracking image URI (1) -->
-<img id="badimage1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/raptor.jpg?reload=true" onload="imageItem1 = 'spoiled';"/>
-
-<!-- Try loading from a tracking frame URI (1) -->
-<iframe id="badframe1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/track.html" onload="frameItem1 = 'spoiled';"></iframe>
-
-<!-- Try loading from a tracking video URI -->
-<video id="badmedia1" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/vp9.webm?reload=true"></video>
-
-<script>
-var v = document.getElementById("badmedia1");
-v.addEventListener("loadedmetadata", function() {
- mediaItem1 = "loaded";
- loaded("video");
-}, true);
-v.addEventListener("error", function() {
- mediaItem1 = "error";
- loaded("video");
-}, true);
-
-// Try loading from a tracking script URI (2) - The loader may follow a different path depending on whether the resource is loaded from JS or HTML.
-var newScript = document.createElement("script");
-newScript.id = "badscript2";
-newScript.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js";
-newScript.addEventListener("load", function() {scriptItem2 = scriptItem;});
-document.body.appendChild(newScript);
-
-/// Try loading from a tracking image URI (2)
-var newImage = document.createElement("img");
-newImage.id = "badimage2";
-newImage.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/raptor.jpg?reload=true";
-newImage.addEventListener("load", function() {imageItem2 = 'spoiled'});
-document.body.appendChild(newImage);
-
-// Try loading from a tracking iframe URI (2)
-var newFrame = document.createElement("iframe");
-newFrame.id = "badframe2";
-newFrame.src = "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/track.html"
-newFrame.addEventListener("load", function() {frameItem2 = 'spoiled'});
-document.body.appendChild(newFrame);
-
-// Try doing an XHR against a tracking domain (bug 1216793)
-function reqListener() {
- xhrItem = "loaded";
- loaded("xhr");
-}
-function transferFailed() {
- xhrItem = "failed";
- loaded("xhr");
-}
-function transferCanceled() {
- xhrItem = "canceled";
- loaded("xhr");
-}
-var oReq = new XMLHttpRequest();
-oReq.addEventListener("load", reqListener);
-oReq.addEventListener("error", transferFailed);
-oReq.addEventListener("abort", transferCanceled);
-oReq.open("GET", "http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js");
-oReq.send();
-
-// Fetch from a tracking domain
-fetch("http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js").then(function(response) {
- if(response.ok) {
- fetchItem = "loaded";
- loaded("fetch");
- } else {
- fetchItem = "badresponse";
- loaded("fetch");
- }
- }).catch(function(error) {
- fetchItem = "error";
- loaded("fetch");
-});
-</script>
-
-The following should not be hidden:
-<div id="styleCheck">STYLE TEST</div>
-
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedPBFrame.html b/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedPBFrame.html
deleted file mode 100644
index f11ec1de3..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedPBFrame.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!DOCTYPE HTML>
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-<html>
-<head>
-<title></title>
-
-<link id="badcss" rel="stylesheet" type="text/css" href="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.css"></link>
-
-</head>
-<body>
-
-<script id="badscript" data-touched="not sure" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js" onload="this.dataset.touched = 'yes';" onerror="this.dataset.touched = 'no';"></script>
-
-<script id="goodscript" data-touched="not sure" src="http://itisatracker.org/tests/toolkit/components/url-classifier/tests/mochitest/good.js" onload="this.dataset.touched = 'yes';" onerror="this.dataset.touched = 'no';"></script>
-
-<!-- The image cache can cache JS handlers, so make sure we use a different URL for raptor.jpg each time -->
-<img id="badimage" data-touched="not sure" src="http://tracking.example.com/tests/toolkit/components/url-classifier/tests/mochitest/raptor.jpg?pbmode=test" onload="this.dataset.touched = 'yes';" onerror="this.dataset.touched = 'no';"/>
-
-The following should not be hidden:
-<div id="styleCheck">STYLE TEST</div>
-
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/classifierCommon.js b/toolkit/components/url-classifier/tests/mochitest/classifierCommon.js
deleted file mode 100644
index 49bda38db..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/classifierCommon.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const { classes: Cc, interfaces: Ci, results: Cr } = Components;
-
-var dbService = Cc["@mozilla.org/url-classifier/dbservice;1"]
- .getService(Ci.nsIUrlClassifierDBService);
-
-var timer;
-function setTimeout(callback, delay) {
- timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.initWithCallback({ notify: callback },
- delay,
- Ci.nsITimer.TYPE_ONE_SHOT);
-}
-
-function doUpdate(update) {
- let listener = {
- QueryInterface: function(iid)
- {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIUrlClassifierUpdateObserver))
- return this;
-
- throw Cr.NS_ERROR_NO_INTERFACE;
- },
- updateUrlRequested: function(url) { },
- streamFinished: function(status) { },
- updateError: function(errorCode) {
- sendAsyncMessage("updateError", errorCode);
- },
- updateSuccess: function(requestedTimeout) {
- sendAsyncMessage("updateSuccess");
- }
- };
-
- let dbService = Cc["@mozilla.org/url-classifier/dbservice;1"]
- .getService(Ci.nsIUrlClassifierDBService);
-
- try {
- dbService.beginUpdate(listener, "test-malware-simple,test-unwanted-simple", "");
- dbService.beginStream("", "");
- dbService.updateStream(update);
- dbService.finishStream();
- dbService.finishUpdate();
- } catch(e) {
- // beginUpdate may fail if there's an existing update in progress
- // retry until success or testcase timeout.
- setTimeout(() => { doUpdate(update); }, 1000);
- }
-}
-
-function doReload() {
- dbService.reloadDatabase();
-
- sendAsyncMessage("reloadSuccess");
-}
-
-// SafeBrowsing.jsm is initialized after mozEntries are added. Add observer
-// to receive "finished" event. For the case when this function is called
-// after the event had already been notified, we lookup entries to see if
-// they are already added to database.
-function waitForInit() {
- let observerService = Cc["@mozilla.org/observer-service;1"]
- .getService(Ci.nsIObserverService);
-
- observerService.addObserver(function() {
- sendAsyncMessage("safeBrowsingInited");
- }, "mozentries-update-finished", false);
-
- // This url must sync with the table, url in SafeBrowsing.jsm addMozEntries
- const table = "test-phish-simple";
- const url = "http://itisatrap.org/firefox/its-a-trap.html";
-
- let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(Ci.nsIScriptSecurityManager);
- let iosvc = Cc["@mozilla.org/network/io-service;1"]
- .getService(Ci.nsIIOService);
-
- let principal = secMan.createCodebasePrincipal(
- iosvc.newURI(url, null, null), {});
-
- let listener = {
- QueryInterface: function(iid)
- {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIUrlClassifierUpdateObserver))
- return this;
- throw Cr.NS_ERROR_NO_INTERFACE;
- },
-
- handleEvent: function(value)
- {
- if (value === table) {
- sendAsyncMessage("safeBrowsingInited");
- }
- },
- };
- dbService.lookup(principal, table, listener);
-}
-
-addMessageListener("doUpdate", ({ testUpdate }) => {
- doUpdate(testUpdate);
-});
-
-addMessageListener("doReload", () => {
- doReload();
-});
-
-addMessageListener("waitForInit", () => {
- waitForInit();
-});
diff --git a/toolkit/components/url-classifier/tests/mochitest/classifierFrame.html b/toolkit/components/url-classifier/tests/mochitest/classifierFrame.html
deleted file mode 100644
index c7923f448..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/classifierFrame.html
+++ /dev/null
@@ -1,57 +0,0 @@
-<html>
-<head>
-<title></title>
-
-<script type="text/javascript">
-
-var scriptItem = "untouched";
-
-function checkLoads() {
- // Make sure the javascript did not load.
- window.parent.is(scriptItem, "untouched", "Should not load bad javascript");
-
- // Make sure the css did not load.
- var elt = document.getElementById("styleCheck");
- var style = document.defaultView.getComputedStyle(elt, "");
- window.parent.isnot(style.visibility, "hidden", "Should not load bad css");
-
- elt = document.getElementById("styleBad");
- style = document.defaultView.getComputedStyle(elt, "");
- window.parent.isnot(style.visibility, "hidden", "Should not load bad css");
-
- elt = document.getElementById("styleImport");
- style = document.defaultView.getComputedStyle(elt, "");
- window.parent.isnot(style.visibility, "visible", "Should import clean css");
-
- // Call parent.loadTestFrame again to test classification metadata in HTTP
- // cache entries.
- if (window.parent.firstLoad) {
- window.parent.info("Reloading from cache...");
- window.parent.firstLoad = false;
- window.parent.loadTestFrame();
- return;
- }
-
- // End (parent) test.
- window.parent.SimpleTest.finish();
-}
-
-</script>
-
-<!-- Try loading from a malware javascript URI -->
-<script type="text/javascript" src="http://malware.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js"></script>
-
-<!-- Try loading from an uwanted software css URI -->
-<link rel="stylesheet" type="text/css" href="http://unwanted.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.css"></link>
-
-<!-- Try loading a marked-as-malware css through an @import from a clean URI -->
-<link rel="stylesheet" type="text/css" href="import.css"></link>
-</head>
-
-<body onload="checkLoads()">
-The following should not be hidden:
-<div id="styleCheck">STYLE TEST</div>
-<div id="styleBad">STYLE BAD</div>
-<div id="styleImport">STYLE IMPORT</div>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/classifierHelper.js b/toolkit/components/url-classifier/tests/mochitest/classifierHelper.js
deleted file mode 100644
index 973f0c2c4..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/classifierHelper.js
+++ /dev/null
@@ -1,201 +0,0 @@
-if (typeof(classifierHelper) == "undefined") {
- var classifierHelper = {};
-}
-
-const CLASSIFIER_COMMON_URL = SimpleTest.getTestFileURL("classifierCommon.js");
-var gScript = SpecialPowers.loadChromeScript(CLASSIFIER_COMMON_URL);
-
-const ADD_CHUNKNUM = 524;
-const SUB_CHUNKNUM = 523;
-const HASHLEN = 32;
-
-const PREFS = {
- PROVIDER_LISTS : "browser.safebrowsing.provider.mozilla.lists",
- DISALLOW_COMPLETIONS : "urlclassifier.disallow_completions",
- PROVIDER_GETHASHURL : "browser.safebrowsing.provider.mozilla.gethashURL"
-};
-
-// addUrlToDB & removeUrlFromDB are asynchronous, queue the task to ensure
-// the callback follow correct order.
-classifierHelper._updates = [];
-
-// Keep urls added to database, those urls should be automatically
-// removed after test complete.
-classifierHelper._updatesToCleanup = [];
-
-classifierHelper._initsCB = [];
-
-// This function return a Promise, promise is resolved when SafeBrowsing.jsm
-// is initialized.
-classifierHelper.waitForInit = function() {
- return new Promise(function(resolve, reject) {
- classifierHelper._initsCB.push(resolve);
- gScript.sendAsyncMessage("waitForInit");
- });
-}
-
-// This function is used to allow completion for specific "list",
-// some lists like "test-malware-simple" is default disabled to ask for complete.
-// "list" is the db we would like to allow it
-// "url" is the completion server
-classifierHelper.allowCompletion = function(lists, url) {
- for (var list of lists) {
- // Add test db to provider
- var pref = SpecialPowers.getCharPref(PREFS.PROVIDER_LISTS);
- pref += "," + list;
- SpecialPowers.setCharPref(PREFS.PROVIDER_LISTS, pref);
-
- // Rename test db so we will not disallow it from completions
- pref = SpecialPowers.getCharPref(PREFS.DISALLOW_COMPLETIONS);
- pref = pref.replace(list, list + "-backup");
- SpecialPowers.setCharPref(PREFS.DISALLOW_COMPLETIONS, pref);
- }
-
- // Set get hash url
- SpecialPowers.setCharPref(PREFS.PROVIDER_GETHASHURL, url);
-}
-
-// Pass { url: ..., db: ... } to add url to database,
-// onsuccess/onerror will be called when update complete.
-classifierHelper.addUrlToDB = function(updateData) {
- return new Promise(function(resolve, reject) {
- var testUpdate = "";
- for (var update of updateData) {
- var LISTNAME = update.db;
- var CHUNKDATA = update.url;
- var CHUNKLEN = CHUNKDATA.length;
- var HASHLEN = update.len ? update.len : 32;
-
- classifierHelper._updatesToCleanup.push(update);
- testUpdate +=
- "n:1000\n" +
- "i:" + LISTNAME + "\n" +
- "ad:1\n" +
- "a:" + ADD_CHUNKNUM + ":" + HASHLEN + ":" + CHUNKLEN + "\n" +
- CHUNKDATA;
- }
-
- classifierHelper._update(testUpdate, resolve, reject);
- });
-}
-
-// Pass { url: ..., db: ... } to remove url from database,
-// onsuccess/onerror will be called when update complete.
-classifierHelper.removeUrlFromDB = function(updateData) {
- return new Promise(function(resolve, reject) {
- var testUpdate = "";
- for (var update of updateData) {
- var LISTNAME = update.db;
- var CHUNKDATA = ADD_CHUNKNUM + ":" + update.url;
- var CHUNKLEN = CHUNKDATA.length;
- var HASHLEN = update.len ? update.len : 32;
-
- testUpdate +=
- "n:1000\n" +
- "i:" + LISTNAME + "\n" +
- "s:" + SUB_CHUNKNUM + ":" + HASHLEN + ":" + CHUNKLEN + "\n" +
- CHUNKDATA;
- }
-
- classifierHelper._updatesToCleanup =
- classifierHelper._updatesToCleanup.filter((v) => {
- return updateData.indexOf(v) == -1;
- });
-
- classifierHelper._update(testUpdate, resolve, reject);
- });
-};
-
-// This API is used to expire all add/sub chunks we have updated
-// by using addUrlToDB and removeUrlFromDB.
-classifierHelper.resetDB = function() {
- return new Promise(function(resolve, reject) {
- var testUpdate = "";
- for (var update of classifierHelper._updatesToCleanup) {
- if (testUpdate.includes(update.db))
- continue;
-
- testUpdate +=
- "n:1000\n" +
- "i:" + update.db + "\n" +
- "ad:" + ADD_CHUNKNUM + "\n" +
- "sd:" + SUB_CHUNKNUM + "\n"
- }
-
- classifierHelper._update(testUpdate, resolve, reject);
- });
-};
-
-classifierHelper.reloadDatabase = function() {
- return new Promise(function(resolve, reject) {
- gScript.addMessageListener("reloadSuccess", function handler() {
- gScript.removeMessageListener('reloadSuccess', handler);
- resolve();
- });
-
- gScript.sendAsyncMessage("doReload");
- });
-}
-
-classifierHelper._update = function(testUpdate, onsuccess, onerror) {
- // Queue the task if there is still an on-going update
- classifierHelper._updates.push({"data": testUpdate,
- "onsuccess": onsuccess,
- "onerror": onerror});
- if (classifierHelper._updates.length != 1) {
- return;
- }
-
- gScript.sendAsyncMessage("doUpdate", { testUpdate });
-};
-
-classifierHelper._updateSuccess = function() {
- var update = classifierHelper._updates.shift();
- update.onsuccess();
-
- if (classifierHelper._updates.length) {
- var testUpdate = classifierHelper._updates[0].data;
- gScript.sendAsyncMessage("doUpdate", { testUpdate });
- }
-};
-
-classifierHelper._updateError = function(errorCode) {
- var update = classifierHelper._updates.shift();
- update.onerror(errorCode);
-
- if (classifierHelper._updates.length) {
- var testUpdate = classifierHelper._updates[0].data;
- gScript.sendAsyncMessage("doUpdate", { testUpdate });
- }
-};
-
-classifierHelper._inited = function() {
- classifierHelper._initsCB.forEach(function (cb) {
- cb();
- });
- classifierHelper._initsCB = [];
-};
-
-classifierHelper._setup = function() {
- gScript.addMessageListener("updateSuccess", classifierHelper._updateSuccess);
- gScript.addMessageListener("updateError", classifierHelper._updateError);
- gScript.addMessageListener("safeBrowsingInited", classifierHelper._inited);
-
- // cleanup will be called at end of each testcase to remove all the urls added to database.
- SimpleTest.registerCleanupFunction(classifierHelper._cleanup);
-};
-
-classifierHelper._cleanup = function() {
- // clean all the preferences may touch by helper
- for (var pref in PREFS) {
- SpecialPowers.clearUserPref(pref);
- }
-
- if (!classifierHelper._updatesToCleanup) {
- return Promise.resolve();
- }
-
- return classifierHelper.resetDB();
-};
-
-classifierHelper._setup();
diff --git a/toolkit/components/url-classifier/tests/mochitest/cleanWorker.js b/toolkit/components/url-classifier/tests/mochitest/cleanWorker.js
deleted file mode 100644
index 685648373..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/cleanWorker.js
+++ /dev/null
@@ -1,10 +0,0 @@
-onmessage = function() {
- try {
- importScripts("evilWorker.js");
- } catch(ex) {
- postMessage("success");
- return;
- }
-
- postMessage("failure");
-};
diff --git a/toolkit/components/url-classifier/tests/mochitest/dnt.html b/toolkit/components/url-classifier/tests/mochitest/dnt.html
deleted file mode 100644
index effc3a4f8..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/dnt.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<html>
-<head>
-<title></title>
-
-<script type="text/javascript">
-
-function makeXHR(url, callback) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.onload = function() {
- callback(xhr.response);
- };
- xhr.send();
-}
-
-function loaded(type) {
- window.parent.postMessage("navigator.doNotTrack=" + navigator.doNotTrack, "*");
-
- makeXHR("dnt.sjs", (res) => {
- window.parent.postMessage("DNT=" + res, "*");
- window.parent.postMessage("finish", "*");
- });
-}
-
-</script>
-</head>
-
-<body onload="loaded('onload')">
-</body>
-
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/dnt.sjs b/toolkit/components/url-classifier/tests/mochitest/dnt.sjs
deleted file mode 100644
index bbb836482..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/dnt.sjs
+++ /dev/null
@@ -1,9 +0,0 @@
-function handleRequest(request, response) {
- var dnt = "unspecified";
- if (request.hasHeader("DNT")) {
- dnt = "1";
- }
-
- response.setHeader("Content-Type", "text/plain", false);
- response.write(dnt);
-}
diff --git a/toolkit/components/url-classifier/tests/mochitest/evil.css b/toolkit/components/url-classifier/tests/mochitest/evil.css
deleted file mode 100644
index f6f08d7c5..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/evil.css
+++ /dev/null
@@ -1 +0,0 @@
-#styleCheck { visibility: hidden; } \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/mochitest/evil.css^headers^ b/toolkit/components/url-classifier/tests/mochitest/evil.css^headers^
deleted file mode 100644
index 4030ea1d3..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/evil.css^headers^
+++ /dev/null
@@ -1 +0,0 @@
-Cache-Control: no-store
diff --git a/toolkit/components/url-classifier/tests/mochitest/evil.js b/toolkit/components/url-classifier/tests/mochitest/evil.js
deleted file mode 100644
index 27f2e8c43..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/evil.js
+++ /dev/null
@@ -1 +0,0 @@
-scriptItem = "loaded malware javascript!";
diff --git a/toolkit/components/url-classifier/tests/mochitest/evil.js^headers^ b/toolkit/components/url-classifier/tests/mochitest/evil.js^headers^
deleted file mode 100644
index 3eced9614..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/evil.js^headers^
+++ /dev/null
@@ -1,2 +0,0 @@
-Access-Control-Allow-Origin: *
-Cache-Control: no-store
diff --git a/toolkit/components/url-classifier/tests/mochitest/evilWorker.js b/toolkit/components/url-classifier/tests/mochitest/evilWorker.js
deleted file mode 100644
index ac34977d7..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/evilWorker.js
+++ /dev/null
@@ -1,3 +0,0 @@
-onmessage = function() {
- postMessage("loaded bad file");
-}
diff --git a/toolkit/components/url-classifier/tests/mochitest/gethash.sjs b/toolkit/components/url-classifier/tests/mochitest/gethash.sjs
deleted file mode 100644
index 9dcc6e0d5..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/gethash.sjs
+++ /dev/null
@@ -1,130 +0,0 @@
-const CC = Components.Constructor;
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-function handleRequest(request, response)
-{
- var query = {};
- request.queryString.split('&').forEach(function (val) {
- var idx = val.indexOf('=');
- query[val.slice(0, idx)] = unescape(val.slice(idx + 1));
- });
-
- var responseBody;
-
- // Store fullhash in the server side.
- if ("list" in query && "fullhash" in query) {
- // In the server side we will store:
- // 1. All the full hashes for a given list
- // 2. All the lists we have right now
- // data is separate by '\n'
- let list = query["list"];
- let hashes = getState(list);
-
- let hash = base64ToString(query["fullhash"]);
- hashes += hash + "\n";
- setState(list, hashes);
-
- let lists = getState("lists");
- if (lists.indexOf(list) == -1) {
- lists += list + "\n";
- setState("lists", lists);
- }
-
- return;
- // gethash count return how many gethash request received.
- // This is used by client to know if a gethash request is triggered by gecko
- } else if ("gethashcount" == request.queryString) {
- var counter = getState("counter");
- responseBody = counter == "" ? "0" : counter;
- } else {
- var body = new BinaryInputStream(request.bodyInputStream);
- var avail;
- var bytes = [];
-
- while ((avail = body.available()) > 0) {
- Array.prototype.push.apply(bytes, body.readByteArray(avail));
- }
-
- var counter = getState("counter");
- counter = counter == "" ? "1" : (parseInt(counter) + 1).toString();
- setState("counter", counter);
-
- responseBody = parseV2Request(bytes);
- }
-
- response.setHeader("Content-Type", "text/plain", false);
- response.write(responseBody);
-
-}
-
-function parseV2Request(bytes) {
- var request = String.fromCharCode.apply(this, bytes);
- var [HEADER, PREFIXES] = request.split("\n");
- var [PREFIXSIZE, LENGTH] = HEADER.split(":").map(val => {
- return parseInt(val);
- });
-
- var ret = "";
- for(var start = 0; start < LENGTH; start += PREFIXSIZE) {
- getState("lists").split("\n").forEach(function(list) {
- var completions = getState(list).split("\n");
-
- for (var completion of completions) {
- if (completion.indexOf(PREFIXES.substr(start, PREFIXSIZE)) == 0) {
- ret += list + ":" + "1" + ":" + "32" + "\n";
- ret += completion;
- }
- }
- });
- }
-
- return ret;
-}
-
-/* Convert Base64 data to a string */
-const toBinaryTable = [
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
-];
-const base64Pad = '=';
-
-function base64ToString(data) {
- var result = '';
- var leftbits = 0; // number of bits decoded, but yet to be appended
- var leftdata = 0; // bits decoded, but yet to be appended
-
- // Convert one by one.
- for (var i = 0; i < data.length; i++) {
- var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
- var padding = (data[i] == base64Pad);
- // Skip illegal characters and whitespace
- if (c == -1) continue;
-
- // Collect data into leftdata, update bitcount
- leftdata = (leftdata << 6) | c;
- leftbits += 6;
-
- // If we have 8 or more bits, append 8 bits to the result
- if (leftbits >= 8) {
- leftbits -= 8;
- // Append if not padding.
- if (!padding)
- result += String.fromCharCode((leftdata >> leftbits) & 0xff);
- leftdata &= (1 << leftbits) - 1;
- }
- }
-
- // If there are any bits left, the base64 string was corrupted
- if (leftbits)
- throw Components.Exception('Corrupted base64 string');
-
- return result;
-}
diff --git a/toolkit/components/url-classifier/tests/mochitest/gethashFrame.html b/toolkit/components/url-classifier/tests/mochitest/gethashFrame.html
deleted file mode 100644
index 560ddcde6..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/gethashFrame.html
+++ /dev/null
@@ -1,62 +0,0 @@
-<html>
-<head>
-<title></title>
-
-<script type="text/javascript">
-
-var scriptItem = "untouched";
-
-function checkLoads() {
-
- var title = document.getElementById("title");
- title.innerHTML = window.parent.shouldLoad ?
- "The following should be hidden:" :
- "The following should not be hidden:"
-
- if (window.parent.shouldLoad) {
- window.parent.is(scriptItem, "loaded malware javascript!", "Should load bad javascript");
- } else {
- window.parent.is(scriptItem, "untouched", "Should not load bad javascript");
- }
-
- var elt = document.getElementById("styleImport");
- var style = document.defaultView.getComputedStyle(elt, "");
- window.parent.isnot(style.visibility, "visible", "Should load clean css");
-
- // Make sure the css did not load.
- elt = document.getElementById("styleCheck");
- style = document.defaultView.getComputedStyle(elt, "");
- if (window.parent.shouldLoad) {
- window.parent.isnot(style.visibility, "visible", "Should load bad css");
- } else {
- window.parent.isnot(style.visibility, "hidden", "Should not load bad css");
- }
-
- elt = document.getElementById("styleBad");
- style = document.defaultView.getComputedStyle(elt, "");
- if (window.parent.shouldLoad) {
- window.parent.isnot(style.visibility, "visible", "Should import bad css");
- } else {
- window.parent.isnot(style.visibility, "hidden", "Should not import bad css");
- }
-}
-
-</script>
-
-<!-- Try loading from a malware javascript URI -->
-<script type="text/javascript" src="http://malware.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.js"></script>
-
-<!-- Try loading from an uwanted software css URI -->
-<link rel="stylesheet" type="text/css" href="http://unwanted.example.com/tests/toolkit/components/url-classifier/tests/mochitest/evil.css"></link>
-
-<!-- Try loading a marked-as-malware css through an @import from a clean URI -->
-<link rel="stylesheet" type="text/css" href="import.css"></link>
-</head>
-
-<body onload="checkLoads()">
-<div id="title"></div>
-<div id="styleCheck">STYLE EVIL</div>
-<div id="styleBad">STYLE BAD</div>
-<div id="styleImport">STYLE IMPORT</div>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/good.js b/toolkit/components/url-classifier/tests/mochitest/good.js
deleted file mode 100644
index 015b9fe52..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/good.js
+++ /dev/null
@@ -1 +0,0 @@
-scriptItem = "loaded whitelisted javascript!";
diff --git a/toolkit/components/url-classifier/tests/mochitest/import.css b/toolkit/components/url-classifier/tests/mochitest/import.css
deleted file mode 100644
index 9b86c8216..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/import.css
+++ /dev/null
@@ -1,3 +0,0 @@
-/* malware.example.com is in the malware database. */
-@import url("http://malware.example.com/tests/toolkit/components/url-classifier/tests/mochitest/bad.css");
-#styleImport { visibility: hidden; }
diff --git a/toolkit/components/url-classifier/tests/mochitest/mochitest.ini b/toolkit/components/url-classifier/tests/mochitest/mochitest.ini
deleted file mode 100644
index c5679e86b..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/mochitest.ini
+++ /dev/null
@@ -1,39 +0,0 @@
-[DEFAULT]
-support-files =
- classifiedAnnotatedPBFrame.html
- classifierCommon.js
- classifierFrame.html
- classifierHelper.js
- cleanWorker.js
- good.js
- evil.css
- evil.css^headers^
- evil.js
- evil.js^headers^
- evilWorker.js
- import.css
- raptor.jpg
- track.html
- unwantedWorker.js
- vp9.webm
- whitelistFrame.html
- workerFrame.html
- ping.sjs
- basic.vtt
- basic.vtt^headers^
- dnt.html
- dnt.sjs
- update.sjs
- bad.css
- bad.css^headers^
- gethash.sjs
- gethashFrame.html
- seek.webm
-
-[test_classifier.html]
-skip-if = (os == 'linux' && debug) #Bug 1199778
-[test_classifier_worker.html]
-[test_classify_ping.html]
-[test_classify_track.html]
-[test_gethash.html]
-[test_bug1254766.html]
diff --git a/toolkit/components/url-classifier/tests/mochitest/ping.sjs b/toolkit/components/url-classifier/tests/mochitest/ping.sjs
deleted file mode 100644
index 37a78956e..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/ping.sjs
+++ /dev/null
@@ -1,16 +0,0 @@
-function handleRequest(request, response)
-{
- var query = {};
- request.queryString.split('&').forEach(function (val) {
- var [name, value] = val.split('=');
- query[name] = unescape(value);
- });
-
- if (request.method == "POST") {
- setState(query["id"], "ping");
- } else {
- var value = getState(query["id"]);
- response.setHeader("Content-Type", "text/plain", false);
- response.write(value);
- }
-}
diff --git a/toolkit/components/url-classifier/tests/mochitest/raptor.jpg b/toolkit/components/url-classifier/tests/mochitest/raptor.jpg
deleted file mode 100644
index 243ba9e2d..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/raptor.jpg
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/url-classifier/tests/mochitest/seek.webm b/toolkit/components/url-classifier/tests/mochitest/seek.webm
deleted file mode 100644
index 72b029723..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/seek.webm
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_allowlisted_annotations.html b/toolkit/components/url-classifier/tests/mochitest/test_allowlisted_annotations.html
deleted file mode 100644
index ba9c86f95..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_allowlisted_annotations.html
+++ /dev/null
@@ -1,56 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test the URI Classifier</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-Components.utils.import("resource://testing-common/UrlClassifierTestUtils.jsm");
-
-// Add https://allowlisted.example.com to the permissions manager
-SpecialPowers.addPermission("trackingprotection",
- Ci.nsIPermissionManager.ALLOW_ACTION,
- { url: "https://allowlisted.example.com" });
-
-function clearPermissions() {
- SpecialPowers.removePermission("trackingprotection",
- { url: "https://allowlisted.example.com" });
- ok(!SpecialPowers.testPermission("trackingprotection",
- Ci.nsIPermissionManager.ALLOW_ACTION,
- { url: "https://allowlisted.example.com" }));
-}
-
-SpecialPowers.pushPrefEnv(
- {"set" : [["urlclassifier.trackingTable", "test-track-simple"],
- ["privacy.trackingprotection.enabled", true],
- ["channelclassifier.allowlist_example", true]]},
- test);
-
-function test() {
- SimpleTest.registerCleanupFunction(UrlClassifierTestUtils.cleanupTestTrackers);
- UrlClassifierTestUtils.addTestTrackers().then(() => {
- document.getElementById("testFrame").src = "allowlistAnnotatedFrame.html";
- });
-}
-
-// Expected finish() call is in "allowlistedAnnotatedFrame.html".
-SimpleTest.waitForExplicitFinish();
-
-</script>
-
-</pre>
-<iframe id="testFrame" width="100%" height="100%" onload=""></iframe>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_bug1254766.html b/toolkit/components/url-classifier/tests/mochitest/test_bug1254766.html
deleted file mode 100644
index 1c149406a..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_bug1254766.html
+++ /dev/null
@@ -1,305 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Bug 1272239 - Test gethash.</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="classifierHelper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-const MALWARE_LIST = "test-malware-simple";
-const MALWARE_HOST1 = "malware.example.com/";
-const MALWARE_HOST2 = "test1.example.com/";
-
-const UNWANTED_LIST = "test-unwanted-simple";
-const UNWANTED_HOST1 = "unwanted.example.com/";
-const UNWANTED_HOST2 = "test2.example.com/";
-
-
-const UNUSED_MALWARE_HOST = "unused.malware.com/";
-const UNUSED_UNWANTED_HOST = "unused.unwanted.com/";
-
-const GETHASH_URL =
- "http://mochi.test:8888/tests/toolkit/components/url-classifier/tests/mochitest/gethash.sjs";
-
-var gPreGethashCounter = 0;
-var gCurGethashCounter = 0;
-
-var expectLoad = false;
-
-function loadTestFrame() {
- return new Promise(function(resolve, reject) {
- var iframe = document.createElement("iframe");
- iframe.setAttribute("src", "gethashFrame.html");
- document.body.appendChild(iframe);
-
- iframe.onload = function() {
- document.body.removeChild(iframe);
- resolve();
- };
- }).then(getGethashCounter);
-}
-
-function getGethashCounter() {
- return new Promise(function(resolve, reject) {
- var xhr = new XMLHttpRequest;
- xhr.open("PUT", GETHASH_URL + "?gethashcount");
- xhr.setRequestHeader("Content-Type", "text/plain");
- xhr.onreadystatechange = function() {
- if (this.readyState == this.DONE) {
- gPreGethashCounter = gCurGethashCounter;
- gCurGethashCounter = parseInt(xhr.response);
- resolve();
- }
- };
- xhr.send();
- });
-}
-
-// calculate the fullhash and send it to gethash server
-function addCompletionToServer(list, url) {
- return new Promise(function(resolve, reject) {
- var listParam = "list=" + list;
- var fullhashParam = "fullhash=" + hash(url);
-
- var xhr = new XMLHttpRequest;
- xhr.open("PUT", GETHASH_URL + "?" + listParam + "&" + fullhashParam, true);
- xhr.setRequestHeader("Content-Type", "text/plain");
- xhr.onreadystatechange = function() {
- if (this.readyState == this.DONE) {
- resolve();
- }
- };
- xhr.send();
- });
-}
-
-function hash(str) {
- function bytesFromString(str) {
- var converter =
- SpecialPowers.Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(SpecialPowers.Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- return converter.convertToByteArray(str);
- }
-
- var hasher = SpecialPowers.Cc["@mozilla.org/security/hash;1"]
- .createInstance(SpecialPowers.Ci.nsICryptoHash);
-
- var data = bytesFromString(str);
- hasher.init(hasher.SHA256);
- hasher.update(data, data.length);
-
- return hasher.finish(true);
-}
-
-// setup function allows classifier send gethash request for test database
-// also it calculate to fullhash for url and store those hashes in gethash sjs.
-function setup() {
- classifierHelper.allowCompletion([MALWARE_LIST, UNWANTED_LIST], GETHASH_URL);
-
- return Promise.all([
- addCompletionToServer(MALWARE_LIST, MALWARE_HOST1),
- addCompletionToServer(MALWARE_LIST, MALWARE_HOST2),
- addCompletionToServer(UNWANTED_LIST, UNWANTED_HOST1),
- addCompletionToServer(UNWANTED_LIST, UNWANTED_HOST2),
- ]);
-}
-
-// Reset function in helper try to simulate the behavior we restart firefox
-function reset() {
- return classifierHelper.resetDB()
- .catch(err => {
- ok(false, "Couldn't update classifier. Error code: " + errorCode);
- // Abort test.
- SimpleTest.finish();
- });
-}
-
-function updateUnusedUrl() {
- var testData = [
- { url: UNUSED_MALWARE_HOST, db: MALWARE_LIST },
- { url: UNUSED_UNWANTED_HOST, db: UNWANTED_LIST }
- ];
-
- return classifierHelper.addUrlToDB(testData)
- .catch(err => {
- ok(false, "Couldn't update classifier. Error code: " + err);
- // Abort test.
- SimpleTest.finish();
- });
-}
-
-function addPrefixToDB() {
- return update(true);
-}
-
-function addCompletionToDB() {
- return update(false);
-}
-
-function update(prefix = false) {
- var length = prefix ? 4 : 32;
- var testData = [
- { url: MALWARE_HOST1, db: MALWARE_LIST, len: length },
- { url: MALWARE_HOST2, db: MALWARE_LIST, len: length },
- { url: UNWANTED_HOST1, db: UNWANTED_LIST, len: length },
- { url: UNWANTED_HOST2, db: UNWANTED_LIST, len: length }
- ];
-
- return classifierHelper.addUrlToDB(testData)
- .catch(err => {
- ok(false, "Couldn't update classifier. Error code: " + errorCode);
- // Abort test.
- SimpleTest.finish();
- });
-}
-
-// This testcase is to make sure gethash works:
-// 1. Add prefixes to DB.
-// 2. Load test frame contains malware & unwanted url, those urls should be blocked.
-// 3. The second step should also trigger a gethash request since completions is not in
-// either cache or DB.
-// 4. Load test frame again, since completions is stored in cache now, no gethash
-// request should be triggered.
-function testGethash() {
- return Promise.resolve()
- .then(addPrefixToDB)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
- .then(reset);
-}
-
-// This testcase is to make sure an update request will clear completion cache:
-// 1. Add prefixes to DB.
-// 2. Load test frame, this should trigger a gethash request
-// 3. Trigger an update, completion cache should be cleared now.
-// 4. Load test frame again, since cache is cleared now, gethash request should be triggered.
-function testUpdateClearCache() {
- return Promise.resolve()
- .then(addPrefixToDB)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
- .then(updateUnusedUrl)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
- .then(reset);
-}
-
-// This testcae is to make sure completions in update works:
-// 1. Add completions to DB.
-// 2. Load test frame, since completions is stored in DB, gethash request should
-// not be triggered.
-function testUpdate() {
- return Promise.resolve()
- .then(addCompletionToDB)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
- .then(reset);
-}
-
-// This testcase is to make sure an update request will not clear completions in DB:
-// 1. Add completions to DB.
-// 2. Load test frame to make sure completions is stored in database, in this case, gethash
-// should not be triggered.
-// 3. Trigger an update, cache is cleared, but completions in DB should still remain.
-// 4. Load test frame again, since completions is in DB, gethash request should not be triggered.
-function testUpdateNotClearCompletions() {
- return Promise.resolve()
- .then(addCompletionToDB)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
- .then(updateUnusedUrl)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
- .then(reset);
-}
-
-// This testcase is to make sure completion store in DB will properly load after restarting.
-// 1. Add completions to DB.
-// 2. Simulate firefox restart by calling reloadDatabase.
-// 3. Load test frame, since completions should be loaded from DB, no gethash request should
-// be triggered.
-function testUpdateCompletionsAfterReload() {
- return Promise.resolve()
- .then(addCompletionToDB)
- .then(classifierHelper.reloadDatabase)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
- .then(reset);
-}
-
-// This testcase is to make sure cache will be cleared after restarting
-// 1. Add prefixes to DB.
-// 2. Load test frame, this should trigger a gethash request and completions will be stored in
-// cache.
-// 3. Load test frame again, no gethash should be triggered because of cache.
-// 4. Simulate firefox restart by calling reloadDatabase.
-// 5. Load test frame again, since cache is cleared, gethash request should be triggered.
-function testGethashCompletionsAfterReload() {
- return Promise.resolve()
- .then(addPrefixToDB)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter == gPreGethashCounter, "Gethash request is not triggered."); })
- .then(classifierHelper.reloadDatabase)
- .then(loadTestFrame)
- .then(() => {
- ok(gCurGethashCounter > gPreGethashCounter, "Gethash request is triggered."); })
- .then(reset);
-}
-
-function runTest() {
- Promise.resolve()
- .then(classifierHelper.waitForInit)
- .then(setup)
- .then(testGethash)
- .then(testUpdateClearCache)
- .then(testUpdate)
- .then(testUpdateNotClearCompletions)
- .then(testUpdateCompletionsAfterReload)
- .then(testGethashCompletionsAfterReload)
- .then(function() {
- SimpleTest.finish();
- }).catch(function(e) {
- ok(false, "Some test failed with error " + e);
- SimpleTest.finish();
- });
-}
-
-SimpleTest.waitForExplicitFinish();
-
-// 'network.predictor.enabled' is disabled because if other testcase load
-// evil.js, evil.css ...etc resources, it may cause we load them from cache
-// directly and bypass classifier check
-SpecialPowers.pushPrefEnv({"set": [
- ["browser.safebrowsing.malware.enabled", true],
- ["network.predictor.enabled", false],
- ["urlclassifier.gethash.timeout_ms", 30000],
-]}, runTest);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_classified_annotations.html b/toolkit/components/url-classifier/tests/mochitest/test_classified_annotations.html
deleted file mode 100644
index 5814fff00..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_classified_annotations.html
+++ /dev/null
@@ -1,50 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test the URI Classifier</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-Components.utils.import("resource://testing-common/UrlClassifierTestUtils.jsm");
-
-function cleanup() {
- SpecialPowers.clearUserPref("privacy.trackingprotection.enabled");
- SpecialPowers.clearUserPref("channelclassifier.allowlist_example");
-}
-
-SpecialPowers.pushPrefEnv(
- {"set" : [["urlclassifier.trackingTable", "test-track-simple"]]},
- test);
-
-function test() {
- UrlClassifierTestUtils.addTestTrackers().then(() => {
- SpecialPowers.setBoolPref("privacy.trackingprotection.enabled", true);
- // Make sure chrome:// URIs are processed. This does not white-list
- // any URIs unless 'https://allowlisted.example.com' is added in the
- // permission manager (see test_allowlisted_annotations.html)
- SpecialPowers.setBoolPref("channelclassifier.allowlist_example", true);
- document.getElementById("testFrame").src = "classifiedAnnotatedFrame.html";
- });
-}
-
-// Expected finish() call is in "classifiedAnnotatedFrame.html".
-SimpleTest.waitForExplicitFinish();
-
-</script>
-
-</pre>
-<iframe id="testFrame" width="100%" height="100%" onload=""></iframe>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_classifier.html b/toolkit/components/url-classifier/tests/mochitest/test_classifier.html
deleted file mode 100644
index 9533db426..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_classifier.html
+++ /dev/null
@@ -1,65 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test the URI Classifier</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="classifierHelper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var firstLoad = true;
-
-// Add some URLs to the malware database.
-var testData = [
- { url: "malware.example.com/",
- db: "test-malware-simple"
- },
- { url: "unwanted.example.com/",
- db: "test-unwanted-simple"
- }
-];
-
-function loadTestFrame() {
- document.getElementById("testFrame").src = "classifierFrame.html";
-}
-
-// Expected finish() call is in "classifierFrame.html".
-SimpleTest.waitForExplicitFinish();
-
-function updateSuccess() {
- SpecialPowers.pushPrefEnv(
- {"set" : [["browser.safebrowsing.malware.enabled", true]]},
- loadTestFrame);
-}
-
-function updateError(errorCode) {
- ok(false, "Couldn't update classifier. Error code: " + errorCode);
- // Abort test.
- SimpleTest.finish();
-}
-
-SpecialPowers.pushPrefEnv(
- {"set" : [["urlclassifier.malwareTable", "test-malware-simple,test-unwanted-simple"],
- ["urlclassifier.phishTable", "test-phish-simple"]]},
- function() {
- classifierHelper.waitForInit()
- .then(() => classifierHelper.addUrlToDB(testData))
- .then(updateSuccess)
- .catch(err => {
- updateError(err);
- });
- });
-
-</script>
-
-</pre>
-<iframe id="testFrame" onload=""></iframe>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_classifier_changetablepref.html b/toolkit/components/url-classifier/tests/mochitest/test_classifier_changetablepref.html
deleted file mode 100644
index 7423d3e8e..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_classifier_changetablepref.html
+++ /dev/null
@@ -1,149 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Bug 1281083 - Changing the urlclassifier.*Table prefs doesn't take effect before the next browser restart.</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="classifierHelper.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-const testTable = "moz-track-digest256";
-const UPDATE_URL = "http://mochi.test:8888/tests/toolkit/components/url-classifier/tests/mochitest/update.sjs";
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-var prefService = Cc["@mozilla.org/preferences-service;1"]
- .getService(Ci.nsIPrefService);
-
-var timer = Cc["@mozilla.org/timer;1"]
- .createInstance(Ci.nsITimer);
-
-// If default preference contain the table we want to test,
-// We should change test table to a different one.
-var trackingTables = SpecialPowers.getCharPref("urlclassifier.trackingTable").split(",");
-ok(!trackingTables.includes(testTable), "test table should not be in the preference");
-
-var listmanager = Cc["@mozilla.org/url-classifier/listmanager;1"].
- getService(Ci.nsIUrlListManager);
-
-is(listmanager.getGethashUrl(testTable), "",
- "gethash url for test table should be empty before setting to preference");
-
-function loadTestFrame() {
- // gethash url of test table "moz-track-digest256" should be updated
- // after setting preference.
- var url = listmanager.getGethashUrl(testTable);
- var expected = SpecialPowers.getCharPref("browser.safebrowsing.provider.mozilla.gethashURL");
-
- is(url, expected, testTable + " matches its gethash url");
-
- // Trigger update
- listmanager.disableUpdate(testTable);
- listmanager.enableUpdate(testTable);
- listmanager.maybeToggleUpdateChecking();
-
- // We wait until "nextupdattime" was set as a signal that update is complete.
- waitForUpdateSuccess(function() {
- document.getElementById("testFrame").src = "bug_1281083.html";
- });
-}
-
-function waitForUpdateSuccess(callback) {
- let nextupdatetime =
- SpecialPowers.getCharPref("browser.safebrowsing.provider.mozilla.nextupdatetime");
-
- if (nextupdatetime !== "1") {
- callback();
- return;
- }
-
- timer.initWithCallback(function() {
- waitForUpdateSuccess(callback);
- }, 10, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
-}
-
-function addCompletionToServer(list, url) {
- return new Promise(function(resolve, reject) {
- var listParam = "list=" + list;
- var fullhashParam = "fullhash=" + hash(url);
-
- var xhr = new XMLHttpRequest;
- xhr.open("PUT", UPDATE_URL + "?" +
- listParam + "&" +
- fullhashParam, true);
- xhr.setRequestHeader("Content-Type", "text/plain");
- xhr.onreadystatechange = function() {
- if (this.readyState == this.DONE) {
- resolve();
- }
- };
- xhr.send();
- });
-}
-
-function hash(str) {
- function bytesFromString(str) {
- var converter =
- SpecialPowers.Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(SpecialPowers.Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- return converter.convertToByteArray(str);
- }
-
- var hasher = SpecialPowers.Cc["@mozilla.org/security/hash;1"]
- .createInstance(SpecialPowers.Ci.nsICryptoHash);
-
- var data = bytesFromString(str);
- hasher.init(hasher.SHA256);
- hasher.update(data, data.length);
-
- return hasher.finish(true);
-}
-
-function runTest() {
- /**
- * In this test we try to modify only urlclassifier.*Table preference to see if
- * url specified in the table will be blocked after update.
- */
- var pushPrefPromise = SpecialPowers.pushPrefEnv(
- {"set" : [["urlclassifier.trackingTable", testTable]]});
-
- // To make sure url is not blocked by an already blocked url.
- // Here we use non-tracking.example.com as a tracked url.
- // Since this table is only used in this bug, so it won't affect other testcases.
- var addCompletePromise =
- addCompletionToServer(testTable, "bug1281083.example.com/");
-
- Promise.all([pushPrefPromise, addCompletePromise])
- .then(() => {
- loadTestFrame();
- });
-}
-
-// Set nextupdatetime to 1 to trigger an update
-SpecialPowers.pushPrefEnv(
- {"set" : [["privacy.trackingprotection.enabled", true],
- ["channelclassifier.allowlist_example", true],
- ["browser.safebrowsing.provider.mozilla.nextupdatetime", "1"],
- ["browser.safebrowsing.provider.mozilla.lists", testTable],
- ["browser.safebrowsing.provider.mozilla.updateURL", UPDATE_URL]]},
- runTest);
-
-// Expected finish() call is in "bug_1281083.html".
-SimpleTest.waitForExplicitFinish();
-
-</script>
-</pre>
-<iframe id="testFrame" width="100%" height="100%" onload=""></iframe>
-</body>
-</html>
-
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_classifier_worker.html b/toolkit/components/url-classifier/tests/mochitest/test_classifier_worker.html
deleted file mode 100644
index 1f54d45b0..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_classifier_worker.html
+++ /dev/null
@@ -1,76 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test the URI Classifier</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="classifierHelper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-// Add some URLs to the malware database.
-var testData = [
- { url: "example.com/tests/toolkit/components/url-classifier/tests/mochitest/evilWorker.js",
- db: "test-malware-simple"
- },
- { url: "example.com/tests/toolkit/components/url-classifier/tests/mochitest/unwantedWorker.js",
- db: "test-unwanted-simple"
- }
-];
-
-function loadTestFrame() {
- document.getElementById("testFrame").src =
- "http://example.com/tests/toolkit/components/url-classifier/tests/mochitest/workerFrame.html";
-}
-
-function onmessage(event)
-{
- var pieces = event.data.split(':');
- if (pieces[0] == "finish") {
- SimpleTest.finish();
- return;
- }
-
- is(pieces[0], "success", pieces[1]);
-}
-
-function updateSuccess() {
- SpecialPowers.pushPrefEnv(
- {"set" : [["browser.safebrowsing.malware.enabled", true]]},
- loadTestFrame);
-}
-
-function updateError(errorCode) {
- ok(false, "Couldn't update classifier. Error code: " + errorCode);
- // Abort test.
- SimpleTest.finish();
-};
-
-SpecialPowers.pushPrefEnv(
- {"set" : [["urlclassifier.malwareTable", "test-malware-simple,test-unwanted-simple"],
- ["urlclassifier.phishTable", "test-phish-simple"]]},
- function() {
- classifierHelper.waitForInit()
- .then(() => classifierHelper.addUrlToDB(testData))
- .then(updateSuccess)
- .catch(err => {
- updateError(err);
- });
- });
-
-window.addEventListener("message", onmessage, false);
-
-SimpleTest.waitForExplicitFinish();
-
-</script>
-
-</pre>
-<iframe id="testFrame" onload=""></iframe>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_classify_ping.html b/toolkit/components/url-classifier/tests/mochitest/test_classify_ping.html
deleted file mode 100644
index 96fa2891a..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_classify_ping.html
+++ /dev/null
@@ -1,121 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Bug 1233914 - ping doesn't honor the TP list here.</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
- SimpleTest.requestFlakyTimeout("Delay to make sure ping is made prior than XHR");
-
- const timeout = 200;
- const host_nottrack = "http://not-tracking.example.com/";
- const host_track = "http://trackertest.org/";
- const path_ping = "tests/toolkit/components/url-classifier/tests/mochitest/ping.sjs";
- const TP_ENABLE_PREF = "privacy.trackingprotection.enabled";
-
- function testPingNonBlacklist() {
- SpecialPowers.setBoolPref(TP_ENABLE_PREF, true);
-
- var msg = "ping should reach page not in blacklist";
- var expectPing = true;
- var id = "1111";
- ping(id, host_nottrack);
-
- return new Promise(function(resolve, reject) {
- setTimeout(function() {
- isPinged(id, expectPing, msg, resolve);
- }, timeout);
- });
- }
-
- function testPingBlacklistSafebrowsingOff() {
- SpecialPowers.setBoolPref(TP_ENABLE_PREF, false);
-
- var msg = "ping should reach page in blacklist when tracking protection is off";
- var expectPing = true;
- var id = "2222";
- ping(id, host_track);
-
- return new Promise(function(resolve, reject) {
- setTimeout(function() {
- isPinged(id, expectPing, msg, resolve);
- }, timeout);
- });
- }
-
- function testPingBlacklistSafebrowsingOn() {
- SpecialPowers.setBoolPref(TP_ENABLE_PREF, true);
-
- var msg = "ping should not reach page in blacklist when tracking protection is on";
- var expectPing = false;
- var id = "3333";
- ping(id, host_track);
-
- return new Promise(function(resolve, reject) {
- setTimeout(function() {
- isPinged(id, expectPing, msg, resolve);
- }, timeout);
- });
- }
-
- function ping(id, host) {
- var elm = document.createElement("a");
- elm.setAttribute('ping', host + path_ping + "?id=" + id);
- elm.setAttribute('href', "#");
- document.body.appendChild(elm);
-
- // Trigger ping.
- elm.click();
-
- document.body.removeChild(elm);
- }
-
- function isPinged(id, expected, msg, callback) {
- var url = "http://mochi.test:8888/" + path_ping;
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url + "?id=" + id);
- xhr.onload = function() {
- var isPinged = xhr.response === "ping";
- is(expected, isPinged, msg);
-
- callback();
- };
- xhr.send();
- }
-
- function cleanup() {
- SpecialPowers.clearUserPref(TP_ENABLE_PREF);
- }
-
- function runTest() {
- Promise.resolve()
- .then(testPingNonBlacklist)
- .then(testPingBlacklistSafebrowsingOff)
- .then(testPingBlacklistSafebrowsingOn)
- .then(function() {
- SimpleTest.finish();
- }).catch(function(e) {
- ok(false, "Some test failed with error " + e);
- SimpleTest.finish();
- });
- }
-
- SimpleTest.waitForExplicitFinish();
- SimpleTest.registerCleanupFunction(cleanup);
- SpecialPowers.pushPrefEnv({"set": [
- ["browser.send_pings", true],
- ["urlclassifier.trackingTable", "test-track-simple"],
- ]}, runTest);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_classify_track.html b/toolkit/components/url-classifier/tests/mochitest/test_classify_track.html
deleted file mode 100644
index a868d7960..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_classify_track.html
+++ /dev/null
@@ -1,162 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Bug 1262406 - Track element doesn't use the URL classifier.</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="classifierHelper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
- const PREF = "browser.safebrowsing.malware.enabled";
- const track_path = "tests/toolkit/components/url-classifier/tests/mochitest/basic.vtt";
- const malware_url = "http://malware.example.com/" + track_path;
- const validtrack_url = "http://mochi.test:8888/" + track_path;
-
- var video = document.createElement("video");
- video.src = "seek.webm";
- video.crossOrigin = "anonymous";
-
- document.body.appendChild(video);
-
- function testValidTrack() {
- SpecialPowers.setBoolPref(PREF, true);
-
- return new Promise(function(resolve, reject) {
- var track = document.createElement("track");
- track.src = validtrack_url;
- video.appendChild(track);
-
- function onload() {
- ok(true, "Track should be loaded when url is not in blacklist");
- finish();
- }
-
- function onerror() {
- ok(false, "Error while loading track");
- finish();
- }
-
- function finish() {
- track.removeEventListener("load", onload);
- track.removeEventListener("error", onerror)
- resolve();
- }
-
- track.addEventListener("load", onload);
- track.addEventListener("error", onerror)
- });
- }
-
- function testBlacklistTrackSafebrowsingOff() {
- SpecialPowers.setBoolPref(PREF, false);
-
- return new Promise(function(resolve, reject) {
- var track = document.createElement("track");
- track.src = malware_url;
- video.appendChild(track);
-
- function onload() {
- ok(true, "Track should be loaded when url is in blacklist and safebrowsing is off");
- finish();
- }
-
- function onerror() {
- ok(false, "Error while loading track");
- finish();
- }
-
- function finish() {
- track.removeEventListener("load", onload);
- track.removeEventListener("error", onerror)
- resolve();
- }
-
- track.addEventListener("load", onload);
- track.addEventListener("error", onerror)
- });
- }
-
- function testBlacklistTrackSafebrowsingOn() {
- SpecialPowers.setBoolPref(PREF, true);
-
- return new Promise(function(resolve, reject) {
- var track = document.createElement("track");
-
- // Add a query string parameter here to avoid url classifier bypass classify
- // because of cache.
- track.src = malware_url + "?testsbon";
- video.appendChild(track);
-
- function onload() {
- ok(false, "Unexpected result while loading track in blacklist");
- finish();
- }
-
- function onerror() {
- ok(true, "Track should not be loaded when url is in blacklist and safebrowsing is on");
- finish();
- }
-
- function finish() {
- track.removeEventListener("load", onload);
- track.removeEventListener("error", onerror)
- resolve();
- }
-
- track.addEventListener("load", onload);
- track.addEventListener("error", onerror)
- });
- }
-
- function cleanup() {
- SpecialPowers.clearUserPref(PREF);
- }
-
- function setup() {
- var testData = [
- { url: "malware.example.com/",
- db: "test-malware-simple"
- }
- ];
-
- return classifierHelper.addUrlToDB(testData)
- .catch(function(err) {
- ok(false, "Couldn't update classifier. Error code: " + err);
- // Abort test.
- SimpleTest.finish();
- });
- }
-
- function runTest() {
- Promise.resolve()
- .then(classifierHelper.waitForInit)
- .then(setup)
- .then(testValidTrack)
- .then(testBlacklistTrackSafebrowsingOff)
- .then(testBlacklistTrackSafebrowsingOn)
- .then(function() {
- SimpleTest.finish();
- }).catch(function(e) {
- ok(false, "Some test failed with error " + e);
- SimpleTest.finish();
- });
- }
-
- SimpleTest.waitForExplicitFinish();
- SimpleTest.registerCleanupFunction(cleanup);
- SpecialPowers.pushPrefEnv({"set": [
- ["media.webvtt.regions.enabled", true],
- ["urlclassifier.malwareTable", "test-malware-simple"],
- ]}, runTest);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_donottrack.html b/toolkit/components/url-classifier/tests/mochitest/test_donottrack.html
deleted file mode 100644
index 56003e7eb..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_donottrack.html
+++ /dev/null
@@ -1,150 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Bug 1258033 - Fix the DNT loophole for tracking protection</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-var mainWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShellTreeItem)
- .rootTreeItem
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
-
-const tests = [
- // DNT turned on and TP turned off, DNT signal sent in both private browsing
- // and normal mode.
- {
- setting: {dntPref:true, tpPref:false, tppbPref:false, pbMode:true},
- expected: {dnt: "1"},
- },
- {
- setting: {dntPref:true, tpPref:false, tppbPref:false, pbMode:false},
- expected: {dnt: "1"}
- },
- // DNT turned off and TP turned on globally, DNT signal sent in both private
- // browsing and normal mode.
- {
- setting: {dntPref:false, tpPref:true, tppbPref:false, pbMode:true},
- expected: {dnt: "1"}
- },
- {
- setting: {dntPref:false, tpPref:true, tppbPref:false, pbMode:false},
- expected: {dnt: "1"}
- },
- // DNT turned off and TP in Private Browsing only, DNT signal sent in private
- // browsing mode only.
- {
- setting: {dntPref:false, tpPref:false, tppbPref:true, pbMode:true},
- expected: {dnt: "1"}
- },
- {
- setting: {dntPref:false, tpPref:false, tppbPref:true, pbMode:false},
- expected: {dnt: "unspecified"}
- },
- // DNT turned off and TP turned off, DNT signal is never sent.
- {
- setting: {dntPref:false, tpPref:false, tppbPref:false, pbMode:true},
- expected: {dnt: "unspecified"}
- },
- {
- setting: {dntPref:false, tpPref:false, tppbPref:false, pbMode:false},
- expected: {dnt: "unspecified"}
- },
-]
-
-const DNT_PREF = 'privacy.donottrackheader.enabled';
-const TP_PREF = 'privacy.trackingprotection.enabled';
-const TP_PB_PREF = 'privacy.trackingprotection.pbmode.enabled';
-
-const contentPage =
- "http://mochi.test:8888/tests/toolkit/components/url-classifier/tests/mochitest/dnt.html";
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-function whenDelayedStartupFinished(aWindow, aCallback) {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- setTimeout(aCallback, 0);
- }
- }, "browser-delayed-startup-finished", false);
-}
-
-function executeTest(test) {
- SpecialPowers.pushPrefEnv({"set" : [
- [DNT_PREF, test.setting.dntPref],
- [TP_PREF, test.setting.tpPref],
- [TP_PB_PREF, test.setting.tppbPref]
- ]});
-
- var win = mainWindow.OpenBrowserWindow({private: test.setting.pbMode});
-
- return new Promise(function(resolve, reject) {
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- whenDelayedStartupFinished(win, function() {
- win.addEventListener("DOMContentLoaded", function onInnerLoad() {
- if (win.content.location.href != contentPage) {
- win.gBrowser.loadURI(contentPage);
- return;
- }
-
- win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
-
- win.content.addEventListener('message', function (event) {
- let [key, value] = event.data.split("=");
- if (key == "finish") {
- win.close();
- resolve();
- } else if (key == "navigator.doNotTrack") {
- is(value, test.expected.dnt, "navigator.doNotTrack should be " + test.expected.dnt);
- } else if (key == "DNT") {
- let msg = test.expected.dnt == "1" ? "" : "not ";
- is(value, test.expected.dnt, "DNT header should " + msg + "be sent");
- } else {
- ok(false, "unexpected message");
- }
- });
- }, true);
- SimpleTest.executeSoon(function() { win.gBrowser.loadURI(contentPage); });
- });
- }, true);
- });
-}
-
-let loop = function loop(index) {
- if (index >= tests.length) {
- SimpleTest.finish();
- return;
- }
-
- let test = tests[index];
- let next = function next() {
- loop(index + 1);
- };
- let result = executeTest(test);
- result.then(next, next);
-};
-
-SimpleTest.waitForExplicitFinish();
-loop(0);
-
-</script>
-
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_gethash.html b/toolkit/components/url-classifier/tests/mochitest/test_gethash.html
deleted file mode 100644
index af995e2a5..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_gethash.html
+++ /dev/null
@@ -1,157 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Bug 1272239 - Test gethash.</title>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="classifierHelper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-<iframe id="testFrame1" onload=""></iframe>
-<iframe id="testFrame2" onload=""></iframe>
-
-<script class="testbody" type="text/javascript">
-
-const MALWARE_LIST = "test-malware-simple";
-const MALWARE_HOST = "malware.example.com/";
-
-const UNWANTED_LIST = "test-unwanted-simple";
-const UNWANTED_HOST = "unwanted.example.com/";
-
-const GETHASH_URL = "http://mochi.test:8888/tests/toolkit/components/url-classifier/tests/mochitest/gethash.sjs";
-const NOTEXIST_URL = "http://mochi.test:8888/tests/toolkit/components/url-classifier/tests/mochitest/nonexistserver.sjs";
-
-var shouldLoad = false;
-
-// In this testcase we store prefixes to localdb and send the fullhash to gethash server.
-// When access the test page gecko should trigger gethash request to server and
-// get the completion response.
-function loadTestFrame(id) {
- return new Promise(function(resolve, reject) {
-
- var iframe = document.getElementById(id);
- iframe.setAttribute("src", "gethashFrame.html");
-
- iframe.onload = function() {
- resolve();
- };
- });
-}
-
-// add 4-bytes prefixes to local database, so when we access the url,
-// it will trigger gethash request.
-function addPrefixToDB(list, url) {
- var testData = [{ db: list, url: url, len: 4 }];
-
- return classifierHelper.addUrlToDB(testData)
- .catch(function(err) {
- ok(false, "Couldn't update classifier. Error code: " + err);
- // Abort test.
- SimpleTest.finish();
- });
-}
-
-// calculate the fullhash and send it to gethash server
-function addCompletionToServer(list, url) {
- return new Promise(function(resolve, reject) {
- var listParam = "list=" + list;
- var fullhashParam = "fullhash=" + hash(url);
-
- var xhr = new XMLHttpRequest;
- xhr.open("PUT", GETHASH_URL + "?" +
- listParam + "&" +
- fullhashParam, true);
- xhr.setRequestHeader("Content-Type", "text/plain");
- xhr.onreadystatechange = function() {
- if (this.readyState == this.DONE) {
- resolve();
- }
- };
- xhr.send();
- });
-}
-
-function hash(str) {
- function bytesFromString(str) {
- var converter =
- SpecialPowers.Cc["@mozilla.org/intl/scriptableunicodeconverter"]
- .createInstance(SpecialPowers.Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- return converter.convertToByteArray(str);
- }
-
- var hasher = SpecialPowers.Cc["@mozilla.org/security/hash;1"]
- .createInstance(SpecialPowers.Ci.nsICryptoHash);
-
- var data = bytesFromString(str);
- hasher.init(hasher.SHA256);
- hasher.update(data, data.length);
-
- return hasher.finish(true);
-}
-
-function setup404() {
- shouldLoad = true;
-
- classifierHelper.allowCompletion([MALWARE_LIST, UNWANTED_LIST], NOTEXIST_URL);
-
- return Promise.all([
- addPrefixToDB(MALWARE_LIST, MALWARE_HOST),
- addPrefixToDB(UNWANTED_LIST, UNWANTED_HOST)
- ]);
-}
-
-function setup() {
- classifierHelper.allowCompletion([MALWARE_LIST, UNWANTED_LIST], GETHASH_URL);
-
- return Promise.all([
- addPrefixToDB(MALWARE_LIST, MALWARE_HOST),
- addPrefixToDB(UNWANTED_LIST, UNWANTED_HOST),
- addCompletionToServer(MALWARE_LIST, MALWARE_HOST),
- addCompletionToServer(UNWANTED_LIST, UNWANTED_HOST),
- ]);
-}
-
-// manually reset DB to make sure next test won't be affected by cache.
-function reset() {
- return classifierHelper.resetDB;
-}
-
-function runTest() {
- Promise.resolve()
- // This test resources get blocked when gethash returns successfully
- .then(classifierHelper.waitForInit)
- .then(setup)
- .then(() => loadTestFrame("testFrame1"))
- .then(reset)
- // This test resources are not blocked when gethash returns an error
- .then(setup404)
- .then(() => loadTestFrame("testFrame2"))
- .then(function() {
- SimpleTest.finish();
- }).catch(function(e) {
- ok(false, "Some test failed with error " + e);
- SimpleTest.finish();
- });
-}
-
-SimpleTest.waitForExplicitFinish();
-
-// 'network.predictor.enabled' is disabled because if other testcase load
-// evil.js, evil.css ...etc resources, it may cause we load them from cache
-// directly and bypass classifier check
-SpecialPowers.pushPrefEnv({"set": [
- ["browser.safebrowsing.malware.enabled", true],
- ["network.predictor.enabled", false],
- ["urlclassifier.gethash.timeout_ms", 30000],
-]}, runTest);
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_lookup_system_principal.html b/toolkit/components/url-classifier/tests/mochitest/test_lookup_system_principal.html
deleted file mode 100644
index fa61e6a00..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_lookup_system_principal.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Test that lookup() on a system principal doesn't crash</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script type="text/javascript">
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-var dbService = Cc["@mozilla.org/url-classifier/dbservice;1"]
- .getService(Ci.nsIUrlClassifierDBService);
-
-dbService.lookup(document.nodePrincipal, "", function(arg) {});
-
-ok(true, "lookup() didn't crash");
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_privatebrowsing_trackingprotection.html b/toolkit/components/url-classifier/tests/mochitest/test_privatebrowsing_trackingprotection.html
deleted file mode 100644
index 02ef57b46..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_privatebrowsing_trackingprotection.html
+++ /dev/null
@@ -1,154 +0,0 @@
-<!DOCTYPE HTML>
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-<html>
-<head>
- <title>Test Tracking Protection in Private Browsing mode</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-var mainWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShellTreeItem)
- .rootTreeItem
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
-var contentPage = "http://www.itisatrap.org/tests/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedPBFrame.html";
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://testing-common/UrlClassifierTestUtils.jsm");
-
-function whenDelayedStartupFinished(aWindow, aCallback) {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- setTimeout(aCallback, 0);
- }
- }, "browser-delayed-startup-finished", false);
-}
-
-function testOnWindow(aPrivate, aCallback) {
- var win = mainWindow.OpenBrowserWindow({private: aPrivate});
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- whenDelayedStartupFinished(win, function() {
- win.addEventListener("DOMContentLoaded", function onInnerLoad() {
- if (win.content.location.href != contentPage) {
- win.gBrowser.loadURI(contentPage);
- return;
- }
- win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
-
- win.content.addEventListener('load', function innerLoad2() {
- win.content.removeEventListener('load', innerLoad2, false);
- SimpleTest.executeSoon(function() { aCallback(win); });
- }, false, true);
- }, true);
- SimpleTest.executeSoon(function() { win.gBrowser.loadURI(contentPage); });
- });
- }, true);
-}
-
-var badids = [
- "badscript",
- "badimage",
- "badcss"
-];
-
-function checkLoads(aWindow, aBlocked) {
- var win = aWindow.content;
- is(win.document.getElementById("badscript").dataset.touched, aBlocked ? "no" : "yes", "Should not load tracking javascript");
- is(win.document.getElementById("badimage").dataset.touched, aBlocked ? "no" : "yes", "Should not load tracking images");
- is(win.document.getElementById("goodscript").dataset.touched, "yes", "Should load whitelisted tracking javascript");
-
- var elt = win.document.getElementById("styleCheck");
- var style = win.document.defaultView.getComputedStyle(elt, "");
- isnot(style.visibility, aBlocked ? "hidden" : "", "Should not load tracking css");
-
- is(win.document.blockedTrackingNodeCount, aBlocked ? badids.length : 0, "Should identify all tracking elements");
-
- var blockedTrackingNodes = win.document.blockedTrackingNodes;
-
- // Make sure that every node in blockedTrackingNodes exists in the tree
- // (that may not always be the case but do not expect any nodes to disappear
- // from the tree here)
- var allNodeMatch = true;
- for (var i = 0; i < blockedTrackingNodes.length; i++) {
- var nodeMatch = false;
- for (var j = 0; j < badids.length && !nodeMatch; j++) {
- nodeMatch = nodeMatch ||
- (blockedTrackingNodes[i] == win.document.getElementById(badids[j]));
- }
-
- allNodeMatch = allNodeMatch && nodeMatch;
- }
- is(allNodeMatch, true, "All annotated nodes are expected in the tree");
-
- // Make sure that every node with a badid (see badids) is found in the
- // blockedTrackingNodes. This tells us if we are neglecting to annotate
- // some nodes
- allNodeMatch = true;
- for (var j = 0; j < badids.length; j++) {
- var nodeMatch = false;
- for (var i = 0; i < blockedTrackingNodes.length && !nodeMatch; i++) {
- nodeMatch = nodeMatch ||
- (blockedTrackingNodes[i] == win.document.getElementById(badids[j]));
- }
-
- allNodeMatch = allNodeMatch && nodeMatch;
- }
- is(allNodeMatch, aBlocked, "All tracking nodes are expected to be annotated as such");
-}
-
-SpecialPowers.pushPrefEnv(
- {"set" : [["urlclassifier.trackingTable", "test-track-simple"],
- ["privacy.trackingprotection.enabled", false],
- ["privacy.trackingprotection.pbmode.enabled", true],
- ["channelclassifier.allowlist_example", true]]},
- test);
-
-function test() {
- SimpleTest.registerCleanupFunction(UrlClassifierTestUtils.cleanupTestTrackers);
- UrlClassifierTestUtils.addTestTrackers().then(() => {
- // Normal mode, with the pref (trackers should be loaded)
- testOnWindow(false, function(aWindow) {
- checkLoads(aWindow, false);
- aWindow.close();
-
- // Private Browsing, with the pref (trackers should be blocked)
- testOnWindow(true, function(aWindow) {
- checkLoads(aWindow, true);
- aWindow.close();
-
- // Private Browsing, without the pref (trackers should be loaded)
- SpecialPowers.setBoolPref("privacy.trackingprotection.pbmode.enabled", false);
- testOnWindow(true, function(aWindow) {
- checkLoads(aWindow, false);
- aWindow.close();
- SimpleTest.finish();
- });
- });
- });
- });
-}
-
-SimpleTest.waitForExplicitFinish();
-
-</script>
-
-</pre>
-<iframe id="testFrame" width="100%" height="100%" onload=""></iframe>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_safebrowsing_bug1272239.html b/toolkit/components/url-classifier/tests/mochitest/test_safebrowsing_bug1272239.html
deleted file mode 100644
index 8066c2a37..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_safebrowsing_bug1272239.html
+++ /dev/null
@@ -1,87 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <title>Bug 1272239 - Only tables with provider could register gethash url in listmanager.</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-// List all the tables
-const prefs = [
- "urlclassifier.phishTable",
- "urlclassifier.malwareTable",
- "urlclassifier.downloadBlockTable",
- "urlclassifier.downloadAllowTable",
- "urlclassifier.trackingTable",
- "urlclassifier.trackingWhitelistTable",
- "urlclassifier.blockedTable"
-];
-
-var prefService = Cc["@mozilla.org/preferences-service;1"]
- .getService(Ci.nsIPrefService);
-
-// Get providers
-var providers = {};
-
-var branch = prefService.getBranch("browser.safebrowsing.provider.");
-var children = branch.getChildList("", {});
-
-for (var child of children) {
- var prefComponents = child.split(".");
- var providerName = prefComponents[0];
- providers[providerName] = {};
-}
-
-// Get lists from |browser.safebrowsing.provider.PROVIDER_NAME.lists| preference.
-var listsWithProvider = [];
-var listsToProvider = [];
-for (var provider in providers) {
- var pref = "browser.safebrowsing.provider." + provider + ".lists";
- var list = SpecialPowers.getCharPref(pref).split(",");
-
- listsToProvider = listsToProvider.concat(list.map( () => { return provider; }));
- listsWithProvider = listsWithProvider.concat(list);
-}
-
-// Get all the lists
-var lists = [];
-for (var pref of prefs) {
- lists = lists.concat(SpecialPowers.getCharPref(pref).split(","));
-}
-
-var listmanager = Cc["@mozilla.org/url-classifier/listmanager;1"].
- getService(Ci.nsIUrlListManager);
-
-for (var list of lists) {
- if (!list)
- continue;
-
- // For lists having a provider, it should have a correct gethash url
- // For lists without a provider, for example, test-malware-simple, it should not
- // have a gethash url.
- var url = listmanager.getGethashUrl(list);
- var index = listsWithProvider.indexOf(list);
- if (index >= 0) {
- var provider = listsToProvider[index];
- var pref = "browser.safebrowsing.provider." + provider + ".gethashURL";
- is(url, SpecialPowers.getCharPref(pref), list + " matches its gethash url");
- } else {
- is(url, "", list + " should not have a gethash url");
- }
-}
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_bug1157081.html b/toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_bug1157081.html
deleted file mode 100644
index 7611dd245..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_bug1157081.html
+++ /dev/null
@@ -1,107 +0,0 @@
-<!DOCTYPE HTML>
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-<html>
-<head>
- <title>Test Tracking Protection with and without Safe Browsing (Bug #1157081)</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-var mainWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShellTreeItem)
- .rootTreeItem
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
-var contentPage = "chrome://mochitests/content/chrome/toolkit/components/url-classifier/tests/mochitest/classifiedAnnotatedPBFrame.html"
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://testing-common/UrlClassifierTestUtils.jsm");
-
-function whenDelayedStartupFinished(aWindow, aCallback) {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- setTimeout(aCallback, 0);
- }
- }, "browser-delayed-startup-finished", false);
-}
-
-function testOnWindow(aCallback) {
- var win = mainWindow.OpenBrowserWindow();
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- whenDelayedStartupFinished(win, function() {
- win.addEventListener("DOMContentLoaded", function onInnerLoad() {
- if (win.content.location.href != contentPage) {
- win.gBrowser.loadURI(contentPage);
- return;
- }
- win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
-
- win.content.addEventListener('load', function innerLoad2() {
- win.content.removeEventListener('load', innerLoad2, false);
- SimpleTest.executeSoon(function() { aCallback(win); });
- }, false, true);
- }, true);
- SimpleTest.executeSoon(function() { win.gBrowser.loadURI(contentPage); });
- });
- }, true);
-}
-
-var badids = [
- "badscript"
-];
-
-function checkLoads(aWindow, aBlocked) {
- var win = aWindow.content;
- is(win.document.getElementById("badscript").dataset.touched, aBlocked ? "no" : "yes", "Should not load tracking javascript");
-}
-
-SpecialPowers.pushPrefEnv(
- {"set" : [["urlclassifier.trackingTable", "test-track-simple"],
- ["privacy.trackingprotection.enabled", true],
- ["browser.safebrowsing.malware.enabled", false],
- ["browser.safebrowsing.phishing.enabled", false],
- ["channelclassifier.allowlist_example", true]]},
- test);
-
-function test() {
- SimpleTest.registerCleanupFunction(UrlClassifierTestUtils.cleanupTestTrackers);
- UrlClassifierTestUtils.addTestTrackers().then(() => {
- // Safe Browsing turned OFF, tracking protection should work nevertheless
- testOnWindow(function(aWindow) {
- checkLoads(aWindow, true);
- aWindow.close();
-
- // Safe Browsing turned ON, tracking protection should still work
- SpecialPowers.setBoolPref("browser.safebrowsing.phishing.enabled", true);
- testOnWindow(function(aWindow) {
- checkLoads(aWindow, true);
- aWindow.close();
- SimpleTest.finish();
- });
- });
- });
-}
-
-SimpleTest.waitForExplicitFinish();
-
-</script>
-
-</pre>
-<iframe id="testFrame" width="100%" height="100%" onload=""></iframe>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_whitelist.html b/toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_whitelist.html
deleted file mode 100644
index 29de0dfed..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/test_trackingprotection_whitelist.html
+++ /dev/null
@@ -1,153 +0,0 @@
-<!DOCTYPE HTML>
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-<html>
-<head>
- <title>Test Tracking Protection in Private Browsing mode</title>
- <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
-</head>
-
-<body>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<pre id="test">
-
-<script class="testbody" type="text/javascript">
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-var mainWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebNavigation)
- .QueryInterface(Ci.nsIDocShellTreeItem)
- .rootTreeItem
- .QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
-var contentPage1 = "http://www.itisatrap.org/tests/toolkit/components/url-classifier/tests/mochitest/whitelistFrame.html";
-var contentPage2 = "http://example.com/tests/toolkit/components/url-classifier/tests/mochitest/whitelistFrame.html";
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource://testing-common/UrlClassifierTestUtils.jsm");
-
-function whenDelayedStartupFinished(aWindow, aCallback) {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- if (aWindow == aSubject) {
- Services.obs.removeObserver(observer, aTopic);
- setTimeout(aCallback, 0);
- }
- }, "browser-delayed-startup-finished", false);
-}
-
-function testOnWindow(contentPage, aCallback) {
- var win = mainWindow.OpenBrowserWindow();
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad, false);
- whenDelayedStartupFinished(win, function() {
- win.addEventListener("DOMContentLoaded", function onInnerLoad() {
- if (win.content.location.href != contentPage) {
- win.gBrowser.loadURI(contentPage);
- return;
- }
- win.removeEventListener("DOMContentLoaded", onInnerLoad, true);
-
- win.content.addEventListener('load', function innerLoad2() {
- win.content.removeEventListener('load', innerLoad2, false);
- SimpleTest.executeSoon(function() { aCallback(win); });
- }, false, true);
- }, true);
- SimpleTest.executeSoon(function() { win.gBrowser.loadURI(contentPage); });
- });
- }, true);
-}
-
-var alwaysbadids = [
- "badscript",
-];
-
-function checkLoads(aWindow, aWhitelisted) {
- var win = aWindow.content;
- is(win.document.getElementById("badscript").dataset.touched, "no", "Should not load tracking javascript");
- is(win.document.getElementById("goodscript").dataset.touched, aWhitelisted ? "yes" : "no", "Should load whitelisted tracking javascript");
-
- var badids = alwaysbadids.slice();
- if (!aWhitelisted) {
- badids.push("goodscript");
- }
- is(win.document.blockedTrackingNodeCount, badids.length, "Should identify all tracking elements");
-
- var blockedTrackingNodes = win.document.blockedTrackingNodes;
-
- // Make sure that every node in blockedTrackingNodes exists in the tree
- // (that may not always be the case but do not expect any nodes to disappear
- // from the tree here)
- var allNodeMatch = true;
- for (var i = 0; i < blockedTrackingNodes.length; i++) {
- var nodeMatch = false;
- for (var j = 0; j < badids.length && !nodeMatch; j++) {
- nodeMatch = nodeMatch ||
- (blockedTrackingNodes[i] == win.document.getElementById(badids[j]));
- }
-
- allNodeMatch = allNodeMatch && nodeMatch;
- }
- is(allNodeMatch, true, "All annotated nodes are expected in the tree");
-
- // Make sure that every node with a badid (see badids) is found in the
- // blockedTrackingNodes. This tells us if we are neglecting to annotate
- // some nodes
- allNodeMatch = true;
- for (var j = 0; j < badids.length; j++) {
- var nodeMatch = false;
- for (var i = 0; i < blockedTrackingNodes.length && !nodeMatch; i++) {
- nodeMatch = nodeMatch ||
- (blockedTrackingNodes[i] == win.document.getElementById(badids[j]));
- }
-
- allNodeMatch = allNodeMatch && nodeMatch;
- }
- is(allNodeMatch, true, "All tracking nodes are expected to be annotated as such");
-}
-
-SpecialPowers.pushPrefEnv(
- {"set" : [["privacy.trackingprotection.enabled", true],
- ["channelclassifier.allowlist_example", true]]},
- test);
-
-function test() {
- SimpleTest.registerCleanupFunction(UrlClassifierTestUtils.cleanupTestTrackers);
- UrlClassifierTestUtils.addTestTrackers().then(() => {
- // Load the test from a URL on the whitelist
- testOnWindow(contentPage1, function(aWindow) {
- checkLoads(aWindow, true);
- aWindow.close();
-
- // Load the test from a URL that's NOT on the whitelist
- testOnWindow(contentPage2, function(aWindow) {
- checkLoads(aWindow, false);
- aWindow.close();
-
- // Load the test from a URL on the whitelist but without the whitelist
- SpecialPowers.pushPrefEnv({"set" : [["urlclassifier.trackingWhitelistTable", ""]]},
- function() {
- testOnWindow(contentPage1, function(aWindow) {
- checkLoads(aWindow, false);
- aWindow.close();
- SimpleTest.finish();
- });
- });
-
- });
- });
- });
-}
-
-SimpleTest.waitForExplicitFinish();
-
-</script>
-
-</pre>
-<iframe id="testFrame" width="100%" height="100%" onload=""></iframe>
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/track.html b/toolkit/components/url-classifier/tests/mochitest/track.html
deleted file mode 100644
index 8785e7c5b..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/track.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<html>
- <head>
- </head>
- <body>
- <h1>Tracking Works!</h1>
- </body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/unwantedWorker.js b/toolkit/components/url-classifier/tests/mochitest/unwantedWorker.js
deleted file mode 100644
index ac34977d7..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/unwantedWorker.js
+++ /dev/null
@@ -1,3 +0,0 @@
-onmessage = function() {
- postMessage("loaded bad file");
-}
diff --git a/toolkit/components/url-classifier/tests/mochitest/update.sjs b/toolkit/components/url-classifier/tests/mochitest/update.sjs
deleted file mode 100644
index 53efaafdf..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/update.sjs
+++ /dev/null
@@ -1,114 +0,0 @@
-const CC = Components.Constructor;
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-function handleRequest(request, response)
-{
- var query = {};
- request.queryString.split('&').forEach(function (val) {
- var idx = val.indexOf('=');
- query[val.slice(0, idx)] = unescape(val.slice(idx + 1));
- });
-
- // Store fullhash in the server side.
- if ("list" in query && "fullhash" in query) {
- // In the server side we will store:
- // 1. All the full hashes for a given list
- // 2. All the lists we have right now
- // data is separate by '\n'
- let list = query["list"];
- let hashes = getState(list);
-
- let hash = base64ToString(query["fullhash"]);
- hashes += hash + "\n";
- setState(list, hashes);
-
- let lists = getState("lists");
- if (lists.indexOf(list) == -1) {
- lists += list + "\n";
- setState("lists", lists);
- }
-
- return;
- }
-
- var body = new BinaryInputStream(request.bodyInputStream);
- var avail;
- var bytes = [];
-
- while ((avail = body.available()) > 0) {
- Array.prototype.push.apply(bytes, body.readByteArray(avail));
- }
-
- var responseBody = parseV2Request(bytes);
-
- response.setHeader("Content-Type", "text/plain", false);
- response.write(responseBody);
-}
-
-function parseV2Request(bytes) {
- var table = String.fromCharCode.apply(this, bytes).slice(0,-2);
-
- var ret = "";
- getState("lists").split("\n").forEach(function(list) {
- if (list == table) {
- var completions = getState(list).split("\n");
- ret += "n:1000\n"
- ret += "i:" + list + "\n";
- ret += "a:1:32:" + 32*(completions.length - 1) + "\n";
-
- for (var completion of completions) {
- ret += completion;
- }
- }
- });
-
- return ret;
-}
-
-/* Convert Base64 data to a string */
-const toBinaryTable = [
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
-];
-const base64Pad = '=';
-
-function base64ToString(data) {
- var result = '';
- var leftbits = 0; // number of bits decoded, but yet to be appended
- var leftdata = 0; // bits decoded, but yet to be appended
-
- // Convert one by one.
- for (var i = 0; i < data.length; i++) {
- var c = toBinaryTable[data.charCodeAt(i) & 0x7f];
- var padding = (data[i] == base64Pad);
- // Skip illegal characters and whitespace
- if (c == -1) continue;
-
- // Collect data into leftdata, update bitcount
- leftdata = (leftdata << 6) | c;
- leftbits += 6;
-
- // If we have 8 or more bits, append 8 bits to the result
- if (leftbits >= 8) {
- leftbits -= 8;
- // Append if not padding.
- if (!padding)
- result += String.fromCharCode((leftdata >> leftbits) & 0xff);
- leftdata &= (1 << leftbits) - 1;
- }
- }
-
- // If there are any bits left, the base64 string was corrupted
- if (leftbits)
- throw Components.Exception('Corrupted base64 string');
-
- return result;
-}
diff --git a/toolkit/components/url-classifier/tests/mochitest/vp9.webm b/toolkit/components/url-classifier/tests/mochitest/vp9.webm
deleted file mode 100644
index 221877e30..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/vp9.webm
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/url-classifier/tests/mochitest/whitelistFrame.html b/toolkit/components/url-classifier/tests/mochitest/whitelistFrame.html
deleted file mode 100644
index 620416fc7..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/whitelistFrame.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE HTML>
-<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
-<html>
-<head>
-<title></title>
-</head>
-<body>
-
-<script id="badscript" data-touched="not sure" src="http://trackertest.org/tests/toolkit/components/url-classifier/tests/mochitest/evil.js" onload="this.dataset.touched = 'yes';" onerror="this.dataset.touched = 'no';"></script>
-
-<script id="goodscript" data-touched="not sure" src="http://itisatracker.org/tests/toolkit/components/url-classifier/tests/mochitest/good.js" onload="this.dataset.touched = 'yes';" onerror="this.dataset.touched = 'no';"></script>
-
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/mochitest/workerFrame.html b/toolkit/components/url-classifier/tests/mochitest/workerFrame.html
deleted file mode 100644
index 69e8dd007..000000000
--- a/toolkit/components/url-classifier/tests/mochitest/workerFrame.html
+++ /dev/null
@@ -1,65 +0,0 @@
-<html>
-<head>
-<title></title>
-
-<script type="text/javascript">
-
-function startCleanWorker() {
- var worker = new Worker("cleanWorker.js");
-
- worker.onmessage = function(event) {
- if (event.data == "success") {
- window.parent.postMessage("success:blocked importScripts('evilWorker.js')", "*");
- } else {
- window.parent.postMessage("failure:failed to block importScripts('evilWorker.js')", "*");
- }
- window.parent.postMessage("finish", "*");
- };
-
- worker.onerror = function(event) {
- window.parent.postmessage("failure:failed to load cleanWorker.js", "*");
- window.parent.postMessage("finish", "*");
- };
-
- worker.postMessage("");
-}
-
-function startEvilWorker() {
- var worker = new Worker("evilWorker.js");
-
- worker.onmessage = function(event) {
- window.parent.postMessage("failure:failed to block evilWorker.js", "*");
- startUnwantedWorker();
- };
-
- worker.onerror = function(event) {
- window.parent.postMessage("success:blocked evilWorker.js", "*");
- startUnwantedWorker();
- };
-
- worker.postMessage("");
-}
-
-function startUnwantedWorker() {
- var worker = new Worker("unwantedWorker.js");
-
- worker.onmessage = function(event) {
- window.parent.postMessage("failure:failed to block unwantedWorker.js", "*");
- startCleanWorker();
- };
-
- worker.onerror = function(event) {
- window.parent.postMessage("success:blocked unwantedWorker.js", "*");
- startCleanWorker();
- };
-
- worker.postMessage("");
-}
-
-</script>
-
-</head>
-
-<body onload="startEvilWorker()">
-</body>
-</html>
diff --git a/toolkit/components/url-classifier/tests/moz.build b/toolkit/components/url-classifier/tests/moz.build
deleted file mode 100644
index 599727ab9..000000000
--- a/toolkit/components/url-classifier/tests/moz.build
+++ /dev/null
@@ -1,18 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-MOCHITEST_MANIFESTS += ['mochitest/mochitest.ini']
-MOCHITEST_CHROME_MANIFESTS += ['mochitest/chrome.ini']
-XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell.ini']
-
-JAR_MANIFESTS += ['jar.mn']
-
-TESTING_JS_MODULES += [
- 'UrlClassifierTestUtils.jsm',
-]
-
-if CONFIG['ENABLE_TESTS']:
- DIRS += ['gtest']
diff --git a/toolkit/components/url-classifier/tests/unit/.eslintrc.js b/toolkit/components/url-classifier/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/url-classifier/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/url-classifier/tests/unit/data/digest1.chunk b/toolkit/components/url-classifier/tests/unit/data/digest1.chunk
deleted file mode 100644
index 3850373c1..000000000
--- a/toolkit/components/url-classifier/tests/unit/data/digest1.chunk
+++ /dev/null
Binary files differ
diff --git a/toolkit/components/url-classifier/tests/unit/data/digest2.chunk b/toolkit/components/url-classifier/tests/unit/data/digest2.chunk
deleted file mode 100644
index 738c96f6b..000000000
--- a/toolkit/components/url-classifier/tests/unit/data/digest2.chunk
+++ /dev/null
@@ -1,2 +0,0 @@
-a:5:32:32
-_H^a7]=#nmnoQ \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/unit/head_urlclassifier.js b/toolkit/components/url-classifier/tests/unit/head_urlclassifier.js
deleted file mode 100644
index 21849ced7..000000000
--- a/toolkit/components/url-classifier/tests/unit/head_urlclassifier.js
+++ /dev/null
@@ -1,429 +0,0 @@
-//* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- *
-function dumpn(s) {
- dump(s + "\n");
-}
-
-const NS_APP_USER_PROFILE_50_DIR = "ProfD";
-const NS_APP_USER_PROFILE_LOCAL_50_DIR = "ProfLD";
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cu = Components.utils;
-var Cr = Components.results;
-
-Cu.import("resource://testing-common/httpd.js");
-
-do_get_profile();
-
-var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
-
-var iosvc = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
-
-var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(Ci.nsIScriptSecurityManager);
-
-// Disable hashcompleter noise for tests
-var prefBranch = Cc["@mozilla.org/preferences-service;1"].
- getService(Ci.nsIPrefBranch);
-prefBranch.setIntPref("urlclassifier.gethashnoise", 0);
-
-// Enable malware/phishing checking for tests
-prefBranch.setBoolPref("browser.safebrowsing.malware.enabled", true);
-prefBranch.setBoolPref("browser.safebrowsing.blockedURIs.enabled", true);
-prefBranch.setBoolPref("browser.safebrowsing.phishing.enabled", true);
-
-// Enable all completions for tests
-prefBranch.setCharPref("urlclassifier.disallow_completions", "");
-
-// Hash completion timeout
-prefBranch.setIntPref("urlclassifier.gethash.timeout_ms", 5000);
-
-function delFile(name) {
- try {
- // Delete a previously created sqlite file
- var file = dirSvc.get('ProfLD', Ci.nsIFile);
- file.append(name);
- if (file.exists())
- file.remove(false);
- } catch(e) {
- }
-}
-
-function cleanUp() {
- delFile("urlclassifier3.sqlite");
- delFile("safebrowsing/classifier.hashkey");
- delFile("safebrowsing/test-phish-simple.sbstore");
- delFile("safebrowsing/test-malware-simple.sbstore");
- delFile("safebrowsing/test-unwanted-simple.sbstore");
- delFile("safebrowsing/test-block-simple.sbstore");
- delFile("safebrowsing/test-track-simple.sbstore");
- delFile("safebrowsing/test-trackwhite-simple.sbstore");
- delFile("safebrowsing/test-phish-simple.pset");
- delFile("safebrowsing/test-malware-simple.pset");
- delFile("safebrowsing/test-unwanted-simple.pset");
- delFile("safebrowsing/test-block-simple.pset");
- delFile("safebrowsing/test-track-simple.pset");
- delFile("safebrowsing/test-trackwhite-simple.pset");
- delFile("safebrowsing/moz-phish-simple.sbstore");
- delFile("safebrowsing/moz-phish-simple.pset");
- delFile("testLarge.pset");
- delFile("testNoDelta.pset");
-}
-
-// Update uses allTables by default
-var allTables = "test-phish-simple,test-malware-simple,test-unwanted-simple,test-track-simple,test-trackwhite-simple,test-block-simple";
-var mozTables = "moz-phish-simple";
-
-var dbservice = Cc["@mozilla.org/url-classifier/dbservice;1"].getService(Ci.nsIUrlClassifierDBService);
-var streamUpdater = Cc["@mozilla.org/url-classifier/streamupdater;1"]
- .getService(Ci.nsIUrlClassifierStreamUpdater);
-
-
-/*
- * Builds an update from an object that looks like:
- *{ "test-phish-simple" : [{
- * "chunkType" : "a", // 'a' is assumed if not specified
- * "chunkNum" : 1, // numerically-increasing chunk numbers are assumed
- * // if not specified
- * "urls" : [ "foo.com/a", "foo.com/b", "bar.com/" ]
- * }
- */
-
-function buildUpdate(update, hashSize) {
- if (!hashSize) {
- hashSize = 32;
- }
- var updateStr = "n:1000\n";
-
- for (var tableName in update) {
- if (tableName != "")
- updateStr += "i:" + tableName + "\n";
- var chunks = update[tableName];
- for (var j = 0; j < chunks.length; j++) {
- var chunk = chunks[j];
- var chunkType = chunk.chunkType ? chunk.chunkType : 'a';
- var chunkNum = chunk.chunkNum ? chunk.chunkNum : j;
- updateStr += chunkType + ':' + chunkNum + ':' + hashSize;
-
- if (chunk.urls) {
- var chunkData = chunk.urls.join("\n");
- updateStr += ":" + chunkData.length + "\n" + chunkData;
- }
-
- updateStr += "\n";
- }
- }
-
- return updateStr;
-}
-
-function buildPhishingUpdate(chunks, hashSize) {
- return buildUpdate({"test-phish-simple" : chunks}, hashSize);
-}
-
-function buildMalwareUpdate(chunks, hashSize) {
- return buildUpdate({"test-malware-simple" : chunks}, hashSize);
-}
-
-function buildUnwantedUpdate(chunks, hashSize) {
- return buildUpdate({"test-unwanted-simple" : chunks}, hashSize);
-}
-
-function buildBlockedUpdate(chunks, hashSize) {
- return buildUpdate({"test-block-simple" : chunks}, hashSize);
-}
-
-function buildMozPhishingUpdate(chunks, hashSize) {
- return buildUpdate({"moz-phish-simple" : chunks}, hashSize);
-}
-
-function buildBareUpdate(chunks, hashSize) {
- return buildUpdate({"" : chunks}, hashSize);
-}
-
-/**
- * Performs an update of the dbservice manually, bypassing the stream updater
- */
-function doSimpleUpdate(updateText, success, failure) {
- var listener = {
- QueryInterface: function(iid)
- {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIUrlClassifierUpdateObserver))
- return this;
- throw Cr.NS_ERROR_NO_INTERFACE;
- },
-
- updateUrlRequested: function(url) { },
- streamFinished: function(status) { },
- updateError: function(errorCode) { failure(errorCode); },
- updateSuccess: function(requestedTimeout) { success(requestedTimeout); }
- };
-
- dbservice.beginUpdate(listener, allTables);
- dbservice.beginStream("", "");
- dbservice.updateStream(updateText);
- dbservice.finishStream();
- dbservice.finishUpdate();
-}
-
-/**
- * Simulates a failed database update.
- */
-function doErrorUpdate(tables, success, failure) {
- var listener = {
- QueryInterface: function(iid)
- {
- if (iid.equals(Ci.nsISupports) ||
- iid.equals(Ci.nsIUrlClassifierUpdateObserver))
- return this;
- throw Cr.NS_ERROR_NO_INTERFACE;
- },
-
- updateUrlRequested: function(url) { },
- streamFinished: function(status) { },
- updateError: function(errorCode) { success(errorCode); },
- updateSuccess: function(requestedTimeout) { failure(requestedTimeout); }
- };
-
- dbservice.beginUpdate(listener, tables, null);
- dbservice.beginStream("", "");
- dbservice.cancelUpdate();
-}
-
-/**
- * Performs an update of the dbservice using the stream updater and a
- * data: uri
- */
-function doStreamUpdate(updateText, success, failure, downloadFailure) {
- var dataUpdate = "data:," + encodeURIComponent(updateText);
-
- if (!downloadFailure) {
- downloadFailure = failure;
- }
-
- streamUpdater.downloadUpdates(allTables, "", true,
- dataUpdate, success, failure, downloadFailure);
-}
-
-var gAssertions = {
-
-tableData : function(expectedTables, cb)
-{
- dbservice.getTables(function(tables) {
- // rebuild the tables in a predictable order.
- var parts = tables.split("\n");
- while (parts[parts.length - 1] == '') {
- parts.pop();
- }
- parts.sort();
- tables = parts.join("\n");
-
- do_check_eq(tables, expectedTables);
- cb();
- });
-},
-
-checkUrls: function(urls, expected, cb, useMoz = false)
-{
- // work with a copy of the list.
- urls = urls.slice(0);
- var doLookup = function() {
- if (urls.length > 0) {
- var tables = useMoz ? mozTables : allTables;
- var fragment = urls.shift();
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + fragment, null, null), {});
- dbservice.lookup(principal, tables,
- function(arg) {
- do_check_eq(expected, arg);
- doLookup();
- }, true);
- } else {
- cb();
- }
- };
- doLookup();
-},
-
-checkTables: function(url, expected, cb)
-{
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + url, null, null), {});
- dbservice.lookup(principal, allTables, function(tables) {
- // Rebuild tables in a predictable order.
- var parts = tables.split(",");
- while (parts[parts.length - 1] == '') {
- parts.pop();
- }
- parts.sort();
- tables = parts.join(",");
- do_check_eq(tables, expected);
- cb();
- }, true);
-},
-
-urlsDontExist: function(urls, cb)
-{
- this.checkUrls(urls, '', cb);
-},
-
-urlsExist: function(urls, cb)
-{
- this.checkUrls(urls, 'test-phish-simple', cb);
-},
-
-malwareUrlsExist: function(urls, cb)
-{
- this.checkUrls(urls, 'test-malware-simple', cb);
-},
-
-unwantedUrlsExist: function(urls, cb)
-{
- this.checkUrls(urls, 'test-unwanted-simple', cb);
-},
-
-blockedUrlsExist: function(urls, cb)
-{
- this.checkUrls(urls, 'test-block-simple', cb);
-},
-
-mozPhishingUrlsExist: function(urls, cb)
-{
- this.checkUrls(urls, 'moz-phish-simple', cb, true);
-},
-
-subsDontExist: function(urls, cb)
-{
- // XXX: there's no interface for checking items in the subs table
- cb();
-},
-
-subsExist: function(urls, cb)
-{
- // XXX: there's no interface for checking items in the subs table
- cb();
-},
-
-urlExistInMultipleTables: function(data, cb)
-{
- this.checkTables(data["url"], data["tables"], cb);
-}
-
-};
-
-/**
- * Check a set of assertions against the gAssertions table.
- */
-function checkAssertions(assertions, doneCallback)
-{
- var checkAssertion = function() {
- for (var i in assertions) {
- var data = assertions[i];
- delete assertions[i];
- gAssertions[i](data, checkAssertion);
- return;
- }
-
- doneCallback();
- }
-
- checkAssertion();
-}
-
-function updateError(arg)
-{
- do_throw(arg);
-}
-
-// Runs a set of updates, and then checks a set of assertions.
-function doUpdateTest(updates, assertions, successCallback, errorCallback) {
- var errorUpdate = function() {
- checkAssertions(assertions, errorCallback);
- }
-
- var runUpdate = function() {
- if (updates.length > 0) {
- var update = updates.shift();
- doStreamUpdate(update, runUpdate, errorUpdate, null);
- } else {
- checkAssertions(assertions, successCallback);
- }
- }
-
- runUpdate();
-}
-
-var gTests;
-var gNextTest = 0;
-
-function runNextTest()
-{
- if (gNextTest >= gTests.length) {
- do_test_finished();
- return;
- }
-
- dbservice.resetDatabase();
- dbservice.setHashCompleter('test-phish-simple', null);
-
- let test = gTests[gNextTest++];
- dump("running " + test.name + "\n");
- test();
-}
-
-function runTests(tests)
-{
- gTests = tests;
- runNextTest();
-}
-
-var timerArray = [];
-
-function Timer(delay, cb) {
- this.cb = cb;
- var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- timer.initWithCallback(this, delay, timer.TYPE_ONE_SHOT);
- timerArray.push(timer);
-}
-
-Timer.prototype = {
-QueryInterface: function(iid) {
- if (!iid.equals(Ci.nsISupports) && !iid.equals(Ci.nsITimerCallback)) {
- throw Cr.NS_ERROR_NO_INTERFACE;
- }
- return this;
- },
-notify: function(timer) {
- this.cb();
- }
-}
-
-// LFSRgenerator is a 32-bit linear feedback shift register random number
-// generator. It is highly predictable and is not intended to be used for
-// cryptography but rather to allow easier debugging than a test that uses
-// Math.random().
-function LFSRgenerator(seed) {
- // Force |seed| to be a number.
- seed = +seed;
- // LFSR generators do not work with a value of 0.
- if (seed == 0)
- seed = 1;
-
- this._value = seed;
-}
-LFSRgenerator.prototype = {
- // nextNum returns a random unsigned integer of in the range [0,2^|bits|].
- nextNum: function(bits) {
- if (!bits)
- bits = 32;
-
- let val = this._value;
- // Taps are 32, 22, 2 and 1.
- let bit = ((val >>> 0) ^ (val >>> 10) ^ (val >>> 30) ^ (val >>> 31)) & 1;
- val = (val >>> 1) | (bit << 31);
- this._value = val;
-
- return (val >>> (32 - bits));
- },
-};
-
-cleanUp();
diff --git a/toolkit/components/url-classifier/tests/unit/tail_urlclassifier.js b/toolkit/components/url-classifier/tests/unit/tail_urlclassifier.js
deleted file mode 100644
index 37f39d1a8..000000000
--- a/toolkit/components/url-classifier/tests/unit/tail_urlclassifier.js
+++ /dev/null
@@ -1 +0,0 @@
-cleanUp();
diff --git a/toolkit/components/url-classifier/tests/unit/test_addsub.js b/toolkit/components/url-classifier/tests/unit/test_addsub.js
deleted file mode 100644
index 1ed65c7ba..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_addsub.js
+++ /dev/null
@@ -1,488 +0,0 @@
-
-function doTest(updates, assertions)
-{
- doUpdateTest(updates, assertions, runNextTest, updateError);
-}
-
-// Test an add of two urls to a fresh database
-function testSimpleAdds() {
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : addUrls
- };
-
- doTest([update], assertions);
-}
-
-// Same as testSimpleAdds, but make the same-domain URLs come from different
-// chunks.
-function testMultipleAdds() {
- var add1Urls = [ "foo.com/a", "bar.com/c" ];
- var add2Urls = [ "foo.com/b" ];
-
- var update = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls },
- { "chunkNum" : 2,
- "urls" : add2Urls }]);
- var assertions = {
- "tableData" : "test-phish-simple;a:1-2",
- "urlsExist" : add1Urls.concat(add2Urls)
- };
-
- doTest([update], assertions);
-}
-
-// Test that a sub will remove an existing add
-function testSimpleSub()
-{
- var addUrls = ["foo.com/a", "bar.com/b"];
- var subUrls = ["1:foo.com/a"];
-
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1, // adds and subtracts don't share a chunk numbering space
- "urls": addUrls }]);
-
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 50,
- "chunkType" : "s",
- "urls": subUrls }]);
-
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1:s:50",
- "urlsExist" : [ "bar.com/b" ],
- "urlsDontExist": ["foo.com/a" ],
- "subsDontExist" : [ "foo.com/a" ]
- }
-
- doTest([addUpdate, subUpdate], assertions);
-
-}
-
-// Same as testSimpleSub(), but the sub comes in before the add.
-function testSubEmptiesAdd()
-{
- var subUrls = ["1:foo.com/a"];
- var addUrls = ["foo.com/a", "bar.com/b"];
-
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 50,
- "chunkType" : "s",
- "urls": subUrls }]);
-
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls": addUrls }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1:s:50",
- "urlsExist" : [ "bar.com/b" ],
- "urlsDontExist": ["foo.com/a" ],
- "subsDontExist" : [ "foo.com/a" ] // this sub was found, it shouldn't exist anymore
- }
-
- doTest([subUpdate, addUpdate], assertions);
-}
-
-// Very similar to testSubEmptiesAdd, except that the domain entry will
-// still have an item left over that needs to be synced.
-function testSubPartiallyEmptiesAdd()
-{
- var subUrls = ["1:foo.com/a"];
- var addUrls = ["foo.com/a", "foo.com/b", "bar.com/b"];
-
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "s",
- "urls": subUrls }]);
-
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1, // adds and subtracts don't share a chunk numbering space
- "urls": addUrls }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1:s:1",
- "urlsExist" : [ "foo.com/b", "bar.com/b" ],
- "urlsDontExist" : ["foo.com/a" ],
- "subsDontExist" : [ "foo.com/a" ] // this sub was found, it shouldn't exist anymore
- }
-
- doTest([subUpdate, addUpdate], assertions);
-}
-
-// We SHOULD be testing that pending subs are removed using
-// subsDontExist assertions. Since we don't have a good interface for getting
-// at sub entries, we'll verify it by side-effect. Subbing a url once
-// then adding it twice should leave the url intact.
-function testPendingSubRemoved()
-{
- var subUrls = ["1:foo.com/a", "2:foo.com/b"];
- var addUrls = ["foo.com/a", "foo.com/b"];
-
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "s",
- "urls": subUrls }]);
-
- var addUpdate1 = buildPhishingUpdate(
- [{ "chunkNum" : 1, // adds and subtracts don't share a chunk numbering space
- "urls": addUrls }]);
-
- var addUpdate2 = buildPhishingUpdate(
- [{ "chunkNum" : 2,
- "urls": addUrls }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1-2:s:1",
- "urlsExist" : [ "foo.com/a", "foo.com/b" ],
- "subsDontExist" : [ "foo.com/a", "foo.com/b" ] // this sub was found, it shouldn't exist anymore
- }
-
- doTest([subUpdate, addUpdate1, addUpdate2], assertions);
-}
-
-// Make sure that a saved sub is removed when the sub chunk is expired.
-function testPendingSubExpire()
-{
- var subUrls = ["1:foo.com/a", "1:foo.com/b"];
- var addUrls = ["foo.com/a", "foo.com/b"];
-
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "s",
- "urls": subUrls }]);
-
- var expireUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "sd" }]);
-
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1, // adds and subtracts don't share a chunk numbering space
- "urls": addUrls }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : [ "foo.com/a", "foo.com/b" ],
- "subsDontExist" : [ "foo.com/a", "foo.com/b" ] // this sub was expired
- }
-
- doTest([subUpdate, expireUpdate, addUpdate], assertions);
-}
-
-// Make sure that the sub url removes from only the chunk that it specifies
-function testDuplicateAdds()
-{
- var urls = ["foo.com/a"];
-
- var addUpdate1 = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls": urls }]);
- var addUpdate2 = buildPhishingUpdate(
- [{ "chunkNum" : 2,
- "urls": urls }]);
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 3,
- "chunkType" : "s",
- "urls": ["2:foo.com/a"]}]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1-2:s:3",
- "urlsExist" : [ "foo.com/a"],
- "subsDontExist" : [ "foo.com/a"]
- }
-
- doTest([addUpdate1, addUpdate2, subUpdate], assertions);
-}
-
-// Tests a sub which matches some existing adds but leaves others.
-function testSubPartiallyMatches()
-{
- var subUrls = ["foo.com/a"];
- var addUrls = ["1:foo.com/a", "2:foo.com/b"];
-
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls" : addUrls }]);
-
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "s",
- "urls" : addUrls }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1:s:1",
- "urlsDontExist" : ["foo.com/a"],
- "subsDontExist" : ["foo.com/a"],
- "subsExist" : ["foo.com/b"]
- };
-
- doTest([addUpdate, subUpdate], assertions);
-}
-
-// XXX: because subsExist isn't actually implemented, this is the same
-// test as above but with a second add chunk that should fail to be added
-// because of a pending sub chunk.
-function testSubPartiallyMatches2()
-{
- var addUrls = ["foo.com/a"];
- var subUrls = ["1:foo.com/a", "2:foo.com/b"];
- var addUrls2 = ["foo.com/b"];
-
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls" : addUrls }]);
-
- var subUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "s",
- "urls" : subUrls }]);
-
- var addUpdate2 = buildPhishingUpdate(
- [{ "chunkNum" : 2,
- "urls" : addUrls2 }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1-2:s:1",
- "urlsDontExist" : ["foo.com/a", "foo.com/b"],
- "subsDontExist" : ["foo.com/a", "foo.com/b"]
- };
-
- doTest([addUpdate, subUpdate, addUpdate2], assertions);
-}
-
-// Verify that two subs for the same domain but from different chunks
-// match (tests that existing sub entries are properly updated)
-function testSubsDifferentChunks() {
- var subUrls1 = [ "3:foo.com/a" ];
- var subUrls2 = [ "3:foo.com/b" ];
-
- var addUrls = [ "foo.com/a", "foo.com/b", "foo.com/c" ];
-
- var subUpdate1 = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "s",
- "urls": subUrls1 }]);
- var subUpdate2 = buildPhishingUpdate(
- [{ "chunkNum" : 2,
- "chunkType" : "s",
- "urls" : subUrls2 }]);
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 3,
- "urls" : addUrls }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:3:s:1-2",
- "urlsExist" : [ "foo.com/c" ],
- "urlsDontExist" : [ "foo.com/a", "foo.com/b" ],
- "subsDontExist" : [ "foo.com/a", "foo.com/b" ]
- };
-
- doTest([subUpdate1, subUpdate2, addUpdate], assertions);
-}
-
-// for bug 534079
-function testSubsDifferentChunksSameHostId() {
- var subUrls1 = [ "1:foo.com/a" ];
- var subUrls2 = [ "1:foo.com/b", "2:foo.com/c" ];
-
- var addUrls = [ "foo.com/a", "foo.com/b" ];
- var addUrls2 = [ "foo.com/c" ];
-
- var subUpdate1 = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "chunkType" : "s",
- "urls": subUrls1 }]);
- var subUpdate2 = buildPhishingUpdate(
- [{ "chunkNum" : 2,
- "chunkType" : "s",
- "urls" : subUrls2 }]);
-
- var addUpdate = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls" : addUrls }]);
- var addUpdate2 = buildPhishingUpdate(
- [{ "chunkNum" : 2,
- "urls" : addUrls2 }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1-2:s:1-2",
- "urlsDontExist" : [ "foo.com/c", "foo.com/b", "foo.com/a", ],
- };
-
- doTest([addUpdate, addUpdate2, subUpdate1, subUpdate2], assertions);
-}
-
-// Test lists of expired chunks
-function testExpireLists() {
- var addUpdate = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : [ "foo.com/a" ]
- },
- { "chunkNum" : 3,
- "urls" : [ "bar.com/a" ]
- },
- { "chunkNum" : 4,
- "urls" : [ "baz.com/a" ]
- },
- { "chunkNum" : 5,
- "urls" : [ "blah.com/a" ]
- },
- ]);
- var subUpdate = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "chunkType" : "s",
- "urls" : [ "50:foo.com/1" ]
- },
- { "chunkNum" : 2,
- "chunkType" : "s",
- "urls" : [ "50:bar.com/1" ]
- },
- { "chunkNum" : 3,
- "chunkType" : "s",
- "urls" : [ "50:baz.com/1" ]
- },
- { "chunkNum" : 5,
- "chunkType" : "s",
- "urls" : [ "50:blah.com/1" ]
- },
- ]);
-
- var expireUpdate = buildPhishingUpdate(
- [ { "chunkType" : "ad:1,3-5" },
- { "chunkType" : "sd:1-3,5" }]);
-
- var assertions = {
- // "tableData" : "test-phish-simple;"
- "tableData": ""
- };
-
- doTest([addUpdate, subUpdate, expireUpdate], assertions);
-}
-
-// Test a duplicate add chunk.
-function testDuplicateAddChunks() {
- var addUrls1 = [ "foo.com/a" ];
- var addUrls2 = [ "bar.com/b" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls1
- },
- { "chunkNum" : 1,
- "urls" : addUrls2
- }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : addUrls1,
- "urlsDontExist" : addUrls2
- };
-
- doTest([update], assertions);
-}
-
-// This test is a bit tricky. We want to test that an add removes all
-// subs with the same add chunk id, even if there is no match. To do
-// that we need to add the same add chunk twice, with an expiration
-// in the middle. This would be easier if subsDontExist actually
-// worked...
-function testExpireWholeSub()
-{
- var subUrls = ["1:foo.com/a"];
-
- var update = buildPhishingUpdate(
- [{ "chunkNum" : 5,
- "chunkType" : "s",
- "urls" : subUrls
- },
- // empty add chunk should still cause foo.com/a to go away.
- { "chunkNum" : 1,
- "urls" : []
- },
- // and now adding chunk 1 again with foo.com/a should succeed,
- // because the sub should have been expired with the empty
- // add chunk.
-
- // we need to expire this chunk to let us add chunk 1 again.
- {
- "chunkType" : "ad:1"
- },
- { "chunkNum" : 1,
- "urls" : [ "foo.com/a" ]
- }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1:s:5",
- "urlsExist" : ["foo.com/a"]
- };
-
- doTest([update], assertions);
-}
-
-
-// This test is roughly the opposite of testExpireWholeSub(). We add
-// the empty add first, and make sure that it prevents a sub for that
-// add from being applied.
-function testPreventWholeSub()
-{
- var subUrls = ["1:foo.com/a"];
-
- var update = buildPhishingUpdate(
- [ // empty add chunk should cause foo.com/a to not be saved
- { "chunkNum" : 1,
- "urls" : []
- },
- { "chunkNum" : 5,
- "chunkType" : "s",
- "urls" : subUrls
- },
- // and now adding chunk 1 again with foo.com/a should succeed,
- // because the sub should have been expired with the empty
- // add chunk.
-
- // we need to expire this chunk to let us add chunk 1 again.
- {
- "chunkType" : "ad:1"
- },
- { "chunkNum" : 1,
- "urls" : [ "foo.com/a" ]
- }]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1:s:5",
- "urlsExist" : ["foo.com/a"]
- };
-
- doTest([update], assertions);
-}
-
-function run_test()
-{
- runTests([
- testSimpleAdds,
- testMultipleAdds,
- testSimpleSub,
- testSubEmptiesAdd,
- testSubPartiallyEmptiesAdd,
- testPendingSubRemoved,
- testPendingSubExpire,
- testDuplicateAdds,
- testSubPartiallyMatches,
- testSubPartiallyMatches2,
- testSubsDifferentChunks,
- testSubsDifferentChunksSameHostId,
- testExpireLists
- ]);
-}
-
-do_test_pending();
diff --git a/toolkit/components/url-classifier/tests/unit/test_backoff.js b/toolkit/components/url-classifier/tests/unit/test_backoff.js
deleted file mode 100644
index 365568c47..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_backoff.js
+++ /dev/null
@@ -1,89 +0,0 @@
-// Some unittests (e.g., paste into JS shell)
-var jslib = Cc["@mozilla.org/url-classifier/jslib;1"].
- getService().wrappedJSObject;
-var _Datenow = jslib.Date.now;
-function setNow(time) {
- jslib.Date.now = function() {
- return time;
- }
-}
-
-function run_test() {
- // 3 errors, 1ms retry period, max 3 requests per ten milliseconds,
- // 5ms backoff interval, 19ms max delay
- var rb = new jslib.RequestBackoff(3, 1, 3, 10, 5, 19);
- setNow(1);
- rb.noteServerResponse(200);
- do_check_true(rb.canMakeRequest());
- setNow(2);
- do_check_true(rb.canMakeRequest());
-
- // First error should trigger a 1ms delay
- rb.noteServerResponse(500);
- do_check_false(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 3);
- setNow(3);
- do_check_true(rb.canMakeRequest());
-
- // Second error should also trigger a 1ms delay
- rb.noteServerResponse(500);
- do_check_false(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 4);
- setNow(4);
- do_check_true(rb.canMakeRequest());
-
- // Third error should trigger a 5ms backoff
- rb.noteServerResponse(500);
- do_check_false(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 9);
- setNow(9);
- do_check_true(rb.canMakeRequest());
-
- // Trigger backoff again
- rb.noteServerResponse(503);
- do_check_false(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 19);
- setNow(19);
- do_check_true(rb.canMakeRequest());
-
- // Trigger backoff a third time and hit max timeout
- rb.noteServerResponse(302);
- do_check_false(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 38);
- setNow(38);
- do_check_true(rb.canMakeRequest());
-
- // One more backoff, should still be at the max timeout
- rb.noteServerResponse(400);
- do_check_false(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 57);
- setNow(57);
- do_check_true(rb.canMakeRequest());
-
- // Request goes through
- rb.noteServerResponse(200);
- do_check_true(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 0);
- setNow(58);
- rb.noteServerResponse(500);
-
- // Another error, should trigger a 1ms backoff
- do_check_false(rb.canMakeRequest());
- do_check_eq(rb.nextRequestTime_, 59);
-
- setNow(59);
- do_check_true(rb.canMakeRequest());
-
- setNow(200);
- rb.noteRequest();
- setNow(201);
- rb.noteRequest();
- setNow(202);
- do_check_true(rb.canMakeRequest());
- rb.noteRequest();
- do_check_false(rb.canMakeRequest());
- setNow(211);
- do_check_true(rb.canMakeRequest());
-
- jslib.Date.now = _Datenow;
-}
diff --git a/toolkit/components/url-classifier/tests/unit/test_bug1274685_unowned_list.js b/toolkit/components/url-classifier/tests/unit/test_bug1274685_unowned_list.js
deleted file mode 100644
index 037bc7b88..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_bug1274685_unowned_list.js
+++ /dev/null
@@ -1,32 +0,0 @@
-Cu.import("resource://gre/modules/SafeBrowsing.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://testing-common/AppInfo.jsm");
-
-// 'Cc["@mozilla.org/xre/app-info;1"]' for xpcshell has no nsIXULAppInfo
-// so that we have to update it to make nsURLFormatter.js happy.
-// (SafeBrowsing.init() will indirectly use nsURLFormatter.js)
-updateAppInfo();
-
-function run_test() {
- SafeBrowsing.init();
-
- let origList = Services.prefs.getCharPref("browser.safebrowsing.provider.google.lists");
-
- // Remove 'goog-malware-shavar' from the original.
- let trimmedList = origList.replace('goog-malware-shavar,', '');
- Services.prefs.setCharPref("browser.safebrowsing.provider.google.lists", trimmedList);
-
- try {
- // Bug 1274685 - Unowned Safe Browsing tables break list updates
- //
- // If SafeBrowsing.registerTableWithURLs() doesn't check if
- // a provider is found before registering table, an exception
- // will be thrown while accessing a null object.
- //
- SafeBrowsing.registerTables();
- } catch (e) {
- ok(false, 'Exception thrown due to ' + e.toString());
- }
-
- Services.prefs.setCharPref("browser.safebrowsing.provider.google.lists", origList);
-}
diff --git a/toolkit/components/url-classifier/tests/unit/test_dbservice.js b/toolkit/components/url-classifier/tests/unit/test_dbservice.js
deleted file mode 100644
index 4b01e7016..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_dbservice.js
+++ /dev/null
@@ -1,314 +0,0 @@
-var checkUrls = [];
-var checkExpect;
-
-var chunk1Urls = [
- "test.com/aba",
- "test.com/foo/bar",
- "foo.bar.com/a/b/c"
-];
-var chunk1 = chunk1Urls.join("\n");
-
-var chunk2Urls = [
- "blah.com/a",
- "baz.com/",
- "255.255.0.1/",
- "www.foo.com/test2?param=1"
-];
-var chunk2 = chunk2Urls.join("\n");
-
-var chunk3Urls = [
- "test.com/a",
- "foo.bar.com/a",
- "blah.com/a",
- ];
-var chunk3 = chunk3Urls.join("\n");
-
-var chunk3SubUrls = [
- "1:test.com/a",
- "1:foo.bar.com/a",
- "2:blah.com/a" ];
-var chunk3Sub = chunk3SubUrls.join("\n");
-
-var chunk4Urls = [
- "a.com/b",
- "b.com/c",
- ];
-var chunk4 = chunk4Urls.join("\n");
-
-var chunk5Urls = [
- "d.com/e",
- "f.com/g",
- ];
-var chunk5 = chunk5Urls.join("\n");
-
-var chunk6Urls = [
- "h.com/i",
- "j.com/k",
- ];
-var chunk6 = chunk6Urls.join("\n");
-
-var chunk7Urls = [
- "l.com/m",
- "n.com/o",
- ];
-var chunk7 = chunk7Urls.join("\n");
-
-// we are going to add chunks 1, 2, 4, 5, and 6 to phish-simple,
-// chunk 2 to malware-simple, and chunk 3 to unwanted-simple,
-// and chunk 7 to block-simple.
-// Then we'll remove the urls in chunk3 from phish-simple, then
-// expire chunk 1 and chunks 4-7 from phish-simple.
-var phishExpected = {};
-var phishUnexpected = {};
-var malwareExpected = {};
-var unwantedExpected = {};
-var blockedExpected = {};
-for (var i = 0; i < chunk2Urls.length; i++) {
- phishExpected[chunk2Urls[i]] = true;
- malwareExpected[chunk2Urls[i]] = true;
-}
-for (var i = 0; i < chunk3Urls.length; i++) {
- unwantedExpected[chunk3Urls[i]] = true;
- delete phishExpected[chunk3Urls[i]];
- phishUnexpected[chunk3Urls[i]] = true;
-}
-for (var i = 0; i < chunk1Urls.length; i++) {
- // chunk1 urls are expired
- phishUnexpected[chunk1Urls[i]] = true;
-}
-for (var i = 0; i < chunk4Urls.length; i++) {
- // chunk4 urls are expired
- phishUnexpected[chunk4Urls[i]] = true;
-}
-for (var i = 0; i < chunk5Urls.length; i++) {
- // chunk5 urls are expired
- phishUnexpected[chunk5Urls[i]] = true;
-}
-for (var i = 0; i < chunk6Urls.length; i++) {
- // chunk6 urls are expired
- phishUnexpected[chunk6Urls[i]] = true;
-}
-for (var i = 0; i < chunk7Urls.length; i++) {
- blockedExpected[chunk7Urls[i]] = true;
- // chunk7 urls are expired
- phishUnexpected[chunk7Urls[i]] = true;
-}
-
-// Check that the entries hit based on sub-parts
-phishExpected["baz.com/foo/bar"] = true;
-phishExpected["foo.bar.baz.com/foo"] = true;
-phishExpected["bar.baz.com/"] = true;
-
-var numExpecting;
-
-function testFailure(arg) {
- do_throw(arg);
-}
-
-function checkNoHost()
-{
- // Looking up a no-host uri such as a data: uri should throw an exception.
- var exception;
- try {
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("data:text/html,<b>test</b>", null, null), {});
- dbservice.lookup(principal, allTables);
-
- exception = false;
- } catch(e) {
- exception = true;
- }
- do_check_true(exception);
-
- do_test_finished();
-}
-
-function tablesCallbackWithoutSub(tables)
-{
- var parts = tables.split("\n");
- parts.sort();
-
- // there's a leading \n here because splitting left an empty string
- // after the trailing newline, which will sort first
- do_check_eq(parts.join("\n"),
- "\ntest-block-simple;a:1\ntest-malware-simple;a:1\ntest-phish-simple;a:2\ntest-unwanted-simple;a:1");
-
- checkNoHost();
-}
-
-
-function expireSubSuccess(result) {
- dbservice.getTables(tablesCallbackWithoutSub);
-}
-
-function tablesCallbackWithSub(tables)
-{
- var parts = tables.split("\n");
- parts.sort();
-
- // there's a leading \n here because splitting left an empty string
- // after the trailing newline, which will sort first
- do_check_eq(parts.join("\n"),
- "\ntest-block-simple;a:1\ntest-malware-simple;a:1\ntest-phish-simple;a:2:s:3\ntest-unwanted-simple;a:1");
-
- // verify that expiring a sub chunk removes its name from the list
- var data =
- "n:1000\n" +
- "i:test-phish-simple\n" +
- "sd:3\n";
-
- doSimpleUpdate(data, expireSubSuccess, testFailure);
-}
-
-function checkChunksWithSub()
-{
- dbservice.getTables(tablesCallbackWithSub);
-}
-
-function checkDone() {
- if (--numExpecting == 0)
- checkChunksWithSub();
-}
-
-function phishExists(result) {
- dumpn("phishExists: " + result);
- try {
- do_check_true(result.indexOf("test-phish-simple") != -1);
- } finally {
- checkDone();
- }
-}
-
-function phishDoesntExist(result) {
- dumpn("phishDoesntExist: " + result);
- try {
- do_check_true(result.indexOf("test-phish-simple") == -1);
- } finally {
- checkDone();
- }
-}
-
-function malwareExists(result) {
- dumpn("malwareExists: " + result);
-
- try {
- do_check_true(result.indexOf("test-malware-simple") != -1);
- } finally {
- checkDone();
- }
-}
-
-function unwantedExists(result) {
- dumpn("unwantedExists: " + result);
-
- try {
- do_check_true(result.indexOf("test-unwanted-simple") != -1);
- } finally {
- checkDone();
- }
-}
-
-function blockedExists(result) {
- dumpn("blockedExists: " + result);
-
- try {
- do_check_true(result.indexOf("test-block-simple") != -1);
- } finally {
- checkDone();
- }
-}
-
-function checkState()
-{
- numExpecting = 0;
-
-
- for (var key in phishExpected) {
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + key, null, null), {});
- dbservice.lookup(principal, allTables, phishExists, true);
- numExpecting++;
- }
-
- for (var key in phishUnexpected) {
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + key, null, null), {});
- dbservice.lookup(principal, allTables, phishDoesntExist, true);
- numExpecting++;
- }
-
- for (var key in malwareExpected) {
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + key, null, null), {});
- dbservice.lookup(principal, allTables, malwareExists, true);
- numExpecting++;
- }
-
- for (var key in unwantedExpected) {
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + key, null, null), {});
- dbservice.lookup(principal, allTables, unwantedExists, true);
- numExpecting++;
- }
-
- for (var key in blockedExpected) {
- var principal = secMan.createCodebasePrincipal(iosvc.newURI("http://" + key, null, null), {});
- dbservice.lookup(principal, allTables, blockedExists, true);
- numExpecting++;
- }
-}
-
-function testSubSuccess(result)
-{
- do_check_eq(result, "1000");
- checkState();
-}
-
-function do_subs() {
- var data =
- "n:1000\n" +
- "i:test-phish-simple\n" +
- "s:3:32:" + chunk3Sub.length + "\n" +
- chunk3Sub + "\n" +
- "ad:1\n" +
- "ad:4-6\n";
-
- doSimpleUpdate(data, testSubSuccess, testFailure);
-}
-
-function testAddSuccess(arg) {
- do_check_eq(arg, "1000");
-
- do_subs();
-}
-
-function do_adds() {
- // This test relies on the fact that only -regexp tables are ungzipped,
- // and only -hash tables are assumed to be pre-md5'd. So we use
- // a 'simple' table type to get simple hostname-per-line semantics.
-
- var data =
- "n:1000\n" +
- "i:test-phish-simple\n" +
- "a:1:32:" + chunk1.length + "\n" +
- chunk1 + "\n" +
- "a:2:32:" + chunk2.length + "\n" +
- chunk2 + "\n" +
- "a:4:32:" + chunk4.length + "\n" +
- chunk4 + "\n" +
- "a:5:32:" + chunk5.length + "\n" +
- chunk5 + "\n" +
- "a:6:32:" + chunk6.length + "\n" +
- chunk6 + "\n" +
- "i:test-malware-simple\n" +
- "a:1:32:" + chunk2.length + "\n" +
- chunk2 + "\n" +
- "i:test-unwanted-simple\n" +
- "a:1:32:" + chunk3.length + "\n" +
- chunk3 + "\n" +
- "i:test-block-simple\n" +
- "a:1:32:" + chunk7.length + "\n" +
- chunk7 + "\n";
-
- doSimpleUpdate(data, testAddSuccess, testFailure);
-}
-
-function run_test() {
- do_adds();
- do_test_pending();
-}
diff --git a/toolkit/components/url-classifier/tests/unit/test_digest256.js b/toolkit/components/url-classifier/tests/unit/test_digest256.js
deleted file mode 100644
index 6ae652915..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_digest256.js
+++ /dev/null
@@ -1,147 +0,0 @@
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Promise",
- "resource://gre/modules/Promise.jsm");
-// Global test server for serving safebrowsing updates.
-var gHttpServ = null;
-// Global nsIUrlClassifierDBService
-var gDbService = Cc["@mozilla.org/url-classifier/dbservice;1"]
- .getService(Ci.nsIUrlClassifierDBService);
-// Security manager for creating nsIPrincipals from URIs
-var gSecMan = Cc["@mozilla.org/scriptsecuritymanager;1"]
- .getService(Ci.nsIScriptSecurityManager);
-
-// A map of tables to arrays of update redirect urls.
-var gTables = {};
-
-// Construct an update from a file.
-function readFileToString(aFilename) {
- let f = do_get_file(aFilename);
- let stream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- stream.init(f, -1, 0, 0);
- let buf = NetUtil.readInputStreamToString(stream, stream.available());
- return buf;
-}
-
-// Registers a table for which to serve update chunks. Returns a promise that
-// resolves when that chunk has been downloaded.
-function registerTableUpdate(aTable, aFilename) {
- let deferred = Promise.defer();
- // If we haven't been given an update for this table yet, add it to the map
- if (!(aTable in gTables)) {
- gTables[aTable] = [];
- }
-
- // The number of chunks associated with this table.
- let numChunks = gTables[aTable].length + 1;
- let redirectPath = "/" + aTable + "-" + numChunks;
- let redirectUrl = "localhost:4444" + redirectPath;
-
- // Store redirect url for that table so we can return it later when we
- // process an update request.
- gTables[aTable].push(redirectUrl);
-
- gHttpServ.registerPathHandler(redirectPath, function(request, response) {
- do_print("Mock safebrowsing server handling request for " + redirectPath);
- let contents = readFileToString(aFilename);
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(contents, contents.length);
- deferred.resolve(contents);
- });
- return deferred.promise;
-}
-
-// Construct a response with redirect urls.
-function processUpdateRequest() {
- let response = "n:1000\n";
- for (let table in gTables) {
- response += "i:" + table + "\n";
- for (let i = 0; i < gTables[table].length; ++i) {
- response += "u:" + gTables[table][i] + "\n";
- }
- }
- do_print("Returning update response: " + response);
- return response;
-}
-
-// Set up our test server to handle update requests.
-function run_test() {
- gHttpServ = new HttpServer();
- gHttpServ.registerDirectory("/", do_get_cwd());
-
- gHttpServ.registerPathHandler("/downloads", function(request, response) {
- let buf = NetUtil.readInputStreamToString(request.bodyInputStream,
- request.bodyInputStream.available());
- let blob = processUpdateRequest();
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(blob, blob.length);
- });
-
- gHttpServ.start(4444);
- run_next_test();
-}
-
-function createURI(s) {
- let service = Cc["@mozilla.org/network/io-service;1"]
- .getService(Ci.nsIIOService);
- return service.newURI(s, null, null);
-}
-
-// Just throw if we ever get an update or download error.
-function handleError(aEvent) {
- do_throw("We didn't download or update correctly: " + aEvent);
-}
-
-add_test(function test_update() {
- let streamUpdater = Cc["@mozilla.org/url-classifier/streamupdater;1"]
- .getService(Ci.nsIUrlClassifierStreamUpdater);
-
- // Load up some update chunks for the safebrowsing server to serve.
- registerTableUpdate("goog-downloadwhite-digest256", "data/digest1.chunk");
- registerTableUpdate("goog-downloadwhite-digest256", "data/digest2.chunk");
-
- // Download some updates, and don't continue until the downloads are done.
- function updateSuccess(aEvent) {
- // Timeout of n:1000 is constructed in processUpdateRequest above and
- // passed back in the callback in nsIUrlClassifierStreamUpdater on success.
- do_check_eq("1000", aEvent);
- do_print("All data processed");
- run_next_test();
- }
- streamUpdater.downloadUpdates(
- "goog-downloadwhite-digest256",
- "goog-downloadwhite-digest256;\n",
- true,
- "http://localhost:4444/downloads",
- updateSuccess, handleError, handleError);
-});
-
-add_test(function test_url_not_whitelisted() {
- let uri = createURI("http://example.com");
- let principal = gSecMan.createCodebasePrincipal(uri, {});
- gDbService.lookup(principal, "goog-downloadwhite-digest256",
- function handleEvent(aEvent) {
- // This URI is not on any lists.
- do_check_eq("", aEvent);
- run_next_test();
- });
-});
-
-add_test(function test_url_whitelisted() {
- // Hash of "whitelisted.com/" (canonicalized URL) is:
- // 93CA5F48E15E9861CD37C2D95DB43D23CC6E6DE5C3F8FA6E8BE66F97CC518907
- let uri = createURI("http://whitelisted.com");
- let principal = gSecMan.createCodebasePrincipal(uri, {});
- gDbService.lookup(principal, "goog-downloadwhite-digest256",
- function handleEvent(aEvent) {
- do_check_eq("goog-downloadwhite-digest256", aEvent);
- run_next_test();
- });
-});
diff --git a/toolkit/components/url-classifier/tests/unit/test_hashcompleter.js b/toolkit/components/url-classifier/tests/unit/test_hashcompleter.js
deleted file mode 100644
index 40fafd923..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_hashcompleter.js
+++ /dev/null
@@ -1,403 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This test ensures that the nsIUrlClassifierHashCompleter works as expected
-// and simulates an HTTP server to provide completions.
-//
-// In order to test completions, each group of completions sent as one request
-// to the HTTP server is called a completion set. There is currently not
-// support for multiple requests being sent to the server at once, in this test.
-// This tests makes a request for each element of |completionSets|, waits for
-// a response and then moves to the next element.
-// Each element of |completionSets| is an array of completions, and each
-// completion is an object with the properties:
-// hash: complete hash for the completion. Automatically right-padded
-// to be COMPLETE_LENGTH.
-// expectCompletion: boolean indicating whether the server should respond
-// with a full hash.
-// forceServerError: boolean indicating whether the server should respond
-// with a 503.
-// table: name of the table that the hash corresponds to. Only needs to be set
-// if a completion is expected.
-// chunkId: positive integer corresponding to the chunk that the hash belongs
-// to. Only needs to be set if a completion is expected.
-// multipleCompletions: boolean indicating whether the server should respond
-// with more than one full hash. If this is set to true
-// then |expectCompletion| must also be set to true and
-// |hash| must have the same prefix as all |completions|.
-// completions: an array of completions (objects with a hash, table and
-// chunkId property as described above). This property is only
-// used when |multipleCompletions| is set to true.
-
-// Basic prefixes with 2/3 completions.
-var basicCompletionSet = [
- {
- hash: "abcdefgh",
- expectCompletion: true,
- table: "test",
- chunkId: 1234,
- },
- {
- hash: "1234",
- expectCompletion: false,
- },
- {
- hash: "\u0000\u0000\u000012312",
- expectCompletion: true,
- table: "test",
- chunkId: 1234,
- }
-];
-
-// 3 prefixes with 0 completions to test HashCompleter handling a 204 status.
-var falseCompletionSet = [
- {
- hash: "1234",
- expectCompletion: false,
- },
- {
- hash: "",
- expectCompletion: false,
- },
- {
- hash: "abc",
- expectCompletion: false,
- }
-];
-
-// The current implementation (as of Mar 2011) sometimes sends duplicate
-// entries to HashCompleter and even expects responses for duplicated entries.
-var dupedCompletionSet = [
- {
- hash: "1234",
- expectCompletion: true,
- table: "test",
- chunkId: 1,
- },
- {
- hash: "5678",
- expectCompletion: false,
- table: "test2",
- chunkId: 2,
- },
- {
- hash: "1234",
- expectCompletion: true,
- table: "test",
- chunkId: 1,
- },
- {
- hash: "5678",
- expectCompletion: false,
- table: "test2",
- chunkId: 2
- }
-];
-
-// It is possible for a hash completion request to return with multiple
-// completions, the HashCompleter should return all of these.
-var multipleResponsesCompletionSet = [
- {
- hash: "1234",
- expectCompletion: true,
- multipleCompletions: true,
- completions: [
- {
- hash: "123456",
- table: "test1",
- chunkId: 3,
- },
- {
- hash: "123478",
- table: "test2",
- chunkId: 4,
- }
- ],
- }
-];
-
-function buildCompletionRequest(aCompletionSet) {
- let prefixes = [];
- let prefixSet = new Set();
- aCompletionSet.forEach(s => {
- let prefix = s.hash.substring(0, 4);
- if (prefixSet.has(prefix)) {
- return;
- }
- prefixSet.add(prefix);
- prefixes.push(prefix);
- });
- return 4 + ":" + (4 * prefixes.length) + "\n" + prefixes.join("");
-}
-
-function parseCompletionRequest(aRequest) {
- // Format: [partial_length]:[num_of_prefix * partial_length]\n[prefixes_data]
-
- let tokens = /(\d):(\d+)/.exec(aRequest);
- if (tokens.length < 3) {
- dump("Request format error.");
- return null;
- }
-
- let partialLength = parseInt(tokens[1]);
- let payloadLength = parseInt(tokens[2]);
-
- let payloadStart = tokens[1].length + // partial length
- 1 + // ':'
- tokens[2].length + // payload length
- 1; // '\n'
-
- let prefixSet = [];
- for (let i = payloadStart; i < aRequest.length; i += partialLength) {
- let prefix = aRequest.substr(i, partialLength);
- if (prefix.length !== partialLength) {
- dump("Header info not correct: " + aRequest.substr(0, payloadStart));
- return null;
- }
- prefixSet.push(prefix);
- }
- prefixSet.sort();
-
- return prefixSet;
-}
-
-// Compare the requests in string format.
-function compareCompletionRequest(aRequest1, aRequest2) {
- let prefixSet1 = parseCompletionRequest(aRequest1);
- let prefixSet2 = parseCompletionRequest(aRequest2);
-
- return equal(JSON.stringify(prefixSet1), JSON.stringify(prefixSet2));
-}
-
-// The fifth completion set is added at runtime by getRandomCompletionSet.
-// Each completion in the set only has one response and its purpose is to
-// provide an easy way to test the HashCompleter handling an arbitrarily large
-// completion set (determined by SIZE_OF_RANDOM_SET).
-const SIZE_OF_RANDOM_SET = 16;
-function getRandomCompletionSet(forceServerError) {
- let completionSet = [];
- let hashPrefixes = [];
-
- let seed = Math.floor(Math.random() * Math.pow(2, 32));
- dump("Using seed of " + seed + " for random completion set.\n");
- let rand = new LFSRgenerator(seed);
-
- for (let i = 0; i < SIZE_OF_RANDOM_SET; i++) {
- let completion = { expectCompletion: false, forceServerError: false, _finished: false };
-
- // Generate a random 256 bit hash. First we get a random number and then
- // convert it to a string.
- let hash;
- let prefix;
- do {
- hash = "";
- let length = 1 + rand.nextNum(5);
- for (let i = 0; i < length; i++)
- hash += String.fromCharCode(rand.nextNum(8));
- prefix = hash.substring(0,4);
- } while (hashPrefixes.indexOf(prefix) != -1);
-
- hashPrefixes.push(prefix);
- completion.hash = hash;
-
- if (!forceServerError) {
- completion.expectCompletion = rand.nextNum(1) == 1;
- } else {
- completion.forceServerError = true;
- }
- if (completion.expectCompletion) {
- // Generate a random alpha-numeric string of length at most 6 for the
- // table name.
- completion.table = (rand.nextNum(31)).toString(36);
-
- completion.chunkId = rand.nextNum(16);
- }
- completionSet.push(completion);
- }
-
- return completionSet;
-}
-
-var completionSets = [basicCompletionSet, falseCompletionSet,
- dupedCompletionSet, multipleResponsesCompletionSet];
-var currentCompletionSet = -1;
-var finishedCompletions = 0;
-
-const SERVER_PORT = 8080;
-const SERVER_PATH = "/hash-completer";
-var server;
-
-// Completion hashes are automatically right-padded with null chars to have a
-// length of COMPLETE_LENGTH.
-// Taken from nsUrlClassifierDBService.h
-const COMPLETE_LENGTH = 32;
-
-var completer = Cc["@mozilla.org/url-classifier/hashcompleter;1"].
- getService(Ci.nsIUrlClassifierHashCompleter);
-
-var gethashUrl;
-
-// Expected highest completion set for which the server sends a response.
-var expectedMaxServerCompletionSet = 0;
-var maxServerCompletionSet = 0;
-
-function run_test() {
- // Generate a random completion set that return successful responses.
- completionSets.push(getRandomCompletionSet(false));
- // We backoff after receiving an error, so requests shouldn't reach the
- // server after that.
- expectedMaxServerCompletionSet = completionSets.length;
- // Generate some completion sets that return 503s.
- for (let j = 0; j < 10; ++j) {
- completionSets.push(getRandomCompletionSet(true));
- }
-
- // Fix up the completions before running the test.
- for (let completionSet of completionSets) {
- for (let completion of completionSet) {
- // Pad the right of each |hash| so that the length is COMPLETE_LENGTH.
- if (completion.multipleCompletions) {
- for (let responseCompletion of completion.completions) {
- let numChars = COMPLETE_LENGTH - responseCompletion.hash.length;
- responseCompletion.hash += (new Array(numChars + 1)).join("\u0000");
- }
- }
- else {
- let numChars = COMPLETE_LENGTH - completion.hash.length;
- completion.hash += (new Array(numChars + 1)).join("\u0000");
- }
- }
- }
- do_test_pending();
-
- server = new HttpServer();
- server.registerPathHandler(SERVER_PATH, hashCompleterServer);
-
- server.start(-1);
- const SERVER_PORT = server.identity.primaryPort;
-
- gethashUrl = "http://localhost:" + SERVER_PORT + SERVER_PATH;
-
- runNextCompletion();
-}
-
-function runNextCompletion() {
- // The server relies on currentCompletionSet to send the correct response, so
- // don't increment it until we start the new set of callbacks.
- currentCompletionSet++;
- if (currentCompletionSet >= completionSets.length) {
- finish();
- return;
- }
-
- dump("Now on completion set index " + currentCompletionSet + ", length " +
- completionSets[currentCompletionSet].length + "\n");
- // Number of finished completions for this set.
- finishedCompletions = 0;
- for (let completion of completionSets[currentCompletionSet]) {
- completer.complete(completion.hash.substring(0,4), gethashUrl,
- (new callback(completion)));
- }
-}
-
-function hashCompleterServer(aRequest, aResponse) {
- let stream = aRequest.bodyInputStream;
- let wrapperStream = Cc["@mozilla.org/binaryinputstream;1"].
- createInstance(Ci.nsIBinaryInputStream);
- wrapperStream.setInputStream(stream);
-
- let len = stream.available();
- let data = wrapperStream.readBytes(len);
-
- // Check if we got the expected completion request.
- let expectedRequest = buildCompletionRequest(completionSets[currentCompletionSet]);
- compareCompletionRequest(data, expectedRequest);
-
- // To avoid a response with duplicate hash completions, we keep track of all
- // completed hash prefixes so far.
- let completedHashes = [];
- let responseText = "";
-
- function responseForCompletion(x) {
- return x.table + ":" + x.chunkId + ":" + x.hash.length + "\n" + x.hash;
- }
- // As per the spec, a server should response with a 204 if there are no
- // full-length hashes that match the prefixes.
- let httpStatus = 204;
- for (let completion of completionSets[currentCompletionSet]) {
- if (completion.expectCompletion &&
- (completedHashes.indexOf(completion.hash) == -1)) {
- completedHashes.push(completion.hash);
-
- if (completion.multipleCompletions)
- responseText += completion.completions.map(responseForCompletion).join("");
- else
- responseText += responseForCompletion(completion);
- }
- if (completion.forceServerError) {
- httpStatus = 503;
- }
- }
-
- dump("Server sending response for " + currentCompletionSet + "\n");
- maxServerCompletionSet = currentCompletionSet;
- if (responseText && httpStatus != 503) {
- aResponse.write(responseText);
- } else {
- aResponse.setStatusLine(null, httpStatus, null);
- }
-}
-
-
-function callback(completion) {
- this._completion = completion;
-}
-
-callback.prototype = {
- completion: function completion(hash, table, chunkId, trusted) {
- do_check_true(this._completion.expectCompletion);
- if (this._completion.multipleCompletions) {
- for (let completion of this._completion.completions) {
- if (completion.hash == hash) {
- do_check_eq(JSON.stringify(hash), JSON.stringify(completion.hash));
- do_check_eq(table, completion.table);
- do_check_eq(chunkId, completion.chunkId);
-
- completion._completed = true;
-
- if (this._completion.completions.every(x => x._completed))
- this._completed = true;
-
- break;
- }
- }
- }
- else {
- // Hashes are not actually strings and can contain arbitrary data.
- do_check_eq(JSON.stringify(hash), JSON.stringify(this._completion.hash));
- do_check_eq(table, this._completion.table);
- do_check_eq(chunkId, this._completion.chunkId);
-
- this._completed = true;
- }
- },
-
- completionFinished: function completionFinished(status) {
- finishedCompletions++;
- do_check_eq(!!this._completion.expectCompletion, !!this._completed);
- this._completion._finished = true;
-
- // currentCompletionSet can mutate before all of the callbacks are complete.
- if (currentCompletionSet < completionSets.length &&
- finishedCompletions == completionSets[currentCompletionSet].length) {
- runNextCompletion();
- }
- },
-};
-
-function finish() {
- do_check_eq(expectedMaxServerCompletionSet, maxServerCompletionSet);
- server.stop(function() {
- do_test_finished();
- });
-}
diff --git a/toolkit/components/url-classifier/tests/unit/test_listmanager.js b/toolkit/components/url-classifier/tests/unit/test_listmanager.js
deleted file mode 100644
index ba11d930e..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_listmanager.js
+++ /dev/null
@@ -1,376 +0,0 @@
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-
-// These tables share the same updateURL.
-const TEST_TABLE_DATA_LIST = [
- // 0:
- {
- tableName: "test-listmanager0-digest256",
- providerName: "google",
- updateUrl: "http://localhost:4444/safebrowsing/update",
- gethashUrl: "http://localhost:4444/safebrowsing/gethash0",
- },
-
- // 1:
- {
- tableName: "test-listmanager1-digest256",
- providerName: "google",
- updateUrl: "http://localhost:4444/safebrowsing/update",
- gethashUrl: "http://localhost:4444/safebrowsing/gethash1",
- },
-
- // 2.
- {
- tableName: "test-listmanager2-digest256",
- providerName: "google",
- updateUrl: "http://localhost:4444/safebrowsing/update",
- gethashUrl: "http://localhost:4444/safebrowsing/gethash2",
- }
-];
-
-// These tables have a different update URL (for v4).
-const TEST_TABLE_DATA_V4 = {
- tableName: "test-phish-proto",
- providerName: "google4",
- updateUrl: "http://localhost:5555/safebrowsing/update?",
- gethashUrl: "http://localhost:5555/safebrowsing/gethash-v4",
-};
-const TEST_TABLE_DATA_V4_DISABLED = {
- tableName: "test-unwanted-proto",
- providerName: "google4",
- updateUrl: "http://localhost:5555/safebrowsing/update?",
- gethashUrl: "http://localhost:5555/safebrowsing/gethash-v4",
-};
-
-const PREF_NEXTUPDATETIME = "browser.safebrowsing.provider.google.nextupdatetime";
-const PREF_NEXTUPDATETIME_V4 = "browser.safebrowsing.provider.google4.nextupdatetime";
-
-let gListManager = Cc["@mozilla.org/url-classifier/listmanager;1"]
- .getService(Ci.nsIUrlListManager);
-
-let gUrlUtils = Cc["@mozilla.org/url-classifier/utils;1"]
- .getService(Ci.nsIUrlClassifierUtils);
-
-// Global test server for serving safebrowsing updates.
-let gHttpServ = null;
-let gUpdateResponse = "";
-let gExpectedUpdateRequest = "";
-let gExpectedQueryV4 = "";
-
-// Handles request for TEST_TABLE_DATA_V4.
-let gHttpServV4 = null;
-
-// These two variables are used to synchronize the last two racing updates
-// (in terms of "update URL") in test_update_all_tables().
-let gUpdatedCntForTableData = 0; // For TEST_TABLE_DATA_LIST.
-let gIsV4Updated = false; // For TEST_TABLE_DATA_V4.
-
-const NEW_CLIENT_STATE = 'sta\0te';
-const CHECKSUM = '\x30\x67\xc7\x2c\x5e\x50\x1c\x31\xe3\xfe\xca\x73\xf0\x47\xdc\x34\x1a\x95\x63\x99\xec\x70\x5e\x0a\xee\x9e\xfb\x17\xa1\x55\x35\x78';
-
-prefBranch.setBoolPref("browser.safebrowsing.debug", true);
-
-// The "\xFF\xFF" is to generate a base64 string with "/".
-prefBranch.setCharPref("browser.safebrowsing.id", "Firefox\xFF\xFF");
-
-// Register tables.
-TEST_TABLE_DATA_LIST.forEach(function(t) {
- gListManager.registerTable(t.tableName,
- t.providerName,
- t.updateUrl,
- t.gethashUrl);
-});
-
-gListManager.registerTable(TEST_TABLE_DATA_V4.tableName,
- TEST_TABLE_DATA_V4.providerName,
- TEST_TABLE_DATA_V4.updateUrl,
- TEST_TABLE_DATA_V4.gethashUrl);
-
-// To test Bug 1302044.
-gListManager.registerTable(TEST_TABLE_DATA_V4_DISABLED.tableName,
- TEST_TABLE_DATA_V4_DISABLED.providerName,
- TEST_TABLE_DATA_V4_DISABLED.updateUrl,
- TEST_TABLE_DATA_V4_DISABLED.gethashUrl);
-
-const SERVER_INVOLVED_TEST_CASE_LIST = [
- // - Do table0 update.
- // - Server would respond "a:5:32:32\n[DATA]".
- function test_update_table0() {
- disableAllUpdates();
-
- gListManager.enableUpdate(TEST_TABLE_DATA_LIST[0].tableName);
- gExpectedUpdateRequest = TEST_TABLE_DATA_LIST[0].tableName + ";\n";
-
- gUpdateResponse = "n:1000\ni:" + TEST_TABLE_DATA_LIST[0].tableName + "\n";
- gUpdateResponse += readFileToString("data/digest2.chunk");
-
- forceTableUpdate();
- },
-
- // - Do table0 update again. Since chunk 5 was added to table0 in the last
- // update, the expected request contains "a:5".
- // - Server would respond "s;2-12\n[DATA]".
- function test_update_table0_with_existing_chunks() {
- disableAllUpdates();
-
- gListManager.enableUpdate(TEST_TABLE_DATA_LIST[0].tableName);
- gExpectedUpdateRequest = TEST_TABLE_DATA_LIST[0].tableName + ";a:5\n";
-
- gUpdateResponse = "n:1000\ni:" + TEST_TABLE_DATA_LIST[0].tableName + "\n";
- gUpdateResponse += readFileToString("data/digest1.chunk");
-
- forceTableUpdate();
- },
-
- // - Do all-table update.
- // - Server would respond no chunk control.
- //
- // Note that this test MUST be the last one in the array since we rely on
- // the number of sever-involved test case to synchronize the racing last
- // two udpates for different URL.
- function test_update_all_tables() {
- disableAllUpdates();
-
- // Enable all tables including TEST_TABLE_DATA_V4!
- TEST_TABLE_DATA_LIST.forEach(function(t) {
- gListManager.enableUpdate(t.tableName);
- });
-
- // We register two v4 tables but only enable one of them
- // to verify that the disabled tables are not updated.
- // See Bug 1302044.
- gListManager.enableUpdate(TEST_TABLE_DATA_V4.tableName);
- gListManager.disableUpdate(TEST_TABLE_DATA_V4_DISABLED.tableName);
-
- // Expected results for v2.
- gExpectedUpdateRequest = TEST_TABLE_DATA_LIST[0].tableName + ";a:5:s:2-12\n" +
- TEST_TABLE_DATA_LIST[1].tableName + ";\n" +
- TEST_TABLE_DATA_LIST[2].tableName + ";\n";
- gUpdateResponse = "n:1000\n";
-
- // We test the request against the query string since v4 request
- // would be appened to the query string. The request is generated
- // by protobuf API (binary) then encoded to base64 format.
- let requestV4 = gUrlUtils.makeUpdateRequestV4([TEST_TABLE_DATA_V4.tableName],
- [""],
- 1);
- gExpectedQueryV4 = "&$req=" + requestV4;
-
- forceTableUpdate();
- },
-
-];
-
-SERVER_INVOLVED_TEST_CASE_LIST.forEach(t => add_test(t));
-
-add_test(function test_partialUpdateV4() {
- disableAllUpdates();
-
- gListManager.enableUpdate(TEST_TABLE_DATA_V4.tableName);
-
- // Since the new client state has been responded and saved in
- // test_update_all_tables, this update request should send
- // a partial update to the server.
- let requestV4 = gUrlUtils.makeUpdateRequestV4([TEST_TABLE_DATA_V4.tableName],
- [btoa(NEW_CLIENT_STATE)],
- 1);
- gExpectedQueryV4 = "&$req=" + requestV4;
-
- forceTableUpdate();
-});
-
-// Tests nsIUrlListManager.getGethashUrl.
-add_test(function test_getGethashUrl() {
- TEST_TABLE_DATA_LIST.forEach(function (t) {
- equal(gListManager.getGethashUrl(t.tableName), t.gethashUrl);
- });
- equal(gListManager.getGethashUrl(TEST_TABLE_DATA_V4.tableName),
- TEST_TABLE_DATA_V4.gethashUrl);
- run_next_test();
-});
-
-function run_test() {
- // Setup primary testing server.
- gHttpServ = new HttpServer();
- gHttpServ.registerDirectory("/", do_get_cwd());
-
- gHttpServ.registerPathHandler("/safebrowsing/update", function(request, response) {
- let body = NetUtil.readInputStreamToString(request.bodyInputStream,
- request.bodyInputStream.available());
-
- // Verify if the request is as expected.
- equal(body, gExpectedUpdateRequest);
-
- // Respond the update which is controlled by the test case.
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
- response.bodyOutputStream.write(gUpdateResponse, gUpdateResponse.length);
-
- gUpdatedCntForTableData++;
-
- if (gUpdatedCntForTableData !== SERVER_INVOLVED_TEST_CASE_LIST.length) {
- // This is not the last test case so run the next once upon the
- // the update success.
- waitForUpdateSuccess(run_next_test);
- return;
- }
-
- if (gIsV4Updated) {
- run_next_test(); // All tests are done. Just finish.
- return;
- }
-
- do_print("Waiting for TEST_TABLE_DATA_V4 to be tested ...");
- });
-
- gHttpServ.start(4444);
-
- // Setup v4 testing server for the different update URL.
- gHttpServV4 = new HttpServer();
- gHttpServV4.registerDirectory("/", do_get_cwd());
-
- gHttpServV4.registerPathHandler("/safebrowsing/update", function(request, response) {
- // V4 update request body should be empty.
- equal(request.bodyInputStream.available(), 0);
-
- // Not on the spec. Found in Chromium source code...
- equal(request.getHeader("X-HTTP-Method-Override"), "POST");
-
- // V4 update request uses GET.
- equal(request.method, "GET");
-
- // V4 append the base64 encoded request to the query string.
- equal(request.queryString, gExpectedQueryV4);
- equal(request.queryString.indexOf('+'), -1);
- equal(request.queryString.indexOf('/'), -1);
-
- // Respond a V2 compatible content for now. In the future we can
- // send a meaningful response to test Bug 1284178 to see if the
- // update is successfully stored to database.
- response.setHeader("Content-Type",
- "application/vnd.google.safebrowsing-update", false);
- response.setStatusLine(request.httpVersion, 200, "OK");
-
- // The protobuf binary represention of response:
- //
- // [
- // {
- // 'threat_type': 2, // SOCIAL_ENGINEERING_PUBLIC
- // 'response_type': 2, // FULL_UPDATE
- // 'new_client_state': 'sta\x00te', // NEW_CLIENT_STATE
- // 'checksum': { "sha256": CHECKSUM }, // CHECKSUM
- // 'additions': { 'compression_type': RAW,
- // 'prefix_size': 4,
- // 'raw_hashes': "00000001000000020000000300000004"}
- // }
- // ]
- //
- let content = "\x0A\x4A\x08\x02\x20\x02\x2A\x18\x08\x01\x12\x14\x08\x04\x12\x10\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x3A\x06\x73\x74\x61\x00\x74\x65\x42\x22\x0A\x20\x30\x67\xC7\x2C\x5E\x50\x1C\x31\xE3\xFE\xCA\x73\xF0\x47\xDC\x34\x1A\x95\x63\x99\xEC\x70\x5E\x0A\xEE\x9E\xFB\x17\xA1\x55\x35\x78\x12\x08\x08\x08\x10\x80\x94\xEB\xDC\x03";
-
- response.bodyOutputStream.write(content, content.length);
-
- if (gIsV4Updated) {
- // This falls to the case where test_partialUpdateV4 is running.
- // We are supposed to have verified the update request contains
- // the state we set in the previous request.
- run_next_test();
- return;
- }
-
- waitUntilMetaDataSaved(NEW_CLIENT_STATE, CHECKSUM, () => {
- gIsV4Updated = true;
-
- if (gUpdatedCntForTableData === SERVER_INVOLVED_TEST_CASE_LIST.length) {
- // All tests are done!
- run_next_test();
- return;
- }
-
- do_print("Wait for all sever-involved tests to be done ...");
- });
-
- });
-
- gHttpServV4.start(5555);
-
- run_next_test();
-}
-
-// A trick to force updating tables. However, before calling this, we have to
-// call disableAllUpdates() first to clean up the updateCheckers in listmanager.
-function forceTableUpdate() {
- prefBranch.setCharPref(PREF_NEXTUPDATETIME, "1");
- prefBranch.setCharPref(PREF_NEXTUPDATETIME_V4, "1");
- gListManager.maybeToggleUpdateChecking();
-}
-
-function disableAllUpdates() {
- TEST_TABLE_DATA_LIST.forEach(t => gListManager.disableUpdate(t.tableName));
- gListManager.disableUpdate(TEST_TABLE_DATA_V4.tableName);
-}
-
-// Since there's no public interface on listmanager to know the update success,
-// we could only rely on the refresh of "nextupdatetime".
-function waitForUpdateSuccess(callback) {
- let nextupdatetime = parseInt(prefBranch.getCharPref(PREF_NEXTUPDATETIME));
- do_print("nextupdatetime: " + nextupdatetime);
- if (nextupdatetime !== 1) {
- callback();
- return;
- }
- do_timeout(1000, waitForUpdateSuccess.bind(null, callback));
-}
-
-// Construct an update from a file.
-function readFileToString(aFilename) {
- let f = do_get_file(aFilename);
- let stream = Cc["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Ci.nsIFileInputStream);
- stream.init(f, -1, 0, 0);
- let buf = NetUtil.readInputStreamToString(stream, stream.available());
- return buf;
-}
-
-function waitUntilMetaDataSaved(expectedState, expectedChecksum, callback) {
- let dbService = Cc["@mozilla.org/url-classifier/dbservice;1"]
- .getService(Ci.nsIUrlClassifierDBService);
-
- dbService.getTables(metaData => {
- do_print("metadata: " + metaData);
- let didCallback = false;
- metaData.split("\n").some(line => {
- // Parse [tableName];[stateBase64]
- let p = line.indexOf(";");
- if (-1 === p) {
- return false; // continue.
- }
- let tableName = line.substring(0, p);
- let metadata = line.substring(p + 1).split(":");
- let stateBase64 = metadata[0];
- let checksumBase64 = metadata[1];
-
- if (tableName !== 'test-phish-proto') {
- return false; // continue.
- }
-
- if (stateBase64 === btoa(expectedState) &&
- checksumBase64 === btoa(expectedChecksum)) {
- do_print('State has been saved to disk!');
- callback();
- didCallback = true;
- }
-
- return true; // break no matter whether the state is matching.
- });
-
- if (!didCallback) {
- do_timeout(1000, waitUntilMetaDataSaved.bind(null, expectedState,
- expectedChecksum,
- callback));
- }
- });
-}
diff --git a/toolkit/components/url-classifier/tests/unit/test_partial.js b/toolkit/components/url-classifier/tests/unit/test_partial.js
deleted file mode 100644
index 83243fb4e..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_partial.js
+++ /dev/null
@@ -1,825 +0,0 @@
-
-/**
- * DummyCompleter() lets tests easily specify the results of a partial
- * hash completion request.
- */
-function DummyCompleter() {
- this.fragments = {};
- this.queries = [];
- this.tableName = "test-phish-simple";
-}
-
-DummyCompleter.prototype =
-{
-QueryInterface: function(iid)
-{
- if (!iid.equals(Ci.nsISupports) &&
- !iid.equals(Ci.nsIUrlClassifierHashCompleter)) {
- throw Cr.NS_ERROR_NO_INTERFACE;
- }
- return this;
-},
-
-complete: function(partialHash, gethashUrl, cb)
-{
- this.queries.push(partialHash);
- var fragments = this.fragments;
- var self = this;
- var doCallback = function() {
- if (self.alwaysFail) {
- cb.completionFinished(1);
- return;
- }
- var results;
- if (fragments[partialHash]) {
- for (var i = 0; i < fragments[partialHash].length; i++) {
- var chunkId = fragments[partialHash][i][0];
- var hash = fragments[partialHash][i][1];
- cb.completion(hash, self.tableName, chunkId);
- }
- }
- cb.completionFinished(0);
- }
- var timer = new Timer(0, doCallback);
-},
-
-getHash: function(fragment)
-{
- var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
- createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- var data = converter.convertToByteArray(fragment);
- var ch = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
- ch.init(ch.SHA256);
- ch.update(data, data.length);
- var hash = ch.finish(false);
- return hash.slice(0, 32);
-},
-
-addFragment: function(chunkId, fragment)
-{
- this.addHash(chunkId, this.getHash(fragment));
-},
-
-// This method allows the caller to generate complete hashes that match the
-// prefix of a real fragment, but have different complete hashes.
-addConflict: function(chunkId, fragment)
-{
- var realHash = this.getHash(fragment);
- var invalidHash = this.getHash("blah blah blah blah blah");
- this.addHash(chunkId, realHash.slice(0, 4) + invalidHash.slice(4, 32));
-},
-
-addHash: function(chunkId, hash)
-{
- var partial = hash.slice(0, 4);
- if (this.fragments[partial]) {
- this.fragments[partial].push([chunkId, hash]);
- } else {
- this.fragments[partial] = [[chunkId, hash]];
- }
-},
-
-compareQueries: function(fragments)
-{
- var expectedQueries = [];
- for (var i = 0; i < fragments.length; i++) {
- expectedQueries.push(this.getHash(fragments[i]).slice(0, 4));
- }
- do_check_eq(this.queries.length, expectedQueries.length);
- expectedQueries.sort();
- this.queries.sort();
- for (var i = 0; i < this.queries.length; i++) {
- do_check_eq(this.queries[i], expectedQueries[i]);
- }
-}
-};
-
-function setupCompleter(table, hits, conflicts)
-{
- var completer = new DummyCompleter();
- completer.tableName = table;
- for (var i = 0; i < hits.length; i++) {
- var chunkId = hits[i][0];
- var fragments = hits[i][1];
- for (var j = 0; j < fragments.length; j++) {
- completer.addFragment(chunkId, fragments[j]);
- }
- }
- for (var i = 0; i < conflicts.length; i++) {
- var chunkId = conflicts[i][0];
- var fragments = conflicts[i][1];
- for (var j = 0; j < fragments.length; j++) {
- completer.addConflict(chunkId, fragments[j]);
- }
- }
-
- dbservice.setHashCompleter(table, completer);
-
- return completer;
-}
-
-function installCompleter(table, fragments, conflictFragments)
-{
- return setupCompleter(table, fragments, conflictFragments);
-}
-
-function installFailingCompleter(table) {
- var completer = setupCompleter(table, [], []);
- completer.alwaysFail = true;
- return completer;
-}
-
-// Helper assertion for checking dummy completer queries
-gAssertions.completerQueried = function(data, cb)
-{
- var completer = data[0];
- completer.compareQueries(data[1]);
- cb();
-}
-
-function doTest(updates, assertions)
-{
- doUpdateTest(updates, assertions, runNextTest, updateError);
-}
-
-// Test an add of two partial urls to a fresh database
-function testPartialAdds() {
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : addUrls,
- "completerQueried" : [completer, addUrls]
- };
-
-
- doTest([update], assertions);
-}
-
-function testPartialAddsWithConflicts() {
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
- // Each result will have both a real match and a conflict
- var completer = installCompleter('test-phish-simple',
- [[1, addUrls]],
- [[1, addUrls]]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : addUrls,
- "completerQueried" : [completer, addUrls]
- };
-
- doTest([update], assertions);
-}
-
-// Test whether the fragmenting code does not cause duplicated completions
-function testFragments() {
- var addUrls = [ "foo.com/a/b/c", "foo.net/", "foo.com/c/" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : addUrls,
- "completerQueried" : [completer, addUrls]
- };
-
-
- doTest([update], assertions);
-}
-
-// Test http://code.google.com/p/google-safe-browsing/wiki/Protocolv2Spec
-// section 6.2 example 1
-function testSpecFragments() {
- var probeUrls = [ "a.b.c/1/2.html?param=1" ];
-
- var addUrls = [ "a.b.c/1/2.html",
- "a.b.c/",
- "a.b.c/1/",
- "b.c/1/2.html?param=1",
- "b.c/1/2.html",
- "b.c/",
- "b.c/1/",
- "a.b.c/1/2.html?param=1" ];
-
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : probeUrls,
- "completerQueried" : [completer, addUrls]
- };
-
- doTest([update], assertions);
-
-}
-
-// Test http://code.google.com/p/google-safe-browsing/wiki/Protocolv2Spec
-// section 6.2 example 2
-function testMoreSpecFragments() {
- var probeUrls = [ "a.b.c.d.e.f.g/1.html" ];
-
- var addUrls = [ "a.b.c.d.e.f.g/1.html",
- "a.b.c.d.e.f.g/",
- "c.d.e.f.g/1.html",
- "c.d.e.f.g/",
- "d.e.f.g/1.html",
- "d.e.f.g/",
- "e.f.g/1.html",
- "e.f.g/",
- "f.g/1.html",
- "f.g/" ];
-
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : probeUrls,
- "completerQueried" : [completer, addUrls]
- };
-
- doTest([update], assertions);
-
-}
-
-function testFalsePositives() {
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
- // Each result will have no matching complete hashes and a non-matching
- // conflict
- var completer = installCompleter('test-phish-simple', [], [[1, addUrls]]);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsDontExist" : addUrls,
- "completerQueried" : [completer, addUrls]
- };
-
- doTest([update], assertions);
-}
-
-function testEmptyCompleter() {
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
- // Completer will never return full hashes
- var completer = installCompleter('test-phish-simple', [], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsDontExist" : addUrls,
- "completerQueried" : [completer, addUrls]
- };
-
- doTest([update], assertions);
-}
-
-function testCompleterFailure() {
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
- // Completer will never return full hashes
- var completer = installFailingCompleter('test-phish-simple');
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsDontExist" : addUrls,
- "completerQueried" : [completer, addUrls]
- };
-
- doTest([update], assertions);
-}
-
-function testMixedSizesSameDomain() {
- var add1Urls = [ "foo.com/a" ];
- var add2Urls = [ "foo.com/b" ];
-
- var update1 = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : add1Urls }],
- 4);
- var update2 = buildPhishingUpdate(
- [
- { "chunkNum" : 2,
- "urls" : add2Urls }],
- 32);
-
- // We should only need to complete the partial hashes
- var completer = installCompleter('test-phish-simple', [[1, add1Urls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1-2",
- // both urls should match...
- "urlsExist" : add1Urls.concat(add2Urls),
- // ... but the completer should only be queried for the partial entry
- "completerQueried" : [completer, add1Urls]
- };
-
- doTest([update1, update2], assertions);
-}
-
-function testMixedSizesDifferentDomains() {
- var add1Urls = [ "foo.com/a" ];
- var add2Urls = [ "bar.com/b" ];
-
- var update1 = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : add1Urls }],
- 4);
- var update2 = buildPhishingUpdate(
- [
- { "chunkNum" : 2,
- "urls" : add2Urls }],
- 32);
-
- // We should only need to complete the partial hashes
- var completer = installCompleter('test-phish-simple', [[1, add1Urls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1-2",
- // both urls should match...
- "urlsExist" : add1Urls.concat(add2Urls),
- // ... but the completer should only be queried for the partial entry
- "completerQueried" : [completer, add1Urls]
- };
-
- doTest([update1, update2], assertions);
-}
-
-function testInvalidHashSize()
-{
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 12); // only 4 and 32 are legal hash sizes
-
- var addUrls2 = [ "zaz.com/a", "xyz.com/b" ];
- var update2 = buildPhishingUpdate(
- [
- { "chunkNum" : 2,
- "urls" : addUrls2
- }],
- 4);
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:2",
- "urlsDontExist" : addUrls
- };
-
- // A successful update will trigger an error
- doUpdateTest([update2, update], assertions, updateError, runNextTest);
-}
-
-function testWrongTable()
-{
- var addUrls = [ "foo.com/a" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
- var completer = installCompleter('test-malware-simple', // wrong table
- [[1, addUrls]], []);
-
- // The above installCompleter installs the completer for test-malware-simple,
- // we want it to be used for test-phish-simple too.
- dbservice.setHashCompleter("test-phish-simple", completer);
-
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- // The urls were added as phishing urls, but the completer is claiming
- // that they are malware urls, and we trust the completer in this case.
- // The result will be discarded, so we can only check for non-existence.
- "urlsDontExist" : addUrls,
- // Make sure the completer was actually queried.
- "completerQueried" : [completer, addUrls]
- };
-
- doUpdateTest([update], assertions,
- function() {
- // Give the dbservice a chance to (not) cache the result.
- var timer = new Timer(3000, function() {
- // The miss earlier will have caused a miss to be cached.
- // Resetting the completer does not count as an update,
- // so we will not be probed again.
- var newCompleter = installCompleter('test-malware-simple', [[1, addUrls]], []); dbservice.setHashCompleter("test-phish-simple",
- newCompleter);
-
- var assertions = {
- "urlsDontExist" : addUrls
- };
- checkAssertions(assertions, runNextTest);
- });
- }, updateError);
-}
-
-function setupCachedResults(addUrls, part2)
-{
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- // Request the add url. This should cause the completion to be cached.
- "urlsExist" : addUrls,
- // Make sure the completer was actually queried.
- "completerQueried" : [completer, addUrls]
- };
-
- doUpdateTest([update], assertions,
- function() {
- // Give the dbservice a chance to cache the result.
- var timer = new Timer(3000, part2);
- }, updateError);
-}
-
-function testCachedResults()
-{
- setupCachedResults(["foo.com/a"], function(add) {
- // This is called after setupCachedResults(). Verify that
- // checking the url again does not cause a completer request.
-
- // install a new completer, this one should never be queried.
- var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
-
- var assertions = {
- "urlsExist" : ["foo.com/a"],
- "completerQueried" : [newCompleter, []]
- };
- checkAssertions(assertions, runNextTest);
- });
-}
-
-function testCachedResultsWithSub() {
- setupCachedResults(["foo.com/a"], function() {
- // install a new completer, this one should never be queried.
- var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
-
- var removeUpdate = buildPhishingUpdate(
- [ { "chunkNum" : 2,
- "chunkType" : "s",
- "urls": ["1:foo.com/a"] }],
- 4);
-
- var assertions = {
- "urlsDontExist" : ["foo.com/a"],
- "completerQueried" : [newCompleter, []]
- }
-
- doTest([removeUpdate], assertions);
- });
-}
-
-function testCachedResultsWithExpire() {
- setupCachedResults(["foo.com/a"], function() {
- // install a new completer, this one should never be queried.
- var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
-
- var expireUpdate =
- "n:1000\n" +
- "i:test-phish-simple\n" +
- "ad:1\n";
-
- var assertions = {
- "urlsDontExist" : ["foo.com/a"],
- "completerQueried" : [newCompleter, []]
- }
- doTest([expireUpdate], assertions);
- });
-}
-
-function testCachedResultsUpdate()
-{
- var existUrls = ["foo.com/a"];
- setupCachedResults(existUrls, function() {
- // This is called after setupCachedResults(). Verify that
- // checking the url again does not cause a completer request.
-
- // install a new completer, this one should never be queried.
- var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
-
- var assertions = {
- "urlsExist" : existUrls,
- "completerQueried" : [newCompleter, []]
- };
-
- var addUrls = ["foobar.org/a"];
-
- var update2 = buildPhishingUpdate(
- [
- { "chunkNum" : 2,
- "urls" : addUrls
- }],
- 4);
-
- checkAssertions(assertions, function () {
- // Apply the update. The cached completes should be gone.
- doStreamUpdate(update2, function() {
- // Now the completer gets queried again.
- var newCompleter2 = installCompleter('test-phish-simple', [[1, existUrls]], []);
- var assertions2 = {
- "tableData" : "test-phish-simple;a:1-2",
- "urlsExist" : existUrls,
- "completerQueried" : [newCompleter2, existUrls]
- };
- checkAssertions(assertions2, runNextTest);
- }, updateError);
- });
- });
-}
-
-function testCachedResultsFailure()
-{
- var existUrls = ["foo.com/a"];
- setupCachedResults(existUrls, function() {
- // This is called after setupCachedResults(). Verify that
- // checking the url again does not cause a completer request.
-
- // install a new completer, this one should never be queried.
- var newCompleter = installCompleter('test-phish-simple', [[1, []]], []);
-
- var assertions = {
- "urlsExist" : existUrls,
- "completerQueried" : [newCompleter, []]
- };
-
- var addUrls = ["foobar.org/a"];
-
- var update2 = buildPhishingUpdate(
- [
- { "chunkNum" : 2,
- "urls" : addUrls
- }],
- 4);
-
- checkAssertions(assertions, function() {
- // Apply the update. The cached completes should be gone.
- doErrorUpdate("test-phish-simple,test-malware-simple", function() {
- // Now the completer gets queried again.
- var newCompleter2 = installCompleter('test-phish-simple', [[1, existUrls]], []);
- var assertions2 = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : existUrls,
- "completerQueried" : [newCompleter2, existUrls]
- };
- checkAssertions(assertions2, runNextTest);
- }, updateError);
- });
- });
-}
-
-function testErrorList()
-{
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 4);
- // The update failure should will kill the completes, so the above
- // must be a prefix to get any hit at all past the update failure.
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : addUrls,
- // These are complete urls, and will only be completed if the
- // list is stale.
- "completerQueried" : [completer, addUrls]
- };
-
- // Apply the update.
- doStreamUpdate(update, function() {
- // Now the test-phish-simple and test-malware-simple tables are marked
- // as fresh. Fake an update failure to mark them stale.
- doErrorUpdate("test-phish-simple,test-malware-simple", function() {
- // Now the lists should be marked stale. Check assertions.
- checkAssertions(assertions, runNextTest);
- }, updateError);
- }, updateError);
-}
-
-
-function testStaleList()
-{
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 32);
-
- var completer = installCompleter('test-phish-simple', [[1, addUrls]], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : addUrls,
- // These are complete urls, and will only be completed if the
- // list is stale.
- "completerQueried" : [completer, addUrls]
- };
-
- // Consider a match stale after one second.
- prefBranch.setIntPref("urlclassifier.max-complete-age", 1);
-
- // Apply the update.
- doStreamUpdate(update, function() {
- // Now the test-phish-simple and test-malware-simple tables are marked
- // as fresh. Wait three seconds to make sure the list is marked stale.
- new Timer(3000, function() {
- // Now the lists should be marked stale. Check assertions.
- checkAssertions(assertions, function() {
- prefBranch.setIntPref("urlclassifier.max-complete-age", 2700);
- runNextTest();
- });
- }, updateError);
- }, updateError);
-}
-
-// Same as testStaleList, but verifies that an empty response still
-// unconfirms the entry.
-function testStaleListEmpty()
-{
- var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls
- }],
- 32);
-
- var completer = installCompleter('test-phish-simple', [], []);
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- // None of these should match, because they won't be completed
- "urlsDontExist" : addUrls,
- // These are complete urls, and will only be completed if the
- // list is stale.
- "completerQueried" : [completer, addUrls]
- };
-
- // Consider a match stale after one second.
- prefBranch.setIntPref("urlclassifier.max-complete-age", 1);
-
- // Apply the update.
- doStreamUpdate(update, function() {
- // Now the test-phish-simple and test-malware-simple tables are marked
- // as fresh. Wait three seconds to make sure the list is marked stale.
- new Timer(3000, function() {
- // Now the lists should be marked stale. Check assertions.
- checkAssertions(assertions, function() {
- prefBranch.setIntPref("urlclassifier.max-complete-age", 2700);
- runNextTest();
- });
- }, updateError);
- }, updateError);
-}
-
-
-// Verify that different lists (test-phish-simple,
-// test-malware-simple) maintain their freshness separately.
-function testErrorListIndependent()
-{
- var phishUrls = [ "phish.com/a" ];
- var malwareUrls = [ "attack.com/a" ];
- var update = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : phishUrls
- }],
- 4);
- // These have to persist past the update failure, so they must be prefixes,
- // not completes.
-
- update += buildMalwareUpdate(
- [
- { "chunkNum" : 2,
- "urls" : malwareUrls
- }],
- 32);
-
- var completer = installCompleter('test-phish-simple', [[1, phishUrls]], []);
-
- var assertions = {
- "tableData" : "test-malware-simple;a:2\ntest-phish-simple;a:1",
- "urlsExist" : phishUrls,
- "malwareUrlsExist" : malwareUrls,
- // Only this phishing urls should be completed, because only the phishing
- // urls will be stale.
- "completerQueried" : [completer, phishUrls]
- };
-
- // Apply the update.
- doStreamUpdate(update, function() {
- // Now the test-phish-simple and test-malware-simple tables are
- // marked as fresh. Fake an update failure to mark *just*
- // phishing data as stale.
- doErrorUpdate("test-phish-simple", function() {
- // Now the lists should be marked stale. Check assertions.
- checkAssertions(assertions, runNextTest);
- }, updateError);
- }, updateError);
-}
-
-function run_test()
-{
- runTests([
- testPartialAdds,
- testPartialAddsWithConflicts,
- testFragments,
- testSpecFragments,
- testMoreSpecFragments,
- testFalsePositives,
- testEmptyCompleter,
- testCompleterFailure,
- testMixedSizesSameDomain,
- testMixedSizesDifferentDomains,
- testInvalidHashSize,
- testWrongTable,
- testCachedResults,
- testCachedResultsWithSub,
- testCachedResultsWithExpire,
- testCachedResultsUpdate,
- testCachedResultsFailure,
- testStaleList,
- testStaleListEmpty,
- testErrorList,
- testErrorListIndependent
- ]);
-}
-
-do_test_pending();
diff --git a/toolkit/components/url-classifier/tests/unit/test_pref.js b/toolkit/components/url-classifier/tests/unit/test_pref.js
deleted file mode 100644
index 68030a246..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_pref.js
+++ /dev/null
@@ -1,14 +0,0 @@
-function run_test() {
- let urlUtils = Cc["@mozilla.org/url-classifier/utils;1"]
- .getService(Ci.nsIUrlClassifierUtils);
-
- // The google protocol version should be "2.2" until we enable SB v4
- // by default.
- equal(urlUtils.getProtocolVersion("google"), "2.2");
-
- // Mozilla protocol version will stick to "2.2".
- equal(urlUtils.getProtocolVersion("mozilla"), "2.2");
-
- // Unknown provider version will be "2.2".
- equal(urlUtils.getProtocolVersion("unknown-provider"), "2.2");
-} \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/unit/test_prefixset.js b/toolkit/components/url-classifier/tests/unit/test_prefixset.js
deleted file mode 100644
index f2ecc9c2b..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_prefixset.js
+++ /dev/null
@@ -1,232 +0,0 @@
-// newPset: returns an empty nsIUrlClassifierPrefixSet.
-function newPset() {
- let pset = Cc["@mozilla.org/url-classifier/prefixset;1"]
- .createInstance(Ci.nsIUrlClassifierPrefixSet);
- pset.init("all");
- return pset;
-}
-
-// arrContains: returns true if |arr| contains the element |target|. Uses binary
-// search and requires |arr| to be sorted.
-function arrContains(arr, target) {
- let start = 0;
- let end = arr.length - 1;
- let i = 0;
-
- while (end > start) {
- i = start + (end - start >> 1);
- let value = arr[i];
-
- if (value < target)
- start = i+1;
- else if (value > target)
- end = i-1;
- else
- break;
- }
- if (start == end)
- i = start;
-
- return (!(i < 0 || i >= arr.length) && arr[i] == target);
-}
-
-// checkContents: Check whether the PrefixSet pset contains
-// the prefixes in the passed array.
-function checkContents(pset, prefixes) {
- var outcount = {}, outset = {};
- outset = pset.getPrefixes(outcount);
- let inset = prefixes;
- do_check_eq(inset.length, outset.length);
- inset.sort((x,y) => x - y);
- for (let i = 0; i < inset.length; i++) {
- do_check_eq(inset[i], outset[i]);
- }
-}
-
-function wrappedProbe(pset, prefix) {
- return pset.contains(prefix);
-};
-
-// doRandomLookups: we use this to test for false membership with random input
-// over the range of prefixes (unsigned 32-bits integers).
-// pset: a nsIUrlClassifierPrefixSet to test.
-// prefixes: an array of prefixes supposed to make up the prefix set.
-// N: number of random lookups to make.
-function doRandomLookups(pset, prefixes, N) {
- for (let i = 0; i < N; i++) {
- let randInt = prefixes[0];
- while (arrContains(prefixes, randInt))
- randInt = Math.floor(Math.random() * Math.pow(2, 32));
-
- do_check_false(wrappedProbe(pset, randInt));
- }
-}
-
-// doExpectedLookups: we use this to test expected membership.
-// pset: a nsIUrlClassifierPrefixSet to test.
-// prefixes:
-function doExpectedLookups(pset, prefixes, N) {
- for (let i = 0; i < N; i++) {
- prefixes.forEach(function (x) {
- dump("Checking " + x + "\n");
- do_check_true(wrappedProbe(pset, x));
- });
- }
-}
-
-// testBasicPset: A very basic test of the prefix set to make sure that it
-// exists and to give a basic example of its use.
-function testBasicPset() {
- let pset = Cc["@mozilla.org/url-classifier/prefixset;1"]
- .createInstance(Ci.nsIUrlClassifierPrefixSet);
- let prefixes = [2,50,100,2000,78000,1593203];
- pset.setPrefixes(prefixes, prefixes.length);
-
- do_check_true(wrappedProbe(pset, 100));
- do_check_false(wrappedProbe(pset, 100000));
- do_check_true(wrappedProbe(pset, 1593203));
- do_check_false(wrappedProbe(pset, 999));
- do_check_false(wrappedProbe(pset, 0));
-
-
- checkContents(pset, prefixes);
-}
-
-function testDuplicates() {
- let pset = Cc["@mozilla.org/url-classifier/prefixset;1"]
- .createInstance(Ci.nsIUrlClassifierPrefixSet);
- let prefixes = [1,1,2,2,2,3,3,3,3,3,3,5,6,6,7,7,9,9,9];
- pset.setPrefixes(prefixes, prefixes.length);
-
- do_check_true(wrappedProbe(pset, 1));
- do_check_true(wrappedProbe(pset, 2));
- do_check_true(wrappedProbe(pset, 5));
- do_check_true(wrappedProbe(pset, 9));
- do_check_false(wrappedProbe(pset, 4));
- do_check_false(wrappedProbe(pset, 8));
-
-
- checkContents(pset, prefixes);
-}
-
-function testSimplePset() {
- let pset = newPset();
- let prefixes = [1,2,100,400,123456789];
- pset.setPrefixes(prefixes, prefixes.length);
-
- doRandomLookups(pset, prefixes, 100);
- doExpectedLookups(pset, prefixes, 1);
-
-
- checkContents(pset, prefixes);
-}
-
-function testReSetPrefixes() {
- let pset = newPset();
- let prefixes = [1, 5, 100, 1000, 150000];
- pset.setPrefixes(prefixes, prefixes.length);
-
- doExpectedLookups(pset, prefixes, 1);
-
- let secondPrefixes = [12, 50, 300, 2000, 5000, 200000];
- pset.setPrefixes(secondPrefixes, secondPrefixes.length);
-
- doExpectedLookups(pset, secondPrefixes, 1);
- for (let i = 0; i < prefixes.length; i++) {
- do_check_false(wrappedProbe(pset, prefixes[i]));
- }
-
-
- checkContents(pset, secondPrefixes);
-}
-
-function testLoadSaveLargeSet() {
- let N = 1000;
- let arr = [];
-
- for (let i = 0; i < N; i++) {
- let randInt = Math.floor(Math.random() * Math.pow(2, 32));
- arr.push(randInt);
- }
-
- arr.sort((x,y) => x - y);
-
- let pset = newPset();
- pset.setPrefixes(arr, arr.length);
-
- doExpectedLookups(pset, arr, 1);
- doRandomLookups(pset, arr, 1000);
-
- checkContents(pset, arr);
-
- // Now try to save, restore, and redo the lookups
- var file = dirSvc.get('ProfLD', Ci.nsIFile);
- file.append("testLarge.pset");
-
- pset.storeToFile(file);
-
- let psetLoaded = newPset();
- psetLoaded.loadFromFile(file);
-
- doExpectedLookups(psetLoaded, arr, 1);
- doRandomLookups(psetLoaded, arr, 1000);
-
- checkContents(psetLoaded, arr);
-}
-
-function testTinySet() {
- let pset = Cc["@mozilla.org/url-classifier/prefixset;1"]
- .createInstance(Ci.nsIUrlClassifierPrefixSet);
- let prefixes = [1];
- pset.setPrefixes(prefixes, prefixes.length);
-
- do_check_true(wrappedProbe(pset, 1));
- do_check_false(wrappedProbe(pset, 100000));
- checkContents(pset, prefixes);
-
- prefixes = [];
- pset.setPrefixes(prefixes, prefixes.length);
- do_check_false(wrappedProbe(pset, 1));
- checkContents(pset, prefixes);
-}
-
-function testLoadSaveNoDelta() {
- let N = 100;
- let arr = [];
-
- for (let i = 0; i < N; i++) {
- // construct a tree without deltas by making the distance
- // between entries larger than 16 bits
- arr.push(((1 << 16) + 1) * i);
- }
-
- let pset = newPset();
- pset.setPrefixes(arr, arr.length);
-
- doExpectedLookups(pset, arr, 1);
-
- var file = dirSvc.get('ProfLD', Ci.nsIFile);
- file.append("testNoDelta.pset");
-
- pset.storeToFile(file);
- pset.loadFromFile(file);
-
- doExpectedLookups(pset, arr, 1);
-}
-
-var tests = [testBasicPset,
- testSimplePset,
- testReSetPrefixes,
- testLoadSaveLargeSet,
- testDuplicates,
- testTinySet,
- testLoadSaveNoDelta];
-
-function run_test() {
- // None of the tests use |executeSoon| or any sort of callbacks, so we can
- // just run them in succession.
- for (let i = 0; i < tests.length; i++) {
- dump("Running " + tests[i].name + "\n");
- tests[i]();
- }
-}
diff --git a/toolkit/components/url-classifier/tests/unit/test_provider_url.js b/toolkit/components/url-classifier/tests/unit/test_provider_url.js
deleted file mode 100644
index 9a946dc3f..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_provider_url.js
+++ /dev/null
@@ -1,34 +0,0 @@
-Cu.import("resource://testing-common/AppInfo.jsm", this);
-Cu.import("resource://gre/modules/Services.jsm");
-
-function updateVersion(version) {
- updateAppInfo({ version });
-}
-
-add_test(function test_provider_url() {
- let urls = [
- "browser.safebrowsing.provider.google.updateURL",
- "browser.safebrowsing.provider.google.gethashURL",
- "browser.safebrowsing.provider.mozilla.updateURL",
- "browser.safebrowsing.provider.mozilla.gethashURL"
- ];
-
- let versions = [
- "49.0",
- "49.0.1",
- "49.0a1",
- "49.0b1",
- "49.0esr",
- "49.0.1esr"
- ];
-
- for (let version of versions) {
- for (let url of urls) {
- updateVersion(version);
- let value = Services.urlFormatter.formatURLPref(url);
- Assert.notEqual(value.indexOf("&appver=49.0&"), -1);
- }
- }
-
- run_next_test();
-});
diff --git a/toolkit/components/url-classifier/tests/unit/test_safebrowsing_protobuf.js b/toolkit/components/url-classifier/tests/unit/test_safebrowsing_protobuf.js
deleted file mode 100644
index 45309ba54..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_safebrowsing_protobuf.js
+++ /dev/null
@@ -1,23 +0,0 @@
-function run_test() {
- let urlUtils = Cc["@mozilla.org/url-classifier/utils;1"]
- .getService(Ci.nsIUrlClassifierUtils);
-
- // No list at all.
- let requestNoList = urlUtils.makeUpdateRequestV4([], [], 0);
-
- // Only one valid list name.
- let requestOneValid =
- urlUtils.makeUpdateRequestV4(["goog-phish-proto"], ["AAAAAA"], 1);
-
- // Only one invalid list name.
- let requestOneInvalid =
- urlUtils.makeUpdateRequestV4(["bad-list-name"], ["AAAAAA"], 1);
-
- // One valid and one invalid list name.
- let requestOneInvalidOneValid =
- urlUtils.makeUpdateRequestV4(["goog-phish-proto", "bad-list-name"],
- ["AAAAAA", "AAAAAA"], 2);
-
- equal(requestNoList, requestOneInvalid);
- equal(requestOneValid, requestOneInvalidOneValid);
-} \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/unit/test_streamupdater.js b/toolkit/components/url-classifier/tests/unit/test_streamupdater.js
deleted file mode 100644
index e5abc4e91..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_streamupdater.js
+++ /dev/null
@@ -1,288 +0,0 @@
-function doTest(updates, assertions, expectError)
-{
- if (expectError) {
- doUpdateTest(updates, assertions, updateError, runNextTest);
- } else {
- doUpdateTest(updates, assertions, runNextTest, updateError);
- }
-}
-
-// Never use the same URLs for multiple tests, because we aren't guaranteed
-// to reset the database between tests.
-function testFillDb() {
- var add1Urls = [ "zaz.com/a", "yxz.com/c" ];
-
- var update = "n:1000\n";
- update += "i:test-phish-simple\n";
-
- var update1 = buildBareUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls }]);
- update += "u:data:," + encodeURIComponent(update1) + "\n";
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1",
- "urlsExist" : add1Urls
- };
-
- doTest([update], assertions, false);
-}
-
-function testSimpleForward() {
- var add1Urls = [ "foo-simple.com/a", "bar-simple.com/c" ];
- var add2Urls = [ "foo-simple.com/b" ];
- var add3Urls = [ "bar-simple.com/d" ];
-
- var update = "n:1000\n";
- update += "i:test-phish-simple\n";
-
- var update1 = buildBareUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls }]);
- update += "u:data:," + encodeURIComponent(update1) + "\n";
-
- var update2 = buildBareUpdate(
- [{ "chunkNum" : 2,
- "urls" : add2Urls }]);
- update += "u:data:," + encodeURIComponent(update2) + "\n";
-
- var update3 = buildBareUpdate(
- [{ "chunkNum" : 3,
- "urls" : add3Urls }]);
- update += "u:data:," + encodeURIComponent(update3) + "\n";
-
- var assertions = {
- "tableData" : "test-phish-simple;a:1-3",
- "urlsExist" : add1Urls.concat(add2Urls).concat(add3Urls)
- };
-
- doTest([update], assertions, false);
-}
-
-// Make sure that a nested forward (a forward within a forward) causes
-// the update to fail.
-function testNestedForward() {
- var add1Urls = [ "foo-nested.com/a", "bar-nested.com/c" ];
- var add2Urls = [ "foo-nested.com/b" ];
-
- var update = "n:1000\n";
- update += "i:test-phish-simple\n";
-
- var update1 = buildBareUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls }]);
- update += "u:data:," + encodeURIComponent(update1) + "\n";
-
- var update2 = buildBareUpdate(
- [{ "chunkNum" : 2 }]);
- var update3 = buildBareUpdate(
- [{ "chunkNum" : 3,
- "urls" : add1Urls }]);
-
- update2 += "u:data:," + encodeURIComponent(update3) + "\n";
-
- update += "u:data:," + encodeURIComponent(update2) + "\n";
-
- var assertions = {
- "tableData" : "",
- "urlsDontExist" : add1Urls.concat(add2Urls)
- };
-
- doTest([update], assertions, true);
-}
-
-// An invalid URL forward causes the update to fail.
-function testInvalidUrlForward() {
- var add1Urls = [ "foo-invalid.com/a", "bar-invalid.com/c" ];
-
- var update = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls }]);
- update += "u:asdf://blah/blah\n"; // invalid URL scheme
-
- // add1Urls is present, but that is an artifact of the way we do the test.
- var assertions = {
- "tableData" : "",
- "urlsExist" : add1Urls
- };
-
- doTest([update], assertions, true);
-}
-
-// A failed network request causes the update to fail.
-function testErrorUrlForward() {
- var add1Urls = [ "foo-forward.com/a", "bar-forward.com/c" ];
-
- var update = buildPhishingUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls }]);
- update += "u:http://test.invalid/asdf/asdf\n"; // invalid URL scheme
-
- // add1Urls is present, but that is an artifact of the way we do the test.
- var assertions = {
- "tableData" : "",
- "urlsExist" : add1Urls
- };
-
- doTest([update], assertions, true);
-}
-
-function testMultipleTables() {
- var add1Urls = [ "foo-multiple.com/a", "bar-multiple.com/c" ];
- var add2Urls = [ "foo-multiple.com/b" ];
- var add3Urls = [ "bar-multiple.com/d" ];
- var add4Urls = [ "bar-multiple.com/e" ];
- var add6Urls = [ "bar-multiple.com/g" ];
-
- var update = "n:1000\n";
- update += "i:test-phish-simple\n";
-
- var update1 = buildBareUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls }]);
- update += "u:data:," + encodeURIComponent(update1) + "\n";
-
- var update2 = buildBareUpdate(
- [{ "chunkNum" : 2,
- "urls" : add2Urls }]);
- update += "u:data:," + encodeURIComponent(update2) + "\n";
-
- update += "i:test-malware-simple\n";
-
- var update3 = buildBareUpdate(
- [{ "chunkNum" : 3,
- "urls" : add3Urls }]);
- update += "u:data:," + encodeURIComponent(update3) + "\n";
-
- update += "i:test-unwanted-simple\n";
- var update4 = buildBareUpdate(
- [{ "chunkNum" : 4,
- "urls" : add4Urls }]);
- update += "u:data:," + encodeURIComponent(update4) + "\n";
-
- update += "i:test-block-simple\n";
- var update6 = buildBareUpdate(
- [{ "chunkNum" : 6,
- "urls" : add6Urls }]);
- update += "u:data:," + encodeURIComponent(update6) + "\n";
-
- var assertions = {
- "tableData" : "test-block-simple;a:6\ntest-malware-simple;a:3\ntest-phish-simple;a:1-2\ntest-unwanted-simple;a:4",
- "urlsExist" : add1Urls.concat(add2Urls),
- "malwareUrlsExist" : add3Urls,
- "unwantedUrlsExist" : add4Urls,
- "blockedUrlsExist" : add6Urls
- };
-
- doTest([update], assertions, false);
-}
-
-function testUrlInMultipleTables() {
- var add1Urls = [ "foo-forward.com/a" ];
-
- var update = "n:1000\n";
- update += "i:test-phish-simple\n";
-
- var update1 = buildBareUpdate(
- [{ "chunkNum" : 1,
- "urls" : add1Urls }]);
- update += "u:data:," + encodeURIComponent(update1) + "\n";
-
- update += "i:test-malware-simple\n";
- var update2 = buildBareUpdate(
- [{ "chunkNum" : 2,
- "urls" : add1Urls }]);
- update += "u:data:," + encodeURIComponent(update2) + "\n";
-
- update += "i:test-unwanted-simple\n";
- var update3 = buildBareUpdate(
- [{ "chunkNum" : 3,
- "urls" : add1Urls }]);
- update += "u:data:," + encodeURIComponent(update3) + "\n";
-
- var assertions = {
- "tableData" : "test-malware-simple;a:2\ntest-phish-simple;a:1\ntest-unwanted-simple;a:3",
- "urlExistInMultipleTables" : { url: add1Urls,
- tables: "test-malware-simple,test-phish-simple,test-unwanted-simple" }
- };
-
- doTest([update], assertions, false);
-}
-
-function Observer(callback) {
- this.observe = callback;
-}
-
-Observer.prototype =
-{
-QueryInterface: function(iid)
-{
- if (!iid.equals(Ci.nsISupports) &&
- !iid.equals(Ci.nsIObserver)) {
- throw Cr.NS_ERROR_NO_INTERFACE;
- }
- return this;
-}
-};
-
-// Tests a database reset request.
-function testReset() {
- // The moz-phish-simple table is populated separately from the other update in
- // a separate update request. Therefore it should not be reset when we run the
- // updates later in this function.
- var mozAddUrls = [ "moz-reset.com/a" ];
- var mozUpdate = buildMozPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : mozAddUrls
- }]);
-
- var dataUpdate = "data:," + encodeURIComponent(mozUpdate);
-
- streamUpdater.downloadUpdates(mozTables, "", true,
- dataUpdate, () => {}, updateError, updateError);
-
- var addUrls1 = [ "foo-reset.com/a", "foo-reset.com/b" ];
- var update1 = buildPhishingUpdate(
- [
- { "chunkNum" : 1,
- "urls" : addUrls1
- }]);
-
- var update2 = "n:1000\nr:pleasereset\n";
-
- var addUrls3 = [ "bar-reset.com/a", "bar-reset.com/b" ];
- var update3 = buildPhishingUpdate(
- [
- { "chunkNum" : 3,
- "urls" : addUrls3
- }]);
-
- var assertions = {
- "tableData" : "moz-phish-simple;a:1\ntest-phish-simple;a:3", // tables that should still be there.
- "mozPhishingUrlsExist" : mozAddUrls, // mozAddUrls added prior to the reset
- // but it should still exist after reset.
- "urlsExist" : addUrls3, // addUrls3 added after the reset.
- "urlsDontExist" : addUrls1 // addUrls1 added prior to the reset
- };
-
- // Use these update responses in order. The update request only
- // contains test-*-simple tables so the reset will only apply to these.
- doTest([update1, update2, update3], assertions, false);
-}
-
-
-function run_test()
-{
- runTests([
- testSimpleForward,
- testNestedForward,
- testInvalidUrlForward,
- testErrorUrlForward,
- testMultipleTables,
- testUrlInMultipleTables,
- testReset
- ]);
-}
-
-do_test_pending();
diff --git a/toolkit/components/url-classifier/tests/unit/test_threat_type_conversion.js b/toolkit/components/url-classifier/tests/unit/test_threat_type_conversion.js
deleted file mode 100644
index f7c51b956..000000000
--- a/toolkit/components/url-classifier/tests/unit/test_threat_type_conversion.js
+++ /dev/null
@@ -1,37 +0,0 @@
-function run_test() {
- let urlUtils = Cc["@mozilla.org/url-classifier/utils;1"]
- .getService(Ci.nsIUrlClassifierUtils);
-
- // Test list name to threat type conversion.
-
- equal(urlUtils.convertListNameToThreatType("goog-malware-proto"), 1);
- equal(urlUtils.convertListNameToThreatType("googpub-phish-proto"), 2);
- equal(urlUtils.convertListNameToThreatType("goog-unwanted-proto"), 3);
- equal(urlUtils.convertListNameToThreatType("goog-phish-proto"), 5);
-
- try {
- urlUtils.convertListNameToThreatType("bad-list-name");
- ok(false, "Bad list name should lead to exception.");
- } catch (e) {}
-
- try {
- urlUtils.convertListNameToThreatType("bad-list-name");
- ok(false, "Bad list name should lead to exception.");
- } catch (e) {}
-
- // Test threat type to list name conversion.
- equal(urlUtils.convertThreatTypeToListNames(1), "goog-malware-proto");
- equal(urlUtils.convertThreatTypeToListNames(2), "googpub-phish-proto,test-phish-proto");
- equal(urlUtils.convertThreatTypeToListNames(3), "goog-unwanted-proto,test-unwanted-proto");
- equal(urlUtils.convertThreatTypeToListNames(5), "goog-phish-proto");
-
- try {
- urlUtils.convertThreatTypeToListNames(0);
- ok(false, "Bad threat type should lead to exception.");
- } catch (e) {}
-
- try {
- urlUtils.convertThreatTypeToListNames(100);
- ok(false, "Bad threat type should lead to exception.");
- } catch (e) {}
-} \ No newline at end of file
diff --git a/toolkit/components/url-classifier/tests/unit/xpcshell.ini b/toolkit/components/url-classifier/tests/unit/xpcshell.ini
deleted file mode 100644
index c34d575c6..000000000
--- a/toolkit/components/url-classifier/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,24 +0,0 @@
-[DEFAULT]
-head = head_urlclassifier.js
-tail = tail_urlclassifier.js
-skip-if = toolkit == 'android'
-support-files =
- data/digest1.chunk
- data/digest2.chunk
-
-[test_addsub.js]
-[test_bug1274685_unowned_list.js]
-[test_backoff.js]
-[test_dbservice.js]
-[test_hashcompleter.js]
-# Bug 752243: Profile cleanup frequently fails
-#skip-if = os == "mac" || os == "linux"
-[test_partial.js]
-[test_prefixset.js]
-[test_threat_type_conversion.js]
-[test_provider_url.js]
-[test_streamupdater.js]
-[test_digest256.js]
-[test_listmanager.js]
-[test_pref.js]
-[test_safebrowsing_protobuf.js]
diff --git a/toolkit/components/url-classifier/tests/unittests.xul b/toolkit/components/url-classifier/tests/unittests.xul
deleted file mode 100644
index 0c9ce898b..000000000
--- a/toolkit/components/url-classifier/tests/unittests.xul
+++ /dev/null
@@ -1,188 +0,0 @@
-<?xml version="1.0"?>
-<window id="PROT_unittest"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="onProtUnittestLoad();"
- title="prot unittests">
-
-<script><![CDATA[
- const Cc = Components.classes;
- const Ci = Components.interfaces;
-
- function G_Debug(zone, s) {
- var label = document.createElement('label');
- var txt = "[" + zone + "] " + s;
- label.appendChild(document.createTextNode(txt));
-
- document.documentElement.appendChild(label);
- }
-
- function G_Assert(zone, cond, msg) {
- if (!cond) {
- G_Debug(zone, msg);
- throw msg;
- }
- }
-
- function ProtectionTableTests() {
- var z = "trtable UNITTEST";
-
- G_Debug(z, "Starting");
-
- var url = "http://www.yahoo.com?foo=bar";
- var url2 = "http://168.188.99.26/.secure/www.ebay.com/";
- var urlTable = Cc['@mozilla.org/url-classifier/table;1?type=url']
- .createInstance(Ci.nsIUrlClassifierTable);
- urlTable.insert(url, "1");
- urlTable.insert(url2, "1");
- G_Assert(z, urlTable.exists(url), "URL lookups broken");
- G_Assert(z, !urlTable.exists("about:config"), "about:config breaks domlook");
- G_Assert(z, urlTable.exists(url2), "URL lookups broken");
- G_Assert(z, urlTable.exists("http://%31%36%38%2e%31%38%38%2e%39%39%2e%32%36/%2E%73%65%63%75%72%65/%77%77%77%2E%65%62%61%79%2E%63%6F%6D/") == true,
- "URL Canonicalization broken");
- G_Assert(z, urlTable.count == 2, 'urlTable: wrong size');
-
- var dom1 = "bar.com";
- var dom2 = "amazon.co.uk";
- var dom3 = "127.0.0.1";
- var domainTable = Cc['@mozilla.org/url-classifier/table;1?type=domain']
- .createInstance(Ci.nsIUrlClassifierTable);
- domainTable.insert(dom1, "1");
- domainTable.insert(dom2, "1");
- domainTable.insert(dom3, "1");
- G_Assert(z, domainTable.exists("http://www.bar.com/?zaz=asdf#url"),
- "Domain lookups broken (single dot)");
- G_Assert(z, domainTable.exists("http://www.amazon.co.uk/?z=af#url"),
- "Domain lookups broken (two dots)");
- G_Assert(z, domainTable.exists("http://127.0.0.1/?z=af#url"),
- "Domain lookups broken (IP)");
- G_Assert(z, domainTable.count == 3, 'domainTable: wrong size');
-
- var site1 = "google.com/safebrowsing/";
- var site2 = "www.foo.bar/";
- var site3 = "127.0.0.1/";
- var siteTable = Cc['@mozilla.org/url-classifier/table;1?type=site']
- .createInstance(Ci.nsIUrlClassifierTable);
- siteTable.insert(site1, "1");
- siteTable.insert(site2, "1");
- siteTable.insert(site3, "1");
- G_Assert(z, siteTable.exists("http://www.google.com/safebrowsing/1.php"),
- "Site lookups broken - reducing");
- G_Assert(z, siteTable.exists("http://www.foo.bar/some/random/path"),
- "Site lookups broken - fqdn");
- G_Assert(z, siteTable.exists("http://127.0.0.1/something?hello=1"),
- "Site lookups broken - IP");
- G_Assert(z, !siteTable.exists("http://www.google.com/search/"),
- "Site lookups broken - overreaching");
- G_Assert(z, siteTable.count == 3, 'siteTable: wrong size');
-
- var url1 = "http://poseidon.marinet.gr/~eleni/eBay/index.php";
- var domainHash = "01844755C8143C4579BB28DD59C23747";
- var enchashTable = Cc['@mozilla.org/url-classifier/table;1?type=enchash']
- .createInstance(Ci.nsIUrlClassifierTable);
- enchashTable.insert(domainHash, "bGtEQWJuMl9FA3Kl5RiXMpgFU8nDJl9J0hXjUck9+"
- + "mMUQwAN6llf0gJeY5DIPPc2f+a8MSBFJN17ANGJ"
- + "Zl5oZVsQfSW4i12rlScsx4tweZAE");
- G_Assert(z, enchashTable.exists(url1), 'enchash lookup failed');
- G_Assert(z, !enchashTable.exists(url1 + '/foo'),
- "enchash lookup broken - overreaching");
- G_Assert(z, enchashTable.count == 1, 'enchashTable: wrong size');
-
- // TODO: test replace
- G_Debug(z, "PASSED");
- }
-
- function ProtectionListManagerTests() {
- var z = "listmanager UNITTEST";
- G_Debug(z, "Starting");
-
- // test lookup and register
- var listManagerInst = Cc["@mozilla.org/url-classifier/listmanager;1"]
- .createInstance(Ci.nsIUrlListManager);
- var listName = 'foo-bar-url';
- listManagerInst.registerTable(listName, false);
- listManagerInst.safeInsert(listName, 'test', '1');
- G_Assert(z, listManagerInst.safeExists(listName, 'test'),
- 'insert/exist failed');
-
- // test serialization
- var baseName = (new Date().getTime()) + ".tmp";
- var tempDir = Cc["@mozilla.org/file/directory_service;1"]
- .getService(Ci.nsIProperties)
- .get("TmpD", Ci.nsILocalFile);
- tempDir.append(baseName);
- tempDir.createUnique(tempDir.DIRECTORY_TYPE, 0744);
-
- var listManager = Cc["@mozilla.org/url-classifier/listmanager;1"]
- .getService(Ci.nsIUrlListManager);
- listManager.setAppDir(tempDir);
-
- var data = "";
-
- var set1Name = "test1-foo-domain";
- data += "[" + set1Name + " 1.2]\n";
- var set1 = {};
- for (var i = 0; i < 10; i++) {
- set1["http://" + i + ".com"] = 1;
- data += "+" + i + ".com\t1\n";
- }
-
- data += "\n";
- var set2Name = "test2-foo-domain";
- // TODO must have blank line
- data += "\n[" + set2Name + " 1.7]\n";
- var set2 = {};
- for (var i = 0; i < 5; i++) {
- set2["http://" + i + ".com"] = 1;
- data += "+" + i + ".com\t1\n";
- }
-
- function deserialized(tablesKnown, tablesData) {
- listManager.wrappedJSObject.dataReady(tablesKnown, tablesData);
-
- var file = tempDir.clone();
- file.append(set1Name + ".sst");
- G_Assert(z, file.exists() && file.isFile() && file.isReadable(),
- "Failed to write out: " + file.path);
-
- file = tempDir.clone();
- file.append(set2Name + ".sst");
- G_Assert(z, file.exists() && file.isFile() && file.isReadable(),
- "Failed to write out: " + file.path);
-
- // now try to read them back from disk
- listManager = Cc["@mozilla.org/url-classifier/listmanager;1"]
- .createInstance(Ci.nsIUrlListManager);
- listManager.setAppDir(tempDir);
- var tables = [ set1Name, set2Name ];
- listManager.enableUpdate(set1Name);
- listManager.enableUpdate(set2Name);
- listManager.wrappedJSObject.readDataFiles();
-
- // assert that the values match
- for (var prop in set1) {
- G_Assert(z,
- listManager.wrappedJSObject.tablesData[set1Name].exists(prop),
- "Couldn't find member " + prop + "of set1 from disk.");
- }
-
- for (var prop in set2) {
- G_Assert(z,
- listManager.wrappedJSObject.tablesData[set2Name].exists(prop),
- "Couldn't find member " + prop + "of set2 from disk.");
- }
-
- tempDir.remove(true);
-
- G_Debug(z, "PASSED");
- };
-
- // Use the unwrapped object for the unittest
- listManager.wrappedJSObject.deserialize_(data, deserialized);
- }
-
- function onProtUnittestLoad() {
- ProtectionTableTests();
- ProtectionListManagerTests();
- }
-]]></script>
-</window>
diff --git a/toolkit/components/urlformatter/moz.build b/toolkit/components/urlformatter/moz.build
index 1543fddda..c7a3ac76e 100644
--- a/toolkit/components/urlformatter/moz.build
+++ b/toolkit/components/urlformatter/moz.build
@@ -4,24 +4,14 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPCSHELL_TESTS_MANIFESTS += ['tests/unit/xpcshell.ini']
-
-XPIDL_SOURCES += [
- 'nsIURLFormatter.idl',
-]
+XPIDL_SOURCES += ['nsIURLFormatter.idl']
XPIDL_MODULE = 'urlformatter'
-EXTRA_COMPONENTS += [
- 'nsURLFormatter.manifest',
-]
+EXTRA_COMPONENTS += ['nsURLFormatter.manifest']
-EXTRA_PP_COMPONENTS += [
- 'nsURLFormatter.js',
-]
+EXTRA_PP_COMPONENTS += ['nsURLFormatter.js']
-CONFIGURE_SUBST_FILES += [
- 'api_keys',
-]
+CONFIGURE_SUBST_FILES += ['api_keys']
DEFINES['OBJDIR'] = OBJDIR
diff --git a/toolkit/components/urlformatter/tests/unit/.eslintrc.js b/toolkit/components/urlformatter/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/urlformatter/tests/unit/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/urlformatter/tests/unit/head_urlformatter.js b/toolkit/components/urlformatter/tests/unit/head_urlformatter.js
deleted file mode 100644
index 8af2aaac4..000000000
--- a/toolkit/components/urlformatter/tests/unit/head_urlformatter.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 Cc = Components.classes;
-var Ci = Components.interfaces;
-var Cr = Components.results;
-var Cu = Components.utils;
-
-Cu.import("resource://testing-common/AppInfo.jsm", this);
-updateAppInfo({
- name: "Url Formatter Test",
- ID: "urlformattertest@test.mozilla.org",
- version: "1",
- platformVersion: "2.0",
-});
-var gAppInfo = getAppInfo();
diff --git a/toolkit/components/urlformatter/tests/unit/test_urlformatter.js b/toolkit/components/urlformatter/tests/unit/test_urlformatter.js
deleted file mode 100644
index 6f218822a..000000000
--- a/toolkit/components/urlformatter/tests/unit/test_urlformatter.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-function run_test() {
- var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
- getService(Ci.nsIURLFormatter);
- var locale = Cc["@mozilla.org/chrome/chrome-registry;1"].
- getService(Ci.nsIXULChromeRegistry).
- getSelectedLocale('global');
- var prefs = Cc['@mozilla.org/preferences-service;1'].
- getService(Ci.nsIPrefBranch);
- var sysInfo = Cc["@mozilla.org/system-info;1"].
- getService(Ci.nsIPropertyBag2);
- var OSVersion = sysInfo.getProperty("name") + " " +
- sysInfo.getProperty("version");
- try {
- OSVersion += " (" + sysInfo.getProperty("secondaryLibrary") + ")";
- } catch (e) {}
- OSVersion = encodeURIComponent(OSVersion);
- var macutils = null;
- try {
- macutils = Cc["@mozilla.org/xpcom/mac-utils;1"].
- getService(Ci.nsIMacUtils);
- } catch (e) {}
- var appInfo = Cc["@mozilla.org/xre/app-info;1"].
- getService(Ci.nsIXULAppInfo).
- QueryInterface(Ci.nsIXULRuntime);
- var abi = macutils && macutils.isUniversalBinary ? "Universal-gcc3" : appInfo.XPCOMABI;
-
- let defaults = prefs.QueryInterface(Ci.nsIPrefService).getDefaultBranch(null);
- let channel = defaults.getCharPref("app.update.channel", "default");
-
- // Set distribution values.
- defaults.setCharPref("distribution.id", "bacon");
- defaults.setCharPref("distribution.version", "1.0");
-
- var upperUrlRaw = "http://%LOCALE%.%VENDOR%.foo/?name=%NAME%&id=%ID%&version=%VERSION%&platversion=%PLATFORMVERSION%&abid=%APPBUILDID%&pbid=%PLATFORMBUILDID%&app=%APP%&os=%OS%&abi=%XPCOMABI%";
- var lowerUrlRaw = "http://%locale%.%vendor%.foo/?name=%name%&id=%id%&version=%version%&platversion=%platformversion%&abid=%appbuildid%&pbid=%platformbuildid%&app=%app%&os=%os%&abi=%xpcomabi%";
- // XXX %APP%'s RegExp is not global, so it only replaces the first space
- var ulUrlRef = "http://" + locale + ".Mozilla.foo/?name=Url Formatter Test&id=urlformattertest@test.mozilla.org&version=1&platversion=2.0&abid=" + gAppInfo.appBuildID + "&pbid=" + gAppInfo.platformBuildID + "&app=urlformatter test&os=XPCShell&abi=" + abi;
- var multiUrl = "http://%VENDOR%.%VENDOR%.%NAME%.%VENDOR%.%NAME%";
- var multiUrlRef = "http://Mozilla.Mozilla.Url Formatter Test.Mozilla.Url Formatter Test";
- var encodedUrl = "https://%LOCALE%.%VENDOR%.foo/?q=%E3%82%BF%E3%83%96&app=%NAME%&ver=%PLATFORMVERSION%";
- var encodedUrlRef = "https://" + locale + ".Mozilla.foo/?q=%E3%82%BF%E3%83%96&app=Url Formatter Test&ver=2.0";
- var advancedUrl = "http://test.mozilla.com/%NAME%/%VERSION%/%APPBUILDID%/%BUILD_TARGET%/%LOCALE%/%CHANNEL%/%OS_VERSION%/%DISTRIBUTION%/%DISTRIBUTION_VERSION%/";
- var advancedUrlRef = "http://test.mozilla.com/Url Formatter Test/1/" + gAppInfo.appBuildID + "/XPCShell_" + abi + "/" + locale + "/" + channel + "/" + OSVersion + "/bacon/1.0/";
-
- var pref = "xpcshell.urlformatter.test";
- var str = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- str.data = upperUrlRaw;
- prefs.setComplexValue(pref, Ci.nsISupportsString, str);
-
- do_check_eq(formatter.formatURL(upperUrlRaw), ulUrlRef);
- do_check_eq(formatter.formatURLPref(pref), ulUrlRef);
- // Keys must be uppercase
- do_check_neq(formatter.formatURL(lowerUrlRaw), ulUrlRef);
- do_check_eq(formatter.formatURL(multiUrl), multiUrlRef);
- // Encoded strings must be kept as is (Bug 427304)
- do_check_eq(formatter.formatURL(encodedUrl), encodedUrlRef);
-
- do_check_eq(formatter.formatURL(advancedUrl), advancedUrlRef);
-}
diff --git a/toolkit/components/urlformatter/tests/unit/xpcshell.ini b/toolkit/components/urlformatter/tests/unit/xpcshell.ini
deleted file mode 100644
index 2f82beaa3..000000000
--- a/toolkit/components/urlformatter/tests/unit/xpcshell.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-head = head_urlformatter.js
-tail =
-skip-if = toolkit == 'android'
-
-[test_urlformatter.js]
diff --git a/toolkit/components/viewsource/moz.build b/toolkit/components/viewsource/moz.build
index aecd25682..965c0b66f 100644
--- a/toolkit/components/viewsource/moz.build
+++ b/toolkit/components/viewsource/moz.build
@@ -4,14 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-BROWSER_CHROME_MANIFESTS += ['test/browser/browser.ini']
-MOCHITEST_CHROME_MANIFESTS += ['test/chrome.ini']
+EXTRA_JS_MODULES += ['ViewSourceBrowser.jsm']
-JAR_MANIFESTS += ['jar.mn']
-
-EXTRA_JS_MODULES += [
- 'ViewSourceBrowser.jsm',
-]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'View Source')
+JAR_MANIFESTS += ['jar.mn'] \ No newline at end of file
diff --git a/toolkit/components/viewsource/test/.eslintrc.js b/toolkit/components/viewsource/test/.eslintrc.js
deleted file mode 100644
index 2c669d844..000000000
--- a/toolkit/components/viewsource/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/viewsource/test/browser/.eslintrc.js b/toolkit/components/viewsource/test/browser/.eslintrc.js
deleted file mode 100644
index 7c8021192..000000000
--- a/toolkit/components/viewsource/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/viewsource/test/browser/browser.ini b/toolkit/components/viewsource/test/browser/browser.ini
deleted file mode 100644
index d9ebbd25f..000000000
--- a/toolkit/components/viewsource/test/browser/browser.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-support-files = head.js
- file_bug464222.html
-
-[browser_bug464222.js]
-[browser_bug699356.js]
-[browser_bug713810.js]
-[browser_contextmenu.js]
-subsuite = clipboard
-[browser_gotoline.js]
-[browser_srcdoc.js]
-[browser_viewsourceprefs.js]
diff --git a/toolkit/components/viewsource/test/browser/browser_bug464222.js b/toolkit/components/viewsource/test/browser/browser_bug464222.js
deleted file mode 100644
index 30c4fb67a..000000000
--- a/toolkit/components/viewsource/test/browser/browser_bug464222.js
+++ /dev/null
@@ -1,12 +0,0 @@
-const source = "http://example.com/browser/toolkit/components/viewsource/test/browser/file_bug464222.html";
-
-add_task(function *() {
- let viewSourceTab = yield* openDocumentSelect(source, "a");
-
- let href = yield ContentTask.spawn(viewSourceTab.linkedBrowser, { }, function* () {
- return content.document.querySelectorAll("a[href]")[0].href;
- });
-
- is(href, "view-source:" + source, "Relative links broken?");
- gBrowser.removeTab(viewSourceTab);
-});
diff --git a/toolkit/components/viewsource/test/browser/browser_bug699356.js b/toolkit/components/viewsource/test/browser/browser_bug699356.js
deleted file mode 100644
index e55c4cf20..000000000
--- a/toolkit/components/viewsource/test/browser/browser_bug699356.js
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-function test() {
- let source = "about:blank";
-
- waitForExplicitFinish();
- openViewSourceWindow(source, function(aWindow) {
- let gBrowser = aWindow.gBrowser;
- let docEl = aWindow.document.documentElement;
-
- is(gBrowser.contentDocument.title, source, "Correct document title");
- is(docEl.getAttribute("title"),
- "Source of: " + source + ("nsILocalFileMac" in Components.interfaces ? "" : " - " + docEl.getAttribute("titlemodifier")),
- "Correct window title");
- closeViewSourceWindow(aWindow, finish);
- });
-}
diff --git a/toolkit/components/viewsource/test/browser/browser_bug713810.js b/toolkit/components/viewsource/test/browser/browser_bug713810.js
deleted file mode 100644
index d5b2f3424..000000000
--- a/toolkit/components/viewsource/test/browser/browser_bug713810.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const source = '<html xmlns="http://www.w3.org/1999/xhtml"><body><p>This is a paragraph.</p></body></html>';
-
-add_task(function *() {
- let viewSourceTab = yield* openDocumentSelect("data:text/html," + source, "p");
- yield ContentTask.spawn(viewSourceTab.linkedBrowser, null, function* () {
- Assert.equal(content.document.body.textContent, "<p>This is a paragraph.</p>",
- "Correct source for text/html");
- });
- gBrowser.removeTab(viewSourceTab);
-
- viewSourceTab = yield* openDocumentSelect("data:application/xhtml+xml," + source, "p");
- yield ContentTask.spawn(viewSourceTab.linkedBrowser, null, function* () {
- Assert.equal(content.document.body.textContent,
- '<p xmlns="http://www.w3.org/1999/xhtml">This is a paragraph.</p>',
- "Correct source for application/xhtml+xml");
- });
- gBrowser.removeTab(viewSourceTab);
-});
-
diff --git a/toolkit/components/viewsource/test/browser/browser_contextmenu.js b/toolkit/components/viewsource/test/browser/browser_contextmenu.js
deleted file mode 100644
index 72b8a40be..000000000
--- a/toolkit/components/viewsource/test/browser/browser_contextmenu.js
+++ /dev/null
@@ -1,107 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var source = "data:text/html,text<link%20href='http://example.com/'%20/>more%20text<a%20href='mailto:abc@def.ghi'>email</a>";
-var gViewSourceWindow, gContextMenu, gCopyLinkMenuItem, gCopyEmailMenuItem;
-
-var expectedData = [];
-
-add_task(function *() {
- // Full source in view source window
- let newWindow = yield loadViewSourceWindow(source);
- yield SimpleTest.promiseFocus(newWindow);
-
- yield* onViewSourceWindowOpen(newWindow, false);
-
- let contextMenu = gViewSourceWindow.document.getElementById("viewSourceContextMenu");
-
- for (let test of expectedData) {
- yield* checkMenuItems(contextMenu, false, test[0], test[1], test[2], test[3]);
- }
-
- yield new Promise(resolve => {
- closeViewSourceWindow(newWindow, resolve);
- });
-
- // Selection source in view source tab
- expectedData = [];
- let newTab = yield openDocumentSelect(source, "body");
- yield* onViewSourceWindowOpen(window, true);
-
- contextMenu = document.getElementById("contentAreaContextMenu");
-
- for (let test of expectedData) {
- yield* checkMenuItems(contextMenu, true, test[0], test[1], test[2], test[3]);
- }
-
- gBrowser.removeTab(newTab);
-
- // Selection source in view source window
- yield pushPrefs(["view_source.tab", false]);
-
- expectedData = [];
- newWindow = yield openDocumentSelect(source, "body");
- yield SimpleTest.promiseFocus(newWindow);
-
- yield* onViewSourceWindowOpen(newWindow, false);
-
- contextMenu = newWindow.document.getElementById("viewSourceContextMenu");
-
- for (let test of expectedData) {
- yield* checkMenuItems(contextMenu, false, test[0], test[1], test[2], test[3]);
- }
-
- yield new Promise(resolve => {
- closeViewSourceWindow(newWindow, resolve);
- });
-});
-
-function* onViewSourceWindowOpen(aWindow, aIsTab) {
- gViewSourceWindow = aWindow;
-
- gCopyLinkMenuItem = aWindow.document.getElementById(aIsTab ? "context-copylink" : "context-copyLink");
- gCopyEmailMenuItem = aWindow.document.getElementById(aIsTab ? "context-copyemail" : "context-copyEmail");
-
- let browser = aIsTab ? gBrowser.selectedBrowser : gViewSourceWindow.gBrowser;
- yield ContentTask.spawn(browser, null, function* (arg) {
- let tags = content.document.querySelectorAll("a[href]");
- Assert.equal(tags[0].href, "view-source:http://example.com/", "Link has correct href");
- Assert.equal(tags[1].href, "mailto:abc@def.ghi", "Link has correct href");
- });
-
- expectedData.push(["a[href]", true, false, "http://example.com/"]);
- expectedData.push(["a[href^=mailto]", false, true, "abc@def.ghi"]);
- expectedData.push(["span", false, false, null]);
-}
-
-function* checkMenuItems(contextMenu, isTab, selector, copyLinkExpected, copyEmailExpected, expectedClipboardContent) {
-
- let browser = isTab ? gBrowser.selectedBrowser : gViewSourceWindow.gBrowser;
- yield ContentTask.spawn(browser, { selector: selector }, function* (arg) {
- content.document.querySelector(arg.selector).scrollIntoView();
- });
-
- let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter(selector,
- { type: "contextmenu", button: 2}, browser);
- yield popupShownPromise;
-
- is(gCopyLinkMenuItem.hidden, !copyLinkExpected, "Copy link menuitem is " + (copyLinkExpected ? "not hidden" : "hidden"));
- is(gCopyEmailMenuItem.hidden, !copyEmailExpected, "Copy email menuitem is " + (copyEmailExpected ? "not hidden" : "hidden"));
-
- if (copyLinkExpected || copyEmailExpected) {
- yield new Promise((resolve, reject) => {
- waitForClipboard(expectedClipboardContent, function() {
- if (copyLinkExpected)
- gCopyLinkMenuItem.click();
- else
- gCopyEmailMenuItem.click();
- }, resolve, reject);
- });
- }
-
- let popupHiddenPromise = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- contextMenu.hidePopup();
- yield popupHiddenPromise;
-}
diff --git a/toolkit/components/viewsource/test/browser/browser_gotoline.js b/toolkit/components/viewsource/test/browser/browser_gotoline.js
deleted file mode 100644
index 5bb45f9ca..000000000
--- a/toolkit/components/viewsource/test/browser/browser_gotoline.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-Cu.import("resource://testing-common/ContentTaskUtils.jsm", this);
-
-var content = "line 1\nline 2\nline 3";
-
-add_task(function*() {
- // First test with text with the text/html mimetype.
- let win = yield loadViewSourceWindow("data:text/html," + encodeURIComponent(content));
- yield checkViewSource(win);
- yield BrowserTestUtils.closeWindow(win);
-
- win = yield loadViewSourceWindow("data:text/plain," + encodeURIComponent(content));
- yield checkViewSource(win);
- yield BrowserTestUtils.closeWindow(win);
-});
-
-var checkViewSource = Task.async(function* (aWindow) {
- is(aWindow.gBrowser.contentDocument.body.textContent, content, "Correct content loaded");
- let statusPanel = aWindow.document.getElementById("statusbar-line-col");
- is(statusPanel.getAttribute("label"), "", "Correct status bar text");
-
- for (let i = 1; i <= 3; i++) {
- aWindow.viewSourceChrome.goToLine(i);
- yield ContentTask.spawn(aWindow.gBrowser, i, function*(i) {
- let selection = content.getSelection();
- Assert.equal(selection.toString(), "line " + i, "Correct text selected");
- });
-
- yield ContentTaskUtils.waitForCondition(() => {
- return (statusPanel.getAttribute("label") == "Line " + i + ", Col 1");
- }, "Correct status bar text");
- }
-});
diff --git a/toolkit/components/viewsource/test/browser/browser_srcdoc.js b/toolkit/components/viewsource/test/browser/browser_srcdoc.js
deleted file mode 100644
index 542741ffc..000000000
--- a/toolkit/components/viewsource/test/browser/browser_srcdoc.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-const frameSource = `<a href="about:mozilla">good</a>`;
-const source = `<html><iframe srcdoc='${frameSource}' id="f"></iframe></html>`;
-
-add_task(function*() {
- let url = `data:text/html,${source}`;
- yield BrowserTestUtils.withNewTab({ gBrowser, url }, checkFrameSource);
-});
-
-function* checkFrameSource() {
- let sourceTab = yield openViewFrameSourceTab("#f");
- registerCleanupFunction(function() {
- gBrowser.removeTab(sourceTab);
- });
-
- yield waitForSourceLoaded(sourceTab);
-
- let browser = gBrowser.selectedBrowser;
- let textContent = yield ContentTask.spawn(browser, {}, function*() {
- return content.document.body.textContent;
- });
- is(textContent, frameSource, "Correct content loaded");
- let id = yield ContentTask.spawn(browser, {}, function*() {
- return content.document.body.id;
- });
- is(id, "viewsource", "View source mode enabled")
-}
diff --git a/toolkit/components/viewsource/test/browser/browser_viewsourceprefs.js b/toolkit/components/viewsource/test/browser/browser_viewsourceprefs.js
deleted file mode 100644
index 7361a70a5..000000000
--- a/toolkit/components/viewsource/test/browser/browser_viewsourceprefs.js
+++ /dev/null
@@ -1,136 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-var plaintextURL = "data:text/plain,hello+world";
-var htmlURL = "about:mozilla";
-
-add_task(function* setup() {
- registerCleanupFunction(function() {
- SpecialPowers.clearUserPref("view_source.tab_size");
- SpecialPowers.clearUserPref("view_source.wrap_long_lines");
- SpecialPowers.clearUserPref("view_source.syntax_highlight");
- });
-});
-
-add_task(function*() {
- yield exercisePrefs(plaintextURL, false);
- yield exercisePrefs(htmlURL, true);
-});
-
-var exercisePrefs = Task.async(function* (source, highlightable) {
- let win = yield loadViewSourceWindow(source);
- let wrapMenuItem = win.document.getElementById("menu_wrapLongLines");
- let syntaxMenuItem = win.document.getElementById("menu_highlightSyntax");
-
- // Strip checked="false" attributes, since we're not interested in them.
- if (wrapMenuItem.getAttribute("checked") == "false") {
- wrapMenuItem.removeAttribute("checked");
- }
- if (syntaxMenuItem.getAttribute("checked") == "false") {
- syntaxMenuItem.removeAttribute("checked");
- }
-
- // Test the default states of these menu items.
- is(wrapMenuItem.hasAttribute("checked"), false,
- "Wrap menu item not checked by default");
- is(syntaxMenuItem.hasAttribute("checked"), true,
- "Syntax menu item checked by default");
-
- yield checkStyle(win, "-moz-tab-size", 4);
- yield checkStyle(win, "white-space", "pre");
-
- // Next, test that the Wrap Long Lines menu item works.
- let prefReady = waitForPrefChange("view_source.wrap_long_lines");
- simulateClick(wrapMenuItem);
- is(wrapMenuItem.hasAttribute("checked"), true, "Wrap menu item checked");
- yield prefReady;
- is(SpecialPowers.getBoolPref("view_source.wrap_long_lines"), true, "Wrap pref set");
-
- yield checkStyle(win, "white-space", "pre-wrap");
-
- prefReady = waitForPrefChange("view_source.wrap_long_lines");
- simulateClick(wrapMenuItem);
- is(wrapMenuItem.hasAttribute("checked"), false, "Wrap menu item unchecked");
- yield prefReady;
- is(SpecialPowers.getBoolPref("view_source.wrap_long_lines"), false, "Wrap pref set");
- yield checkStyle(win, "white-space", "pre");
-
- // Check that the Syntax Highlighting menu item works.
- prefReady = waitForPrefChange("view_source.syntax_highlight");
- simulateClick(syntaxMenuItem);
- is(syntaxMenuItem.hasAttribute("checked"), false, "Syntax menu item unchecked");
- yield prefReady;
- is(SpecialPowers.getBoolPref("view_source.syntax_highlight"), false, "Syntax highlighting pref set");
- yield checkHighlight(win, false);
-
- prefReady = waitForPrefChange("view_source.syntax_highlight");
- simulateClick(syntaxMenuItem);
- is(syntaxMenuItem.hasAttribute("checked"), true, "Syntax menu item checked");
- yield prefReady;
- is(SpecialPowers.getBoolPref("view_source.syntax_highlight"), true, "Syntax highlighting pref set");
- yield checkHighlight(win, highlightable);
- yield BrowserTestUtils.closeWindow(win);
-
- // Open a new view-source window to check that the prefs are obeyed.
- SpecialPowers.setIntPref("view_source.tab_size", 2);
- SpecialPowers.setBoolPref("view_source.wrap_long_lines", true);
- SpecialPowers.setBoolPref("view_source.syntax_highlight", false);
-
- win = yield loadViewSourceWindow(source);
- wrapMenuItem = win.document.getElementById("menu_wrapLongLines");
- syntaxMenuItem = win.document.getElementById("menu_highlightSyntax");
-
- // Strip checked="false" attributes, since we're not interested in them.
- if (wrapMenuItem.getAttribute("checked") == "false") {
- wrapMenuItem.removeAttribute("checked");
- }
- if (syntaxMenuItem.getAttribute("checked") == "false") {
- syntaxMenuItem.removeAttribute("checked");
- }
-
- is(wrapMenuItem.hasAttribute("checked"), true, "Wrap menu item checked");
- is(syntaxMenuItem.hasAttribute("checked"), false, "Syntax menu item unchecked");
- yield checkStyle(win, "-moz-tab-size", 2);
- yield checkStyle(win, "white-space", "pre-wrap");
- yield checkHighlight(win, false);
-
- SpecialPowers.clearUserPref("view_source.tab_size");
- SpecialPowers.clearUserPref("view_source.wrap_long_lines");
- SpecialPowers.clearUserPref("view_source.syntax_highlight");
-
- yield BrowserTestUtils.closeWindow(win);
-});
-
-// Simulate a menu item click, including toggling the checked state.
-// This saves us from opening the menu and trying to click on the item,
-// which doesn't work on Mac OS X.
-function simulateClick(aMenuItem) {
- if (aMenuItem.hasAttribute("checked"))
- aMenuItem.removeAttribute("checked");
- else
- aMenuItem.setAttribute("checked", "true");
-
- aMenuItem.click();
-}
-
-var checkStyle = Task.async(function* (win, styleProperty, expected) {
- let browser = win.gBrowser;
- let value = yield ContentTask.spawn(browser, styleProperty, function* (styleProperty) {
- let style = content.getComputedStyle(content.document.body, null);
- return style.getPropertyValue(styleProperty);
- });
- is(value, expected, "Correct value of " + styleProperty);
-});
-
-var checkHighlight = Task.async(function* (win, expected) {
- let browser = win.gBrowser;
- let highlighted = yield ContentTask.spawn(browser, {}, function* () {
- let spans = content.document.getElementsByTagName("span");
- return Array.some(spans, (span) => {
- let style = content.getComputedStyle(span, null);
- return style.getPropertyValue("color") !== "rgb(0, 0, 0)";
- });
- });
- is(highlighted, expected, "Syntax highlighting " + (expected ? "on" : "off"));
-});
diff --git a/toolkit/components/viewsource/test/browser/file_bug464222.html b/toolkit/components/viewsource/test/browser/file_bug464222.html
deleted file mode 100644
index 4f2a43f0d..000000000
--- a/toolkit/components/viewsource/test/browser/file_bug464222.html
+++ /dev/null
@@ -1 +0,0 @@
-<a href="file_bug464222.html">I'm a link</a> \ No newline at end of file
diff --git a/toolkit/components/viewsource/test/browser/head.js b/toolkit/components/viewsource/test/browser/head.js
deleted file mode 100644
index bb46369b0..000000000
--- a/toolkit/components/viewsource/test/browser/head.js
+++ /dev/null
@@ -1,200 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-Cu.import("resource://gre/modules/PromiseUtils.jsm");
-Cu.import("resource://gre/modules/Preferences.jsm");
-
-const WINDOW_TYPE = "navigator:view-source";
-
-function openViewSourceWindow(aURI, aCallback) {
- let viewSourceWindow = openDialog("chrome://global/content/viewSource.xul", null, null, aURI);
- viewSourceWindow.addEventListener("pageshow", function pageShowHandler(event) {
- // Wait for the inner window to load, not viewSourceWindow.
- if (event.target.location == "view-source:" + aURI) {
- info("View source window opened: " + event.target.location);
- viewSourceWindow.removeEventListener("pageshow", pageShowHandler, false);
- aCallback(viewSourceWindow);
- }
- }, false);
-}
-
-function loadViewSourceWindow(URL) {
- return new Promise((resolve) => {
- openViewSourceWindow(URL, resolve);
- })
-}
-
-function closeViewSourceWindow(aWindow, aCallback) {
- Services.wm.addListener({
- onCloseWindow: function() {
- Services.wm.removeListener(this);
- executeSoon(aCallback);
- }
- });
- aWindow.close();
-}
-
-function testViewSourceWindow(aURI, aTestCallback, aCloseCallback) {
- openViewSourceWindow(aURI, function(aWindow) {
- aTestCallback(aWindow);
- closeViewSourceWindow(aWindow, aCloseCallback);
- });
-}
-
-function waitForViewSourceWindow() {
- return new Promise(resolve => {
- let windowListener = {
- onOpenWindow(xulWindow) {
- let win = xulWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- win.addEventListener("load", function listener() {
- win.removeEventListener("load", listener, false);
- if (win.document.documentElement.getAttribute("windowtype") !=
- WINDOW_TYPE) {
- return;
- }
- // Found the window
- resolve(win);
- Services.wm.removeListener(windowListener);
- }, false);
- },
- onCloseWindow() {},
- onWindowTitleChange() {}
- };
- Services.wm.addListener(windowListener);
- });
-}
-
-/**
- * Opens a view source tab / window for a selection (View Selection Source)
- * within the currently selected browser in gBrowser.
- *
- * @param aCSSSelector - used to specify a node within the selection to
- * view the source of. It is expected that this node is
- * within an existing selection.
- * @returns the new tab / window which shows the source.
- */
-function* openViewPartialSource(aCSSSelector) {
- let contentAreaContextMenuPopup =
- document.getElementById("contentAreaContextMenu");
- let popupShownPromise =
- BrowserTestUtils.waitForEvent(contentAreaContextMenuPopup, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter(aCSSSelector,
- { type: "contextmenu", button: 2 }, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- let openPromise;
- if (Services.prefs.getBoolPref("view_source.tab")) {
- openPromise = BrowserTestUtils.waitForNewTab(gBrowser, null);
- } else {
- openPromise = waitForViewSourceWindow();
- }
-
- let popupHiddenPromise =
- BrowserTestUtils.waitForEvent(contentAreaContextMenuPopup, "popuphidden");
- let item = document.getElementById("context-viewpartialsource-selection");
- EventUtils.synthesizeMouseAtCenter(item, {});
- yield popupHiddenPromise;
-
- return (yield openPromise);
-}
-
-/**
- * Opens a view source tab for a frame (View Frame Source) within the
- * currently selected browser in gBrowser.
- *
- * @param aCSSSelector - used to specify the frame to view the source of.
- * @returns the new tab which shows the source.
- */
-function* openViewFrameSourceTab(aCSSSelector) {
- let contentAreaContextMenuPopup =
- document.getElementById("contentAreaContextMenu");
- let popupShownPromise =
- BrowserTestUtils.waitForEvent(contentAreaContextMenuPopup, "popupshown");
- yield BrowserTestUtils.synthesizeMouseAtCenter(aCSSSelector,
- { type: "contextmenu", button: 2 }, gBrowser.selectedBrowser);
- yield popupShownPromise;
-
- let frameContextMenu = document.getElementById("frame");
- popupShownPromise =
- BrowserTestUtils.waitForEvent(frameContextMenu, "popupshown");
- EventUtils.synthesizeMouseAtCenter(frameContextMenu, {});
- yield popupShownPromise;
-
- let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, null);
-
- let popupHiddenPromise =
- BrowserTestUtils.waitForEvent(frameContextMenu, "popuphidden");
- let item = document.getElementById("context-viewframesource");
- EventUtils.synthesizeMouseAtCenter(item, {});
- yield popupHiddenPromise;
-
- return (yield newTabPromise);
-}
-
-registerCleanupFunction(function() {
- var windows = Services.wm.getEnumerator(WINDOW_TYPE);
- ok(!windows.hasMoreElements(), "No remaining view source windows still open");
- while (windows.hasMoreElements())
- windows.getNext().close();
-});
-
-/**
- * For a given view source tab / window, wait for the source loading step to
- * complete.
- */
-function waitForSourceLoaded(tabOrWindow) {
- return new Promise(resolve => {
- let mm = tabOrWindow.messageManager ||
- tabOrWindow.linkedBrowser.messageManager;
- mm.addMessageListener("ViewSource:SourceLoaded", function sourceLoaded() {
- mm.removeMessageListener("ViewSource:SourceLoaded", sourceLoaded);
- setTimeout(resolve, 0);
- });
- });
-}
-
-/**
- * Open a new document in a new tab, select part of it, and view the source of
- * that selection. The document is not closed afterwards.
- *
- * @param aURI - url to load
- * @param aCSSSelector - used to specify a node to select. All of this node's
- * children will be selected.
- * @returns the new tab / window which shows the source.
- */
-function* openDocumentSelect(aURI, aCSSSelector) {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, aURI);
- registerCleanupFunction(function() {
- gBrowser.removeTab(tab);
- });
-
- yield ContentTask.spawn(gBrowser.selectedBrowser, { selector: aCSSSelector }, function* (arg) {
- let element = content.document.querySelector(arg.selector);
- content.getSelection().selectAllChildren(element);
- });
-
- let tabOrWindow = yield openViewPartialSource(aCSSSelector);
-
- // Wait until the source has been loaded.
- yield waitForSourceLoaded(tabOrWindow);
-
- return tabOrWindow;
-}
-
-function pushPrefs(...aPrefs) {
- return new Promise(resolve => {
- SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve);
- });
-}
-
-function waitForPrefChange(pref) {
- let deferred = PromiseUtils.defer();
- let observer = () => {
- Preferences.ignore(pref, observer);
- deferred.resolve();
- };
- Preferences.observe(pref, observer);
- return deferred.promise;
-}
diff --git a/toolkit/components/viewsource/test/chrome.ini b/toolkit/components/viewsource/test/chrome.ini
deleted file mode 100644
index bd013ab6c..000000000
--- a/toolkit/components/viewsource/test/chrome.ini
+++ /dev/null
@@ -1,4 +0,0 @@
-[DEFAULT]
-
-[test_bug428653.html]
-support-files = file_empty.html
diff --git a/toolkit/components/viewsource/test/file_empty.html b/toolkit/components/viewsource/test/file_empty.html
deleted file mode 100644
index 495c23ec8..000000000
--- a/toolkit/components/viewsource/test/file_empty.html
+++ /dev/null
@@ -1 +0,0 @@
-<!DOCTYPE html><html><body></body></html>
diff --git a/toolkit/components/viewsource/test/test_bug428653.html b/toolkit/components/viewsource/test/test_bug428653.html
deleted file mode 100644
index b1d48bfb3..000000000
--- a/toolkit/components/viewsource/test/test_bug428653.html
+++ /dev/null
@@ -1,45 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=428653
--->
-<head>
- <title>View Source Test (bug 428653)</title>
- <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
-</head>
-<body>
-
- <iframe id="content" src="http://example.org/tests/toolkit/components/viewsource/test/file_empty.html"></iframe>
-
- <script type="application/javascript">
- /*
- Test that we can't call the content browser's document.open() over Xrays.
- See the security checks in nsHTMLDocument::Open, which make sure that the
- entry global's principal matches that of the document.
- */
- SimpleTest.waitForExplicitFinish();
-
- addLoadEvent(function testDocumentOpen() {
- var browser = document.getElementById("content");
- ok(browser, "got browser");
- var doc = browser.contentDocument;
- ok(doc, "got content document");
-
- var opened = false;
- try {
- doc.open("text/html", "replace");
- opened = true;
- } catch (e) {
- is(e.name, "SecurityError", "Unexpected exception")
- }
- is(opened, false, "Shouldn't have opened document");
-
- doc.wrappedJSObject.open("text/html", "replace");
- ok(true, "Should be able to open document via Xray Waiver");
-
- SimpleTest.finish();
- });
- </script>
-</body>
-</html>
diff --git a/toolkit/components/workerloader/moz.build b/toolkit/components/workerloader/moz.build
index 145f7adc0..f81309dcc 100644
--- a/toolkit/components/workerloader/moz.build
+++ b/toolkit/components/workerloader/moz.build
@@ -4,11 +4,4 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-MOCHITEST_CHROME_MANIFESTS += ['tests/chrome.ini']
-
-EXTRA_JS_MODULES.workers += [
- 'require.js'
-]
-
-with Files('**'):
- BUG_COMPONENT = ('Toolkit', 'Async Tooling')
+EXTRA_JS_MODULES.workers += ['require.js']
diff --git a/toolkit/components/workerloader/tests/.eslintrc.js b/toolkit/components/workerloader/tests/.eslintrc.js
deleted file mode 100644
index 2c669d844..000000000
--- a/toolkit/components/workerloader/tests/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/workerloader/tests/chrome.ini b/toolkit/components/workerloader/tests/chrome.ini
deleted file mode 100644
index c83a0b081..000000000
--- a/toolkit/components/workerloader/tests/chrome.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-support-files =
- moduleA-depends.js
- moduleB-dependency.js
- moduleC-circular.js
- moduleD-circular.js
- moduleE-throws-during-require.js
- moduleF-syntax-error.js
- moduleG-throws-later.js
- moduleH-module-dot-exports.js
- utils_mainthread.js
- utils_worker.js
- worker_test_loading.js
-
-[test_loading.xul]
diff --git a/toolkit/components/workerloader/tests/moduleA-depends.js b/toolkit/components/workerloader/tests/moduleA-depends.js
deleted file mode 100644
index 0e1cc7c8b..000000000
--- a/toolkit/components/workerloader/tests/moduleA-depends.js
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// A trivial module that depends on an equally trivial module
-var B = require("chrome://mochitests/content/chrome/toolkit/components/workerloader/tests/moduleB-dependency.js");
-
-// Ensure that the initial set of exports is empty
-if (Object.keys(exports).length) {
- throw new Error("exports should be empty, initially");
-}
-
-// Export some values
-exports.A = true;
-exports.importedFoo = B.foo;
diff --git a/toolkit/components/workerloader/tests/moduleB-dependency.js b/toolkit/components/workerloader/tests/moduleB-dependency.js
deleted file mode 100644
index 5c9831fc3..000000000
--- a/toolkit/components/workerloader/tests/moduleB-dependency.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-exports.B = true;
-exports.foo = "foo";
-
-// Side-effect to detect if we attempt to re-execute this module.
-if ("loadedB" in self) {
- throw new Error("B has been evaluted twice");
-}
-self.loadedB = true;
diff --git a/toolkit/components/workerloader/tests/moduleC-circular.js b/toolkit/components/workerloader/tests/moduleC-circular.js
deleted file mode 100644
index 5dc14259a..000000000
--- a/toolkit/components/workerloader/tests/moduleC-circular.js
+++ /dev/null
@@ -1,18 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Module C and module D have circular dependencies.
-// This should not prevent from loading them.
-
-// This value is set before any circular dependency, it should be visible
-// in D.
-exports.enteredC = true;
-
-var D = require("chrome://mochitests/content/chrome/toolkit/components/workerloader/tests/moduleD-circular.js");
-
-// The following values are set after importing D.
-// copiedFromD.copiedFromC should have only one field |enteredC|
-exports.copiedFromD = JSON.parse(JSON.stringify(D));
-// exportedFromD.copiedFromC should have all the fields defined in |exports|
-exports.exportedFromD = D;
-exports.finishedC = true;
diff --git a/toolkit/components/workerloader/tests/moduleD-circular.js b/toolkit/components/workerloader/tests/moduleD-circular.js
deleted file mode 100644
index d77bdc74d..000000000
--- a/toolkit/components/workerloader/tests/moduleD-circular.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Module C and module D have circular dependencies.
-// This should not prevent from loading them.
-
-exports.enteredD = true;
-var C = require("chrome://mochitests/content/chrome/toolkit/components/workerloader/tests/moduleC-circular.js");
-exports.copiedFromC = JSON.parse(JSON.stringify(C));
-exports.exportedFromC = C;
-exports.finishedD = true;
diff --git a/toolkit/components/workerloader/tests/moduleE-throws-during-require.js b/toolkit/components/workerloader/tests/moduleE-throws-during-require.js
deleted file mode 100644
index b0be0449f..000000000
--- a/toolkit/components/workerloader/tests/moduleE-throws-during-require.js
+++ /dev/null
@@ -1,10 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Skip a few lines
-// 5
-// 6
-// 7
-// 8
-// 9
-throw new Error("Let's see if this error is obtained with the right origin");
diff --git a/toolkit/components/workerloader/tests/moduleF-syntax-error.js b/toolkit/components/workerloader/tests/moduleF-syntax-error.js
deleted file mode 100644
index c03fa32f8..000000000
--- a/toolkit/components/workerloader/tests/moduleF-syntax-error.js
+++ /dev/null
@@ -1,6 +0,0 @@
-<!--
-Any copyright is dedicated to the Public Domain.
-http://creativecommons.org/publicdomain/zero/1.0/
--->
-<?xml version="1.0" encoding="UTF-8" ?>
-<foo>Anything that doesn't parse as JavaScript</foo>
diff --git a/toolkit/components/workerloader/tests/moduleG-throws-later.js b/toolkit/components/workerloader/tests/moduleG-throws-later.js
deleted file mode 100644
index 8a24bc7e4..000000000
--- a/toolkit/components/workerloader/tests/moduleG-throws-later.js
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Skip a few lines
-// 5
-// 6
-// 7
-// 8
-// 9
-exports.doThrow = function doThrow() {
- Array.prototype.sort.apply("foo"); // This will raise a native TypeError
-};
diff --git a/toolkit/components/workerloader/tests/moduleH-module-dot-exports.js b/toolkit/components/workerloader/tests/moduleH-module-dot-exports.js
deleted file mode 100644
index a6b93bbcc..000000000
--- a/toolkit/components/workerloader/tests/moduleH-module-dot-exports.js
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// This should be overwritten by module.exports
-exports.key = "wrong value";
-
-module.exports = {
- key: "value"
-};
-
-// This should also be overwritten by module.exports
-exports.key = "another wrong value";
diff --git a/toolkit/components/workerloader/tests/test_loading.xul b/toolkit/components/workerloader/tests/test_loading.xul
deleted file mode 100644
index 2744270e1..000000000
--- a/toolkit/components/workerloader/tests/test_loading.xul
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0"?>
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<window title="Testing the worker loader"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- onload="test();">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/>
- <script type="application/javascript"
- src="utils_mainthread.js"/>
- <script type="application/javascript">
- <![CDATA[
-
-let worker;
-let main = this;
-
-function test() {
- info("Starting test " + document.uri);
-
- worker = new ChromeWorker("worker_test_loading.js");
- SimpleTest.waitForExplicitFinish();
- info("Chrome worker created");
- worker_handler(worker);
- worker.postMessage(document.uri);
- ok(true, "Test in progress");
-};
-]]>
- </script>
-
- <body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"></p>
- <div id="content" style="display:none;"></div>
- <pre id="test"></pre>
- </body>
- <label id="test-result"/>
-</window>
diff --git a/toolkit/components/workerloader/tests/utils_mainthread.js b/toolkit/components/workerloader/tests/utils_mainthread.js
deleted file mode 100644
index 148591c3d..000000000
--- a/toolkit/components/workerloader/tests/utils_mainthread.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function worker_handler(worker) {
- worker.onerror = function(error) {
- error.preventDefault();
- ok(false, "error "+ error.message);
- };
- worker.onmessage = function(msg) {
-// ok(true, "MAIN: onmessage " + JSON.stringify(msg.data));
- switch (msg.data.kind) {
- case "is":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- "( "+ msg.data.a + " ==? " + msg.data.b + ")" );
- return;
- case "isnot":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- "( "+ msg.data.a + " !=? " + msg.data.b + ")" );
- return;
- case "ok":
- SimpleTest.ok(msg.data.condition, msg.data.description);
- return;
- case "info":
- SimpleTest.info(msg.data.description);
- return;
- case "finish":
- SimpleTest.finish();
- return;
- default:
- SimpleTest.ok(false, "test_osfile.xul: wrong message " + JSON.stringify(msg.data));
- return;
- }
- };
-}
diff --git a/toolkit/components/workerloader/tests/utils_worker.js b/toolkit/components/workerloader/tests/utils_worker.js
deleted file mode 100644
index da82d4b0a..000000000
--- a/toolkit/components/workerloader/tests/utils_worker.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function log(text) {
- dump("WORKER " + text + "\n");
-}
-
-function send(message) {
- self.postMessage(message);
-}
-
-function finish() {
- send({kind: "finish"});
-}
-
-function ok(condition, description) {
- send({kind: "ok", condition: !!condition, description: "" + description});
-}
-
-function is(a, b, description) {
- let outcome = a == b; // Need to decide outcome here, as not everything can be serialized
- send({kind: "is", outcome: outcome, description: "" + description, a: "" + a, b: "" + b});
-}
-
-function isnot(a, b, description) {
- let outcome = a != b; // Need to decide outcome here, as not everything can be serialized
- send({kind: "isnot", outcome: outcome, description: "" + description, a: "" + a, b: "" + b});
-}
-
-function info(description) {
- send({kind: "info", description: "" + description});
-}
diff --git a/toolkit/components/workerloader/tests/worker_handler.js b/toolkit/components/workerloader/tests/worker_handler.js
deleted file mode 100644
index b09b8c34c..000000000
--- a/toolkit/components/workerloader/tests/worker_handler.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function worker_handler(worker) {
- worker.onerror = function(error) {
- error.preventDefault();
- ok(false, "error "+error);
- }
- worker.onmessage = function(msg) {
- ok(true, "MAIN: onmessage " + JSON.stringify(msg.data));
- switch (msg.data.kind) {
- case "is":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- "( "+ msg.data.a + " ==? " + msg.data.b + ")" );
- return;
- case "isnot":
- SimpleTest.ok(msg.data.outcome, msg.data.description +
- "( "+ msg.data.a + " !=? " + msg.data.b + ")" );
- return;
- case "ok":
- SimpleTest.ok(msg.data.condition, msg.data.description);
- return;
- case "info":
- SimpleTest.info(msg.data.description);
- return;
- case "finish":
- SimpleTest.finish();
- return;
- default:
- SimpleTest.ok(false, "test_osfile.xul: wrong message " + JSON.stringify(msg.data));
- return;
- }
- };
-}
diff --git a/toolkit/components/workerloader/tests/worker_test_loading.js b/toolkit/components/workerloader/tests/worker_test_loading.js
deleted file mode 100644
index 40702e4e1..000000000
--- a/toolkit/components/workerloader/tests/worker_test_loading.js
+++ /dev/null
@@ -1,121 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-importScripts("utils_worker.js"); // Test suite code
-info("Test suite configured");
-
-importScripts("resource://gre/modules/workers/require.js");
-info("Loader imported");
-
-var PATH = "chrome://mochitests/content/chrome/toolkit/components/workerloader/tests/";
-var tests = [];
-var add_test = function(test) {
- tests.push(test);
-};
-
-add_test(function test_setup() {
- ok(typeof require != "undefined", "Function |require| is defined");
-});
-
-// Test simple loading (moduleA-depends.js requires moduleB-dependency.js)
-add_test(function test_load() {
- let A = require(PATH + "moduleA-depends.js");
- ok(true, "Opened module A");
-
- is(A.A, true, "Module A exported value A");
- ok(!("B" in A), "Module A did not export value B");
- is(A.importedFoo, "foo", "Module A re-exported B.foo");
-
- // re-evaluating moduleB-dependency.js would cause an error, but re-requiring it shouldn't
- let B = require(PATH + "moduleB-dependency.js");
- ok(true, "Managed to re-require module B");
- is(B.B, true, "Module B exported value B");
- is(B.foo, "foo", "Module B exported value foo");
-});
-
-// Test simple circular loading (moduleC-circular.js and moduleD-circular.js require each other)
-add_test(function test_circular() {
- let C = require(PATH + "moduleC-circular.js");
- ok(true, "Loaded circular modules C and D");
- is(C.copiedFromD.copiedFromC.enteredC, true, "Properties exported by C before requiring D can be seen by D immediately");
-
- let D = require(PATH + "moduleD-circular.js");
- is(D.exportedFromC.finishedC, true, "Properties exported by C after requiring D can be seen by D eventually");
-});
-
-// Testing error cases
-add_test(function test_exceptions() {
- let should_throw = function(f) {
- try {
- f();
- return null;
- } catch (ex) {
- return ex;
- }
- };
-
- let exn = should_throw(() => require(PATH + "this module doesn't exist"));
- ok(!!exn, "Attempting to load a module that doesn't exist raises an error");
-
- exn = should_throw(() => require(PATH + "moduleE-throws-during-require.js"));
- ok(!!exn, "Attempting to load a module that throws at toplevel raises an error");
- is(exn.moduleName, PATH + "moduleE-throws-during-require.js",
- "moduleName is correct");
- isnot(exn.moduleStack.indexOf("moduleE-throws-during-require.js"), -1,
- "moduleStack contains the name of the module");
- is(exn.lineNumber, 10, "The error comes with the right line number");
-
- exn = should_throw(() => require(PATH + "moduleF-syntaxerror.xml"));
- ok(!!exn, "Attempting to load a non-well formatted module raises an error");
-
- exn = should_throw(() => require(PATH + "moduleG-throws-later.js").doThrow());
- ok(!!exn, "G.doThrow() has raised an error");
- info(exn);
- ok(exn.toString().startsWith("TypeError"), "The exception is a TypeError.");
- is(exn.moduleName, PATH + "moduleG-throws-later.js", "The name of the module is correct");
- isnot(exn.moduleStack.indexOf("moduleG-throws-later.js"), -1,
- "The name of the right file appears somewhere in the stack");
- is(exn.lineNumber, 11, "The error comes with the right line number");
-});
-
-function get_exn(f) {
- try {
- f();
- return undefined;
- } catch (ex) {
- return ex;
- }
-}
-
-// Test module.exports
-add_test(function test_module_dot_exports() {
- let H = require(PATH + "moduleH-module-dot-exports.js");
- is(H.key, "value", "module.exports worked");
- let H2 = require(PATH + "moduleH-module-dot-exports.js");
- is(H2.key, "value", "module.exports returned the same key");
- ok(H2 === H, "module.exports returned the same module the second time");
- let exn = get_exn(() => H.key = "this should not be accepted");
- ok(exn instanceof TypeError, "Cannot alter value in module.exports after export");
- exn = get_exn(() => H.key2 = "this should not be accepted, either");
- ok(exn instanceof TypeError, "Cannot add value to module.exports after export");
-});
-
-self.onmessage = function(message) {
- for (let test of tests) {
- info("Entering " + test.name);
- try {
- test();
- } catch (ex) {
- ok(false, "Test " + test.name + " failed");
- info(ex);
- info(ex.stack);
- }
- info("Leaving " + test.name);
- }
- finish();
-};
-
-
-
diff --git a/toolkit/components/xulstore/moz.build b/toolkit/components/xulstore/moz.build
index 30559fccb..4ee7a5d27 100644
--- a/toolkit/components/xulstore/moz.build
+++ b/toolkit/components/xulstore/moz.build
@@ -4,12 +4,7 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-MOCHITEST_CHROME_MANIFESTS += ['tests/chrome/chrome.ini']
-XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
-
-XPIDL_SOURCES += [
- 'nsIXULStore.idl',
-]
+XPIDL_SOURCES += ['nsIXULStore.idl']
XPIDL_MODULE = 'toolkit_xulstore'
diff --git a/toolkit/components/xulstore/tests/chrome/.eslintrc.js b/toolkit/components/xulstore/tests/chrome/.eslintrc.js
deleted file mode 100644
index 8c0f4f574..000000000
--- a/toolkit/components/xulstore/tests/chrome/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/chrome.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/xulstore/tests/chrome/animals.rdf b/toolkit/components/xulstore/tests/chrome/animals.rdf
deleted file mode 100644
index c7319e641..000000000
--- a/toolkit/components/xulstore/tests/chrome/animals.rdf
+++ /dev/null
@@ -1,142 +0,0 @@
-<?xml version="1.0"?>
-
-<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:NC="http://home.netscape.com/NC-rdf#"
- xmlns:ANIMALS="http://www.some-fictitious-zoo.com/rdf#">
-
- <ANIMALS:Class RDF:about="http://www.some-fictitious-zoo.com/arachnids">
- <ANIMALS:name>Arachnids</ANIMALS:name>
- </ANIMALS:Class>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/arachnids/tarantula">
- <ANIMALS:name>Tarantula</ANIMALS:name>
- </RDF:Description>
-
- <ANIMALS:Class RDF:about="http://www.some-fictitious-zoo.com/birds">
- <ANIMALS:name>Birds</ANIMALS:name>
- </ANIMALS:Class>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/birds/emu">
- <ANIMALS:name>Emu</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/birds/barnowl">
- <ANIMALS:name>Barn Owl</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/birds/raven">
- <ANIMALS:name>Raven</ANIMALS:name>
- </RDF:Description>
-
- <ANIMALS:Class RDF:about="http://www.some-fictitious-zoo.com/crustaceans">
- <ANIMALS:name>Crustaceans</ANIMALS:name>
- </ANIMALS:Class>
-
- <ANIMALS:Class RDF:about="http://www.some-fictitious-zoo.com/fish">
- <ANIMALS:name>Fish</ANIMALS:name>
- </ANIMALS:Class>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/fish/cod">
- <ANIMALS:name>Cod</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/fish/swordfish">
- <ANIMALS:name>Swordfish</ANIMALS:name>
- </RDF:Description>
-
- <ANIMALS:Class RDF:about="http://www.some-fictitious-zoo.com/mammals">
- <ANIMALS:name>Mammals</ANIMALS:name>
- </ANIMALS:Class>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/lion">
- <ANIMALS:name>Lion</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/hippopotamus">
- <ANIMALS:name>HIPPOPOTAMUS</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/africanelephant">
- <ANIMALS:name>African Elephant</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/llama">
- <ANIMALS:name>LLAMA</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/polarbear">
- <ANIMALS:name>Polar Bear</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/aardvark">
- <ANIMALS:name>aardvark</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/ninebandedarmadillo">
- <ANIMALS:name>Nine-banded Armadillo</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/mammals/gorilla">
- <ANIMALS:name>Gorilla</ANIMALS:name>
- </RDF:Description>
-
- <ANIMALS:Class RDF:about="http://www.some-fictitious-zoo.com/reptiles">
- <ANIMALS:name>Reptiles</ANIMALS:name>
- </ANIMALS:Class>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/reptiles/anaconda">
- <ANIMALS:name>Anaconda</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Description RDF:about="http://www.some-fictitious-zoo.com/reptiles/chameleon">
- <ANIMALS:name>Chameleon</ANIMALS:name>
- </RDF:Description>
-
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/some-animals" ANIMALS:name="Zoo Animals">
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/arachnids"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/birds"/>
- </RDF:Seq>
-
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/all-animals" ANIMALS:name="Zoo Animals">
- <RDF:li>
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/arachnids">
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/arachnids/tarantula"/>
- </RDF:Seq>
- </RDF:li>
- <RDF:li>
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/birds">
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/birds/emu"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/birds/barnowl"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/birds/raven"/>
- </RDF:Seq>
- </RDF:li>
- <RDF:li>
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/crustaceans"/>
- </RDF:li>
- <RDF:li>
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/fish">
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/fish/cod"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/fish/swordfish"/>
- </RDF:Seq>
- </RDF:li>
- <RDF:li>
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/mammals">
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/lion"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/hippopotamus"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/africanelephant"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/llama"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/polarbear"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/aardvark"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/ninebandedarmadillo"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/mammals/gorilla"/>
- </RDF:Seq>
- </RDF:li>
- <RDF:li>
- <RDF:Seq RDF:about="http://www.some-fictitious-zoo.com/reptiles">
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/reptiles/anaconda"/>
- <RDF:li RDF:resource="http://www.some-fictitious-zoo.com/reptiles/chameleon"/>
- </RDF:Seq>
- </RDF:li>
- </RDF:Seq>
-
-</RDF:RDF>
diff --git a/toolkit/components/xulstore/tests/chrome/chrome.ini b/toolkit/components/xulstore/tests/chrome/chrome.ini
deleted file mode 100644
index 91efd5455..000000000
--- a/toolkit/components/xulstore/tests/chrome/chrome.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-support-files =
- window_persistence.xul
- animals.rdf
-
-[test_persistence.xul]
diff --git a/toolkit/components/xulstore/tests/chrome/test_persistence.xul b/toolkit/components/xulstore/tests/chrome/test_persistence.xul
deleted file mode 100644
index 736a067ed..000000000
--- a/toolkit/components/xulstore/tests/chrome/test_persistence.xul
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-
-<window title="Persistence Tests"
- onload="runTest()"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
-
- <script>
- SimpleTest.waitForExplicitFinish();
- function runTest() {
- window.openDialog("window_persistence.xul", "_blank", "chrome", true);
- }
-
- function windowOpened() {
- window.openDialog("window_persistence.xul", "_blank", "chrome", false);
- }
-
- function testDone() {
- SimpleTest.finish();
- }
- </script>
-
-<body xmlns="http://www.w3.org/1999/xhtml">
- <p id="display"/>
-</body>
-
-</window>
diff --git a/toolkit/components/xulstore/tests/chrome/window_persistence.xul b/toolkit/components/xulstore/tests/chrome/window_persistence.xul
deleted file mode 100644
index 4d76fe11d..000000000
--- a/toolkit/components/xulstore/tests/chrome/window_persistence.xul
+++ /dev/null
@@ -1,98 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
-<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
-
-<window title="Persistence Tests"
- onload="opened()"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
- persist="screenX screenY width height">
-
-<button id="button1" label="Button1" persist="value"/>
-<button id="button2" label="Button2" value="Normal" persist="value"/>
-
-<tree id="tree" datasources="animals.rdf" ref="http://www.some-fictitious-zoo.com/all-animals"
- flags="dont-build-content" width="200" height="200">
- <treecols orient="horizontal" id="treecols">
- <treecol id="treecol" primary="true" label="Name" flex="1"/>
- </treecols>
- <template id="template">
- <treechildren>
- <treeitem uri="rdf:*">
- <treerow>
- <treecell label="rdf:http://www.some-fictitious-zoo.com/rdf#name"/>
- <treecell/>
- </treerow>
- </treeitem>
- </treechildren>
- </template>
-</tree>
-
-<script>
-<![CDATA[
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-let XULStore = Cc["@mozilla.org/xul/xulstore;1"].getService(Ci.nsIXULStore);
-let URI = "chrome://mochitests/content/chrome/toolkit/components/xulstore/tests/chrome/window_persistence.xul";
-
-function opened()
-{
- // If the data in the tree has not been loaded yet, wait a bit and try again.
- var treeView = document.getElementById("tree").view;
- if (treeView.rowCount != 6 && treeView.rowCount != 17) {
- setTimeout(opened, 50);
- return;
- }
-
- runTest(treeView);
-}
-
-function runTest(treeView)
-{
- var firstRun = window.arguments[0];
- if (firstRun) {
- document.getElementById("button1").setAttribute("value", "Pressed");
- document.getElementById("button2").removeAttribute("value");
-
- document.getElementById("button2").setAttribute("foo", "bar");
- document.persist("button2", "foo");
- is(XULStore.getValue(URI, "button2", "foo"), "bar", "attribute persisted")
- document.getElementById("button2").removeAttribute("foo");
- document.persist("button2", "foo");
- is(XULStore.hasValue(URI, "button2", "foo"), false, "attribute removed")
-
- is(treeView.rowCount, 6, "tree rows are closed");
- treeView.toggleOpenState(1);
- treeView.toggleOpenState(7);
-
- window.close();
- window.opener.windowOpened();
- }
- else {
- is(document.getElementById("button1").getAttribute("value"), "Pressed",
- "Attribute set");
- is(document.getElementById("button2").hasAttribute("value"), true,
- "Attribute cleared");
- is(document.getElementById("button2").getAttribute("value"), "",
- "Attribute cleared");
- is(document.getElementById("button2").hasAttribute("foo"), false,
- "Attribute cleared");
- is(document.getElementById("button2").getAttribute("foo"), "",
- "Attribute cleared");
-
- is(treeView.rowCount, 17, "tree rows are open");
- is(treeView.isContainerOpen(0), false, "first closed row");
- is(treeView.isContainerOpen(1), true, "first open row");
- is(treeView.isContainerOpen(7), true, "second open row");
-
- window.close();
- window.opener.testDone();
- }
-}
-
-function is(l, r, n) { window.opener.wrappedJSObject.SimpleTest.is(l,r,n); }
-
-]]></script>
-
-</window>
diff --git a/toolkit/components/xulstore/tests/xpcshell/.eslintrc.js b/toolkit/components/xulstore/tests/xpcshell/.eslintrc.js
deleted file mode 100644
index d35787cd2..000000000
--- a/toolkit/components/xulstore/tests/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/toolkit/components/xulstore/tests/xpcshell/localstore.rdf b/toolkit/components/xulstore/tests/xpcshell/localstore.rdf
deleted file mode 100644
index 458eb50ea..000000000
--- a/toolkit/components/xulstore/tests/xpcshell/localstore.rdf
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0"?>
-<RDF:RDF xmlns:NC="http://home.netscape.com/NC-rdf#"
- xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
- <RDF:Description RDF:about="chrome://browser/content/browser.xul#sidebar-title"
- value="" />
- <RDF:Description RDF:about="about:config#prefCol"
- ordinal="1"
- sortDirection="ascending" />
- <RDF:Description RDF:about="chrome://browser/content/browser.xul#addon-bar"
- collapsed="true" />
- <RDF:Description RDF:about="about:config">
- <NC:persist RDF:resource="about:config#prefCol"/>
- <NC:persist RDF:resource="about:config#lockCol"/>
- <NC:persist RDF:resource="about:config#typeCol"/>
- <NC:persist RDF:resource="about:config#valueCol"/>
- </RDF:Description>
- <RDF:Description RDF:about="about:config#lockCol"
- ordinal="3" />
- <RDF:Description RDF:about="chrome://browser/content/browser.xul">
- <NC:persist RDF:resource="chrome://browser/content/browser.xul#main-window"/>
- <NC:persist RDF:resource="chrome://browser/content/browser.xul#addon-bar"/>
- <NC:persist RDF:resource="chrome://browser/content/browser.xul#sidebar-box"/>
- <NC:persist RDF:resource="chrome://browser/content/browser.xul#sidebar-title"/>
- </RDF:Description>
- <RDF:Description RDF:about="chrome://browser/content/browser.xul#main-window"
- width="994"
- height="768"
- screenX="4"
- screenY="22"
- sizemode="normal" />
-</RDF:RDF>
diff --git a/toolkit/components/xulstore/tests/xpcshell/test_XULStore.js b/toolkit/components/xulstore/tests/xpcshell/test_XULStore.js
deleted file mode 100644
index c3c96654b..000000000
--- a/toolkit/components/xulstore/tests/xpcshell/test_XULStore.js
+++ /dev/null
@@ -1,199 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/◦
-*/
-
-"use strict"
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-const Cr = Components.results;
-
-Cu.import("resource://gre/modules/osfile.jsm")
-
-var XULStore = null;
-var browserURI = "chrome://browser/content/browser.xul";
-var aboutURI = "about:config";
-
-function run_test() {
- do_get_profile();
- run_next_test();
-}
-
-function checkValue(uri, id, attr, reference) {
- let value = XULStore.getValue(uri, id, attr);
- do_check_true(value === reference);
-}
-
-function checkValueExists(uri, id, attr, exists) {
- do_check_eq(XULStore.hasValue(uri, id, attr), exists);
-}
-
-function getIDs(uri) {
- let it = XULStore.getIDsEnumerator(uri);
- let result = [];
-
- while (it.hasMore()) {
- let value = it.getNext();
- result.push(value);
- }
-
- result.sort();
- return result;
-}
-
-function getAttributes(uri, id) {
- let it = XULStore.getAttributeEnumerator(uri, id);
-
- let result = [];
-
- while (it.hasMore()) {
- let value = it.getNext();
- result.push(value);
- }
-
- result.sort();
- return result;
-}
-
-function checkArrays(a, b) {
- a.sort();
- b.sort();
- do_check_true(a.toString() == b.toString());
-}
-
-function checkOldStore() {
- checkArrays(['addon-bar', 'main-window', 'sidebar-title'], getIDs(browserURI));
- checkArrays(['collapsed'], getAttributes(browserURI, 'addon-bar'));
- checkArrays(['height', 'screenX', 'screenY', 'sizemode', 'width'],
- getAttributes(browserURI, 'main-window'));
- checkArrays(['value'], getAttributes(browserURI, 'sidebar-title'));
-
- checkValue(browserURI, "addon-bar", "collapsed", "true");
- checkValue(browserURI, "main-window", "width", "994");
- checkValue(browserURI, "main-window", "height", "768");
- checkValue(browserURI, "main-window", "screenX", "4");
- checkValue(browserURI, "main-window", "screenY", "22");
- checkValue(browserURI, "main-window", "sizemode", "normal");
- checkValue(browserURI, "sidebar-title", "value", "");
-
- checkArrays(['lockCol', 'prefCol'], getIDs(aboutURI));
- checkArrays(['ordinal'], getAttributes(aboutURI, 'lockCol'));
- checkArrays(['ordinal', 'sortDirection'], getAttributes(aboutURI, 'prefCol'));
-
- checkValue(aboutURI, "prefCol", "ordinal", "1");
- checkValue(aboutURI, "prefCol", "sortDirection", "ascending");
- checkValue(aboutURI, "lockCol", "ordinal", "3");
-}
-
-add_task(function* testImport() {
- let src = "localstore.rdf";
- let dst = OS.Path.join(OS.Constants.Path.profileDir, src);
-
- yield OS.File.copy(src, dst);
-
- // Importing relies on XULStore not yet being loaded before this point.
- XULStore = Cc["@mozilla.org/xul/xulstore;1"].getService(Ci.nsIXULStore);
- checkOldStore();
-});
-
-add_task(function* testTruncation() {
- let dos = Array(8192).join("~");
- // Long id names should trigger an exception
- Assert.throws(() => XULStore.setValue(browserURI, dos, "foo", "foo"), /NS_ERROR_ILLEGAL_VALUE/);
-
- // Long attr names should trigger an exception
- Assert.throws(() => XULStore.setValue(browserURI, "foo", dos, "foo"), /NS_ERROR_ILLEGAL_VALUE/);
-
- // Long values should be truncated
- XULStore.setValue(browserURI, "dos", "dos", dos);
- dos =XULStore.getValue(browserURI, "dos", "dos");
- do_check_true(dos.length == 4096)
- XULStore.removeValue(browserURI, "dos", "dos")
-});
-
-add_task(function* testGetValue() {
- // Get non-existing property
- checkValue(browserURI, "side-window", "height", "");
-
- // Get existing property
- checkValue(browserURI, "main-window", "width", "994");
-});
-
-add_task(function* testHasValue() {
- // Check non-existing property
- checkValueExists(browserURI, "side-window", "height", false);
-
- // Check existing property
- checkValueExists(browserURI, "main-window", "width", true);
-});
-
-add_task(function* testSetValue() {
- // Set new attribute
- checkValue(browserURI, "side-bar", "width", "");
- XULStore.setValue(browserURI, "side-bar", "width", "1000");
- checkValue(browserURI, "side-bar", "width", "1000");
- checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["width"], getAttributes(browserURI, 'side-bar'));
-
- // Modify existing property
- checkValue(browserURI, "side-bar", "width", "1000");
- XULStore.setValue(browserURI, "side-bar", "width", "1024");
- checkValue(browserURI, "side-bar", "width", "1024");
- checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["width"], getAttributes(browserURI, 'side-bar'));
-
- // Add another attribute
- checkValue(browserURI, "side-bar", "height", "");
- XULStore.setValue(browserURI, "side-bar", "height", "1000");
- checkValue(browserURI, "side-bar", "height", "1000");
- checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["width", "height"], getAttributes(browserURI, 'side-bar'));
-});
-
-add_task(function* testRemoveValue() {
- // Remove first attribute
- checkValue(browserURI, "side-bar", "width", "1024");
- XULStore.removeValue(browserURI, "side-bar", "width");
- checkValue(browserURI, "side-bar", "width", "");
- checkValueExists(browserURI, "side-bar", "width", false);
- checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["height"], getAttributes(browserURI, 'side-bar'));
-
- // Remove second attribute
- checkValue(browserURI, "side-bar", "height", "1000");
- XULStore.removeValue(browserURI, "side-bar", "height");
- checkValue(browserURI, "side-bar", "height", "");
- checkArrays(["addon-bar", "main-window", "sidebar-title"], getIDs(browserURI));
-
- // Removing an attribute that doesn't exists shouldn't fail
- XULStore.removeValue(browserURI, "main-window", "bar");
-
- // Removing from an id that doesn't exists shouldn't fail
- XULStore.removeValue(browserURI, "foo", "bar");
-
- // Removing from a document that doesn't exists shouldn't fail
- let nonDocURI = "chrome://example/content/other.xul";
- XULStore.removeValue(nonDocURI, "foo", "bar");
-
- // Remove all attributes in browserURI
- XULStore.removeValue(browserURI, "addon-bar", "collapsed");
- checkArrays([], getAttributes(browserURI, "addon-bar"));
- XULStore.removeValue(browserURI, "main-window", "width");
- XULStore.removeValue(browserURI, "main-window", "height");
- XULStore.removeValue(browserURI, "main-window", "screenX");
- XULStore.removeValue(browserURI, "main-window", "screenY");
- XULStore.removeValue(browserURI, "main-window", "sizemode");
- checkArrays([], getAttributes(browserURI, "main-window"));
- XULStore.removeValue(browserURI, "sidebar-title", "value");
- checkArrays([], getAttributes(browserURI, "sidebar-title"));
- checkArrays([], getIDs(browserURI));
-
- // Remove all attributes in aboutURI
- XULStore.removeValue(aboutURI, "prefCol", "ordinal");
- XULStore.removeValue(aboutURI, "prefCol", "sortDirection");
- checkArrays([], getAttributes(aboutURI, "prefCol"));
- XULStore.removeValue(aboutURI, "lockCol", "ordinal");
- checkArrays([], getAttributes(aboutURI, "lockCol"));
- checkArrays([], getIDs(aboutURI));
-});
diff --git a/toolkit/components/xulstore/tests/xpcshell/xpcshell.ini b/toolkit/components/xulstore/tests/xpcshell/xpcshell.ini
deleted file mode 100644
index d483dae02..000000000
--- a/toolkit/components/xulstore/tests/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-skip-if = toolkit == 'android'
-support-files =
- localstore.rdf
-
-[test_XULStore.js]