jiotests.js 150 KB
Newer Older
Tristan Cavelier's avatar
Tristan Cavelier committed
1
(function () { var thisfun = function(loader) {
Tristan Cavelier's avatar
Tristan Cavelier committed
2
    var JIO = loader.JIO;
Tristan Cavelier's avatar
Tristan Cavelier committed
3

4 5 6 7 8 9 10 11 12
// localStorage cleanup
var k;
for (k in localStorage) {
    if (/^jio\//.test(k)) {
        localStorage.removeItem(k);
    }
}
delete k;

Tristan Cavelier's avatar
Tristan Cavelier committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26
//// Tools
var empty_fun = function (){},
contains = function (array,content) {
    var i;
    if (typeof array !== 'object') {
        return undefined;
    }
    for (i = 0; i < array.length || 0; i+= 1) {
        if (array[i] === content) {
            return true;
        }
    }
    return false;
},
27
clone = function (obj) {
28 29 30 31 32
  var tmp = JSON.stringify(obj);
  if (tmp !== undefined) {
    return JSON.parse(tmp);
  }
  return tmp;
33
},
34 35 36 37 38 39 40
// generates a revision hash from document metadata, revision history
// and the deleted_flag
generateRevisionHash = function (doc, revisions, deleted_flag) {
    var string = JSON.stringify(doc) + JSON.stringify(revisions) +
        JSON.stringify(deleted_flag? true: false);
    return hex_sha256(string);
},
Tristan Cavelier's avatar
Tristan Cavelier committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
// localStorage wrapper
localstorage = {
    clear: function () {
        return localStorage.clear();
    },
    getItem: function (item) {
        var value = localStorage.getItem(item);
        return value === null? null: JSON.parse(value);
    },
    setItem: function (item,value) {
        return localStorage.setItem(item,JSON.stringify (value));
    },
    removeItem: function (item) {
        return localStorage.removeItem(item);
    }
},
cleanUpLocalStorage = function(){
    var k, storageObject = localstorage.getAll();
59 60 61
    for (k in storageObject) {
        var splitk = k.split('/');
        if ( splitk[0] === 'jio' ) {
Tristan Cavelier's avatar
Tristan Cavelier committed
62
            localstorage.removeItem(k);
63 64 65 66 67 68 69 70
        }
    }
    var d = document.createElement ('div');
    d.setAttribute('id','log');
    document.querySelector ('body').appendChild(d);
    // remove everything
    localStorage.clear();
},
Tristan Cavelier's avatar
Tristan Cavelier committed
71
base_tick = 30000,
Tristan Cavelier's avatar
Tristan Cavelier committed
72
basicTestFunctionGenerator = function(o,res,value,message) {
73

Tristan Cavelier's avatar
Tristan Cavelier committed
74
    return function(err,val) {
Tristan Cavelier's avatar
Tristan Cavelier committed
75
        var jobstatus = (err?'fail':'done');
76

Tristan Cavelier's avatar
Tristan Cavelier committed
77 78 79 80 81 82 83 84 85 86 87
        switch (res) {
        case 'status':
            err = err || {}; val = err.status;
            break;
        case 'jobstatus':
            val = jobstatus;
            break;
        case 'value':
            val = err || val;
            break;
        default:
88
            ok(false, "Unknown case " + res);
Tristan Cavelier's avatar
Tristan Cavelier committed
89 90 91 92
        }
        deepEqual (val,value,message);
    };
},
Sven Franck's avatar
Sven Franck committed
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
/**
 * Prepare a specific test for jio and create a spy.
 * It creates a function [function_name] in [obj] which can be use as a
 * jio callback. To prepare the test, we need to know what kind of return
 * value you want -> [result_type]:
 * - "status": [value] is compared with err.status, the error code
 * - "jobstatus": [value] check if the request is "fail" or "done"
 * - "value": [value] is compared to the response
 * @method basicSpyFunction
 * @param  {object} obj The object to work with
 * @param  {string} result_type The result type
 * @param  {object} value The value to be compared
 * @param  {string} message The test message
 * @param  {string} function_name The callback name
 */
basicSpyFunction = function(obj, result_type, value, message, function_name) {
    function_name = function_name || 'f';
    obj[function_name] =
        basicTestFunctionGenerator(obj, result_type, value, message);
    obj.t.spy(obj, function_name);
Tristan Cavelier's avatar
Tristan Cavelier committed
114
},
115 116 117 118 119 120 121 122 123 124

/**
 * Advances in time and execute the test previously prepared.
 * The default function to test is "f" in [obj].
 * @method basicTickFunction
 * @param  {object} obj The object to work with
 * @param  {number} tick The time to advance in ms (optional)
 * @param  {function_name} function_name The callback to test (optional)
 */
basicTickFunction = function (obj) {
Tristan Cavelier's avatar
Tristan Cavelier committed
125
    var tick, fun, i = 1;
Tristan Cavelier's avatar
Tristan Cavelier committed
126
    tick = 10000;
127
    fun = "f";
Sven Franck's avatar
Sven Franck committed
128

Tristan Cavelier's avatar
Tristan Cavelier committed
129 130 131 132 133 134
    if (typeof arguments[i] === 'number') {
        tick = arguments[i]; i++;
    }
    if (typeof arguments[i] === 'string') {
        fun = arguments[i]; i++;
    }
135 136 137 138
    obj.clock.tick(tick);
    if (!obj[fun].calledOnce) {
        if (obj[fun].called) {
            ok(false, 'too much results (obj.' + fun +')');
Tristan Cavelier's avatar
Tristan Cavelier committed
139
        } else {
140
            ok(false, 'no response (obj.' + fun +')');
Tristan Cavelier's avatar
Tristan Cavelier committed
141 142 143
        }
    }
},
144
getXML = function (url) {
145 146
  var xml = $.ajax({url:url, async:false});
  return xml.responseText;
Tristan Cavelier's avatar
Tristan Cavelier committed
147 148 149 150
},
objectifyDocumentArray = function (array) {
    var obj = {}, k;
    for (k = 0; k < array.length; k += 1) {
Tristan Cavelier's avatar
Tristan Cavelier committed
151
        obj[array[k]._id] = array[k];
Tristan Cavelier's avatar
Tristan Cavelier committed
152 153 154
    }
    return obj;
},
Tristan Cavelier's avatar
Tristan Cavelier committed
155 156
getLastJob = function (id) {
    return (localstorage.getItem("jio/job_array/"+id) || [undefined]).pop();
Tristan Cavelier's avatar
Tristan Cavelier committed
157
},
Tristan Cavelier's avatar
Tristan Cavelier committed
158 159
generateTools = function (sinon) {
    var o = {};
160

Tristan Cavelier's avatar
Tristan Cavelier committed
161
    o.t = sinon;
162
    o.server = o.t.sandbox.useFakeServer();
Tristan Cavelier's avatar
Tristan Cavelier committed
163 164 165 166
    o.clock = o.t.sandbox.useFakeTimers();
    o.clock.tick(base_tick);
    o.spy = basicSpyFunction;
    o.tick = basicTickFunction;
167

Tristan Cavelier's avatar
Tristan Cavelier committed
168
    // test methods
Tristan Cavelier's avatar
Tristan Cavelier committed
169
    o.testLastJobLabel = function (label, mess) {
Tristan Cavelier's avatar
Tristan Cavelier committed
170 171 172 173 174 175
        var lastjob = getLastJob(o.jio.getId());
        if (lastjob) {
            deepEqual(lastjob.command.label, label, mess);
        } else {
            deepEqual("No job on the queue", "Job with label: "+label, mess);
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
176 177
    };
    o.testLastJobId = function (id, mess) {
Tristan Cavelier's avatar
Tristan Cavelier committed
178 179 180 181 182 183
        var lastjob = getLastJob(o.jio.getId());
        if (lastjob) {
            deepEqual(lastjob.id, id, mess);
        } else {
            deepEqual("No job on the queue", "Job with id: "+id, mess);
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
184 185
    };
    o.testLastJobWaitForTime = function (mess) {
Tristan Cavelier's avatar
Tristan Cavelier committed
186 187 188 189 190 191
        var lastjob = getLastJob(o.jio.getId());
        if (lastjob) {
            ok(lastjob.status.waitfortime > 0, mess);
        } else {
            deepEqual("No job on the queue", "Job waiting for time", mess);
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
192 193
    };
    o.testLastJobWaitForJob = function (job_id_array, mess) {
Tristan Cavelier's avatar
Tristan Cavelier committed
194 195 196 197 198 199 200 201 202 203
        var lastjob = getLastJob(o.jio.getId());
        if (lastjob) {
            deepEqual(lastjob.status.waitforjob, job_id_array, mess);
        } else {
            deepEqual(
                "No job on the queue",
                "Job waiting for: " + JSON.stringify (job_id_array),
                mess
            );
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
204
    };
Tristan Cavelier's avatar
Tristan Cavelier committed
205
    // wait method
Tristan Cavelier's avatar
Tristan Cavelier committed
206 207 208 209
    o.waitUntilAJobExists = function (timeout) {
        var cpt = 0
        while (true) {
            if (getLastJob(o.jio.getId()) !== undefined) {
Tristan Cavelier's avatar
Tristan Cavelier committed
210 211
                break;
            }
Tristan Cavelier's avatar
Tristan Cavelier committed
212
            if (timeout >= cpt) {
Tristan Cavelier's avatar
Tristan Cavelier committed
213
                ok(false, "No job were added to the queue");
Tristan Cavelier's avatar
Tristan Cavelier committed
214 215 216 217
                break;
            }
            o.clock.tick(25);
            cpt += 25;
Tristan Cavelier's avatar
Tristan Cavelier committed
218
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
219 220 221 222
    };
    o.waitUntilLastJobIs = function (state) {
        while (true) {
            if (getLastJob(o.jio.getId()) === undefined) {
Tristan Cavelier's avatar
Tristan Cavelier committed
223
                ok(false, "No job have state: " + state);
Tristan Cavelier's avatar
Tristan Cavelier committed
224 225 226 227 228 229
                break;
            }
            if (getLastJob(o.jio.getId()).status.label === state) {
                break;
            }
            o.clock.tick(25);
230
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
231
    };
232 233 234 235 236 237 238 239 240 241 242 243
    o.constructFakeServerUrl = function(type, path) {
      switch (type) {
        case "dav":
          return 'https:\\/\\/ca-davstorage:8080\\/' + path + '(\\?.*|$)';
          break;
        case "s3":
          return path;
          break;
      }
    };
    o.addFakeServerResponse = function (type, method, path, status, response) {
      var url = new RegExp(o.constructFakeServerUrl(type, path) );
244 245 246 247 248
      o.server.respondWith(method, url,
        [status, { "Content-Type": 'application/xml' }, response]
      );
    }

Tristan Cavelier's avatar
Tristan Cavelier committed
249
    return o;
Tristan Cavelier's avatar
Tristan Cavelier committed
250
},
Tristan Cavelier's avatar
Tristan Cavelier committed
251 252
//// end tools

Tristan Cavelier's avatar
Tristan Cavelier committed
253 254 255 256 257 258 259 260 261
//// test function
isUuid = function (uuid) {
    var x = "[0-9a-fA-F]{4}";
    if (typeof uuid !== "string" ) {
        return false;
    }
    return uuid.match("^"+x+x+"-"+x+"-"+x+"-"+x+"-"+x+x+x+"$") === null?
        false: true;
};
Tristan Cavelier's avatar
Tristan Cavelier committed
262 263 264 265 266 267 268 269 270 271
//// QUnit Tests ////
module ('Jio Global tests');

test ( "Jio simple methods", function () {
    // Test Jio simple methods
    // It checks if we can create several instance of jio at the same
    // time. Checks if they don't overlap informations, if they are
    // started and stopped correctly and if they are ready when they
    // have to be ready.

Tristan Cavelier's avatar
Tristan Cavelier committed
272 273
    var o = generateTools(this);

Tristan Cavelier's avatar
Tristan Cavelier committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    o.jio = JIO.newJio();
    ok ( o.jio, 'a new jio -> 1');

    o.jio2 = JIO.newJio();
    ok ( o.jio2, 'another new jio -> 2');

    JIO.addStorageType('qunit', empty_fun);

    ok ( o.jio2.getId() !== o.jio.getId(), '1 and 2 must be different');

    o.jio.stop();
    o.jio2.stop();

});

// test ( 'Jio Publish/Sububscribe/Unsubscribe methods', function () {
//     // Test the Publisher, Subscriber of a single jio.
//     // It is just testing if these function are working correctly.
//     // The test publishes an event, waits a little, and check if the
//     // event has been received by the callback of the previous
//     // subscribe. Then, the test unsubscribe the callback function from
//     // the event, and publish the same event. If it receives the event,
//     // the unsubscribe method is not working correctly.

//     var o = {};
//     o.jio = JIO.newJio();

//     var spy1 = this.spy();

//     // Subscribe the pubsub_test event.
//     o.callback = o.jio.subscribe('pubsub_test',spy1);
//     // And publish the event.
//     o.jio.publish('pubsub_test');
//     ok (spy1.calledOnce, 'subscribing & publishing, event called once');

//     o.jio.unsubscribe('pubsub_test',spy1);
//     o.jio.publish('pubsub_test');
//     ok (spy1.calledOnce, 'unsubscribing, same event not called twice');

//     o.jio.stop();
// });

Tristan Cavelier's avatar
Tristan Cavelier committed
316
module ( "Jio Dummy Storages" );
Tristan Cavelier's avatar
Tristan Cavelier committed
317

Tristan Cavelier's avatar
Tristan Cavelier committed
318 319
test ("All requests ok", function () {
    // Tests the request methods and the response with dummy storages
Tristan Cavelier's avatar
Tristan Cavelier committed
320

Tristan Cavelier's avatar
Tristan Cavelier committed
321
    var o = generateTools(this);
322

Tristan Cavelier's avatar
Tristan Cavelier committed
323
    // All Ok Dummy Storage
Tristan Cavelier's avatar
Tristan Cavelier committed
324 325 326 327 328 329 330
    o.jio = JIO.newJio({"type": "dummyallok"});

    // post empty document, some storage can create there own id (like couchdb
    // generates uuid). In this case, the dummy storage write an undefined id.
    o.spy(o, "value", {"ok": true, "id": undefined},
          "Post document with empty id");
    o.jio.post({}, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
331
    o.tick(o);
332

Tristan Cavelier's avatar
Tristan Cavelier committed
333 334 335
    // post non empty document
    o.spy(o, "value", {"ok": true, "id": "file"}, "Post non empty document");
    o.jio.post({"_id": "file", "title": "myFile"}, o.f);
336 337
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
338 339 340 341
    // put without id
    // error 20 -> document id required
    o.spy(o, "status", 20, "Put document with empty id");
    o.jio.put({}, o.f);
342 343
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
344 345 346 347
    // put non empty document
    o.spy(o, "value", {"ok": true, "id": "file"}, "Put non empty document");
    o.jio.put({"_id": "file", "title": "myFile"}, o.f);
    o.tick(o);
348

Tristan Cavelier's avatar
Tristan Cavelier committed
349 350 351 352 353 354 355 356 357
    // put an attachment without attachment id
    // error 22 -> attachment id required
    o.spy(o, "status", 22,
          "Put attachment without id");
    o.jio.putAttachment({
        "id": "file",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
358
    o.tick(o);
359

Tristan Cavelier's avatar
Tristan Cavelier committed
360 361 362 363 364 365 366 367
    // put an attachment
    o.spy(o, "value", {"ok": true, "id": "file/attmt"},
          "Put attachment");
    o.jio.putAttachment({
        "id": "file/attmt",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
368
    o.tick(o);
369

Tristan Cavelier's avatar
Tristan Cavelier committed
370 371 372 373 374 375 376 377
    // get document
    o.spy(o, "value", {"_id": "file", "title": "get_title"}, "Get document");
    o.jio.get("file", o.f);
    o.tick(o);

    // get attachment
    o.spy(o, "value", "0123456789", "Get attachment");
    o.jio.get("file/attmt", o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
378 379
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    // remove document
    o.spy(o, "value", {"ok": true, "id": "file"}, "Remove document");
    o.jio.remove({"_id": "file"}, o.f);
    o.tick(o);

    // remove attachment
    o.spy(o, "value", {"ok": true, "id": "file/attmt"}, "Remove attachment");
    o.jio.remove({"_id": "file/attmt"}, o.f);
    o.tick(o);

    // alldocs
    // error 405 -> Method not allowed
    o.spy(o, "status", 405, "AllDocs fail");
    o.jio.allDocs(o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
395 396

    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
});

test ("All requests fail", function () {
    // Tests the request methods and the err object with dummy storages

    var o = generateTools(this);

    // All Ok Dummy Storage
    o.jio = JIO.newJio({"type": "dummyallfail"});

    // post empty document
    // error 0 -> unknown
    o.spy(o, "status", 0, "Post document with empty id");
    o.jio.post({}, o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
412

Tristan Cavelier's avatar
Tristan Cavelier committed
413 414 415 416
    // test if the job still exists
    if (getLastJob(o.jio.getId()) !== undefined) {
        ok(false, "The job is not removed from the job queue");
    }
Tristan Cavelier's avatar
Tristan Cavelier committed
417

Tristan Cavelier's avatar
Tristan Cavelier committed
418 419 420
    // post non empty document
    o.spy(o, "status", 0, "Post non empty document");
    o.jio.post({"_id": "file", "title": "myFile"}, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
421
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
422 423 424 425 426

    // put without id
    // error 20 -> document id required
    o.spy(o, "status", 20, "Put document with empty id");
    o.jio.put({}, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
427
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
428 429 430 431

    // put non empty document
    o.spy(o, "status", 0, "Put non empty document");
    o.jio.put({"_id": "file", "title": "myFile"}, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
432
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

    // put an attachment without attachment id
    // error 22 -> attachment id required
    o.spy(o, "status", 22,
          "Put attachment without id");
    o.jio.putAttachment({
        "id": "file",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
    o.tick(o);

    // put an attachment
    o.spy(o, "status", 0,
          "Put attachment");
    o.jio.putAttachment({
        "id": "file/attmt",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
    o.tick(o);

    // get document
    o.spy(o, "status", 0, "Get document");
    o.jio.get("file", o.f);
    o.tick(o);

    // get attachment
    o.spy(o, "status", 0, "Get attachment");
    o.jio.get("file/attmt", o.f);
    o.tick(o);

    // remove document
    o.spy(o, "status", 0, "Remove document");
    o.jio.remove({"_id": "file"}, o.f);
    o.tick(o);

    // remove attachment
    o.spy(o, "status", 0, "Remove attachment");
    o.jio.remove({"_id": "file/attmt"}, o.f);
    o.tick(o);

    // alldocs
    // error 405 -> Method not allowed
    o.spy(o, "status", 405, "AllDocs fail");
Tristan Cavelier's avatar
Tristan Cavelier committed
478 479
    o.jio.allDocs(o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
480

Tristan Cavelier's avatar
Tristan Cavelier committed
481
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
482 483 484 485 486 487 488 489 490
});

test ("All document not found", function () {
    // Tests the request methods without document

    var o = generateTools(this);

    // All Ok Dummy Storage
    o.jio = JIO.newJio({"type": "dummyallnotfound"});
Tristan Cavelier's avatar
Tristan Cavelier committed
491

Tristan Cavelier's avatar
Tristan Cavelier committed
492 493 494
    // post document
    o.spy(o, "value", {"ok": true, "id": "file"}, "Post document");
    o.jio.post({"_id": "file", "title": "myFile"}, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
495
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
496 497 498 499

    // put document
    o.spy(o, "value", {"ok": true, "id": "file"}, "Put document");
    o.jio.put({"_id": "file", "title": "myFile"}, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
500
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
501 502 503 504 505 506 507 508 509 510

    // put an attachment without attachment id
    // error 22 -> attachment id required
    o.spy(o, "status", 22,
          "Put attachment without id");
    o.jio.putAttachment({
        "id": "file",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
511
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
512 513 514 515 516 517 518 519 520

    // put an attachment
    o.spy(o, "value", {"ok": true, "id": "file/attmt"},
          "Put attachment");
    o.jio.putAttachment({
        "id": "file/attmt",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
521
    o.tick(o);
522

Tristan Cavelier's avatar
Tristan Cavelier committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    // get document
    o.spy(o, "status", 404, "Get document");
    o.jio.get("file", o.f);
    o.tick(o);

    // get attachment
    o.spy(o, "status", 404, "Get attachment");
    o.jio.get("file/attmt", o.f);
    o.tick(o);

    // remove document
    o.spy(o, "status", 404, "Remove document");
    o.jio.remove({"_id": "file"}, o.f);
    o.tick(o);

    // remove attachment
    o.spy(o, "status", 404, "Remove attachment");
    o.jio.remove({"_id": "file/attmt"}, o.f);
    o.tick(o);

    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
544
});
Tristan Cavelier's avatar
Tristan Cavelier committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

test ("All document found", function () {
    // Tests the request methods with document

    var o = generateTools(this);

    // All Ok Dummy Storage
    o.jio = JIO.newJio({"type": "dummyallfound"});

    // post non empty document
    o.spy(o, "status", 409, "Post document");
    o.jio.post({"_id": "file", "title": "myFile"}, o.f);
    o.tick(o);

    // put non empty document
    o.spy(o, "value", {"ok": true, "id": "file"}, "Put non empty document");
    o.jio.put({"_id": "file", "title": "myFile"}, o.f);
    o.tick(o);

    // put an attachment without attachment id
    // error 22 -> attachment id required
    o.spy(o, "status", 22,
          "Put attachment without id");
    o.jio.putAttachment({
        "id": "file",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
    o.tick(o);

    // put an attachment
    o.spy(o, "value", {"ok": true, "id": "file/attmt"},
          "Put attachment");
    o.jio.putAttachment({
        "id": "file/attmt",
        "data": "0123456789",
        "mimetype": "text/plain"
    }, o.f);
    o.tick(o);

    // get document
    o.spy(o, "value", {"_id": "file", "title": "get_title"}, "Get document");
    o.jio.get("file", o.f);
    o.tick(o);

    // get attachment
    o.spy(o, "value", "0123456789", "Get attachment");
    o.jio.get("file/attmt", o.f);
    o.tick(o);

    // remove document
    o.spy(o, "value", {"ok": true, "id": "file"}, "Remove document");
    o.jio.remove({"_id": "file"}, o.f);
    o.tick(o);

    // remove attachment
    o.spy(o, "value", {"ok": true, "id": "file/attmt"}, "Remove attachment");
    o.jio.remove({"_id": "file/attmt"}, o.f);
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
605 606 607
    o.jio.stop();
});

Tristan Cavelier's avatar
Tristan Cavelier committed
608
module ( "Jio Job Managing" );
Tristan Cavelier's avatar
Tristan Cavelier committed
609

Tristan Cavelier's avatar
Tristan Cavelier committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623
test ("Several Jobs at the same time", function () {

    var o = generateTools(this);

    o.jio = JIO.newJio({"type":"dummyallok"});
    o.spy(o, "value", {"ok": true, "id": "file"}, "job1", "f");
    o.spy(o, "value", {"ok": true, "id": "file2"}, "job2", "f2");
    o.spy(o, "value", {"ok": true, "id": "file3"}, "job3", "f3");
    o.jio.put({"_id": "file",  "content": "content"}, o.f);
    o.jio.put({"_id": "file2", "content": "content2"}, o.f2);
    o.jio.put({"_id": "file3", "content": "content3"}, o.f3);
    o.tick(o, 1000, "f");
    o.tick(o, "f2");
    o.tick(o, "f3");
Tristan Cavelier's avatar
Tristan Cavelier committed
624 625
    o.jio.stop();

Tristan Cavelier's avatar
Tristan Cavelier committed
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
});

test ("Similar Jobs at the same time (Replace)", function () {

    var o = generateTools(this);

    o.jio = JIO.newJio({"type":"dummyallok"});
    o.spy(o, "status", 12, "job1 replaced", "f");
    o.spy(o, "status", 12, "job2 replaced", "f2");
    o.spy(o, "value", {"ok": true, "id": "file"}, "job3 ok", "f3");
    o.jio.put({"_id": "file", "content": "content"}, o.f);
    o.jio.put({"_id": "file", "content": "content"}, o.f2);
    o.jio.put({"_id": "file", "content": "content"}, o.f3);
    o.tick(o, 1000, "f");
    o.tick(o, "f2");
    o.tick(o, "f3");
Tristan Cavelier's avatar
Tristan Cavelier committed
642
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
643

Tristan Cavelier's avatar
Tristan Cavelier committed
644 645
});

Tristan Cavelier's avatar
Tristan Cavelier committed
646
test ("One document aim jobs at the same time (Wait for job(s))" , function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
647

Tristan Cavelier's avatar
Tristan Cavelier committed
648
    var o = generateTools(this);
Tristan Cavelier's avatar
Tristan Cavelier committed
649

Tristan Cavelier's avatar
Tristan Cavelier committed
650 651 652 653
    o.jio = JIO.newJio({"type":"dummyallok"});
    o.spy(o, "value", {"ok": true, "id": "file"}, "job1", "f");
    o.spy(o, "value", {"ok": true, "id": "file"}, "job2", "f2");
    o.spy(o, "value", {"_id": "file", "title": "get_title"}, "job3", "f3");
Tristan Cavelier's avatar
Tristan Cavelier committed
654

Tristan Cavelier's avatar
Tristan Cavelier committed
655 656
    o.jio.post({"_id": "file", "content": "content"}, o.f);
    o.testLastJobWaitForJob(undefined, "job1 is not waiting for someone");
Tristan Cavelier's avatar
Tristan Cavelier committed
657

Tristan Cavelier's avatar
Tristan Cavelier committed
658 659
    o.jio.put({"_id": "file", "content": "content"}, o.f2);
    o.testLastJobWaitForJob([1], "job2 is waiting");
Tristan Cavelier's avatar
Tristan Cavelier committed
660

Tristan Cavelier's avatar
Tristan Cavelier committed
661 662
    o.jio.get("file", o.f3);
    o.testLastJobWaitForJob([1, 2], "job3 is waiting");
Tristan Cavelier's avatar
Tristan Cavelier committed
663

Tristan Cavelier's avatar
Tristan Cavelier committed
664 665 666
    o.tick(o, 1000, "f");
    o.tick(o, "f2");
    o.tick(o, "f3");
Tristan Cavelier's avatar
Tristan Cavelier committed
667
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
668

Tristan Cavelier's avatar
Tristan Cavelier committed
669 670
});

Tristan Cavelier's avatar
Tristan Cavelier committed
671
test ("One document aim jobs at the same time (Elimination)" , function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
672

Tristan Cavelier's avatar
Tristan Cavelier committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686
    var o = generateTools(this);

    o.jio = JIO.newJio({"type":"dummyallok"});
    o.spy(o, "status", 10, "job1 stopped", "f");
    o.spy(o, "value", {"ok": true, "id": "file"}, "job2", "f2");

    o.jio.post({"_id": "file", "content": "content"}, o.f);
    o.testLastJobLabel("post", "job1 exists");

    o.jio.remove({"_id": "file"}, o.f2);
    o.testLastJobLabel("remove", "job1 does not exist anymore");

    o.tick(o, 1000, "f");
    o.tick(o, "f2");
Tristan Cavelier's avatar
Tristan Cavelier committed
687
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
688

Tristan Cavelier's avatar
Tristan Cavelier committed
689 690
});

Tristan Cavelier's avatar
Tristan Cavelier committed
691
test ("One document aim jobs at the same time (Not Acceptable)" , function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
692

Tristan Cavelier's avatar
Tristan Cavelier committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
    var o = generateTools(this);

    o.jio = JIO.newJio({"type":"dummyallok"});
    o.spy(o, "value", {"_id": "file", "title": "get_title"}, "job1", "f");
    o.spy(o, "status", 11, "job2 is not acceptable", "f2");

    o.jio.get("file", o.f);
    o.testLastJobId(1, "job1 added to queue");
    o.waitUntilLastJobIs("on going");

    o.jio.get("file", o.f2);
    o.testLastJobId(1, "job2 not added");

    o.tick(o, 1000, "f");
    o.tick(o, "f2");
Tristan Cavelier's avatar
Tristan Cavelier committed
708
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
709

Tristan Cavelier's avatar
Tristan Cavelier committed
710 711
});

Tristan Cavelier's avatar
Tristan Cavelier committed
712
test ("Server will be available soon (Wait for time)" , function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
713

Tristan Cavelier's avatar
Tristan Cavelier committed
714 715
    var o = generateTools(this);
    o.max_retry = 3;
Tristan Cavelier's avatar
Tristan Cavelier committed
716

Tristan Cavelier's avatar
Tristan Cavelier committed
717 718
    o.jio = JIO.newJio({"type":"dummyall3tries"});
    o.spy(o, "value", {"ok": true, "id": "file"}, "job1", "f");
719

Tristan Cavelier's avatar
Tristan Cavelier committed
720 721 722 723 724 725 726
    o.jio.put({"_id": "file", "content": "content"},
              {"max_retry": o.max_retry}, o.f);
    for (o.i = 0; o.i < o.max_retry - 1; o.i += 1) {
        o.waitUntilLastJobIs("on going");
        o.waitUntilLastJobIs("wait");
        o.testLastJobWaitForTime("job1 is waiting for time");
    }
727

Tristan Cavelier's avatar
Tristan Cavelier committed
728 729
    o.tick(o, 1000, "f");
    o.jio.stop();
730

Tristan Cavelier's avatar
Tristan Cavelier committed
731 732 733 734 735 736 737 738 739 740
});

module ( "Jio Restore");

test ("Restore old Jio", function() {

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "dummyall3tries",
741
        "application_name": "jiotests"
Sven Franck's avatar
Sven Franck committed
742
    });
Tristan Cavelier's avatar
Tristan Cavelier committed
743 744 745 746

    o.jio_id = o.jio.getId();

    o.jio.put({"_id": "file", "title": "myFile"}, {"max_retry":3}, o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
747 748
    o.waitUntilLastJobIs("initial"); // "on going" or "wait" should work
    // xxx also test with o.waitUntilLastJobIs("on going") ?
Tristan Cavelier's avatar
Tristan Cavelier committed
749 750 751 752
    o.jio.close();

    o.jio = JIO.newJio({
        "type": "dummyallok",
753
        "application_name": "jiotests"
Sven Franck's avatar
Sven Franck committed
754
    });
Tristan Cavelier's avatar
Tristan Cavelier committed
755 756 757 758 759 760
    o.waitUntilAJobExists(30000); // timeout 30 sec
    o.testLastJobLabel("put", "Job restored");
    o.clock.tick(1000);
    ok(getLastJob(o.jio.getId()) === undefined,
       "Job executed");

761
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
762

763
});
Tristan Cavelier's avatar
Tristan Cavelier committed
764

Tristan Cavelier's avatar
Tristan Cavelier committed
765
module ( "Jio LocalStorage" );
766

Tristan Cavelier's avatar
Tristan Cavelier committed
767
test ("Post", function(){
768

Tristan Cavelier's avatar
Tristan Cavelier committed
769 770 771 772 773
    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "local",
        "username": "upost",
774
        "application_name": "apost"
Sven Franck's avatar
Sven Franck committed
775
    });
Tristan Cavelier's avatar
Tristan Cavelier committed
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811

    // post without id
    o.spy (o, "status", 405, "Post without id");
    o.jio.post({}, o.f);
    o.tick(o);

    // post non empty document
    o.spy (o, "value", {"ok": true, "id": "post1"}, "Post");
    o.jio.post({"_id": "post1", "title": "myPost1"}, o.f);
    o.tick(o);

    deepEqual(
        localstorage.getItem("jio/localstorage/upost/apost/post1"),
        {
            "_id": "post1",
            "title": "myPost1"
        },
        "Check document"
    );

    // post but document already exists
    o.spy (o, "status", 409, "Post but document already exists");
    o.jio.post({"_id": "post1", "title": "myPost2"}, o.f);
    o.tick(o);

    o.jio.stop();
});


test ("Put", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "local",
        "username": "uput",
812
        "application_name": "aput"
Sven Franck's avatar
Sven Franck committed
813
    });
814

Tristan Cavelier's avatar
Tristan Cavelier committed
815
    // put without id
816
    // error 20 -> document id required
Tristan Cavelier's avatar
Tristan Cavelier committed
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
    o.spy (o, "status", 20, "Put without id");
    o.jio.put({}, o.f);
    o.tick(o);

    // put non empty document
    o.spy (o, "value", {"ok": true, "id": "put1"}, "Creates a document");
    o.jio.put({"_id": "put1", "title": "myPut1"}, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem("jio/localstorage/uput/aput/put1"),
        {
            "_id": "put1",
            "title": "myPut1"
832
        },
Tristan Cavelier's avatar
Tristan Cavelier committed
833 834 835 836 837 838 839 840 841 842 843 844 845 846
        "Check document"
    );

    // put but document already exists
    o.spy (o, "value", {"ok": true, "id": "put1"}, "Update the document");
    o.jio.put({"_id": "put1", "title": "myPut2"}, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem("jio/localstorage/uput/aput/put1"),
        {
            "_id": "put1",
            "title": "myPut2"
847
        },
Tristan Cavelier's avatar
Tristan Cavelier committed
848 849 850
        "Check document"
    );

Sven Franck's avatar
Sven Franck committed
851
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
852

Tristan Cavelier's avatar
Tristan Cavelier committed
853
});
854

Tristan Cavelier's avatar
Tristan Cavelier committed
855
test ("PutAttachment", function(){
Tristan Cavelier's avatar
Tristan Cavelier committed
856

Tristan Cavelier's avatar
Tristan Cavelier committed
857
    var o = generateTools(this);
Sven Franck's avatar
Sven Franck committed
858

Tristan Cavelier's avatar
Tristan Cavelier committed
859 860 861
    o.jio = JIO.newJio({
        "type": "local",
        "username": "uputattmt",
862
        "application_name": "aputattmt"
Sven Franck's avatar
Sven Franck committed
863
    });
Tristan Cavelier's avatar
Tristan Cavelier committed
864 865 866 867 868 869 870

    // putAttachment without doc id
    // error 20 -> document id required
    o.spy(o, "status", 20, "PutAttachment without doc id");
    o.jio.putAttachment({}, o.f);
    o.tick(o);

Sebastien Robin's avatar
Sebastien Robin committed
871
    // putAttachment without attachment id
Tristan Cavelier's avatar
Tristan Cavelier committed
872
    // error 22 -> attachment id required
Sebastien Robin's avatar
Sebastien Robin committed
873
    o.spy(o, "status", 22, "PutAttachment without attachment id");
Tristan Cavelier's avatar
Tristan Cavelier committed
874 875 876 877 878 879 880 881 882 883 884 885 886
    o.jio.putAttachment({"id": "putattmt1"}, o.f);
    o.tick(o);

    // putAttachment without document
    // error 404 -> not found
    o.spy(o, "status", 404, "PutAttachment without document");
    o.jio.putAttachment({"id": "putattmt1/putattmt2"}, o.f);
    o.tick(o);

    // adding a document
    localstorage.setItem("jio/localstorage/uputattmt/aputattmt/putattmt1", {
        "_id": "putattmt1",
        "title": "myPutAttmt1"
Sven Franck's avatar
Sven Franck committed
887
    });
Tristan Cavelier's avatar
Tristan Cavelier committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949

    // putAttachment with document
    o.spy(o, "value", {"ok": true, "id": "putattmt1/putattmt2"},
          "PutAttachment with document, without data");
    o.jio.putAttachment({"id": "putattmt1/putattmt2"}, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem("jio/localstorage/uputattmt/aputattmt/putattmt1"),
        {
            "_id": "putattmt1",
            "title": "myPutAttmt1",
            "_attachments": {
                "putattmt2": {
                    "length": 0,
                    // md5("")
                    "digest": "md5-d41d8cd98f00b204e9800998ecf8427e"
                }
            }
        },
        "Check document"
    );

    // check attachment
    deepEqual(
        localstorage.getItem(
            "jio/localstorage/uputattmt/aputattmt/putattmt1/putattmt2"),
        "", "Check attachment"
    );

    // update attachment
    o.spy(o, "value", {"ok": true, "id": "putattmt1/putattmt2"},
          "Update Attachment, with data");
    o.jio.putAttachment({"id": "putattmt1/putattmt2", "data": "abc"}, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem("jio/localstorage/uputattmt/aputattmt/putattmt1"),
        {
            "_id": "putattmt1",
            "title": "myPutAttmt1",
            "_attachments": {
                "putattmt2": {
                    "length": 3,
                    // md5("abc")
                    "digest": "md5-900150983cd24fb0d6963f7d28e17f72"
                }
            }
        },
        "Check document"
    );

    // check attachment
    deepEqual(
        localstorage.getItem(
            "jio/localstorage/uputattmt/aputattmt/putattmt1/putattmt2"),
        "abc", "Check attachment"
    );

    o.jio.stop();
Sven Franck's avatar
Sven Franck committed
950
});
951

Tristan Cavelier's avatar
Tristan Cavelier committed
952
test ("Get", function(){
Tristan Cavelier's avatar
Tristan Cavelier committed
953

Tristan Cavelier's avatar
Tristan Cavelier committed
954
    var o = generateTools(this);
Tristan Cavelier's avatar
Tristan Cavelier committed
955

Tristan Cavelier's avatar
Tristan Cavelier committed
956 957 958
    o.jio = JIO.newJio({
        "type": "local",
        "username": "uget",
959
        "application_name": "aget"
Tristan Cavelier's avatar
Tristan Cavelier committed
960 961
    });

962 963
    // get inexistent document
    o.spy(o, "status", 404, "Get inexistent document");
Tristan Cavelier's avatar
Tristan Cavelier committed
964 965 966
    o.jio.get("get1", o.f);
    o.tick(o);

967 968
    // get inexistent attachment
    o.spy(o, "status", 404, "Get inexistent attachment");
Tristan Cavelier's avatar
Tristan Cavelier committed
969 970 971 972 973 974 975 976 977 978 979 980 981 982
    o.jio.get("get1/get2", o.f);
    o.tick(o);

    // adding a document
    o.doc_get1 = {
        "_id": "get1",
        "title": "myGet1"
    };
    localstorage.setItem("jio/localstorage/uget/aget/get1", o.doc_get1);

    // get document
    o.spy(o, "value", o.doc_get1, "Get document");
    o.jio.get("get1", o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
983

984 985
    // get inexistent attachment (document exists)
    o.spy(o, "status", 404, "Get inexistent attachment (document exists)");
Tristan Cavelier's avatar
Tristan Cavelier committed
986
    o.jio.get("get1/get2", o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
987 988
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    // adding an attachment
    o.doc_get1["_attachments"] = {
        "get2": {
            "length": 2,
            // md5("de")
            "digest": "md5-5f02f0889301fd7be1ac972c11bf3e7d"
        }
    };
    localstorage.setItem("jio/localstorage/uget/aget/get1", o.doc_get1);
    localstorage.setItem("jio/localstorage/uget/aget/get1/get2", "de");

    // get attachment
    o.spy(o, "value", "de", "Get attachment");
    o.jio.get("get1/get2", o.f);
Tristan Cavelier's avatar
Tristan Cavelier committed
1003 1004 1005
    o.tick(o);

    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
1006

Tristan Cavelier's avatar
Tristan Cavelier committed
1007 1008
});

Tristan Cavelier's avatar
Tristan Cavelier committed
1009 1010 1011 1012 1013 1014 1015
test ("Remove", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "local",
        "username": "uremove",
1016
        "application_name": "aremove"
Tristan Cavelier's avatar
Tristan Cavelier committed
1017 1018
    });

1019 1020
    // remove inexistent document
    o.spy(o, "status", 404, "Remove inexistent document");
Tristan Cavelier's avatar
Tristan Cavelier committed
1021 1022 1023
    o.jio.remove({"_id": "remove1"}, o.f);
    o.tick(o);

1024 1025
    // remove inexistent document/attachment
    o.spy(o, "status", 404, "Remove inexistent document/attachment");
Tristan Cavelier's avatar
Tristan Cavelier committed
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    o.jio.remove({"_id": "remove1/remove2"}, o.f);
    o.tick(o);

    // adding a document
    localstorage.setItem("jio/localstorage/uremove/aremove/remove1", {
        "_id": "remove1",
        "title": "myRemove1"
    });

    // remove document
    o.spy(o, "value", {"ok": true, "id": "remove1"}, "Remove document");
    o.jio.remove({"_id": "remove1"}, o.f);
    o.tick(o);

    // check document
    ok(localstorage.getItem("jio/localstorage/uremove/aremove/remove1")===null,
Sebastien Robin's avatar
Sebastien Robin committed
1042
       "Check document is removed");
Tristan Cavelier's avatar
Tristan Cavelier committed
1043 1044 1045 1046 1047 1048 1049 1050 1051

    // adding a document + attmt
    localstorage.setItem("jio/localstorage/uremove/aremove/remove1", {
        "_id": "remove1",
        "title": "myRemove1",
        "_attachments": {
            "remove2": {
                "length": 4,
                "digest": "md5-blahblah"
Tristan Cavelier's avatar
Tristan Cavelier committed
1052 1053
            }
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
1054 1055 1056 1057 1058
    });
    localstorage.setItem(
        "jio/localstorage/uremove/aremove/remove1/remove2", "fghi");

    // remove attachment
1059
    o.spy(o, "value", {"ok": true, "id": "remove1"}, "Remove document and attachment");
Tristan Cavelier's avatar
Tristan Cavelier committed
1060 1061
    o.jio.remove({"_id": "remove1"}, o.f);
    o.tick(o);
1062 1063 1064 1065
    ok(localstorage.getItem("jio/localstorage/uremove/aremove/remove1"
       )===null, "Check document is removed");
    ok(localstorage.getItem("jio/localstorage/uremove/aremove/remove1/remove2"
      )===null, "Check attachment is removed");
Tristan Cavelier's avatar
Tristan Cavelier committed
1066 1067

    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
1068

Tristan Cavelier's avatar
Tristan Cavelier committed
1069 1070 1071
});


Tristan Cavelier's avatar
Tristan Cavelier committed
1072 1073
test ("AllDocs", function(){

1074
    var o = generateTools(this), i, m = 15;
Tristan Cavelier's avatar
Tristan Cavelier committed
1075 1076 1077 1078

    o.jio = JIO.newJio({
        "type": "local",
        "username": "ualldocs",
1079
        "application_name": "aalldocs"
Tristan Cavelier's avatar
Tristan Cavelier committed
1080
    });
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    o.localpath = "jio/localstorage/ualldocs/aalldocs";

    // sample data
    o.titles = ["Shawshank Redemption", "Godfather", "Godfather 2",
      "Pulp Fiction", "The Good, The Bad and The Ugly", "12 Angry Men",
      "The Dark Knight", "Schindlers List",
      "Lord of the Rings - Return of the King", "Fight Club",
      "Star Wars Episode V", "Lord Of the Rings - Fellowship of the Ring",
      "One flew over the Cuckoo's Nest", "Inception", "Godfellas"
    ];
    o.years = [1994,1972,1974,1994,1966,1957,2008,1993,2003,1999,1980,2001,
      1975,2010,1990
    ];
    o.director = ["Frank Darabont", "Francis Ford Coppola",
      "Francis Ford Coppola", "Quentin Tarantino", "Sergio Leone",
      "Sidney Lumet", "Christopher Nolan", "Steven Spielberg",
      "Peter Jackson", "David Fincher", "Irvin Kershner", "Peter Jackson",
      "Milos Forman", "Christopher Nolan", " Martin Scorsese"
    ]
    // set documents
    for (i = 0; i < m; i += 1) {
      o.fakeDoc = {};
      o.fakeDoc._id = "doc_"+i;
      o.fakeDoc.title = o.titles[i];
      o.fakeDoc.year = o.years[i];
      o.fakeDoc.author = o.director[i];
      localstorage.setItem(o.localpath+"/doc_"+i, o.fakeDoc);
    }
Tristan Cavelier's avatar
Tristan Cavelier committed
1109

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    // response
    o.allDocsResponse = {};
    o.allDocsResponse.rows = [];
    o.allDocsResponse.total_rows = 15;
    for (i = 0; i < m; i += 1) {
      o.allDocsResponse.rows.push({
        "id": "doc_"+i,
        "key": "doc_"+i,
        "value": {}
      });
    };
Tristan Cavelier's avatar
Tristan Cavelier committed
1121
    // alldocs
1122
    o.spy(o, "value", o.allDocsResponse, "All docs");
Tristan Cavelier's avatar
Tristan Cavelier committed
1123 1124
    o.jio.allDocs(o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    // include docs
    o.allDocsResponse = {};
    o.allDocsResponse.rows = [];
    o.allDocsResponse.total_rows = 15;
    for (i = 0; i < m; i += 1) {
      o.allDocsResponse.rows.push({
        "id": "doc_"+i,
        "key": "doc_"+i,
        "value": {},
        "doc": localstorage.getItem(o.localpath+"/doc_"+i)
      });
    };

    // alldocs
    o.spy(o, "value", o.allDocsResponse, "All docs (include docs)");
    o.jio.allDocs({"include_docs":true}, o.f);
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
1144
    o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
1145

Tristan Cavelier's avatar
Tristan Cavelier committed
1146
});
Tristan Cavelier's avatar
Tristan Cavelier committed
1147

1148 1149 1150 1151 1152 1153 1154 1155
module ( "Jio Revision Storage + Local Storage" );

test ("Post", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1156
        "sub_storage": {
1157 1158
            "type": "local",
            "username": "urevpost",
1159
            "application_name": "arevpost"
1160 1161
        }
    });
1162
    o.localpath = "jio/localstorage/urevpost/arevpost";
1163 1164

    // post without id
1165
    o.revisions = {"start": 0, "ids": []};
1166 1167 1168
    o.spy (o, "status", undefined, "Post without id");
    o.jio.post({}, function (err, response) {
        o.f.apply(arguments);
1169 1170 1171
        o.uuid = (err || response).id;
        ok(isUuid(o.uuid), "Uuid should look like " +
           "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx : " + o.uuid);
1172 1173
    });
    o.tick(o);
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    o.rev = "1-"+generateRevisionHash({"_id": o.uuid}, o.revisions);

    // check document
    deepEqual(
        localstorage.getItem(o.localpath + "/" + o.uuid + "." + o.rev),
        {"_id": o.uuid + "." + o.rev},
        "Check document"
    );

    // check document tree
    o.doc_tree = {
        "_id": o.uuid + ".revision_tree.json",
        "children": [{
            "rev": o.rev, "status": "available", "children": []
        }]
    };
    deepEqual(
        localstorage.getItem(
            o.localpath + "/" + o.uuid + ".revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
    );
1197 1198 1199

    // post non empty document
    o.doc = {"_id": "post1", "title": "myPost1"};
1200
    o.rev = "1-"+generateRevisionHash(o.doc, o.revisions);
1201 1202 1203 1204 1205 1206 1207
    o.spy (o, "value", {"ok": true, "id": "post1", "rev": o.rev}, "Post");
    o.jio.post(o.doc, o.f);
    o.tick(o);

    // check document
    o.doc["_id"] = "post1."+o.rev;
    deepEqual(
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        localstorage.getItem(o.localpath + "/post1." + o.rev),
        o.doc,
        "Check document"
    );

    // check document tree
    o.doc_tree._id = "post1.revision_tree.json";
    o.doc_tree.children[0] = {
        "rev": o.rev, "status": "available", "children": []
    };
    deepEqual(
        localstorage.getItem(
            o.localpath + "/post1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
1224 1225 1226 1227
    );

    // post and document already exists
    o.doc = {"_id": "post1", "title": "myPost2"};
1228
    o.rev = "1-"+generateRevisionHash(o.doc, o.revisions);
1229 1230 1231 1232 1233 1234
    o.spy (o, "value", {
        "ok": true, "id": "post1", "rev": o.rev
    }, "Post and document already exists");
    o.jio.post(o.doc, o.f);
    o.tick(o);

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    // check document
    o.doc["_id"] = "post1."+o.rev;
    deepEqual(
        localstorage.getItem(o.localpath + "/post1." + o.rev),
        o.doc,
        "Check document"
    );

    // check document tree
    o.doc_tree._id = "post1.revision_tree.json";
    o.doc_tree.children.unshift({
        "rev": o.rev, "status": "available", "children": []
    });
    deepEqual(
        localstorage.getItem(
            o.localpath + "/post1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
    );

1256 1257
    // post + revision
    o.doc = {"_id": "post1", "_rev": o.rev, "title": "myPost2"};
1258 1259
    o.revisions = {"start": 1, "ids": [o.rev.split('-')[1]]};
    o.rev = "2-"+generateRevisionHash(o.doc, o.revisions);
1260 1261 1262 1263 1264 1265 1266 1267 1268
    o.spy (o, "status", undefined, "Post + revision");
    o.jio.post(o.doc, o.f);
    o.tick(o);

    // // keep_revision_history
    // ok (false, "keep_revision_history Option Not Implemented");

    // check document
    o.doc["_id"] = "post1."+o.rev;
1269
    delete o.doc._rev;
1270
    deepEqual(
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
        localstorage.getItem(o.localpath + "/post1." + o.rev),
        o.doc,
        "Check document"
    );

    // check document tree
    o.doc_tree._id = "post1.revision_tree.json";
    o.doc_tree.children[0].children.unshift({
        "rev": o.rev, "status": "available", "children": []
    });
    deepEqual(
        localstorage.getItem(
            o.localpath + "/post1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
1287 1288 1289 1290 1291 1292
    );

    o.jio.stop();

});

1293 1294 1295 1296 1297 1298
test ("Put", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1299
        "sub_storage": {
1300 1301
            "type": "local",
            "username": "urevput",
1302
            "application_name": "arevput"
1303 1304
        }
    });
1305
    o.localpath = "jio/localstorage/urevput/arevput";
1306 1307 1308 1309 1310 1311 1312 1313 1314

    // put without id
    // error 20 -> document id required
    o.spy (o, "status", 20, "Put without id");
    o.jio.put({}, o.f);
    o.tick(o);

    // put non empty document
    o.doc = {"_id": "put1", "title": "myPut1"};
1315 1316
    o.revisions = {"start": 0, "ids": []};
    o.rev = "1-"+generateRevisionHash(o.doc, o.revisions);
1317 1318 1319 1320 1321 1322
    o.spy (o, "value", {"ok": true, "id": "put1", "rev": o.rev},
           "Creates a document");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check document
1323
    o.doc._id = "put1." + o.rev;
1324
    deepEqual(
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
        localstorage.getItem(o.localpath + "/put1." + o.rev),
        o.doc,
        "Check document"
    );

    // check document tree
    o.doc_tree = {
        "_id": "put1.revision_tree.json",
        "children": [{
            "rev": o.rev, "status": "available", "children": []
        }]
    };
    deepEqual(
        localstorage.getItem(
            o.localpath + "/put1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
1343 1344
    );

1345 1346 1347 1348 1349 1350
    // put without rev and document already exists
    o.doc = {"_id": "put1", "title": "myPut2"};
    o.rev = "1-"+generateRevisionHash(o.doc, o.revisions);
    o.spy (o, "value", {"ok": true, "id": "put1", "rev": o.rev},
           "Put same document without revision");
    o.jio.put(o.doc, o.f);
1351 1352
    o.tick(o);

1353 1354 1355
    o.doc_tree.children.unshift({
        "rev": o.rev, "status": "available", "children": []
    });
1356 1357

    // put + revision
1358
    o.doc = {"_id": "put1", "_rev": o.rev, "title": "myPut2"};
1359 1360
    o.revisions = {"start": 1, "ids": [o.rev.split('-')[1]]};
    o.rev = "2-"+generateRevisionHash(o.doc, o.revisions);
1361 1362
    o.spy (o, "value", {"id": "put1", "ok": true, "rev": o.rev},
           "Put + revision");
1363 1364 1365 1366
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check document
1367
    o.doc._id = "put1." + o.rev;
1368
    delete o.doc._rev;
1369
    deepEqual(
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
        localstorage.getItem(o.localpath + "/put1." + o.rev),
        o.doc,
        "Check document"
    );

    // check document tree
    o.doc_tree.children[0].children.unshift({
        "rev": o.rev, "status": "available", "children": []
    });
    deepEqual(
        localstorage.getItem(
            o.localpath + "/put1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    );

    // put + wrong revision
    o.doc = {"_id": "put1", "_rev": "3-wr3", "title": "myPut3"};
    o.revisions = {"start": 3, "ids": ["wr3"]};
    o.rev = "4-"+generateRevisionHash(o.doc, o.revisions);
    o.spy (o, "value", {"id": "put1", "ok": true, "rev": o.rev},
           "Put + wrong revision");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check document
    o.doc._id = "put1." + o.rev;
    delete o.doc._rev;
    deepEqual(
        localstorage.getItem(o.localpath + "/put1." + o.rev),
        o.doc,
        "Check document"
    );

    // check document tree
    o.doc_tree.children.unshift({
      "rev": "3-wr3",
      "status": "missing",
      "children": [{
        "rev": o.rev,
        "status": "available",
        "children": []
      }]
    });
    deepEqual(
        localstorage.getItem(
            o.localpath + "/put1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
1421 1422 1423 1424 1425
    );

    // put + revision history
    o.doc = {
      "_id": "put1",
1426 1427
      //"_revs": ["3-rh3", "2-rh2", "1-rh1"], // same as below
      "_revs": {"start": 3, "ids": ["rh3", "rh2", "rh1"]},
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
      "title": "myPut3"
    };
    o.spy (o, "value", {"id": "put1", "ok": true, "rev": "3-rh3"},
           "Put + revision history");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check document
    o.doc._id = "put1.3-rh3";
    delete o.doc._revs;
    deepEqual(
        localstorage.getItem(o.localpath + "/put1.3-rh3"),
        o.doc,
        "Check document"
    );

    // check document tree
    o.doc_tree.children.unshift({
      "rev": "1-rh1",
      "status": "missing",
      "children": [{
        "rev": "2-rh2",
        "status": "missing",
        "children": [{
          "rev": "3-rh3",
          "status": "available",
          "children": []
        }]
      }]
    });
    deepEqual(
        localstorage.getItem(
            o.localpath + "/put1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
1464 1465
    );

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
    // add attachment
    o.doc._attachments = {
      "att1": {
        "length": 1,
        "content_type": "text/plain",
        "digest": "md5-0cc175b9c0f1b6a831c399e269772661"
      },
      "att2": {
        "length": 2,
        "content_type": "dont/care",
        "digest": "md5-5360af35bde9ebd8f01f492dc059593c"
      }
    };
    localstorage.setItem(o.localpath + "/put1.3-rh3", o.doc);
    localstorage.setItem(o.localpath + "/put1.3-rh3/att1", "a");
    localstorage.setItem(o.localpath + "/put1.3-rh3/att2", "bc");

    // put + revision with attachment
    o.attachments = o.doc._attachments;
    o.doc = {"_id": "put1", "_rev": "3-rh3", "title": "myPut4"};
    o.revisions = {"start": 3, "ids": ["rh3","rh2","rh1"]};
    o.rev = "4-"+generateRevisionHash(o.doc, o.revisions);
    o.spy (o, "value", {"id": "put1", "ok": true, "rev": o.rev},
           "Put + revision (document contains attachments)");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check document
    o.doc._id = "put1." + o.rev;
    o.doc._attachments = o.attachments;
    delete o.doc._rev;
    deepEqual(
        localstorage.getItem(o.localpath + "/put1." + o.rev),
        o.doc,
        "Check document"
    );

    // check attachments
    deepEqual(
        localstorage.getItem(o.localpath + "/put1." + o.rev + "/att1"),
        "a",
        "Check Attachment"
    );
    deepEqual(
        localstorage.getItem(o.localpath + "/put1." + o.rev + "/att2"),
        "bc",
        "Check Attachment"
    );

    // check document tree
    o.doc_tree.children[0].children[0].children[0].children.unshift({
        "rev": o.rev, "status": "available", "children": []
    });
    deepEqual(
        localstorage.getItem(
            o.localpath + "/put1.revision_tree.json"
        ),
        o.doc_tree,
        "Check document tree"
    );

1527 1528 1529 1530
    o.jio.stop();

});

1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
test("Put Attachment", function () {

    var o = generateTools(this);

    o.jio = JIO.newJio({
      "type": "revision",
      "sub_storage": {
        "type": "local",
        "username": "urevputattmt",
        "application_name": "arevputattmt"
      }
    });

    // putAttachment without doc id
    // error 20 -> document id required
    o.spy(o, "status", 20, "PutAttachment without doc id");
    o.jio.putAttachment({}, o.f);
    o.tick(o);

    // putAttachment without attachment id
    // erorr 22 -> attachment id required
    o.spy(o, "status", 22, "PutAttachment without attachment id");
    o.jio.putAttachment({"id": "putattmt1"}, o.f);
    o.tick(o);

    // putAttachment without document
    o.revisions = {"start": 0, "ids": []}
    o.rev_hash = generateRevisionHash({"_id": "doc1/attmt1"},
                                      o.revisions);
    o.rev = "1-" + o.rev_hash;
    o.spy(o, "value", {"ok": true, "id": "doc1/attmt1", "rev": o.rev},
          "PutAttachment without document, without data");
    o.jio.putAttachment({"id": "doc1/attmt1"}, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem(
          "jio/localstorage/urevputattmt/arevputattmt/doc1." + o.rev
        ),
        {
            "_id": "doc1." + o.rev,
            "_attachments": {
                "attmt1": {
                    "length": 0,
                    // md5("")
                    "digest": "md5-d41d8cd98f00b204e9800998ecf8427e"
                }
            }
        },
        "Check document"
    );

    // check attachment
    deepEqual(
        localstorage.getItem(
            "jio/localstorage/urevputattmt/arevputattmt/doc1." + o.rev
            + "/attmt1"
        ),
        "", "Check attachment"
    );

    // update attachment
    o.prev_rev = o.rev;
    o.revisions = {"start": 1, "ids": [o.rev_hash]}
    o.rev_hash = generateRevisionHash({
      "_id": "doc1/attmt1",
      "_data": "abc",
      "_rev": o.prev_rev
    }, o.revisions);
    o.rev = "2-" + o.rev_hash;
    o.spy(o, "value", {"ok": true, "id": "doc1/attmt1", "rev": o.rev},
          "Update Attachment, with data");
    o.jio.putAttachment({
      "id": "doc1/attmt1",
      "data": "abc",
      "rev": o.prev_rev
    }, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem(
          "jio/localstorage/urevputattmt/arevputattmt/doc1." + o.rev
        ),
        {
            "_id": "doc1." + o.rev,
            "_attachments": {
                "attmt1": {
                    "length": 3,
                    // md5("abc")
                    "digest": "md5-900150983cd24fb0d6963f7d28e17f72"
                }
            }
        },
        "Check document"
    );

    // check attachment
    deepEqual(
        localstorage.getItem(
            "jio/localstorage/urevputattmt/arevputattmt/doc1." + o.rev +
            "/attmt1"
        ),
        "abc", "Check attachment"
    );

    // putAttachment new attachment
    o.prev_rev = o.rev;
    o.revisions = {"start": 2, "ids": [o.rev_hash, o.revisions.ids[0]]}
    o.rev_hash = generateRevisionHash({
      "_id": "doc1/attmt2",
      "_data": "def",
      "_rev": o.prev_rev
    }, o.revisions);
    o.rev = "3-" + o.rev_hash;
    o.spy(o, "value", {"ok": true, "id": "doc1/attmt2", "rev": o.rev},
          "PutAttachment without document, without data");
    o.jio.putAttachment({
      "id": "doc1/attmt2",
      "data": "def",
      "rev": o.prev_rev
    }, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem(
          "jio/localstorage/urevputattmt/arevputattmt/doc1." + o.rev
        ),
        {
            "_id": "doc1." + o.rev,
            "_attachments": {
                "attmt1": {
                    "length": 3,
                    "digest": "md5-900150983cd24fb0d6963f7d28e17f72"
                },
                "attmt2": {
                    "length": 3,
                    // md5("def")
                    "digest": "md5-4ed9407630eb1000c0f6b63842defa7d"
                }
            }
        },
        "Check document"
    );

    // check attachment
    deepEqual(
        localstorage.getItem(
            "jio/localstorage/urevputattmt/arevputattmt/doc1." + o.rev +
            "/attmt2"
        ),
        "def", "Check attachment"
    );

    o.jio.stop();

});

1691 1692 1693 1694 1695 1696
test ("Get", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1697
        "sub_storage": {
1698 1699
            "type": "local",
            "username": "urevget",
1700
            "application_name": "arevget"
1701 1702 1703 1704
        }
    });
    o.localpath = "jio/localstorage/urevget/arevget";

1705 1706
    // get inexistent document
    o.spy(o, "status", 404, "Get inexistent document (winner)");
1707 1708 1709
    o.jio.get("get1", o.f);
    o.tick(o);

1710 1711
    // get inexistent attachment
    o.spy(o, "status", 404, "Get inexistent attachment (winner)");
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    o.jio.get("get1/get2", o.f);
    o.tick(o);

    // adding a document
    o.doctree = {"children":[{
        "rev": "1-rev1", "status": "available", "children": []
    }]};
    o.doc_myget1 = {"_id": "get1", "title": "myGet1"};
    localstorage.setItem(o.localpath+"/get1.revision_tree.json", o.doctree);
    localstorage.setItem(o.localpath+"/get1.1-rev1", o.doc_myget1);

    // get document
1724 1725 1726 1727 1728 1729 1730 1731 1732
    o.doc_myget1_cloned = clone(o.doc_myget1);
    o.doc_myget1_cloned["_rev"] = "1-rev1";
    o.doc_myget1_cloned["_revisions"] = {"start": 1, "ids": ["rev1"]};
    o.doc_myget1_cloned["_revs_info"] = [{
        "rev": "1-rev1", "status": "available"
    }];
    o.spy(o, "value", o.doc_myget1_cloned, "Get document (winner)");
    o.jio.get("get1", {"revs_info": true, "revs": true, "conflicts": true},
              o.f);
1733 1734 1735 1736
    o.tick(o);

    // adding two documents
    o.doctree = {"children":[{
1737 1738 1739
        "rev": "1-rev1", "status": "available", "children": []
    },{
        "rev": "1-rev2", "status": "available", "children": [{
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
            "rev": "2-rev3", "status": "available", "children": []
        }]
    }]};
    o.doc_myget2 = {"_id": "get1", "title": "myGet2"};
    o.doc_myget3 = {"_id": "get1", "title": "myGet3"};
    localstorage.setItem(o.localpath+"/get1.revision_tree.json", o.doctree);
    localstorage.setItem(o.localpath+"/get1.1-rev2", o.doc_myget2);
    localstorage.setItem(o.localpath+"/get1.2-rev3", o.doc_myget3);

    // get document
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    o.doc_myget3_cloned = clone(o.doc_myget3);
    o.doc_myget3_cloned["_rev"] = "2-rev3";
    o.doc_myget3_cloned["_revisions"] = {"start": 2, "ids": ["rev3","rev2"]};
    o.doc_myget3_cloned["_revs_info"] = [{
        "rev": "2-rev3", "status": "available"
    },{
        "rev": "1-rev2", "status": "available"
    }];
    o.doc_myget3_cloned["_conflicts"] = ["1-rev1"];
    o.spy(o, "value", o.doc_myget3_cloned,
1760
          "Get document (winner, after posting another one)");
1761 1762
    o.jio.get("get1", {"revs_info": true, "revs": true, "conflicts": true},
              o.f);
1763 1764
    o.tick(o);

1765 1766
    // get inexistent specific document
    o.spy(o, "status", 404, "Get document (inexistent specific revision)");
1767 1768 1769 1770
    o.jio.get("get1", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev0"
    }, o.f);
1771 1772 1773
    o.tick(o);

    // get specific document
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    o.doc_myget2_cloned = clone(o.doc_myget2);
    o.doc_myget2_cloned["_rev"] = "1-rev2";
    o.doc_myget2_cloned["_revisions"] = {"start": 1, "ids": ["rev2"]};
    o.doc_myget2_cloned["_revs_info"] = [{
        "rev": "1-rev2", "status": "available"
    }];
    o.doc_myget2_cloned["_conflicts"] = ["1-rev1"];
    o.spy(o, "value", o.doc_myget2_cloned, "Get document (specific revision)");
    o.jio.get("get1", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev2"
    }, o.f);
1786 1787
    o.tick(o);

1788 1789 1790 1791
    // adding an attachment
    o.attmt_myget2 = {
        "get2": {
            "length": 3,
1792 1793
            "digest": "md5-dontcare",
            "revpos": 1
1794 1795
        }
    };
1796 1797
    o.doc_myget2["_attachments"] = o.attmt_myget2;
    o.doc_myget3["_attachments"] = o.attmt_myget2;
1798
    localstorage.setItem(o.localpath+"/get1.1-rev2", o.doc_myget2);
1799
    localstorage.setItem(o.localpath+"/get1.2-rev3", o.doc_myget3);
1800
    localstorage.setItem(o.localpath+"/get1.1-rev2/get2", "abc");
1801 1802 1803 1804 1805 1806

    // get attachment winner
    o.spy(o, "value", "abc", "Get attachment (winner)");
    o.jio.get("get1/get2", o.f);
    o.tick(o);

1807 1808
    // get inexistent attachment specific rev
    o.spy(o, "status", 404, "Get inexistent attachment (specific revision)");
1809 1810 1811 1812
    o.jio.get("get1/get2", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev1"
    }, o.f);
1813 1814 1815 1816
    o.tick(o);

    // get attachment specific rev
    o.spy(o, "value", "abc", "Get attachment (specific revision)");
1817 1818 1819 1820
    o.jio.get("get1/get2", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev2"
    }, o.f);
1821 1822
    o.tick(o);

Sven Franck's avatar
Sven Franck committed
1823
    // get document with attachment (specific revision)
1824
    o.doc_myget2_cloned["_attachments"] = o.attmt_myget2;
1825
    o.spy(o, "value", o.doc_myget2_cloned,
1826
          "Get document which have an attachment (specific revision)");
1827 1828 1829 1830
    o.jio.get("get1", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev2"
    }, o.f);
1831 1832 1833
    o.tick(o);

    // get document with attachment (winner)
1834 1835 1836
    o.doc_myget3_cloned["_attachments"] = o.attmt_myget2;
    o.spy(o, "value", o.doc_myget3_cloned,
          "Get document which have an attachment (winner)");
1837 1838
    o.jio.get("get1", {"revs_info": true, "revs": true, "conflicts": true},
              o.f);
1839 1840 1841 1842 1843 1844
    o.tick(o);

    o.jio.stop();

});

Sven Franck's avatar
Sven Franck committed
1845 1846 1847 1848 1849 1850
test ("Remove", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1851
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
1852 1853
            "type": "local",
            "username": "urevrem",
1854
            "application_name": "arevrem"
Sven Franck's avatar
Sven Franck committed
1855 1856 1857 1858
        }
    });
    o.localpath = "jio/localstorage/urevrem/arevrem";

1859
    // 1. remove document without revision
1860
    o.spy (o, "status", 404,
Tristan Cavelier's avatar
Tristan Cavelier committed
1861
           "Remove document (no doctree, no revision)");
1862 1863 1864
    o.jio.remove({"_id":"remove1"}, o.f);
    o.tick(o);

1865
    // 2. remove attachment without revision
1866
    o.spy (o, "status", 404,
Tristan Cavelier's avatar
Tristan Cavelier committed
1867
           "Remove attachment (no doctree, no revision)");
1868 1869 1870
    o.jio.remove({"_id":"remove1/remove2"}, o.f);
    o.tick(o);

Sven Franck's avatar
Sven Franck committed
1871 1872 1873 1874
    // adding two documents
    o.doc_myremove1 = {"_id": "remove1", "title": "myRemove1"};
    o.doc_myremove2 = {"_id": "remove1", "title": "myRemove2"};

1875
    o.very_old_rev = "1-veryoldrev";
Sven Franck's avatar
Sven Franck committed
1876

1877 1878
    localstorage.setItem(o.localpath+"/remove1."+o.very_old_rev,
                         o.doc_myremove1);
Sven Franck's avatar
Sven Franck committed
1879 1880 1881 1882 1883 1884
    localstorage.setItem(o.localpath+"/remove1.1-rev2", o.doc_myremove1);

    // add attachment
    o.attmt_myremove1 = {
        "remove2": {
            "length": 3,
Tristan Cavelier's avatar
Tristan Cavelier committed
1885 1886
            "digest": "md5-dontcare",
            "revpos":1
Sven Franck's avatar
Sven Franck committed
1887 1888 1889
        },
    };
    o.doc_myremove1 = {"_id": "remove1", "title": "myRemove1",
1890
                       "_attachments":o.attmt_myremove1};
1891 1892
    o.revisions = {"start":1,"ids":[o.very_old_rev.split('-'),[1]]}
    o.old_rev = "2-"+generateRevisionHash(o.doc_myremove1, o.revisions);
Sven Franck's avatar
Sven Franck committed
1893 1894 1895 1896 1897 1898 1899 1900

    localstorage.setItem(o.localpath+"/remove1."+o.old_rev, o.doc_myremove1);
    localstorage.setItem(o.localpath+"/remove1."+o.old_rev+"/remove2", "xyz");

    o.doctree = {"children":[{
        "rev": o.very_old_rev, "status": "available", "children": [{
            "rev": o.old_rev, "status": "available", "children": []
        }]
1901 1902 1903
    },{
        "rev": "1-rev2", "status": "available", "children": []
    }]};
Sven Franck's avatar
Sven Franck committed
1904 1905
    localstorage.setItem(o.localpath+"/remove1.revision_tree.json", o.doctree);

1906
    // 3. remove non existing attachment with revision
Sven Franck's avatar
Sven Franck committed
1907 1908
    o.spy(o, "status", 404,
          "Remove NON-existing attachment (revision)");
Sven Franck's avatar
Sven Franck committed
1909 1910 1911
    o.jio.remove({"_id":"remove1.1-rev2/remove0","_rev":o.old_rev}, o.f);
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
1912 1913 1914
    o.revisions = {"start": 2, "ids":[
        o.old_rev.split('-')[1], o.very_old_rev.split('-')[1]
    ]};
Sven Franck's avatar
Sven Franck committed
1915
    o.doc_myremove1 = {"_id":"remove1/remove2","_rev":o.old_rev};
1916
    o.rev = "3-"+generateRevisionHash(o.doc_myremove1, o.revisions);
Sven Franck's avatar
Sven Franck committed
1917

1918
    // 4. remove existing attachment with revision
Sven Franck's avatar
Sven Franck committed
1919
    o.spy (o, "value", {"ok": true, "id": "remove1."+o.rev, "rev": o.rev},
Tristan Cavelier's avatar
Tristan Cavelier committed
1920
           "Remove existing attachment (revision)");
1921 1922 1923 1924
    o.jio.remove({"_id":"remove1/remove2","_rev":o.old_rev}, o.f);
    o.tick(o);

    o.testtree = {"children":[{
Sven Franck's avatar
Sven Franck committed
1925 1926
        "rev": o.very_old_rev, "status": "available", "children": [{
            "rev": o.old_rev, "status": "available", "children": [{
1927
                "rev": o.rev, "status": "available", "children": []
Sven Franck's avatar
Sven Franck committed
1928 1929
            }]
        }]
1930 1931 1932
    },{
        "rev": "1-rev2", "status": "available", "children": []
    }]};
Sven Franck's avatar
Sven Franck committed
1933

1934
    // 5. check if document tree has been updated correctly
Tristan Cavelier's avatar
Tristan Cavelier committed
1935 1936
    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1.revision_tree.json"
1937
    ),o.testtree, "Check document tree");
1938 1939

    // 6. check if attachment has been removed
1940 1941 1942
    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1."+o.rev+"/remove2"
    ), null, "Check attachment");
1943 1944

    // 7. check if document is updated
1945 1946
    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1."+o.rev
Sven Franck's avatar
Sven Franck committed
1947
    ), {"_id": "remove1."+o.rev, "title":"myRemove1"}, "Check document");
Sven Franck's avatar
Sven Franck committed
1948

Sven Franck's avatar
Sven Franck committed
1949 1950 1951 1952 1953 1954 1955 1956 1957
    // add another attachment
    o.attmt_myremove2 = {
        "remove3": {
            "length": 3,
            "digest": "md5-hello123"
        },
        "revpos":1
    };
    o.doc_myremove2 = {"_id": "remove1", "title": "myRemove2",
1958
                       "_attachments":o.attmt_myremove2};
1959 1960 1961
    o.revisions = {"start":1,"ids":["rev2"] };
    o.second_old_rev = "2-"+generateRevisionHash(o.doc_myremove2, o.revisions);

1962 1963 1964 1965
    localstorage.setItem(o.localpath+"/remove1."+o.second_old_rev,
                         o.doc_myremove2);
    localstorage.setItem(o.localpath+"/remove1."+o.second_old_rev+"/remove3",
                         "stu");
Sven Franck's avatar
Sven Franck committed
1966 1967 1968 1969 1970 1971 1972

    o.doctree = {"children":[{
        "rev": o.very_old_rev, "status": "available", "children": [{
            "rev": o.old_rev, "status": "available", "children": [{
                "rev": o.rev, "status": "available", "children":[]
            }]
        }]
Tristan Cavelier's avatar
Tristan Cavelier committed
1973
    },{
Sven Franck's avatar
Sven Franck committed
1974 1975
        "rev": "1-rev2", "status": "available", "children": [{
            "rev": o.second_old_rev, "status": "available", "children":[]
Tristan Cavelier's avatar
Tristan Cavelier committed
1976 1977
        }]
    }]};
Sven Franck's avatar
Sven Franck committed
1978 1979
    localstorage.setItem(o.localpath+"/remove1.revision_tree.json", o.doctree);

1980
    // 8. remove non existing attachment without revision
Sven Franck's avatar
Sven Franck committed
1981 1982
    o.spy (o,"status", 409,
           "409 - Removing non-existing-attachment (no revision)");
Sven Franck's avatar
Sven Franck committed
1983 1984 1985
    o.jio.remove({"_id":"remove1/remove0"}, o.f);
    o.tick(o);

1986
    o.revisions = {"start":2,"ids":[o.second_old_rev.split('-')[1],"rev2"]};
Sven Franck's avatar
Sven Franck committed
1987
    o.doc_myremove3 = {"_id":"remove1/remove3","_rev":o.second_old_rev};
1988
    o.second_rev = "3-"+generateRevisionHash(o.doc_myremove3, o.revisions);
Sven Franck's avatar
Sven Franck committed
1989

1990
    // 9. remove existing attachment without revision
Sven Franck's avatar
Sven Franck committed
1991
    o.spy (o,"status", 409, "409 - Removing existing attachment (no revision)");
Sven Franck's avatar
Sven Franck committed
1992 1993 1994
    o.jio.remove({"_id":"remove1/remove3"}, o.f);
    o.tick(o);

1995
    // 10. remove wrong revision
Sven Franck's avatar
Sven Franck committed
1996
    o.spy (o,"status", 409, "409 - Removing document (false revision)");
1997
    o.jio.remove({"_id":"remove1","_rev":"1-rev2"}, o.f);
Sven Franck's avatar
Sven Franck committed
1998 1999
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
2000 2001
    o.revisions = {"start": 3, "ids":[
        o.rev.split('-')[1],
2002 2003
        o.old_rev.split('-')[1],o.very_old_rev.split('-')[1]
    ]};
Sven Franck's avatar
Sven Franck committed
2004
    o.doc_myremove4 = {"_id":"remove1","_rev":o.rev};
2005 2006
    o.second_new_rev = "4-"+
        generateRevisionHash(o.doc_myremove4, o.revisions, true);
Sven Franck's avatar
Sven Franck committed
2007

2008
    // 11. remove document version with revision
2009 2010
    o.spy (o, "value", {"ok": true, "id": "remove1", "rev":
        o.second_new_rev},
Tristan Cavelier's avatar
Tristan Cavelier committed
2011
           "Remove document (with revision)");
Sven Franck's avatar
Sven Franck committed
2012
    o.jio.remove({"_id":"remove1", "_rev":o.rev}, o.f);
Sven Franck's avatar
Sven Franck committed
2013 2014
    o.tick(o);

2015 2016 2017 2018 2019
    o.testtree["children"][0]["children"][0]["children"][0]["children"].push({
        "rev": o.second_new_rev,
        "status": "deleted",
        "children": []
    });
2020 2021 2022 2023 2024 2025
    o.testtree["children"][1]["children"].push({
        "rev":o.second_old_rev,
        "status":"available",
        "children":[]
    });

2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1.revision_tree.json"
    ), o.testtree, "Check document tree");

    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1."+o.second_new_rev+"/remove2"
    ), null, "Check attachment");

    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1."+o.second_new_rev
    ), null, "Check document");

    // remove document without revision
Sven Franck's avatar
Sven Franck committed
2039
    o.spy (o,"status", 409, "409 - Removing document (no revision)");
Sven Franck's avatar
Sven Franck committed
2040 2041
    o.jio.remove({"_id":"remove1"}, o.f);
    o.tick(o);
2042

Sven Franck's avatar
Sven Franck committed
2043 2044 2045
    o.jio.stop();
});

2046
module ( "Jio Revision Storage + Local Storage" );
Sven Franck's avatar
Sven Franck committed
2047

2048
test ("Scenario", function(){
Sven Franck's avatar
Sven Franck committed
2049 2050 2051 2052 2053

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
2054
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
2055 2056
            "type": "local",
            "username": "usam1",
2057
            "application_name": "asam1"
Sven Franck's avatar
Sven Franck committed
2058 2059 2060 2061
        }
    });
    o.localpath = "jio/localstorage/usam1/asam1";

2062 2063
    // new application
    ok ( o.jio, "I open my application with revision and localstorage");
Sven Franck's avatar
Sven Franck committed
2064

2065
    // put non empty document A-1
Sven Franck's avatar
Sven Franck committed
2066
    o.doc = {"_id": "sample1", "title": "mySample1"};
2067 2068
    o.revisions = {"start": 0, "ids": []};
    o.hex = generateRevisionHash(o.doc, o.revisions);
2069
    o.rev = "1-"+o.hex;
Sven Franck's avatar
Sven Franck committed
2070

2071
    o.spy (o, "value", {"ok": true, "id": "sample1", "rev": o.rev},
2072 2073
           "Then, I create a new document (no attachment), my application "+
           "keep the revision in memory");
Sven Franck's avatar
Sven Franck committed
2074 2075 2076
    o.jio.put(o.doc, o.f);
    o.tick(o);

2077
    // open new tab (JIO)
Sven Franck's avatar
Sven Franck committed
2078 2079
    o.jio2 = JIO.newJio({
        "type": "revision",
2080
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
2081 2082
            "type": "local",
            "username": "usam1",
2083
            "application_name": "asam1"
Sven Franck's avatar
Sven Franck committed
2084 2085 2086 2087
        }
    });
    o.localpath = "jio/localstorage/usam1/asam1";

2088
    // Create a new JIO in a new tab
2089 2090
    ok (o.jio2, "Now, I am opening a new tab, with the same application"+
        " and the same storage tree");
Sven Franck's avatar
Sven Franck committed
2091

2092
    // Get the document from the first storage
Sven Franck's avatar
Sven Franck committed
2093 2094 2095
    o.doc._rev = o.rev;
    o.doc._revisions = {"ids":[o.hex], "start":1 };
    o.doc._revs_info = [{"rev": o.rev, "status": "available"}];
2096 2097
    o.spy(o, "value", o.doc, "And, on this new tab, I load the document,"+
        "and my application keep the revision in memory");
Sven Franck's avatar
Sven Franck committed
2098
    o.jio2.get("sample1", {
2099 2100
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": o.rev }, o.f);
Sven Franck's avatar
Sven Franck committed
2101 2102
    o.tick(o);

2103
    // MODFIY the 2nd version
Sven Franck's avatar
Sven Franck committed
2104 2105 2106 2107
    o.doc_2 = {"_id": "sample1", "_rev": o.rev,
        "title":"mySample2_modified"};
    o.revisions_2 = {"start":1 , "ids":[o.hex]};
    o.hex_2 = generateRevisionHash(o.doc_2, o.revisions_2)
2108
    o.rev_2 = "2-"+o.hex_2;
2109
    o.spy (o, "value", {"id":"sample1", "ok":true, "rev": o.rev_2},
2110
           "So, I can modify and update it");
Sven Franck's avatar
Sven Franck committed
2111
    o.jio2.put(o.doc_2, o.f);
Sven Franck's avatar
Sven Franck committed
2112 2113
    o.tick(o);

2114
    // MODFIY first version
2115 2116 2117
    o.doc_1 = {
        "_id": "sample1", "_rev": o.rev, "title": "mySample1_modified"
    };
Sven Franck's avatar
Sven Franck committed
2118 2119 2120 2121 2122
    o.revisions_1 = {"start": 1, "ids":[o.rev.split('-')[1]
    ]};
    o.hex_1 = generateRevisionHash(o.doc_1, o.revisions_1);
    o.rev_1 = "2-"+o.hex_1;
    o.spy (o, "value", {"id":"sample1", "ok":true, "rev": o.rev_1},
2123
           "Back to the first tab, I update the document.");
Sven Franck's avatar
Sven Franck committed
2124
    o.jio.put(o.doc_1, o.f);
Sven Franck's avatar
Sven Franck committed
2125 2126
    o.tick(o);

2127
    // Close 1st tab
Sven Franck's avatar
Sven Franck committed
2128 2129
    o.jio.close();

2130 2131 2132 2133 2134
    // Close 2nd tab
    o.jio2.close();
    ok ( o.jio2, "I close tab both tabs");

    // Reopen JIO
Sven Franck's avatar
Sven Franck committed
2135 2136
    o.jio = JIO.newJio({
        "type": "revision",
2137
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
2138 2139
            "type": "local",
            "username": "usam1",
2140
            "application_name": "asam1"
Sven Franck's avatar
Sven Franck committed
2141 2142 2143
        }
    });
    o.localpath = "jio/localstorage/usam1/asam1";
2144
    ok ( o.jio, "Later, I open my application again");
Sven Franck's avatar
Sven Franck committed
2145

2146
    // GET document without revision = winner & conflict!
2147
    o.mydocSample3 = {"_id": "sample1", "title": "mySample1_modified",
2148
                      "_rev": o.rev_1};
Sven Franck's avatar
Sven Franck committed
2149 2150
    o.mydocSample3._conflicts = [o.rev_2]
    o.mydocSample3._revs_info = [{"rev": o.rev_1, "status": "available"},{
2151 2152
        "rev":o.rev,"status":"available"
        }];
Sven Franck's avatar
Sven Franck committed
2153
    o.mydocSample3._revisions = {"ids":[o.hex_1, o.hex], "start":2 };
2154
    o.spy(o, "value", o.mydocSample3,
2155 2156
          "I load the same document as before, and a popup shows that "+
          "there is a conflict");
2157 2158
    o.jio.get("sample1", {"revs_info": true, "revs": true, "conflicts": true,
        }, o.f);
Sven Franck's avatar
Sven Franck committed
2159 2160
    o.tick(o);

2161
    // REMOVE one of the two conflicting versions
2162 2163 2164 2165 2166
    o.revisions = {"start": 2, "ids":[
        o.rev_1.split('-')[1],o.rev.split('-')[1]
    ]};
    o.doc_myremove3 = {"_id": "sample1", "_rev": o.rev_1};
    o.rev_3 = "3-"+generateRevisionHash(o.doc_myremove3, o.revisions,true);
Sven Franck's avatar
Sven Franck committed
2167 2168

    o.spy (o, "value", {"ok": true, "id": "sample1", "rev": o.rev_3},
2169
           "I choose one of the document and close the application.");
2170
    o.jio.remove({"_id":"sample1", "_rev":o.rev_1}, o.f);
Sven Franck's avatar
Sven Franck committed
2171 2172
    o.tick(o);

2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
    // check to see if conflict still exists
    o.mydocSample4 = {"_id": "sample1", "title": "mySample2_modified",
                      "_rev": o.rev_2};
    o.mydocSample4._revs_info = [{"rev": o.rev_2, "status": "available"},{
        "rev":o.rev,"status":"available"
        }];
    o.mydocSample4._revisions = {"ids":[o.hex_2, o.hex], "start":2 };

    o.spy(o, "value", o.mydocSample4, "Test if conflict still exists");
    o.jio.get("sample1", {"revs_info": true, "revs": true,
              "conflicts": true,}, o.f);
    o.tick(o);

2186
    // END
Sven Franck's avatar
Sven Franck committed
2187
    o.jio.stop();
2188

Sven Franck's avatar
Sven Franck committed
2189
});
Sven Franck's avatar
Sven Franck committed
2190

