import FIREFOX_52_6_0esr_RELEASE from mozilla-esr52 hg repo

This commit is contained in:
Roy Tam 2018-01-19 03:59:58 +08:00
commit dcd9973243
150858 changed files with 23884658 additions and 0 deletions

View file

@ -0,0 +1,54 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.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 { Cc, Ci, Cu } = require('chrome');
const { Loader } = require('sdk/test/loader');
const loader = Loader(module);
const httpd = loader.require('./httpd');
const { pathFor } = require('sdk/system');
const { startServerAsync } = httpd;
const basePath = pathFor('ProfD');
const { atob } = Cu.import("resource://gre/modules/Services.jsm", {});
const historyService = Cc["@mozilla.org/browser/nav-history-service;1"]
.getService(Ci.nsINavHistoryService);
const { events } = require('sdk/places/events');
const { OS } = Cu.import("resource://gre/modules/osfile.jsm", {});
function onFaviconChange (url) {
return new Promise(resolve => {
function handler ({data, type}) {
if (type !== 'history-page-changed' ||
data.url !== url ||
data.property !== Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON)
return;
events.off('data', handler);
resolve(data.value);
}
events.on('data', handler);
});
}
exports.onFaviconChange = onFaviconChange;
/*
* Takes page content, a page path, and favicon binary data
*/
function serve ({name, favicon, port, host}) {
let faviconTag = '<link rel="icon" type="image/x-icon" href="/'+ name +'.ico"/>';
let content = '<html><head>' + faviconTag + '<title>'+name+'</title></head><body></body></html>';
let srv = startServerAsync(port, basePath);
let pagePath = OS.Path.join(basePath, name + '.html');
let iconPath = OS.Path.join(basePath, name + '.ico');
return OS.File.writeAtomic(iconPath, favicon).
then(() => {
return OS.File.writeAtomic(pagePath, content);
}).
then(() => srv);
}
exports.serve = serve;
var binFavicon = exports.binFavicon = atob('AAABAAEAEBAAAAAAAABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAAAEAAAAAAAAAAAAAAAEAAAABAAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgACAgAAAwMDAAMDcwADwyqYABAQEAAgICAAMDAwAERERABYWFgAcHBwAIiIiACkpKQBVVVUATU1NAEJCQgA5OTkAgHz/AFBQ/wCTANYA/+zMAMbW7wDW5+cAkKmtAAAAMwAAAGYAAACZAAAAzAAAMwAAADMzAAAzZgAAM5kAADPMAAAz/wAAZgAAAGYzAABmZgAAZpkAAGbMAABm/wAAmQAAAJkzAACZZgAAmZkAAJnMAACZ/wAAzAAAAMwzAADMZgAAzJkAAMzMAADM/wAA/2YAAP+ZAAD/zAAzAAAAMwAzADMAZgAzAJkAMwDMADMA/wAzMwAAMzMzADMzZgAzM5kAMzPMADMz/wAzZgAAM2YzADNmZgAzZpkAM2bMADNm/wAzmQAAM5kzADOZZgAzmZkAM5nMADOZ/wAzzAAAM8wzADPMZgAzzJkAM8zMADPM/wAz/zMAM/9mADP/mQAz/8wAM///AGYAAABmADMAZgBmAGYAmQBmAMwAZgD/AGYzAABmMzMAZjNmAGYzmQBmM8wAZjP/AGZmAABmZjMAZmZmAGZmmQBmZswAZpkAAGaZMwBmmWYAZpmZAGaZzABmmf8AZswAAGbMMwBmzJkAZszMAGbM/wBm/wAAZv8zAGb/mQBm/8wAzAD/AP8AzACZmQAAmTOZAJkAmQCZAMwAmQAAAJkzMwCZAGYAmTPMAJkA/wCZZgAAmWYzAJkzZgCZZpkAmWbMAJkz/wCZmTMAmZlmAJmZmQCZmcwAmZn/AJnMAACZzDMAZsxmAJnMmQCZzMwAmcz/AJn/AACZ/zMAmcxmAJn/mQCZ/8wAmf//AMwAAACZADMAzABmAMwAmQDMAMwAmTMAAMwzMwDMM2YAzDOZAMwzzADMM/8AzGYAAMxmMwCZZmYAzGaZAMxmzACZZv8AzJkAAMyZMwDMmWYAzJmZAMyZzADMmf8AzMwAAMzMMwDMzGYAzMyZAMzMzADMzP8AzP8AAMz/MwCZ/2YAzP+ZAMz/zADM//8AzAAzAP8AZgD/AJkAzDMAAP8zMwD/M2YA/zOZAP8zzAD/M/8A/2YAAP9mMwDMZmYA/2aZAP9mzADMZv8A/5kAAP+ZMwD/mWYA/5mZAP+ZzAD/mf8A/8wAAP/MMwD/zGYA/8yZAP/MzAD/zP8A//8zAMz/ZgD//5kA///MAGZm/wBm/2YAZv//AP9mZgD/Zv8A//9mACEApQBfX18Ad3d3AIaGhgCWlpYAy8vLALKysgDX19cA3d3dAOPj4wDq6uoA8fHxAPj4+ADw+/8ApKCgAICAgAAAAP8AAP8AAAD//wD/AAAA/wD/AP//AAD///8ACgoKCgoKCgoKCgoKCgoKCgoKCgoHAQEMbQoKCgoKCgoAAAdDH/kgHRIAAAAAAAAAAADrHfn5ASQQAAAAAAAAAArsBx0B+fkgHesAAAAAAAD/Cgwf+fn5IA4dEus/IvcACgcMAfkg+QEB+SABHushbf8QHR/5HQH5+QEdHetEHx4K7B/5+QH5+fkdDBL5+SBE/wwdJfkf+fn5AR8g+fkfEArsCh/5+QEeJR/5+SAeBwAACgoe+SAlHwFAEhAfAAAAAPcKHh8eASYBHhAMAAAAAAAA9EMdIB8gHh0dBwAAAAAAAAAA7BAdQ+wHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AADwfwAAwH8AAMB/AAAAPwAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAQAAgAcAAIAPAADADwAA8D8AAP//AAA');

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,27 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.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 { safeMerge: merge } = require('sdk/util/object');
const app = require("sdk/system/xul-app");
// Once Bug 903018 is resolved, just move the application testing to
// module.metadata.engines
if (app.is('Firefox')) {
merge(module.exports,
require('./test-places-events'),
require('./test-places-bookmarks'),
require('./test-places-favicon'),
require('./test-places-history'),
require('./test-places-host'),
require('./test-places-utils')
);
} else {
exports['test unsupported'] = (assert) => {
assert.pass('This application is unsupported.');
};
}
require('sdk/test/runner').runTestsFromModule(module);

View file

@ -0,0 +1,239 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict'
const { Cc, Ci, Cu } = require('chrome');
const bmsrv = Cc['@mozilla.org/browser/nav-bookmarks-service;1'].
getService(Ci.nsINavBookmarksService);
const hsrv = Cc['@mozilla.org/browser/nav-history-service;1'].
getService(Ci.nsINavHistoryService);
const brsrv = Cc["@mozilla.org/browser/nav-history-service;1"]
.getService(Ci.nsIBrowserHistory);
const tagsrv = Cc['@mozilla.org/browser/tagging-service;1'].
getService(Ci.nsITaggingService);
const asyncHistory = Cc['@mozilla.org/browser/history;1'].
getService(Ci.mozIAsyncHistory);
const { send } = require('sdk/addon/events');
const { setTimeout } = require('sdk/timers');
const { newURI } = require('sdk/url/utils');
const { defer, all } = require('sdk/core/promise');
const { once } = require('sdk/system/events');
const { set } = require('sdk/preferences/service');
const {
Bookmark, Group, Separator,
save, search,
MENU, TOOLBAR, UNSORTED
} = require('sdk/places/bookmarks');
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
function invalidResolve (assert) {
return function (e) {
assert.fail('Resolve state should not be called: ' + e);
};
}
exports.invalidResolve = invalidResolve;
// Removes all children of group
function clearBookmarks (group) {
group
? bmsrv.removeFolderChildren(group.id)
: clearAllBookmarks();
}
function clearAllBookmarks () {
[MENU, TOOLBAR, UNSORTED].forEach(clearBookmarks);
}
function clearHistory (done) {
PlacesUtils.history.clear().catch(Cu.reportError).then(done);
}
// Cleans bookmarks and history and disables maintanance
function resetPlaces (done) {
// Set last maintenance to current time to prevent
// Places DB maintenance occuring and locking DB
set('places.database.lastMaintenance', Math.floor(Date.now() / 1000));
clearAllBookmarks();
clearHistory(done);
}
exports.resetPlaces = resetPlaces;
function compareWithHost (assert, item) {
let id = item.id;
let type = item.type === 'group' ? bmsrv.TYPE_FOLDER : bmsrv['TYPE_' + item.type.toUpperCase()];
let url = item.url && !item.url.endsWith('/') ? item.url + '/' : item.url;
if (type === bmsrv.TYPE_BOOKMARK) {
assert.equal(url, bmsrv.getBookmarkURI(id).spec.toString(), 'Matches host url');
let tags = tagsrv.getTagsForURI(newURI(item.url));
for (let tag of tags) {
// Handle both array for raw data and set for instances
if (Array.isArray(item.tags))
assert.ok(~item.tags.indexOf(tag), 'has correct tag');
else
assert.ok(item.tags.has(tag), 'has correct tag');
}
assert.equal(tags.length,
Array.isArray(item.tags) ? item.tags.length : item.tags.size,
'matches tag count');
}
if (type !== bmsrv.TYPE_SEPARATOR) {
assert.equal(item.title, bmsrv.getItemTitle(id), 'Matches host title');
}
assert.equal(item.index, bmsrv.getItemIndex(id), 'Matches host index');
assert.equal(item.group.id || item.group, bmsrv.getFolderIdForItem(id), 'Matches host group id');
assert.equal(type, bmsrv.getItemType(id), 'Matches host type');
}
exports.compareWithHost = compareWithHost;
function addVisits (urls) {
var deferred = defer();
asyncHistory.updatePlaces([].concat(urls).map(createVisit), {
handleResult: function () {},
handleError: deferred.reject,
handleCompletion: deferred.resolve
});
return deferred.promise;
}
exports.addVisits = addVisits;
function removeVisits (urls) {
[].concat(urls).map(url => {
hsrv.removePage(newURI(url));
});
}
exports.removeVisits = removeVisits;
// Creates a mozIVisitInfo object
function createVisit (url) {
let place = {}
place.uri = newURI(url);
place.title = "Test visit for " + place.uri.spec;
place.visits = [{
transitionType: hsrv.TRANSITION_LINK,
visitDate: +(new Date()) * 1000,
referredURI: undefined
}];
return place;
}
function createBookmark (data) {
data = data || {};
let item = {
title: data.title || 'Moz',
url: data.url || (!data.type || data.type === 'bookmark' ?
'http://moz.com/' :
undefined),
tags: data.tags || (!data.type || data.type === 'bookmark' ?
['firefox'] :
undefined),
type: data.type || 'bookmark',
group: data.group
};
return send('sdk-places-bookmarks-create', item);
}
exports.createBookmark = createBookmark;
function historyBatch () {
hsrv.runInBatchMode(() => {}, null);
}
exports.historyBatch = historyBatch;
function createBookmarkItem (data) {
let deferred = defer();
data = data || {};
save({
title: data.title || 'Moz',
url: data.url || 'http://moz.com/',
tags: data.tags || (!data.type || data.type === 'bookmark' ?
['firefox'] :
undefined),
type: data.type || 'bookmark',
group: data.group
}).on('end', function (bookmark) {
deferred.resolve(bookmark[0]);
});
return deferred.promise;
}
exports.createBookmarkItem = createBookmarkItem;
function createBookmarkTree () {
let agg = [];
return createBookmarkItem({ type: 'group', title: 'mozgroup' })
.then(group => {
agg.push(group);
return all([createBookmarkItem({
title: 'mozilla.com',
url: 'http://mozilla.com/',
group: group,
tags: ['mozilla', 'firefox', 'thunderbird', 'rust']
}), createBookmarkItem({
title: 'mozilla.org',
url: 'http://mozilla.org/',
group: group,
tags: ['mozilla', 'firefox', 'thunderbird', 'rust']
}), createBookmarkItem({
title: 'firefox',
url: 'http://firefox.com/',
group: group,
tags: ['mozilla', 'firefox', 'browser']
}), createBookmarkItem({
title: 'thunderbird',
url: 'http://mozilla.org/thunderbird/',
group: group,
tags: ['mozilla', 'thunderbird', 'email']
}), createBookmarkItem({
title: 'moz subfolder',
group: group,
type: 'group'
})
]);
})
.then(results => {
agg = agg.concat(results);
let subfolder = results.filter(item => item.type === 'group')[0];
return createBookmarkItem({
title: 'dark javascript secrets',
url: 'http://w3schools.com',
group: subfolder,
tags: []
});
}).then(item => {
agg.push(item);
return createBookmarkItem(
{ type: 'group', group: MENU, title: 'other stuff' }
);
}).then(newGroup => {
agg.push(newGroup);
return all([
createBookmarkItem({
title: 'mdn',
url: 'http://developer.mozilla.org/en-US/',
group: newGroup,
tags: ['javascript']
}),
createBookmarkItem({
title: 'web audio',
url: 'http://webaud.io',
group: newGroup,
tags: ['javascript', 'web audio']
}),
createBookmarkItem({
title: 'web audio components',
url: 'http://component.fm',
group: newGroup,
tags: ['javascript', 'web audio', 'components']
})
]);
}).then(results => {
agg = agg.concat(results);
return agg;
});
}
exports.createBookmarkTree = createBookmarkTree;

