addon-sdk/source/test/addons/places/tests/test-places-bookmarks.js

Thu, 15 Jan 2015 15:59:08 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 15 Jan 2015 15:59:08 +0100
branch
TOR_BUG_9701
changeset 10
ac0c01689b40
permissions
-rw-r--r--

Implement a real Private Browsing Mode condition by changing the API/ABI;
This solves Tor bug #9701, complying with disk avoidance documented in
https://www.torproject.org/projects/torbrowser/design/#disk-avoidance.

     1 /* This Source Code Form is subject to the terms of the Mozilla Public
     2  * License, v. 2.0. If a copy of the MPL was not distributed with this
     3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     4 'use strict';
     6 module.metadata = {
     7   'engines': {
     8     'Firefox': '*'
     9   }
    10 };
    12 const { Cc, Ci } = require('chrome');
    13 const { request } = require('sdk/addon/host');
    14 const { filter } = require('sdk/event/utils');
    15 const { on, off } = require('sdk/event/core');
    16 const { setTimeout } = require('sdk/timers');
    17 const { newURI } = require('sdk/url/utils');
    18 const { defer, all } = require('sdk/core/promise');
    19 const { defer: async } = require('sdk/lang/functional');
    20 const { before, after } = require('sdk/test/utils');
    22 const {
    23   Bookmark, Group, Separator,
    24   save, search, remove,
    25   MENU, TOOLBAR, UNSORTED
    26 } = require('sdk/places/bookmarks');
    27 const {
    28   invalidResolve, invalidReject, createTree,
    29   compareWithHost, createBookmark, createBookmarkItem,
    30   createBookmarkTree, addVisits, resetPlaces
    31 } = require('../places-helper');
    32 const { promisedEmitter } = require('sdk/places/utils');
    33 const bmsrv = Cc['@mozilla.org/browser/nav-bookmarks-service;1'].
    34                     getService(Ci.nsINavBookmarksService);
    35 const tagsrv = Cc['@mozilla.org/browser/tagging-service;1'].
    36                     getService(Ci.nsITaggingService);
    38 exports.testDefaultFolders = function (assert) {
    39   var ids = [
    40     bmsrv.bookmarksMenuFolder,
    41     bmsrv.toolbarFolder,
    42     bmsrv.unfiledBookmarksFolder
    43   ];
    44   [MENU, TOOLBAR, UNSORTED].forEach(function (g, i) {
    45     assert.ok(g.id === ids[i], ' default group matches id');
    46   });
    47 };
    49 exports.testValidation = function (assert) {
    50   assert.throws(() => {
    51     Bookmark({ title: 'a title' });
    52   }, /The `url` property must be a valid URL/, 'throws empty URL error');
    54   assert.throws(() => {
    55     Bookmark({ title: 'a title', url: 'not.a.url' });
    56   }, /The `url` property must be a valid URL/, 'throws invalid URL error');
    58   assert.throws(() => {
    59     Bookmark({ url: 'http://foo.com' });
    60   }, /The `title` property must be defined/, 'throws title error');
    62   assert.throws(() => {
    63     Bookmark();
    64   }, /./, 'throws any error');
    66   assert.throws(() => {
    67     Group();
    68   }, /The `title` property must be defined/, 'throws title error for group');
    70   assert.throws(() => {
    71     Bookmark({ url: 'http://foo.com', title: 'my title', tags: 'a tag' });
    72   }, /The `tags` property must be a Set, or an array/, 'throws error for non set/array tag');
    73 };
    75 exports.testCreateBookmarks = function (assert, done) {
    76   var bm = Bookmark({
    77     title: 'moz',
    78     url: 'http://mozilla.org',
    79     tags: ['moz1', 'moz2', 'moz3']
    80   });
    82   save(bm).on('data', (bookmark, input) => {
    83     assert.equal(input, bm, 'input is original input item');
    84     assert.ok(bookmark.id, 'Bookmark has ID');
    85     assert.equal(bookmark.title, 'moz');
    86     assert.equal(bookmark.url, 'http://mozilla.org');
    87     assert.equal(bookmark.group, UNSORTED, 'Unsorted folder is default parent');
    88     assert.ok(bookmark !== bm, 'bookmark should be a new instance');
    89     compareWithHost(assert, bookmark);
    90   }).on('end', bookmarks => {
    91     assert.equal(bookmarks.length, 1, 'returned bookmarks in end');
    92     assert.equal(bookmarks[0].url, 'http://mozilla.org');
    93     assert.equal(bookmarks[0].tags.has('moz1'), true, 'has first tag');
    94     assert.equal(bookmarks[0].tags.has('moz2'), true, 'has second tag');
    95     assert.equal(bookmarks[0].tags.has('moz3'), true, 'has third tag');
    96     assert.pass('end event is called');
    97     done();
    98   });
    99 };
   101 exports.testCreateGroup = function (assert, done) {
   102   save(Group({ title: 'mygroup', group: MENU })).on('data', g => {
   103     assert.ok(g.id, 'Bookmark has ID');
   104     assert.equal(g.title, 'mygroup', 'matches title');
   105     assert.equal(g.group, MENU, 'Menu folder matches');
   106     compareWithHost(assert, g);
   107   }).on('end', results => {
   108     assert.equal(results.length, 1);
   109     assert.pass('end event is called');
   110     done();
   111   });
   112 };
   114 exports.testCreateSeparator = function (assert, done) {
   115   save(Separator({ group: MENU })).on('data', function (s) {
   116     assert.ok(s.id, 'Separator has id');
   117     assert.equal(s.group, MENU, 'Parent group matches');
   118     compareWithHost(assert, s);
   119   }).on('end', function (results) {
   120     assert.equal(results.length, 1);
   121     assert.pass('end event is called');
   122     done();
   123   });
   124 };
   126 exports.testCreateError = function (assert, done) {
   127   let bookmarks = [
   128     { title: 'moz1', url: 'http://moz1.com', type: 'bookmark'},
   129     { title: 'moz2', url: 'invalidurl', type: 'bookmark'},
   130     { title: 'moz3', url: 'http://moz3.com', type: 'bookmark'}
   131   ];
   133   let dataCount = 0, errorCount = 0;
   134   save(bookmarks).on('data', bookmark => {
   135     assert.ok(/moz[1|3]/.test(bookmark.title), 'valid bookmarks complete');
   136     dataCount++;
   137   }).on('error', (reason, item) => {
   138     assert.ok(
   139       /The `url` property must be a valid URL/.test(reason),
   140       'Error event called with correct reason');
   141     assert.equal(item, bookmarks[1], 'returns input that failed in event');
   142     errorCount++;
   143   }).on('end', items => {
   144     assert.equal(dataCount, 2, 'data event called twice');
   145     assert.equal(errorCount, 1, 'error event called once');
   146     assert.equal(items.length, bookmarks.length, 'all items should be in result');
   147     assert.equal(items[0].toString(), '[object Bookmark]',
   148       'should be a saved instance');
   149     assert.equal(items[2].toString(), '[object Bookmark]',
   150       'should be a saved instance');
   151     assert.equal(items[1], bookmarks[1], 'should be original, unsaved object');
   153     search({ query: 'moz' }).on('end', items => {
   154       assert.equal(items.length, 2, 'only two items were successfully saved');
   155       bookmarks[1].url = 'http://moz2.com/';
   156       dataCount = errorCount = 0;
   157       save(bookmarks).on('data', bookmark => {
   158         dataCount++;
   159       }).on('error', reason => errorCount++)
   160       .on('end', items => {
   161         assert.equal(items.length, 3, 'all 3 items saved');
   162         assert.equal(dataCount, 3, '3 data events called');
   163         assert.equal(errorCount, 0, 'no error events called');
   164         search({ query: 'moz' }).on('end', items => {
   165           assert.equal(items.length, 3, 'only 3 items saved');
   166           items.map(item =>
   167             assert.ok(/moz\d\.com/.test(item.url), 'correct item'))
   168           done();
   169         });
   170       });
   171     });
   172   });
   173 };
   175 exports.testSaveDucktypes = function (assert, done) {
   176   save({
   177     title: 'moz',
   178     url: 'http://mozilla.org',
   179     type: 'bookmark'
   180   }).on('data', (bookmark) => {
   181     compareWithHost(assert, bookmark);
   182     done();
   183   });
   184 };
   186 exports.testSaveDucktypesParent = function (assert, done) {
   187   let folder = { title: 'myfolder', type: 'group' };
   188   let bookmark = { title: 'mozzie', url: 'http://moz.com', group: folder, type: 'bookmark' };
   189   let sep = { type: 'separator', group: folder };
   190   save([sep, bookmark]).on('end', (res) => {
   191     compareWithHost(assert, res[0]);
   192     compareWithHost(assert, res[1]);
   193     assert.equal(res[0].group.title, 'myfolder', 'parent is ducktyped group');
   194     assert.equal(res[1].group.title, 'myfolder', 'parent is ducktyped group');
   195     done();
   196   });
   197 };
   199 /*
   200  * Tests the scenario where the original bookmark item is resaved
   201  * and does not have an ID or an updated date, but should still be
   202  * mapped to the item it created previously
   203  */
   204 exports.testResaveOriginalItemMapping = function (assert, done) {
   205   let bookmark = Bookmark({ title: 'moz', url: 'http://moz.org' });
   206   save(bookmark).on('data', newBookmark => {
   207     bookmark.title = 'new moz';
   208     save(bookmark).on('data', newNewBookmark => {
   209       assert.equal(newBookmark.id, newNewBookmark.id, 'should be the same bookmark item');
   210       assert.equal(bmsrv.getItemTitle(newBookmark.id), 'new moz', 'should have updated title');
   211       done();
   212     });
   213   });
   214 };
   216 exports.testCreateMultipleBookmarks = function (assert, done) {
   217   let data = [
   218     Bookmark({title: 'bm1', url: 'http://bm1.com'}),
   219     Bookmark({title: 'bm2', url: 'http://bm2.com'}),
   220     Bookmark({title: 'bm3', url: 'http://bm3.com'}),
   221   ];
   222   save(data).on('data', function (bookmark, input) {
   223     let stored = data.filter(({title}) => title === bookmark.title)[0];
   224     assert.equal(input, stored, 'input is original input item');
   225     assert.equal(bookmark.title, stored.title, 'titles match');
   226     assert.equal(bookmark.url, stored.url, 'urls match');
   227     compareWithHost(assert, bookmark);
   228   }).on('end', function (bookmarks) {
   229     assert.equal(bookmarks.length, 3, 'all bookmarks returned');
   230     done();
   231   });
   232 };
   234 exports.testCreateImplicitParent = function (assert, done) {
   235   let folder = Group({ title: 'my parent' });
   236   let bookmarks = [
   237     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: folder }),
   238     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: folder }),
   239     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: folder })
   240   ];
   241   save(bookmarks).on('data', function (bookmark) {
   242     if (bookmark.type === 'bookmark') {
   243       assert.equal(bookmark.group.title, folder.title, 'parent is linked');
   244       compareWithHost(assert, bookmark);
   245     } else if (bookmark.type === 'group') {
   246       assert.equal(bookmark.group.id, UNSORTED.id, 'parent ID of group is correct');
   247       compareWithHost(assert, bookmark);
   248     }
   249   }).on('end', function (results) {
   250     assert.equal(results.length, 3, 'results should only hold explicit saves');
   251     done();
   252   });
   253 };
   255 exports.testCreateExplicitParent = function (assert, done) {
   256   let folder = Group({ title: 'my parent' });
   257   let bookmarks = [
   258     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: folder }),
   259     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: folder }),
   260     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: folder })
   261   ];
   262   save(bookmarks.concat(folder)).on('data', function (bookmark) {
   263     if (bookmark.type === 'bookmark') {
   264       assert.equal(bookmark.group.title, folder.title, 'parent is linked');
   265       compareWithHost(assert, bookmark);
   266     } else if (bookmark.type === 'group') {
   267       assert.equal(bookmark.group.id, UNSORTED.id, 'parent ID of group is correct');
   268       compareWithHost(assert, bookmark);
   269     }
   270   }).on('end', function () {
   271     done();
   272   });
   273 };
   275 exports.testCreateNested = function (assert, done) {
   276   let topFolder = Group({ title: 'top', group: MENU });
   277   let midFolder = Group({ title: 'middle', group: topFolder });
   278   let bookmarks = [
   279     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder }),
   280     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder }),
   281     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder })
   282   ];
   283   let dataEventCount = 0;
   284   save(bookmarks).on('data', function (bookmark) {
   285     if (bookmark.type === 'bookmark') {
   286       assert.equal(bookmark.group.title, midFolder.title, 'parent is linked');
   287     } else if (bookmark.title === 'top') {
   288       assert.equal(bookmark.group.id, MENU.id, 'parent ID of top group is correct');
   289     } else {
   290       assert.equal(bookmark.group.title, topFolder.title, 'parent title of middle group is correct');
   291     }
   292     dataEventCount++;
   293     compareWithHost(assert, bookmark);
   294   }).on('end', () => {
   295     assert.equal(dataEventCount, 5, 'data events for all saves have occurred');
   296     assert.ok('end event called');
   297     done();
   298   });
   299 };
   301 /*
   302  * Was a scenario when implicitly saving a bookmark that was already created,
   303  * it was not being properly fetched and attempted to recreate
   304  */
   305 exports.testAddingToExistingParent = function (assert, done) {
   306   let group = { type: 'group', title: 'mozgroup' };
   307   let bookmarks = [
   308     { title: 'moz1', url: 'http://moz1.com', type: 'bookmark', group: group },
   309     { title: 'moz2', url: 'http://moz2.com', type: 'bookmark', group: group },
   310     { title: 'moz3', url: 'http://moz3.com', type: 'bookmark', group: group }
   311   ],
   312   firstBatch, secondBatch;
   314   saveP(bookmarks).then(data => {
   315     firstBatch = data;
   316     return saveP([
   317       { title: 'moz4', url: 'http://moz4.com', type: 'bookmark', group: group },
   318       { title: 'moz5', url: 'http://moz5.com', type: 'bookmark', group: group }
   319     ]);
   320   }, assert.fail).then(data => {
   321     secondBatch = data;
   322     assert.equal(firstBatch[0].group.id, secondBatch[0].group.id,
   323       'successfully saved to the same parent');
   324     done();
   325   }, assert.fail);
   326 };
   328 exports.testUpdateParent = function (assert, done) {
   329   let group = { type: 'group', title: 'mozgroup' };
   330   saveP(group).then(item => {
   331     item[0].title = 'mozgroup-resave';
   332     return saveP(item[0]);
   333   }).then(item => {
   334     assert.equal(item[0].title, 'mozgroup-resave', 'group saved successfully');
   335     done();
   336   });
   337 };
   339 exports.testUpdateSeparator = function (assert, done) {
   340   let sep = [Separator(), Separator(), Separator()];
   341   saveP(sep).then(item => {
   342     item[0].index = 2;
   343     return saveP(item[0]);
   344   }).then(item => {
   345     assert.equal(item[0].index, 2, 'updated index of separator');
   346     done();
   347   });
   348 };
   350 exports.testPromisedSave = function (assert, done) {
   351   let topFolder = Group({ title: 'top', group: MENU });
   352   let midFolder = Group({ title: 'middle', group: topFolder });
   353   let bookmarks = [
   354     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
   355     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
   356     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
   357   ];
   358   let first, second, third;
   359   saveP(bookmarks).then(bms => {
   360     first = bms.filter(b => b.title === 'moz1')[0];
   361     second = bms.filter(b => b.title === 'moz2')[0];
   362     third = bms.filter(b => b.title === 'moz3')[0];
   363     assert.equal(first.index, 0);
   364     assert.equal(second.index, 1);
   365     assert.equal(third.index, 2);
   366     first.index = 3;
   367     return saveP(first);
   368   }).then(() => {
   369     assert.equal(bmsrv.getItemIndex(first.id), 2, 'properly moved bookmark');
   370     assert.equal(bmsrv.getItemIndex(second.id), 0, 'other bookmarks adjusted');
   371     assert.equal(bmsrv.getItemIndex(third.id), 1, 'other bookmarks adjusted');
   372     done();
   373   });
   374 };
   376 exports.testPromisedErrorSave = function (assert, done) {
   377   let bookmarks = [
   378     { title: 'moz1', url: 'http://moz1.com', type: 'bookmark'},
   379     { title: 'moz2', url: 'invalidurl', type: 'bookmark'},
   380     { title: 'moz3', url: 'http://moz3.com', type: 'bookmark'}
   381   ];
   382   saveP(bookmarks).then(invalidResolve, reason => {
   383     assert.ok(
   384       /The `url` property must be a valid URL/.test(reason),
   385       'Error event called with correct reason');
   387     bookmarks[1].url = 'http://moz2.com';
   388     return saveP(bookmarks);
   389   }).then(res => {
   390     return searchP({ query: 'moz' });
   391   }).then(res => {
   392     assert.equal(res.length, 3, 'all 3 should be saved upon retry');
   393     res.map(item => assert.ok(/moz\d\.com/.test(item.url), 'correct item'));
   394     done();
   395   }, invalidReject);
   396 };
   398 exports.testMovingChildren = function (assert, done) {
   399   let topFolder = Group({ title: 'top', group: MENU });
   400   let midFolder = Group({ title: 'middle', group: topFolder });
   401   let bookmarks = [
   402     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
   403     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
   404     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
   405   ];
   406   save(bookmarks).on('end', bms => {
   407     let first = bms.filter(b => b.title === 'moz1')[0];
   408     let second = bms.filter(b => b.title === 'moz2')[0];
   409     let third = bms.filter(b => b.title === 'moz3')[0];
   410     assert.equal(first.index, 0);
   411     assert.equal(second.index, 1);
   412     assert.equal(third.index, 2);
   413     /* When moving down in the same container we take
   414      * into account the removal of the original item. If you want
   415      * to move from index X to index Y > X you must use
   416      * moveItem(id, folder, Y + 1)
   417      */
   418     first.index = 3;
   419     save(first).on('end', () => {
   420       assert.equal(bmsrv.getItemIndex(first.id), 2, 'properly moved bookmark');
   421       assert.equal(bmsrv.getItemIndex(second.id), 0, 'other bookmarks adjusted');
   422       assert.equal(bmsrv.getItemIndex(third.id), 1, 'other bookmarks adjusted');
   423       done();
   424     });
   425   });
   426 };
   428 exports.testMovingChildrenNewFolder = function (assert, done) {
   429   let topFolder = Group({ title: 'top', group: MENU });
   430   let midFolder = Group({ title: 'middle', group: topFolder });
   431   let newFolder = Group({ title: 'new', group: MENU });
   432   let bookmarks = [
   433     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
   434     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
   435     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
   436   ];
   437   save(bookmarks).on('end', bms => {
   438     let first = bms.filter(b => b.title === 'moz1')[0];
   439     let second = bms.filter(b => b.title === 'moz2')[0];
   440     let third = bms.filter(b => b.title === 'moz3')[0];
   441     let definedMidFolder = first.group;
   442     let definedNewFolder;
   443     first.group = newFolder;
   444     assert.equal(first.index, 0);
   445     assert.equal(second.index, 1);
   446     assert.equal(third.index, 2);
   447     save(first).on('data', (data) => {
   448       if (data.type === 'group') definedNewFolder = data;
   449     }).on('end', (moved) => {
   450       assert.equal(bmsrv.getItemIndex(second.id), 0, 'other bookmarks adjusted');
   451       assert.equal(bmsrv.getItemIndex(third.id), 1, 'other bookmarks adjusted');
   452       assert.equal(bmsrv.getItemIndex(first.id), 0, 'properly moved bookmark');
   453       assert.equal(bmsrv.getFolderIdForItem(first.id), definedNewFolder.id,
   454         'bookmark has new parent');
   455       assert.equal(bmsrv.getFolderIdForItem(second.id), definedMidFolder.id,
   456         'sibling bookmarks did not move');
   457       assert.equal(bmsrv.getFolderIdForItem(third.id), definedMidFolder.id,
   458         'sibling bookmarks did not move');
   459       done();
   460     });
   461   });
   462 };
   464 exports.testRemoveFunction = function (assert) {
   465   let topFolder = Group({ title: 'new', group: MENU });
   466   let midFolder = Group({ title: 'middle', group: topFolder });
   467   let bookmarks = [
   468     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
   469     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
   470     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
   471   ];
   472   remove([midFolder, topFolder].concat(bookmarks)).map(item => {
   473     assert.equal(item.remove, true, 'remove toggled `remove` property to true');
   474   });
   475 };
   477 exports.testRemove = function (assert, done) {
   478   let id;
   479   createBookmarkItem().then(data => {
   480     id = data.id;
   481     compareWithHost(assert, data); // ensure bookmark exists
   482     save(remove(data)).on('data', (res) => {
   483       assert.pass('data event should be called');
   484       assert.ok(!res, 'response should be empty');
   485     }).on('end', () => {
   486       assert.throws(function () {
   487         bmsrv.getItemTitle(id);
   488       }, 'item should no longer exist');
   489       done();
   490     });
   491   });
   492 };
   494 /*
   495  * Tests recursively removing children when removing a group
   496  */
   497 exports.testRemoveAllChildren = function (assert, done) {
   498   let topFolder = Group({ title: 'new', group: MENU });
   499   let midFolder = Group({ title: 'middle', group: topFolder });
   500   let bookmarks = [
   501     Bookmark({ title: 'moz1', url: 'http://moz1.com', group: midFolder}),
   502     Bookmark({ title: 'moz2', url: 'http://moz2.com', group: midFolder}),
   503     Bookmark({ title: 'moz3', url: 'http://moz3.com', group: midFolder})
   504   ];
   506   let saved = [];
   507   save(bookmarks).on('data', (data) => saved.push(data)).on('end', () => {
   508     save(remove(topFolder)).on('end', () => {
   509       assert.equal(saved.length, 5, 'all items should have been saved');
   510       saved.map((item) => {
   511         assert.throws(function () {
   512           bmsrv.getItemTitle(item.id);
   513         }, 'item should no longer exist');
   514       });
   515       done();
   516     });
   517   });
   518 };
   520 exports.testResolution = function (assert, done) {
   521   let firstSave, secondSave;
   522   createBookmarkItem().then((item) => {
   523     firstSave = item;
   524     assert.ok(item.updated, 'bookmark has updated time');
   525     item.title = 'my title';
   526     // Ensure delay so a different save time is set
   527     return delayed(item);
   528   }).then(saveP)
   529   .then(items => {
   530     let item = items[0];
   531     secondSave = item;
   532     assert.ok(firstSave.updated < secondSave.updated, 'snapshots have different update times');
   533     firstSave.title = 'updated title';
   534     return saveP(firstSave, { resolve: (mine, theirs) => {
   535       assert.equal(mine.title, 'updated title', 'correct data for my object');
   536       assert.equal(theirs.title, 'my title', 'correct data for their object');
   537       assert.equal(mine.url, theirs.url, 'other data is equal');
   538       assert.equal(mine.group, theirs.group, 'other data is equal');
   539       assert.ok(mine !== firstSave, 'instance is not passed in');
   540       assert.ok(theirs !== secondSave, 'instance is not passed in');
   541       assert.equal(mine.toString(), '[object Object]', 'serialized objects');
   542       assert.equal(theirs.toString(), '[object Object]', 'serialized objects');
   543       mine.title = 'a new title';
   544       return mine;
   545     }});
   546   }).then((results) => {
   547     let result = results[0];
   548     assert.equal(result.title, 'a new title', 'resolve handles results');
   549     done();
   550   });
   551 };
   553 /*
   554  * Same as the resolution test, but with the 'unsaved' snapshot
   555  */
   556 exports.testResolutionMapping = function (assert, done) {
   557   let bookmark = Bookmark({ title: 'moz', url: 'http://bookmarks4life.com/' });
   558   let saved;
   559   saveP(bookmark).then(data => {
   560     saved = data[0];
   561     saved.title = 'updated title';
   562     // Ensure a delay for different updated times
   563     return delayed(saved);
   564   }).then(saveP)
   565   .then(() => {
   566     bookmark.title = 'conflicting title';
   567     return saveP(bookmark, { resolve: (mine, theirs) => {
   568       assert.equal(mine.title, 'conflicting title', 'correct data for my object');
   569       assert.equal(theirs.title, 'updated title', 'correct data for their object');
   570       assert.equal(mine.url, theirs.url, 'other data is equal');
   571       assert.equal(mine.group, theirs.group, 'other data is equal');
   572       assert.ok(mine !== bookmark, 'instance is not passed in');
   573       assert.ok(theirs !== saved, 'instance is not passed in');
   574       assert.equal(mine.toString(), '[object Object]', 'serialized objects');
   575       assert.equal(theirs.toString(), '[object Object]', 'serialized objects');
   576       mine.title = 'a new title';
   577       return mine;
   578     }});
   579   }).then((results) => {
   580     let result = results[0];
   581     assert.equal(result.title, 'a new title', 'resolve handles results');
   582     done();
   583   });
   584 };
   586 exports.testUpdateTags = function (assert, done) {
   587   createBookmarkItem({ tags: ['spidermonkey'] }).then(bookmark => {
   588     bookmark.tags.add('jagermonkey');
   589     bookmark.tags.add('ionmonkey');
   590     bookmark.tags.delete('spidermonkey');
   591     save(bookmark).on('data', saved => {
   592       assert.equal(saved.tags.size, 2, 'should have 2 tags');
   593       assert.ok(saved.tags.has('jagermonkey'), 'should have added tag');
   594       assert.ok(saved.tags.has('ionmonkey'), 'should have added tag');
   595       assert.ok(!saved.tags.has('spidermonkey'), 'should not have removed tag');
   596       done();
   597     });
   598   });
   599 };
   601 /*
   602  * View `createBookmarkTree` in `./places-helper.js` to see
   603  * expected tree construction
   604  */
   606 exports.testSearchByGroupSimple = function (assert, done) {
   607   createBookmarkTree().then(() => {
   608      // In initial release of Places API, groups can only be queried
   609      // via a 'simple query', which is one folder set, and no other
   610      // parameters
   611     return searchP({ group: UNSORTED });
   612   }).then(results => {
   613     let groups = results.filter(({type}) => type === 'group');
   614     assert.equal(groups.length, 2, 'returns folders');
   615     assert.equal(results.length, 7,
   616       'should return all bookmarks and folders under UNSORTED');
   617     assert.equal(groups[0].toString(), '[object Group]', 'returns instance');
   618     return searchP({
   619       group: groups.filter(({title}) => title === 'mozgroup')[0]
   620     });
   621   }).then(results => {
   622     let groups = results.filter(({type}) => type === 'group');
   623     assert.equal(groups.length, 1, 'returns one subfolder');
   624     assert.equal(results.length, 6,
   625       'returns all children bookmarks/folders');
   626     assert.ok(results.filter(({url}) => url === 'http://w3schools.com/'),
   627       'returns nested children');
   628     done();
   629   }).then(null, assert.fail);
   630 };
   632 exports.testSearchByGroupComplex = function (assert, done) {
   633   let mozgroup;
   634   createBookmarkTree().then(results => {
   635     mozgroup = results.filter(({title}) => title === 'mozgroup')[0];
   636     return searchP({ group: mozgroup, query: 'javascript' });
   637   }).then(results => {
   638     assert.equal(results.length, 1, 'only one javascript result under mozgroup');
   639     assert.equal(results[0].url, 'http://w3schools.com/', 'correct result');
   640     return searchP({ group: mozgroup, url: '*.mozilla.org' });
   641   }).then(results => {
   642     assert.equal(results.length, 2, 'expected results');
   643     assert.ok(
   644       !results.filter(({url}) => /developer.mozilla/.test(url)).length,
   645       'does not find results from other folders');
   646     done();
   647   }, assert.fail);
   648 };
   650 exports.testSearchEmitters = function (assert, done) {
   651   createBookmarkTree().then(() => {
   652     let count = 0;
   653     search({ tags: ['mozilla', 'firefox'] }).on('data', data => {
   654       assert.ok(/mozilla|firefox/.test(data.title), 'one of the correct items');
   655       assert.ok(data.tags.has('firefox'), 'has firefox tag');
   656       assert.ok(data.tags.has('mozilla'), 'has mozilla tag');
   657       assert.equal(data + '', '[object Bookmark]', 'returns bookmark');
   658       count++;
   659     }).on('end', data => {
   660       assert.equal(count, 3, 'data event was called for each item');
   661       assert.equal(data.length, 3,
   662         'should return two bookmarks that have both mozilla AND firefox');
   663       assert.equal(data[0].title, 'mozilla.com', 'returns correct bookmark');
   664       assert.equal(data[1].title, 'mozilla.org', 'returns correct bookmark');
   665       assert.equal(data[2].title, 'firefox', 'returns correct bookmark');
   666       assert.equal(data[0] + '', '[object Bookmark]', 'returns bookmarks');
   667       done();
   668     });
   669   });
   670 };
   672 exports.testSearchTags = function (assert, done) {
   673   createBookmarkTree().then(() => {
   674     // AND tags
   675     return searchP({ tags: ['mozilla', 'firefox'] });
   676   }).then(data => {
   677     assert.equal(data.length, 3,
   678       'should return two bookmarks that have both mozilla AND firefox');
   679     assert.equal(data[0].title, 'mozilla.com', 'returns correct bookmark');
   680     assert.equal(data[1].title, 'mozilla.org', 'returns correct bookmark');
   681     assert.equal(data[2].title, 'firefox', 'returns correct bookmark');
   682     assert.equal(data[0] + '', '[object Bookmark]', 'returns bookmarks');
   683     return searchP([{tags: ['firefox']}, {tags: ['javascript']}]);
   684   }).then(data => {
   685     // OR tags
   686     assert.equal(data.length, 6,
   687       'should return all bookmarks with firefox OR javascript tag');
   688     done();
   689   });
   690 };
   692 /*
   693  * Tests 4 scenarios
   694  * '*.mozilla.com'
   695  * 'mozilla.com'
   696  * 'http://mozilla.com/'
   697  * 'http://mozilla.com/*'
   698  */
   699 exports.testSearchURL = function (assert, done) {
   700   createBookmarkTree().then(() => {
   701     return searchP({ url: 'mozilla.org' });
   702   }).then(data => {
   703     assert.equal(data.length, 2, 'only URLs with host domain');
   704     assert.equal(data[0].url, 'http://mozilla.org/');
   705     assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
   706     return searchP({ url: '*.mozilla.org' });
   707   }).then(data => {
   708     assert.equal(data.length, 3, 'returns domain and when host is other than domain');
   709     assert.equal(data[0].url, 'http://mozilla.org/');
   710     assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
   711     assert.equal(data[2].url, 'http://developer.mozilla.org/en-US/');
   712     return searchP({ url: 'http://mozilla.org' });
   713   }).then(data => {
   714     assert.equal(data.length, 1, 'only exact URL match');
   715     assert.equal(data[0].url, 'http://mozilla.org/');
   716     return searchP({ url: 'http://mozilla.org/*' });
   717   }).then(data => {
   718     assert.equal(data.length, 2, 'only URLs that begin with query');
   719     assert.equal(data[0].url, 'http://mozilla.org/');
   720     assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
   721     return searchP([{ url: 'mozilla.org' }, { url: 'component.fm' }]);
   722   }).then(data => {
   723     assert.equal(data.length, 3, 'returns URLs that match EITHER query');
   724     assert.equal(data[0].url, 'http://mozilla.org/');
   725     assert.equal(data[1].url, 'http://mozilla.org/thunderbird/');
   726     assert.equal(data[2].url, 'http://component.fm/');
   727   }).then(() => {
   728     done();
   729   });
   730 };
   732 /*
   733  * Searches url, title, tags
   734  */
   735 exports.testSearchQuery = function (assert, done) {
   736   createBookmarkTree().then(() => {
   737     return searchP({ query: 'thunder' });
   738   }).then(data => {
   739     assert.equal(data.length, 3);
   740     assert.equal(data[0].title, 'mozilla.com', 'query matches tag, url, or title');
   741     assert.equal(data[1].title, 'mozilla.org', 'query matches tag, url, or title');
   742     assert.equal(data[2].title, 'thunderbird', 'query matches tag, url, or title');
   743     return searchP([{ query: 'rust' }, { query: 'component' }]);
   744   }).then(data => {
   745     // rust OR component
   746     assert.equal(data.length, 3);
   747     assert.equal(data[0].title, 'mozilla.com', 'query matches tag, url, or title');
   748     assert.equal(data[1].title, 'mozilla.org', 'query matches tag, url, or title');
   749     assert.equal(data[2].title, 'web audio components', 'query matches tag, url, or title');
   750     return searchP([{ query: 'moz', tags: ['javascript']}]);
   751   }).then(data => {
   752     assert.equal(data.length, 1);
   753     assert.equal(data[0].title, 'mdn',
   754       'only one item matches moz query AND has a javascript tag');
   755   }).then(() => {
   756     done();
   757   });
   758 };
   760 /*
   761  * Test caching on bulk calls.
   762  * Each construction of a bookmark item snapshot results in
   763  * the recursive lookup of parent groups up to the root groups --
   764  * ensure that the appropriate instances equal each other, and no duplicate
   765  * fetches are called
   766  *
   767  * Implementation-dependent, this checks the host event `sdk-places-bookmarks-get`,
   768  * and if implementation changes, this could increase or decrease
   769  */
   771 exports.testCaching = function (assert, done) {
   772   let count = 0;
   773   let stream = filter(request, ({event}) =>
   774     /sdk-places-bookmarks-get/.test(event));
   775   on(stream, 'data', handle);
   777   let group = { type: 'group', title: 'mozgroup' };
   778   let bookmarks = [
   779     { title: 'moz1', url: 'http://moz1.com', type: 'bookmark', group: group },
   780     { title: 'moz2', url: 'http://moz2.com', type: 'bookmark', group: group },
   781     { title: 'moz3', url: 'http://moz3.com', type: 'bookmark', group: group }
   782   ];
   784   /*
   785    * Use timeout in tests since the platform calls are synchronous
   786    * and the counting event shim may not have occurred yet
   787    */
   789   saveP(bookmarks).then(() => {
   790     assert.equal(count, 0, 'all new items and root group, no fetches should occur');
   791     count = 0;
   792     return saveP([
   793       { title: 'moz4', url: 'http://moz4.com', type: 'bookmark', group: group },
   794       { title: 'moz5', url: 'http://moz5.com', type: 'bookmark', group: group }
   795     ]);
   796   // Test `save` look-up
   797   }).then(() => {
   798     assert.equal(count, 1, 'should only look up parent once');
   799     count = 0;
   800     return searchP({ query: 'moz' });
   801   }).then(results => {
   802     // Should query for each bookmark (5) from the query (id -> data),
   803     // their parent during `construct` (1) and the root shouldn't
   804     // require a lookup
   805     assert.equal(count, 6, 'lookup occurs once for each item and parent');
   806     off(stream, 'data', handle);
   807     done();
   808   });
   810   function handle ({data}) count++
   811 };
   813 /*
   814  * Search Query Options
   815  */
   817 exports.testSearchCount = function (assert, done) {
   818   let max = 8;
   819   createBookmarkTree()
   820   .then(testCount(1))
   821   .then(testCount(2))
   822   .then(testCount(3))
   823   .then(testCount(5))
   824   .then(testCount(10))
   825   .then(() => {
   826     done();
   827   });
   829   function testCount (n) {
   830     return function () {
   831       return searchP({}, { count: n }).then(results => {
   832         if (n > max) n = max;
   833         assert.equal(results.length, n,
   834           'count ' + n + ' returns ' + n + ' results');
   835       });
   836     };
   837   }
   838 };
   840 exports.testSearchSort = function (assert, done) {
   841   let urls = [
   842     'http://mozilla.com/', 'http://webaud.io/', 'http://mozilla.com/webfwd/',
   843     'http://developer.mozilla.com/', 'http://bandcamp.com/'
   844   ];
   846   saveP(
   847     urls.map(url =>
   848       Bookmark({ url: url, title: url.replace(/http:\/\/|\//g,'')}))
   849   ).then(() => {
   850     return searchP({}, { sort: 'title' });
   851   }).then(results => {
   852     checkOrder(results, [4,3,0,2,1]);
   853     return searchP({}, { sort: 'title', descending: true });
   854   }).then(results => {
   855     checkOrder(results, [1,2,0,3,4]);
   856     return searchP({}, { sort: 'url' });
   857   }).then(results => {
   858     checkOrder(results, [4,3,0,2,1]);
   859     return searchP({}, { sort: 'url', descending: true });
   860   }).then(results => {
   861     checkOrder(results, [1,2,0,3,4]);
   862     return addVisits(['http://mozilla.com/', 'http://mozilla.com']);
   863   }).then(() =>
   864     saveP(Bookmark({ url: 'http://github.com', title: 'github.com' }))
   865   ).then(() => addVisits('http://bandcamp.com/'))
   866   .then(() => searchP({ query: 'webfwd' }))
   867   .then(results => {
   868     results[0].title = 'new title for webfwd';
   869     return saveP(results[0]);
   870   })
   871   .then(() =>
   872     searchP({}, { sort: 'visitCount' })
   873   ).then(results => {
   874     assert.equal(results[5].url, 'http://mozilla.com/',
   875       'last entry is the highest visit count');
   876     return searchP({}, { sort: 'visitCount', descending: true });
   877   }).then(results => {
   878     assert.equal(results[0].url, 'http://mozilla.com/',
   879       'first entry is the highest visit count');
   880     return searchP({}, { sort: 'date' });
   881   }).then(results => {
   882     assert.equal(results[5].url, 'http://bandcamp.com/',
   883       'latest visited should be first');
   884     return searchP({}, { sort: 'date', descending: true });
   885   }).then(results => {
   886     assert.equal(results[0].url, 'http://bandcamp.com/',
   887       'latest visited should be at the end');
   888     return searchP({}, { sort: 'dateAdded' });
   889   }).then(results => {
   890     assert.equal(results[5].url, 'http://github.com/',
   891      'last added should be at the end');
   892     return searchP({}, { sort: 'dateAdded', descending: true });
   893   }).then(results => {
   894     assert.equal(results[0].url, 'http://github.com/',
   895       'last added should be first');
   896     return searchP({}, { sort: 'lastModified' });
   897   }).then(results => {
   898     assert.equal(results[5].url, 'http://mozilla.com/webfwd/',
   899       'last modified should be last');
   900     return searchP({}, { sort: 'lastModified', descending: true });
   901   }).then(results => {
   902     assert.equal(results[0].url, 'http://mozilla.com/webfwd/',
   903       'last modified should be first');
   904   }).then(() => {
   905     done();
   906   });
   908   function checkOrder (results, nums) {
   909     assert.equal(results.length, nums.length, 'expected return count');
   910     for (let i = 0; i < nums.length; i++) {
   911       assert.equal(results[i].url, urls[nums[i]], 'successful order');
   912     }
   913   }
   914 };
   916 exports.testSearchComplexQueryWithOptions = function (assert, done) {
   917   createBookmarkTree().then(() => {
   918     return searchP([
   919       { tags: ['rust'], url: '*.mozilla.org' },
   920       { tags: ['javascript'], query: 'mozilla' }
   921     ], { sort: 'title' });
   922   }).then(results => {
   923     let expected = [
   924       'http://developer.mozilla.org/en-US/',
   925       'http://mozilla.org/'
   926     ];
   927     for (let i = 0; i < expected.length; i++)
   928       assert.equal(results[i].url, expected[i], 'correct ordering and item');
   929     done();
   930   });
   931 };
   933 exports.testCheckSaveOrder = function (assert, done) {
   934   let group = Group({ title: 'mygroup' });
   935   let bookmarks = [
   936     Bookmark({ url: 'http://url1.com', title: 'url1', group: group }),
   937     Bookmark({ url: 'http://url2.com', title: 'url2', group: group }),
   938     Bookmark({ url: 'http://url3.com', title: 'url3', group: group }),
   939     Bookmark({ url: 'http://url4.com', title: 'url4', group: group }),
   940     Bookmark({ url: 'http://url5.com', title: 'url5', group: group })
   941   ];
   942   saveP(bookmarks).then(results => {
   943     for (let i = 0; i < bookmarks.length; i++)
   944       assert.equal(results[i].url, bookmarks[i].url,
   945         'correct ordering of bookmark results');
   946     done();
   947   });
   948 };
   950 before(exports, (name, assert, done) => resetPlaces(done));
   951 after(exports, (name, assert, done) => resetPlaces(done));
   953 function saveP () {
   954   return promisedEmitter(save.apply(null, Array.slice(arguments)));
   955 }
   957 function searchP () {
   958   return promisedEmitter(search.apply(null, Array.slice(arguments)));
   959 }
   961 function delayed (value, ms) {
   962   let { promise, resolve } = defer();
   963   setTimeout(() => resolve(value), ms || 10);
   964   return promise;
   965 }

mercurial