All files / intermock/src/lang/ts intermock.ts

97.21% Statements 174/179
86.92% Branches 93/107
100% Functions 22/22
97.21% Lines 174/179

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 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 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 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 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 379 380 381 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 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 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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 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 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616                              1x   1x 1x 1x 1x 1x 1x                                                                                                               65x 65x   65x 11x 54x 28x   26x                           75x 2x 1x     1x         74x                             47x 47x                                     3x 3x   3x 3x   3x   1x 1x         1x 1x   2x   2x     3x 3x                                         12x 1x   11x     12x 1x     1x     11x   4x 4x   7x   2x 2x       2x 2x         5x 5x 5x                                               11x 11x   11x 11x     11x 11x 11x 11x           11x 11x                                     3x 3x   3x 2x     3x       3x       3x 9x 3x     6x 6x                                     104x 29x     75x 75x   75x 11x     75x 75x   75x     75x 1x       74x 11x 11x     63x 63x 63x     63x   11x     11x   2x     2x   3x   3x   47x   47x       75x                           4x 320x   16x 4x 4x 4x     4x 2x   1x 1x   1x   1x         2x     16x   304x     320x     4x                                   33x 4x 4x     33x 18x 18x 18x           33x   104x       47x 44x     3x 1x     2x                               24x 1429x           39x 39x 1x   38x 20x 9x       18x   38x   8x 8x   8x       8x 4x 2x       4x     8x     1382x     1428x     24x                   13x   13x 622x 622x       622x 63x   559x     622x   622x     13x   13x                   13x   1x       12x                             1x 13x 13x     13x       13x 13x       13x 13x         13x    
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import ts from 'typescript';
 
import {DEFAULT_ARRAY_RANGE, FIXED_ARRAY_COUNT} from '../../lib/constants';
import {defaultTypeToMock} from '../../lib/default-type-to-mock';
import {fake} from '../../lib/fake';
import {randomRange} from '../../lib/random-range';
import {smartProps} from '../../lib/smart-props';
import {stringify} from '../../lib/stringify';
 
/**
 * Intermock general options
 */
export interface Options {
  // Array of file tuples. (filename, data)
  files?: Array<[string, string]>;
 
  // TypeScript is currently the only supported language
  language?: SupportedLanguage;
 
  // Specific interfaces to write to output
  interfaces?: string[];
 
  // Used for testing mode,
  isFixedMode?: boolean;
 
  // One of object|json|string. Strings have their object's functions
  // stringified.
  output?: OutputType;
 
  // Should optional properties always be enabled
  isOptionalAlwaysEnabled?: boolean;
}
 
type OutputType = 'object'|'json'|'string';
type SupportedLanguage = 'typescript';
 
interface JSDoc {
  comment: string;
}
 
interface NodeWithDocs extends ts.PropertySignature {
  jsDoc: JSDoc[];
}
 
type TypeCacheRecord = {
  kind: ts.SyntaxKind,
  aliasedTo: ts.SyntaxKind
};
 
type Output = Record<string, {}>;
type Types = Record<string, {}>;
 
/**
 * Generate fake data using faker for primitive types: string|number|boolean.
 *
 * @param property Output property to write to
 * @param syntaxType Type of primitive, such as boolean|number|string
 * @param options Intermock options object
 * @param mockType Optional specification of what Faker type to use
 */
function generatePrimitive(
    property: string, syntaxType: ts.SyntaxKind, options: Options,
    mockType?: string) {
  const smartMockType = smartProps[property];
  const isFixedMode = options.isFixedMode ? options.isFixedMode : false;
 
  if (mockType) {
    return fake(mockType, options.isFixedMode);
  } else if (smartMockType) {
    return fake(smartMockType, options.isFixedMode);
  } else {
    return defaultTypeToMock[syntaxType](isFixedMode);
  }
}
 
/**
 * Determines if a property marked as optional will have fake data generated for
 * it. Invokes this using Math.random.
 *
 * @param questionToken
 * @param options Intermock general options object
 */