2191
module ("JIO Replicate Revision Storage");
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249

  var testReplicateRevisionStorageGenerator = function (
    sinon, jio_description, document_name_have_revision
  ) {

    var o = generateTools(sinon), leavesAction, generateLocalPath;

    o.jio = JIO.newJio(jio_description);

    generateLocalPath = function (storage_description) {
      return "jio/localstorage/" + storage_description.username + "/" +
        storage_description.application_name;
    };

    leavesAction = function (action, storage_description, param) {
      var i;
      if (param === undefined) {
        param = {};
      } else {
        param = clone(param);
      }
      if (storage_description.storage_list !== undefined) {
        // it is the replicate revision storage tree
        for (i = 0; i < storage_description.storage_list.length; i += 1) {
          leavesAction(action, storage_description.storage_list[i], param);
        }
      } else if (storage_description.sub_storage !== undefined) {
        // it is the revision storage tree
        param.revision = true;
        leavesAction(action, storage_description.sub_storage, param);
      } else {
        // it is the storage tree leaf
        param[storage_description.type] = true;
        action(storage_description, param);
      }
    };
    o.leavesAction = function (action) {
      leavesAction(action, jio_description);
    };

    // post a new document without id
    o.doc = {"title": "post document without id"};
    o.spy(o, "status", undefined, "Post document (without id)");
    o.jio.post(o.doc, function (err, response) {
      o.f.apply(arguments);
      o.response_rev = (err || response).rev;
      if (isUuid((err || response).id)) {
        ok(true, "Uuid format");
        o.uuid = (err || response).id;
      } else {
        deepEqual((err || response).id,
                  "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Uuid format");
      }
    });
    o.tick(o);

    // check document
    o.doc._id = o.uuid;
2250 2251
    o.revision = {"start": 0, "ids": []};
    o.rev = "1-1";
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
    o.local_rev = "1-" + generateRevisionHash(o.doc, o.revision);
    o.leavesAction(function (storage_description, param) {
      var suffix = "", doc = clone(o.doc);
      if (param.revision) {
        deepEqual(o.response_rev, o.rev, "Check revision");
        doc._id += "." + o.local_rev;
        suffix = "." + o.local_rev;
      }
      deepEqual(
        localstorage.getItem(generateLocalPath(storage_description) +
                             "/" + o.uuid + suffix),
        doc, "Check document"
      );
    });

2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
    // get the post document without revision
    o.spy(o, "value", {
      "_id": o.uuid,
      "title": "post document without id",
      "_rev": "1-1",
      "_revisions": {"start": 1, "ids": ["1"]},
      "_revs_info": [{"rev": "1-1", "status": "available"}]
    }, "Get the previous document (without revision)");
    o.jio.get(o.uuid, {
      "conflicts": true,
      "revs": true,
      "revs_info": true
    }, o.f);
    o.tick(o);

2282
    // post a new document with id
2283 2284
    o.doc = {"_id": "doc1", "title": "post new doc with id"};
    o.spy(o, "value", {"ok": true, "id": "doc1", "rev": o.rev},
2285 2286 2287 2288
          "Post document (with id)");
    o.jio.post(o.doc, o.f);
    o.tick(o);

2289 2290 2291 2292
    //  /
    //  |
    // 1-1

2293
    // check document
2294 2295 2296 2297
    o.local_rev_hash = generateRevisionHash(o.doc, o.revision);
    o.local_rev = "1-" + o.local_rev_hash;
    o.specific_rev_hash = o.local_rev_hash;
    o.specific_rev = o.local_rev;
2298 2299 2300 2301 2302 2303 2304 2305
    o.leavesAction(function (storage_description, param) {
      var suffix = "", doc = clone(o.doc);
      if (param.revision) {
        doc._id += "." + o.local_rev;
        suffix = "." + o.local_rev;
      }
      deepEqual(
        localstorage.getItem(generateLocalPath(storage_description) +
2306
                             "/doc1" + suffix),
2307 2308 2309 2310
        doc, "Check document"
      );
    });

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
    // get the post document without revision
    o.spy(o, "value", {
      "_id": "doc1",
      "title": "post new doc with id",
      "_rev": "1-1",
      "_revisions": {"start": 1, "ids": ["1"]},
      "_revs_info": [{"rev": "1-1", "status": "available"}]
    }, "Get the previous document (without revision)");
    o.jio.get("doc1", {
      "conflicts": true,
      "revs": true,
      "revs_info": true
    }, o.f);
    o.tick(o);

2326
    // post same document without revision
2327 2328 2329
    o.doc = {"_id": "doc1", "title": "post same document without revision"};
    o.rev = "1-2";
    o.spy(o, "value", {"ok": true, "id": "doc1", "rev": o.rev},
2330 2331 2332 2333
          "Post same document (without revision)");
    o.jio.post(o.doc, o.f);
    o.tick(o);

2334 2335 2336 2337
    //    /
    //   / \
    // 1-1 1-2

2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
    // check document
    o.local_rev = "1-" + generateRevisionHash(o.doc, o.revision);
    o.leavesAction(function (storage_description, param) {
      var suffix = "", doc = clone(o.doc);
      if (param.revision) {
        doc._id += "." + o.local_rev;
        suffix = "." + o.local_rev;
      }
      deepEqual(
        localstorage.getItem(generateLocalPath(storage_description) +
2348
                             "/doc1" + suffix),
2349 2350 2351 2352 2353
        doc, "Check document"
      );
    });

    // post a new revision
2354 2355 2356
    o.doc = {"_id": "doc1", "title": "post new revision", "_rev": o.rev};
    o.rev = "2-3";
    o.spy(o, "value", {"ok": true, "id": "doc1", "rev": o.rev},
2357 2358 2359 2360
          "Post document (with revision)");
    o.jio.post(o.doc, o.f);
    o.tick(o);

2361 2362 2363 2364 2365 2366
    //    /
    //   / \
    // 1-1 1-2
    //      |
    //     2-3

2367 2368 2369 2370 2371
    // check document
    o.revision.start += 1;
    o.revision.ids.unshift(o.local_rev.split("-").slice(1).join("-"));
    o.doc._rev = o.local_rev;
    o.local_rev = "2-" + generateRevisionHash(o.doc, o.revision);
2372
    o.specific_rev_conflict = o.local_rev;
2373 2374 2375 2376 2377 2378 2379 2380 2381
    o.leavesAction(function (storage_description, param) {
      var suffix = "", doc = clone(o.doc);
      delete doc._rev;
      if (param.revision) {
        doc._id += "." + o.local_rev;
        suffix = "." + o.local_rev;
      }
      deepEqual(
        localstorage.getItem(generateLocalPath(storage_description) +
2382
                             "/doc1" + suffix),
2383 2384 2385 2386
        doc, "Check document"
      );
    });

2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
    // get the post document with revision
    o.spy(o, "value", {
      "_id": "doc1",
      "title": "post same document without revision",
      "_rev": "1-2",
      "_revisions": {"start": 1, "ids": ["2"]},
      "_revs_info": [{"rev": "1-2", "status": "available"}],
      "_conflicts": ["1-1"]
    }, "Get the previous document (with revision)");
    o.jio.get("doc1", {
      "conflicts": true,
      "revs": true,
      "revs_info": true,
      "rev": "1-2"
    }, o.f);
    o.tick(o);

    // get the post document with specific revision
    o.spy(o, "value", {
      "_id": "doc1",
      "title": "post new doc with id",
      "_rev": o.specific_rev,
      "_revisions": {"start": 1, "ids": [o.specific_rev_hash]},
      "_revs_info": [{"rev": o.specific_rev, "status": "available"}],
      "_conflicts": [o.specific_rev_conflict]
    }, "Get a previous document (with local storage revision)");
    o.jio.get("doc1", {
      "conflicts": true,
      "revs": true,
      "revs_info": true,
      "rev": o.specific_rev
    }, o.f);
    o.tick(o);

2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
    // put document without id
    o.spy(o, "status", 20, "Put document without id")
    o.jio.put({}, o.f);
    o.tick(o);

    // put document without rev
    o.doc = {"_id": "doc1", "title": "put new document"};
    o.rev = "1-4";
    o.spy(o, "value", {"id": "doc1", "ok": true, "rev": o.rev},
          "Put document without rev")
    o.jio.put(o.doc, o.f);
    o.tick(o);

    //    __/__
    //   /  |  \
    // 1-1 1-2 1-4
    //      |
    //     2-3

    // put new revision
    o.doc = {"_id": "doc1", "title": "put new revision", "_rev": "1-4"};
    o.rev = "2-5";
    o.spy(o, "value", {"id": "doc1", "ok": true, "rev": o.rev},
          "Put document without rev")
    o.jio.put(o.doc, o.f);
    o.tick(o);

    //    __/__
    //   /  |  \
    // 1-1 1-2 1-4
    //      |   |
    //     2-3 2-5

    // putAttachment to inexistent document
    // putAttachment
    // get document
    // get attachment
    // put document
    // get document
    // get attachment
    // remove attachment
    // get document
    // get inexistent attachment

    // remove document and conflict
    o.rev = "3-6";
    o.spy(o, "value", {"ok": true, "id": "doc1", "rev": o.rev},
          "Remove document");
    o.jio.remove({"_id": "doc1", "_rev": "2-5"}, o.f);
    o.tick(o);

    // remove document and conflict
    o.rev = "3-7";
    o.spy(o, "value", {"ok": true, "id": "doc1", "rev": o.rev},
          "Remove document");
    o.jio.remove({"_id": "doc1", "_rev": "2-3"}, o.f);
    o.tick(o);

    // remove document
    o.rev = "2-8";
    o.spy(o, "value", {"ok": true, "id": "doc1", "rev": o.rev},
          "Remove document");
    o.jio.remove({"_id": "doc1", "_rev": "1-1"}, o.f);
    o.tick(o);

    // get inexistent document
    o.spy(o, "status", 404, "Get inexistent document");
    o.jio.get("doc1", {
      "conflicts": true,
      "revs": true,
      "revs_info": true
    }, o.f);
    o.tick(o);

2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
    o.jio.stop();

  };

  test ("[Revision + Local Storage] Scenario", function () {
    testReplicateRevisionStorageGenerator(this, {
      "type": "replicaterevision",
      "storage_list": [{
        "type": "revision",
        "sub_storage": {
          "type": "local",
          "username": "ureprevloc",
          "application_name": "areprevloc"
        }
      }]
    });
  });
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
  test("[Replicate Revision + Revision + Local Storage] Scenario", function () {
    testReplicateRevisionStorageGenerator(this, {
      "type": "replicaterevision",
      "storage_list": [{
        "type": "replicaterevision",
        "storage_list": [{
          "type": "revision",
          "sub_storage": {
            "type": "local",
            "username": "urepreprevloc",
            "application_name": "arepreprevloc"
          }
        }]
      }]
    });
  });
