jiotests.js 119 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
},
Tristan Cavelier's avatar
Tristan Cavelier committed
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 145 146 147 148 149 150 151 152 153 154
getXML = function (url) {
    var tmp = '';
    $.ajax({
      url: url,
      async: false,
      dataType: 'text',
      success: function (xml) {
        tmp=xml;
      }
    });
    return tmp;
Tristan Cavelier's avatar
Tristan Cavelier committed
155 156 157 158
},
objectifyDocumentArray = function (array) {
    var obj = {}, k;
    for (k = 0; k < array.length; k += 1) {
Tristan Cavelier's avatar
Tristan Cavelier committed
159
        obj[array[k]._id] = array[k];
Tristan Cavelier's avatar
Tristan Cavelier committed
160 161 162
    }
    return obj;
},
Tristan Cavelier's avatar
Tristan Cavelier committed
163 164
getLastJob = function (id) {
    return (localstorage.getItem("jio/job_array/"+id) || [undefined]).pop();
Tristan Cavelier's avatar
Tristan Cavelier committed
165
},
Tristan Cavelier's avatar
Tristan Cavelier committed
166 167 168
generateTools = function (sinon) {
    var o = {};
    o.t = sinon;
169
    o.server = o.t.sandbox.useFakeServer();
Tristan Cavelier's avatar
Tristan Cavelier committed
170 171 172 173
    o.clock = o.t.sandbox.useFakeTimers();
    o.clock.tick(base_tick);
    o.spy = basicSpyFunction;
    o.tick = basicTickFunction;
174

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

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

Tristan Cavelier's avatar
Tristan Cavelier committed
252 253 254 255 256 257 258 259 260
//// 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;
};
261

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
    });

Tristan Cavelier's avatar
Tristan Cavelier committed
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);

Tristan Cavelier's avatar
Tristan Cavelier committed
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

Tristan Cavelier's avatar
Tristan Cavelier committed
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
    });

Tristan Cavelier's avatar
Tristan Cavelier committed
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);

Tristan Cavelier's avatar
Tristan Cavelier committed
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 1074 1075 1076 1077 1078
test ("AllDocs", function(){

    var o = generateTools(this);

    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
    });

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

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

Tristan Cavelier's avatar
Tristan Cavelier committed
1090
});
Tristan Cavelier's avatar
Tristan Cavelier committed
1091

1092 1093 1094 1095 1096 1097 1098 1099
module ( "Jio Revision Storage + Local Storage" );

test ("Post", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1100
        "sub_storage": {
1101 1102
            "type": "local",
            "username": "urevpost",
1103
            "application_name": "arevpost"
1104 1105
        }
    });
1106
    o.localpath = "jio/localstorage/urevpost/arevpost";
1107 1108

    // post without id
1109
    o.revisions = {"start": 0, "ids": []};
1110 1111 1112
    o.spy (o, "status", undefined, "Post without id");
    o.jio.post({}, function (err, response) {
        o.f.apply(arguments);
1113 1114 1115
        o.uuid = (err || response).id;
        ok(isUuid(o.uuid), "Uuid should look like " +
           "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx : " + o.uuid);
1116 1117
    });
    o.tick(o);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    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"
    );
1141 1142 1143

    // post non empty document
    o.doc = {"_id": "post1", "title": "myPost1"};
Tristan Cavelier's avatar
Tristan Cavelier committed
1144
    o.rev = "1-"+generateRevisionHash(o.doc, o.revisions);
1145 1146 1147 1148 1149 1150 1151
    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(
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        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"
1168 1169 1170 1171
    );

    // post and document already exists
    o.doc = {"_id": "post1", "title": "myPost2"};
Tristan Cavelier's avatar
Tristan Cavelier committed
1172
    o.rev = "1-"+generateRevisionHash(o.doc, o.revisions);
1173 1174 1175 1176 1177 1178
    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);

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    // 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"
    );

1200 1201
    // post + revision
    o.doc = {"_id": "post1", "_rev": o.rev, "title": "myPost2"};
Tristan Cavelier's avatar
Tristan Cavelier committed
1202 1203
    o.revisions = {"start": 1, "ids": [o.rev.split('-')[1]]};
    o.rev = "2-"+generateRevisionHash(o.doc, o.revisions);
1204 1205 1206 1207 1208 1209 1210 1211 1212
    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;
1213
    delete o.doc._rev;
1214
    deepEqual(
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
        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"
1231 1232 1233 1234 1235 1236
    );

    o.jio.stop();

});

1237 1238 1239 1240 1241 1242
test ("Put", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1243
        "sub_storage": {
1244 1245
            "type": "local",
            "username": "urevput",
1246
            "application_name": "arevput"
1247 1248
        }
    });
1249
    o.localpath = "jio/localstorage/urevput/arevput";
1250 1251 1252 1253 1254 1255 1256 1257 1258

    // 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"};
Tristan Cavelier's avatar
Tristan Cavelier committed
1259 1260
    o.revisions = {"start": 0, "ids": []};
    o.rev = "1-"+generateRevisionHash(o.doc, o.revisions);
1261 1262 1263 1264 1265 1266
    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
1267
    o.doc._id = "put1." + o.rev;
