All files / lib tools.js

99.52% Statements 209/210
100% Branches 66/66
95.45% Functions 42/44
99.46% Lines 185/186

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                2x   2x 2x 2x 2x 2x 2x   2x 2x 2x 2x   2x   2x                         2x 3x 1x 1x   3x 1x                     2x 3x   3x 1x 1x     2x 2x 2x 2x                           2x 3x   3x 3x   3x 2x 2x     1x 1x                         2x 2x   2x 1x 1x     1x 1x                         2x 2x 2x 2x 1x                     2x 3x   3x 1x 1x     2x 2x 2x                   2x 1x   1x 1x 1x 1x 1x 1x             1x 1x                   2x 1x 1x   1x   1x         1x     2x                             2x 2x 3x                   2x 2x 2x   2x 2x   1x 1x 1x   1x             2x 2x 2x   2x 2x   1x 1x 1x   1x             2x 2x 2x   2x 4x 1x   3x       2x 2x   1x 1x 1x   1x             2x 4x         3x 1x 1x 1x     2x   2x 2x 2x   2x 1x   2x       2x               2x 1x   1x 3x 2x 2x   1x           1x             2x 3x   3x 6x 4x   2x   2x     3x                   2x 1x   1x                   1x 1x 5x     1x         16x 10x 10x 3x   1x                         2x 1x   1x 2x 2x   1x             1x             2x 2x             2x 3x   3x 6x 4x   2x   2x     3x 1x 1x     3x             2x 1x 1x   1x 1x 3x       1x             2x 3x 1x   1x 2x     1x             2x 1x    
"use strict";
 
/**
 * Glace tools.
 *
 * @module
 */
 
const util = require("util");
 
require("colors");
const _ = require("lodash");
const expect = require("chai").expect;
const highlight = require("cli-highlight").highlight;
const Testrail = require("testrail-api");
const U = require("glace-utils");
 
const classifier = require("./classifier")();
const CONF = require("./config");
const plugins = require("./plugins");
const utils = require("./utils");
 
const d = U.switchColor();
 
let stepsCache = null;
 
/**
 * Get list of steps data, where step data is an object with keys:
 * `name` - name of step, `decription` - short details of steps,
 * `doc` - documentation of step.
 *
 * @memberOf module:tools
 * @function
 * @arg {string} [filter] - String chunk to filter steps.
 * @arg {boolean} [namesOnly=false] - Flag to filter by step names only.
 * @return {array<object>}
 */
const listSteps = (filter, namesOnly=false) => {
    if (!stepsCache) {
        stepsCache = getStepsData(getStepNames());
        learnClassifier(stepsCache);
    }
    if (!filter) return stepsCache;
    return filterSteps(stepsCache, filter, namesOnly);
};
 
/**
 * Print list of steps in stdout.
 *
 * @memberOf module:tools
 * @function
 * @arg {string} [filter] - String chunk to filter steps.
 * @arg {boolean} [namesOnly=false] - Flag to filter by step names only.
 */
const printSteps = (filter, namesOnly=false) => {
    const steps = listSteps(filter, namesOnly);
 
    if (!steps.length) {
        console.log("No steps are found".yellow);
        return;
    }
 
    steps.reverse().forEach((step, i) => {
        console.log(d(`${i+1}. ${step.name}:`));
        console.log(d(step.description));
        if (step.doc) console.log(highlight(step.doc, { language: "js" }));
    });
};
 
/**
 * Print list of implemented test cases.
 *
 * <img src="./list_tests.gif" title="listTests example" />
 *
 * @memberOf module:tools
 * @name listTests
 * @function
 * @arg {string} [filter] - String chunk to filter test cases.
 */
const printTests = filter => {
    fakeLoad();
 
    let cases = CONF.test.cases;
    if (filter) cases = cases.filter(c => U.textContains(c.name, filter));
 
    if (!cases.length) {
        console.log("No tests are found".yellow);
        return;
    }
 
    cases.forEach((c, i) => {
        console.log(d(`${i+1}. ${c.name}`));
    });
};
 
/**
 * Print list of available plugins.
 *
 * <img src="./list_plugins.gif" title="listPlugins example" />
 *
 * @memberOf module:tools
 * @name listPlugins
 * @function
 */
const printPlugins = () => {
    const pluginsList = plugins.get();
 
    if (!pluginsList.length) {
        console.log("No plugins are detected".yellow);
        return;
    }
 
    pluginsList.forEach((p, i) => {
        console.log(`${i+1}. ${p.name}`.yellow, p.path);
    });
};
 