function isQuestionToken(
    questionToken: ts.Token<ts.SyntaxKind.QuestionToken>|undefined,
    options: Options) {
  if (questionToken) {
    if (options.isFixedMode && !options.isOptionalAlwaysEnabled) {
      return true;
    }
 
    else Iif (Math.random() < .5 && !options.isOptionalAlwaysEnabled) {
      return true;
    }
  }
 
  return false;
}
 
/**
 * Process an untyped interface property, defaults to generating a primitive.
 *
 * @param output The object outputted by Intermock after all types are mocked
 * @param property Output property to write to
 * @param kind TS data type of property type
 * @param mockType Specification of what Faker type to use
 * @param options Intermock general options object
 */
function processGenericPropertyType(
    output: Output, property: string, kind: ts.SyntaxKind, mockType: string,
    options: Options) {
  const mock = generatePrimitive(property, kind, options, mockType);
  output[property] = mock;
}
 
/**
 * Generate a function for a call signature of a property of an interface. Uses
 * the `new Function` constructor and stringifies any internal function
 * declarations/calls or returned complex types.
 *
 * @param node Node being processed
 * @param output The object outputted by Intermock after all types are mocked
 * @param property Output property to write to
 * @param sourceFile TypeScript AST object compiled from file data
 * @param options Intermock general options object
 * @param types Top-level types of interfaces/aliases etc.
 */
function processFunctionPropertyType(
    node: ts.PropertySignature, output: Output, property: string,
    sourceFile: ts.SourceFile, options: Options, types: Record<string, {}>) {
  // TODO process args from parameters of function
  const args = '';
  let body = '';
 
  const funcNode = node.type as ts.FunctionTypeNode;
  const returnType = funcNode.type;
 
  switch (returnType.kind) {
    case ts.SyntaxKind.TypeReference:
      const tempBody: Record<string, {}> = {};
      processPropertyTypeReference(
          node, tempBody, 'body',
          ((returnType as ts.TypeReferenceNode).typeName as ts.Identifier).text,
          returnType.kind, sourceFile, options, types);
 
      body = `return ${stringify(tempBody['body'])}`;
      break;
    default:
      body = `return ${
          JSON.stringify(generatePrimitive('', returnType.kind, options))}`;
      break;
  }
 
  const func = new Function(args, body);
  output[property] = func;
}
 
/**
 * Process an individual interface property.
 *
 * @param node Node being processed
 * @param output The object outputted by Intermock after all types are mocked
 * @param property Output property to write to
 * @param typeName Type name of property
 * @param kind TS data type of property type
 * @param sourceFile TypeScript AST object compiled from file data
 * @param options Intermock general options object
 * @param types Top-level types of interfaces/aliases etc.
 */
function processPropertyTypeReference(
    node: ts.PropertySignature, output: Output, property: string,
    typeName: string, kind: ts.SyntaxKind, sourceFile: ts.SourceFile,
    options: Options, types: Record<string, {}>) {
  let normalizedTypeName;
 
  if (typeName.startsWith('Array<')) {
    normalizedTypeName = typeName.replace('Array<', '').replace('>', '');
  } else {
    normalizedTypeName = typeName;
  }
 
  if (normalizedTypeName !== typeName) {
    processArrayPropertyType(
        node, output, property, normalizedTypeName, kind, sourceFile, options,
        types);
    return;
  }
 
  switch ((types[normalizedTypeName] as TypeCacheRecord).kind) {
    case ts.SyntaxKind.EnumDeclaration:
      setEnum(sourceFile, output, typeName, property);
      break;
    default:
      if ((types[normalizedTypeName] as TypeCacheRecord).kind !==
          (types[normalizedTypeName] as TypeCacheRecord).aliasedTo) {
        const alias = (types[normalizedTypeName] as TypeCacheRecord).aliasedTo;
        const isPrimitiveType = alias === ts.SyntaxKind.StringKeyword ||
            alias === ts.SyntaxKind.NumberKeyword ||
            alias === ts.SyntaxKind.BooleanKeyword;
 
        Eif (isPrimitiveType) {
          output[property] = generatePrimitive(property, alias, options, '');
        } else {
          // TODO
        }
      } else {
        output[property] = {};
        processFile(sourceFile, output[property], options, types, typeName);
        break;
      }
  }
}
 
