All files / webdriverio/src utils.js

99.1% Statements 110/111
98.81% Branches 83/84
95.24% Functions 20/21
100% Lines 108/108

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                        70x 70x   70x 477x 477x 477x 15123x 15123x             70x 477x         477x 477x               70x       302x 2x           300x 1x           299x 274x     25x             332x             36x   36x 27x     36x 56x 17x 39x 12x 12x 27x 12x 12x   15x 11x 11x       36x                 2x                   8x 1x     7x         7x       1x         1x 1x 1x 1x 6x 1x 1x 1x   1x 1x         5x 5x   4x 4x     4x 1x               7x                 29x           9x 7x         2x 2x                   224x 216x 216x               8x 4x 4x 4x 4x     4x                   26x 17x 17x               9x 5x 5x 8x     4x                 69x 9x 1x     8x           60x     50x             21x   21x           76x                               3x 9x 3x   6x 5x   1x 1x         20x       7x                 5x 1x                     13x 13x 8x         5x 1x     4x      
import fs from 'fs'
import path from 'path'
import cssValue from 'css-value'
import rgb2hex from 'rgb2hex'
import GraphemeSplitter from 'grapheme-splitter'
import logger from '@wdio/logger'
import isObject from 'lodash.isobject'
import { URL } from 'url'
 
import { ELEMENT_KEY, UNICODE_CHARACTERS } from './constants'
import { findStrategy } from './utils/findStrategy'
 
const log = logger('webdriverio')
const INVALID_SELECTOR_ERROR = 'selector needs to be typeof `string` or `function`'
 
const applyScopePrototype = (prototype, scope) => {
    const dir = path.resolve(__dirname, 'commands', scope)
    const files = fs.readdirSync(dir)
    for (let filename of files) {
        const commandName = path.basename(filename, path.extname(filename))
        prototype[commandName] = { value: require(path.join(dir, commandName)).default }
    }
}
 
/**
 * enhances objects with element commands
 */
export const getPrototype = (scope) => {
    const prototype = {}
 
    /**
     * register action commands
     */
    applyScopePrototype(prototype, scope)
    return prototype
}
 
/**
 * get element id from WebDriver response
 * @param  {?Object|undefined} res         body object from response or null
 * @return {?string}   element id or null if element couldn't be found
 */
export const getElementFromResponse = (res) => {
    /**
    * a function selector can return null
    */
    if (!res) {
        return null
    }
 
    /**
     * deprecated JSONWireProtocol response
     */
    if (res.ELEMENT) {
        return res.ELEMENT
    }
 
    /**
     * W3C WebDriver response
     */
    if (res[ELEMENT_KEY]) {
        return res[ELEMENT_KEY]
    }
 
    return null
}
 
/**
 * traverse up the scope chain until browser element was reached
 */
export function getBrowserObject (elem) {
    return elem.parent ? getBrowserObject(elem.parent) : elem
}
 
/**
 * transform whatever value is into an array of char strings
 */
export function transformToCharString (value) {
    const ret = []
 
    if (!Array.isArray(value)) {
        value = [value]
    }
 
    for (const val of value) {
        if (typeof val === 'string') {
            ret.push(...checkUnicode(val))
        } else if (typeof val === 'number') {
            const entry = `${val}`.split('')
            ret.push(...entry)
        } else if (val && typeof val === 'object') {
            try {
                ret.push(...JSON.stringify(val).split(''))
            } catch (e) { /* ignore */ }
        } else if (typeof val === 'boolean') {
            const entry = val ? 'true'.split('') : 'false'.split('')
            ret.push(...entry)
        }
    }
 
    return ret
}
 