/**
 * Get list of available fixtures.
 *
 * @memberOf module:tools
 * @function
 * @arg {string} [filter] - String chunk to filter fixtures.
 * @arg {boolean} [namesOnly=false] - Flag to filter by fixture names only.
 * @return {array<object>}
 */
const listFixtures = (filter, namesOnly=false) => {
    fakeLoad();
    const fixtures = getFixtures();
    if (!filter) return fixtures;
    return filterFixtures(fixtures, filter, namesOnly);
};
 
/**
 * Print list of fixtures in stdout.
 *
 * @memberOf module:tools
 * @function
 * @arg {string} [filter] - String chunk to filter fixtures.
 * @arg {boolean} [namesOnly=false] - Flag to filter by fixture names only.
 */
const printFixtures = (filter, namesOnly=false) => {
    const fixtures = listFixtures(filter, namesOnly);
 
    if (!fixtures.length) {
        console.log("No fixtures are found".yellow);
        return;
    }
 
    fixtures.forEach((fx, i) => {
        console.log(d(`${i+1}. ${fx.name}`));
        if (fx.doc) console.log(highlight(fx.doc, { language: "js" }));
    });
};
 
/**
 * Make fake load of tests in order to collect tests, fixtures, steps, etc.
 *
 * @memberOf module:tools
 * @function
 */
const fakeLoad = () => {
    const dummy = () => {};
 
    global.before = dummy;
    global.after = dummy;
    global.beforeEach = dummy;
    global.afterEach = dummy;
    global.it = dummy;
    global.describe = (name, cb) => {
        cb.call({
            retries: dummy,
            timeout: dummy,
        });
    };
 
    require("./globals");
    require("./loader");
};
 
/**
 * Check testrail cases consistency with implemented tests.
 *
 * @memberOf module:tools
 * @function
 * @arg {function} cb - Callback function.
 */
const checkTestrail = cb => {
    checkTestrailOpts();
    fakeLoad();
 
    console.log("TestRail connecting...".yellow);
 
    const testrail = new Testrail({
        host: CONF.testrail.host,
        user: CONF.testrail.user,
        password: CONF.testrail.token });
 
    checkTestrailCases(testrail, cb);
};
 
module.exports = {
    checkTestrail,
    fakeLoad,
    listSteps,
    printSteps,
    printTests,
    printPlugins,
    listFixtures,
    printFixtures,
};
 
/**
 * Check testrail options.
 * @ignore
 */
const checkTestrailOpts = () => {
    for (const opt in CONF.testrail) {
        expect(CONF.testrail[opt],
            `TestRail option '${opt}' isn't specified in config`)
            .to.exist;
    }
};
 
/**
 * Check testrail missed cases which are implemented.
 * @ignore
 */
const checkTestrailMissed = cases => {
    const testrailNames = cases.map(case_ => case_.title);
    const testNames = CONF.test.cases.map(case_ => case_.name);
 
    const missed = _.difference(testNames, testrailNames);
    if (!missed.length) return 0;
 
    console.log("\nMissed TestRail cases:".magenta.bold);
    missed.forEach((title, i) => {
        console.log(`${i+1}. ${title}`.cyan.bold);
    });
    return 1;
};
 
/**
 * Check testrail cases which are not implemented yet.
 * @ignore
 */
const checkTestrailNotImplemented = cases => {
    const testrailNames = cases.map(case_ => case_.title);
    const testNames = CONF.test.cases.map(case_ => case_.name);
 
    const notImplemented = _.difference(testrailNames, testNames);
    if (!notImplemented.length) return 0;
 
    console.log("\nNot implemented TestRail cases:".magenta.bold);
    notImplemented.forEach((title, i) => {
        console.log(`${i+1}. ${title}`.cyan.bold);
    });
    return 1;
};
 
/**
 * Check testrail duplicated cases.
 * @ignore
 */
const checkTestrailDuplicates = cases => {
    const testrailNames = [];
    let testrailDups = [];
 
    cases.forEach(case_ => {
        if (testrailNames.includes(case_.title)) {
            testrailDups.push(case_.title);
        } else {
            testrailNames.push(case_.title);
        }
    });
 
    testrailDups = _.uniq(testrailDups);
    if (!testrailDups.length) return 0;
 
    console.log("\nTestRail duplicated cases:".magenta.bold);
    testrailDups.forEach((title, i) => {
        console.log(`${i+1}. ${title}`.cyan.bold);
    });
    return 1;
};
 
/**
 * Check testrail cases.
 * @ignore
 */
