您的当前位置:首页正文

mongodb中文档id生成原理以及mock方法

来源:要发发知识网

那么当我们在对rest api服务做测试的时候,就需要来模拟这样的id,而且它必须有效的。什么意思呢?我来举个例子:假设我们要对查看博文这个api做测试,那么其中就可能会有这样两条用例:

  1. 当postId不合法时,服务器应该返回处理错误
  2. 当postId合法但不存在时,服务器应该返回处理成功并返回0条记录

其中,第1条用例我们在测试的时候,可以很简单地模拟一个无效的postId,比如:12345 这样的就可以了。但是对于第2条,我们则必须要模拟一个有效的id,它是可以通过mongodb合法性校验的,但是呢mongodb利用这个id去数据库中寻找时又是找不到对应记录的。

为了达到这样一个目的,我们必须得要知道id到底是如何生成出来的,这样我们就可以模拟出符合要求的id了。

ObjectID.prototype.generate = function(time) {
  if ('number' != typeof time) {
    time = parseInt(Date.now()/1000,10);
  }
  
  var time4Bytes = BinaryParser.encodeInt(time, 32, true, true);
  /* for time-based ObjectID the bytes following the time will be zeroed */
  var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
  var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid);
  var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);

  return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes;
};

这里的MACHINE_ID就直接采用了随机数,而其他的驱动器则采用了md5值。接下来,我们再来看看encodeInt方法:

BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) {
    var max = maxBits[bits];

  if (data >= max || data < -(max / 2)) {
    this.warn("encodeInt::overflow");
    data = 0;
  }

    if (data < 0) {
    data += max;
  }

    for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256));

    for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0");

  return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join("");
};

好了,那么归根结底,一个合法的id字符串表现形式其实就是:一个由16进制数字组成的长度为24的字符串