builder.js 16.6 KB
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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
// 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';

const chrome = require('./chrome');
const edge = require('./edge');
const executors = require('./executors');
const firefox = require('./firefox');
const ie = require('./ie');
const capabilities = require('./lib/capabilities');
const webdriver = require('./lib/webdriver');
const promise = require('./lib/promise');
const opera = require('./opera');
const phantomjs = require('./phantomjs');
const safari = require('./safari');

const Browser = capabilities.Browser;
const Capabilities = capabilities.Capabilities;
const Capability = capabilities.Capability;
const WebDriver = webdriver.WebDriver;



var seleniumServer;

/**
 * Starts an instance of the Selenium server if not yet running.
 * @param {string} jar Path to the server jar to use.
 * @return {!promise.Promise<string>} A promise for the server's
 *     addrss once started.
 */
function startSeleniumServer(jar) {
  if (!seleniumServer) {
    // Requiring 'chrome' above would create a cycle:
    // index -> builder -> chrome -> index
    var remote = require('./remote');
    seleniumServer = new remote.SeleniumServer(jar);
  }
  return seleniumServer.start();
}


/**
 * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment
 * variables listed below may be used to override a builder's configuration,
 * allowing quick runtime changes.
 *
 * - {@code SELENIUM_BROWSER}: defines the target browser in the form
 *   {@code browser[:version][:platform]}.
 *
 * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder
 *   instances. This environment variable should be set to a fully qualified
 *   URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This
 *   option always takes precedence over {@code SELENIUM_SERVER_JAR}.
 *
 * - {@code SELENIUM_SERVER_JAR}: defines the path to the
 *   <a href="http://selenium-release.storage.googleapis.com/index.html">
 *   standalone Selenium server</a> jar to use. The server will be started the
 *   first time a WebDriver instance and be killed when the process exits.
 *
 * Suppose you had mytest.js that created WebDriver with
 *
 *     var driver = new webdriver.Builder()
 *         .forBrowser('chrome')
 *         .build();
 *
 * This test could be made to use Firefox on the local machine by running with
 * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to
 * target Google Chrome on a remote machine, you can simply set the
 * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables:
 *
 *     SELENIUM_BROWSER=chrome:36:LINUX \
 *     SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \
 *     node mytest.js
 *
 * You could also use a local copy of the standalone Selenium server:
 *
 *     SELENIUM_BROWSER=chrome:36:LINUX \
 *     SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \
 *     node mytest.js
 */
class Builder {
  constructor() {
    /** @private {promise.ControlFlow} */
    this.flow_ = null;

    /** @private {string} */
    this.url_ = '';

    /** @private {?string} */
    this.proxy_ = null;

    /** @private {!Capabilities} */
    this.capabilities_ = new Capabilities();

    /** @private {chrome.Options} */
    this.chromeOptions_ = null;

    /** @private {firefox.Options} */
    this.firefoxOptions_ = null;

    /** @private {opera.Options} */
    this.operaOptions_ = null;

    /** @private {ie.Options} */
    this.ieOptions_ = null;

    /** @private {safari.Options} */
    this.safariOptions_ = null;

    /** @private {edge.Options} */
    this.edgeOptions_ = null;

    /** @private {boolean} */
    this.ignoreEnv_ = false;
  }

  /**
   * Configures this builder to ignore any environment variable overrides and to
   * only use the configuration specified through this instance's API.
   *
   * @return {!Builder} A self reference.
   */
  disableEnvironmentOverrides() {
    this.ignoreEnv_ = true;
    return this;
  }

  /**
   * Sets the URL of a remote WebDriver server to use. Once a remote URL has
   * been specified, the builder direct all new clients to that server. If this
   * method is never called, the Builder will attempt to create all clients
   * locally.
   *
   * As an alternative to this method, you may also set the
   * `SELENIUM_REMOTE_URL` environment variable.
   *
   * @param {string} url The URL of a remote server to use.
   * @return {!Builder} A self reference.
   */
  usingServer(url) {
    this.url_ = url;
    return this;
  }

  /**
   * @return {string} The URL of the WebDriver server this instance is
   *     configured to use.
   */
  getServerUrl() {
    return this.url_;
  }

  /**
   * Sets the URL of the proxy to use for the WebDriver's HTTP connections.
   * If this method is never called, the Builder will create a connection
   * without a proxy.
   *
   * @param {string} proxy The URL of a proxy to use.
   * @return {!Builder} A self reference.
   */
  usingWebDriverProxy(proxy) {
    this.proxy_ = proxy;
    return this;
  }

  /**
   * @return {?string} The URL of the proxy server to use for the WebDriver's
   *    HTTP connections, or `null` if not set.
   */
  getWebDriverProxy() {
    return this.proxy_;
  }

  /**
   * Sets the desired capabilities when requesting a new session. This will
   * overwrite any previously set capabilities.
   * @param {!(Object|Capabilities)} capabilities The desired capabilities for
   *     a new session.
   * @return {!Builder} A self reference.
   */
  withCapabilities(capabilities) {
    this.capabilities_ = new Capabilities(capabilities);
    return this;
  }