const checkTestrailCases = (client, cb) => {
    client.getCases(
        CONF.testrail.projectId,
        { suite_id: CONF.testrail.suiteId },
        (err, response, cases) => {
 
            if (err) {
                console.log(err);
                cb(1);
                return;
            }
 
            let errorCode = 0;
 
            errorCode += checkTestrailDuplicates(cases);
            errorCode += checkTestrailNotImplemented(cases);
            errorCode += checkTestrailMissed(cases);
 
            if (!errorCode) {
                console.log("TestRail cases correspond current tests".green.bold);
            }
            console.log(
                "\nTestRail suite is",
                `${CONF.testrail.host}/index.php?/suites/view/${CONF.testrail.suiteId}`.yellow);
 
            cb(errorCode);
        });
};
 
/**
 * Get fixtures.
 * @ignore
 */
const getFixtures = () => {
    const fixtures = [];
 
    for (const name in global) {
        if (!name.startsWith("fx")) continue;
        const func = global[name];
        if (!util.isFunction(func)) continue;
 
        fixtures.push({
            name: name,
            doc: utils.getDoc(func),
        });
    }
 
    return fixtures;
};
 
/**
 * Filter fixtures.
 * @ignore
 */
const filterFixtures = (fixtures, filter, namesOnly) => {
    const filtered = [];
 
    for (const fx of fixtures) {
        if (namesOnly) {
            if (!U.textContains(fx.name, filter)) continue;
        } else {
            if (!U.textContains(fx.name, filter) && !U.textContains(fx.doc, filter)) continue;
        }
        filtered.push(fx);
    }
 
    return filtered;
};
 
/**
 * Get list of step names.
 *
 * @ignore
 * @function
 * @return {array<string>}
 */
const getStepNames = () => {
    global.$ || fakeLoad();
 
    const NOT_STEPS = [
        "constructor",
        "hasOwnProperty",
        "isPrototypeOf",
        "propertyIsEnumerable",
        "toLocaleString",
        "toString",
        "valueOf",
    ];
 
    let names = [];
    for (const key in $) {
        names.push(key);
    };
 
    names = _.union(
        names,
        Object.getOwnPropertyNames($),
        Object.getOwnPropertyNames(Object.getPrototypeOf($))
    ).sort()
        .filter(i => !i.startsWith("_"))
        .filter(i => /^\w+$/.test(i))
        .filter(i => !NOT_STEPS.includes(i))
        .filter(i => /^\D/.test(i));
 
    return names;
};
 
/**
 * Get list of step data, where step data is an object with keys:
 * `name` - name of step, `decription` - short details of steps,
 * `doc` - documentation of step.
 *
 * @ignore
 * @function
 * @arg {array<string>} names - List of step names.
 * @return {array<object>} 
 */
const getStepsData = names => {
    const result = [];
 
    for (const name of names) {
        const func = $[name];
        if (!util.isFunction(func)) continue;
 
        result.push({
            name: name,
            description: funcDescription(func),
            doc: utils.getDoc(func),
        });
    };
 
    return result;
};
 
/**
 * Learn classifier on step names and description.
 * @ignore
 */
const learnClassifier = steps => {
    steps.forEach(step => classifier.learn(step.doc, step.name));
};
 
/**
 * Filter steps and return relevant result merged with ML predictions.
 * @ignore
 */
const filterSteps = (steps, filter, namesOnly) => {
    let filtered = [];
 
    for (const step of steps) {
        if (namesOnly) {
            if (!U.textContains(step.name, filter)) continue;
        } else {
            if (!U.textContains(step.name, filter) && !U.textContains(step.doc, filter)) continue;
        }
        filtered.push(step);
    }
 
    if (!namesOnly) {
        const classified = classifySteps(steps, filter);
        filtered = mergeSteps(classified, filtered);
    }
 
    return filtered;
};
 
/**
 * Get classified steps based on ML.
 * @ignore
 */
const classifySteps = (steps, filter) => {
    const result = [];
    const sampling = classifier.classify(filter);
 
    for (const sample of sampling) {
        for (const step of steps) {
            if (sample.label === step.name) result.push(step);
        }
    }
 
    return result;
};
 
/**
 * Merge steps.
 * @ignore
 */
const mergeSteps = (base, merging) => {
    const usedNames = base.map(s => s.name);
    const result = _.clone(base);
 
    for (const step of merging) {
        if (!usedNames.includes(step.name)) result.push(step);
    }
 
    return result;
};
 
/**
 * Get function description.
 * @ignore 
 */
const funcDescription = func => {
    return "  " + func.toString().replace("\n", " ").split(/\) *\{/)[0] + ") {...}";
};