/**
 * Process JSDocs to determine if a different Faker type should be used to mock
 * the data of the interface.
 *
 * @param node Node being processed
 * @param output The object outputted by Intermock after all types are mocked
 * @param property Output property to write to
 * @param jsDocs JSDocs to process
 * @param options Intermock general options object
 */
function processJsDocs(
    node: ts.PropertySignature, output: Output, property: string,
    jsDocs: JSDoc[], options: Options) {
  // TODO handle case where we get multiple mock JSDocs or a JSDoc like
  // mockRange for an array. In essence, we are only dealing with
  // primitives now
 
  // TODO Handle error case where a complex type has MockDocs
 
  let mockType = '';
  let jsDocComment = '';
 
  Eif (jsDocs.length > 0 && jsDocs[0].comment) {
    jsDocComment = jsDocs[0].comment;
  }
 
  Eif (jsDocComment.startsWith('!mockType')) {
    const match = jsDocComment.match(/(?<=\{).+?(?=\})/g);
    Eif (match) {
      mockType = match[0];
    }
  } else {
    // TODO
  }
 
  const mock = generatePrimitive(property, node.kind, options, mockType);
  output[property] = mock;
}
 
/**
 * Process an array definition.
 *
 * @param node Node being processed
 * @param output The object outputted by Intermock after all types are mocked
 * @param property Output property to write to
 * @param typeName Type name of property
 * @param kind TS data type of property type
 * @param sourceFile TypeScript AST object compiled from file data
 * @param options Intermock general options object
 * @param types Top-level types of interfaces/aliases etc.
 */
function processArrayPropertyType(
    node: ts.PropertySignature, output: Output, property: string,
    typeName: string, kind: ts.SyntaxKind, sourceFile: ts.SourceFile,
    options: Options, types: Record<string, {}>) {
  typeName = typeName.replace('[', '').replace(']', '');
  output[property] = [];
 
  if ((node.type as ts.ArrayTypeNode).elementType) {
    kind = (node.type as ts.ArrayTypeNode).elementType.kind;
  }
 
  const isPrimitiveType = kind === ts.SyntaxKind.StringKeyword ||
      kind === ts.SyntaxKind.BooleanKeyword ||
      kind === ts.SyntaxKind.NumberKeyword;
 
  const arrayRange = options.isFixedMode ?
      FIXED_ARRAY_COUNT :
      randomRange(DEFAULT_ARRAY_RANGE[0], DEFAULT_ARRAY_RANGE[1]);
 
  for (let i = 0; i < arrayRange; i++) {
    if (isPrimitiveType) {
      (output[property] as Array<{}>)[i] =
          generatePrimitive(property, kind, options, '');
    } else {
      (output[property] as Array<{}>).push({});
      processFile(
          sourceFile, (output[property] as Array<{}>)[i], options, types,
          typeName);
    }
  }
}
 
/**
 * Process each interface property.
 *
 * @param node Node being processed
 * @param output The object outputted by Intermock after all types are mocked
 * @param sourceFile TypeScript AST object compiled from file data
 * @param options Intermock general options object
 * @param types Top-level types of interfaces/aliases etc.
 */