1268
    deepEqual(
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
        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"
1287 1288 1289 1290 1291 1292 1293
    );

    // put and document already exists
    o.spy (o, "status", 409, "Update the document");
    o.jio.put({"_id": "put1", "title": "myPut2"}, o.f);
    o.tick(o);

1294 1295

    // put + revision
1296
    o.doc = {"_id": "put1", "_rev": o.rev, "title": "myPut2"};
Tristan Cavelier's avatar
Tristan Cavelier committed
1297 1298
    o.revisions = {"start": 1, "ids": [o.rev.split('-')[1]]};
    o.rev = "2-"+generateRevisionHash(o.doc, o.revisions);
1299 1300 1301 1302 1303
    o.spy (o, "status", undefined, "Put + revision");
    o.jio.put(o.doc, o.f);
    o.tick(o);

    // check document
1304
    o.doc._id = "put1." + o.rev;
1305
    delete o.doc._rev;
1306
    deepEqual(
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        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"
1322 1323 1324 1325 1326 1327
    );

    o.jio.stop();

});

1328 1329 1330 1331 1332 1333
test ("Get", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1334
        "sub_storage": {
1335 1336
            "type": "local",
            "username": "urevget",
1337
            "application_name": "arevget"
1338 1339 1340 1341
        }
    });
    o.localpath = "jio/localstorage/urevget/arevget";

Tristan Cavelier's avatar
Tristan Cavelier committed
1342 1343
    // get inexistent document
    o.spy(o, "status", 404, "Get inexistent document (winner)");
1344 1345 1346
    o.jio.get("get1", o.f);
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
1347 1348
    // get inexistent attachment
    o.spy(o, "status", 404, "Get inexistent attachment (winner)");
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    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
1361 1362 1363 1364 1365 1366 1367 1368 1369
    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);
1370 1371 1372 1373
    o.tick(o);

    // adding two documents
    o.doctree = {"children":[{
1374 1375 1376
        "rev": "1-rev1", "status": "available", "children": []
    },{
        "rev": "1-rev2", "status": "available", "children": [{
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
            "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
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    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,
1397
          "Get document (winner, after posting another one)");
1398 1399
    o.jio.get("get1", {"revs_info": true, "revs": true, "conflicts": true},
              o.f);
1400 1401
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
1402 1403
    // get inexistent specific document
    o.spy(o, "status", 404, "Get document (inexistent specific revision)");
1404 1405 1406 1407
    o.jio.get("get1", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev0"
    }, o.f);
1408 1409 1410
    o.tick(o);

    // get specific document
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    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);
1423 1424
    o.tick(o);

1425 1426 1427 1428
    // adding an attachment
    o.attmt_myget2 = {
        "get2": {
            "length": 3,
1429 1430
            "digest": "md5-dontcare",
            "revpos": 1
1431 1432
        }
    };
1433 1434
    o.doc_myget2["_attachments"] = o.attmt_myget2;
    o.doc_myget3["_attachments"] = o.attmt_myget2;
1435
    localstorage.setItem(o.localpath+"/get1.1-rev2", o.doc_myget2);
1436
    localstorage.setItem(o.localpath+"/get1.2-rev3", o.doc_myget3);
1437
    localstorage.setItem(o.localpath+"/get1.1-rev2/get2", "abc");
1438 1439 1440 1441 1442 1443

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

Tristan Cavelier's avatar
Tristan Cavelier committed
1444 1445
    // get inexistent attachment specific rev
    o.spy(o, "status", 404, "Get inexistent attachment (specific revision)");
1446 1447 1448 1449
    o.jio.get("get1/get2", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev1"
    }, o.f);
1450 1451 1452 1453
    o.tick(o);

    // get attachment specific rev
    o.spy(o, "value", "abc", "Get attachment (specific revision)");
1454 1455 1456 1457
    o.jio.get("get1/get2", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev2"
    }, o.f);
1458 1459
    o.tick(o);

Sven Franck's avatar
Sven Franck committed
1460
    // get document with attachment (specific revision)
1461
    o.doc_myget2_cloned["_attachments"] = o.attmt_myget2;
1462
    o.spy(o, "value", o.doc_myget2_cloned,
1463
          "Get document which have an attachment (specific revision)");
1464 1465 1466 1467
    o.jio.get("get1", {
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": "1-rev2"
    }, o.f);
1468 1469 1470
    o.tick(o);

    // get document with attachment (winner)
1471 1472 1473
    o.doc_myget3_cloned["_attachments"] = o.attmt_myget2;
    o.spy(o, "value", o.doc_myget3_cloned,
          "Get document which have an attachment (winner)");
1474 1475
    o.jio.get("get1", {"revs_info": true, "revs": true, "conflicts": true},
              o.f);
1476 1477 1478 1479 1480 1481
    o.tick(o);

    o.jio.stop();

});

Sven Franck's avatar
Sven Franck committed
1482 1483 1484 1485 1486 1487
test ("Remove", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1488
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
1489 1490
            "type": "local",
            "username": "urevrem",
1491
            "application_name": "arevrem"
Sven Franck's avatar
Sven Franck committed
1492 1493 1494 1495
        }
    });
    o.localpath = "jio/localstorage/urevrem/arevrem";