2528
  test ("2x [Revision + Local Storage] Scenario", function () {
2529 2530 2531 2532 2533 2534
    testReplicateRevisionStorageGenerator(this, {
      "type": "replicaterevision",
      "storage_list": [{
        "type": "revision",
        "sub_storage": {
          "type": "local",
2535 2536 2537 2538 2539 2540 2541 2542 2543
          "username": "ureprevlocloc1",
          "application_name": "areprevloc1"
        }
      }, {
        "type": "revision",
        "sub_storage": {
          "type": "local",
          "username": "ureprevlocloc2",
          "application_name": "areprevloc2"
2544 2545 2546 2547
        }
      }]
    });
  });
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588
  test("2x [Replicate Rev + 2x [Rev + Local]] Scenario", function () {
    testReplicateRevisionStorageGenerator(this, {
      "type": "replicaterevision",
      "storage_list": [{
        "type": "replicaterevision",
        "storage_list": [{
          "type": "revision",
          "sub_storage": {
            "type": "local",
            "username": "urepreprevloc1",
            "application_name": "arepreprevloc1"
          }
        }, {
          "type": "revision",
          "sub_storage": {
            "type": "local",
            "username": "urepreprevloc2",
            "application_name": "arepreprevloc2"
          }
        }]
      }, {
        "type": "replicaterevision",
        "storage_list": [{
          "type": "revision",
          "sub_storage": {
            "type": "local",
            "username": "urepreprevloc3",
            "application_name": "arepreprevloc3"
          }
        }, {
          "type": "revision",
          "sub_storage": {
            "type": "local",
            "username": "urepreprevloc4",
            "application_name": "arepreprevloc4"
          }
        }]
      }]
    });
  });
