2016-04-27 163 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实际上是命令的输出(它是一个数组不是整数) 。