1496
    // 1. remove document without revision
1497
    o.spy (o, "status", 404,
Tristan Cavelier's avatar
Tristan Cavelier committed
1498
           "Remove document (no doctree, no revision)");
1499 1500 1501
    o.jio.remove({"_id":"remove1"}, o.f);
    o.tick(o);

1502
    // 2. remove attachment without revision
1503
    o.spy (o, "status", 404,
Tristan Cavelier's avatar
Tristan Cavelier committed
1504
           "Remove attachment (no doctree, no revision)");
1505 1506 1507
    o.jio.remove({"_id":"remove1/remove2"}, o.f);
    o.tick(o);

Sven Franck's avatar
Sven Franck committed
1508 1509 1510 1511
    // adding two documents
    o.doc_myremove1 = {"_id": "remove1", "title": "myRemove1"};
    o.doc_myremove2 = {"_id": "remove1", "title": "myRemove2"};

1512
    o.very_old_rev = "1-veryoldrev";
Sven Franck's avatar
Sven Franck committed
1513

1514 1515
    localstorage.setItem(o.localpath+"/remove1."+o.very_old_rev,
                         o.doc_myremove1);
Sven Franck's avatar
Sven Franck committed
1516 1517 1518 1519 1520 1521
    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
1522 1523
            "digest": "md5-dontcare",
            "revpos":1
Sven Franck's avatar
Sven Franck committed
1524 1525 1526
        },
    };
    o.doc_myremove1 = {"_id": "remove1", "title": "myRemove1",
1527
                       "_attachments":o.attmt_myremove1};
1528 1529
    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
1530 1531 1532 1533 1534 1535 1536 1537

    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": []
        }]
1538 1539 1540
    },{
        "rev": "1-rev2", "status": "available", "children": []
    }]};
Sven Franck's avatar
Sven Franck committed
1541 1542
    localstorage.setItem(o.localpath+"/remove1.revision_tree.json", o.doctree);

1543
    // 3. remove non existing attachment with revision
Sven Franck's avatar
Sven Franck committed
1544 1545
    o.spy(o, "status", 404,
          "Remove NON-existing attachment (revision)");
Sven Franck's avatar
Sven Franck committed
1546 1547 1548
    o.jio.remove({"_id":"remove1.1-rev2/remove0","_rev":o.old_rev}, o.f);
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
1549 1550 1551
    o.revisions = {"start": 2, "ids":[
        o.old_rev.split('-')[1], o.very_old_rev.split('-')[1]
    ]};
Sven Franck's avatar
Sven Franck committed
1552
    o.doc_myremove1 = {"_id":"remove1/remove2","_rev":o.old_rev};
1553
    o.rev = "3-"+generateRevisionHash(o.doc_myremove1, o.revisions);
Sven Franck's avatar
Sven Franck committed
1554

1555
    // 4. remove existing attachment with revision
Sven Franck's avatar
Sven Franck committed
1556
    o.spy (o, "value", {"ok": true, "id": "remove1."+o.rev, "rev": o.rev},
Tristan Cavelier's avatar
Tristan Cavelier committed
1557
           "Remove existing attachment (revision)");
1558 1559 1560 1561
    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
1562 1563
        "rev": o.very_old_rev, "status": "available", "children": [{
            "rev": o.old_rev, "status": "available", "children": [{
1564
                "rev": o.rev, "status": "available", "children": []
Sven Franck's avatar
Sven Franck committed
1565 1566
            }]
        }]
1567 1568 1569
    },{
        "rev": "1-rev2", "status": "available", "children": []
    }]};
Sven Franck's avatar
Sven Franck committed
1570

1571
    // 5. check if document tree has been updated correctly
Tristan Cavelier's avatar
Tristan Cavelier committed
1572 1573
    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1.revision_tree.json"
1574
    ),o.testtree, "Check document tree");
1575 1576

    // 6. check if attachment has been removed
1577 1578 1579
    deepEqual(localstorage.getItem(
        "jio/localstorage/urevrem/arevrem/remove1."+o.rev+"/remove2"
    ), null, "Check attachment");
1580 1581

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

Sven Franck's avatar
Sven Franck committed
1586 1587 1588 1589 1590 1591 1592 1593 1594
    // add another attachment
    o.attmt_myremove2 = {
        "remove3": {
            "length": 3,
            "digest": "md5-hello123"
        },
        "revpos":1
    };
    o.doc_myremove2 = {"_id": "remove1", "title": "myRemove2",
1595
                       "_attachments":o.attmt_myremove2};
1596 1597 1598
    o.revisions = {"start":1,"ids":["rev2"] };
    o.second_old_rev = "2-"+generateRevisionHash(o.doc_myremove2, o.revisions);

1599 1600 1601 1602
    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
1603 1604 1605 1606 1607 1608 1609

    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
1610
    },{
Sven Franck's avatar
Sven Franck committed
1611 1612
        "rev": "1-rev2", "status": "available", "children": [{
            "rev": o.second_old_rev, "status": "available", "children":[]
Tristan Cavelier's avatar
Tristan Cavelier committed
1613 1614
        }]
    }]};