function sanitizeCSS (value) {
    /* istanbul ignore next */
    if (!value) {
        return value
    }
 
    return value.trim().replace(/'/g, '').replace(/"/g, '').toLowerCase()
}
 
/**
 * parse css values to a better format
 * @param  {Object} cssPropertyValue result of WebDriver call
 * @param  {String} cssProperty      name of css property to parse
 * @return {Object}                  parsed css property
 */
export function parseCSS (cssPropertyValue, cssProperty) {
    if (!cssPropertyValue) {
        return null
    }
 
    let parsedValue = {
        property: cssProperty,
        value: cssPropertyValue.toLowerCase().trim()
    }
 
    if (parsedValue.value.indexOf('rgb') === 0) {
        /**
         * remove whitespaces in rgb values
         */
        parsedValue.value = parsedValue.value.replace(/\s/g, '')
 
        /**
         * parse color values
         */
        let color = parsedValue.value
        parsedValue.parsed = rgb2hex(parsedValue.value)
        parsedValue.parsed.type = 'color'
        parsedValue.parsed[/[rgba]+/g.exec(color)[0]] = color
    } else if (parsedValue.property === 'font-family') {
        let font = cssValue(cssPropertyValue)
        let string = parsedValue.value
        let value = cssPropertyValue.split(/,/).map(sanitizeCSS)
 
        parsedValue.value = sanitizeCSS(font[0].value || font[0].string)
        parsedValue.parsed = { value, type: 'font', string }
    } else {
        /**
         * parse other css properties
         */
        try {
            parsedValue.parsed = cssValue(cssPropertyValue)
 
            Eif (parsedValue.parsed.length === 1) {
                parsedValue.parsed = parsedValue.parsed[0]
            }
 
            if (parsedValue.parsed.type && parsedValue.parsed.type === 'number' && parsedValue.parsed.unit === '') {
                parsedValue.value = parsedValue.parsed.value
            }
        } catch (e) {
            // TODO improve css-parse lib to handle properties like
            // `-webkit-animation-timing-function :  cubic-bezier(0.25, 0.1, 0.25, 1)
        }
    }
 
    return parsedValue
}
 
/**
 * check for unicode character or split string into literals
 * @param  {String} value  text
 * @return {Array}         set of characters or unicode symbols
 */
export function checkUnicode (value) {
    return Object.prototype.hasOwnProperty.call(UNICODE_CHARACTERS, value)
        ? [UNICODE_CHARACTERS[value]]
        : new GraphemeSplitter().splitGraphemes(value)
}
 
function fetchElementByJSFunction (selector, scope) {
    if (!scope.elementId) {
        return scope.execute(selector)
    }
    /**
     * use a regular function because IE does not understand arrow functions
     */
    const script = (function (elem) { return (selector).call(elem) }).toString().replace('selector', `(${selector.toString()})`)
    return getBrowserObject(scope).execute(`return (${script}).apply(null, arguments)`, scope)
}
 
/**
 * logic to find an element
 */
export async function findElement(selector) {
    /**
     * fetch element using regular protocol command
     */
    if (typeof selector === 'string') {
        const { using, value } = findStrategy(selector, this.isW3C, this.isMobile)
        return this.elementId
            ? this.findElementFromElement(this.elementId, using, value)
            : this.findElement(using, value)
    }
 
    /**
     * fetch element with JS function
     */
    if (typeof selector === 'function') {
        const notFoundError = new Error(`Function selector "${selector.toString()}" did not return an HTMLElement`)
        let elem = await fetchElementByJSFunction(selector, this)
        elem = Array.isArray(elem) ? elem[0] : elem
        return getElementFromResponse(elem) ? elem : notFoundError
    }
 
    throw new Error(INVALID_SELECTOR_ERROR)
}
 
/**
 * logic to find a elements
 */
export async function findElements(selector) {
    /**
     * fetch element using regular protocol command
     */
    if (typeof selector === 'string') {
        const { using, value } = findStrategy(selector, this.isW3C, this.isMobile)
        return this.elementId
            ? this.findElementsFromElement(this.elementId, using, value)
            : this.findElements(using, value)
    }
 
    /**
     * fetch element with JS function
     */
    if (typeof selector === 'function') {
        let elems = await fetchElementByJSFunction(selector, this)
        elems = Array.isArray(elems) ? elems : [elems]
        return elems.filter((elem) => elem && getElementFromResponse(elem))
    }
 
    throw new Error(INVALID_SELECTOR_ERROR)
}
 
/**
 * Strip element object and return w3c and jsonwp compatible keys
 */
 
export function verifyArgsAndStripIfElement(args) {
    function verify(arg) {
        if (isObject(arg) && arg.constructor.name === 'Element') {
            if (!arg.elementId) {
                throw new Error(`The element with selector "${arg.selector}" you trying to pass into the execute method wasn't found`)
            }
 
            return {
                [ELEMENT_KEY]: arg.elementId,
                ELEMENT: arg.elementId
            }
        }
 
        return arg
    }
 
    return !Array.isArray(args) ? verify(args) : args.map(verify)
}
 
/**
 * getElementRect
 */
export async function getElementRect(scope) {
    const rect = await scope.getElementRect(scope.elementId)
 
    let defaults = { x: 0, y: 0, width: 0, height: 0 }
 
    /**
     * getElementRect workaround for Safari 12.0.3
     * if one of [x, y, height, width] is undefined get rect with javascript
     */
    if (Object.keys(defaults).some(key => rect[key] == null)) {
        /* istanbul ignore next */
        const rectJs = await getBrowserObject(scope).execute(function (el) {
            if (!el || !el.getBoundingClientRect) {
                return
            }
            const { left, top, width, height } = el.getBoundingClientRect()
            return {
                x: left + this.scrollX,
                y: top + this.scrollY,
                width,
                height
            }
        }, scope)
 
        // try set proper value
        Object.keys(defaults).forEach(key => {
            if (rect[key] != null) {
                return
            }
            if (typeof rectJs[key] === 'number') {
                rect[key] = Math.floor(rectJs[key])
            } else {
                log.error('getElementRect', { rect, rectJs, key })
                throw new Error('Failed to receive element rects via execute command')
            }
        })
    }
 
    return rect
}
 
export function getAbsoluteFilepath(filepath) {
    return filepath.startsWith('/') || filepath.startsWith('\\') || filepath.match(/^[a-zA-Z]:\\/)
        ? filepath
        : path.join(process.cwd(), filepath)
}
 
/**
 * check if directory exists
 */
export function assertDirectoryExists(filepath) {
    if (!fs.existsSync(path.dirname(filepath))) {
        throw new Error(`directory (${path.dirname(filepath)}) doesn't exist`)
    }
}
 
/**
 * check if urls are valid and fix them if necessary
 * @param  {string}  url                url to navigate to
 * @param  {Boolean} [retryCheck=false] true if an url was already check and still failed with fix applied
 * @return {string}                     fixed url
 */
export function validateUrl (url, origError) {
    try {
        const urlObject = new URL(url)
        return urlObject.href
    } catch (e) {
        /**
         * if even adding http:// doesn't help, fail with original error
         */
        if (origError) {
            throw origError
        }
 
        return validateUrl(`http://${url}`, e)
    }
}