All files / wdio-testingbot-service/src service.js

98.68% Statements 75/76
86.21% Branches 50/58
100% Functions 18/18
98.67% Lines 74/75

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      1x 1x       27x 27x             16x 16x 16x 16x 16x 16x   16x               4x               3x 1x                 2x       2x   2x       2x 1x                 2x 1x                 2x 1x     1x 1x               3x                           3x                 2x 1x   1x 1x               3x 1x     2x           2x       2x   2x 1x 1x     1x 3x 3x         3x 1x   2x   2x 1x 1x     1x 3x 1x 1x       8x                 2x 2x 1x   1x 1x                   9x       11x         11x         11x 5x 5x 1x     5x     11x 55x 43x     12x     11x 5x     11x 11x      
import request from 'request'
import logger from '@wdio/logger'
 
const log = logger('@wdio/testingbot-service')
const jobDataProperties = ['name', 'tags', 'public', 'build', 'extra']
 
export default class TestingBotService {
    constructor () {
        this.testCnt = 0
        this.failures = 0
    }
 
    /**
     * gather information about runner
     */
    beforeSession (config, capabilities) {
        this.config = config
        this.capabilities = capabilities
        this.config.user = config.user
        this.config.key = config.key
        this.tbUser = this.config.user
        this.tbSecret = this.config.key
 
        this.isServiceEnabled = this.tbUser && this.tbSecret
    }
 
    /**
     * Before suite
     * @param {Object} suite Suite
    */
    beforeSuite (suite) {
        this.suiteTitle = suite.title
    }
 
    /**
     * Before test
     * @param {Object} test Test
    */
    beforeTest (test) {
        if (!this.isServiceEnabled) {
            return
        }
 
        /**
         * in jasmine we get Jasmine__TopLevel__Suite as title since service using test
         * framework hooks in order to execute async functions.
         * This tweak allows us to set the real suite name for jasmine jobs.
         */
        /* istanbul ignore if */
        if (this.suiteTitle === 'Jasmine__TopLevel__Suite') {
            this.suiteTitle = test.fullName.slice(0, test.fullName.indexOf(test.title) - 1)
        }
 
        const context = test.parent === 'Jasmine__TopLevel__Suite' ? test.fullName : test.parent + ' - ' + test.title
 
        global.browser.execute('tb:test-context=' + context)
    }
 
    afterSuite (suite) {
        if (Object.prototype.hasOwnProperty.call(suite, 'error')) {
            ++this.failures
        }
    }
 
    /**
     * After test
     * @param {Object} test Test
     */
    afterTest (test) {
        if (!test.passed) {
            ++this.failures
        }
    }
 
    /**
     * Before feature
     * @param {Object} feature Feature
     */
    beforeFeature (uri, feature) {
        if (!this.isServiceEnabled) {
            return
        }
 
        this.suiteTitle = feature.name || feature.getName()
        global.browser.execute('tb:test-context=Feature: ' + this.suiteTitle)
    }
 
    /**
     * After step
     * @param {Object} feature Feature
     */
    afterStep (uri, feature) {
        Eif (
            /**
             * Cucumber v1
             */
            feature.failureException ||
            /**
             * Cucumber v2
             */
            (typeof feature.getFailureException === 'function' && feature.getFailureException()) ||
            /**
             * Cucumber v3, v4
             */
            (feature.status === 'failed')
        ) {
            ++this.failures
        }
    }
 
    /**
     * Before scenario
     * @param {Object} scenario Scenario
     */
    beforeScenario (uri, feature, scenario) {
        if (!this.isServiceEnabled) {
            return
        }
        const scenarioName = scenario.name || scenario.getName()
        global.browser.execute('tb:test-context=Scenario: ' + scenarioName)
    }
 
    /**
     * Update TestingBot info
     * @return {Promise} Promsie with result of updateJob method call
     */
    after (result) {
        if (!this.isServiceEnabled) {
            return
        }
 
        let failures = this.failures
 
        /**
         * set failures if user has bail option set in which case afterTest and
         * afterSuite aren't executed before after hook
         */
        Iif (global.browser.config.mochaOpts && global.browser.config.mochaOpts.bail && Boolean(result)) {
            failures = 1
        }
 
        const status = 'status: ' + (failures > 0 ? 'failing' : 'passing')
 
        if (!global.browser.isMultiremote) {
            log.info(`Update job with sessionId ${global.browser.sessionId}, ${status}`)
            return this.updateJob(global.browser.sessionId, failures)
        }
 
        return Promise.all(Object.keys(this.capabilities).map((browserName) => {
            log.info(`Update multiremote job for browser "${browserName}" and sessionId ${global.browser[browserName].sessionId}, ${status}`)
            return this.updateJob(global.browser[browserName].sessionId, failures, false, browserName)
        }))
    }
 
    onReload (oldSessionId, newSessionId) {
        if (!this.isServiceEnabled) {
            return
        }
        const status = 'status: ' + (this.failures > 0 ? 'failing' : 'passing')
 
        if (!global.browser.isMultiremote) {
            log.info(`Update (reloaded) job with sessionId ${oldSessionId}, ${status}`)
            return this.updateJob(oldSessionId, this.failures, true)
        }
 
        const browserName = global.browser.instances.filter(
            (browserName) => global.browser[browserName].sessionId === newSessionId)[0]
        log.info(`Update (reloaded) multiremote job for browser "${browserName}" and sessionId ${oldSessionId}, ${status}`)
        return this.updateJob(oldSessionId, this.failures, true, browserName)
    }
 
    updateJob (sessionId, failures, calledOnReload = false, browserName) {
        return new Promise((resolve, reject) => request.put(this.getRestUrl(sessionId), {
            json: true,
            auth: {
                user: this.tbUser,
                pass: this.tbSecret
            },
            body: this.getBody(failures, calledOnReload, browserName)
        }, (e, res, body) => {
            /* istanbul ignore if */
            this.failures = 0
            if (e) {
                return reject(e)
            }
            global.browser.jobData = body
            return resolve(body)
        }))
    }
 
    /**
     *
     * @param   {String} sessionId Session id
     * @returns {String}           TestingBot API URL
     */
    getRestUrl (sessionId) {
        return `https://api.testingbot.com/v1/tests/${sessionId}`
    }
 
    getBody (failures, calledOnReload = false, browserName) {
        let body = { test: {} }
 
        /**
         * set default values
         */
        body.test['name'] = this.suiteTitle
 
        /**
         * add reload count to title if reload is used
         */
        if (calledOnReload || this.testCnt) {
            let testCnt = ++this.testCnt
            if (global.browser.isMultiremote) {
                testCnt = Math.ceil(testCnt / global.browser.instances.length)
            }
 
            body.test['name'] += ` (${testCnt})`
        }
 
        for (let prop of jobDataProperties) {
            if (!this.capabilities[prop]) {
                continue
            }
 
            body.test[prop] = this.capabilities[prop]
        }
 
        if (browserName) {
            body.test['name'] = `${browserName}: ${body.test['name']}`
        }
 
        body.test['success'] = failures === 0 ? '1' : '0'
        return body
    }
}