Sven Franck's avatar
Sven Franck committed
1615 1616
    localstorage.setItem(o.localpath+"/remove1.revision_tree.json", o.doctree);

1617
    // 8. remove non existing attachment without revision
Sven Franck's avatar
Sven Franck committed
1618 1619
    o.spy (o,"status", 409,
           "409 - Removing non-existing-attachment (no revision)");
Sven Franck's avatar
Sven Franck committed
1620 1621 1622
    o.jio.remove({"_id":"remove1/remove0"}, o.f);
    o.tick(o);

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

1627
    // 9. remove existing attachment without revision
Sven Franck's avatar
Sven Franck committed
1628
    o.spy (o,"status", 409, "409 - Removing existing attachment (no revision)");
Sven Franck's avatar
Sven Franck committed
1629 1630 1631
    o.jio.remove({"_id":"remove1/remove3"}, o.f);
    o.tick(o);

1632
    // 10. remove wrong revision
Sven Franck's avatar
Sven Franck committed
1633
    o.spy (o,"status", 409, "409 - Removing document (false revision)");
1634
    o.jio.remove({"_id":"remove1","_rev":"1-rev2"}, o.f);
Sven Franck's avatar
Sven Franck committed
1635 1636
    o.tick(o);

Tristan Cavelier's avatar
Tristan Cavelier committed
1637 1638
    o.revisions = {"start": 3, "ids":[
        o.rev.split('-')[1],
1639 1640
        o.old_rev.split('-')[1],o.very_old_rev.split('-')[1]
    ]};
Sven Franck's avatar
Sven Franck committed
1641
    o.doc_myremove4 = {"_id":"remove1","_rev":o.rev};
1642 1643
    o.second_new_rev = "4-"+
        generateRevisionHash(o.doc_myremove4, o.revisions, true);
Sven Franck's avatar
Sven Franck committed
1644

1645
    // 11. remove document version with revision
1646 1647
    o.spy (o, "value", {"ok": true, "id": "remove1", "rev":
        o.second_new_rev},
Tristan Cavelier's avatar
Tristan Cavelier committed
1648
           "Remove document (with revision)");
Sven Franck's avatar
Sven Franck committed
1649
    o.jio.remove({"_id":"remove1", "_rev":o.rev}, o.f);
Sven Franck's avatar
Sven Franck committed
1650 1651
    o.tick(o);

1652 1653 1654 1655 1656
    o.testtree["children"][0]["children"][0]["children"][0]["children"].push({
        "rev": o.second_new_rev,
        "status": "deleted",
        "children": []
    });
1657 1658 1659 1660 1661 1662
    o.testtree["children"][1]["children"].push({
        "rev":o.second_old_rev,
        "status":"available",
        "children":[]
    });

1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
    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
1676
    o.spy (o,"status", 409, "409 - Removing document (no revision)");
Sven Franck's avatar
Sven Franck committed
1677 1678
    o.jio.remove({"_id":"remove1"}, o.f);
    o.tick(o);
1679

Sven Franck's avatar
Sven Franck committed
1680 1681 1682
    o.jio.stop();
});

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

1685
test ("Scenario", function(){
Sven Franck's avatar
Sven Franck committed
1686 1687 1688 1689 1690

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "revision",
1691
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
1692 1693
            "type": "local",
            "username": "usam1",
1694
            "application_name": "asam1"
Sven Franck's avatar
Sven Franck committed
1695 1696 1697 1698
        }
    });
    o.localpath = "jio/localstorage/usam1/asam1";

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

1702
    // put non empty document A-1
Sven Franck's avatar
Sven Franck committed
1703
    o.doc = {"_id": "sample1", "title": "mySample1"};
1704 1705
    o.revisions = {"start": 0, "ids": []};
    o.hex = generateRevisionHash(o.doc, o.revisions);
1706
    o.rev = "1-"+o.hex;
Sven Franck's avatar
Sven Franck committed
1707

1708
    o.spy (o, "value", {"ok": true, "id": "sample1", "rev": o.rev},
1709 1710
           "Then, I create a new document (no attachment), my application "+
           "keep the revision in memory");
Sven Franck's avatar
Sven Franck committed
1711 1712 1713
    o.jio.put(o.doc, o.f);
    o.tick(o);

1714
    // open new tab (JIO)
Sven Franck's avatar
Sven Franck committed
1715 1716
    o.jio2 = JIO.newJio({
        "type": "revision",
1717
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
1718 1719
            "type": "local",
            "username": "usam1",
1720
            "application_name": "asam1"
Sven Franck's avatar
Sven Franck committed
1721 1722 1723 1724
        }
    });
    o.localpath = "jio/localstorage/usam1/asam1";

1725
    // Create a new JIO in a new tab
1726 1727
    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
1728

1729
    // Get the document from the first storage
Sven Franck's avatar
Sven Franck committed
1730 1731 1732
    o.doc._rev = o.rev;
    o.doc._revisions = {"ids":[o.hex], "start":1 };
    o.doc._revs_info = [{"rev": o.rev, "status": "available"}];
1733 1734
    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
1735
    o.jio2.get("sample1", {
1736 1737
        "revs_info": true, "revs": true, "conflicts": true,
        "rev": o.rev }, o.f);
