All files index.js

97.33% Statements 73/75
96.23% Branches 51/53
100% Functions 13/13
97.14% Lines 68/70

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                            15x 15x 15x 15x               15x 15x   15x               29x 3x             26x 1x             25x 1x           24x 9x     15x       4x 3x   1x           11x 7x     4x 4x 4x         4x 34x 4x 4x   4x 1x     3x           3x 23x 23x 17x 17x 17x 17x 1x     16x 2x             2x 2x 2x           2x 2x               2x         2x       2x                 7x 3x     4x 4x 4x 4x             6x 1x           5x 1x 1x           4x               4x           4x 2x             2x 1x 1x   1x            
import fs from 'fs'
import zlib from 'zlib'
import path from 'path'
import request from 'request'
import changeCase from 'change-case'
 
import { createHMAC, getSauceEndpoint, toString, getParameters } from './utils'
import {
    PROTOCOL_MAP, DEFAULT_OPTIONS, SYMBOL_INSPECT,
    SYMBOL_TOSTRING, SYMBOL_ITERATOR, TO_STRING_TAG
} from './constants'
 
export default class SauceLabs {
    constructor (options) {
        this._options = Object.assign({}, DEFAULT_OPTIONS, options)
        this.username = this._options.user
        this._accessKey = this._options.key
        this._auth = {
            user: this.username,
            pass: this._accessKey
        }
 
        /**
         * public fields
         */
        this.region = this._options.region
        this.headless = this._options.headless
 
        return new Proxy({}, { get: ::this.get })
    }
 
    get (obj, propName) {
        /**
         * print to string output
         * https://nodejs.org/api/util.html#util_util_inspect_custom
         */
        if (propName === SYMBOL_INSPECT || propName === 'inspect') {
            return () => toString(this)
        }
 
        /**
         * print to string tag
         * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag
         */
        if (propName === SYMBOL_TOSTRING) {
            return TO_STRING_TAG
        }
 
        /**
         * return instance iterator
         * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator
         */
        if (propName === SYMBOL_ITERATOR) {
            return
        }
 
        /**
         * allow to return publicly registered class properties
         */
        if (this[propName]) {
            return !propName.startsWith('_') ? this[propName] : undefined
        }
 
        if (!PROTOCOL_MAP.has(propName)) {
            /**
             * just return if propName is a symbol (Node 8 and lower)
             */
            if (typeof propName !== 'string') {
                return
            }
            throw new Error(`Couldn't find API endpoint for command "${propName}"`)
        }
 
        /**
         * handle special commands not defined in the protocol
         */
        if (propName === 'downloadJobAsset') {
            return ::this._downloadJobAsset
        }
 
        return (...args) => {
            const { description, method, endpoint, host, basePath } = PROTOCOL_MAP.get(propName)
            const params = getParameters(description.parameters)
 
            /**
             * validate required url params
             */
            let url = endpoint
            for (const [i, urlParam] of Object.entries(params.filter(p => p.in === 'path'))) {
                const param = args[i]
                const type = urlParam.type.replace('integer', 'number')
 
                if (typeof param !== type) {
                    throw new Error(`Expected parameter for url param '${urlParam.name}' from type '${type}', found '${typeof param}'`)
                }
 
                url = url.replace(`{${urlParam.name}}`, param)
            }
 
            /**
             * validate required options
             */
            const bodyMap = new Map()
            const options = args.slice(params.filter(p => p.required).length)[0] || {}
            for (const optionParam of params.filter(p => p.in === 'query')) {
                const expectedType = optionParam.type.replace('integer', 'number')
                const option = options[changeCase.camelCase(optionParam.name)]
                const isRequired = Boolean(optionParam.required) || (typeof optionParam.required === 'undefined' && typeof optionParam.default === 'undefined')
                if ((isRequired || option) && (!option || typeof option !== expectedType)) {
                    throw new Error(`Expected parameter for option '${optionParam.name}' from type '${expectedType}', found '${typeof option}'`)
                }
 
                if (option) {
                    bodyMap.set(optionParam.name, option)
                }
            }
 
            /**
             * convert map into json object
             */
            const body = [...bodyMap.entries()].reduce((e, [k, v]) => {
                e[k] = v
                return e
            }, {})
 
            /**
             * make request
             */
            const uri = getSauceEndpoint(host + basePath, this._options.region, this._options.headless) + url
            return new Promise((resolve, reject) => request({
                uri,
                method: method.toUpperCase(),
                [method === 'post' ? 'json' : 'qs']: body,
                json: true,
                auth: this._auth
            }, (err, response, body) => {
                /* istanbul ignore if */
                if (err) {
                    return reject(err)
                }
 
                /* istanbul ignore if */
                if (response.statusCode !== 200) {
                    return reject(new Error((body && body.message) || `Unknown Error (${response.statusCode})`))
                }
 
                return resolve(body)
            }))
        }
    }
 
    async _downloadJobAsset (jobId, assetName, downloadPath) {
        /**
         * check job id
         */
        if (typeof jobId !== 'string' || typeof assetName !== 'string') {
            throw new Error('You need to define a job id and the file name of the asset as a string')
        }
 
        const hmac = await createHMAC(this.username, this._accessKey, jobId)
        const host = getSauceEndpoint('saucelabs.com', this._options.region, this._options.headless, 'https://assets.')
        return new Promise((resolve, reject) => {
            const req = request({
                method: 'GET',
                uri: `${host}/jobs/${jobId}/${assetName}?ts=${Date.now()}&auth=${hmac}`
            }, (err, res, body) => {
                /**
                 * check if request was successful
                 */
                if (err) {
                    return reject(err)
                }
 
                /**
                 * check if we received the asset
                 */
                if (res.statusCode !== 200) {
                    const reason = JSON.parse(body).message || 'unknown'
                    return reject(new Error(`There was an error downloading asset ${assetName}, status code: ${res.statusCode}, reason: ${reason}`))
                }
 
                /**
                 * parse asset as json if proper content type is given
                 */
                Iif (res.headers['content-type'] === 'application/json') {
                    try {
                        body = JSON.parse(body)
                    } catch (e) {
                        // do nothing
                    }
                }
 
                return resolve(body)
            })
 
            /**
             * only pipe asset to file if path is given
             */
            if (typeof downloadPath === 'string') {
                const fd = fs.createWriteStream(path.resolve(process.cwd(), downloadPath))
 
                /**
                 * unzip gzipped logs
                 * ToDo: this only affects tracing logs which are uploaded gzipped,
                 *       there should be seperate api definition for extended debugging
                 */
                if (assetName.endsWith('.gz')) {
                    const gunzip = zlib.createGunzip()
                    req.pipe(gunzip).pipe(fd)
                } else {
                    req.pipe(fd)
                }
            }
        })
    }
}