all files / jWebDriver/lib/ jwebdriver.js

84.3% Statements 102/121
58% Branches 29/50
85% Functions 17/20
84.3% Lines 102/121
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                                                                                                                                                          1121× 1121× 1121× 1121× 1121×                                                     16× 16×                       413× 412×                                   413× 413× 413× 413×   410×     413× 413× 413× 413× 413× 413× 413× 413× 586×   413× 413× 248×   248×   248× 248×       165×   413× 413×         413×               412×     411× 411× 411×           411× 411× 411×     411× 411× 411×     407×       407×   407×           407×                                                                                                           419× 419×              
'use strict';
/**
 * A webdriver client for Node.js
 * <p>
 * You can use JWebDriver connect to local webdriver or webdriver grid.
 * </p>
 * @class JWebDriver
 */
 
const extend = require('xtend');
const request = require('request');
const PromiseClass = require('promiseclass');
 
const mapCommands = require('./commands.js');
const Browser = require('./browser');
const Elements = require('./elements');
const mixPromise = require('./mixpromise');
 
// color list
const colors = {
    black: '\x1b[0;30m',
    dkgray: '\x1b[1;30m',
    brick: '\x1b[0;31m',
    red: '\x1b[1;31m',
    green: '\x1b[0;32m',
    lime: '\x1b[1;32m',
    brown: '\x1b[0;33m',
    yellow: '\x1b[1;33m',
    navy: '\x1b[0;34m',
    blue: '\x1b[1;34m',
    violet: '\x1b[0;35m',
    magenta: '\x1b[1;35m',
    teal: '\x1b[0;36m',
    cyan: '\x1b[1;36m',
    ltgray: '\x1b[0;37m',
    white: '\x1b[1;37m',
    reset: '\x1b[0m'
};
 
// default config
const defConfig = {
	'host': '127.0.0.1',
	'port': 4444,
    'logLevel': 0, // 0: no log, 1: warning & error, 2: all log
    'nocolor': false,
    'speed': 0
};
 