/*
2589
module ("Jio DAVStorage");
Tristan Cavelier's avatar
Tristan Cavelier committed
2590

2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
test ("Post", function () {

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "dav",
        "username": "davpost",
        "password": "checkpwd",
        "url": "https://ca-davstorage:8080"
    });

    // post without id
    o.spy (o, "status", 405, "Post without id");
    o.jio.post({}, o.f);
    o.clock.tick(5000);

    // post non empty document
2608
    o.addFakeServerResponse("dav", "PUT", "myFile", 201, "HTML RESPONSE");
2609
    o.spy(o, "value", {"id": "myFile", "ok": true},
2610
          "Create = POST non empty document");
2611 2612 2613 2614 2615 2616
    o.jio.post({"_id": "myFile", "title": "hello there"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    // post but document already exists (post = error!, put = ok)
    o.answer = JSON.stringify({"_id": "myFile", "title": "hello there"});
2617
    o.addFakeServerResponse("dav", "GET", "myFile", 200, o.answer);
2618 2619 2620
    o.spy (o, "status", 409, "Post but document already exists");
    o.jio.post({"_id": "myFile", "title": "hello again"}, o.f);
    o.clock.tick(5000);
2621
    o.server.respond();
2622 2623

    o.jio.stop();
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
});

test ("Put", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "dav",
        "username": "davput",
        "password": "checkpwd",
        "url": "https://ca-davstorage:8080"
    });

    // put without id => id required
    o.spy (o, "status", 20, "Put without id");
    o.jio.put({}, o.f);
    o.clock.tick(5000);

    // put non empty document
2643
    o.addFakeServerResponse("dav", "PUT", "put1", 201, "HTML RESPONSE");
2644 2645 2646 2647 2648
    o.spy (o, "value", {"ok": true, "id": "put1"},
           "Create = PUT non empty document");
    o.jio.put({"_id": "put1", "title": "myPut1"}, o.f);
    o.clock.tick(5000);
    o.server.respond();
2649 2650 2651
    //console.log( o.server );
    //console.log( o.server.requests[0].requestHeaders );
    //console.log( o.server.requests[0].responseHeaders );
2652 2653 2654

    // put but document already exists = update
    o.answer = JSON.stringify({"_id": "put1", "title": "myPut1"});
2655 2656
    o.addFakeServerResponse("dav", "GET", "put1", 200, o.answer);
    o.addFakeServerResponse("dav", "PUT", "put1", 201, "HTML RESPONSE");
2657 2658 2659 2660 2661 2662
    o.spy (o, "value", {"ok": true, "id": "put1"}, "Updated the document");
    o.jio.put({"_id": "put1", "title": "myPut2abcdedg"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    o.jio.stop();
2663
});
2664 2665 2666 2667 2668 2669 2670

test ("PutAttachment", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "dav",
2671
        "username": "davputattm",
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686
        "password": "checkpwd",
        "url": "https://ca-davstorage:8080"
    });

    // putAttachment without doc id => id required
    o.spy(o, "status", 20, "PutAttachment without doc id");
    o.jio.putAttachment({}, o.f);
    o.clock.tick(5000);

    // putAttachment without attachment id => attachment id required
    o.spy(o, "status", 22, "PutAttachment without attachment id");
    o.jio.putAttachment({"id": "putattmt1"}, o.f);
    o.clock.tick(5000);

    // putAttachment without underlying document => not found
2687
    o.addFakeServerResponse("dav", "GET", "putattmtx", 22, "HTML RESPONSE");
2688 2689
    o.spy(o, "status", 22, "PutAttachment without document");
    o.jio.putAttachment({"id": "putattmtx.putattmt2"}, o.f);
2690 2691 2692 2693 2694
    o.clock.tick(5000);
    o.server.respond();

    // putAttachment with document without data
    o.answer = JSON.stringify({"_id": "putattmt1", "title": "myPutAttm1"});
2695 2696 2697 2698
    o.addFakeServerResponse("dav", "GET", "putattmt1", 200, o.answer);
    o.addFakeServerResponse("dav", "PUT", "putattmt1", 201, "HTML RESPONSE");
    o.addFakeServerResponse("dav", "PUT", "putattmt1.putattmt2", 201,"HTML"+
      + "RESPONSE");
2699 2700 2701 2702 2703 2704 2705 2706
    o.spy(o, "value", {"ok": true, "id": "putattmt1/putattmt2"},
          "PutAttachment with document, without data");
    o.jio.putAttachment({"id": "putattmt1/putattmt2"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    // update attachment
    o.answer = JSON.stringify({"_id": "putattmt1", "title": "myPutAttm1"});
2707 2708 2709 2710
    o.addFakeServerResponse("dav", "GET", "putattmt1", 200, o.answer);
    o.addFakeServerResponse("dav", "PUT", "putattmt1", 201, "HTML RESPONSE");
    o.addFakeServerResponse("dav", "PUT", "putattmt1.putattmt2", 201,"HTML"+
      "RESPONSE");
2711 2712 2713 2714 2715 2716 2717 2718 2719
    o.spy(o, "value", {"ok": true, "id": "putattmt1/putattmt2"},
          "Update Attachment, with data");
    o.jio.putAttachment({"id": "putattmt1/putattmt2", "data": "abc"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    o.jio.stop();
});

2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
test ("Get", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "dav",
        "username": "davget",
        "password": "checkpwd",
        "url": "https://ca-davstorage:8080"
    });

    // get inexistent document
2732
    o.addFakeServerResponse("dav", "GET", "get1", 404, "HTML RESPONSE");
2733 2734 2735 2736 2737 2738
    o.spy(o, "status", 404, "Get non existing document");
    o.jio.get("get1", o.f);
    o.clock.tick(5000);
    o.server.respond();

    // get inexistent attachment
2739
    o.addFakeServerResponse("dav", "GET", "get1.get2", 404, "HTML RESPONSE");
2740 2741 2742 2743 2744 2745 2746
    o.spy(o, "status", 404, "Get non existing attachment");
    o.jio.get("get1/get2", o.f);
    o.clock.tick(5000);
    o.server.respond();

    // get document
    o.answer = JSON.stringify({"_id": "get3", "title": "some title"});
2747
    o.addFakeServerResponse("dav", "GET", "get3", 200, o.answer);
2748 2749 2750 2751 2752 2753
    o.spy(o, "value", {"_id": "get3", "title": "some title"}, "Get document");
    o.jio.get("get3", o.f);
    o.clock.tick(5000);
    o.server.respond();

    // get inexistent attachment (document exists)
2754
    o.addFakeServerResponse("dav", "GET", "get3.getx", 404, "HTML RESPONSE");
2755 2756 2757 2758 2759 2760 2761
    o.spy(o, "status", 404, "Get non existing attachment (doc exists)");
    o.jio.get("get3/getx", o.f);
    o.clock.tick(5000);
    o.server.respond();

    // get attachment
    o.answer = JSON.stringify({"_id": "get4", "title": "some attachment"});
2762
    o.addFakeServerResponse("dav", "GET", "get3.get4", 200, o.answer);
2763 2764 2765 2766 2767 2768 2769 2770 2771
    o.spy(o, "value", {"_id": "get4", "title": "some attachment"},
      "Get attachment");
    o.jio.get("get3/get4", o.f);
    o.clock.tick(5000);
    o.server.respond();

    o.jio.stop();
});

2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
test ("Remove", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "dav",
        "username": "davremove",
        "password": "checkpwd",
        "url": "https://ca-davstorage:8080"
    });

    // remove inexistent document
2784
    o.addFakeServerResponse("dav", "GET", "remove1", 404, "HTML RESPONSE");
2785 2786 2787 2788 2789 2790
    o.spy(o, "status", 404, "Remove non existening document");
    o.jio.remove({"_id": "remove1"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    // remove inexistent document/attachment
2791 2792
    o.addFakeServerResponse("dav", "GET", "remove1.remove2", 404, "HTML" +
      "RESPONSE");
2793 2794 2795 2796 2797 2798 2799
    o.spy(o, "status", 404, "Remove inexistent document/attachment");
    o.jio.remove({"_id": "remove1/remove2"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    // remove document
    o.answer = JSON.stringify({"_id": "remove3", "title": "some doc"});
2800 2801
    o.addFakeServerResponse("dav", "GET", "remove3", 200, o.answer);
    o.addFakeServerResponse("dav", "DELETE", "remove3", 200, "HTML RESPONSE");
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
    o.spy(o, "value", {"ok": true, "id": "remove3"}, "Remove document");
    o.jio.remove({"_id": "remove3"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    o.answer = JSON.stringify({
      "_id": "remove4",
      "title": "some doc",
      "_attachments": {
            "remove5": {
                "length": 4,
                "digest": "md5-d41d8cd98f00b204e9800998ecf8427e"
            }
      }
    });
    // remove attachment
2818 2819 2820 2821
    o.addFakeServerResponse("dav", "GET", "remove4", 200, o.answer);
    o.addFakeServerResponse("dav", "PUT", "remove4", 201, "HTML RESPONSE");
    o.addFakeServerResponse("dav", "DELETE", "remove4.remove5", 200, "HTML"+
      "RESPONSE");
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
    o.spy(o, "value", {"ok": true, "id": "remove4/remove5"},
          "Remove attachment");
    o.jio.remove({"_id": "remove4/remove5"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    o.answer = JSON.stringify({
      "_id": "remove6",
      "title": "some other doc",
      "_attachments": {
            "remove7": {
                "length": 4,
                "digest": "md5-d41d8cd98f00b204e9800998ecf8427e"
            },
            "remove8": {
                "length": 4,
                "digest": "md5-e41d8cd98f00b204e9800998ecf8427e"
            },
            "remove9": {
                "length": 4,
                "digest": "md5-f41d8cd98f00b204e9800998ecf8427e"
            }
      }
    });
    // remove document with multiple attachments
2847 2848 2849 2850 2851 2852 2853 2854
    o.addFakeServerResponse("dav", "GET", "remove6", 200, o.answer);
    o.addFakeServerResponse("dav", "DELETE", "remove6.remove7", 200, "HTML"+
      "RESPONSE");
    o.addFakeServerResponse("dav", "DELETE", "remove6.remove8", 200, "HTML"+
      "RESPONSE");
    o.addFakeServerResponse("dav", "DELETE", "remove6.remove9", 200, "HTML"+
      "RESPONSE");
    o.addFakeServerResponse("dav", "DELETE", "remove6", 200, "HTML RESPONSE");
2855 2856 2857 2858 2859 2860 2861 2862 2863
    o.spy(o, "value", {"ok": true, "id": "remove6"},
          "Remove document with multiple attachments");
    o.jio.remove({"_id": "remove6"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    o.jio.stop();
});

2864
test ("AllDocs", function () {
2865

2866 2867 2868
  // need to make server requests before activating fakeServer
  var davlist = getXML('responsexml/davlist'),
    o = generateTools(this);
Tristan Cavelier's avatar
Tristan Cavelier committed
2869

2870 2871 2872 2873 2874 2875
    o.jio = JIO.newJio({
        "type": "dav",
        "username": "davall",
        "password": "checkpwd",
        "url": "https://ca-davstorage:8080"
    });
2876

2877
  // get allDocs, no content
2878
  o.addFakeServerResponse("dav", "PROPFIND", "", 200, davlist);
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
  o.thisShouldBeTheAnswer = {
      "rows": [
        {"id": "alldocs1", "key": "alldocs1", "value": {}},
        {"id": "alldocs2", "key": "alldocs2", "value": {}}
      ],
      "total_rows": 2
  }
  o.spy(o, "value", o.thisShouldBeTheAnswer, "allDocs (no content)");
  o.jio.allDocs(o.f);
  o.clock.tick(5000);
  o.server.respond();

  // allDocs with option include
2892 2893 2894 2895 2896 2897 2898 2899 2900
  o.all1 = {"_id": "allDocs1", "title": "a doc title"};
  o.all2 = {"_id": "allDocs2", "title": "another doc title"};
  o.thisShouldBeTheAnswer = {
      "rows": [
        {"id": "alldocs1", "key": "alldocs1", "value": {}, "doc": o.all1},
        {"id": "alldocs2", "key": "alldocs2", "value": {}, "doc": o.all2}
      ],
      "total_rows": 2
  }
2901 2902 2903 2904
  o.addFakeServerResponse("dav", "GET", "alldocs1", 200,
    JSON.stringify(o.all1));
  o.addFakeServerResponse("dav", "GET", "alldocs2", 200,
    JSON.stringify(o.all2));
2905 2906 2907 2908 2909 2910
  o.spy(o, "value", o.thisShouldBeTheAnswer, "allDocs (include_docs)");
  o.jio.allDocs({"include_docs":true}, o.f);
  o.clock.tick(5000);
  o.server.respond();

  o.jio.stop();
Tristan Cavelier's avatar
Tristan Cavelier committed
2911
});
2912

2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
// NOTES: this test is for a live webDav server on localstorage
// see the documentation how to setup an apache2 webDav-server
// tests cannot be run subsequently, so only do one test at a time
/*
test ("webDav Live Server setup", function () {

    var o = generateTools(this);

    // turn off fakeserver - otherwise no requests will be made
    o.server.restore();

    o.jio = JIO.newJio({
        "type": "dav",
        "username": "davlive",
        "password": "checkpwd",
        "url": "http://127.0.1.1/dav"
    });

    // not used, check console for responses
    // o.spy(o, "value", {"id": "_id_", "ok": true}, "Live Webdav");

    // post a new document
    o.jio.post({"_id": "one.json", "title": "hello"}), o.f);
    o.clock.tick(5000);

    // modify document
    o.jio.put({"_id": "one.json", "title": "hello modified"}), o.f);
    o.clock.tick(5000);

    // add attachment
    o.jio.putAttachment({
      "id": "one.json/att.txt",
      "mimetype": "text/plain",
      "content":"there2"
    }, o.f);

    // test allDocs
    o.jio.allDocs({"include_docs":true},
      function(s){console.log(s);},
      function ( e ) {console.log(e);
    }, o.f);
    o.clock.tick(5000);

    // get Attachment
    o.jio.get("one.json/att.txt", o.f);
    o.clock.tick(5000);

    // remove Attachment
    o.jio.remove("one.json/att.txt", o.f.);
    o.clock.tick(5000);

    // remove Document
    o.jio.remove("one.json", o.f.);
    o.clock.tick(5000);
    o.jio.stop();
});
*/
2970
/*
Tristan Cavelier's avatar
Tristan Cavelier committed
2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127
module ('Jio ReplicateStorage');

test ('Document load', function () {
    // Test if ReplicateStorage can load several documents.

    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick(base_tick);
    o.mytest = function (message,doc,doc2) {
        o.f = function (err,val) {
            var gooddoc = doc;
            if (val) {
                if (doc2 && val.content === doc2.content) {
                    gooddoc = doc2;
                }
            }
            deepEqual (err || val,gooddoc,message);
        };
        o.t.spy(o,'f');
        o.jio.get('file',{max_retry:3},o.f);
        o.clock.tick(10000);
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok(false, 'too much results');
            } else {
                ok(false, 'no response');
            }
        }
    };
    o.jio = JIO.newJio({type:'replicate',storagelist:[
        {type:'dummyallok',username:'1'},
        {type:'dummyallok',username:'2'}]});
    o.mytest('DummyStorageAllOK,OK: load same file',{
        _id:'file',content:'content',
        _last_modified:15000,
        _creation_date:10000
    });
    o.jio.stop();

    o.jio = JIO.newJio({type:'replicate',storagelist:[
        {type:'dummyall3tries'},
        {type:'dummyallok'}]});
    o.mytest('DummyStorageAllOK,3tries: load 2 different files',
             {
                 _id:'file',content:'content',
                 _last_modified:15000,_creation_date:10000
             },{
                 _id:'file',content:'content file',
                 _last_modified:17000,_creation_date:11000
             });
    o.jio.stop();
});

test ('Document save', function () {
    // Test if ReplicateStorage can save several documents.

    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick(base_tick);
    o.mytest = function (message,value) {
        o.f = function (err,val) {
            if (err) {
                err = err.status;
            }
            deepEqual (err || val,value,message);
        };
        o.t.spy(o,'f');
        o.jio.put({_id:'file',content:'content'},{max_retry:3},o.f);
        o.clock.tick(500);
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok(false, 'too much results');
            } else {
                ok(false, 'no response');
            }
        }
    };
    o.jio = JIO.newJio({type:'replicate',storagelist:[
        {type:'dummyallok',username:'1'},
        {type:'dummyallok',username:'2'}]});
    o.mytest('DummyStorageAllOK,OK: save a file.',{ok:true,id:'file'});
    o.jio.stop();

    o.jio = JIO.newJio({type:'replicate',storagelist:[
        {type:'dummyall3tries',username:'1'},
        {type:'dummyallok',username:'2'}]});
    o.mytest('DummyStorageAll3Tries,OK: save a file.',{ok:true,id:'file'});
    o.jio.stop();
});

test ('Get Document List', function () {
    // Test if ReplicateStorage can get several list.

    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick(base_tick);
    o.mytest = function (message,value) {
        o.f = function (err,val) {
            deepEqual (err || objectifyDocumentArray(val.rows),
                       objectifyDocumentArray(value),message);
        };
        o.t.spy(o,'f');
        o.jio.allDocs({max_retry:3},o.f);
        o.clock.tick(10000);
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok(false, 'too much results');
            } else {
                ok(false, 'no response');
            }
        }
    };
    o.jio = JIO.newJio({type:'replicate',storagelist:[
        {type:'dummyall3tries',username:'1'},
        {type:'dummyallok',username:'2'}]});
    o.doc1 = {id:'file',key:'file',value:{
              _last_modified:15000,_creation_date:10000}};
    o.doc2 = {id:'memo',key:'memo',value:{
              _last_modified:25000,_creation_date:20000}};
    o.mytest('DummyStorageAllOK,3tries: get document list.',
             [o.doc1,o.doc2]);
    o.jio.stop();

    o.jio = JIO.newJio({type:'replicate',storagelist:[
        {type:'dummyall3tries',username:'3'},
        {type:'dummyall3tries',username:'4'}]});
    o.mytest('DummyStorageAll3tries,3tries: get document list.',
             [o.doc1,o.doc2]);
    o.jio.stop();
});

test ('Remove document', function () {
    // Test if ReplicateStorage can remove several documents.

    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick(base_tick);
    o.mytest = function (message,value) {
        o.f = function (err,val) {
            if (err) {
                err = err.status;
            }
            deepEqual (err || val,value,message);
        };
        o.t.spy(o,'f');
        o.jio.remove({_id:'file'},{max_retry:3},o.f);
        o.clock.tick(10000);
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok(false, 'too much results');
            } else {
                ok(false, 'no response');
            }
        }
    };
    o.jio = JIO.newJio({type:'replicate',storagelist:[
        {type:'dummyallok',username:'1'},
        {type:'dummyall3tries',username:'2'}]});
    o.mytest('DummyStorageAllOK,3tries: remove document.',{ok:true,id:'file'});
    o.jio.stop();
});
3128 3129 3130 3131 3132 3133 3134 3135 3136
*/
module ("Jio IndexStorage");

