execute_script_test.js 12.1 KB
Newer Older
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
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

'use strict';

var fail = require('assert').fail;

var webdriver = require('..'),
    Browser = webdriver.Browser,
    By = webdriver.By,
    assert = require('../testing/assert'),
    test = require('../lib/test');


test.suite(function(env) {
  var driver;

  test.before(function*() {
    driver = yield env.builder().build();
  });

  test.after(function() {
    return driver.quit();
  });

  test.beforeEach(function() {
    return driver.get(test.Pages.echoPage);
  });

  describe('executeScript;', function() {
    var shouldHaveFailed = new Error('Should have failed');

    test.it('fails if script throws', function() {
      return execute('throw new Error("boom")')
          .then(function() { throw shouldHaveFailed; })
          .catch(function(e) {
            // The java WebDriver server adds a bunch of crap to error messages.
            // Error message will just be "JavaScript error" for IE.
            assert(e.message).matches(/.*(JavaScript error|boom).*/);
          });
    });

    test.it('fails if script does not parse', function() {
      return execute('throw function\\*')
          .then(function() { throw shouldHaveFailed; })
          .catch(function(e) {
            assert(e).notEqualTo(shouldHaveFailed);
          });
    });

    describe('scripts;', function() {
      test.it('do not pollute the global scope', function*() {
        yield execute('var x = 1;');
        yield assert(execute('return typeof x;')).equalTo('undefined');
      });

      test.it('can set global variables', function*() {
        yield execute('window.x = 1234;');
        yield assert(execute('return x;')).equalTo(1234);
      });

      test.it('may be defined as a function expression', function*() {
        let result = yield execute(function() {
          return 1234 + 'abc';
        });
        assert(result).equalTo('1234abc');
      });
    });

    describe('return values;', function() {

      test.it('returns undefined as null', function() {
        return assert(execute('var x; return x;')).isNull();
      });

      test.it('can return null', function() {
        return assert(execute('return null;')).isNull();
      });

      test.it('can return numbers', function*() {
        yield assert(execute('return 1234')).equalTo(1234);
        yield assert(execute('return 3.1456')).equalTo(3.1456);
      });

      test.it('can return strings', function() {
        return assert(execute('return "hello"')).equalTo('hello');
      });

      test.it('can return booleans', function*() {
        yield assert(execute('return true')).equalTo(true);
        yield assert(execute('return false')).equalTo(false);
      });

      test.it('can return an array of primitives', function() {
        return execute('var x; return [1, false, null, 3.14, x]')
            .then(verifyJson([1, false, null, 3.14, null]));
      });

      test.it('can return nested arrays', function() {
        return execute('return [[1, 2, [3]]]').then(verifyJson([[1, 2, [3]]]));
      });

      test.ignore(env.browsers(Browser.IE)).
      it('can return empty object literal', function() {
        return execute('return {}').then(verifyJson({}));
      });

      test.it('can return object literals', function() {
        return execute('return {a: 1, b: false, c: null}').then(result => {
          verifyJson(['a', 'b', 'c'])(Object.keys(result).sort());
          assert(result.a).equalTo(1);
          assert(result.b).equalTo(false);
          assert(result.c).isNull();
        });
      });

      test.it('can return complex object literals', function() {
        return execute('return {a:{b: "hello"}}')
            .then(verifyJson({a:{b: 'hello'}}));
      });

      test.it('can return dom elements as web elements', function*() {
        let result =
            yield execute('return document.querySelector(".header.host")');
        assert(result).instanceOf(webdriver.WebElement);

        return assert(result.getText()).startsWith('host: ');
      });

      test.it('can return array of dom elements', function*() {
        let result = yield execute(
            'var nodes = document.querySelectorAll(".request,.host");' +
            'return [nodes[0], nodes[1]];');
        assert(result.length).equalTo(2);

        assert(result[0]).instanceOf(webdriver.WebElement);
        yield assert(result[0].getText()).startsWith('GET ');

        assert(result[1]).instanceOf(webdriver.WebElement);
        yield assert(result[1].getText()).startsWith('host: ');
      });

      test.it('can return a NodeList as an array of web elements', function*() {
        let result =
            yield execute('return document.querySelectorAll(".request,.host");')

        assert(result.length).equalTo(2);

        assert(result[0]).instanceOf(webdriver.WebElement);
        yield assert(result[0].getText()).startsWith('GET ');

        assert(result[1]).instanceOf(webdriver.WebElement);
        yield assert(result[1].getText()).startsWith('host: ');
      });

      test.it('can return object literal with element property', function*() {
        let result = yield execute('return {a: document.body}');

        assert(result.a).instanceOf(webdriver.WebElement);
        yield assert(result.a.getTagName()).equalTo('body');
      });
    });

    describe('parameters;', function() {
      test.it('can pass numeric arguments', function*() {
        yield assert(execute('return arguments[0]', 12)).equalTo(12);
        yield assert(execute('return arguments[0]', 3.14)).equalTo(3.14);
      });

      test.it('can pass boolean arguments', function*() {
        yield assert(execute('return arguments[0]', true)).equalTo(true);
        yield assert(execute('return arguments[0]', false)).equalTo(false);
      });

      test.it('can pass string arguments', function*() {
        yield assert(execute('return arguments[0]', 'hi')).equalTo('hi');
      });

      test.it('can pass null arguments', function*() {
        yield assert(execute('return arguments[0] === null', null)).equalTo(true);
        yield assert(execute('return arguments[0]', null)).equalTo(null);
      });

      test.it('passes undefined as a null argument', function*() {
        var x;
        yield assert(execute('return arguments[0] === null', x)).equalTo(true);
        yield assert(execute('return arguments[0]', x)).equalTo(null);
      });

      test.it('can pass multiple arguments', function*() {
        yield assert(execute('return arguments.length')).equalTo(0);
        yield assert(execute('return arguments.length', 1, 'a', false)).equalTo(3);
      });

      test.ignore(env.browsers(Browser.FIREFOX, Browser.SAFARI)).
      it('can return arguments object as array', function*() {
        let val = yield execute('return arguments', 1, 'a', false);

        assert(val.length).equalTo(3);
        assert(val[0]).equalTo(1);
        assert(val[1]).equalTo('a');
        assert(val[2]).equalTo(false);
      });

      test.it('can pass object literal', function*() {
        let result = yield execute(
            'return [typeof arguments[0], arguments[0].a]', {a: 'hello'})
        assert(result[0]).equalTo('object');
        assert(result[1]).equalTo('hello');
      });

      test.it('WebElement arguments are passed as DOM elements', function*() {
        let el = yield driver.findElement(By.tagName('div'));
        let result =
            yield execute('return arguments[0].tagName.toLowerCase();', el);
        assert(result).equalTo('div');
      });

      test.it('can pass array containing object literals', function*() {
        let result = yield execute('return arguments[0]', [{color: "red"}]);
        assert(result.length).equalTo(1);
        assert(result[0].color).equalTo('red');
      });

      test.it('does not modify object literal parameters', function() {
        var input = {color: 'red'};
        return execute('return arguments[0];', input).then(verifyJson(input));
      });
    });

    // See https://code.google.com/p/selenium/issues/detail?id=8223.
    describe('issue 8223;', function() {
      describe('using for..in loops;', function() {
        test.it('can return array built from for-loop index', function() {
          return execute(function() {
            var ret = [];
            for (var i = 0; i < 3; i++) {
              ret.push(i);
            }
            return ret;
          }).then(verifyJson[0, 1, 2]);
        });

        test.it('can copy input array contents', function() {
          return execute(function(input) {
            var ret = [];
            for (var i in input) {
              ret.push(input[i]);
            }
            return ret;
          }, ['fa', 'fe', 'fi']).then(verifyJson(['fa', 'fe', 'fi']));
        });

        test.it('can iterate over input object keys', function() {
          return execute(function(thing) {
            var ret = [];
            for (var w in thing.words) {
              ret.push(thing.words[w].word);
            }
            return ret;
          }, {words: [{word: 'fa'}, {word: 'fe'}, {word: 'fi'}]})
          .then(verifyJson(['fa', 'fe', 'fi']));
        });

        describe('recursive functions;', function() {
          test.it('can build array from input', function() {
            var input = ['fa', 'fe', 'fi'];
            return execute(function(thearray) {
              var ret = [];
              function build_response(thearray, ret) {
                ret.push(thearray.shift());
                return (!thearray.length && ret
                    || build_response(thearray, ret));
              }
              return build_response(thearray, ret);
            }, input).then(verifyJson(input));
          });

          test.it('can build array from elements in object', function() {
            var input = {words: [{word: 'fa'}, {word: 'fe'}, {word: 'fi'}]};
            return execute(function(thing) {
              var ret = [];
              function build_response(thing, ret) {
                var item = thing.words.shift();
                ret.push(item.word);
                return (!thing.words.length && ret
                    || build_response(thing, ret));
              }
              return build_response(thing, ret);
            }, input).then(verifyJson(['fa', 'fe', 'fi']));
          });
        });
      });
    });

    describe('async timeouts', function() {
      var TIMEOUT_IN_MS = 200;
      var ACCEPTABLE_WAIT = TIMEOUT_IN_MS / 10;
      var TOO_LONG_WAIT = TIMEOUT_IN_MS * 10;

      before(function() {
        return driver.manage().timeouts().setScriptTimeout(TIMEOUT_IN_MS)
      });

      test.it('does not fail if script execute in time', function() {
        return executeTimeOutScript(ACCEPTABLE_WAIT);
      });

      test.it('fails if script took too long', function() {
        return executeTimeOutScript(TOO_LONG_WAIT)
          .then(function() {
            fail('it should have timed out');
          }).catch(function(e) {
            assert(e.name).equalTo('ScriptTimeoutError');
          });
      });

      function executeTimeOutScript(sleepTime) {
        return driver.executeAsyncScript(function(sleepTime) {
          var callback = arguments[arguments.length - 1];
          setTimeout(callback, sleepTime)
        }, sleepTime);
      }
    })
  });

  function verifyJson(expected) {
    return function(actual) {
      return assert(JSON.stringify(actual)).equalTo(JSON.stringify(expected));
    };
  }

  function execute() {
    return driver.executeScript.apply(driver, arguments);
  }
});