All files / botbuilder-unit/src/messages BotMessage.js

78.38% Statements 116/148
78.48% Branches 62/79
91.67% Functions 22/24
78.38% Lines 116/148
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 96 97 98 99 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 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 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 235 236 237 238 239 240 241 242 243 2441x 1x     116x 116x 116x 116x 116x     116x 114x       1x 1x   1x 114x               1x   114x 114x         114x           114x   111x     111x     111x     108x     108x       6x 6x 6x         1x 111x 13x   98x 5x 5x 1x 1x   4x 1x     93x 93x 93x 1x 1x   92x       1x 108x 106x   2x 2x 2x           1x 108x 97x   11x 11x 11x           1x 111x 108x   3x 1x 1x       1x       2x 2x             1x 111x 108x     3x 22x 4x 4x       4x             18x 4x       4x 5x   14x 7x       7x 14x     14x   7x           3x 3x       3x   1x   114x 110x   4x     4x 1x 1x   3x 3x 1x 1x     2x 8x 8x   8x 8x 8x   8x 8x 1x 1x     1x     1x 1x     1x       1x   1x 116x     116x 116x 116x       1x
const BaseScriptStep = require('./BaseScriptStep');
const inspect = require('util').inspect;
function BotMessage(step, config, bot, logReporter, prevStepPromise) {
 
  BaseScriptStep.call(this, step, config, bot, logReporter, prevStepPromise);
  this.receivedMessage = null;
  this.replyResolver = null;
  this.replyPromise = new Promise((resolve, reject) => {
    this.replyResolver = resolve;
  })
 
  this.stepFinishedPromise = Promise.all([prevStepPromise, this.replyPromise]).then(() => {
    return this.validate();
  });
}
 
BotMessage.prototype = Object.create(BaseScriptStep.prototype);
BotMessage.prototype.constructor = BotMessage;
 
BotMessage.prototype.isStepHasValidator = function () {
  return ("undefined" != typeof this.config.bot)
    || ("undefined" != typeof this.config.suggestedActions)
    || ("undefined" != typeof this.config.attachments)
    || ("undefined" != typeof this.config.endConversation)
    || ("undefined" != typeof this.config.typing)
}
 
 
BotMessage.prototype.validate = function () {
 
  return new Promise((resolve, reject) => {
    Iif (null == this.receivedMessage) {
      let msg = 'Can\'t continue validation. There are no received message';
      reject(msg);
      return;
    }
    Iif (!this.isStepHasValidator()) {
      let msg = `Unable to find matching validator. Step config:\n${inspect(this.config)}`;
      reject();
      return;
    }
 
    this.validateSuggestedActions()
      .then(() => {
        return this.validateAttachments();
      })
      .then(() => {
        return this.validateAttachmentLayout();
      })
      .then(() => {
        return this.validateBotMessage();
      })
      .then(() => {
        return this.validateEndConversation();
      })
      .then(() => {
        return this.validateTyping();
      })
      .then(resolve)
      .catch((error) => {
        this.logReporter.info(`Expected message at step ${this.step}`, this.config);
        this.logReporter.expectationError(this.step, this.receivedMessage, error);
        reject(error);
      })
  })
}
 
BotMessage.prototype.validateBotMessage = function () {
  if (!this.config.bot) {
    return Promise.resolve();
  }
  if ("function" == typeof this.config.bot) {
    let promise = this.config.bot.call(null, this.receivedMessage);
    if (!(promise instanceof Promise )) {
      let error = `Message validation by callback failed. Callback MUST return a promise `;
      return Promise.reject(error);
    }
    return promise.catch((error) => {
      return Promise.reject(error);
    })
  } else {
    let isRegExp = this.config.bot.test ? true : false;
    let result = isRegExp ? this.config.bot.test(this.receivedMessage.text) : this.receivedMessage.text === this.config.bot;
    if (!result) {
      let error = `Received text <${this.receivedMessage.text}> does not match <${this.config.bot}>`;
      return Promise.reject(error);
    }
    return Promise.resolve();
 
  }
}
BotMessage.prototype.validateTyping = function () {
  if (!this.config.typing) {
    return Promise.resolve();
  }
  Eif ("typing" == this.receivedMessage.type) {
    this.logReporter.typing(this.step);
    return Promise.resolve();
  } else {
    let msg = 'Typing indicator expected';
    return Promise.reject(msg);
  }
}
BotMessage.prototype.validateEndConversation = function () {
  if (!this.config.endConversation) {
    return Promise.resolve();
  }
  Eif ("endOfConversation" == this.receivedMessage.type) {
    this.logReporter.endConversation(this.step);
    return Promise.resolve();
  } else {
    let msg = 'endConversation indicator expected'
    return Promise.reject(msg);
  }
}
BotMessage.prototype.validateAttachmentLayout = function () {
  if (!this.config.attachmentLayout) {
    return Promise.resolve();
  }
  if ("function" == typeof this.config.attachmentLayout) {
    let promise = this.config.attachmentLayout.call(null, this.receivedMessage.attachmentLayout);
    Iif (!(promise instanceof Promise )) {
      let msg = `Attachment layout validation by callback failed. Callback MUST return a promise`;
      return Promise.reject((msg));
    }
    return promise.catch(() => {
      let msg = `Attachment layout validation by callback failed.`;
      return Promise.reject((msg));
    })
  } else Eif (this.config.attachmentLayout == this.receivedMessage.attachmentLayout) {
    return Promise.resolve();
  } else {
    let msg = `Attachment layout validation failed:<${this.receivedMessage.attachmentLayout}> does not match <${this.config.attachmentLayout}>`;
    return Promise.reject(msg);
  }
}
 