test ("Post", function () {

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "indexed",
3137 3138 3139 3140
        "indices": [
            {"name":"indexA", "fields":["findMeA"]},
            {"name":"indexAB", "fields":["findMeA","findMeB"]}
        ],
3141 3142 3143 3144 3145 3146
        "sub_storage": {
          "type": "local",
          "username": "ipost",
          "application_name": "ipost"
        }
    });
Tristan Cavelier's avatar
Tristan Cavelier committed
3147

3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
    // post without id
    o.spy (o, "status", undefined, "Post without id");
    o.jio.post({}, o.f);
    o.tick(o);

    // post non empty document
    o.doc = {"_id": "some_id", "title": "myPost1",
      "findMeA":"keyword_abc", "findMeB":"keyword_def"
    };
    o.spy (o, "value", {"ok": true, "id": "some_id"}, "Post document");
    o.jio.post(o.doc, o.f);
    o.tick(o);

    // check document
3162 3163
    o.fakeIndex = {
      "_id": "ipost_indices.json",
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
      "indexAB": {
        "findMeA": {
          "keyword_abc":["some_id"]
        },
        "findMeB": {
          "keyword_def":["some_id"]
        }
      },
      "indexA": {
        "findMeA": {
          "keyword_abc":["some_id"]
        }
      }
3177
    };
