Snippets

Metadrop Gestionar phantomjs desde un feature context

Created by Omar

  /**
   * Get phantomjs port.
   * 
   * @TODO: extract by settings!
   *
   * @return int
   *   Port.
   */
  public static function getPort() {
    return 9000;
  }

  /**
   * @BeforeFeature
   */
  public static function ensurePhantomjs() {
    if (!self::isPhantomjsActive()) {
      self::startPhantomjs();
    }
  }

  /**
   * @AfterScenario @javascript
   */
  public function restartPhantomjs() {
    // Stop driver.
    $driver = $this->getSession()->getDriver();
    $driver->stop();

    // Restart phantomjs.
    self::stopPhantomjs();
    self::startPhantomjs();
    sleep(1);

    // Start driver again.
    $driver->setWebdriver(new WebDriver('http://127.0.0.1:9000/wd/hub'));
    $driver->start();
  }

  /**
   * Start phantomjs
   */
  public static function startPhantomjs() {
    $port = self::getPort();
    $command = 'phantomjs2 --webdriver=' . $port . ' --load-images=false --ignore-ssl-errors=true > /dev/null 2>/dev/null &';
    exec($command);
  }

  /**
   * @AfterSuite
   *
   * We need register shutdown function to stop phantomjs
   * because other processes will require it after this hook implementation.
   */phantomjs-behat
  public static function registerPhantomjsStopAfterTests() {
    register_shutdown_function(array('FeatureContext', 'stopPhantomjs'));
  }

  /**
   * Kill phantomjs if it was launched.
   */
  public static function stopPhantomjs() {
    $pid = self::getPhantomjsPid();
    if ($pid) {
      exec('kill ' . $pid);
    }
  }

  /**
   * Get phantomjs pid.
   *
   * We use ps aux and grep to extract the process id.
   *
   * @return int
   *   Phantomjs pid.
   */
  public static function getPhantomjsPid() {
    $port = self::getPort();
    $command = "ps aux | grep 'phantomjs2 --webdriver=$port' | grep -v grep | awk '{ print $2 }' | head -1";
    exec($command, $out);
    return !empty($out[0]) ? $out[0] : NULL;
  }

  /**
   * Check phantomjs is active.
   *
   * @return bool
   *   Phantomjs is active.
   */
  public static function isPhantomjsActive() {
    $pid = self::getPhantomjsPid();
    return !empty($pid);
  }

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.