2016-04-27 160 views
0

我正在測試Web爬網程序腳本。我正在使用php內置webserver在本地測試頁面。Behat:完成測試後無法終止Web服務器進程

我可以啓動服務器,但我不能殺死進程,因爲它已經被殺死(我得到了我設置的例外Could not kill the testing web server)。

這裏是我的嘗試:

<?php 

use Behat\Behat\Tester\Exception\PendingException; 
use Behat\Behat\Context\Context; 
use Behat\Behat\Context\SnippetAcceptingContext; 
use Behat\Gherkin\Node\PyStringNode; 
use Behat\Gherkin\Node\TableNode; 

use Behat\Behat\Hook\Scope\BeforeScenarioScope; 
use Behat\Behat\Hook\Scope\AfterScenarioScope; 

/** 
* Defines application features from the specific context. 
*/ 
class FeatureContext implements Context, SnippetAcceptingContext 
{ 

    const TESTING_BASE_URL = 'http://127.0.0.1:6666'; 
    const TESTING_DIR = '/tmp/testDirectory'; 

    private $pid; 

    /** 
    * Initializes context. 
    * 
    * Every scenario gets its own context instance. 
    * You can also pass arbitrary arguments to the 
    * context constructor through behat.yml. 
    */ 
    public function __construct() 
    { 
    } 

    /** 
    * @BeforeScenario 
    */ 
    public function before(BeforeScenarioScope $scope) 
    { 
     // Create testing directory holding our pages 
     if (!is_dir(self::TESTING_DIR)) { 
      if (!mkdir(self::TESTING_DIR)) { 
       throw new \Exception('Cannot create the directory for testing'); 
      } 
     } 

     // Start the testing server 
     $command = sprintf(
      'php -S %s -t $%s >/dev/null 2>&1 & echo $!', 
      escapeshellarg(self::TESTING_BASE_URL), 
      escapeshellarg(self::TESTING_DIR) 
     ); 

     $output = []; 
     exec($command, $output, $return_var); 

     if ($return_var !== 0) { 
      throw new \Exception('Cannot start the testing web server'); 
     } 

     $this->pid = (int)$output[0]; 
     echo sprintf(
      'Testing web server started on %s with PID %s %s %s', 
      self::TESTING_BASE_URL, 
      (string)$this->pid, 
      PHP_EOL, 
      PHP_EOL 
     ); 

    } 

    /** 
    * @AfterScenario 
    */ 
    public function after(AfterScenarioScope $scope) 
    { 
      // ... kill the web server 
      $output = []; 
      exec('kill ' . (string) $this->pid, $return_var); 

      if ($return_var !== 0) { 
       throw new \Exception('Could not kill the testing web server (PID ' . (string) $this->pid . ')'); 
      } 

      echo 'Testing web server killed (PID ', (string) $this->pid, ')', PHP_EOL, PHP_EOL; 

      // ... remove the test directory 
      $o = []; 
      exec('rm -rf ' . escapeshellarg(self::TESTING_DIR), $o, $returnVar); 

      if ($returnVar !== 0) { 
       throw new \Exception('Cannot remove the testing directory'); 
      } 
    } 


    // ... 
} 

我也嘗試就像把它全部在構造函數中,使用register_shutdown_function,沒有任何成功的各種事情。

我錯過了什麼?有關我如何解決這個問題的任何想法?

而不僅僅是「不關心殺死服務器進程」(因爲對我來說,當我嘗試殺死進程時,看起來它已經消失了,因此錯誤,當我在命令上發出ps aux | grep php時找不到它在運行behat後線),是不是「乾淨」殺了它,因爲我參加?

回答

0

的exec調用缺少輸出參數:

exec('kill ' . (string) $this->pid, $output, $return_var); 

除非本被設置時,異常將總是被拋出,因爲$return_var實際上是命令的輸出(它是一個數組不是整數) 。