BotMessage.prototype.validateAttachments = function () {
  if (!this.config.attachments) {
    return Promise.resolve();
  }
 
  let iterateAndValidate = function (validatorConfig, receivedValue, path) {
    if ("function" == typeof validatorConfig) {
      let promise = validatorConfig.call(null, receivedValue, path);
      Iif (!(promise instanceof Promise )) {
        throw ('Attachment validation by callback failed. Callback MUST return a Promise');
      }
 
      return promise.catch((error) => {
        let msg = `Attachment validation by callback failed. Path: ${path}`;
        if (error) {
          msg += ' Error:' + inspect(error)
        }
        throw (msg);
      })
    } else if (Array.isArray(validatorConfig)) {
      Iif (!Array.isArray(receivedValue)) {
        let msg = `Attachment validation failed, array must exist at path: ${path}`;
        throw msg;
      }
      validatorConfig.forEach((item, i) => {
        iterateAndValidate(item, receivedValue[i], path + `[${i}]`)
      });
    } else if ("object" == typeof validatorConfig) {
      Iif ("object" != typeof receivedValue) {
        let msg = `Attachment validation failed, object must exist at path: ${path}`;
        throw msg;
      }
      for (let key in validatorConfig) {
        Iif (!validatorConfig.hasOwnProperty(key)) {
          continue;
        }
        iterateAndValidate(validatorConfig[key], receivedValue[key], path + `[${key}]`);
      }
    } else Iif (validatorConfig != receivedValue) {
      let msg = `Attachment validation failed at path: ${path}`;
      throw msg;
    }
 
  }
  try {
    iterateAndValidate(this.config.attachments, this.receivedMessage.attachments, 'attachments');
  } catch (e) {
    return Promise.reject(e);
  }
  return Promise.resolve();
}
BotMessage.prototype.validateSuggestedActions = function () {
 
  if (!this.config.suggestedActions) {
    return Promise.resolve();
  }
  let isSuggestedActionsPresent = this.receivedMessage.suggestedActions
    && this.receivedMessage.suggestedActions.actions
    && this.receivedMessage.suggestedActions.actions.length;
  if (!isSuggestedActionsPresent) {
    let msg = `Step #${this.step}, Message misses Suggested Actions`;
    return Promise.reject(msg);
  }
  let isRangeError = this.config.suggestedActions.length != this.receivedMessage.suggestedActions.actions.length;
  if (isRangeError) {
    let msg = (`Step #${this.step}, amount of received suggested actions (${this.receivedMessage.suggestedActions.actions.length}) differs from expected (${this.config.suggestedActions.length})`);
    return Promise.reject(msg);
  }
 
  for (let i = 0; i < this.config.suggestedActions.length; i++) {
    let expectedAction = this.config.suggestedActions[i];
    let messageAction = this.receivedMessage.suggestedActions.actions[i];
    //
    let isSameType = messageAction['type'] == expectedAction.data['type'];
    let isSameValue = messageAction['value'] == expectedAction.data['value'];
    let isSameTitle = messageAction['title'] == expectedAction.data['title'];
 
    let isOk = isSameTitle && isSameType && isSameValue;
    if (!isOk) {
      let msg = `Step #${this.step}, Failed to compare actions with index ${i}. Reasons:`;
      Iif ( !isSameTitle ) {
        msg += `\n- Expected title: ${expectedAction.data.title}\n- Received title: ${messageAction["title"]}`;
      }
      Iif ( !isSameType ) {
        msg += "\n- Wrong type of the card";
      }
      Eif ( !isSameValue ) {
        msg += `\n- Messages are different:\n- Expected value: ${expectedAction.data.value}\n- Received value: ${messageAction['value']}`;
      }
 
      return Promise.reject(msg);
 
    }
  }
  return Promise.resolve();
}
BotMessage.prototype.receiveBotReply = function (receivedMessage) {
  Iif (this.receivedMessage) {
    throw new Error('This step already has received message');
  }
  this.receivedMessage = receivedMessage;
  this.logReporter.messageReceived(this.step, receivedMessage);
  this.replyResolver();
 
}
 
module.exports = BotMessage;