xwikistorage.tests.js 19.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*jslint
    indent: 2,
    maxlen: 80,
    plusplus: true,
    nomen: true,
    regexp: true
*/
/*global
    define,
    jIO,
    test,
    ok,
    sinon,
    module,
    clearTimeout,
    setTimeout,
    start,
    stop,
    deepEqual
*/
Tristan Cavelier's avatar
Tristan Cavelier committed
21 22 23 24 25 26 27

// define([module_name], [dependencies], module);
(function (dependencies, module) {
  "use strict";
  if (typeof define === 'function' && define.amd) {
    return define(dependencies, module);
  }
28 29
  module(jIO);
}(['jio', 'xwikistorage'], function (jIO) {
Tristan Cavelier's avatar
Tristan Cavelier committed
30 31
  "use strict";

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
  function nThen(next) {
    var funcs = [],
      timeouts = [],
      calls = 0,
      abort,
      ret,
      waitFor;
    waitFor = function (func) {
      calls++;
      return function () {
        if (func) {
          func.apply(null, arguments);
        }
        calls = (calls || 1) - 1;
        while (!calls && funcs.length && !abort) {
          funcs.shift()(waitFor);
        }
      };
Tristan Cavelier's avatar
Tristan Cavelier committed
50
    };
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    waitFor.abort = function () {
      timeouts.forEach(clearTimeout);
      abort = 1;
    };
    ret = {
      nThen: function (next) {
        if (!abort) {
          if (!calls) {
            next(waitFor);
          } else {
            funcs.push(next);
          }
        }
        return ret;
      },
      orTimeout: function (func, milliseconds) {
        var cto, timeout;
        if (abort) { return ret; }
        if (!milliseconds) {
          throw new Error("Must specify milliseconds to orTimeout()");
        }
        timeout = setTimeout(function () {
          var f;
          while (f !== cto) { f = funcs.shift(); }
          func(waitFor);
          calls = (calls || 1) - 1;
          while (!calls && funcs.length) { funcs.shift()(waitFor); }
        }, milliseconds);
        cto = function () {
          var i;
          for (i = 0; i < timeouts.length; i++) {
            if (timeouts[i] === timeout) {
              timeouts.splice(i, 1);
              clearTimeout(timeout);
              return;
            }
          }
          throw new Error('timeout not listed in array');
        };
        funcs.push(cto);
        timeouts.push(timeout);
        return ret;
      }
    };
    return ret.nThen(next);
Tristan Cavelier's avatar
Tristan Cavelier committed
96 97
  }

Tristan Cavelier's avatar
Tristan Cavelier committed
98 99
  module('XWikiStorage');

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  function setUp() {
    var o = {
      sinon: sinon.sandbox.create()
    };
    o.addFakeServerResponse =
      function (type, method, path, status, response, t) {
        t = t || 'application/xml';
        /*jslint unparam: true */
        o.sinon.server.respondWith(method, new RegExp(path), [
          status,
          {"Content-Type": t},
          response
        ]);
      };
    o.sinon.useFakeTimers();
    o.sinon.useFakeServer();

    o.respond = function () {
      o.sinon.clock.tick(5000);
      o.sinon.server.respond();
    };

    o.jio = jIO.createJIO(
      {type: 'xwiki', formTokenPath: 'form_token', xwikiurl: ''}
    );
Tristan Cavelier's avatar
Tristan Cavelier committed
125 126 127 128 129 130 131 132 133 134 135
    o.addFakeServerResponse("xwiki", "GET", "form_token", 200,
                            '<meta name="form_token" content="OMGHAX"/>');
    o._addFakeServerResponse = o.addFakeServerResponse;
    o.expectedRequests = [];
    o.addFakeServerResponse = function (a, b, c, d, e) {
      o._addFakeServerResponse(a, b, c, d, e);
      o.expectedRequests.push([b, c]);
    };
    o.assertReqs = function (count, message) {
      var i, j, req, expected, ex;
      o.requests = (o.requests || 0) + count;
136
      ok(o.sinon.server.requests.length === o.requests,
Tristan Cavelier's avatar
Tristan Cavelier committed
137
         message + "[expected [" + count + "] got [" +
138
         (o.sinon.server.requests.length - (o.requests - count)) + "]]");
Tristan Cavelier's avatar
Tristan Cavelier committed
139
      for (i = 1; i <= count; i += 1) {
140
        req = o.sinon.server.requests[o.sinon.server.requests.length - i];
Tristan Cavelier's avatar
Tristan Cavelier committed
141 142 143 144 145 146 147 148
        if (!req) {
          break;
        }
        for (j = o.expectedRequests.length - 1; j >= 0; j -= 1) {
          expected = o.expectedRequests[j];
          if (req.method === expected[0] &&
              req.url.indexOf(expected[1]) !== 0) {
            o.expectedRequests.splice(j, 1);
Tristan Cavelier's avatar
Tristan Cavelier committed
149
          }
Tristan Cavelier's avatar
Tristan Cavelier committed
150 151 152 153 154 155 156 157 158 159
        }
      }
      ex = o.expectedRequests.pop();
      if (ex) {
        ok(0, "expected [" +  ex[0] + "] request for [" + ex[1] + "]");
      }
    };
    return o;
  }

160 161 162 163 164 165 166 167 168 169 170 171 172
  function nThenTest(o, nt) {
    stop();
    nt.nThen(function () {
      o.sinon.restore();
      start();

    }).orTimeout(function () {
      o.sinon.restore();
      ok(0);
      start();
    }, 1000);
  }

Tristan Cavelier's avatar
Tristan Cavelier committed
173 174 175
  test("Post", function () {

    var o = setUp(this);
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    nThenTest(o, nThen(function (waitFor) {

      // post non empty document
      o.addFakeServerResponse("xwiki", "POST", "myFile1", 201, "HTML RESPONSE");
      o.jio.post({"_id": "myFile1", "title": "hello there"}).
        then(waitFor(function (ret) {
          deepEqual({
            id: "myFile1",
            method: "post",
            result: "success",
            status: 201,
            statusText: "Created"
          }, ret);

        }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(
        3,
        "post -> 1 request to get csrf token, 1 to get doc and 1 to post data"
      );
    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  test("Post2", function () {

    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      // post but document already exists (post = error!, put = ok)
      o.answer = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<page xmlns="http://www.xwiki.org"><title>hello there</title></page>';
      o.addFakeServerResponse("xwiki", "GET", "pages/myFile2", 200, o.answer);

      o.jio.post({"_id": "myFile2", "title": "hello again"}).
        then(function () {
          ok(0);
        }, waitFor(function (err) {
          deepEqual({
            error: "conflict",
            id: "myFile2",
            message: "Cannot create a new document",
            method: "post",
            reason: "document exists",
            result: "error",
            status: 409,
            statusText: "Conflict"
          }, err);
        }));

      o.respond();

    }).nThen(function () {

      o.assertReqs(2, "post w/ existing doc -> 2 request to get doc then fail");

    }));
Tristan Cavelier's avatar
Tristan Cavelier committed
235

Tristan Cavelier's avatar
Tristan Cavelier committed
236 237
  });

238
  test("PutNoId", function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
239 240

    var o = setUp(this);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    nThenTest(o, nThen(function (waitFor) {

      // put without id => id required
      o.jio.put({}).then(function () {
        ok(0);
      }, waitFor(function (err) {
        deepEqual({
          "error": "bad_request",
          "message": "Document id must be a non empty string.",
          "method": "put",
          "reason": "wrong document id",
          "result": "error",
          "status": 400,
          "statusText": "Bad Request"
        }, err);
      }));

    }).nThen(function () {

      o.assertReqs(0, "put w/o id -> 0 requests");

    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
  test("Put", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      // put non empty document
      o.addFakeServerResponse("xwiki", "POST", "put1", 201, "HTML RESPONSE");
      o.jio.put({"_id": "put1", "title": "myPut1"}).
        then(waitFor(function (res) {
          deepEqual({
            "id": "put1",
            "method": "put",
            "result": "success",
            "status": 201,
            "statusText": "Created"
          }, res);
        }));

      o.respond();

    }).nThen(function () {

      o.assertReqs(
        3,
        "put normal doc -> 1 req to get doc (404), 1 for csrf token, 1 to post"
      );

    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
293

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  test("PutUpdateDoc", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      // put but document already exists = update
      o.answer = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<page xmlns="http://www.xwiki.org"><title>mtPut1</title></page>';
      o.addFakeServerResponse("xwiki", "GET", "put2", 200, o.answer);
      o.addFakeServerResponse("xwiki", "POST", "put2", 201, "HTML RESPONSE");

      o.jio.put({"_id": "put2", "title": "myPut2abcdedg"}).
        then(waitFor(function (ret) {
          deepEqual({
            "id": "put2",
            "method": "put",
            "result": "success",
            "status": 204,
            "statusText": "No Content"
          }, ret);
        }));

      o.respond();

    }).nThen(function () {

      o.assertReqs(
        4,
        "put update doc -> 2 req to get doc, 1 for csrf token, 1 to post"
      );

    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
326

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
  test("PutAttachmentNoDocId", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {
      // putAttachment without doc id => id required
      o.jio.putAttachment({}, function () {
        ok(0);
      }, waitFor(function (err) {
        deepEqual({
          "attachment": undefined,
          "error": "bad_request",
          "message": "Document id must be a non empty string.",
          "method": "putAttachment",
          "reason": "wrong document id",
          "result": "error",
          "status": 400,
          "statusText": "Bad Request"
        }, err);
      }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(0, "put attach w/o doc id -> 0 requests");
    }));
Tristan Cavelier's avatar
Tristan Cavelier committed
351 352
  });

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
  test("PutAttachmentNoAttachId", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {
      // putAttachment without attachment id => attachment id required
      o.jio.putAttachment({"_id": "putattmt1"}, function () {
        ok(0);
      }, waitFor(function (err) {
        deepEqual({
          "attachment": undefined,
          "error": "bad_request",
          "id": "putattmt1",
          "message": "Attachment id must be a non empty string.",
          "method": "putAttachment",
          "reason": "wrong attachment id",
          "result": "error",
          "status": 400,
          "statusText": "Bad Request"
        }, err);
      }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(0, "put attach w/o attach id -> 0 requests");
    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
379

380
  test("PutAttachmentUnderlyingDocumentNonexistant", function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
381
    var o = setUp(this);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    nThenTest(o, nThen(function (waitFor) {
      // putAttachment without underlying document => not found
      o.jio.putAttachment(
        {"_id": "putattmtx", "_attachment": "putattmt2", "_data": ""},
        function () {
          ok(0);
        },
        waitFor(function (err) {
          deepEqual({
            "attachment": "putattmt2",
            "error": "not_found",
            "id": "putattmtx",
            "message": "Impossible to add attachment",
            "method": "putAttachment",
            "reason": "missing",
            "result": "error",
            "status": 404,
            "statusText": "Not Found"
          }, err);
        })
      );

      o.respond();

    }).nThen(function () {
      o.assertReqs(
        1,
        "put attach w/o existing document -> 1 request to get doc"
      );
    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
413

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
  test("GetNonexistantDoc", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {
      // get inexistent document
      o.jio.get({_id: "get_nonexistant_doc"}, function () {
        ok(0);
      }, waitFor(function (err) {
        deepEqual({
          "error": "not_found",
          "id": "get_nonexistant_doc",
          "message": "Cannot find document",
          "method": "get",
          "reason": "missing",
          "result": "error",
          "status": 404,
          "statusText": "Not Found"
        }, err);
      }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(1, "try to get nonexistent doc -> 1 request");
    }));
Tristan Cavelier's avatar
Tristan Cavelier committed
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
  test("GetAttachInNonexistantDoc", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {
      o.jio.getAttachment(
        {"_id": "noSuchDoc", "_attachment": "its_attachment"},
        function () {
          ok(0);
        },
        waitFor(function (err) {
          deepEqual({
            "attachment": "its_attachment",
            "error": "not_found",
            "id": "noSuchDoc",
            "message": "Cannot find document",
            "method": "getAttachment",
            "reason": "missing document",
            "result": "error",
            "status": 404,
            "statusText": "Not Found"
          }, err);
        })
      );

      o.respond();

    }).nThen(function () {
      o.assertReqs(1, "try to get nonexistent attach -> 1 request");
    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
469

470
  test("GetDoc", function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
471
    var o = setUp(this);
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    nThenTest(o, nThen(function (waitFor) {
      o.answer = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<page xmlns="http://www.xwiki.org"><title>some title</title></page>';
      o.addFakeServerResponse("xwiki", "GET", "get_doc", 200, o.answer);

      o.jio.get({_id: "get_doc"}).then(waitFor(function (ret) {
        deepEqual({
          "data": {
            "_attachments": {},
            "_id": "get_doc",
            "title": "some title"
          },
          "id": "get_doc",
          "method": "get",
          "result": "success",
          "status": 200,
          "statusText": "Ok"
        }, ret);
      }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(2, "get document -> 2 request");
    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
498

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 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
  test("GetNonexistantAttach", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      // get inexistent attachment (document exists)
      o.answer = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
        '<page xmlns="http://www.xwiki.org"><title>some title</title></page>';
      o.addFakeServerResponse(
        "xwiki",
        "GET",
        "get_nonexistant_attach",
        200,
        o.answer
      );

      o.jio.getAttachment(
        {"_id": "get_nonexistant_attach", "_attachment": "nxattach"},
        function () {
          ok(0);
        },
        waitFor(function (err) {
          deepEqual({
            "attachment": "nxattach",
            "error": "not_found",
            "id": "get_nonexistant_attach",
            "message": "Cannot find attachment",
            "method": "getAttachment",
            "reason": "missing attachment",
            "result": "error",
            "status": 404,
            "statusText": "Not Found"
          }, err);
        })
      );

      o.respond();

    }).nThen(function () {
      o.assertReqs(2, "get nonexistant attachment -> 2 request to get doc");
    }));
  });

  test("GetAttachHappyPath", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      // get attachment
      o.addFakeServerResponse(
        "xwiki",
        "GET",
        "spaces/Main/pages/get_attachment$",
        200,
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
          '<page xmlns="http://www.xwiki.org"><title>some title</title></page>'
      );
      o.addFakeServerResponse(
        "xwiki",
        "GET",
        "spaces/Main/pages/get_attachment/attachments",
        200,
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
          '<attachments xmlns="http://www.xwiki.org">' +
          '<attachment><name>attach_name</name></attachment>' +
          '</attachments>'
      );

      // We can't fully test this
      // because sinon doesn't support HTML5 blob responses.
      //o.addFakeServerResponse(
      //    "xwiki", "GET", "download/Main/get_attachment/attach_name", 200,
      //    "content", "application/octet-stream");

      o.jio.getAttachment(
        {"_id": "get_attachment", "_attachment": "attach_name"},
        waitFor(function (ret) {
          deepEqual({
            "attachment": "attach_name",
            "error": "err_network_error",
            "id": "get_attachment",
            "message": "Failed to get attachment [get_attachment/attach_name]",
            "method": "getAttachment",
            "reason": "Error getting data from network",
            "result": "error",
            "status": 404,
            "statusText": "Not Found"
          }, ret);
        })
      );

      o.respond();

    }).nThen(function () {
      o.assertReqs(3, "get attachment -> 2 requests to get doc, 1 for attach");
    }));
Tristan Cavelier's avatar
Tristan Cavelier committed
593 594
  });

Tristan Cavelier's avatar
Tristan Cavelier committed
595

596
  test("RemoveNonexistantDocument", function () {
Tristan Cavelier's avatar
Tristan Cavelier committed
597
    var o = setUp(this);
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
    nThenTest(o, nThen(function (waitFor) {

      // remove inexistent document
      o.addFakeServerResponse("xwiki", "GET", "remove1", 404, "HTML RESPONSE");

      o.jio.remove({"_id": "remove1"}, waitFor(function (ret) {
        deepEqual({
          "error": "error",
          "id": "remove1",
          "message": "Failed to delete document [remove1]",
          "method": "remove",
          "reason": "Not Found",
          "result": "error",
          "status": 404,
          "statusText": "Not Found"
        }, ret);
      }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(
        2,
        "remove nonexistent doc -> 1 request for csrf and 1 for doc"
      );
    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
625 626


627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
  test("RemoveNonexistantAttachment", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      // remove inexistent document/attachment
      o.addFakeServerResponse("xwiki", "GET", "remove1/remove2", 404, "HTML" +
                              "RESPONSE");

      o.jio.removeAttachment(
        {"_id": "remove1", "_attachment": "remove2"},
        function () {
          ok(0);
        },
        waitFor(function (err) {
          deepEqual({
            "attachment": "remove2",
            "error": "not_found",
            "id": "remove1",
            "message": "Document not found",
            "method": "removeAttachment",
            "reason": "missing document",
            "result": "error",
            "status": 404,
            "statusText": "Not Found"
          }, err);
        })
      );

      o.respond();

    }).nThen(function () {
      o.assertReqs(1, "remove nonexistant attach -> 1 request for doc");
    }));
  });
Tristan Cavelier's avatar
Tristan Cavelier committed
661 662


663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
  test("RemoveDocument", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      o.addFakeServerResponse("xwiki", "POST", "delete/Main/remove3",
                              200, "HTML RESPONSE");

      o.jio.remove({"_id": "remove3"}).then(waitFor(function (ret) {
        deepEqual({
          "id": "remove3",
          "method": "remove",
          "result": "success",
          "status": 204,
          "statusText": "No Content"
        }, ret);
      }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(
        2,
        "remove document -> 1 request for csrf and 1 for deleting doc"
      );
    }));
  });

  test("RemoveAttachment", function () {
    var o = setUp(this);
    nThenTest(o, nThen(function (waitFor) {

      // remove attachment
      o.addFakeServerResponse(
        "xwiki",
        "GET",
        "spaces/Main/pages/remove4$",
        200,
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
          '<page xmlns="http://www.xwiki.org"><title>some title</title></page>'
      );
      o.addFakeServerResponse(
        "xwiki",
        "GET",
        "spaces/Main/pages/remove4/attachments",
        200,
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
          '<attachments xmlns="http://www.xwiki.org">' +
          '<attachment><name>remove5</name></attachment>' +
          '</attachments>'
      );
      o.addFakeServerResponse(
        "xwiki",
        "POST",
        "delattachment/Main/remove4/remove5",
        200,
        "HTML RESPONSE"
      );

      o.jio.removeAttachment(
        {"_id": "remove4", "_attachment": "remove5"}
      ).always(waitFor(function (ret) {
        deepEqual({
          "attachment": "remove5",
          "id": "remove4",
          "method": "removeAttachment",
          "result": "success",
          "status": 204,
          "statusText": "No Content"
        }, ret);
      }));

      o.respond();

    }).nThen(function () {
      o.assertReqs(
        4,
        "remove attach -> get doc, get attachments, get csrf, remove attach"
      );
    }));
Tristan Cavelier's avatar
Tristan Cavelier committed
742 743 744
  });

}));