3178 3179 3180 3181 3182
    o.jio.get("ipost_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);
3183

3184 3185 3186 3187 3188 3189 3190 3191 3192
    // post with escapable characters
    o.doc = {"_id": "other_id", "title": "myPost2",
      "findMeA":"keyword_*§$%&/()=?", "findMeB":"keyword_|ð@ł¶đæðſæðæſ³"
    };
    o.spy (o, "value", {"ok": true, "id": "other_id"},
           "Post with escapable characters");
    o.jio.post(o.doc, o.f);
    o.tick(o);

3193
    // post and document already exists
3194
    o.doc = {"_id": "some_id", "title": "myPost3",
3195 3196 3197 3198 3199
      "findMeA":"keyword_ghi", "findMeB":"keyword_jkl"
    }
    o.spy (o, "status", 409, "Post and document already exists");
    o.jio.post(o.doc, o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
3200

3201 3202
    o.jio.stop();
});
3203 3204 3205 3206 3207 3208 3209 3210 3211

test ("Put", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
          "type": "indexed",
          "indices": [
              {"name":"indexA", "fields":["author"]},
3212
              {"name":"indexAB", "fields":["author","year"]}
3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
          ],
          "sub_storage": {
            "type": "local",
            "username": "iput",
            "application_name": "iput"
          }
      });

    // put without id
    // error 20 -> document id required
    o.spy (o, "status", 20, "Put without id");
    o.jio.put({}, o.f);
    o.tick(o);

    // put non empty document
    o.doc = {"_id": "put1", "title": "myPut1", "author":"John Doe"};
    o.spy (o, "value", {"ok": true, "id": "put1"}, "Put-create document");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check index file
3234
    o.fakeIndex = {
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
      "indexA": {
        "author": {
          "John Doe": ["put1"]
        }
      },
      "indexAB": {
        "author": {
          "John Doe": ["put1"]
        },
        "year": {}
      },
3246
      "_id": "iput_indices.json"
3247
    };