Sven Franck's avatar
Sven Franck committed
1738 1739
    o.tick(o);

1740
    // MODFIY the 2nd version
Sven Franck's avatar
Sven Franck committed
1741 1742 1743 1744
    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)
1745
    o.rev_2 = "2-"+o.hex_2;
1746
    o.spy (o, "value", {"id":"sample1", "ok":true, "rev": o.rev_2},
1747
           "So, I can modify and update it");
Sven Franck's avatar
Sven Franck committed
1748
    o.jio2.put(o.doc_2, o.f);
Sven Franck's avatar
Sven Franck committed
1749 1750
    o.tick(o);

1751
    // MODFIY first version
1752 1753 1754
    o.doc_1 = {
        "_id": "sample1", "_rev": o.rev, "title": "mySample1_modified"
    };
Sven Franck's avatar
Sven Franck committed
1755 1756 1757 1758 1759
    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},
1760
           "Back to the first tab, I update the document.");
Sven Franck's avatar
Sven Franck committed
1761
    o.jio.put(o.doc_1, o.f);
Sven Franck's avatar
Sven Franck committed
1762 1763
    o.tick(o);

1764
    // Close 1st tab
Sven Franck's avatar
Sven Franck committed
1765 1766
    o.jio.close();

1767 1768 1769 1770 1771
    // Close 2nd tab
    o.jio2.close();
    ok ( o.jio2, "I close tab both tabs");

    // Reopen JIO
Sven Franck's avatar
Sven Franck committed
1772 1773
    o.jio = JIO.newJio({
        "type": "revision",
1774
        "sub_storage": {
Sven Franck's avatar
Sven Franck committed
1775 1776
            "type": "local",
            "username": "usam1",
1777
            "application_name": "asam1"
Sven Franck's avatar
Sven Franck committed
1778 1779 1780
        }
    });
    o.localpath = "jio/localstorage/usam1/asam1";
1781
    ok ( o.jio, "Later, I open my application again");
Sven Franck's avatar
Sven Franck committed
1782

1783
    // GET document without revision = winner & conflict!
1784
    o.mydocSample3 = {"_id": "sample1", "title": "mySample1_modified",
1785
                      "_rev": o.rev_1};
Sven Franck's avatar
Sven Franck committed
1786 1787
    o.mydocSample3._conflicts = [o.rev_2]
    o.mydocSample3._revs_info = [{"rev": o.rev_1, "status": "available"},{
1788 1789
        "rev":o.rev,"status":"available"
        }];
Sven Franck's avatar
Sven Franck committed
1790
    o.mydocSample3._revisions = {"ids":[o.hex_1, o.hex], "start":2 };
1791
    o.spy(o, "value", o.mydocSample3,
1792 1793
          "I load the same document as before, and a popup shows that "+
          "there is a conflict");
1794 1795
    o.jio.get("sample1", {"revs_info": true, "revs": true, "conflicts": true,
        }, o.f);
Sven Franck's avatar
Sven Franck committed
1796 1797
    o.tick(o);

1798
    // REMOVE one of the two conflicting versions
1799 1800 1801 1802 1803
    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
1804 1805

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

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
    // 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);

1823
    // END
Sven Franck's avatar
Sven Franck committed
1824
    o.jio.stop();
1825

Sven Franck's avatar
Sven Franck committed
1826
});
Sven Franck's avatar
Sven Franck committed
1827

1828
module ("JIO Replicate Revision Storage");
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021

  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.revision = {"start": 0, "ids": []};
    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;
    o.rev = "1";
    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"
      );
    });

    // post a new document with id
    o.doc = {"_id": "post1", "title": "post new doc with id"};
    o.rev = "1"
    o.spy(o, "value", {"ok": true, "id": "post1", "rev": o.rev},
          "Post document (with id)");
    o.jio.post(o.doc, o.f);
    o.tick(o);

    // 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) +
                             "/post1" + suffix),
        doc, "Check document"
      );
    });

    // post same document without revision
    o.doc = {"_id": "post1", "title": "post same document without revision"};
    o.rev = "2";
    o.spy(o, "value", {"ok": true, "id": "post1", "rev": o.rev},
          "Post same document (without revision)");
    o.jio.post(o.doc, o.f);
    o.tick(o);

    // 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) +
                             "/post1" + suffix),
        doc, "Check document"
      );
    });

    // post a new revision
    o.doc = {"_id": "post1", "title": "post new revision", "_rev": o.rev};
    o.rev = "3";
    o.spy(o, "value", {"ok": true, "id": "post1", "rev": o.rev},
          "Post document (with revision)");
    o.jio.post(o.doc, o.f);
    o.tick(o);

    // 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);
    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) +
                             "/post1" + suffix),
        doc, "Check document"
      );
    });

    o.jio.stop();

  };

  test ("[Local Storage] Scenario", function () {
    testReplicateRevisionStorageGenerator(this, {
      "type": "replicaterevision",
      "storage_list": [{
        "type": "local",
        "username": "ureploc",
        "application_name": "areploc"
      }]
    });
  });
  test ("[Revision + Local Storage] Scenario", function () {
    testReplicateRevisionStorageGenerator(this, {
      "type": "replicaterevision",
      "storage_list": [{
        "type": "revision",
        "sub_storage": {
          "type": "local",
          "username": "ureprevloc",
          "application_name": "areprevloc"
        }
      }]
    });
  });
  test ("[Revision + Local Storage, Local Storage] Scenario", function () {
    testReplicateRevisionStorageGenerator(this, {
      "type": "replicaterevision",
      "storage_list": [{
        "type": "revision",
        "sub_storage": {
          "type": "local",
          "username": "ureprevlocloc",
          "application_name": "areprevlocloc"
        }
      },{
        "type": "local",
        "username": "ureprevlocloc2",
        "application_name": "areprevlocloc2"
      }]
    });
  });