  /**
   * Returns the base set of capabilities this instance is currently configured
   * to use.
   * @return {!Capabilities} The current capabilities for this builder.
   */
  getCapabilities() {
    return this.capabilities_;
  }

  /**
   * Configures the target browser for clients created by this instance.
   * Any calls to {@link #withCapabilities} after this function will
   * overwrite these settings.
   *
   * You may also define the target browser using the {@code SELENIUM_BROWSER}
   * environment variable. If set, this environment variable should be of the
   * form `browser[:[version][:platform]]`.
   *
   * @param {(string|Browser)} name The name of the target browser;
   *     common defaults are available on the {@link webdriver.Browser} enum.
   * @param {string=} opt_version A desired version; may be omitted if any
   *     version should be used.
   * @param {string=} opt_platform The desired platform; may be omitted if any
   *     version may be used.
   * @return {!Builder} A self reference.
   */
  forBrowser(name, opt_version, opt_platform) {
    this.capabilities_.set(Capability.BROWSER_NAME, name);
    this.capabilities_.set(Capability.VERSION, opt_version || null);
    this.capabilities_.set(Capability.PLATFORM, opt_platform || null);
    return this;
  }

  /**
   * Sets the proxy configuration to use for WebDriver clients created by this
   * builder. Any calls to {@link #withCapabilities} after this function will
   * overwrite these settings.
   * @param {!capabilities.ProxyConfig} config The configuration to use.
   * @return {!Builder} A self reference.
   */
  setProxy(config) {
    this.capabilities_.setProxy(config);
    return this;
  }

  /**
   * Sets the logging preferences for the created session. Preferences may be
   * changed by repeated calls, or by calling {@link #withCapabilities}.
   * @param {!(./lib/logging.Preferences|Object<string, string>)} prefs The
   *     desired logging preferences.
   * @return {!Builder} A self reference.
   */
  setLoggingPrefs(prefs) {
    this.capabilities_.setLoggingPrefs(prefs);
    return this;
  }

  /**
   * Sets whether native events should be used.
   * @param {boolean} enabled Whether to enable native events.
   * @return {!Builder} A self reference.
   */
  setEnableNativeEvents(enabled) {
    this.capabilities_.setEnableNativeEvents(enabled);
    return this;
  }

  /**
   * Sets how elements should be scrolled into view for interaction.
   * @param {number} behavior The desired scroll behavior: either 0 to align
   *     with the top of the viewport or 1 to align with the bottom.
   * @return {!Builder} A self reference.
   */
  setScrollBehavior(behavior) {
    this.capabilities_.setScrollBehavior(behavior);
    return this;
  }

  /**
   * Sets the default action to take with an unexpected alert before returning
   * an error.
   * @param {string} behavior The desired behavior; should be "accept",
   *     "dismiss", or "ignore". Defaults to "dismiss".
   * @return {!Builder} A self reference.
   */
  setAlertBehavior(behavior) {
    this.capabilities_.setAlertBehavior(behavior);
    return this;
  }

  /**
   * Sets Chrome specific {@linkplain chrome.Options options} for drivers
   * created by this builder. Any logging or proxy settings defined on the given
   * options will take precedence over those set through
   * {@link #setLoggingPrefs} and {@link #setProxy}, respectively.
   *
   * @param {!chrome.Options} options The ChromeDriver options to use.
   * @return {!Builder} A self reference.
   */
  setChromeOptions(options) {
    this.chromeOptions_ = options;
    return this;
  }

  /**
   * Sets Firefox specific {@linkplain firefox.Options options} for drivers
   * created by this builder. Any logging or proxy settings defined on the given
   * options will take precedence over those set through
   * {@link #setLoggingPrefs} and {@link #setProxy}, respectively.
   *
   * @param {!firefox.Options} options The FirefoxDriver options to use.
   * @return {!Builder} A self reference.
   */
  setFirefoxOptions(options) {
    this.firefoxOptions_ = options;
    return this;
  }

  /**
   * Sets Opera specific {@linkplain opera.Options options} for drivers created
   * by this builder. Any logging or proxy settings defined on the given options
   * will take precedence over those set through {@link #setLoggingPrefs} and
   * {@link #setProxy}, respectively.
   *
   * @param {!opera.Options} options The OperaDriver options to use.
   * @return {!Builder} A self reference.
   */
  setOperaOptions(options) {
    this.operaOptions_ = options;
    return this;
  }

  /**
   * Set Internet Explorer specific {@linkplain ie.Options options} for drivers
   * created by this builder. Any proxy settings defined on the given options
   * will take precedence over those set through {@link #setProxy}.
   *
   * @param {!ie.Options} options The IEDriver options to use.
   * @return {!Builder} A self reference.
   */
  setIeOptions(options) {
    this.ieOptions_ = options;
    return this;
  }

  /**
   * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser
   * for drivers created by this builder. Any proxy settings defined on the
   * given options will take precedence over those set through
   * {@link #setProxy}.
   *
   * @param {!edge.Options} options The MicrosoftEdgeDriver options to use.
   * @return {!Builder} A self reference.
   */
  setEdgeOptions(options) {
    this.edgeOptions_ = options;
    return this;
  }