View file

@ -0,0 +1,948 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'engines': {
'Firefox': '*'
}
};
const { Cc, Ci } = require('chrome');
const { request } = require('sdk/addon/host');
const { filter } = require('sdk/event/utils');
const { on, off } = require('sdk/event/core');
const { setTimeout } = require('sdk/timers');
const { newURI } = require('sdk/url/utils');
const { defer, all, resolve } = require('sdk/core/promise');
const { before, after } = require('sdk/test/utils');
const {
Bookmark, Group, Separator,
save, search, remove,
MENU, TOOLBAR, UNSORTED
} = require('sdk/places/bookmarks');
const {
invalidResolve, createTree,
compareWithHost, createBookmark, createBookmarkItem,
createBookmarkTree, addVisits, resetPlaces
} = require('./places-helper');
const { promisedEmitter } = require('sdk/places/utils');
const bmsrv = Cc['@mozilla.org/browser/nav-bookmarks-service;1'].
getService(Ci.nsINavBookmarksService);
const tagsrv = Cc['@mozilla.org/browser/tagging-service;1'].
getService(Ci.nsITaggingService);
exports.testDefaultFolders = function (assert) {
var ids = [
bmsrv.bookmarksMenuFolder,
bmsrv.toolbarFolder,
bmsrv.unfiledBookmarksFolder
];
[MENU, TOOLBAR, UNSORTED].forEach(function (g, i) {
assert.ok(g.id === ids[i], ' default group matches id');
});
};
exports.testValidation = function (assert) {
assert.throws(() => {
Bookmark({ title: 'a title' });
}, /The `url` property must be a valid URL/, 'throws empty URL error');
assert.throws(() => {
Bookmark({ title: 'a title', url: 'not.a.url' });
}, /The `url` property must be a valid URL/, 'throws invalid URL error');
assert.throws(() => {
Bookmark({ url: 'http://foo.com' });
}, /The `title` property must be defined/, 'throws title error');
assert.throws(() => {
Bookmark();
}, /./, 'throws any error');
assert.throws(() => {
Group();
}, /The `title` property must be defined/, 'throws title error for group');
assert.throws(() => {
Bookmark({ url: 'http://foo.com', title: 'my title', tags: 'a tag' });
}, /The `tags` property must be a Set, or an array/, 'throws error for non set/array tag');
};
exports.testCreateBookmarks = function (assert, done) {
var bm = Bookmark({
title: 'moz',
url: 'http://mozilla.org',
tags: ['moz1', 'moz2', 'moz3']
});
save(bm).on('data', (bookmark, input) => {
assert.equal(input, bm, 'input is original input item');
assert.ok(bookmark.id, 'Bookmark has ID');
assert.equal(bookmark.title, 'moz');
assert.equal(bookmark.url, 'http://mozilla.org');
assert.equal(bookmark.group, UNSORTED, 'Unsorted folder is default parent');
assert.ok(bookmark !== bm, 'bookmark should be a new instance');
compareWithHost(assert, bookmark);
}).on('end', bookmarks => {
assert.equal(bookmarks.length, 1, 'returned bookmarks in end');
assert.equal(bookmarks[0].url, 'http://mozilla.org');
assert.equal(bookmarks[0].tags.has('moz1'), true, 'has first tag');
assert.equal(bookmarks[0].tags.has('moz2'), true, 'has second tag');
assert.equal(bookmarks[0].tags.has('moz3'), true, 'has third tag');
assert.pass('end event is called');
done();
});
};
exports.testCreateGroup = function (assert, done) {
save(Group({ title: 'mygroup', group: MENU })).on('data', g => {
assert.ok(g.id, 'Bookmark has ID');
assert.equal(g.title, 'mygroup', 'matches title');
assert.equal(g.group, MENU, 'Menu folder matches');
compareWithHost(assert, g);
}).on('end', results => {
assert.equal(results.length, 1);
assert.pass('end event is called');
done();
});
};
exports.testCreateSeparator = function (assert, done) {
save(Separator({ group: MENU })).on('data', function (s) {
assert.ok(s.id, 'Separator has id');
assert.equal(s.group, MENU, 'Parent group matches');
compareWithHost(assert, s);
}).on('end', function (results) {
assert.equal(results.length, 1);
assert.pass('end event is called');
done();
});
};
exports.testCreateError = function (assert, done) {
let bookmarks = [
{ title: 'moz1', url: 'http://moz1.com', type: 'bookmark'},
{ title: 'moz2', url: 'invalidurl', type: 'bookmark'},
{ title: 'moz3', url: 'http://moz3.com', type: 'bookmark'}
];
let dataCount = 0, errorCount = 0;
save(bookmarks).on('data', bookmark => {
assert.ok(/moz[1|3]/.test(bookmark.title), 'valid bookmarks complete');
dataCount++;
}).on('error', (reason, item) => {
assert.ok(
/The `url` property must be a valid URL/.test(reason),
'Error event called with correct reason');
assert.equal(item, bookmarks[1], 'returns input that failed in event');
errorCount++;
}).on('end', items => {
assert.equal(dataCount, 2, 'data event called twice');
assert.equal(errorCount, 1, 'error event called once');
assert.equal(items.length, bookmarks.length, 'all items should be in result');
assert.equal(items[0].toString(), '[object Bookmark]',
'should be a saved instance');
assert.equal(items[2].toString(), '[object Bookmark]',
'should be a saved instance');
assert.equal(items[1], bookmarks[1], 'should be original, unsaved object');
search({ query: 'moz' }).on('end', items => {
assert.equal(items.length, 2, 'only two items were successfully saved');
bookmarks[1].url = 'http://moz2.com/';
dataCount = errorCount = 0;
save(bookmarks).on('data', bookmark => {
dataCount++;
}).on('error', reason => errorCount++)
.on('end', items => {
assert.equal(items.length, 3, 'all 3 items saved');
assert.equal(dataCount, 3, '3 data events called');
assert.equal(errorCount, 0, 'no error events called');
search({ query: 'moz' }).on('end', items => {
assert.equal(items.length, 3, 'only 3 items saved');
items.map(item =>
assert.ok(/moz\d\.com/.test(item.url), 'correct item'))
done();
});
});
});
});
};
exports.testSaveDucktypes = function (assert, done) {
save({
title: 'moz',
url: 'http://mozilla.org',
type: 'bookmark'
}).on('data', (bookmark) => {
compareWithHost(assert, bookmark);
done();
});
};
exports.testSaveDucktypesParent = function (assert, done) {
let folder = { title: 'myfolder', type: 'group' };
let bookmark = { title: 'mozzie', url: 'http://moz.com', group: folder, type: 'bookmark' };
let sep = { type: 'separator', group: folder };
save([sep, bookmark]).on('end', (res) => {
compareWithHost(assert, res[0]);
compareWithHost(assert, res[1]);
assert.equal(res[0].group.title, 'myfolder', 'parent is ducktyped group');
assert.equal(res[1].group.title, 'myfolder', 'parent is ducktyped group');
done();
});
};
/*
* Tests the scenario where the original bookmark item is resaved
* and does not have an ID or an updated date, but should still be
* mapped to the item it created previously
*/
exports.testResaveOriginalItemMapping = function (assert, done) {
let bookmark = Bookmark({ title: 'moz', url: 'http://moz.org' });
save(bookmark).on('data', newBookmark => {
bookmark.title = 'new moz';
save(bookmark).on('data', newNewBookmark => {
assert.equal(newBookmark.id, newNewBookmark.id, 'should be the same bookmark item');
assert.equal(bmsrv.getItemTitle(newBookmark.id), 'new moz', 'should have updated title');
done();
});
});
};
exports.testCreateMultipleBookmarks = function (assert, done) {
let data = [
Bookmark({title: 'bm1', url: 'http://bm1.com'}),
Bookmark({title: 'bm2', url: 'http://bm2.com'}),
Bookmark({title: 'bm3', url: 'http://bm3.com'}),
];
save(data).on('data', function (bookmark, input) {
let stored = data.filter(({title}) => title === bookmark.title)[0];
assert.equal(input, stored, 'input is original input item');
assert.equal(bookmark.title, stored.title, 'titles match');
assert.equal(bookmark.url, stored.url, 'urls match');
compareWithHost(assert, bookmark);
}).on('end', function (bookmarks) {
assert.equal(bookmarks.length, 3, 'all bookmarks returned');
done();
});
};
exports.testCreateImplicitParent = function (assert, done) {
let folder = Group({ title: 'my parent' });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: folder }),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: folder }),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: folder })
];
save(bookmarks).on('data', function (bookmark) {
if (bookmark.type === 'bookmark') {
assert.equal(bookmark.group.title, folder.title, 'parent is linked');
compareWithHost(assert, bookmark);
} else if (bookmark.type === 'group') {
assert.equal(bookmark.group.id, UNSORTED.id, 'parent ID of group is correct');
compareWithHost(assert, bookmark);
}
}).on('end', function (results) {
assert.equal(results.length, 3, 'results should only hold explicit saves');
done();
});
};
exports.testCreateExplicitParent = function (assert, done) {
let folder = Group({ title: 'my parent' });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: folder }),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: folder }),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: folder })
];
save(bookmarks.concat(folder)).on('data', function (bookmark) {
if (bookmark.type === 'bookmark') {
assert.equal(bookmark.group.title, folder.title, 'parent is linked');
compareWithHost(assert, bookmark);
} else if (bookmark.type === 'group') {
assert.equal(bookmark.group.id, UNSORTED.id, 'parent ID of group is correct');
compareWithHost(assert, bookmark);
}
}).on('end', function () {
done();
});
};
exports.testCreateNested = function (assert, done) {
let topFolder = Group({ title: 'top', group: MENU });
let midFolder = Group({ title: 'middle', group: topFolder });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder }),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder }),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder })
];
let dataEventCount = 0;
save(bookmarks).on('data', function (bookmark) {
if (bookmark.type === 'bookmark') {
assert.equal(bookmark.group.title, midFolder.title, 'parent is linked');
} else if (bookmark.title === 'top') {
assert.equal(bookmark.group.id, MENU.id, 'parent ID of top group is correct');
} else {
assert.equal(bookmark.group.title, topFolder.title, 'parent title of middle group is correct');
}
dataEventCount++;
compareWithHost(assert, bookmark);
}).on('end', () => {
assert.equal(dataEventCount, 5, 'data events for all saves have occurred');
assert.ok('end event called');
done();
});
};
/*
* Was a scenario when implicitly saving a bookmark that was already created,
* it was not being properly fetched and attempted to recreate
*/
exports.testAddingToExistingParent = function (assert, done) {
let group = { type: 'group', title: 'mozgroup' };
let bookmarks = [
{ title: 'moz1', url: 'http://moz1.com', type: 'bookmark', group: group },
{ title: 'moz2', url: 'http://moz2.com', type: 'bookmark', group: group },
{ title: 'moz3', url: 'http://moz3.com', type: 'bookmark', group: group }
],
firstBatch, secondBatch;
saveP(bookmarks).then(data => {
firstBatch = data;
return saveP([
{ title: 'moz4', url: 'http://moz4.com', type: 'bookmark', group: group },
{ title: 'moz5', url: 'http://moz5.com', type: 'bookmark', group: group }
]);
}, assert.fail).then(data => {
secondBatch = data;
assert.equal(firstBatch[0].group.id, secondBatch[0].group.id,
'successfully saved to the same parent');
}).then(done).catch(assert.fail);
};
exports.testUpdateParent = function (assert, done) {
let group = { type: 'group', title: 'mozgroup' };
saveP(group).then(item => {
item[0].title = 'mozgroup-resave';
return saveP(item[0]);
}).then(item => {
assert.equal(item[0].title, 'mozgroup-resave', 'group saved successfully');
}).then(done).catch(assert.fail);
};
exports.testUpdateSeparator = function (assert, done) {
let sep = [Separator(), Separator(), Separator()];
saveP(sep).then(item => {
item[0].index = 2;
return saveP(item[0]);
}).then(item => {
assert.equal(item[0].index, 2, 'updated index of separator');
}).then(done).catch(assert.fail);
};
exports.testPromisedSave = function (assert, done) {
let topFolder = Group({ title: 'top', group: MENU });
let midFolder = Group({ title: 'middle', group: topFolder });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
];
let first, second, third;
saveP(bookmarks).then(bms => {
first = bms.filter(b => b.title === 'moz1')[0];
second = bms.filter(b => b.title === 'moz2')[0];
third = bms.filter(b => b.title === 'moz3')[0];
assert.equal(first.index, 0);
assert.equal(second.index, 1);
assert.equal(third.index, 2);
first.index = 3;
return saveP(first);
}).then(() => {
assert.equal(bmsrv.getItemIndex(first.id), 2, 'properly moved bookmark');
assert.equal(bmsrv.getItemIndex(second.id), 0, 'other bookmarks adjusted');
assert.equal(bmsrv.getItemIndex(third.id), 1, 'other bookmarks adjusted');
}).then(done).catch(assert.fail);
};
exports.testPromisedErrorSave = function*(assert) {
let bookmarks = [
{ title: 'moz1', url: 'http://moz1.com', type: 'bookmark'},
{ title: 'moz2', url: 'invalidurl', type: 'bookmark'},
{ title: 'moz3', url: 'http://moz3.com', type: 'bookmark'}
];
yield saveP(bookmarks).then(() => {
assert.fail("should not resolve");
}, reason => {
assert.ok(
/The `url` property must be a valid URL/.test(reason),
'Error event called with correct reason');
});
bookmarks[1].url = 'http://moz2.com';
yield saveP(bookmarks);
let res = yield searchP({ query: 'moz' });
assert.equal(res.length, 3, 'all 3 should be saved upon retry');
res.map(item => assert.ok(/moz\d\.com/.test(item.url), 'correct item'));
};
exports.testMovingChildren = function (assert, done) {
let topFolder = Group({ title: 'top', group: MENU });
let midFolder = Group({ title: 'middle', group: topFolder });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
];
save(bookmarks).on('end', bms => {
let first = bms.filter(b => b.title === 'moz1')[0];
let second = bms.filter(b => b.title === 'moz2')[0];
let third = bms.filter(b => b.title === 'moz3')[0];
assert.equal(first.index, 0);
assert.equal(second.index, 1);
assert.equal(third.index, 2);
/* When moving down in the same container we take
* into account the removal of the original item. If you want
* to move from index X to index Y > X you must use
* moveItem(id, folder, Y + 1)
*/
first.index = 3;
save(first).on('end', () => {
assert.equal(bmsrv.getItemIndex(first.id), 2, 'properly moved bookmark');
assert.equal(bmsrv.getItemIndex(second.id), 0, 'other bookmarks adjusted');
assert.equal(bmsrv.getItemIndex(third.id), 1, 'other bookmarks adjusted');
done();
});
});
};
exports.testMovingChildrenNewFolder = function (assert, done) {
let topFolder = Group({ title: 'top', group: MENU });
let midFolder = Group({ title: 'middle', group: topFolder });
let newFolder = Group({ title: 'new', group: MENU });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
];
save(bookmarks).on('end', bms => {
let first = bms.filter(b => b.title === 'moz1')[0];
let second = bms.filter(b => b.title === 'moz2')[0];
let third = bms.filter(b => b.title === 'moz3')[0];
let definedMidFolder = first.group;
let definedNewFolder;
first.group = newFolder;
assert.equal(first.index, 0);
assert.equal(second.index, 1);
assert.equal(third.index, 2);
save(first).on('data', (data) => {
if (data.type === 'group') definedNewFolder = data;
}).on('end', (moved) => {
assert.equal(bmsrv.getItemIndex(second.id), 0, 'other bookmarks adjusted');
assert.equal(bmsrv.getItemIndex(third.id), 1, 'other bookmarks adjusted');
assert.equal(bmsrv.getItemIndex(first.id), 0, 'properly moved bookmark');
assert.equal(bmsrv.getFolderIdForItem(first.id), definedNewFolder.id,
'bookmark has new parent');
assert.equal(bmsrv.getFolderIdForItem(second.id), definedMidFolder.id,
'sibling bookmarks did not move');
assert.equal(bmsrv.getFolderIdForItem(third.id), definedMidFolder.id,
'sibling bookmarks did not move');
done();
});
});
};
exports.testRemoveFunction = function (assert) {
let topFolder = Group({ title: 'new', group: MENU });
let midFolder = Group({ title: 'middle', group: topFolder });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
];
remove([midFolder, topFolder].concat(bookmarks)).map(item => {
assert.equal(item.remove, true, 'remove toggled `remove` property to true');
});
};
exports.testRemove = function (assert, done) {
let id;
createBookmarkItem().then(data => {
id = data.id;
compareWithHost(assert, data); // ensure bookmark exists
save(remove(data)).on('data', (res) => {
assert.pass('data event should be called');
assert.ok(!res, 'response should be empty');
}).on('end', () => {
assert.throws(function () {
bmsrv.getItemTitle(id);
}, 'item should no longer exist');
done();
});
}).catch(assert.fail);
};
/*
* Tests recursively removing children when removing a group
*/
exports.testRemoveAllChildren = function (assert, done) {
let topFolder = Group({ title: 'new', group: MENU });
let midFolder = Group({ title: 'middle', group: topFolder });
let bookmarks = [
Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
];
let saved = [];
save(bookmarks).on('data', (data) => saved.push(data)).on('end', () => {
save(remove(topFolder)).on('end', () => {
assert.equal(saved.length, 5, 'all items should have been saved');
saved.map((item) => {
assert.throws(function () {
bmsrv.getItemTitle(item.id);
}, 'item should no longer exist');
});
done();
});
});
};
exports.testResolution = function (assert, done) {
let firstSave, secondSave;
createBookmarkItem().then((item) => {
firstSave = item;
assert.ok(item.updated, 'bookmark has updated time');
item.title = 'my title';
// Ensure delay so a different save time is set
return resolve(item);
}).then(saveP)
.then(items => {
let item = items[0];
secondSave = item;
assert.ok(firstSave.updated < secondSave.updated, 'snapshots have different update times');
firstSave.title = 'updated title';
return saveP(firstSave, { resolve: (mine, theirs) => {
assert.equal(mine.title, 'updated title', 'correct data for my object');
assert.equal(theirs.title, 'my title', 'correct data for their object');
assert.equal(mine.url, theirs.url, 'other data is equal');
assert.equal(mine.group, theirs.group, 'other data is equal');
assert.ok(mine !== firstSave, 'instance is not passed in');
assert.ok(theirs !== secondSave, 'instance is not passed in');
assert.equal(mine.toString(), '[object Object]', 'serialized objects');
assert.equal(theirs.toString(), '[object Object]', 'serialized objects');
mine.title = 'a new title';
return mine;
}});
}).then((results) => {
let result = results[0];
assert.equal(result.title, 'a new title', 'resolve handles results');
}).then(done).catch(assert.fail);
};
/*
* Same as the resolution test, but with the 'unsaved' snapshot
*/
exports.testResolutionMapping = function (assert, done) {
let bookmark = Bookmark({ title: 'moz', url: 'http://bookmarks4life.com/' });
let saved;
saveP(bookmark).then(data => {
saved = data[0];
saved.title = 'updated title';
// Ensure a delay for different updated times
return resolve(saved);
}).
then(saveP).
then(() => {
bookmark.title = 'conflicting title';
return saveP(bookmark, { resolve: (mine, theirs) => {
assert.equal(mine.title, 'conflicting title', 'correct data for my object');
assert.equal(theirs.title, 'updated title', 'correct data for their object');
assert.equal(mine.url, theirs.url, 'other data is equal');
assert.equal(mine.group, theirs.group, 'other data is equal');
assert.ok(mine !== bookmark, 'instance is not passed in');
assert.ok(theirs !== saved, 'instance is not passed in');
assert.equal(mine.toString(), '[object Object]', 'serialized objects');
assert.equal(theirs.toString(), '[object Object]', 'serialized objects');
mine.title = 'a new title';
return mine;
}});
}).then((results) => {
let result = results[0];
assert.equal(result.title, 'a new title', 'resolve handles results');
}).then(done).catch(assert.fail);
};
exports.testUpdateTags = function (assert, done) {
createBookmarkItem({ tags: ['spidermonkey'] }).then(bookmark => {
bookmark.tags.add('jagermonkey');
bookmark.tags.add('ionmonkey');
bookmark.tags.delete('spidermonkey');
save(bookmark).on('data', saved => {
assert.equal(saved.tags.size, 2, 'should have 2 tags');
assert.ok(saved.tags.has('jagermonkey'), 'should have added tag');
assert.ok(saved.tags.has('ionmonkey'), 'should have added tag');
assert.ok(!saved.tags.has('spidermonkey'), 'should not have removed tag');
done();
});
}).catch(assert.fail);
};
/*
* View `createBookmarkTree` in `./places-helper.js` to see
* expected tree construction
*/
exports.testSearchByGroupSimple = function (assert, done) {
createBookmarkTree().then(() => {
// In initial release of Places API, groups can only be queried
// via a 'simple query', which is one folder set, and no other
// parameters
return searchP({ group: UNSORTED });
}).then(results => {
let groups = results.filter(({type}) => type === 'group');
assert.equal(groups.length, 2, 'returns folders');
assert.equal(results.length, 7,
'should return all bookmarks and folders under UNSORTED');
assert.equal(groups[0].toString(), '[object Group]', 'returns instance');
return searchP({
group: groups.filter(({title}) => title === 'mozgroup')[0]
});
}).then(results => {
let groups = results.filter(({type}) => type === 'group');
assert.equal(groups.length, 1, 'returns one subfolder');
assert.equal(results.length, 6,
'returns all children bookmarks/folders');
assert.ok(results.filter(({url}) => url === 'http://w3schools.com/'),
'returns nested children');
}).then(done).catch(assert.fail);
};
exports.testSearchByGroupComplex = function (assert, done) {
let mozgroup;
createBookmarkTree().then(results => {
mozgroup = results.filter(({title}) => title === 'mozgroup')[0];
return searchP({ group: mozgroup, query: 'javascript' });
}).then(results => {
assert.equal(results.length, 1, 'only one javascript result under mozgroup');
assert.equal(results[0].url, 'http://w3schools.com/', 'correct result');
return searchP({ group: mozgroup, url: '*.mozilla.org' });
}).then(results => {
assert.equal(results.length, 2, 'expected results');
assert.ok(
!results.filter(({url}) => /developer.mozilla/.test(url)).length,
'does not find results from other folders');
}).then(done).catch(assert.fail);
};
exports.testSearchEmitters = function (assert, done) {
createBookmarkTree().then(() => {
let count = 0;
search({ tags: ['mozilla', 'firefox'] }).on('data', data => {
assert.ok(/mozilla|firefox/.test(data.title), 'one of the correct items');
assert.ok(data.tags.has('firefox'), 'has firefox tag');
assert.ok(data.tags.has('mozilla'), 'has mozilla tag');
assert.equal(data + '', '[object Bookmark]', 'returns bookmark');
count++;
}).on('end', data => {
assert.equal(count, 3, 'data event was called for each item');
assert.equal(data.length, 3,
'should return two bookmarks that have both mozilla AND firefox');
assert.equal(data[0].title, 'mozilla.com', 'returns correct bookmark');
assert.equal(data[1].title, 'mozilla.org', 'returns correct bookmark');
assert.equal(data[2].title, 'firefox', 'returns correct bookmark');
assert.equal(data[0] + '', '[object Bookmark]', 'returns bookmarks');
done();
});
}).catch(assert.fail);
};
exports.testSearchTags = function (assert, done) {
createBookmarkTree().then(() => {
// AND tags
return searchP({ tags: ['mozilla', 'firefox'] });
}).then(data => {
assert.equal(data.length, 3,
'should return two bookmarks that have both mozilla AND firefox');
assert.equal(data[0].title, 'mozilla.com', 'returns correct bookmark');
assert.equal(data[1].title, 'mozilla.org', 'returns correct bookmark');
assert.equal(data[2].title, 'firefox', 'returns correct bookmark');
assert.equal(data[0] + '', '[object Bookmark]', 'returns bookmarks');
return searchP([{tags: ['firefox']}, {tags: ['javascript']}]);
}).then(data => {
// OR tags
assert.equal(data.length, 6,
'should return all bookmarks with firefox OR javascript tag');
}).then(done).catch(assert.fail);
};
/*
* Tests 4 scenarios
* '*.mozilla.com'
* 'mozilla.com'
* 'http://mozilla.com/'
* 'http://mozilla.com/*'
*/
exports.testSearchURLForBookmarks = function*(assert) {
yield createBookmarkTree()
let data = yield searchP({ url: 'mozilla.org' });
assert.equal(data.length, 2, 'only URLs with host domain');
assert.equal(data[0].url, 'http://mozilla.org/');
assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
data = yield searchP({ url: '*.mozilla.org' });
assert.equal(data.length, 3, 'returns domain and when host is other than domain');
assert.equal(data[0].url, 'http://mozilla.org/');
assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
assert.equal(data[2].url, 'http://developer.mozilla.org/en-US/');
data = yield searchP({ url: 'http://mozilla.org' });
assert.equal(data.length, 1, 'only exact URL match');
assert.equal(data[0].url, 'http://mozilla.org/');
data = yield searchP({ url: 'http://mozilla.org/*' });
assert.equal(data.length, 2, 'only URLs that begin with query');
assert.equal(data[0].url, 'http://mozilla.org/');
assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
data = yield searchP([{ url: 'mozilla.org' }, { url: 'component.fm' }]);
assert.equal(data.length, 3, 'returns URLs that match EITHER query');
assert.equal(data[0].url, 'http://mozilla.org/');
assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
assert.equal(data[2].url, 'http://component.fm/');
};
/*
* Searches url, title, tags
*/
exports.testSearchQueryForBookmarks = function*(assert) {
yield createBookmarkTree();
let data = yield searchP({ query: 'thunder' });
assert.equal(data.length, 3);
assert.equal(data[0].title, 'mozilla.com', 'query matches tag, url, or title');
assert.equal(data[1].title, 'mozilla.org', 'query matches tag, url, or title');
assert.equal(data[2].title, 'thunderbird', 'query matches tag, url, or title');
data = yield searchP([{ query: 'rust' }, { query: 'component' }]);
// rust OR component
assert.equal(data.length, 3);
assert.equal(data[0].title, 'mozilla.com', 'query matches tag, url, or title');
assert.equal(data[1].title, 'mozilla.org', 'query matches tag, url, or title');
assert.equal(data[2].title, 'web audio components', 'query matches tag, url, or title');
data = yield searchP([{ query: 'moz', tags: ['javascript']}]);
assert.equal(data.length, 1);
assert.equal(data[0].title, 'mdn',
'only one item matches moz query AND has a javascript tag');
};
/*
* Test caching on bulk calls.
* Each construction of a bookmark item snapshot results in
* the recursive lookup of parent groups up to the root groups --
* ensure that the appropriate instances equal each other, and no duplicate
* fetches are called
*
* Implementation-dependent, this checks the host event `sdk-places-bookmarks-get`,
* and if implementation changes, this could increase or decrease
*/
exports.testCaching = function (assert, done) {
let count = 0;
let stream = filter(request, ({event}) =>
/sdk-places-bookmarks-get/.test(event));
on(stream, 'data', handle);
let group = { type: 'group', title: 'mozgroup' };
let bookmarks = [
{ title: 'moz1', url: 'http://moz1.com', type: 'bookmark', group: group },
{ title: 'moz2', url: 'http://moz2.com', type: 'bookmark', group: group },
{ title: 'moz3', url: 'http://moz3.com', type: 'bookmark', group: group }
];
/*
* Use timeout in tests since the platform calls are synchronous
* and the counting event shim may not have occurred yet
*/
saveP(bookmarks).then(() => {
assert.equal(count, 0, 'all new items and root group, no fetches should occur');
count = 0;
return saveP([
{ title: 'moz4', url: 'http://moz4.com', type: 'bookmark', group: group },
{ title: 'moz5', url: 'http://moz5.com', type: 'bookmark', group: group }
]);
// Test `save` look-up
}).then(() => {
assert.equal(count, 1, 'should only look up parent once');
count = 0;
return searchP({ query: 'moz' });
}).then(results => {
// Should query for each bookmark (5) from the query (id -> data),
// their parent during `construct` (1) and the root shouldn't
// require a lookup
assert.equal(count, 6, 'lookup occurs once for each item and parent');
off(stream, 'data', handle);
}).then(done).catch(assert.fail);
function handle ({data}) {
return count++;
}
};
/*
* Search Query Options
*/
exports.testSearchCount = function (assert, done) {
let max = 8;
createBookmarkTree()
.then(testCount(1))
.then(testCount(2))
.then(testCount(3))
.then(testCount(5))
.then(testCount(10))
.then(done)
.catch(assert.fail);
function testCount (n) {
return function () {
return searchP({}, { count: n }).then(results => {
if (n > max) n = max;
assert.equal(results.length, n,
'count ' + n + ' returns ' + n + ' results');
});
};
}
};
exports.testSearchSortForBookmarks = function (assert, done) {
let urls = [
'http://mozilla.com/', 'http://webaud.io/', 'http://mozilla.com/webfwd/',
'http://developer.mozilla.com/', 'http://bandcamp.com/'
];
saveP(
urls.map(url =>
Bookmark({ url: url, title: url.replace(/http:\/\/|\//g,'')}))
).then(() => {
return searchP({}, { sort: 'title' });
}).then(results => {
checkOrder(results, [4,3,0,2,1]);
return searchP({}, { sort: 'title', descending: true });
}).then(results => {
checkOrder(results, [1,2,0,3,4]);
return searchP({}, { sort: 'url' });
}).then(results => {
checkOrder(results, [4,3,0,2,1]);
return searchP({}, { sort: 'url', descending: true });
}).then(results => {
checkOrder(results, [1,2,0,3,4]);
return addVisits(['http://mozilla.com/', 'http://mozilla.com']);
}).then(() =>
saveP(Bookmark({ url: 'http://github.com', title: 'github.com' }))
).then(() => addVisits('http://bandcamp.com/'))
.then(() => searchP({ query: 'webfwd' }))
.then(results => {
results[0].title = 'new title for webfwd';
return saveP(results[0]);
})
.then(() =>
searchP({}, { sort: 'visitCount' })
).then(results => {
assert.equal(results[5].url, 'http://mozilla.com/',
'last entry is the highest visit count');
return searchP({}, { sort: 'visitCount', descending: true });
}).then(results => {
assert.equal(results[0].url, 'http://mozilla.com/',
'first entry is the highest visit count');
return searchP({}, { sort: 'date' });
}).then(results => {
assert.equal(results[5].url, 'http://bandcamp.com/',
'latest visited should be first');
return searchP({}, { sort: 'date', descending: true });
}).then(results => {
assert.equal(results[0].url, 'http://bandcamp.com/',
'latest visited should be at the end');
return searchP({}, { sort: 'dateAdded' });
}).then(results => {
assert.equal(results[5].url, 'http://github.com/',
'last added should be at the end');
return searchP({}, { sort: 'dateAdded', descending: true });
}).then(results => {
assert.equal(results[0].url, 'http://github.com/',
'last added should be first');
return searchP({}, { sort: 'lastModified' });
}).then(results => {
assert.equal(results[5].url, 'http://mozilla.com/webfwd/',
'last modified should be last');
return searchP({}, { sort: 'lastModified', descending: true });
}).then(results => {
assert.equal(results[0].url, 'http://mozilla.com/webfwd/',
'last modified should be first');
}).then(done).catch(assert.fail);
function checkOrder (results, nums) {
assert.equal(results.length, nums.length, 'expected return count');
for (let i = 0; i < nums.length; i++) {
assert.equal(results[i].url, urls[nums[i]], 'successful order');
}
}
};
exports.testSearchComplexQueryWithOptions = function (assert, done) {
createBookmarkTree().then(() => {
return searchP([
{ tags: ['rust'], url: '*.mozilla.org' },
{ tags: ['javascript'], query: 'mozilla' }
], { sort: 'title' });
}).then(results => {
let expected = [
'http://developer.mozilla.org/en-US/',
'http://mozilla.org/'
];
for (let i = 0; i < expected.length; i++)
assert.equal(results[i].url, expected[i], 'correct ordering and item');
}).then(done).catch(assert.fail);
};
exports.testCheckSaveOrder = function (assert, done) {
let group = Group({ title: 'mygroup' });
let bookmarks = [
Bookmark({ url: 'http://url1.com', title: 'url1', group: group }),
Bookmark({ url: 'http://url2.com', title: 'url2', group: group }),
Bookmark({ url: 'http://url3.com', title: 'url3', group: group }),
Bookmark({ url: 'http://url4.com', title: 'url4', group: group }),
Bookmark({ url: 'http://url5.com', title: 'url5', group: group })
];
saveP(bookmarks).then(results => {
for (let i = 0; i < bookmarks.length; i++)
assert.equal(results[i].url, bookmarks[i].url,
'correct ordering of bookmark results');
}).then(done).catch(assert.fail);
};
before(exports, (name, assert, done) => resetPlaces(done));
after(exports, (name, assert, done) => resetPlaces(done));
function saveP () {
return promisedEmitter(save.apply(null, Array.prototype.slice.call(arguments)));
}
function searchP () {
return promisedEmitter(search.apply(null, Array.prototype.slice.call(arguments)));
}

View file

@ -0,0 +1,328 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'engines': {
'Firefox': '*'
}
};
const { Cc, Ci } = require('chrome');
const { defer, all } = require('sdk/core/promise');
const { filter } = require('sdk/event/utils');
const { on, off } = require('sdk/event/core');
const { events } = require('sdk/places/events');
const { setTimeout } = require('sdk/timers');
const { before, after } = require('sdk/test/utils');
const bmsrv = Cc['@mozilla.org/browser/nav-bookmarks-service;1'].
getService(Ci.nsINavBookmarksService);
const { release, platform } = require('node/os');
const isOSX10_6 = (() => {
let vString = release();
return vString && /darwin/.test(platform()) && /10\.6/.test(vString);
})();
const { search } = require('sdk/places/history');
const {
invalidResolve, createTree, createBookmark,
compareWithHost, addVisits, resetPlaces, createBookmarkItem,
removeVisits, historyBatch
} = require('./places-helper');
const { save, MENU, UNSORTED } = require('sdk/places/bookmarks');
const { promisedEmitter } = require('sdk/places/utils');
exports['test bookmark-item-added'] = function (assert, done) {
events.on('data', function handler ({type, data}) {
if (type !== 'bookmark-item-added') return;
if (data.title !== 'bookmark-added-title') return;
events.off('data', handler);
assert.equal(type, 'bookmark-item-added', 'correct type in bookmark-added event');
assert.equal(data.type, 'bookmark', 'correct data.type in bookmark-added event');
assert.ok(data.id != null, 'correct data.id in bookmark-added event');
assert.notEqual(data.parentId, null, 'correct data.parentId in bookmark-added event');
assert.ok(data.index >= 0, 'correct data.index in bookmark-added event');
assert.equal(data.url, 'http://moz.com/', 'correct data.url in bookmark-added event');
assert.notEqual(data.dateAdded, null, 'correct data.dateAdded in bookmark-added event');
done();
});
createBookmark({ title: 'bookmark-added-title' });
};
exports['test bookmark-item-changed'] = function (assert, done) {
let id;
let complete = makeCompleted(done);
// Due to bug 969616 and bug 971964, disabling tests in 10.6 (happens only
// in debug builds) to prevent intermittent failures
if (isOSX10_6) {
assert.pass('skipping test in OSX 10.6');
return done();
}
function handler ({type, data}) {
if (type !== 'bookmark-item-changed') return;
if (data.id !== id) return;
// Abort if the 'bookmark-item-changed' event isn't for the `title` property,
// as sometimes the event can be for the `url` property.
// Intermittent failure, bug 969616
if (data.property !== 'title') return;
assert.equal(type, 'bookmark-item-changed',
'correct type in bookmark-item-changed event');
assert.equal(data.type, 'bookmark',
'correct data in bookmark-item-changed event');
assert.equal(data.property, 'title',
'correct property in bookmark-item-changed event');
assert.equal(data.value, 'bookmark-changed-title-2',
'correct value in bookmark-item-changed event');
assert.ok(data.id === id, 'correct id in bookmark-item-changed event');
assert.ok(data.parentId != null, 'correct data in bookmark-added event');
events.off('data', handler);
complete();
}
events.on('data', handler);
createBookmarkItem({ title: 'bookmark-changed-title' }).then(item => {
id = item.id;
item.title = 'bookmark-changed-title-2';
return saveP(item);
}).then(complete).catch(assert.fail);
};
exports['test bookmark-item-moved'] = function (assert, done) {
let id;
let complete = makeCompleted(done);
let previousIndex, previousParentId;
// Due to bug 969616 and bug 971964, disabling tests in 10.6 (happens only
// in debug builds) to prevent intermittent failures
if (isOSX10_6) {
assert.ok(true, 'skipping test in OSX 10.6');
return done();
}
function handler ({type, data}) {
if (type !== 'bookmark-item-moved') return;
if (data.id !== id) return;
assert.equal(type, 'bookmark-item-moved',
'correct type in bookmark-item-moved event');
assert.equal(data.type, 'bookmark',
'correct data in bookmark-item-moved event');
assert.ok(data.id === id, 'correct id in bookmark-item-moved event');
assert.equal(data.previousParentId, previousParentId,
'correct previousParentId');
assert.equal(data.currentParentId, bmsrv.getFolderIdForItem(id),
'correct currentParentId');
assert.equal(data.previousIndex, previousIndex, 'correct previousIndex');
assert.equal(data.currentIndex, bmsrv.getItemIndex(id), 'correct currentIndex');
events.off('data', handler);
complete();
}
events.on('data', handler);
createBookmarkItem({
title: 'bookmark-moved-title',
group: UNSORTED
}).then(item => {
id = item.id;
previousIndex = bmsrv.getItemIndex(id);
previousParentId = bmsrv.getFolderIdForItem(id);
item.group = MENU;
return saveP(item);
}).then(complete).catch(assert.fail);
};
exports['test bookmark-item-removed'] = function (assert, done) {
let id;
let complete = makeCompleted(done);
function handler ({type, data}) {
if (type !== 'bookmark-item-removed') return;
if (data.id !== id) return;
assert.equal(type, 'bookmark-item-removed',
'correct type in bookmark-item-removed event');
assert.equal(data.type, 'bookmark',
'correct data in bookmark-item-removed event');
assert.ok(data.id === id, 'correct id in bookmark-item-removed event');
assert.equal(data.parentId, UNSORTED.id,
'correct parentId in bookmark-item-removed');
assert.equal(data.url, 'http://moz.com/',
'correct url in bookmark-item-removed event');
assert.equal(data.index, 0,
'correct index in bookmark-item-removed event');
events.off('data', handler);
complete();
}
events.on('data', handler);
createBookmarkItem({
title: 'bookmark-item-remove-title',
group: UNSORTED
}).then(item => {
id = item.id;
item.remove = true;
return saveP(item);
}).then(complete).catch(assert.fail);
};
exports['test bookmark-item-visited'] = function (assert, done) {
let id;
let complete = makeCompleted(done);
function handler ({type, data}) {
if (type !== 'bookmark-item-visited') return;
if (data.id !== id) return;
assert.equal(type, 'bookmark-item-visited',
'correct type in bookmark-item-visited event');
assert.ok(data.id === id, 'correct id in bookmark-item-visited event');
assert.equal(data.parentId, UNSORTED.id,
'correct parentId in bookmark-item-visited');
assert.ok(data.transitionType != null,
'has a transition type in bookmark-item-visited event');
assert.ok(data.time != null,
'has a time in bookmark-item-visited event');
assert.ok(data.visitId != null,
'has a visitId in bookmark-item-visited event');
assert.equal(data.url, 'http://bookmark-item-visited.com/',
'correct url in bookmark-item-visited event');
events.off('data', handler);
complete();
}
events.on('data', handler);
createBookmarkItem({
title: 'bookmark-item-visited',
url: 'http://bookmark-item-visited.com/'
}).then(item => {
id = item.id;
return addVisits('http://bookmark-item-visited.com/');
}).then(complete).catch(assert.fail);
};
exports['test history-start-batch, history-end-batch, history-start-clear'] = function (assert, done) {
let complete = makeCompleted(done, 4);
let startEvent = filter(events, ({type}) => type === 'history-start-batch');
let endEvent = filter(events, ({type}) => type === 'history-end-batch');
let clearEvent = filter(events, ({type}) => type === 'history-start-clear');
function startHandler ({type, data}) {
assert.pass('history-start-batch called');
assert.equal(type, 'history-start-batch',
'history-start-batch has correct type');
off(startEvent, 'data', startHandler);
on(endEvent, 'data', endHandler);
complete();
}
function endHandler ({type, data}) {
assert.pass('history-end-batch called');
assert.equal(type, 'history-end-batch',
'history-end-batch has correct type');
off(endEvent, 'data', endHandler);
complete();
}
function clearHandler ({type, data}) {
assert.pass('history-start-clear called');
assert.equal(type, 'history-start-clear',
'history-start-clear has correct type');
off(clearEvent, 'data', clearHandler);
complete();
}
on(startEvent, 'data', startHandler);
on(clearEvent, 'data', clearHandler);
historyBatch();
resetPlaces(complete);
};
exports['test history-visit, history-title-changed'] = function (assert, done) {
let complete = makeCompleted(() => {
off(titleEvents, 'data', titleHandler);
off(visitEvents, 'data', visitHandler);
done();
}, 6);
let visitEvents = filter(events, ({type}) => type === 'history-visit');
let titleEvents = filter(events, ({type}) => type === 'history-title-changed');
let urls = ['http://moz.com/', 'http://firefox.com/', 'http://mdn.com/'];
function visitHandler ({type, data}) {
assert.equal(type, 'history-visit', 'correct type in history-visit');
assert.ok(~urls.indexOf(data.url), 'history-visit has correct url');
assert.ok(data.visitId != null, 'history-visit has a visitId');
assert.ok(data.time != null, 'history-visit has a time');
assert.ok(data.sessionId != null, 'history-visit has a sessionId');
assert.ok(data.referringId != null, 'history-visit has a referringId');
assert.ok(data.transitionType != null, 'history-visit has a transitionType');
complete();
}
function titleHandler ({type, data}) {
assert.equal(type, 'history-title-changed',
'correct type in history-title-changed');
assert.ok(~urls.indexOf(data.url),
'history-title-changed has correct url');
assert.ok(data.title, 'history-title-changed has title');
complete();
}
on(titleEvents, 'data', titleHandler);
on(visitEvents, 'data', visitHandler);
addVisits(urls);
}
exports['test history-delete-url'] = function (assert, done) {
let complete = makeCompleted(() => {
events.off('data', handler);
done();
}, 3);
let urls = ['http://moz.com/', 'http://firefox.com/', 'http://mdn.com/'];
function handler({type, data}) {
if (type !== 'history-delete-url') return;
assert.equal(type, 'history-delete-url',
'history-delete-url has correct type');
assert.ok(~urls.indexOf(data.url), 'history-delete-url has correct url');
complete();
}
events.on('data', handler);
addVisits(urls).then(() => {
removeVisits(urls);
});
};
exports['test history-page-changed'] = function (assert) {
assert.pass('history-page-changed tested in test-places-favicons');
};
exports['test history-delete-visits'] = function (assert) {
assert.pass('TODO test history-delete-visits');
};
// Bug 1060843
// Wait a tick before finishing tests, as some bookmark activities require
// completion of a result for events. For example, when creating a bookmark,
// a `bookmark-item-added` event is fired, listened to by the first test here,
// while constructing the bookmark item requires subsequent calls to that bookmark item.
// If we destroy the underlying bookmark immediately, these calls will fail.
//
// The places SDK abstraction around this alleviates it, but these are low level events.
after(exports, (name, assert, done) => setTimeout(() => resetPlaces(done), 1));
before(exports, (name, assert, done) => resetPlaces(done));
function saveP () {
return promisedEmitter(save.apply(null, Array.prototype.slice.call(arguments)));
}
function makeCompleted (done, countTo) {
let count = 0;
countTo = countTo || 2;
return function () {
if (++count === countTo) done();
};
}

View file

@ -0,0 +1,242 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'engines': {
'Firefox': '*'
}
};
const { Cc, Ci, Cu } = require('chrome');
const { getFavicon } = require('sdk/places/favicon');
const tabs = require('sdk/tabs');
const open = tabs.open;
const port = 8099;
const host = 'http://localhost:' + port;
const { onFaviconChange, serve, binFavicon } = require('./favicon-helpers');
const { once } = require('sdk/system/events');
const { resetPlaces } = require('./places-helper');
const faviconService = Cc["@mozilla.org/browser/favicon-service;1"].
getService(Ci.nsIFaviconService);
exports.testStringGetFaviconCallbackSuccess = function*(assert) {
let name = 'callbacksuccess'
let srv = yield makeServer(name);
let url = host + '/' + name + '.html';
let favicon = host + '/' + name + '.ico';
let tab;
let wait = new Promise(resolve => {
onFaviconChange(url).then((faviconUrl) => {
getFavicon(url, (url) => {
assert.equal(favicon, url, 'Callback returns correct favicon url');
resolve();
});
});
});
assert.pass("Opening tab");
open({
url: url,
onOpen: (newTab) => tab = newTab,
inBackground: true
});
yield wait;
assert.pass("Complete");
yield complete(tab, srv);
};
exports.testStringGetFaviconCallbackFailure = function*(assert) {
let name = 'callbackfailure';
let srv = yield makeServer(name);
let url = host + '/' + name + '.html';
let tab;
let wait = waitAndExpire(url);
assert.pass("Opening tab");
open({
url: url,
onOpen: (newTab) => tab = newTab,
inBackground: true
});
yield wait;
assert.pass("Getting favicon");
yield new Promise(resolve => {
getFavicon(url, (url) => {
assert.equal(url, null, 'Callback returns null');
resolve();
});
});
assert.pass("Complete");
yield complete(tab, srv);
};
exports.testStringGetFaviconPromiseSuccess = function*(assert) {
let name = 'promisesuccess'
let srv = yield makeServer(name);
let url = host + '/' + name + '.html';
let favicon = host + '/' + name + '.ico';
let tab;
let wait = onFaviconChange(url);
assert.pass("Opening tab");
open({
url: url,
onOpen: (newTab) => tab = newTab,
inBackground: true
});
yield wait;
assert.pass("Getting favicon");
yield getFavicon(url).then((url) => {
assert.equal(url, favicon, 'Callback returns null');
}, () => {
assert.fail('Reject should not be called');
});
assert.pass("Complete");
yield complete(tab, srv);
};
exports.testStringGetFaviconPromiseFailure = function*(assert) {
let name = 'promisefailure'
let srv = yield makeServer(name);
let url = host + '/' + name + '.html';
let tab;
let wait = waitAndExpire(url);
assert.pass("Opening tab");
open({
url: url,
onOpen: (newTab) => tab = newTab,
inBackground: true
});
yield wait;
assert.pass("Getting favicon");
yield getFavicon(url).then(invalidResolve(assert), validReject(assert, 'expired url'));
assert.pass("Complete");
yield complete(tab, srv);
};
exports.testTabsGetFaviconPromiseSuccess = function*(assert) {
let name = 'tabs-success'
let srv = yield makeServer(name);
let url = host + '/' + name + '.html';
let favicon = host + '/' + name + '.ico';
let tab;
let iconPromise = onFaviconChange(url);
assert.pass("Opening tab");
open({
url: url,
onOpen: (newTab) => tab = newTab,
inBackground: true
});
yield iconPromise;
assert.pass("Getting favicon");
yield getFavicon(tab).then((url) => {
assert.equal(url, favicon, "getFavicon should return url for tab");
});
assert.pass("Complete");
yield complete(tab, srv);
};
exports.testTabsGetFaviconPromiseFailure = function*(assert) {
let name = 'tabs-failure'
let srv = yield makeServer(name);
let url = host + '/' + name + '.html';
let tab;
let wait = waitAndExpire(url);
assert.pass("Opening tab");
open({
url: url,
onOpen: (newTab) => tab = newTab,
inBackground: true
});
yield wait;
assert.pass("Getting favicon");
yield getFavicon(tab).then(invalidResolve(assert), validReject(assert, 'expired tab'));
assert.pass("Complete");
yield complete(tab, srv);
};
exports.testRejects = function*(assert) {
yield getFavicon({})
.then(invalidResolve(assert), validReject(assert, 'Object'));
yield getFavicon(null)
.then(invalidResolve(assert), validReject(assert, 'null'));
yield getFavicon(undefined)
.then(invalidResolve(assert), validReject(assert, 'undefined'));
yield getFavicon([])
.then(invalidResolve(assert), validReject(assert, 'Array'));
};
var invalidResolve = (assert) => () => assert.fail('Promise should not be resolved successfully');
var validReject = (assert, name) => () => assert.pass(name + ' correctly rejected');
var makeServer = (name) => serve({
name: name,
favicon: binFavicon,
port: port,
host: host
});
var waitAndExpire = (url) => new Promise(resolve => {
onFaviconChange(url).then(() => {
once('places-favicons-expired', resolve);
faviconService.expireAllFavicons();
});
});
var complete = (tab, srv) => new Promise(resolve => {
tab.close(() => {
resetPlaces(() => {
srv.stop(resolve);
});
});
});

View file

@ -0,0 +1,244 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'engines': {
'Firefox': '*'
}
};
const { Cc, Ci } = require('chrome');
const { defer, all } = require('sdk/core/promise');
const { has } = require('sdk/util/array');
const { setTimeout } = require('sdk/timers');
const { before, after } = require('sdk/test/utils');
const { set } = require('sdk/preferences/service');
const {
search
} = require('sdk/places/history');
const {
invalidResolve, createTree,
compareWithHost, addVisits, resetPlaces
} = require('./places-helper');
const { promisedEmitter } = require('sdk/places/utils');
exports.testEmptyQuery = function*(assert) {
let within = toBeWithin();
yield addVisits([
'http://simplequery-1.com', 'http://simplequery-2.com'
]);
let results = yield searchP();
assert.equal(results.length, 2, 'Correct number of entries returned');
assert.equal(results[0].url, 'http://simplequery-1.com/',
'matches url');
assert.equal(results[1].url, 'http://simplequery-2.com/',
'matches url');
assert.equal(results[0].title, 'Test visit for ' + results[0].url,
'title matches');
assert.equal(results[1].title, 'Test visit for ' + results[1].url,
'title matches');
assert.equal(results[0].visitCount, 1, 'matches access');
assert.equal(results[1].visitCount, 1, 'matches access');
assert.ok(within(results[0].time), 'accurate access time');
assert.ok(within(results[1].time), 'accurate access time');
assert.equal(Object.keys(results[0]).length, 4,
'no addition exposed properties on history result');
};
exports.testVisitCount = function*(assert) {
yield addVisits([
'http://simplequery-1.com', 'http://simplequery-1.com',
'http://simplequery-1.com', 'http://simplequery-1.com'
]);
let results = yield searchP();
assert.equal(results.length, 1, 'Correct number of entries returned');
assert.equal(results[0].url, 'http://simplequery-1.com/', 'correct url');
assert.equal(results[0].visitCount, 4, 'matches access count');
};
/*
* Tests 4 scenarios
* '*.mozilla.org'
* 'mozilla.org'
* 'http://mozilla.org/'
* 'http://mozilla.org/*'
*/
exports.testSearchURLForHistory = function*(assert) {
yield addVisits([
'http://developer.mozilla.org', 'http://mozilla.org',
'http://mozilla.org/index', 'https://mozilla.org'
]);
let results = yield searchP({ url: 'http://mozilla.org/' });
assert.equal(results.length, 1, 'should just be an exact match');
results = yield searchP({ url: '*.mozilla.org' });
assert.equal(results.length, 4, 'returns all entries');
results = yield searchP({ url: 'mozilla.org' });
assert.equal(results.length, 3, 'returns entries where mozilla.org is host');
results = yield searchP({ url: 'http://mozilla.org/*' });
assert.equal(results.length, 2, 'should match anything starting with substring');
};
// Disabling due to intermittent Bug 892619
// TODO solve this
/*
exports.testSearchTimeRange = function (assert, done) {
let firstTime, secondTime;
addVisits([
'http://earlyvisit.org', 'http://earlyvisit.org/earlytown.html'
]).then(searchP).then(results => {
firstTime = results[0].time;
var deferred = defer();
setTimeout(() => deferred.resolve(), 1000);
return deferred.promise;
}).then(() => {
return addVisits(['http://newvisit.org', 'http://newvisit.org/whoawhoa.html']);
}).then(searchP).then(results => {
results.filter(({url, time}) => {
if (/newvisit/.test(url)) secondTime = time;
});
return searchP({ from: firstTime - 1000 });
}).then(results => {
assert.equal(results.length, 4, 'should return all entries');
return searchP({ to: firstTime + 500 });
}).then(results => {
assert.equal(results.length, 2, 'should return only first entries');
results.map(item => {
assert.ok(/earlyvisit/.test(item.url), 'correct entry');
});
return searchP({ from: firstTime + 500 });
}).then(results => {
assert.equal(results.length, 2, 'should return only last entries');
results.map(item => {
assert.ok(/newvisit/.test(item.url), 'correct entry');
});
done();
});
};
*/
exports.testSearchQueryForHistory = function*(assert) {
yield addVisits([
'http://mozilla.com', 'http://webaud.io', 'http://mozilla.com/webfwd'
]);
let results = yield searchP({ query: 'moz' });
assert.equal(results.length, 2, 'should return urls that match substring');
results.map(({url}) => {
assert.ok(/moz/.test(url), 'correct item');
});
results = yield searchP([{ query: 'webfwd' }, { query: 'aud.io' }]);
assert.equal(results.length, 2, 'should OR separate queries');
results.map(({url}) => {
assert.ok(/webfwd|aud\.io/.test(url), 'correct item');
});
};
/*
* Query Options
*/
exports.testSearchCount = function (assert, done) {
addVisits([
'http://mozilla.com', 'http://webaud.io', 'http://mozilla.com/webfwd',
'http://developer.mozilla.com', 'http://bandcamp.com'
]).then(testCount(1))
.then(testCount(2))
.then(testCount(3))
.then(testCount(5))
.then(done);
function testCount (n) {
return function () {
return searchP({}, { count: n }).then(results => {
assert.equal(results.length, n,
'count ' + n + ' returns ' + n + ' results');
});
};
}
};
exports.testSearchSortForHistory = function*(assert) {
function checkOrder (results, nums) {
assert.equal(results.length, nums.length, 'expected return count');
for (let i = 0; i < nums.length; i++) {
assert.equal(results[i].url, places[nums[i]], 'successful order');
}
}
let places = [
'http://mozilla.com/', 'http://webaud.io/', 'http://mozilla.com/webfwd/',
'http://developer.mozilla.com/', 'http://bandcamp.com/'
];
yield addVisits(places);
let results = yield searchP({}, { sort: 'title' });
checkOrder(results, [4,3,0,2,1]);
results = yield searchP({}, { sort: 'title', descending: true });
checkOrder(results, [1,2,0,3,4]);
results = yield searchP({}, { sort: 'url' });
checkOrder(results, [4,3,0,2,1]);
results = yield searchP({}, { sort: 'url', descending: true });
checkOrder(results, [1,2,0,3,4]);
yield addVisits('http://mozilla.com'); // for visit conut
yield addVisits('http://github.com'); // for checking date
results = yield searchP({}, { sort: 'visitCount' });
assert.equal(results[5].url, 'http://mozilla.com/',
'last entry is the highest visit count');
results = yield searchP({}, { sort: 'visitCount', descending: true });
assert.equal(results[0].url, 'http://mozilla.com/',
'first entry is the highest visit count');
results = yield searchP({}, { sort: 'date' });
assert.equal(results[5].url, 'http://github.com/',
'latest visited should be first');
results = yield searchP({}, { sort: 'date', descending: true });
assert.equal(results[0].url, 'http://github.com/',
'latest visited should be at the end');
};
exports.testEmitters = function (assert, done) {
let urls = [
'http://mozilla.com/', 'http://webaud.io/', 'http://mozilla.com/webfwd/',
'http://developer.mozilla.com/', 'http://bandcamp.com/'
];
addVisits(urls).then(() => {
let count = 0;
search().on('data', item => {
assert.ok(~urls.indexOf(item.url), 'data value found in url list');
count++;
}).on('end', results => {
assert.equal(results.length, 5, 'correct count of items');
assert.equal(count, 5, 'data event called 5 times');
done();
});
});
};
function toBeWithin (range) {
range = range || 2000;
var current = new Date() * 1000; // convert to microseconds
return compared => {
return compared - current < range;
};
}
function searchP () {
return promisedEmitter(search.apply(null, Array.prototype.slice.call(arguments)));
}
before(exports, (name, assert, done) => resetPlaces(done));
after(exports, (name, assert, done) => resetPlaces(done));

View file

@ -0,0 +1,301 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'engines': {
'Firefox': '*'
}
};
const { Cc, Ci } = require('chrome');
const { defer, all } = require('sdk/core/promise');
const { setTimeout } = require('sdk/timers');
const { newURI } = require('sdk/url/utils');
const { send } = require('sdk/addon/events');
const { set } = require('sdk/preferences/service');
const { before, after } = require('sdk/test/utils');
require('sdk/places/host/host-bookmarks');
require('sdk/places/host/host-tags');
require('sdk/places/host/host-query');
const {
invalidResolve, createTree,
compareWithHost, createBookmark, createBookmarkTree, resetPlaces
} = require('./places-helper');
const bmsrv = Cc['@mozilla.org/browser/nav-bookmarks-service;1'].
getService(Ci.nsINavBookmarksService);
const hsrv = Cc['@mozilla.org/browser/nav-history-service;1'].
getService(Ci.nsINavHistoryService);
const tagsrv = Cc['@mozilla.org/browser/tagging-service;1'].
getService(Ci.nsITaggingService);
exports.testBookmarksCreate = function*(assert) {
let items = [{
title: 'my title',
url: 'http://test-places-host.com/testBookmarksCreate/',
tags: ['some', 'tags', 'yeah'],
type: 'bookmark'
}, {
title: 'my folder',
type: 'group',
group: bmsrv.bookmarksMenuFolder
}, {
type: 'separator',
group: bmsrv.unfiledBookmarksFolder
}];
yield all(items.map((item) => {
return send('sdk-places-bookmarks-create', item).then((data) => {
compareWithHost(assert, data);
});
}));
};
exports.testBookmarksCreateFail = function (assert, done) {
let items = [{
title: 'my title',
url: 'not-a-url',
type: 'bookmark'
}, {
type: 'group',
group: bmsrv.bookmarksMenuFolder
}, {
group: bmsrv.unfiledBookmarksFolder
}];
all(items.map(function (item) {
return send('sdk-places-bookmarks-create', item).then(null, function (reason) {
assert.ok(reason, 'bookmark create should fail');
});
})).then(done);
};
exports.testBookmarkLastUpdated = function (assert, done) {
let timestamp;
let item;
createBookmark({
url: 'http://test-places-host.com/testBookmarkLastUpdated'
}).then(function (data) {
item = data;
timestamp = item.updated;
return send('sdk-places-bookmarks-last-updated', { id: item.id });
}).then(function (updated) {
let { resolve, promise } = defer();
assert.equal(timestamp, updated, 'should return last updated time');
item.title = 'updated mozilla';
setTimeout(() => {
resolve(send('sdk-places-bookmarks-save', item));
}, 100);
return promise;
}).then(function (data) {
assert.ok(data.updated > timestamp, 'time has elapsed and updated the updated property');
done();
});
};
exports.testBookmarkRemove = function (assert, done) {
let id;
createBookmark({
url: 'http://test-places-host.com/testBookmarkRemove/'
}).then(function (data) {
id = data.id;
compareWithHost(assert, data); // ensure bookmark exists
bmsrv.getItemTitle(id); // does not throw an error
return send('sdk-places-bookmarks-remove', data);
}).then(function () {
assert.throws(function () {
bmsrv.getItemTitle(id);
}, 'item should no longer exist');
done();
}, assert.fail);
};
exports.testBookmarkGet = function (assert, done) {
let bookmark;
createBookmark({
url: 'http://test-places-host.com/testBookmarkGet/'
}).then(function (data) {
bookmark = data;
return send('sdk-places-bookmarks-get', { id: data.id });
}).then(function (data) {
'title url index group updated type tags'.split(' ').map(function (prop) {
if (prop === 'tags') {
for (let tag of bookmark.tags) {
assert.ok(~data.tags.indexOf(tag),
'correctly fetched tag ' + tag);
}
assert.equal(bookmark.tags.length, data.tags.length,
'same amount of tags');
}
else
assert.equal(bookmark[prop], data[prop], 'correctly fetched ' + prop);
});
done();
});
};
exports.testTagsTag = function (assert, done) {
let url;
createBookmark({
url: 'http://test-places-host.com/testTagsTag/',
}).then(function (data) {
url = data.url;
return send('sdk-places-tags-tag', {
url: data.url, tags: ['mozzerella', 'foxfire']
});
}).then(function () {
let tags = tagsrv.getTagsForURI(newURI(url));
assert.ok(~tags.indexOf('mozzerella'), 'first tag found');
assert.ok(~tags.indexOf('foxfire'), 'second tag found');
assert.ok(~tags.indexOf('firefox'), 'default tag found');
assert.equal(tags.length, 3, 'no extra tags');
done();
});
};
exports.testTagsUntag = function (assert, done) {
let item;
createBookmark({
url: 'http://test-places-host.com/testTagsUntag/',
tags: ['tag1', 'tag2', 'tag3']
}).then(data => {
item = data;
return send('sdk-places-tags-untag', {
url: item.url,
tags: ['tag2', 'firefox']
});
}).then(function () {
let tags = tagsrv.getTagsForURI(newURI(item.url));
assert.ok(~tags.indexOf('tag1'), 'first tag persisted');
assert.ok(~tags.indexOf('tag3'), 'second tag persisted');
assert.ok(!~tags.indexOf('firefox'), 'first tag removed');
assert.ok(!~tags.indexOf('tag2'), 'second tag removed');
assert.equal(tags.length, 2, 'no extra tags');
done();
});
};
exports.testTagsGetURLsByTag = function (assert, done) {
let item;
createBookmark({
url: 'http://test-places-host.com/testTagsGetURLsByTag/'
}).then(function (data) {
item = data;
return send('sdk-places-tags-get-urls-by-tag', {
tag: 'firefox'
});
}).then(function(urls) {
assert.equal(item.url, urls[0], 'returned correct url');
assert.equal(urls.length, 1, 'returned only one url');
done();
});
};
exports.testTagsGetTagsByURL = function (assert, done) {
let item;
createBookmark({
url: 'http://test-places-host.com/testTagsGetURLsByTag/',
tags: ['firefox', 'mozilla', 'metal']
}).then(function (data) {
item = data;
return send('sdk-places-tags-get-tags-by-url', {
url: data.url,
});
}).then(function(tags) {
assert.ok(~tags.indexOf('firefox'), 'returned first tag');
assert.ok(~tags.indexOf('mozilla'), 'returned second tag');
assert.ok(~tags.indexOf('metal'), 'returned third tag');
assert.equal(tags.length, 3, 'returned all tags');
done();
});
};
exports.testHostQuery = function (assert, done) {
all([
createBookmark({
url: 'http://firefox.com/testHostQuery/',
tags: ['firefox', 'mozilla']
}),
createBookmark({
url: 'http://mozilla.com/testHostQuery/',
tags: ['mozilla']
}),
createBookmark({ url: 'http://thunderbird.com/testHostQuery/' })
]).then(data => {
return send('sdk-places-query', {
queries: { tags: ['mozilla'] },
options: { sortingMode: 6, queryType: 1 } // sort by URI ascending, bookmarks only
});
}).then(results => {
assert.equal(results.length, 2, 'should only return two');
assert.equal(results[0].url,
'http://mozilla.com/testHostQuery/', 'is sorted by URI asc');
return send('sdk-places-query', {
queries: { tags: ['mozilla'] },
options: { sortingMode: 5, queryType: 1 } // sort by URI descending, bookmarks only
});
}).then(results => {
assert.equal(results.length, 2, 'should only return two');
assert.equal(results[0].url,
'http://firefox.com/testHostQuery/', 'is sorted by URI desc');
done();
});
};
exports.testHostMultiQuery = function (assert, done) {
all([
createBookmark({
url: 'http://firefox.com/testHostMultiQuery/',
tags: ['firefox', 'mozilla']
}),
createBookmark({
url: 'http://mozilla.com/testHostMultiQuery/',
tags: ['mozilla']
}),
createBookmark({ url: 'http://thunderbird.com/testHostMultiQuery/' })
]).then(data => {
return send('sdk-places-query', {
queries: [{ tags: ['firefox'] }, { uri: 'http://thunderbird.com/testHostMultiQuery/' }],
options: { sortingMode: 5, queryType: 1 } // sort by URI descending, bookmarks only
});
}).then(results => {
assert.equal(results.length, 2, 'should return 2 results ORing queries');
assert.equal(results[0].url,
'http://firefox.com/testHostMultiQuery/', 'should match URL or tag');
assert.equal(results[1].url,
'http://thunderbird.com/testHostMultiQuery/', 'should match URL or tag');
return send('sdk-places-query', {
queries: [{ tags: ['firefox'], url: 'http://mozilla.com/testHostMultiQuery/' }],
options: { sortingMode: 5, queryType: 1 } // sort by URI descending, bookmarks only
});
}).then(results => {
assert.equal(results.length, 0, 'query props should be AND\'d');
done();
});
};
exports.testGetAllBookmarks = function (assert, done) {
createBookmarkTree().then(() => {
return send('sdk-places-bookmarks-get-all', {});
}).then(res => {
assert.equal(res.length, 8, 'all bookmarks returned');
done();
}, assert.fail);
};
exports.testGetAllChildren = function (assert, done) {
createBookmarkTree().then(results => {
return send('sdk-places-bookmarks-get-children', {
id: results.filter(({title}) => title === 'mozgroup')[0].id
});
}).then(results => {
assert.equal(results.length, 5,
'should return all children and folders at a single depth');
done();
});
};
before(exports, (name, assert, done) => resetPlaces(done));
after(exports, (name, assert, done) => resetPlaces(done));

