๐Ÿ“ฆ JohanLorenzo / markdown-testfile-to-json

๐Ÿ“„ index.js ยท 92 lines
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'use strict';

var Promise = require('promise');
var readFile = Promise.denodeify(require('fs').readFile);
var parseMarkdown = require('./lib/parsers/markdown');
var errorHandler = require('./lib/error-handler');
var _ = require('lodash');

module.exports = function(inputFilePaths) {
  var promises = inputFilePaths.map(_handleSingleFilePath);

  return Promise.all(promises).then(function(suitesPerFile) {

    var allSuites = _.flatten(suitesPerFile);
    var mergedSuites = _mergeSuites(allSuites);
    _linkSuiteVariables(mergedSuites);

    // Sometimes some promises have failed
    if (errorHandler.hasAnyError()) {
      return Promise.reject(errorHandler.errors);
    } else {
      return Promise.resolve(mergedSuites);
    }

  }).catch(function() {
    return Promise.reject(errorHandler.errors);
  });
};

function _linkSuiteVariables(mergedSuites) {
  mergedSuites.forEach(function(suite) {
    if(typeof suite.variables !== 'undefined') {
      _linkSuiteVariablesToTestcases(suite.variables, suite.testcases);
      delete suite.variables;
    }
  });
}

function _linkSuiteVariablesToTestcases(suiteVariables, testcases) {
  testcases.forEach(function(testcase) {
    var testcaseVariables = suiteVariables[testcase.id];

    if (typeof testcaseVariables === 'undefined') {
      errorHandler.add(new Error('The id "' + testcase.id + '" mentioned in the table is not defined in the suite'));
    } else {
      testcase.variablesFromSuite = testcaseVariables;
    }
  });
}

function _handleSingleFilePath(inputFilePath) {
  return readFile(inputFilePath, 'utf8').then(function(text) {
    var json = parseMarkdown(text);
    if (errorHandler.hasAnyErrorWithoutFileNameSet()) {
      errorHandler.setFileNameIfNotSet(inputFilePath);
      // We don't specify the reasons because, all the errors we'll need are
      // in the error handler
      return Promise.reject();
    }
    return Promise.resolve(json);
  });
}

function _mergeSuites(nonMutableSuites) {
  var mutableSuites = nonMutableSuites.slice();
  var mergedSuites = [];

  while (mutableSuites.length > 0) {
    var originalSuite = _.pullAt(mutableSuites, 0)[0];

    for (var j = 0; j < mutableSuites.length;) {
      if (originalSuite.name !== mutableSuites[j].name) {
        j++;
      } else {
        var duplicateSuite = mutableSuites[j];
        originalSuite = _.merge(originalSuite, duplicateSuite, _mergeArraysCustomizer);
        _.pullAt(mutableSuites, j);
      }
    }

    mergedSuites.push(originalSuite);
  }

  return mergedSuites;
}

function _mergeArraysCustomizer(a, b) {
  if (_.isArray(a)) {
    return a.concat(b);
  }
}