const JWebDriver = PromiseClass.create({
 
    /**
     * init driver
     * @method constructor
     * @private
     * @param  {String|Object} [host] webdriver server ip or options
     * @param  {String} [port] webdriver server port
     */
    constructor(host, port) {
        let self = this;
        let options;
        Iif(port !== undefined){
            options = {
                host: host,
                port: port
            };
        }
        else{
            options = host;
        }
        let config = extend({}, defConfig, options);
        self.config = config;
    },
 
    /**
     * get webdriver server info
     * @method info
     * @public
     * @param  {Function} done callback function
     */
    info(done){
        this.execCmd('getStatus', function(error, ret){
            done(error, ret && ret.value);
        });
    },
 
    /**
     * save log
     * @method log
     * @public
     * @param  {COMMAND|DATA|RESULT|ERROR|WARNING|INFO} type log type
     * @param  {Object} message log message
     */
    log(type, message){
        let self = this;
        let config = self.config;
        let logLevel = config.logLevel;
        let nocolor = config.nocolor;
        Iif(logLevel === 2 || (logLevel === 1 && (type === 'ERROR' || type === 'WARNING'))){
            let dateString = (new Date()).toString().match(/\d\d:\d\d:\d\d/)[0];
            let mapColors = {
                'COMMAND': colors.violet,
                'DATA': colors.brown,
                'RESPONSE': colors.teal,
                'ERROR': colors.red,
                'WARNING': colors.yellow,
                'INFO': colors.white
            };
            if(nocolor === true){
                console.log('[ ' + dateString + ' ]: ', type, '\t', message);
            }
            else{
                console.log(colors.dkgray +'[ ' + dateString + ' ]: ' + colors.reset, mapColors[type] + type + colors.reset, '\t', message);
            }
        }
    },
 
    /**
     * sleep sync
     * @method sleep
     * @public
     * @param  {Number} ms
     * @param  {Function} done callback function
     */
    sleep(ms, done){
        this.log('COMMAND', 'SLEEP\t'+ms);
        setTimeout(done, ms);
    },
 
    /**
     * request sync
     * @method requestSync
     * @public
     * @param  {object} options
     * @param  {Function} done callback function
     * @return {Object} error, {response:{}, body:{}}
     */
    request(options, done){
        request(options, function(error, response, body){
            done(error, {
                response: response,
                body: body
            });
        });
    },
 
    /**
     * execute protocal command
     * @method execCmd
     * @public
     * @param  {String} cmd protocal command, defined in command.js
     * @param  {Object} [pathData] replace the path parameters
     * @param  {Object} [data] send data to protocal api
     * @param  {Function} done callback function
     * @return {Object} the return object from webdriver server
     */
    execCmd(cmd, pathData, data, done){
        let self = this;
        let config = self.config;
        let cmdInfo = mapCommands[cmd];
        if(typeof pathData === 'function'){
            pathData = undefined;
            data = undefined;
        }
        else Iif(typeof data === 'function'){
            data = undefined;
        }
        done = getDone(arguments);
        Eif(cmdInfo !== undefined){
            let host = config.host;
            let port = config.port;
            let method = cmdInfo[0];
            let apiPath = cmdInfo[1];
            pathData = pathData || {};
            for(let name in pathData){
                apiPath = apiPath.replace(':'+name, encodeURIComponent(pathData[name]));
            }
            self.log('COMMAND', method + '\t' + apiPath);
            if(data){
                data = JSON.stringify(data);
                // encode Unicode
                data = data.replace(/[^\x00-\xff]/g, function(a){
                    return '\\'+escape(a).substr(1);
                });
                Eif(data !== '{}'){
                    self.log('DATA', data);
                }
            }
            else{
                data = '';
            }
            let url = 'http://'+host+':'+port+'/wd/hub'+apiPath;
            let headers = {
                'Accept': 'application/json; charset=utf-8',
                'Content-Type': 'application/json;charset=UTF-8',
                'Content-Length': data.length
            };
            self.request({
                method: method,
                url: url,
                headers: headers,
                body: data,
                followAllRedirects: true,
                timeout: 600000
            }, function(error, response){
                if(error){
                    done(error);
                }
                else{
                    let body = response.body;
                    response = response.response;
                    Iif(response.statusCode === 204){
                        // no content
                        self.log('RESPONSE', null);
                        done(null, null);
                    }
                    else{
                        try{
                            body = body.replace(/\x00/g,'');
                            body = JSON.parse(body);
                        }
                        catch(e){}
                        let wdStatus = body.status;
                        let value = body.value;
                        if(response.statusCode !== 200 || wdStatus !== 0){
                            let errorInfo = value ? (value.message ? value.message : value) : body;
                            self.log('ERROR', errorInfo);
                            return done(errorInfo);
                        }
                        else{
                            Iif(value && value.hCode !== undefined){
                                delete value['hCode'];
                                delete value['class'];
                            }
                            self.log('RESPONSE', value);
                        }
                        Iif(config.speed > 0){
                            self.sleep(config.speed, function(){
                                done(null, body);
                            });
                        }
                        else{
                            done(null, body);
                        }
                    }
                }
            });
        }
        else{
            done('Invalid cmd');
        }
    },
 
    /**
     * get all sessions
     * @method sessions
     * @public
     * @param  {Function} done callback function
     * @return {Array} sessions array
     */
    sessions(done){
        let self = this;
        self.execCmd('getSessions', function(error, ret){
            Iif(error){
                done(error);
            }
            else{
                let arrSessionsInfos = ret.value;
                let arrSessions = [];
                let arrPromise = [];
                function getSession(sessionInfo){
                   arrPromise.push(new Promise(function(resolve){
                        self.session({
                            sessionId: sessionInfo.id
                        }, function(error, ret){
                            arrSessions.push(ret);
                            resolve();
                        });
                    }));
                }
                for(let i=0,len=arrSessionsInfos.length;i<len;i++){
                    getSession(arrSessionsInfos[i]);
                }
                Promise.all(arrPromise).then(function(){
                    done(null, arrSessions);
                }).catch(done);
            }
        });
    },
 
    /**
     * init new session or attach to a session id
     * @method session
     * @public
     * @param  {String|Object} browserName or capabilitie object
     * @param  {String} version
     * @param  {String} platform
     * @param  {Function} done callback function
     * @return {Browser} Browser object
     */
    session(browserName, version, platform, done){
        var self = this;
        Eif(typeof version === 'function'){
            version = undefined;
            platform = undefined;
        }
        else if(typeof platform === 'function'){
            platform = undefined;
        }
        done = getDone(arguments);
        let browser = new Browser(self, browserName, version, platform);
        browser.init(function(error){
            self.lastBrowser = browser;
            done(error, browser);
        }).catch(done);
    }
 
});
 
// get done callback
function getDone(args){
    let done = args[args.length -1];
    return typeof done === 'function' ? done : null;
}
 
// expose Browser & Elements & chaiSupportChainPromise
JWebDriver.Browser = Browser;
JWebDriver.Elements = Elements;
JWebDriver.chaiSupportChainPromise = PromiseClass.chaiSupportChainPromise;
 
// mix Browser Elements to JWebDriver
mixPromise(JWebDriver, Browser, Elements);
 
module.exports = JWebDriver;