View file

@ -0,0 +1,78 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'engines': {
'Firefox': '*'
}
};
const { defer, all } = require('sdk/core/promise');
const { setTimeout } = require('sdk/timers');
const { TreeNode } = require('sdk/places/utils');
exports['test construct tree'] = function (assert) {
let tree = TreeNode(1);
tree.add([2, 3, 4]);
tree.get(2).add([2.1, 2.2, 2.3]);
let newTreeNode = TreeNode(4.3);
newTreeNode.add([4.31, 4.32]);
tree.get(4).add([4.1, 4.2, newTreeNode]);
assert.equal(tree.get(2).value, 2, 'get returns node with correct value');
assert.equal(tree.get(2.3).value, 2.3, 'get returns node with correct value');
assert.equal(tree.get(4.32).value, 4.32, 'get returns node even if created from nested node');
assert.equal(tree.get(4).children.length, 3, 'nodes have correct children length');
assert.equal(tree.get(3).children.length, 0, 'nodes have correct children length');
assert.equal(tree.get(4).get(4.32).value, 4.32, 'node.get descends from itself');
assert.equal(tree.get(4).get(2), null, 'node.get descends from itself fails if not descendant');
};
exports['test walk'] = function (assert, done) {
let resultsAll = [];
let resultsNode = [];
let tree = TreeNode(1);
tree.add([2, 3, 4]);
tree.get(2).add([2.1, 2.2]);
tree.walk(function (node) {
resultsAll.push(node.value);
}).then(() => {
[1, 2, 2.1, 2.2, 3, 4].forEach(num => {
assert.ok(~resultsAll.indexOf(num), 'function applied to each node from root');
});
return tree.get(2).walk(node => resultsNode.push(node.value));
}).then(() => {
[2, 2.1, 2.2].forEach(function (num) {
assert.ok(~resultsNode.indexOf(num), 'function applied to each node from node');
});
}).catch(assert.fail).then(done);
};
exports['test async walk'] = function (assert, done) {
let resultsAll = [];
let tree = TreeNode(1);
tree.add([2, 3, 4]);
tree.get(2).add([2.1, 2.2]);
tree.walk(function (node) {
let deferred = defer();
setTimeout(function () {
resultsAll.push(node.value);
deferred.resolve(node.value);
}, node.value === 2 ? 50 : 5);
return deferred.promise;
}).then(function () {
[1, 2, 2.1, 2.2, 3, 4].forEach(function (num) {
assert.ok(~resultsAll.indexOf(num), 'function applied to each node from root');
});
assert.ok(resultsAll.indexOf(2) < resultsAll.indexOf(2.1),
'child should wait for parent to complete');
assert.ok(resultsAll.indexOf(2) < resultsAll.indexOf(2.2),
'child should wait for parent to complete');
done();
});
};