[ Index ]

PHP Cross Reference of PHK Manager

title

Body

[close]

/PHK/UnitTest/ -> PHPUnit.php (source)

   1  <?php
   2  //=============================================================================
   3  //
   4  // Copyright Francois Laupretre <phk@tekwire.net>
   5  //
   6  //   Licensed under the Apache License, Version 2.0 (the "License");
   7  //   you may not use this file except in compliance with the License.
   8  //   You may obtain a copy of the License at
   9  //
  10  //       http://www.apache.org/licenses/LICENSE-2.0
  11  //
  12  //   Unless required by applicable law or agreed to in writing, software
  13  //   distributed under the License is distributed on an "AS IS" BASIS,
  14  //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15  //   See the License for the specific language governing permissions and
  16  //   limitations under the License.
  17  //
  18  //=============================================================================
  19  // Please note that most of this file is derived from the code published by
  20  // the PHPUnit project (v 3.2.2).
  21  // As such, please consider the following notice:
  22  /*
  23   * PHPUnit
  24   *
  25   * Copyright (c) 2002-2007, Sebastian Bergmann <sb@sebastian-bergmann.de>.
  26   * All rights reserved.
  27   *
  28   * Redistribution and use in source and binary forms, with or without
  29   * modification, are permitted provided that the following conditions
  30   * are met:
  31   *
  32   *   * Redistributions of source code must retain the above copyright
  33   *     notice, this list of conditions and the following disclaimer.
  34   *
  35   *   * Redistributions in binary form must reproduce the above copyright
  36   *     notice, this list of conditions and the following disclaimer in
  37   *     the documentation and/or other materials provided with the
  38   *     distribution.
  39   *
  40   *   * Neither the name of Sebastian Bergmann nor the names of his
  41   *     contributors may be used to endorse or promote products derived
  42   *     from this software without specific prior written permission.
  43   *
  44   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  45   * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  46   * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  47   * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  48   * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  49   * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  50   * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  51   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  52   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  53   * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  54   * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  55   * POSSIBILITY OF SUCH DAMAGE.
  56  */
  57  //=============================================================================
  58  /**
  59  * @copyright Francois Laupretre <phk@tekwire.net>
  60  * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, V 2.0
  61  * @category PHK
  62  * @package PHK
  63  *///==========================================================================
  64  
  65  namespace PHK\UnitTest {
  66  
  67  if (!function_exists('PHK\UnitTest\_phk_load_phpunit_interface'))
  68  {
  69  function _phk_load_phpunit_interface()
  70  {
  71  if (!class_exists('PHK\UnitTest\PHPUnit_Runner_PHKTestSuiteLoader',false))
  72  {
  73  //=============================================================================
  74  /**
  75  */
  76  class PHPUnit_Runner_PHKTestSuiteLoader implements \PHPUnit_Runner_TestSuiteLoader
  77  {
  78  
  79  //-------------------
  80  
  81  public function load($suiteClassName, $suiteClassFile = '')
  82  {
  83  if (class_exists($suiteClassName, true))
  84      {
  85      return new \ReflectionClass($suiteClassName);
  86      }
  87  else throw new \RuntimeException("Class $suiteClassName could not be found");
  88  }
  89  
  90  //-------------------
  91  
  92  public function reload(\ReflectionClass $aClass)
  93  {
  94  return $aClass;
  95  }
  96  
  97  //---------------------------------
  98  } // End of class
  99  //-------------------------
 100  } // End of class_exists
 101  //=============================================================================
 102  
 103  if (!class_exists('PHK\UnitTest\PHPUnit_TextUI_PHK',false))
 104  {
 105  //=============================================================================
 106  /**
 107  */
 108  class PHPUnit_TextUI_PHK
 109  {
 110  //-------------------
 111  
 112  public static function main()
 113  {
 114  PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');
 115  
 116  self::handleLoader('PHK\UnitTest\PHPUnit_Runner_PHKTestSuiteLoader');
 117  
 118  //----
 119  
 120  $arguments=self::handleArguments();
 121  
 122  $runner= new \PHPUnit_TextUI_TestRunner;
 123  
 124  $suite = $runner->getTest($arguments['test'],'',$arguments['syntaxCheck']);
 125  
 126  try    {
 127      if (\PHK\Tools\Util::envIsWeb()) echo "<pre>\n";
 128  
 129      $result = $runner->doRun($suite,$arguments);
 130  
 131      if (\PHK\Tools\Util::envIsWeb()) echo "</pre>\n";
 132      }
 133  catch (\Exception $e)
 134      {
 135      throw new \RuntimeException('Could not create and run test suite: '
 136          . $e->getMessage());
 137      }
 138  
 139  if (!\PHK\Tools\Util::envIsWeb())
 140      {
 141      if ($result->wasSuccessful()) exit(\PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
 142      else if($result->errorCount() > 0)
 143          exit(\PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
 144      else exit(\PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
 145      }
 146  }
 147  
 148  //-------------------
 149  /**
 150  * @access protected
 151  * @static
 152  */
 153  
 154  protected static function handleArguments()
 155  {
 156  $arguments = array('syntaxCheck' => TRUE);
 157  
 158  $longOptions = array(
 159      'configuration=',
 160      'exclude-group=',
 161      'filter=',
 162      'group=',
 163      'help',
 164      'loader=',
 165      'log-json=',
 166      'log-tap=',
 167      'log-xml=',
 168      'repeat=',
 169      'skeleton',
 170      'stop-on-failure',
 171      'tap',
 172      'testdox',
 173      'testdox-html=',
 174      'testdox-text=',
 175      'no-syntax-check',
 176      'verbose',
 177      'version',
 178      'wait');
 179  
 180  if (class_exists('Image_GraphViz', FALSE)) $longOptions[] = 'log-graphviz=';
 181  
 182  if (extension_loaded('pdo'))
 183      {
 184      $longOptions[] = 'test-db-dsn=';
 185      $longOptions[] = 'test-db-log-rev=';
 186      $longOptions[] = 'test-db-log-prefix=';
 187      $longOptions[] = 'test-db-log-info=';
 188      }
 189  
 190  if (extension_loaded('xdebug'))
 191      {
 192      $longOptions[] = 'coverage-html=';
 193      $longOptions[] = 'coverage-xml=';
 194      $longOptions[] = 'log-metrics=';
 195      $longOptions[] = 'log-pmd=';
 196      $longOptions[] = 'report=';
 197      }
 198  
 199  try
 200      {
 201      //-- Tests if argv exists - allows to run in web mode
 202  
 203      $options = \PHPUnit_Util_Getopt::getopt(
 204          isset($_SERVER['argv']) ? $_SERVER['argv'] : array(),'d:',$longOptions);
 205      }
 206  catch (\RuntimeException $e)
 207      {
 208      \PHPUnit_TextUI_TestRunner::showError($e->getMessage());
 209      }
 210  
 211  $arguments['test']=(isset($options[1][0]) ? $options[1][0] : 'AllTests');
 212  
 213  $arguments['testFile'] = '';
 214  
 215  foreach ($options[0] as $option)
 216      {
 217      switch ($option[0])
 218          {
 219          case '--configuration':
 220              $arguments['configuration'] = $option[1];
 221              break;
 222  
 223          case '--coverage-xml':
 224              $arguments['coverageXML'] = $option[1];
 225              break;
 226  
 227          case 'd':
 228              $ini = explode('=', $option[1]);
 229              if (isset($ini[0]))
 230                  {
 231                  if (isset($ini[1]))
 232                      {
 233                      ini_set($ini[0], $ini[1]);
 234                      }
 235                  else ini_set($ini[0], TRUE);
 236                  }
 237              break;
 238  
 239          case '--help':
 240              self::showHelp();
 241              exit(\PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
 242              break;
 243  
 244          case '--filter':
 245              if (preg_match('/^[a-zA-Z0-9_]/', $option[1]))
 246                  $arguments['filter'] = '/^' . $option[1] . '$/';
 247              else
 248                  $arguments['filter'] = $option[1];
 249              break;
 250  
 251          case '--group':
 252              $arguments['groups'] = explode(',', $option[1]);
 253              break;
 254  
 255          case '--exclude-group':
 256              $arguments['excludeGroups'] = explode(',', $option[1]);
 257              break;
 258  
 259          case '--loader':
 260              self::handleLoader($option[1]);
 261              break;
 262  
 263          case '--log-json':
 264              $arguments['jsonLogfile'] = $option[1];
 265              break;
 266  
 267          case '--log-graphviz':
 268              $arguments['graphvizLogfile'] = $option[1];
 269              break;
 270  
 271          case '--log-tap':
 272              $arguments['tapLogfile'] = $option[1];
 273              break;
 274  
 275          case '--log-xml':
 276              $arguments['xmlLogfile'] = $option[1];
 277              break;
 278  
 279          case '--log-pmd':
 280              $arguments['pmdXML'] = $option[1];
 281              break;
 282  
 283          case '--log-metrics':
 284              $arguments['metricsXML'] = $option[1];
 285              break;
 286  
 287          case '--repeat':
 288              $arguments['repeat'] = (int)$option[1];
 289              break;
 290  
 291          case '--stop-on-failure':
 292              $arguments['stopOnFailure'] = TRUE;
 293              break;
 294  
 295          case '--test-db-dsn':
 296              $arguments['testDatabaseDSN'] = $option[1];
 297              break;
 298  
 299          case '--test-db-log-rev':
 300              $arguments['testDatabaseLogRevision'] = $option[1];
 301              break;
 302  
 303          case '--test-db-prefix':
 304              $arguments['testDatabasePrefix'] = $option[1];
 305              break;
 306  
 307          case '--test-db-log-info':
 308              $arguments['testDatabaseLogInfo'] = $option[1];
 309              break;
 310  
 311          case '--coverage-html':
 312          case '--report':
 313              $arguments['reportDirectory'] = $option[1];
 314              break;
 315  
 316          case '--skeleton':
 317              if (isset($arguments['test']))
 318                  self::doSkeleton($arguments['test'],'');
 319              else
 320                  {
 321                  self::showHelp();
 322                  exit(\PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
 323                  }
 324              break;
 325  
 326          case '--tap':
 327              $arguments['printer'] = new \PHPUnit_Util_Log_TAP;
 328              break;
 329  
 330          case '--testdox':
 331              $arguments['printer'] = new \PHPUnit_Util_TestDox_ResultPrinter_Text;
 332              break;
 333  
 334          case '--testdox-html':
 335              $arguments['testdoxHTMLFile'] = $option[1];
 336              break;
 337  
 338          case '--testdox-text':
 339              $arguments['testdoxTextFile'] = $option[1];
 340              break;
 341  
 342          case '--no-syntax-check':
 343              $arguments['syntaxCheck'] = FALSE;
 344              break;
 345  
 346          case '--verbose':
 347              $arguments['verbose'] = TRUE;
 348              break;
 349  
 350          case '--version':
 351              \PHPUnit_TextUI_TestRunner::printVersionString();
 352              exit(\PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
 353              break;
 354  
 355          case '--wait':
 356              $arguments['wait'] = TRUE;
 357              break;
 358          }
 359      }
 360  
 361  if (!isset($arguments['test']) && isset($arguments['configuration']))
 362      {
 363      $configuration= new \PHPUnit_Util_Configuration($arguments['configuration']);
 364  
 365      $testSuite = $configuration->getTestSuiteConfiguration();
 366  
 367      if ($testSuite !== NULL) $arguments['test'] = $testSuite;
 368      }
 369  
 370  if ((isset($arguments['testDatabaseLogRevision'])
 371      && !isset($arguments['testDatabaseDSN'])))
 372      {
 373      self::showHelp();
 374      exit(\PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
 375      }
 376  
 377  return $arguments;
 378  }
 379  
 380  /**
 381  * @param  string  $test
 382  * @param  string  $testFile
 383  * @access protected
 384  * @static
 385  */
 386  protected static function doSkeleton($test, $testFile)
 387  {
 388  if ($test !== FALSE)
 389      {
 390      \PHPUnit_TextUI_TestRunner::printVersionString();
 391  
 392      try
 393          {
 394          $skeleton = new \PHPUnit_Util_Skeleton($test, $testFile);
 395          $skeleton->write();
 396          }
 397      catch (\Exception $e)
 398          {
 399          print $e->getMessage() . "\n";
 400  
 401          printf('Could not write test class skeleton for "%s" to "%s".' . "\n",
 402              $test,$testFile);
 403  
 404          exit(\PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
 405          }
 406  
 407      printf('Wrote test class skeleton for "%s" to "%s".' . "\n",
 408          $test,$skeleton->getTestSourceFile());
 409  
 410      exit(\PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
 411      }
 412  }
 413  
 414  /**
 415  * @param  string  $loaderName
 416  * @access protected
 417  * @static
 418  */
 419  protected static function handleLoader($loaderName)
 420  {
 421  if (!class_exists($loaderName, FALSE))
 422      {
 423      \PHPUnit_Util_Fileloader::checkAndLoad(str_replace('_', '/', $loaderName)
 424          . '.php');
 425      }
 426  
 427  if (class_exists($loaderName, FALSE))
 428      {
 429      $class = new \ReflectionClass($loaderName);
 430  
 431      if ($class->implementsInterface('PHPUnit_Runner_TestSuiteLoader') &&
 432          $class->isInstantiable())
 433          {
 434          $loader = $class->newInstance();
 435          }
 436      }
 437  
 438  if (!isset($loader))
 439      {
 440      \PHPUnit_TextUI_TestRunner::showError(
 441          sprintf('Could not use "%s" as loader.',$loaderName));
 442      }
 443  
 444  \PHPUnit_TextUI_TestRunner::setLoader($loader);
 445  }
 446  
 447  /**
 448  * @access public
 449  * @static
 450  */
 451  public static function showHelp()
 452  {
 453  \PHPUnit_TextUI_TestRunner::printVersionString();
 454  
 455  print "Usage: php <package> [switches] [UnitTest]\n\n";
 456  
 457  if (class_exists('Image_GraphViz', FALSE)) {
 458      print "  --log-graphviz <file>  Log test execution in GraphViz markup.\n";
 459  }
 460  
 461  print "  --log-json <file>      Log test execution in JSON format.\n" .
 462        "  --log-tap <file>       Log test execution in TAP format to file.\n" .
 463        "  --log-xml <file>       Log test execution in XML format to file.\n";
 464  
 465  if (extension_loaded('xdebug')) {
 466      print "  --log-metrics <file>   Write metrics report in XML format.\n" .
 467            "  --log-pmd <file>       Write violations report in PMD XML format.\n\n" .
 468            "  --coverage-html <dir>  Generate code coverage report in HTML format.\n" .
 469            "  --coverage-xml <file>  Write code coverage information in XML format.\n\n";
 470  }
 471  
 472  if (extension_loaded('pdo')) {
 473      print "  --test-db-dsn <dsn>    DSN for the test database.\n" .
 474            "  --test-db-log-rev <r>  Revision information for database logging.\n" .
 475            "  --test-db-prefix ...   Prefix that should be stripped from filenames.\n" .
 476            "  --test-db-log-info ... Additional information for database logging.\n\n";
 477  }
 478  
 479  print "  --testdox-html <file>  Write agile documentation in HTML format to file.\n" .
 480        "  --testdox-text <file>  Write agile documentation in Text format to file.\n\n" .
 481        "  --filter <pattern>     Filter which tests to run.\n" .
 482        "  --group ...            Only runs tests from the specified group(s).\n" .
 483        "  --exclude-group ...    Exclude tests from the specified group(s).\n\n" .
 484        "  --loader <loader>      TestSuiteLoader implementation to use.\n" .
 485        "  --repeat <times>       Runs the test(s) repeatedly.\n\n" .
 486        "  --tap                  Report test execution progress in TAP format.\n" .
 487        "  --testdox              Report test execution progress in TestDox format.\n\n" .
 488        "  --no-syntax-check      Disable syntax check of test source files.\n" .
 489        "  --stop-on-failure      Stop execution upon first error or failure.\n" .
 490        "  --verbose              Output more verbose information.\n" .
 491        "  --wait                 Waits for a keystroke after each test.\n\n" .
 492        "  --skeleton             Generate skeleton UnitTest class for Unit in Unit.php.\n\n" .
 493        "  --help                 Prints this usage information.\n" .
 494        "  --version              Prints the version and exits.\n\n" .
 495        "  --configuration <file> Read configuration from XML file.\n" .
 496        "  -d key[=value]         Sets a php.ini value.\n";
 497  }
 498  
 499  //---------------------------------
 500  } // End of class PHPUnit_TextUI_PHK
 501  //-------------------------
 502  } // End of class_exists('PHPUnit_TextUI_PHK')
 503  //=============================================================================
 504  } // End of function \PHK\UnitTest\_phk_load_phpunit_interface
 505  //=============================================================================
 506  } // End of function_exists(\PHK\UnitTest\_phk_load_phpunit_interface)
 507  //===========================================================================
 508  } // End of namespace
 509  //===========================================================================
 510  ?>


Generated: Thu Jun 4 18:33:15 2015 Cross-referenced by PHPXref 0.7.1