3248 3249 3250 3251 3252
    o.jio.get("iput_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);
3253

3254
    // modify document - modify keyword on index!
3255
    o.doc = {"_id": "put1", "title": "myPuttter1", "author":"Jane Doe"};
3256
    o.spy (o, "value", {"ok": true, "id": "put1"}, "Modify existing document");
3257 3258 3259 3260
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check index file
3261
    o.fakeIndex = {
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
      "indexA": {
        "author": {
          "Jane Doe": ["put1"]
          }
      },
      "indexAB": {
        "author": {
          "Jane Doe": ["put1"]
          },
        "year": {}
      },
3273
      "_id": "iput_indices.json"
3274
    };
3275 3276 3277 3278 3279
    o.jio.get("iput_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);
3280 3281 3282 3283 3284 3285 3286 3287 3288

    // add new document with same keyword!
    o.doc = {"_id": "new_doc", "title": "myPut2", "author":"Jane Doe"};
    o.spy (o, "value", {"ok": true, "id": "new_doc"},
      "Add new document with same keyword");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check index file
3289
    o.fakeIndex = {
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
      "indexA": {
        "author": {
          "Jane Doe": ["put1", "new_doc"]
          }
        },
      "indexAB": {
        "author": {
          "Jane Doe": ["put1", "new_doc"]
          },
        "year": {}
        },
3301
      "_id": "iput_indices.json"
3302
    };
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
    o.jio.get("iput_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);

    // add second keyword to index file
    o.doc = {"_id": "put1", "title": "myPut2", "author":"Jane Doe",
      "year":"1912"};
    o.spy (o, "value", {"ok": true, "id": "put1"},
      "add second keyword to index file");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check index file
    o.fakeIndex = {
3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
      "indexA": {
        "author": {
          "Jane Doe": ["put1"]
          }
        },
      "indexAB": {
        "author": {
          "Jane Doe": ["put1"]
          },
        "year": {
          "1912": ["put1"]
          }
        },
3332 3333 3334 3335 3336 3337 3338
      "_id": "iput_indices.json"
    };
    o.jio.get("iput_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);
3339 3340 3341 3342 3343 3344 3345 3346 3347

    // remove a keyword from an existing document
    o.doc = {"_id": "new_doc", "title": "myPut2"};
    o.spy (o, "value", {"ok": true, "id": "new_doc"},
      "Remove keyword from existing document");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check index file
3348
    o.fakeIndex = {
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
      "indexA": {
        "author": {
          "Jane Doe": ["put1"]
        }
      },
      "indexAB": {
        "author": {
          "Jane Doe": ["put1"]
        }, 
        "year": {
          "1912": ["put1"]
        }
      },
3362
      "_id": "iput_indices.json"
3363
    };
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453
    o.jio.get("iput_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);

    o.jio.stop();
});

test ("PutAttachment", function(){

    // not sure these need to be run, because the index does not change
    // and only small modifications have been made to handle putAttachment
    // tests are from localStorage putAttachment
    var o = generateTools(this);

    o.jio = JIO.newJio({
          "type": "indexed",
          "indices": [
              {"name":"indexA", "fields":["author"]},
              {"name":"indexAB", "fields":["author","year"]}
          ],
          "sub_storage": {
            "type": "local",
            "username": "iputatt",
            "application_name": "iputatt"
          }
      });

    // putAttachment without doc id
    // error 20 -> document id required
    o.spy(o, "status", 20, "PutAttachment without doc id");
    o.jio.putAttachment({}, o.f);
    o.tick(o);

    // putAttachment without attachment id
    // error 22 -> attachment id required
    o.spy(o, "status", 22, "PutAttachment without attachment id");
    o.jio.putAttachment({"id": "putattmt1"}, o.f);
    o.tick(o);

    // putAttachment without document
    // error 404 -> not found
    o.spy(o, "status", 404, "PutAttachment without document");
    o.jio.putAttachment({"id": "putattmt1/putattmt2"}, o.f);
    o.tick(o);

    // putAttachment with document
    o.doc = {"_id": "putattmt1","title": "myPutAttmt1"};
    o.spy (o, "value", {"ok": true, "id": "putattmt1"},
      "Put underlying document");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    o.spy(o, "value", {"ok": true, "id": "putattmt1/putattmt2"},
          "PutAttachment with document, without data");
    o.jio.putAttachment({"id": "putattmt1/putattmt2"}, o.f);
    o.tick(o);

    // check document
    deepEqual(
        localstorage.getItem("jio/localstorage/iputatt/iputatt/putattmt1"),
        {
            "_id": "putattmt1",
            "title": "myPutAttmt1",
            "_attachments": {
                "putattmt2": {
                    "length": 0,
                    // md5("")
                    "digest": "md5-d41d8cd98f00b204e9800998ecf8427e"
                }
            }
        },
        "Check document"
    );

    // check attachment
    deepEqual(
        localstorage.getItem(
            "jio/localstorage/iputatt/iputatt/putattmt1/putattmt2"),
        "", "Check attachment"
    );

    // update attachment
    o.spy(o, "value", {"ok": true, "id": "putattmt1/putattmt2"},
          "Update Attachment, with data");
    o.jio.putAttachment({"id": "putattmt1/putattmt2", "data": "abc"}, o.f);
    o.tick(o);

    // check document
3454
    deepEqual(
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
        localstorage.getItem("jio/localstorage/iputatt/iputatt/putattmt1"),
        {
            "_id": "putattmt1",
            "title": "myPutAttmt1",
            "_attachments": {
                "putattmt2": {
                    "length": 3,
                    // md5("abc")
                    "digest": "md5-900150983cd24fb0d6963f7d28e17f72"
                }
            }
        },
        "Check document"
    );

    // check attachment
    deepEqual(
        localstorage.getItem(
            "jio/localstorage/iputatt/iputatt/putattmt1/putattmt2"),
        "abc", "Check attachment"
3475 3476 3477 3478
    );

    o.jio.stop();
});
3479

3480
test ("Get", function(){
3481

3482 3483 3484
    // not sure these need to be run, because the index does not change
    // and only small modifications have been made to handle putAttachment
    // tests are from localStorage putAttachment
3485
    var o = generateTools(this);
3486

3487
    o.jio = JIO.newJio({
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
          "type": "indexed",
          "indices": [
              {"name":"indexA", "fields":["author"]},
              {"name":"indexAB", "fields":["author","year"]}
          ],
          "sub_storage": {
            "type": "local",
            "username": "iget",
            "application_name": "iget"
          }
      });
3499 3500 3501 3502 3503 3504 3505 3506 3507 3508

    // get inexistent document
    o.spy(o, "status", 404, "Get inexistent document");
    o.jio.get("get1", o.f);
    o.tick(o);

    // get inexistent attachment
    o.spy(o, "status", 404, "Get inexistent attachment");
    o.jio.get("get1/get2", o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
3509

3510 3511 3512 3513
    // adding a document
    o.doc_get1 = {
        "_id": "get1",
        "title": "myGet1"
Tristan Cavelier's avatar
Tristan Cavelier committed
3514
    };
3515
    localstorage.setItem("jio/localstorage/iget/iget/get1", o.doc_get1);
Tristan Cavelier's avatar
Tristan Cavelier committed
3516

3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
    // get document
    o.spy(o, "value", o.doc_get1, "Get document");
    o.jio.get("get1", o.f);
    o.tick(o);

    // get inexistent attachment (document exists)
    o.spy(o, "status", 404, "Get inexistent attachment (document exists)");
    o.jio.get("get1/get2", o.f);
    o.tick(o);

    // adding an attachment
    o.doc_get1["_attachments"] = {
        "get2": {
            "length": 2,
            // md5("de")
            "digest": "md5-5f02f0889301fd7be1ac972c11bf3e7d"
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
3534
    };
3535 3536
    localstorage.setItem("jio/localstorage/iget/iget/get1", o.doc_get1);
    localstorage.setItem("jio/localstorage/iget/iget/get1/get2", "de");
3537 3538 3539 3540 3541 3542

    // get attachment
    o.spy(o, "value", "de", "Get attachment");
    o.jio.get("get1/get2", o.f);
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
3543 3544
    o.jio.stop();
});
3545

3546 3547 3548 3549 3550 3551 3552 3553
test ("Remove", function(){

    // not sure these need to be run, because the index does not change
    // and only small modifications have been made to handle putAttachment
    // tests are from localStorage putAttachment
    var o = generateTools(this);

    o.jio = JIO.newJio({
3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564
      "type": "indexed",
      "indices": [
          {"name":"indexA", "fields":["author"]},
          {"name":"indexAB", "fields":["author","year"]}
      ],
      "sub_storage": {
        "type": "local",
        "username": "irem",
        "application_name": "irem"
      }
    });
3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595

    // remove inexistent document
    o.spy(o, "status", 404, "Remove inexistent document");
    o.jio.remove({"_id": "remove1"}, o.f);
    o.tick(o);

    // remove inexistent document/attachment
    o.spy(o, "status", 404, "Remove inexistent document/attachment");
    o.jio.remove({"_id": "remove1/remove2"}, o.f);
    o.tick(o);

    // adding a document
    o.jio.put({"_id": "remove1", "title": "myRemove1",
      "author": "Mr. President", "year": "2525"
    });
    o.tick(o);

    // adding a 2nd document with same keywords
    o.jio.put({"_id": "removeAlso", "title": "myRemove2",
      "author": "Martin Mustermann", "year": "2525"
    });
    o.tick(o);

    // remove document
    o.spy(o, "value", {"ok": true, "id": "remove1"}, "Remove document");
    o.jio.remove({"_id": "remove1"}, o.f);
    o.tick(o);

    // check index
    o.fakeIndex = {
      "_id": "irem_indices.json",
3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608
      "indexA": {
         "author": {
           "Martin Mustermann": ["removeAlso"]
          }
        },
      "indexAB": {
        "year": {
          "2525": ["removeAlso"]
        },
        "author": {
          "Martin Mustermann": ["removeAlso"]
          }
        }
Tristan Cavelier's avatar
Tristan Cavelier committed
3609
    };
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
    o.jio.get("irem_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);

    // check document
    o.spy(o, "status", 404, "Check if document has been removed");
    o.jio.get("remove1", o.f);
    o.tick(o);

    // adding a new document
    o.jio.put({"_id": "remove3",
        "title": "myRemove1",
        "author": "Mrs Sunshine",
        "year": "1234"
    });
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
3628

3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648
    // adding an attachment
    o.jio.putAttachment({"id":"remove3/removeAtt", "mimetype":"text/plain",
      "content":"hello"});
    o.tick(o);

    // add another attachment
    o.jio.putAttachment({"id":"remove3/removeAtt2", "mimetype":"text/plain",
      "content":"hello2"});
    o.tick(o);

    // remove attachment
    o.spy(o, "value", {"ok": true, "id": "remove3/removeAtt2"},
          "Remove one of multiple attachment");
    o.jio.remove({"_id": "remove3/removeAtt2"}, o.f);
    o.tick(o);

    // check index
    o.fakeIndex = {
      "_id": "irem_indices.json",
      "indexA": {
3649 3650 3651 3652
        "author":{
          "Martin Mustermann": ["removeAlso"],
          "Mrs Sunshine": ["remove3"]
        }
3653 3654
      },
      "indexAB": {
3655
        "year": {
3656
          "1234": ["remove3"],
3657 3658 3659
          "2525": ["removeAlso"]
        },
        "author": {
3660 3661
          "Martin Mustermann": ["removeAlso"],
          "Mrs Sunshine": ["remove3"]
3662
        }
3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680
      }
    };
    o.jio.get("irem_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);

    // remove document and attachment together
    o.spy(o, "value", {"ok": true, "id": "remove3"},
          "Remove one document and attachment together");
    o.jio.remove({"_id": "remove3"}, o.f);
    o.tick(o);

    // check index
    o.fakeIndex = {
      "_id": "irem_indices.json",
      "indexA": {
3681 3682 3683
        "author": {
          "Martin Mustermann": ["removeAlso"]
        }
3684 3685
      },
      "indexAB": {
3686 3687 3688 3689
        "year": {
          "2525": ["removeAlso"]
        },
        "author": {
3690
          "Martin Mustermann": ["removeAlso"]
3691
        }
3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708
      }
    };
    o.jio.get("irem_indices.json",function(err, response){
       o.actualIndex = response;
       deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
    });
    o.tick(o);

    // check attachment
    o.spy(o, "status", 404, "Check if attachment has been removed");
    o.jio.get("remove3/removeAtt", o.f);
    o.tick(o);

    // check document
    o.spy(o, "status", 404, "Check if document has been removed");
    o.jio.get("remove3", o.f);
    o.tick(o);
Tristan Cavelier's avatar
Tristan Cavelier committed
3709 3710 3711

    o.jio.stop();
});
3712

3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
test ("AllDocs", function () {

  var o = generateTools(this);

    o.jio = JIO.newJio({
      "type": "indexed",
      "indices": [
          {"name":"indexA", "fields":["author"]},
          {"name":"indexAB", "fields":["author","year"]}
      ],
      "sub_storage": {
        "type": "local",
        "username": "iall",
        "application_name": "iall"
      }
    });

  // adding documents
  o.all1 = { "_id": "dragon.doc",
    "title": "some title", "author": "Dr. No", "year": "1968"
  };
  o.spy (o, "value", {"ok": true, "id": "dragon.doc"}, "Put 1");
  o.jio.put(o.all1, o.f);
  o.tick(o);
  o.all2 = {"_id": "timemachine",
    "title": "hello world", "author": "Dr. Who", "year": "1968"
  }
  o.spy (o, "value", {"ok": true, "id": "timemachine"}, "Put 2");
  o.jio.put(o.all2, o.f);
  o.tick(o);
  o.all3 = {"_id": "rocket.ppt",
    "title": "sunshine.", "author": "Dr. Snuggles", "year": "1985"
  }
  o.spy (o, "value", {"ok": true, "id": "rocket.ppt"}, "Put 3");
  o.jio.put(o.all3, o.f);
  o.tick(o);
  o.all4 = {"_id": "stick.jpg",
    "title": "clouds", "author": "Dr. House", "year": "2005"
  }
  o.spy (o, "value", {"ok": true, "id": "stick.jpg"}, "Put 4");
  o.jio.put(o.all4, o.f);
  o.tick(o);

  // check index
  o.fakeIndex = {
    "_id": "iall_indices.json",
    "indexA": {
3760 3761 3762 3763 3764 3765
      "author": {
        "Dr. No": ["dragon.doc"],
        "Dr. Who": ["timemachine"],
        "Dr. Snuggles": ["rocket.ppt"],
        "Dr. House":["stick.jpg"]
      }
3766 3767
    },
    "indexAB": {
3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778
      "author": {
        "Dr. No": ["dragon.doc"],
        "Dr. Who": ["timemachine"],
        "Dr. Snuggles": ["rocket.ppt"],
        "Dr. House":["stick.jpg"]
      },
      "year": {
        "1968": ["dragon.doc", "timemachine"],
        "1985": ["rocket.ppt"],
        "2005":["stick.jpg"]
      }
3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812
    }
  };
  o.jio.get("iall_indices.json",function(err, response){
      o.actualIndex = response;
      deepEqual(o.actualIndex, o.fakeIndex, "Check index file");
  });
  o.tick(o);

  o.thisShouldBeTheAnswer = {
    "rows": [
      {"id": "dragon.doc", "key": "dragon.doc", "value": {} },
      {"id": "timemachine", "key": "timemachine", "value": {} },
      {"id": "rocket.ppt", "key": "rocket.ppt", "value": {} },
      {"id": "stick.jpg", "key": "stick.jpg", "value": {} }
    ],
    "total_rows": 4
  }
  o.spy(o, "value", o.thisShouldBeTheAnswer, "allDocs (served by index)");
  o.jio.allDocs(o.f);
  o.tick(o);

  o.thisShouldBeTheAnswer2 = {
    "rows": [
      {"id": "dragon.doc", "key": "dragon.doc", "value": {}, "doc": o.all1 },
      {"id": "timemachine", "key": "timemachine", "value": {}, "doc": o.all2 },
      {"id": "rocket.ppt", "key": "rocket.ppt", "value": {}, "doc": o.all3 },
      {"id": "stick.jpg", "key": "stick.jpg", "value": {}, "doc": o.all4 }
    ],
    "total_rows": 4
  }
  o.spy(o, "value", o.thisShouldBeTheAnswer2, "allDocs (include_docs)");
  o.jio.allDocs({"include_docs":true}, o.f);
  o.tick(o);

3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829
  // complex queries
  o.thisShouldBeTheAnswer3 = {"nothing here":"yet"}
  o.spy(o, "value", o.thisShouldBeTheAnswer3,
    "allDocs (complex queries year >= 1985)");
  o.jio.allDocs({
    "query":{
      "query":jIO.ComplexQueries.parse('(year: >= "1985" AND author:"D%")'),
      "filter": {
          "limit":[0,2],
          "sort_on":[['key','descending']],
          "select_list":['author','year']
      },
      "wildcard_character":'%'
    }
  }, o.f);
  o.tick(o);

3830 3831
  o.jio.stop();
});
3832
/*
Tristan Cavelier's avatar
Tristan Cavelier committed
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
module ('Jio CryptedStorage');

test ('Document save' , function () {
    var o = {}, clock = this.sandbox.useFakeTimers();
    clock.tick(base_tick);
    o.jio=JIO.newJio({type:'crypt',
                      username:'cryptsave',
                      password:'mypwd',
                      storage:{type:'local',
                               username:'cryptsavelocal',
3843
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877
    o.f = function (err,val) {
        if (err) {
            err = err.status;
        }
        deepEqual (err || val,{ok:true,id:'testsave'},'save ok');
    };
    this.spy(o,'f');
    o.jio.put({_id:'testsave',content:'contentoftest'},o.f);
    clock.tick(1000);
    if (!o.f.calledOnce) {
        ok (false, 'no response / too much results');
    }
    // encrypt 'testsave' with 'cryptsave:mypwd' password
    o.tmp = LocalOrCookieStorage.getItem( // '/' = '%2F'
        'jio/local/cryptsavelocal/jiotests/rZx5PJxttlf9QpZER%2F5x354bfX54QFa1');
    if (o.tmp) {
        delete o.tmp._last_modified;
        delete o.tmp._creation_date;
    }
    deepEqual (o.tmp,
               {_id:'rZx5PJxttlf9QpZER/5x354bfX54QFa1',
                content:'upZkPIpitF3QMT/DU5jM3gP0SEbwo1n81rMOfLE'},
               'Check if the document is realy encrypted');
    o.jio.stop();
});

test ('Document load' , function () {
    var o = {}, clock = this.sandbox.useFakeTimers();
    clock.tick(base_tick);
    o.jio=JIO.newJio({type:'crypt',
                      username:'cryptload',
                      password:'mypwd',
                      storage:{type:'local',
                               username:'cryptloadlocal',
3878
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907
    o.f = function (err,val) {
        deepEqual (err || val,{
            _id:'testload',content:'contentoftest',
            _last_modified:500,_creation_date:500},'load ok');
    };
    this.spy(o,'f');
    // encrypt 'testload' with 'cryptload:mypwd' password
    // and 'contentoftest' with 'cryptload:mypwd'
    o.doc = {
        _id:'hiG4H80pwkXCCrlLl1X0BD0BfWLZwDUX',
        content:'kSulH8Qo105dSKHcY2hEBXWXC9b+3PCEFSm1k7k',
        _last_modified:500,_creation_date:500};
    addFileToLocalStorage('cryptloadlocal','jiotests',o.doc);
    o.jio.get('testload',o.f);
    clock.tick(1000);
    if (!o.f.calledOnce) {
        ok (false, 'no response / too much results');
    }
    o.jio.stop();
});

test ('Get Document List', function () {
    var o = {}, clock = this.sandbox.useFakeTimers();
    clock.tick(base_tick);
    o.jio=JIO.newJio({type:'crypt',
                      username:'cryptgetlist',
                      password:'mypwd',
                      storage:{type:'local',
                               username:'cryptgetlistlocal',
3908
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
    o.f = function (err,val) {
        deepEqual (err || objectifyDocumentArray(val.rows),
                   objectifyDocumentArray(o.doc_list),'Getting list');
    };
    o.tick = function (tick) {
        clock.tick (tick || 1000);
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok (false, 'too much results');
            } else {
                ok (false, 'no response');
            }
        }
    };
    this.spy(o,'f');
    o.doc_list = [{
        id:'testgetlist1',key:'testgetlist1',value:{
            _last_modified:500,_creation_date:200}
    },{
        id:'testgetlist2',key:'testgetlist2',value:{
            _last_modified:300,_creation_date:300}
    }];
    o.doc_encrypt_list = [
        {_id:'541eX0WTMDw7rqIP7Ofxd1nXlPOtejxGnwOzMw',
         content:'/4dBPUdmLolLfUaDxPPrhjRPdA',
         _last_modified:500,_creation_date:200},
        {_id:'541eX0WTMDw7rqIMyJ5tx4YHWSyxJ5UjYvmtqw',
         content:'/4FBALhweuyjxxD53eFQDSm4VA',
         _last_modified:300,_creation_date:300}
    ];
    // encrypt with 'cryptgetlist:mypwd' as password
    LocalOrCookieStorage.setItem(
        'jio/local_file_name_array/cryptgetlistlocal/jiotests',
        [o.doc_encrypt_list[0]._id,o.doc_encrypt_list[1]._id]);
    LocalOrCookieStorage.setItem(
        'jio/local/cryptgetlistlocal/jiotests/'+o.doc_encrypt_list[0]._id,
        o.doc_encrypt_list[0]);
    LocalOrCookieStorage.setItem(
        'jio/local/cryptgetlistlocal/jiotests/'+o.doc_encrypt_list[1]._id,
        o.doc_encrypt_list[1]);
    o.jio.allDocs(o.f);
    o.tick(10000);

    o.jio.stop();
});

test ('Remove document', function () {
    var o = {}, clock = this.sandbox.useFakeTimers();
    clock.tick(base_tick);
    o.jio=JIO.newJio({type:'crypt',
                      username:'cryptremove',
                      password:'mypwd',
                      storage:{type:'local',
                               username:'cryptremovelocal',
3963
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008
    o.f = function (err,val) {
        deepEqual (err || val,{ok:true,id:'file'},'Document remove');
    };
    this.spy(o,'f');
    // encrypt with 'cryptremove:mypwd' as password
    o.doc = {_id:'JqCLTjyxQqO9jwfxD/lyfGIX+qA',
             content:'LKaLZopWgML6IxERqoJ2mUyyO',
             _last_modified:500,_creation_date:500};
    o.jio.remove({_id:'file'},o.f);
    clock.tick(1000);
    if (!o.f.calledOnce){
        ok (false, 'no response / too much results');
    }
    o.jio.stop();
});


module ('Jio ConflictManagerStorage');

test ('Simple methods', function () {
    // Try all the simple methods like saving, loading, removing a document and
    // getting a list of document without testing conflicts

    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick(base_tick);
    o.spy = function(value,message) {
        o.f = function(err,val) {
            deepEqual (err || val,value,message);
        };
        o.t.spy(o,'f');
    };
    o.tick = function (tick) {
        o.clock.tick(tick || 1000);
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok(false, 'too much results');
            } else {
                ok(false, 'no response');
            }
        }
    };
    o.jio = JIO.newJio({type:'conflictmanager',
                        username:'methods',
                        storage:{type:'local',
                                 username:'conflictmethods',
4009
                                 application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181
    // PUT
    o.spy({ok:true,id:'file.doc',rev:'1'},'saving "file.doc".');
    o.jio.put({_id:'file.doc',content:'content1'},function (err,val) {
        if (val) {
            o.rev1 = val.rev;
            val.rev = val.rev.split('-')[0];
        }
        o.f (err,val);
    });
    o.tick();
    // PUT with options
    o.spy({ok:true,id:'file2.doc',rev:'1',
           conflicts:{total_rows:0,rows:[]},
           revisions:{start:1,ids:['1']},
           revs_info:[{rev:'1',status:'available'}]},
          'saving "file2.doc".');
    o.jio.put({_id:'file2.doc',content:'yes'},
              {revs:true,revs_info:true,conflicts:true},
              function (err,val) {
                  if (val) {
                      o.rev2 = val.rev;
                      val.rev = val.rev.split('-')[0];
                      if (val.revs_info) {
                          if (val.revisions) {
                              makeRevsAccordingToRevsInfo(
                                  val.revisions,val.revs_info);
                          }
                          val.revs_info[0].rev =
                              val.revs_info[0].rev.split('-')[0];
                      }
                 }
                  o.f (err,val);
              });
    o.tick();

    // GET
    o.get_callback = function (err,val) {
        if (val) {
            val._rev = (val._rev?val._rev.split('-')[0]:'/');
            val._creation_date = (val._creation_date?true:undefined);
            val._last_modified = (val._last_modified?true:undefined);
        }
        o.f(err,val);
    };
    o.spy({_id:'file.doc',content:'content1',_rev:'1',
           _creation_date:true,_last_modified:true},'loading "file.doc".');
    o.jio.get('file.doc',o.get_callback);
    o.tick();
    // GET with options
    o.get_callback = function (err,val) {
        if (val) {
            val._rev = (val._rev?val._rev.split('-')[0]:'/');
            val._creation_date = (val._creation_date?true:undefined);
            val._last_modified = (val._last_modified?true:undefined);
            if (val._revs_info) {
                if (val._revisions) {
                    makeRevsAccordingToRevsInfo(
                        val._revisions,val._revs_info);
                }
                val._revs_info[0].rev =
                    val._revs_info[0].rev.split('-')[0];
            }
        }
        o.f(err,val);
    };
    o.spy({_id:'file2.doc',content:'yes',_rev:'1',
           _creation_date:true,_last_modified:true,
           _conflicts:{total_rows:0,rows:[]},
           _revisions:{start:1,ids:['1']},
           _revs_info:[{rev:'1',status:'available'}]},
          'loading "file2.doc".');
    o.jio.get('file2.doc',{revs:true,revs_info:true,conflicts:true},
              o.get_callback);
    o.tick();

    // allDocs
    o.spy({total_rows:2,rows:[{
        id:'file.doc',key:'file.doc',
        value:{_rev:'1',_creation_date:true,_last_modified:true}
    },{
        id:'file2.doc',key:'file2.doc',
        value:{_rev:'1',_creation_date:true,_last_modified:true}
    }]},'getting list.');
    o.jio.allDocs(function (err,val) {
        if (val) {
            var i;
            for (i = 0; i < val.total_rows; i+= 1) {
                val.rows[i].value._creation_date =
                    val.rows[i].value._creation_date?
                    true:undefined;
                val.rows[i].value._last_modified =
                    val.rows[i].value._last_modified?
                    true:undefined;
                val.rows[i].value._rev = val.rows[i].value._rev.split('-')[0];
            }
            // because the result can be disordered
            if (val.total_rows === 2 && val.rows[0].id === 'file2.doc') {
                var tmp = val.rows[0];
                val.rows[0] = val.rows[1];
                val.rows[1] = tmp;
            }
        }
        o.f(err,val);
    });
    o.tick();

    // remove
    o.spy({ok:true,id:'file.doc',rev:'2'},
          'removing "file.doc"');
    o.jio.remove({_id:'file.doc'},{rev:o.rev1},function (err,val) {
        if (val) {
            val.rev = val.rev?val.rev.split('-')[0]:undefined;
        }
        o.f(err,val);
    });
    o.tick();
    // remove with options
    o.spy({
        ok:true,id:'file2.doc',rev:'2',
        conflicts:{total_rows:0,rows:[]},
        revisions:{start:2,ids:['2',getHashFromRev(o.rev2)]},
        revs_info:[{rev:'2',status:'deleted'}]
    },'removing "file2.doc"');
    o.jio.remove(
        {_id:'file2.doc'},
        {rev:o.rev2,conflicts:true,revs:true,revs_info:true},
        function (err,val) {
            if (val) {
                val.rev = val.rev?val.rev.split('-')[0]:undefined;
                if (val.revs_info) {
                    if (val.revisions) {
                        makeRevsAccordingToRevsInfo(
                            val.revisions,val.revs_info);
                    }
                    val.revs_info[0].rev =
                        val.revs_info[0].rev.split('-')[0];
                }
            }
            o.f(err,val);
        });
    o.tick();

    o.spy(404,'loading document fail.');
    o.jio.get('file.doc',function (err,val) {
        if (err) {
            err = err.status;
        }
        o.f(err,val);
    });
    o.tick();

    o.jio.stop();
});

test ('Revision Conflict', function() {
    // Try to tests all revision conflict possibility

    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick (base_tick);
    o.spy = basic_spy_function;
    o.tick = basic_tick_function;

    o.localNamespace = 'jio/local/revisionconflict/jiotests/';
    o.rev={};
    o.checkContent = function (string,message) {
        ok (LocalOrCookieStorage.getItem(o.localNamespace + string),
            message || '"' + string + '" is saved.');
    };
    o.checkNoContent = function (string,message) {
        ok (!LocalOrCookieStorage.getItem(o.localNamespace + string),
            message || '"' + string + '" does not exists.');
    };
4182
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
4183
                            username:'revisionconflict',
4184
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
4185 4186
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
4187
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345
    // create a new file
    o.spy(o,'value',
          {ok:true,id:'file.doc',rev:'1',conflicts:{total_rows:0,rows:[]},
           revs_info:[{rev:'1',status:'available'}],
           revisions:{start:1,ids:['1']}},
          'new file "file.doc".');
    o.jio.put(
        {_id:'file.doc',content:'content1'},
        {revs:true,revs_info:true,conflicts:true},
        function (err,val) {
            if (val) {
                o.rev.first = val.rev;
                val.rev = val.rev?val.rev.split('-')[0]:undefined;
                if (val.revs_info) {
                    if (val.revisions) {
                        makeRevsAccordingToRevsInfo(
                            val.revisions,val.revs_info);
                    }
                    val.revs_info[0].rev =
                        val.revs_info[0].rev.split('-')[0];
                }
            }
            o.f(err,val);
        }
    );
    o.tick(o);
    o.checkContent('file.doc.'+o.rev.first);
    // modify the file
    o.spy(o,'value',
          {ok:true,id:'file.doc',rev:'2',
           conflicts:{total_rows:0,rows:[]},
           revisions:{start:2,ids:['2',getHashFromRev(o.rev.first)]},
           revs_info:[{rev:'2',status:'available'}]},
          'modify "file.doc", revision: "'+
          o.rev.first+'".');
    o.jio.put(
        {_id:'file.doc',content:'content2',_rev:o.rev.first},
        {revs:true,revs_info:true,conflicts:true},
        function (err,val) {
            if (val) {
                o.rev.second = val.rev;
                val.rev = val.rev?val.rev.split('-')[0]:undefined;
                if (val.revs_info) {
                    if (val.revisions) {
                        makeRevsAccordingToRevsInfo(
                            val.revisions,val.revs_info);
                    }
                    val.revs_info[0].rev =
                        val.revs_info[0].rev.split('-')[0];
                }
            }
            o.f(err,val);
        }
    );
    o.tick(o);
    o.checkContent('file.doc.'+o.rev.second);
    o.checkNoContent('file.doc.'+o.rev.first);
    // modify the file from the second revision instead of the third
    o.test_message = 'modify "file.doc", revision: "'+
        o.rev.first+'" -> conflict!';
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file.doc',content:'content3',_rev:o.rev.first},
        {revs:true,revs_info:true,conflicts:true},function (err,val) {
            o.f();
            var k;
            if (err) {
                o.rev.third = err.rev;
                err.rev = checkRev(err.rev);
                if (err.conflicts && err.conflicts.rows) {
                    o.tmp = err.conflicts;
                    o.solveConflict = checkConflictRow (err.conflicts.rows[0]);
                }
                for (k in {'error':0,'message':0,'reason':0,'statusText':0}) {
                    if (err[k]) {
                        delete err[k];
                    } else {
                        err[k] = 'ERROR: ' + k + ' is missing !';
                    }
                }
            }
            deepEqual(err||val,{
                rev:o.rev.third,
                conflicts:{total_rows:1,rows:[
                    {id:'file.doc',key:[o.rev.second,o.rev.third],
                     value:{_solveConflict:'function'}}]},
                status:409,
                // just one revision in the history, it does not keep older
                // revisions because it is not a revision manager storage.
                revisions:{start:1,ids:[getHashFromRev(o.rev.third)]},
                revs_info:[{rev:o.rev.second,status:'available'},
                           {rev:o.rev.third,status:'available'}]
            },o.test_message);
            ok (!revs_infoContains(err.revs_info,o.rev.first),
                'check if the first revision is not include to '+
                'the conflict list.');
            ok (revs_infoContains(err.revs_info,err.rev),
                'check if the new revision is include to '+
                'the conflict list.');
        });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.third);
    // loading test
    o.spy(o,'value',{_id:'file.doc',_rev:o.rev.third,content:'content3',
                     _conflicts:o.tmp},
          'loading "file.doc" -> conflict!');
    o.jio.get('file.doc',{conflicts:true},function (err,val) {
        var k;
        if (val) {
            if (val._conflicts && val._conflicts.rows) {
                checkConflictRow (val._conflicts.rows[0]);
            }
            for (k in {'_creation_date':0,'_last_modified':0}) {
                if (val[k]) {
                    delete val[k];
                } else {
                    val[k] = 'ERROR: ' + k + ' is missing !';
                }
            }
        }
        o.f(err,val);
    });
    o.tick(o);
    if (!o.solveConflict) { return ok(false,'Cannot to continue the tests'); }
    // solving conflict
    o.spy(o,'value',{ok:true,id:'file.doc',rev:'3'},
          'solve conflict "file.doc".');
    o.solveConflict(
        'content4',function (err,val) {
            if (val) {
                o.rev.forth = val.rev;
                val.rev = val.rev?val.rev.split('-')[0]:undefined;
            }
            o.f(err,val);
        });
    o.tick(o);
    o.checkContent('file.doc.'+o.rev.forth);
    o.checkNoContent('file.doc.'+o.rev.second);
    o.checkNoContent('file.doc.'+o.rev.third);
    o.jio.stop();
});

test ('Conflict in a conflict solving', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick (base_tick);
    o.spy = basic_spy_function;
    o.tick = basic_tick_function;

    o.localNamespace = 'jio/local/conflictconflict/jiotests/';
    o.rev={};
    o.checkContent = function (string,message) {
        ok (LocalOrCookieStorage.getItem(o.localNamespace + string),
            message || '"' + string + '" is saved.');
    };
    o.checkNoContent = function (string,message) {
        ok (!LocalOrCookieStorage.getItem(o.localNamespace + string),
            message || '"' + string + '" does not exists.');
    };
4346
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
4347
                            username:'conflictconflict',
4348
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
4349 4350
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
4351
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532
    // create a new file
    o.test_message = 'new file "file.doc", revision: "0".'
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file.doc',content:'content1'},
        {conflicts:true,revs:true,revs_info:true},
        function(err,val) {
            o.f();
            if (val) {
                o.rev.first = val.rev;
                val.rev = checkRev(val.rev);
            }
            deepEqual(err||val,{
                ok:true,id:'file.doc',rev:o.rev.first,
                conflicts:{total_rows:0,rows:[]},
                revisions:{start:1,ids:[getHashFromRev(o.rev.first)]},
                revs_info:[{rev:o.rev.first,status:'available'}]
            },o.test_message);
        });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.first);
    // modify the file from the second revision instead of the third
    o.test_message = 'modify "file.doc", revision: "0" -> conflict!';
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file.doc',content:'content2'},
        {conflicts:true,revs:true,revs_info:true},
        function (err,val) {
        o.f();
        var k;
        if (err) {
            o.rev.second = err.rev;
            err.rev = checkRev(err.rev);
            if (err.conflicts && err.conflicts.rows) {
                o.solveConflict = checkConflictRow (err.conflicts.rows[0]);
            }
            for (k in {'error':0,'message':0,'reason':0,'statusText':0}) {
                if (err[k]) {
                    delete err[k];
                } else {
                    err[k] = 'ERROR: ' + k + ' is missing !';
                }
            }
        }
        deepEqual(err||val,{
            rev:o.rev.second,
            conflicts:{total_rows:1,rows:[
                {id:'file.doc',key:[o.rev.first,o.rev.second],
                 value:{_solveConflict:'function'}}]},
            status:409,
            // just one revision in the history, it does not keep older
            // revisions because it is not a revision manager storage.
            revisions:{start:1,ids:[getHashFromRev(o.rev.second)]},
            revs_info:[{rev:o.rev.first,status:'available'},
                       {rev:o.rev.second,status:'available'}]
        },o.test_message);
    });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.second);
    if (!o.solveConflict) { return ok(false,'Cannot to continue the tests'); }
    // saving another time
    o.test_message = 'modify "file.doc" when solving, revision: "'+
        o.rev.first+'" -> conflict!';
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file.doc',content:'content3',_rev:o.rev.first},
        {conflicts:true,revs:true,revs_info:true},
        function(err,val){
            o.f();
            if (err) {
                o.rev.third = err.rev;
                err.rev = checkRev(err.rev);
                if (err.conflicts && err.conflicts.rows) {
                    checkConflictRow (err.conflicts.rows[0]);
                }
                for (k in {'error':0,'message':0,'reason':0,'statusText':0}) {
                    if (err[k]) {
                        delete err[k];
                    } else {
                        err[k] = 'ERROR: ' + k + ' is missing !';
                    }
                }
            }
            deepEqual(err||val,{
                rev:o.rev.third,
                conflicts:{total_rows:1,rows:[
                    {id:'file.doc',key:[o.rev.second,o.rev.third],
                     value:{_solveConflict:'function'}}]},
                status:409,
                // just one revision in the history, it does not keep older
                // revisions because it is not a revision manager storage.
                revisions:{start:2,ids:[getHashFromRev(o.rev.third),
                                        getHashFromRev(o.rev.first)]},
                revs_info:[{rev:o.rev.second,status:'available'},
                           {rev:o.rev.third,status:'available'}]
            },o.test_message);
        });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.third);
    o.checkNoContent ('file.doc.'+o.rev.first);
    // solving first conflict
    o.test_message = 'solving conflict "file.doc" -> conflict!';
    o.f = o.t.spy();
    o.solveConflict(
        'content4',{conflicts:true,revs:true,revs_info:true},
        function (err,val) {
            o.f();
            if (err) {
                o.rev.forth = err.rev;
                err.rev = checkRev(err.rev);
                if (err.conflicts && err.conflicts.rows) {
                    o.solveConflict = checkConflictRow (err.conflicts.rows[0]);
                }
                for (k in {'error':0,'message':0,'reason':0,'statusText':0}) {
                    if (err[k]) {
                        delete err[k];
                    } else {
                        err[k] = 'ERROR: ' + k + ' is missing !';
                    }
                }
            }
            deepEqual(err||val,{
                rev:o.rev.forth,
                conflicts:{total_rows:1,rows:[
                    {id:'file.doc',key:[o.rev.third,o.rev.forth],
                     value:{_solveConflict:'function'}}]},
                status:409,
                // just one revision in the history, it does not keep older
                // revisions because it is not a revision manager storage.
                revisions:{start:2,ids:[getHashFromRev(o.rev.forth),
                                        getHashFromRev(o.rev.second)]},
                revs_info:[{rev:o.rev.third,status:'available'},
                           {rev:o.rev.forth,status:'available'}]
            },o.test_message);
        });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.forth);
    o.checkNoContent ('file.doc.'+o.rev.second);
    if (!o.solveConflict) { return ok(false,'Cannot to continue the tests'); }
    // solving last conflict
    o.test_message = 'solving last conflict "file.doc".';
    o.f = o.t.spy();
    o.solveConflict(
        'content5',{conflicts:true,revs:true,revs_info:true},
        function (err,val) {
            if (val) {
                o.rev.fifth = val.rev;
                val.rev = checkRev(val.rev);
            }
            deepEqual(err||val,{
                ok:true,id:'file.doc',rev:o.rev.fifth,
                conflicts:{total_rows:0,rows:[]},
                revisions:{start:3,ids:[getHashFromRev(o.rev.fifth),
                                        getHashFromRev(o.rev.forth),
                                        getHashFromRev(o.rev.second)]},
                revs_info:[{rev:o.rev.fifth,status:'available'}]
            },o.test_message);
            o.f();
        });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.fifth);

    o.jio.stop();
});

test ('Remove revision conflict', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick (base_tick);
    o.spy = basic_spy_function;
    o.tick = basic_tick_function;

    o.localNamespace = 'jio/local/removeconflict/jiotests/';
    o.rev={};
    o.checkContent = function (string,message) {
        ok (LocalOrCookieStorage.getItem(o.localNamespace + string),
            message || '"' + string + '" is saved.');
    };
    o.checkNoContent = function (string,message) {
        ok (!LocalOrCookieStorage.getItem(o.localNamespace + string),
            message || '"' + string + '" does not exists.');
    };
4533
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
4534
                            username:'removeconflict',
4535
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
4536 4537
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
4538
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762

    o.test_message = 'new file "file.doc", revision: "0".';
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file.doc',content:'content1'},
        {conflicts:true,revs:true,revs_info:true},
        function(err,val) {
            o.f();
            if (val) {
                o.rev.first = val.rev;
                val.rev = checkRev(val.rev);
            }
            deepEqual(err||val,{
                ok:true,id:'file.doc',rev:o.rev.first,
                conflicts:{total_rows:0,rows:[]},
                revisions:{start:1,ids:[getHashFromRev(o.rev.first)]},
                revs_info:[{rev:o.rev.first,status:'available'}]
            },o.test_message);
        });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.first);

    o.test_message = 'remove "file.doc", revision: "wrong" -> conflict!';
    o.f = o.t.spy();
    o.jio.remove(
        {_id:'file.doc'},
        {conflicts:true,revs:true,revs_info:true,rev:'wrong'},
        function (err,val) {
            o.f();
            if (err) {
                o.rev.second = err.rev;
                err.rev = checkRev(err.rev);
                if (err.conflicts && err.conflicts.rows) {
                    o.solveConflict = checkConflictRow (err.conflicts.rows[0]);
                }
                for (k in {'error':0,'message':0,'reason':0,'statusText':0}) {
                    if (err[k]) {
                        delete err[k];
                    } else {
                        err[k] = 'ERROR: ' + k + ' is missing !';
                    }
                }
            }
            deepEqual(err||val,{
                rev:o.rev.second,
                conflicts:{total_rows:1,rows:[
                    {id:'file.doc',key:[o.rev.first,o.rev.second],
                     value:{_solveConflict:'function'}}]},
                status:409,
                // just one revision in the history, it does not keep older
                // revisions because it is not a revision manager storage.
                revisions:{start:1,ids:[getHashFromRev(o.rev.second)]},
                revs_info:[{rev:o.rev.first,status:'available'},
                           {rev:o.rev.second,status:'deleted'}]
            },o.test_message);
        });
    o.tick(o);

    o.test_message = 'new file again "file.doc".';
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file.doc',content:'content2'},
        {conflicts:true,revs:true,revs_info:true},
        function (err,val) {
            o.f();
            if (err) {
                o.rev.third = err.rev;
                err.rev = checkRev(err.rev);
                if (err.conflicts && err.conflicts.rows) {
                    o.solveConflict = checkConflictRow (err.conflicts.rows[0]);
                }
                for (k in {'error':0,'message':0,'reason':0,'statusText':0}) {
                    if (err[k]) {
                        delete err[k];
                    } else {
                        err[k] = 'ERROR: ' + k + ' is missing !';
                    }
                }
            }
            deepEqual(err||val,{
                rev:o.rev.third,
                conflicts:{total_rows:1,rows:[
                    {id:'file.doc',key:[o.rev.first,o.rev.second,o.rev.third],
                     value:{_solveConflict:'function'}}]},
                status:409,
                // just one revision in the history, it does not keep older
                // revisions because it is not a revision manager storage.
                revisions:{start:1,ids:[getHashFromRev(o.rev.third)]},
                revs_info:[{rev:o.rev.first,status:'available'},
                           {rev:o.rev.second,status:'deleted'},
                           {rev:o.rev.third,status:'available'}]
            },o.test_message);
        });
    o.tick(o);
    o.checkContent ('file.doc.'+o.rev.third);

    o.test_message = 'remove "file.doc", revision: "'+o.rev.first+
        '" -> conflict!'
    o.f = o.t.spy();
    o.jio.remove(
        {_id:'file.doc'},
        {conflicts:true,revs:true,revs_info:true,rev:o.rev.first},
        function (err,val) {
            o.f();
            if (err) {
                o.rev.forth = err.rev;
                err.rev = checkRev(err.rev);
                if (err.conflicts && err.conflicts.rows) {
                    o.solveConflict = checkConflictRow (err.conflicts.rows[0]);
                }
                for (k in {'error':0,'message':0,'reason':0,'statusText':0}) {
                    if (err[k]) {
                        delete err[k];
                    } else {
                        err[k] = 'ERROR: ' + k + ' is missing !';
                    }
                }
            }
            deepEqual(err||val,{
                rev:o.rev.forth,
                conflicts:{total_rows:1,rows:[
                    {id:'file.doc',key:[o.rev.second,o.rev.third,o.rev.forth],
                     value:{_solveConflict:'function'}}]},
                status:409,
                // just one revision in the history, it does not keep older
                // revisions because it is not a revision manager storage.
                revisions:{start:2,ids:[getHashFromRev(o.rev.forth),
                                        getHashFromRev(o.rev.first)]},
                revs_info:[{rev:o.rev.second,status:'deleted'},
                           {rev:o.rev.third,status:'available'},
                           {rev:o.rev.forth,status:'deleted'}]
            },o.test_message);
        });
    o.tick(o);
    o.checkNoContent ('file.doc.'+o.rev.first);
    o.checkNoContent ('file.doc.'+o.rev.forth);

    if (!o.solveConflict) { return ok(false, 'Cannot continue the tests'); }
    o.test_message = 'solve "file.doc"';
    o.f = o.t.spy();
    o.solveConflict({conflicts:true,revs:true,revs_info:true},function(err,val){
        o.f();
        if (val) {
            o.rev.fifth = val.rev;
            val.rev = checkRev(val.rev);
        }
        deepEqual(err||val,{
            ok:true,id:'file.doc',rev:o.rev.fifth,
            conflicts:{total_rows:0,rows:[]},
            revisions:{start:3,ids:[getHashFromRev(o.rev.fifth),
                                    getHashFromRev(o.rev.forth),
                                    getHashFromRev(o.rev.first)]},
            revs_info:[{rev:o.rev.fifth,status:'deleted'}]
        },o.test_message);
    });
    o.tick(o);
    o.checkNoContent ('file.doc.'+o.rev.second);
    o.checkNoContent ('file.doc.'+o.rev.forth);
    o.checkNoContent ('file.doc.'+o.rev.fifth);

    o.test_message = 'save "file3.doc"';
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file3.doc',content:'content3'},
        function(err,val) {
            o.f();
            if (val) {
                o.rev.sixth = val.rev;
                val.rev = checkRev(val.rev);
            }
            deepEqual(err||val,{
                ok:true,id:'file3.doc',rev:o.rev.sixth
            },o.test_message);
        });
    o.tick(o);
    o.test_message = 'save "file3.doc", rev "'+o.rev.sixth+'"';
    o.f = o.t.spy();
    o.jio.put(
        {_id:'file3.doc',content:'content3',_rev:o.rev.sixth},
        function(err,val) {
            o.f();
            if (val) {
                o.rev.seventh = val.rev;
                val.rev = checkRev(val.rev);
            }
            deepEqual(err||val,{
                ok:true,id:'file3.doc',rev:o.rev.seventh
            },o.test_message);
        });
    o.tick(o);

    o.test_message = 'remove last "file3.doc"';
    o.f = o.t.spy();
    o.jio.remove(
        {_id:'file3.doc'},
        {conflicts:true,revs:true,revs_info:true,rev:'last'},
        function (err,val) {
            o.f();
            if (val) {
                o.rev.eighth = val.rev;
                val.rev = checkRev(val.rev);
            }
            deepEqual(err||val,{
                ok:true,id:'file3.doc',
                rev:o.rev.eighth,
                conflicts:{total_rows:0,rows:[]},
                // just one revision in the history, it does not keep older
                // revisions because it is not a revision manager storage.
                revisions:{start:3,ids:[getHashFromRev(o.rev.eighth),
                                        getHashFromRev(o.rev.seventh),
                                        getHashFromRev(o.rev.sixth)]},
                revs_info:[{rev:o.rev.eighth,status:'deleted'}]
            },o.test_message);
        });
    o.tick(o);

    o.jio.stop();
});

test ('Load Revisions', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick (base_tick);
    o.spy = basic_spy_function;
    o.tick = basic_tick_function;
4763
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
4764
                            username:'loadrevisions',
4765
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
4766 4767
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
4768
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783
    o.spy(o,'status',404,'load file rev:1,','f'); // 12 === Replaced
    o.spy(o,'status',404,'load file rev:2','g');
    o.spy(o,'status',404,'and load file rev:3 at the same time','h');
    o.jio.get('file',{rev:'1'},o.f);
    o.jio.get('file',{rev:'2'},o.g);
    o.jio.get('file',{rev:'3'},o.h);
    o.tick(o,1000,'f'); o.tick(o,0,'g'); o.tick(o,0,'h');
    o.jio.stop();
});

test ('Get revision List', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick (base_tick);
    o.spy = basic_spy_function;
    o.tick = basic_tick_function;
4784
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
4785
                            username:'getrevisionlist',
4786
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
4787 4788 4789
    o.rev = {};
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
4790
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891
    o.spy(o,'value',{total_rows:0,rows:[]},'Get revision list');
    o.jio.allDocs(o.f);
    o.tick(o);

    o.spy(o,'value',{total_rows:0,rows:[],conflicts:{total_rows:0,rows:[]}},
          'Get revision list with informations');
    o.jio.allDocs({conflicts:true,revs:true,info_revs:true},o.f);
    o.tick(o);

    o.spy(o,'jobstatus','done','saving file');
    o.jio.put({_id:'file',content:'content file'},function (err,val) {
        o.rev.file1 = val?val.rev:undefined;
        o.f(err,val);
    });
    o.tick(o);
    o.spy(o,'jobstatus','done','saving memo');
    o.jio.put({_id:'memo',content:'content memo'},function (err,val) {
        o.rev.memo1 = val?val.rev:undefined;
        o.f(err,val);
    });
    o.tick(o);
    o.spy(o,'status',409,'saving memo conflict');
    o.jio.put({_id:'memo',content:'content memo'},function (err,val) {
        o.rev.memo2 = err?err.rev:undefined;
        o.f(err,val);
    });
    o.tick(o);

    o.f = o.t.spy();
    o.jio.allDocs(function (err,val) {
        var i;
        if (val) {
            for (i = 0; i < val.total_rows; i+= 1) {
                val.rows[i].value._creation_date =
                    val.rows[i].value._creation_date?true:undefined;
                val.rows[i].value._last_modified =
                    val.rows[i].value._last_modified?true:undefined;
                o.rev[i] = checkRev (val.rows[i].value._rev);
            }
        }
        deepEqual(err||val,{total_rows:2,rows:[{
            id:'file',key:'file',value:{
                _creation_date:true,_last_modified:true,_rev:o.rev[0]
            }
        },{
            id:'memo',key:'memo',value:{
                _creation_date:true,_last_modified:true,_rev:o.rev[1]
            }
        }]},'Get revision list after adding 2 files');
        o.f();
    });
    o.tick(o);

    o.f = o.t.spy();
    o.jio.allDocs(
        {conflicts:true,revs:true,revs_info:true},
        function (err,val) {
            var i;
            if (val) {
                for (i = 0; i < val.total_rows; i+= 1) {
                    val.rows[i].value._creation_date =
                        val.rows[i].value._creation_date?true:undefined;
                    val.rows[i].value._last_modified =
                        val.rows[i].value._last_modified?true:undefined;
                    if (val.conflicts && val.conflicts.rows) {
                        o.solveConflict =
                            checkConflictRow (val.conflicts.rows[0]);
                    }
                }
            }
            deepEqual(err||val,{
                total_rows:2,rows:[{
                    id:'file',key:'file',value:{
                        _creation_date:true,_last_modified:true,
                        _revisions:{start:1,ids:[getHashFromRev(o.rev.file1)]},
                        _rev:o.rev.file1,_revs_info:[{
                            rev:o.rev.file1,status:'available'
                        }]
                    }
                },{
                    id:'memo',key:'memo',value:{
                        _creation_date:true,_last_modified:true,
                        _revisions:{start:1,ids:[getHashFromRev(o.rev.memo2)]},
                        _rev:o.rev.memo2,_revs_info:[{
                            rev:o.rev.memo1,status:'available'
                        },{
                            rev:o.rev.memo2,status:'available'
                        }]
                    }
                }],
                conflicts:{total_rows:1,rows:[{
                    id:'memo',key:[o.rev.memo1,o.rev.memo2],
                    value:{_solveConflict:'function'}
                }]}
            },'Get revision list with informations after adding 2 files');
            o.f();
        });
    o.tick(o);

    o.jio.stop();
});
4892
*/
Tristan Cavelier's avatar
Tristan Cavelier committed
4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910
};                              // end thisfun

if (window.requirejs) {
    require.config ({
        paths: {
            jiotestsloader: './jiotests.loader',

            jQueryAPI: '../lib/jquery/jquery',
            jQuery: '../js/jquery.requirejs_module',
            JIO: '../src/jio',
            JIODummyStorages: '../src/jio.dummystorages',
            JIOStorages: '../src/jio.storage',
            SJCLAPI:'../lib/sjcl/sjcl.min',
            SJCL:'../js/sjcl.requirejs_module'
        }
    });
    require(['jiotestsloader'],thisfun);
} else {
Tristan Cavelier's avatar
Tristan Cavelier committed
4911
    thisfun ({JIO:jIO});
Tristan Cavelier's avatar
Tristan Cavelier committed
4912 4913 4914
}

}());