  /**
   * Sets Safari specific {@linkplain safari.Options options} for drivers
   * created by this builder. Any logging settings defined on the given options
   * will take precedence over those set through {@link #setLoggingPrefs}.
   *
   * @param {!safari.Options} options The Safari options to use.
   * @return {!Builder} A self reference.
   */
  setSafariOptions(options) {
    this.safariOptions_ = options;
    return this;
  }

  /**
   * Sets the control flow that created drivers should execute actions in. If
   * the flow is never set, or is set to {@code null}, it will use the active
   * flow at the time {@link #build()} is called.
   * @param {promise.ControlFlow} flow The control flow to use, or
   *     {@code null} to
   * @return {!Builder} A self reference.
   */
  setControlFlow(flow) {
    this.flow_ = flow;
    return this;
  }

  /**
   * Creates a new WebDriver client based on this builder's current
   * configuration.
   *
   * While this method will immediately return a new WebDriver instance, any
   * commands issued against it will be deferred until the associated browser
   * has been fully initialized. Users may call {@link #buildAsync()} to obtain
   * a promise that will not be fulfilled until the browser has been created
   * (the difference is purely in style).
   *
   * @return {!webdriver.WebDriver} A new WebDriver instance.
   * @throws {Error} If the current configuration is invalid.
   * @see #buildAsync()
   */
  build() {
    // Create a copy for any changes we may need to make based on the current
    // environment.
    var capabilities = new Capabilities(this.capabilities_);

    var browser;
    if (!this.ignoreEnv_ && process.env.SELENIUM_BROWSER) {
      browser = process.env.SELENIUM_BROWSER.split(/:/, 3);
      capabilities.set(Capability.BROWSER_NAME, browser[0]);
      capabilities.set(Capability.VERSION, browser[1] || null);
      capabilities.set(Capability.PLATFORM, browser[2] || null);
    }

    browser = capabilities.get(Capability.BROWSER_NAME);

    if (typeof browser !== 'string') {
      throw TypeError(
          `Target browser must be a string, but is <${typeof browser}>;` +
          ' did you forget to call forBrowser()?');
    }

    if (browser === 'ie') {
      browser = Browser.INTERNET_EXPLORER;
    }

    // Apply browser specific overrides.
    if (browser === Browser.CHROME && this.chromeOptions_) {
      capabilities.merge(this.chromeOptions_.toCapabilities());

    } else if (browser === Browser.FIREFOX && this.firefoxOptions_) {
      capabilities.merge(this.firefoxOptions_.toCapabilities());

    } else if (browser === Browser.INTERNET_EXPLORER && this.ieOptions_) {
      capabilities.merge(this.ieOptions_.toCapabilities());

    } else if (browser === Browser.OPERA && this.operaOptions_) {
      capabilities.merge(this.operaOptions_.toCapabilities());

    } else if (browser === Browser.SAFARI && this.safariOptions_) {
      capabilities.merge(this.safariOptions_.toCapabilities());

    } else if (browser === Browser.EDGE && this.edgeOptions_) {
      capabilities.merge(this.edgeOptions_.toCapabilities());
    }

    // Check for a remote browser.
    var url = this.url_;
    if (!this.ignoreEnv_) {
      if (process.env.SELENIUM_REMOTE_URL) {
        url = process.env.SELENIUM_REMOTE_URL;
      } else if (process.env.SELENIUM_SERVER_JAR) {
        url = startSeleniumServer(process.env.SELENIUM_SERVER_JAR);
      }
    }

    if (url) {
      var executor = executors.createExecutor(url, this.proxy_);
      return WebDriver.createSession(executor, capabilities, this.flow_);
    }

    // Check for a native browser.
    switch (browser) {
      case Browser.CHROME:
        return new chrome.Driver(capabilities, null, this.flow_);

      case Browser.FIREFOX:
        return new firefox.Driver(capabilities, this.flow_);

      case Browser.INTERNET_EXPLORER:
        return new ie.Driver(capabilities, this.flow_);

      case Browser.EDGE:
        return new edge.Driver(capabilities, null, this.flow_);

      case Browser.OPERA:
        return new opera.Driver(capabilities, null, this.flow_);

      case Browser.PHANTOM_JS:
        return new phantomjs.Driver(capabilities, this.flow_);

      case Browser.SAFARI:
        return new safari.Driver(capabilities, this.flow_);

      default:
        throw new Error('Do not know how to build driver: ' + browser
            + '; did you forget to call usingServer(url)?');
    }
  }

  /**
   * Creates a new WebDriver client based on this builder's current
   * configuration. This method returns a promise that will not be fulfilled
   * until the new browser session has been fully initialized.
   *
   * __Note:__ this method is purely a convenience wrapper around
   * {@link #build()}.
   *
   * @return {!promise.Promise<!webdriver.WebDriver>} A promise that will be
   *    fulfilled with the newly created WebDriver instance once the browser
   *    has been fully initialized.
   * @see #build()
   */
  buildAsync() {
    let driver = this.build();
    return driver.getSession().then(() => driver);
  }
}


// PUBLIC API


exports.Builder = Builder;