function traverseInterfaceMembers(
    node: ts.Node, output: Output, sourceFile: ts.SourceFile, options: Options,
    types: Record<string, {}>) {
  if (node.kind !== ts.SyntaxKind.PropertySignature) {
    return;
  }
 
  const processPropertySignature = (node: ts.PropertySignature) => {
    let jsDocs: JSDoc[] = [];
 
    if ((node as NodeWithDocs).jsDoc) {
      jsDocs = (node as NodeWithDocs).jsDoc;
    }
 
    const property = node.name.getText();
    const questionToken = node.questionToken;
 
    let typeName = '';
    let kind;
 
    if (isQuestionToken(questionToken, options)) {
      return;
    }
 
 
    if (jsDocs.length > 0) {
      processJsDocs(node, output, property, jsDocs, options);
      return;
    }
 
    Eif (node.type) {
      kind = node.type.kind;
      typeName = node.type.getText();
    }
 
    switch (kind) {
      case ts.SyntaxKind.TypeReference:
        processPropertyTypeReference(
            node, output, property, typeName, kind as ts.SyntaxKind, sourceFile,
            options, types);
        break;
      case ts.SyntaxKind.ArrayType:
        processArrayPropertyType(
            node, output, property, typeName, kind as ts.SyntaxKind, sourceFile,
            options, types);
        break;
      case ts.SyntaxKind.FunctionType:
        processFunctionPropertyType(
            node, output, property, sourceFile, options, types);
        break;
      default:
        processGenericPropertyType(
            output, property, kind as ts.SyntaxKind, '', options);
        break;
    }
  };
 
  processPropertySignature(node as ts.PropertySignature);
}
 
/**
 * Process an enum and set it.
 *
 * @param sourceFile TypeScript AST object compiled from file data
 * @param output The object outputted by Intermock after all types are mocked
 * @param typeName Type name of property
 * @param property Output property to write to
 */