2022
module ("Jio DAVStorage");
Tristan Cavelier's avatar
Tristan Cavelier committed
2023

2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
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
    o.addFakeServerResponse("PUT", "myFile", 201, "HTML RESPONSE");
    o.spy(o, "value", {"id": "myFile", "ok": true},
2043
          "Create = POST non empty document");
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    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"});
    o.addFakeServerResponse("GET", "myFile", 200, o.answer);
    o.spy (o, "status", 409, "Post but document already exists");
    o.jio.post({"_id": "myFile", "title": "hello again"}, o.f);
    o.clock.tick(5000);
2054
    o.server.respond();
2055

2056 2057 2058
    // as all custom headers trigger preflight requests, the test also
    // need to simulate CORS (cross domain ajax with preflight)
    // custom header may be authentication for example
2059 2060
    o.jio.stop();

2061
    // do the same tests live webDav-Server simulating CORS!
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
    /* also check for equality

    deepEqual(
        localstorage.getItem("jio/localstorage/uput/aput/put1"),
        {
            "_id": "put1",
            "title": "myPut1"
        },
        "Check document"
    );
    */
});

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
    o.addFakeServerResponse("PUT", "put1", 201, "HTML RESPONSE");
    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();
2098 2099 2100
    //console.log( o.server );
    //console.log( o.server.requests[0].requestHeaders );
    //console.log( o.server.requests[0].responseHeaders );
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112

    // put but document already exists = update
    o.answer = JSON.stringify({"_id": "put1", "title": "myPut1"});
    o.addFakeServerResponse("GET", "put1", 200, o.answer);
    o.addFakeServerResponse("PUT", "put1", 201, "HTML RESPONSE");
    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();

2113
    // do the same tests live webDav-Server/simulate CORS
2114 2115
    // check for credentials in sinon

2116
});
2117 2118 2119 2120 2121 2122 2123

test ("PutAttachment", function(){

    var o = generateTools(this);

    o.jio = JIO.newJio({
        "type": "dav",
2124
        "username": "davputattm",
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
        "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
    o.addFakeServerResponse("GET", "putattmtx", 404, "HTML RESPONSE");
    o.spy(o, "status", 404, "PutAttachment without document");
    o.jio.putAttachment({"id": "putattmtx/putattmt2"}, o.f);
    o.clock.tick(5000);
    o.server.respond();

    // putAttachment with document without data
    o.answer = JSON.stringify({"_id": "putattmt1", "title": "myPutAttm1"});
    o.addFakeServerResponse("GET", "putattmt1", 200, o.answer);
    o.addFakeServerResponse("PUT", "putattmt1", 201, "HTML RESPONSE");
    o.addFakeServerResponse("PUT", "putattmt1/putattmt2", 201,"HTML RESPONSE");
    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();

    // check document
    // check attachment

    // update attachment
    o.answer = JSON.stringify({"_id": "putattmt1", "title": "myPutAttm1"});
    o.addFakeServerResponse("GET", "putattmt1", 200, o.answer);
    o.addFakeServerResponse("PUT", "putattmt1", 201, "HTML RESPONSE");
    o.addFakeServerResponse("PUT", "putattmt1/putattmt2", 201,"HTML RESPONSE");
    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();

    // check document
    // check attachment

    o.jio.stop();

    // do the same tests live webDav-Server/simulate CORS
    // check for credentials in sinon
});

2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 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
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
    o.addFakeServerResponse("GET", "get1", 404, "HTML RESPONSE");
    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
    o.addFakeServerResponse("GET", "get1/get2", 404, "HTML RESPONSE");
    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"});
    o.addFakeServerResponse("GET", "get3", 200, o.answer);
    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)
    o.addFakeServerResponse("GET", "get3/getx", 404, "HTML RESPONSE");
    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"});
    o.addFakeServerResponse("GET", "get3/get4", 200, o.answer);
    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();

    // do the same tests live webDav-Server/simulate CORS
    // check for credentials in sinon
});


2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
/*
    // note: http errno:
    //     200 OK
    //     201 Created
    //     204 No Content
    //     207 Multi Status
    //     403 Forbidden
    //     404 Not Found
    //     405 Not Allowed

    server.respondWith (
      // lastmodified = 7000, creationdate = 5000
      "PROPFIND",
          /https:\/\/ca-davstorage:8080\/davpost\/myFile(\?.*|$)/,
      [errnoprop,{'Content-Type':'text/xml; charset="utf-8"'},
        o.davpost]);

    server.respondWith ("MKCOL","https://ca-davstorage:8080/dav",
                          [200,{},'']);
    server.respondWith ("MKCOL","https://ca-davstorage:8080/dav/davpost",
                          [200,{},'']);
    server.respondWith ("MKCOL",
                        "https://ca-davstorage:8080/dav/davpost/jiotests",
                          [200,{},'']);
 */
/*
Tristan Cavelier's avatar
Tristan Cavelier committed
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310

test ('Get Document List', function () {
    // Test if DavStorage can get a list a document.

    var o = {};
    o.davlist = getXML('responsexml/davlist');
    o.clock = this.sandbox.useFakeTimers();
    o.clock.tick(base_tick);
    o.t = this;
    o.mytest = function (message,metadata_only,value,errnoprop) {
        var server = o.t.sandbox.useFakeServer();
        server.respondWith (
            "PROPFIND",
                /https:\/\/ca-davstorage:8080\/davlist\/jiotests\/(\?.*|$)/,
            [errnoprop,{'Content-Type':'text/xml; charset="utf-8"'},
             o.davlist]);
        server.respondWith (
            "GET",
                /https:\/\/ca-davstorage:8080\/davlist\/jiotests\/file(\?.*|$)/,
            [200,{},'content']);
        server.respondWith (
            "GET",
                /https:\/\/ca-davstorage:8080\/davlist\/jiotests\/memo(\?.*|$)/,
            [200,{},'content2']);
        o.f = function (err,val) {
            if (err) {
                result = undefined;
            } else {
                deepEqual (objectifyDocumentArray(val.rows),
                           objectifyDocumentArray(value),message);
                return;
            }
            deepEqual (result, value, message);
        };
        o.t.spy(o,'f');
        o.jio.allDocs({metadata_only:metadata_only},o.f);
        o.clock.tick(1000);
        server.respond();
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok(false, 'too much results');
            } else {
                ok(false, 'no response');
            }
        }
    };
    o.jio = JIO.newJio({type:'dav',username:'davlist',
                        password:'checkpwd',
                        url:'https://ca-davstorage:8080',
2311
                        application_name:'jiotests'});
Tristan Cavelier's avatar
Tristan Cavelier committed
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
    o.mytest('fail to get list',true,undefined,404);
    o.mytest('getting list',true,[{
        id:'file',key:'file',
        value:{
            _creation_date:1335962911000,
            _last_modified:1335962907000
        }
    },{
        id:'memo',key:'memo',
        value:{
            _creation_date:1335894073000,
            _last_modified:1335955713000
        }
    }],207);
    o.mytest('getting list',false,[{
        id:'file',key:'file',
        value:{
            content:'content',
            _creation_date:1335962911000,
            _last_modified:1335962907000
        }
    },{
        id:'memo',key:'memo',
        value:{
            content:'content2',
            _creation_date:1335894073000,
            _last_modified:1335955713000
        }
    }],207);
2341

Tristan Cavelier's avatar
Tristan Cavelier committed
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
    o.jio.stop();
});

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

    var o = {}; o.clock = this.sandbox.useFakeTimers(); o.t = this;
    o.clock.tick(base_tick);
    o.mytest = function (message,value,errnodel) {
        var server = o.t.sandbox.useFakeServer();
        server.respondWith (
            "DELETE",
                /https:\/\/ca-davstorage:8080\/davremove\/jiotests\/file(\?.*|$)/,
            [errnodel,{},'']);
        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'},o.f);
        o.clock.tick(1000);
        server.respond();
        if (!o.f.calledOnce) {
            if (o.f.called) {
                ok(false, 'too much results');
            } else {
                ok(false, 'no response');
            }
        }
    };
    o.jio = JIO.newJio({type:'dav',username:'davremove',
                        password:'checkpwd',
                        url:'https://ca-davstorage:8080',
2377
                        application_name:'jiotests'});
Tristan Cavelier's avatar
Tristan Cavelier committed
2378 2379 2380 2381 2382

    o.mytest('remove document',{ok:true,id:'file'},204);
    o.mytest('remove an already removed document',404,404);
    o.jio.stop();

2383 2384 2385
});
*/
/*
Tristan Cavelier's avatar
Tristan Cavelier committed
2386 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 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 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 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 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
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();
});

module ('Jio IndexedStorage');

test ('Document load', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers();
    o.clock.tick(base_tick);
    o.jio = JIO.newJio({type:'indexed',storage:{type:'dummyall3tries'}});
    // loading must take long time with dummyall3tries
    o.f = this.spy();
    o.jio.get('memo',{max_retry:3,metadata_only:true},o.f);
    o.clock.tick(1000);
    ok(!o.f.called,'Callback must not be called');
    // wait long time too retreive list
    o.clock.tick(1000);

    // now we can test if the document metadata are loaded faster.
    o.doc = {_id:'memo',_last_modified:25000,_creation_date:20000};
    o.f2 = function (err,val) {
        deepEqual (err||val,o.doc,'Document metadata retrieved');
    };
    this.spy(o,'f2');
    o.jio.get('memo',{max_retry:3,metadata_only:true},o.f2);
    o.clock.tick(1000);
    if (!o.f2.calledOnce) {
        if (o.f2.called) {
            ok (false, 'too much results');
        } else {
            ok (false, 'no response');
        }
    }

    // test a simple document loading
    o.doc2 = {_id:'file',_last_modified:17000,
              _creation_date:11000,content:'content file'};
    o.f3 = function (err,val) {
        deepEqual (err||val,o.doc2,'Simple document loading');
    };
    this.spy(o,'f3');
    o.jio.get('file',{max_retry:3},o.f3);
    o.clock.tick(2000);
    if (!o.f3.calledOnce) {
        ok (false, 'no response / too much results');
    }
    o.jio.stop();
});

test ('Document save', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers();
    o.clock.tick(base_tick);
    o.jio = JIO.newJio({type:'indexed',
                        storage:{type:'dummyall3tries',
                                 username:'indexsave'}});
    o.f = function (err,val) {
        if (err) {
            err = err.status;
        }
        deepEqual (err || val,{ok:true,id:'file'},'document save');
    };
    this.spy(o,'f');
    o.jio.put({_id:'file',content:'content'},{max_retry:3},o.f);
    o.clock.tick(2000);
    if (!o.f.calledOnce){
        ok (false, 'no response / too much results');
    }
    o.jio.stop();
});

test ('Get document list', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers();
    o.clock.tick(base_tick);
    o.jio = JIO.newJio({type:'indexed',
                        storage:{type:'dummyall3tries',
                                 username:'indexgetlist'}});
    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}};
    // getting list must take long time with dummyall3tries
    o.f = this.spy();
    o.jio.allDocs({max_retry:3},o.f);
    o.clock.tick(1000);
    ok(!o.f.called,'Callback must not be called');
    // wail long time too retreive list
    o.clock.tick(1000);
    // now we can test if the document list is loaded faster
    o.f2 = function (err,val) {
        deepEqual (err || objectifyDocumentArray(val.rows),
                   objectifyDocumentArray([o.doc1,o.doc2]),'get document list');
    };
    this.spy(o,'f2');
    o.jio.allDocs({max_retry:3},o.f2);
    o.clock.tick(1000)
    if (!o.f2.calledOnce) {
        ok (false, 'no response / too much results');
    }
});

test ('Remove document', function () {
    var o = {}; o.clock = this.sandbox.useFakeTimers();
    o.clock.tick(base_tick);
2643
    o.sub_storage = {type:'dummyall3tries',username:'indexremove'}
Tristan Cavelier's avatar
Tristan Cavelier committed
2644
    o.storage_file_object_name = 'jio/indexed_file_object/'+
2645
        JSON.stringify (o.sub_storage);
Tristan Cavelier's avatar
Tristan Cavelier committed
2646

2647
    o.jio = JIO.newJio({type:'indexed',storage:o.sub_storage});
Tristan Cavelier's avatar
Tristan Cavelier committed
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
    o.f = function (err,val) {
        if (err) {
            err = err.status;
        }
        deepEqual (err || val,{ok:true,id:'file'},'document remove');
    };
    this.spy(o,'f');
    o.jio.remove({_id:'file'},{max_retry:3},o.f);
    o.clock.tick(2000);
    if (!o.f.calledOnce){
        ok (false, 'no response / too much results');
    }

    o.tmp = LocalOrCookieStorage.getItem(o.storage_file_object_name) || {};
    ok (!o.tmp.file,'File does not exists anymore');

    o.jio.stop();
});

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',
2677
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
    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',
2712
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
    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',
2742
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
    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',
2797
                               application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
    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',
2843
                                 application_name:'jiotests'}});
Tristan Cavelier's avatar
Tristan Cavelier committed
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 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 2970 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
    // 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.');
    };
3016
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
3017
                            username:'revisionconflict',
3018
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
3019 3020
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
3021
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
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 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
    // 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.');
    };
3180
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
3181
                            username:'conflictconflict',
3182
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
3183 3184
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
3185
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
    // 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.');
    };
3367
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
3368
                            username:'removeconflict',
3369
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
3370 3371
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
3372
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
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 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 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 3596

    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;
3597
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
3598
                            username:'loadrevisions',
3599
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
3600 3601
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
3602
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617
    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;
3618
    o.sub_storage_spec = {type:'local',
Tristan Cavelier's avatar
Tristan Cavelier committed
3619
                            username:'getrevisionlist',
3620
                            application_name:'jiotests'}
Tristan Cavelier's avatar
Tristan Cavelier committed
3621 3622 3623
    o.rev = {};
    //////////////////////////////////////////////////////////////////////
    o.jio = JIO.newJio({type:'conflictmanager',
3624
                        storage:o.sub_storage_spec});
Tristan Cavelier's avatar
Tristan Cavelier committed
3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
    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();
});
3726
*/
Tristan Cavelier's avatar
Tristan Cavelier committed
3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
};                              // end thisfun

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

            jQueryAPI: '../lib/jquery/jquery',
            jQuery: '../js/jquery.requirejs_module',
            JIO: '../src/jio',
            Base64API: '../lib/base64/base64',
            Base64: '../js/base64.requirejs_module',
            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
3747
    thisfun ({JIO:jIO});
Tristan Cavelier's avatar
Tristan Cavelier committed
3748 3749 3750
}

}());