function setEnum(
    sourceFile: ts.SourceFile, output: Output, typeName: string,
    property: string) {
  const processNode = (node: ts.Node) => {
    switch (node.kind) {
      case ts.SyntaxKind.EnumDeclaration:
        if ((node as ts.EnumDeclaration).name.text === typeName) {
          const members = (node as ts.EnumDeclaration).members;
          const selectedMemberIdx = Math.floor(members.length / 2);
          const selectedMember = members[selectedMemberIdx];
 
          // TODO handle bitwise initializers
          if (selectedMember.initializer) {
            switch (selectedMember.initializer.kind) {
              case ts.SyntaxKind.NumericLiteral:
                output[property] = Number(selectedMember.initializer.getText());
                break;
              case ts.SyntaxKind.StringLiteral:
                output[property] =
                    selectedMember.initializer.getText().replace(/\'/g, '');
                break;
              default:
                break;
            }
          } else {
            output[property] = selectedMemberIdx;
          }
        }
        break;
      default:
        break;
    }
 
    ts.forEachChild(node, processNode);
  };
 
  processNode(sourceFile);
}
 
/**
 * Traverse each declared interface in a node.
 *
 * @param node Node being processed
 * @param output The object outputted by Intermock after all types are mocked
 * @param sourceFile TypeScript AST object compiled from file data
 * @param options Intermock general options object
 * @param types Top-level types of interfaces/aliases etc.
 * @param propToTraverse Optional specific property to traverse through the
 *     interface
 * @param path Optional specific path to write to on the output object
 */
function traverseInterface(
    node: ts.Node, output: Output, sourceFile: ts.SourceFile, options: Options,
    types: Types, propToTraverse?: string, path?: string) {
  if (path) {
    output[path] = {};
    output = output[path];
  }
 
  if (!propToTraverse && !path) {
    const newPath = (node as ts.InterfaceDeclaration).name.text;
    output[newPath] = {};
    output = output[newPath];
  }
 
  // TODO get range from JSDoc
  // TODO given a range of interfaces to generate, add to array. If 1
  // then just return an object
  node.forEachChild(
      child =>
          traverseInterfaceMembers(child, output, sourceFile, options, types));
}
 
function isSpecificInterface(name: string, options: Options) {
  if (!options.interfaces) {
    return true;
  }
 
  if (options.interfaces.indexOf(name) === -1) {
    return false;
  }
 
  return true;
}
 
/**
 * Process an individual TS file given a TS AST object.
 *
 * @param sourceFile TypeScript AST object compiled from file data
 * @param output The object outputted by Intermock after all types are mocked
 * @param options Intermock general options object
 * @param types Top-level types of interfaces/aliases etc.
 * @param propToTraverse Optional specific property to traverse through the
 *     interface
 */
function processFile(
    sourceFile: ts.SourceFile, output: Output, options: Options, types: Types,
    propToTraverse?: string) {
  const processNode = (node: ts.Node) => {
    switch (node.kind) {
      case ts.SyntaxKind.InterfaceDeclaration:
        /**
         * TODO: Handle interfaces that extend others, via checking hertiage
         * clauses
         */
        const p = (node as ts.InterfaceDeclaration).name.text;
        if (!isSpecificInterface(p, options) && !propToTraverse) {
          return;
        }
        if (propToTraverse) {
          if (p === propToTraverse) {
            traverseInterface(
                node, output, sourceFile, options, types, propToTraverse);
          }
        } else {
          traverseInterface(node, output, sourceFile, options, types);
        }
        break;
      case ts.SyntaxKind.TypeAliasDeclaration:
        const type = (node as ts.TypeAliasDeclaration).type;
        const path = (node as ts.TypeAliasDeclaration).name.text;
 
        Iif (!isSpecificInterface(path, options)) {
          return;
        }
 
        if (propToTraverse) {
          if (path === propToTraverse) {
            traverseInterface(
                type, output, sourceFile, options, types, propToTraverse);
          }
        } else {
          traverseInterface(
              type, output, sourceFile, options, types, undefined, path);
        }
        break;
 
      default:
        break;
    }
 
    ts.forEachChild(node, processNode);
  };
 
  processNode(sourceFile);
}
 
/**
 * Gathers all interfaces and types references ahead of time so that when
 * interface properties reference them then we can know their type.
 *
 * @param sourceFile TypeScript AST object compiled from file data
 */
function gatherTypes(sourceFile: ts.SourceFile) {
  const types: Types = {};
 
  const processNode = (node: ts.Node) => {
    const name = (node as ts.DeclarationStatement).name;
    const text = name ? name.text : '';
 
    let aliasedTo;
 
    if ((node as ts.TypeAliasDeclaration).type) {
      aliasedTo = (node as ts.TypeAliasDeclaration).type.kind;
    } else {
      aliasedTo = node.kind;
    }
 
    types[text] = {kind: node.kind, aliasedTo};
 
    ts.forEachChild(node, processNode);
  };
 
  processNode(sourceFile);
 
  return types;
}
 
/**
 * Fromat output based on the specified output type in the options object.
 *
 * @param output The object outputted by Intermock after all types are mocked
 * @param options Intermock general options object
 */
function formatOutput(output: Output, options: Options): string|Output {
  switch (options.output) {
    case 'json':
      return JSON.stringify(output);
    case 'string':
      return stringify(output);
    default:
      return output;
  }
}
 
/**
 * Intermock API.
 *
 * Given an options object, with a files array property, Intermock parses the
 * AST and generates mock objects with fake data.
 *
 * This is the only part of the API exposed to a caller (including the CLI). All
 * data is passed through the `files` property on the options object.
 *
 * @param options Intermock general options object
 */
export function mock(options: Options) {
  const output: Output = {};
  const fileContents = options.files;
  let types: Types;
 
  Iif (!fileContents) {
    return {};
  }
 
  fileContents.forEach((f) => {
    types = gatherTypes(
        ts.createSourceFile(f[0], f[1], ts.ScriptTarget.ES2015, true));
  });
 
  fileContents.forEach((f) => {
    processFile(
        ts.createSourceFile(f[0], f[1], ts.ScriptTarget.ES2015, true), output,
        options, types);
  });
 
  return formatOutput(output, options);
}