From 7417a00de79c01b1b761bfb90e43475e440948b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 13:40:50 -0430 Subject: [PATCH 001/230] Initial step to replace simpletest for PHPUnit This is probably temporary, still needed to see if PHPUnit is already in path (installed with pear or something) --- cake/tests/lib/cake_test_suite_dispatcher.php | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/cake/tests/lib/cake_test_suite_dispatcher.php b/cake/tests/lib/cake_test_suite_dispatcher.php index d0d128786..2b4ee4250 100644 --- a/cake/tests/lib/cake_test_suite_dispatcher.php +++ b/cake/tests/lib/cake_test_suite_dispatcher.php @@ -17,7 +17,6 @@ * @since CakePHP(tm) v 1.3 * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -require_once CAKE_TESTS_LIB . 'test_manager.php'; /** * CakeTestSuiteDispatcher handles web requests to the test suite and runs the correct action. @@ -116,7 +115,18 @@ class CakeTestSuiteDispatcher { * @return void */ function _checkSimpleTest() { - if (!App::import('Vendor', 'simpletest/reporter')) { + $found = $path = null; + foreach (App::path('vendors') as $vendor) { + if (is_dir($vendor . 'PHPUnit')) { + $path = $vendor; + } + } + + if ($path && ini_set('include_path', $path . PATH_SEPARATOR . ini_get('include_path'))) { + $found = include 'PHPUnit' . DS . 'Framework.php'; + } + + if (!$found) { $baseDir = $this->_baseDir; include CAKE_TESTS_LIB . 'templates/simpletest.php'; exit(); @@ -171,6 +181,7 @@ class CakeTestSuiteDispatcher { */ function &getManager() { if (empty($this->Manager)) { + require_once CAKE_TESTS_LIB . 'test_manager.php'; $this->Manager = new $this->_managerClass(); } return $this->Manager; From 14559aabd9b545c40790aa0e8074fddbad0ab3e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 13:47:08 -0430 Subject: [PATCH 002/230] Adding compatibility assert methods for CakeTestCase to ease the transition to PHPUnit --- cake/tests/lib/cake_test_case.php | 35 ++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index b2799e44d..50aebfe76 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -82,7 +82,7 @@ class CakeTestDispatcher extends Dispatcher { * @package cake * @subpackage cake.cake.tests.lib */ -class CakeTestCase extends UnitTestCase { +class CakeTestCase extends PHPUnit_Framework_TestCase { /** * Methods used internally. @@ -191,8 +191,10 @@ class CakeTestCase extends UnitTestCase { * @param string $message * @return boolean */ - public function skipIf($shouldSkip, $message = '%s') { - parent::skipIf($shouldSkip, $message); + public function skipIf($shouldSkip, $message = '') { + if ($shouldSkip) { + $this->markTestSkipped($message); + } return $shouldSkip; } @@ -298,7 +300,7 @@ class CakeTestCase extends UnitTestCase { * @param mixed $params Parameters (see above), or simply a string of what to return * @return mixed Whatever is returned depending of requested result */ - public function testAction($url, $params = array()) { + public function runTestAction($url, $params = array()) { $default = array( 'return' => 'result', 'fixturize' => false, @@ -685,7 +687,7 @@ class CakeTestCase extends UnitTestCase { return false; } } - return $this->assert(new TrueExpectation(), true, '%s'); + return $this->assertTrue(true, '%s'); } /** @@ -817,5 +819,28 @@ class CakeTestCase extends UnitTestCase { return $permuted; } } + + protected function assertEqual($a, $b) { + return $this->assertEquals($a, $b); + } + + protected function assertPattern($pattern, $string, $message = '') { + return $this->assertRegExp($pattern, $string, $message); + } + + protected function assertIdentical($expected, $actual, $message = '') { + return $this->assertSame($expected, $actual, $message); + } + + protected function assertNoPattern($pattern, $string, $message = '') { + return $this->assertNotRegExp($pattern, $string, $message); + } + + protected function assertNoErrors() { + } + + protected function expectException($name = null) { + $this->setExpectedException($name); + } } ?> \ No newline at end of file From 15dd798e306ff6b8350a85da16df7435de8488f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 13:49:10 -0430 Subject: [PATCH 003/230] Some experimental movements inside TEstManager to make it work with PHPUnit --- cake/tests/lib/test_manager.php | 61 ++++++++++++++++----------------- 1 file changed, 29 insertions(+), 32 deletions(-) diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index dce37e144..3fd1b502c 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -29,7 +29,7 @@ define('APP_TEST_GROUPS', TESTS . 'groups'); * @package cake * @subpackage cake.cake.tests.lib */ -class TestManager { +class TestManager extends PHPUnit_Runner_BaseTestRunner { /** * Extension suffix for test case files. * @@ -64,7 +64,8 @@ class TestManager { * @return void */ public function __construct() { - $this->_installSimpleTest(); + //require_once(CAKE_TESTS_LIB . 'cake_web_test_case.php'); + require_once(CAKE_TESTS_LIB . 'cake_test_case.php'); if (isset($_GET['app'])) { $this->appTest = true; } @@ -73,21 +74,6 @@ class TestManager { } } -/** - * Includes the required simpletest files in order for the testsuite to run - * - * @return void - */ - public function _installSimpleTest() { - App::import('Vendor', array( - 'simpletest' . DS . 'unit_tester', - 'simpletest' . DS . 'mock_objects', - 'simpletest' . DS . 'web_tester' - )); - require_once(CAKE_TESTS_LIB . 'cake_web_test_case.php'); - require_once(CAKE_TESTS_LIB . 'cake_test_case.php'); - } - /** * Runs all tests in the Application depending on the current appTest setting * @@ -120,11 +106,11 @@ class TestManager { * Runs a specific test case file * * @param string $testCaseFile Filename of the test to be run. - * @param Object $reporter Reporter instance to attach to the test case. + * @param PHPUnit_Framework_TestListener $reporter Reporter instance to attach to the test case. * @param boolean $testing Set to true if testing, otherwise test case will be run. * @return mixed Result of test case being run. */ - public function runTestCase($testCaseFile, &$reporter, $testing = false) { + public function runTestCase($testCaseFile, PHPUnit_Framework_TestListener &$reporter, $testing = false) { $testCaseFileWithPath = $this->_getTestsPath() . DS . $testCaseFile; if (!file_exists($testCaseFileWithPath)) { @@ -136,9 +122,16 @@ class TestManager { return true; } - $test = new TestSuite(sprintf(__('Individual test case: %s', true), $testCaseFile)); - $test->addTestFile($testCaseFileWithPath); - return $test->run($reporter); + $testSuite = new PHPUnit_Framework_TestSuite; + $testSuite->setName(sprintf(__('Individual test case: %s', true), $testCaseFile)); + $testSuite->addTestFile($testCaseFileWithPath); + + $result = new PHPUnit_Framework_TestResult; + $result->addListener($reporter); + $reporter->paintHeader($testSuite->getName()); + $run = $testSuite->run($result); + $reporter->paintResult($result); + return $run; } /** @@ -193,16 +186,16 @@ class TestManager { * @access public * @static */ - public static function addTestFile(&$groupTest, $file) { - $manager = new TestManager(); - - if (file_exists($file . $manager->_testExtension)) { - $file .= $manager->_testExtension; - } elseif (file_exists($file . $manager->_groupExtension)) { - $file .= $manager->_groupExtension; - } - $groupTest->addTestFile($file); - } + // public static function addTestFile(&$groupTest, $file) { + // $manager = new TestManager(); + // + // if (file_exists($file . $manager->_testExtension)) { + // $file .= $manager->_testExtension; + // } elseif (file_exists($file . $manager->_groupExtension)) { + // $file .= $manager->_groupExtension; + // } + // $groupTest->addTestFile($file); + // } /** * Returns a list of test cases found in the current valid test case path @@ -393,6 +386,10 @@ class TestManager { } return $this->_groupExtension; } + + protected function runFailed($message) { + + } } ?> \ No newline at end of file From ce7f892d6a1c9ce74188b352ebaeecf515af492d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 13:50:07 -0430 Subject: [PATCH 004/230] Removing simpletest dependency in CakeBaseReporter --- cake/tests/lib/reporter/cake_base_reporter.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cake/tests/lib/reporter/cake_base_reporter.php b/cake/tests/lib/reporter/cake_base_reporter.php index 932b45eea..c6d36a987 100644 --- a/cake/tests/lib/reporter/cake_base_reporter.php +++ b/cake/tests/lib/reporter/cake_base_reporter.php @@ -24,7 +24,7 @@ * @package cake * @subpackage cake.tests.lib */ -class CakeBaseReporter extends SimpleReporter { +class CakeBaseReporter { /** * Time the test runs started. @@ -81,7 +81,6 @@ class CakeBaseReporter extends SimpleReporter { * @param array $params Array of request parameters the reporter should use. See above. */ function __construct($charset = 'utf-8', $params = array()) { - parent::__construct(); if (!$charset) { $charset = 'utf-8'; } From 9afbeaa217e7d2e4c0d91e2f8de90b6688dab792 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 13:51:25 -0430 Subject: [PATCH 005/230] Converting CakeHtmlReporter in a TestCase listener. this apparently shows that it is easy to make the transition to PHPUnit. --- .../tests/lib/reporter/cake_html_reporter.php | 138 ++++++++++++++++-- 1 file changed, 122 insertions(+), 16 deletions(-) diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 19ea25da2..69b28eb6d 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -26,7 +26,7 @@ include_once dirname(__FILE__) . DS . 'cake_base_reporter.php'; * @package cake * @subpackage cake.tests.lib */ -class CakeHtmlReporter extends CakeBaseReporter { +class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_TestListener{ /** * Paints the top of the web page setting the @@ -39,7 +39,6 @@ class CakeHtmlReporter extends CakeBaseReporter { $this->sendNoCacheHeaders(); $this->paintDocumentStart(); $this->paintTestMenu(); - echo "

$testName

\n"; echo "
    \n"; } @@ -155,20 +154,20 @@ class CakeHtmlReporter extends CakeBaseReporter { * @param string $test_name Name class of test. * @return void */ - public function paintFooter($test_name) { - $colour = ($this->getFailCount() + $this->getExceptionCount() > 0 ? "red" : "green"); + public function paintFooter($result) { + $colour = ($result->failureCount() + $result->errorCount() > 0 ? "red" : "green"); echo "
\n"; echo "
"; - echo $this->getTestCaseProgress() . "/" . $this->getTestCaseCount(); + echo $result->count() . "/" . $result->count() - $result->skippedCount(); echo " test cases complete:\n"; - echo "" . $this->getPassCount() . " passes, "; - echo "" . $this->getFailCount() . " fails and "; - echo "" . $this->getExceptionCount() . " exceptions."; + echo "" . count($result->passed()) . " passes, "; + echo "" . $result->failureCount() . " fails and "; + echo "" . $result->errorCount() . " exceptions."; echo "
\n"; echo '
'; - echo '

Time taken by tests (in seconds): ' . $this->_timeDuration . '

'; + echo '

Time taken by tests (in seconds): ' . $result->time() . '

'; if (function_exists('memory_get_peak_usage')) { echo '

Peak memory use: (in bytes): ' . number_format(memory_get_peak_usage()) . '

'; } @@ -247,18 +246,24 @@ class CakeHtmlReporter extends CakeBaseReporter { * trail of the nesting test suites below the * top level test. * - * @param string $message Failure message displayed in + * @param PHPUnit_Framework_AssertionFailedError $message Failure object displayed in * the context of the other tests. * @return void */ public function paintFail($message) { - parent::paintFail($message); + $context = $message->getTrace(); + $realContext = $context[3]; + $context = $context[2]; + echo "
  • \n"; echo "Failed"; - echo "
    " . $this->_htmlEntities($message) . "
    \n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - echo "
    " . implode(" -> ", $breadcrumb) . "
    \n"; + echo "
    " . $this->_htmlEntities($message->getDescription()) . "
    \n"; + echo "
    " . sprintf(__('File: %s'), $context['file']) . "
    \n"; + echo "
    " . sprintf(__('Method: %s'), $realContext['function']) . "
    \n"; + echo "
    " . sprintf(__('Line: %s'), $context['line']) . "
    \n"; + //$breadcrumb = $this->getTestList(); + //array_shift($breadcrumb); + //echo "
    " . implode(" -> ", $breadcrumb) . "
    \n"; echo "
  • \n"; } @@ -291,7 +296,6 @@ class CakeHtmlReporter extends CakeBaseReporter { * @return void */ public function paintError($message) { - parent::paintError($message); echo "
  • \n"; echo "Error"; echo "
    " . $this->_htmlEntities($message) . "
    \n"; @@ -355,5 +359,107 @@ class CakeHtmlReporter extends CakeBaseReporter { protected function _htmlEntities($message) { return htmlentities($message, ENT_COMPAT, $this->_characterSet); } + + public function paintResult(PHPUnit_Framework_TestResult $result) { + + /*if ($result->errorCount() > 0) { + $this->printErrors($result); + } + + if ($result->failureCount() > 0) { + $this->printFailures($result); + } + + if ($result->skippedCount() > 0) { + $this->printIncompletes($result); + } + + if ($result->skippedCount() > 0) { + $this->printSkipped($result); + }*/ + + $this->paintFooter($result); + } + +/** +* An error occurred. +* +* @param PHPUnit_Framework_Test $test +* @param Exception $e +* @param float $time +*/ + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { + + } + +/** +* A failure occurred. +* +* @param PHPUnit_Framework_Test $test +* @param PHPUnit_Framework_AssertionFailedError $e +* @param float $time +*/ + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { + $this->paintFail($e); + } + +/** +* Incomplete test. +* +* @param PHPUnit_Framework_Test $test +* @param Exception $e +* @param float $time +*/ + public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) { + + } + +/** +* Skipped test. +* +* @param PHPUnit_Framework_Test $test +* @param Exception $e +* @param float $time +* @since Method available since Release 3.0.0 +*/ + public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { + + } + +/** + * A test suite started. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { + echo '

    ' . sprintf(__('Running %s'), $suite->getName()) . '

    '; + } + +/** + * A test suite ended. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { + } + +/** + * A test started. + * + * @param PHPUnit_Framework_Test $test + */ + public function startTest(PHPUnit_Framework_Test $test) { + } + +/** + * A test ended. + * + * @param PHPUnit_Framework_Test $test + * @param float $time + */ + public function endTest(PHPUnit_Framework_Test $test, $time) { + } } ?> \ No newline at end of file From 10434c35b65373fcc376406dec303e1358ab745c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 16:30:06 -0430 Subject: [PATCH 006/230] Improving PHPUnit path detection when it is installed via pear --- cake/tests/lib/cake_test_suite_dispatcher.php | 25 ++++++++++++------- cake/tests/lib/test_manager.php | 2 +- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/cake/tests/lib/cake_test_suite_dispatcher.php b/cake/tests/lib/cake_test_suite_dispatcher.php index 2b4ee4250..6a7512728 100644 --- a/cake/tests/lib/cake_test_suite_dispatcher.php +++ b/cake/tests/lib/cake_test_suite_dispatcher.php @@ -92,7 +92,7 @@ class CakeTestSuiteDispatcher { * @return void */ function dispatch() { - $this->_checkSimpleTest(); + $this->_checkPHPUnit(); $this->_parseParams(); if ($this->params['group']) { @@ -110,20 +110,27 @@ class CakeTestSuiteDispatcher { } /** - * Checks that simpleTest is installed. Will exit if it doesn't + * Checks that PHPUnit is installed. Will exit if it doesn't * * @return void */ - function _checkSimpleTest() { + function _checkPHPUnit() { $found = $path = null; - foreach (App::path('vendors') as $vendor) { - if (is_dir($vendor . 'PHPUnit')) { - $path = $vendor; - } + + if (@include 'PHPUnit' . DS . 'Framework.php') { + $found = true; } - if ($path && ini_set('include_path', $path . PATH_SEPARATOR . ini_get('include_path'))) { - $found = include 'PHPUnit' . DS . 'Framework.php'; + if (!$found) { + foreach (App::path('vendors') as $vendor) { + if (is_dir($vendor . 'PHPUnit')) { + $path = $vendor; + } + } + + if ($path && ini_set('include_path', $path . PATH_SEPARATOR . ini_get('include_path'))) { + $found = include 'PHPUnit' . DS . 'Framework.php'; + } } if (!$found) { diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 3fd1b502c..7b06aab61 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -128,7 +128,7 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { $result = new PHPUnit_Framework_TestResult; $result->addListener($reporter); - $reporter->paintHeader($testSuite->getName()); + $reporter->paintHeader(); $run = $testSuite->run($result); $reporter->paintResult($result); return $run; From 4a152d3d55b9cdf63eacb638024c8cc711d2af15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 16:31:03 -0430 Subject: [PATCH 007/230] Adding number of assertion runned in html reporter enabling "show passes" (that in contrast of simpletest only reports the passed test method instead of the assertion) cleaning up a bit --- .../tests/lib/reporter/cake_base_reporter.php | 4 ++ .../tests/lib/reporter/cake_html_reporter.php | 57 +++++++++---------- 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/cake/tests/lib/reporter/cake_base_reporter.php b/cake/tests/lib/reporter/cake_base_reporter.php index c6d36a987..c0b5653f9 100644 --- a/cake/tests/lib/reporter/cake_base_reporter.php +++ b/cake/tests/lib/reporter/cake_base_reporter.php @@ -65,6 +65,10 @@ class CakeBaseReporter { */ protected $_characterSet; +/** +* The number of assertions done for a test suite +*/ + protected $numAssertions = 0; /** * Does nothing yet. The first output will * be sent on the first test start. diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 69b28eb6d..e59269562 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -26,16 +26,15 @@ include_once dirname(__FILE__) . DS . 'cake_base_reporter.php'; * @package cake * @subpackage cake.tests.lib */ -class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_TestListener{ +class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_TestListener { /** * Paints the top of the web page setting the * title to the name of the starting test. * - * @param string $test_name Name class of test. * @return void */ - public function paintHeader($testName) { + public function paintHeader() { $this->sendNoCacheHeaders(); $this->paintDocumentStart(); $this->paintTestMenu(); @@ -161,9 +160,10 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo "padding: 8px; margin: 1em 0; background-color: $colour; color: white;"; echo "\">"; echo $result->count() . "/" . $result->count() - $result->skippedCount(); - echo " test cases complete:\n"; + echo " test methods complete:\n"; echo "" . count($result->passed()) . " passes, "; - echo "" . $result->failureCount() . " fails and "; + echo "" . $result->failureCount() . " fails, "; + echo "" . $this->numAssertions . " assertions and "; echo "" . $result->errorCount() . " exceptions."; echo "
  • \n"; echo '
    '; @@ -174,8 +174,8 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo $this->_paintLinks(); echo '
    '; if ( - isset($this->params['codeCoverage']) && - $this->params['codeCoverage'] && + isset($this->params['codeCoverage']) && + $this->params['codeCoverage'] && class_exists('CodeCoverageManager') ) { CodeCoverageManager::report(); @@ -257,7 +257,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo "
  • \n"; echo "Failed"; - echo "
    " . $this->_htmlEntities($message->getDescription()) . "
    \n"; + echo "
    " . $this->_htmlEntities($message->getDescription()) . "
    \n"; echo "
    " . sprintf(__('File: %s'), $context['file']) . "
    \n"; echo "
    " . sprintf(__('Method: %s'), $realContext['function']) . "
    \n"; echo "
    " . sprintf(__('Line: %s'), $context['line']) . "
    \n"; @@ -272,19 +272,18 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * trail of the nesting test suites below the * top level test. * - * @param string $message Pass message displayed in the context of the other tests. + * @param PHPUnit_Framework_Test test method that just passed + * @param float $time time spent to run the test method * @return void */ - public function paintPass($message) { - parent::paintPass($message); - + public function paintPass(PHPUnit_Framework_Test $test, $time = null) { if (isset($this->params['show_passes']) && $this->params['show_passes']) { echo "
  • \n"; echo "Passed "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - echo implode(" -> ", $breadcrumb); - echo "
    " . $this->_htmlEntities($message) . "\n"; + //$breadcrumb = $this->getTestList(); + //array_shift($breadcrumb); + //echo implode(" -> ", $breadcrumb); + echo "
    " . $this->_htmlEntities($test->getName()) . " ($time seconds)\n"; echo "
  • \n"; } } @@ -312,7 +311,6 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * @return void */ public function paintException($exception) { - parent::paintException($exception); echo "
  • \n"; echo "Exception"; $message = 'Unexpected exception of type [' . get_class($exception) . @@ -333,7 +331,6 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * @return void */ public function paintSkip($message) { - parent::paintSkip($message); echo "
  • \n"; echo "Skipped "; echo $this->_htmlEntities($message); @@ -369,7 +366,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes if ($result->failureCount() > 0) { $this->printFailures($result); } - + if ($result->skippedCount() > 0) { $this->printIncompletes($result); } @@ -389,15 +386,15 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * @param float $time */ public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { - + } /** * A failure occurred. * -* @param PHPUnit_Framework_Test $test +* @param PHPUnit_Framework_Test $test * @param PHPUnit_Framework_AssertionFailedError $e -* @param float $time +* @param float $time */ public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { $this->paintFail($e); @@ -407,8 +404,8 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * Incomplete test. * * @param PHPUnit_Framework_Test $test -* @param Exception $e -* @param float $time +* @param Exception $e +* @param float $time */ public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) { @@ -418,19 +415,16 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * Skipped test. * * @param PHPUnit_Framework_Test $test -* @param Exception $e -* @param float $time -* @since Method available since Release 3.0.0 +* @param Exception $e +* @param float $time */ public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { - } /** * A test suite started. * * @param PHPUnit_Framework_TestSuite $suite - * @since Method available since Release 2.2.0 */ public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { echo '

    ' . sprintf(__('Running %s'), $suite->getName()) . '

    '; @@ -440,7 +434,6 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * A test suite ended. * * @param PHPUnit_Framework_TestSuite $suite - * @since Method available since Release 2.2.0 */ public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { } @@ -457,9 +450,11 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * A test ended. * * @param PHPUnit_Framework_Test $test - * @param float $time + * @param float $time */ public function endTest(PHPUnit_Framework_Test $test, $time) { + $this->numAssertions += $test->getNumAssertions(); + $this->paintPass($test, $time); } } ?> \ No newline at end of file From cdf4006f1600ae7debf3211533987ecbe29c4782 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 18:25:15 -0430 Subject: [PATCH 008/230] Refactoring TestManager::runAllTests() and improving the TestManager test case --- cake/tests/cases/libs/test_manager.test.php | 66 ++++++++++++++---- cake/tests/lib/test_manager.php | 75 ++++++++++++--------- 2 files changed, 98 insertions(+), 43 deletions(-) diff --git a/cake/tests/cases/libs/test_manager.test.php b/cake/tests/cases/libs/test_manager.test.php index fed2b1852..1575f7e06 100644 --- a/cake/tests/cases/libs/test_manager.test.php +++ b/cake/tests/cases/libs/test_manager.test.php @@ -20,6 +20,13 @@ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ +class TestTestManager extends TestManager { + + public function setTestSuite($testSuite) { + $this->_testSuite = $testSuite; + } +} + /** * TestManagerTest class * @@ -28,14 +35,37 @@ */ class TestManagerTest extends CakeTestCase { +/** + * Number of times the funcion PHPUnit_Framework_TestSuite::addTestFile() has been called + * + * @var integer + */ + protected $_countFiles = 0; + /** * setUp method * * @return void */ public function setUp() { - $this->TestManager = new TestManager(); - $this->Reporter = new CakeHtmlReporter(); + $this->_countFiles = 0; + $this->TestManager = new TestTestManager(); + $testSuiteStub = $this->getMock('PHPUnit_Framework_TestSuite'); + $testSuiteStub + ->expects($this->any()) + ->method('addTestFile') + ->will($this->returnCallback(array(&$this, '_countIncludedTestFiles'))); + $this->TestManager->setTestSuite($testSuiteStub); + $this->Reporter = $this->getMock('CakeHtmlReporter'); + } + +/** + * Helper method to count the number of times the + * function PHPUnit_Framework_TestSuite::addTestFile() has been called + * @return void + */ + public function _countIncludedTestFiles() { + $this->_countFiles++; } /** @@ -44,14 +74,28 @@ class TestManagerTest extends CakeTestCase { * @return void */ public function testRunAllTests() { - $folder = new Folder(CORE_TEST_CASES); + $folder = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(CORE_TEST_CASES)); $extension = str_replace('.', '\.', $this->TestManager->getExtension('test')); - $out = $folder->findRecursive('.*' . $extension); + $out = new RegexIterator($folder, '#^.+'.$extension.'$#i', RecursiveRegexIterator::GET_MATCH); - $reporter = new CakeHtmlReporter(); - $list = $this->TestManager->runAllTests($reporter, true); + $files = array(); + foreach ($out as $testFile) { + $files[] = $testFile[0]; + } - $this->assertEqual(count($out), count($list)); + $result = $this->TestManager->runAllTests($this->Reporter, true); + + $this->assertEqual(count($files), $this->_countFiles); + $this->assertType('PHPUnit_Framework_TestResult', $result); + } + +/** +* Tests that trying to run an unexistent file throws an exception +* @expectedException InvalidArgumentException +*/ + public function testRunUnexistentCase() { + $file = md5(time()); + $result = $this->TestManager->runTestCase($file, $this->Reporter); } /** @@ -60,14 +104,10 @@ class TestManagerTest extends CakeTestCase { * @return void */ public function testRunTestCase() { - $file = md5(time()); - $result = $this->TestManager->runTestCase($file, $this->Reporter); - $this->assertError('Test case ' . $file . ' cannot be found'); - $this->assertFalse($result); - $file = str_replace(CORE_TEST_CASES, '', __FILE__); $result = $this->TestManager->runTestCase($file, $this->Reporter, true); - $this->assertTrue($result); + $this->assertEqual(1, $this->_countFiles); + $this->assertType('PHPUnit_Framework_TestResult', $result); } /** diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 7b06aab61..b3bdd4ec4 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -58,6 +58,13 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { */ public $pluginTest = false; +/** + * TestSuite container for single or grouped test files + * + * @var PHPUnit_Framework_TestSuiteboolean + */ + protected $_testSuit = null; + /** * Constructor for the TestManager class * @@ -77,29 +84,30 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { /** * Runs all tests in the Application depending on the current appTest setting * - * @param Object $reporter Reporter object for the tests being run. - * @param boolean $testing Are tests supposed to be auto run. Set to true to return testcase list. + * @param PHPUnit_Framework_TestListener $reporter Reporter instance to attach to the test case. * @return mixed */ - public function runAllTests(&$reporter, $testing = false) { + public function runAllTests(&$reporter) { $testCases = $this->_getTestFileList($this->_getTestsPath()); - if ($this->appTest) { - $test = new TestSuite(__('All App Tests', true)); - } else if ($this->pluginTest) { - $test = new TestSuite(sprintf(__('All %s Plugin Tests', true), Inflector::humanize($this->pluginTest))); - } else { - $test = new TestSuite(__('All Core Tests', true)); - } - if ($testing) { - return $testCases; + if ($this->appTest) { + $test = $this->getTestSuite(__('All App Tests', true)); + } else if ($this->pluginTest) { + $test = $this->getTestSuite(sprintf(__('All %s Plugin Tests', true), Inflector::humanize($this->pluginTest))); + } else { + $test = $this->getTestSuite(__('All Core Tests', true)); } foreach ($testCases as $testCase) { $test->addTestFile($testCase); } - return $test->run($reporter); + $result = new PHPUnit_Framework_TestResult; + $result->addListener($reporter); + $reporter->paintHeader(); + $run = $test->run($result); + $reporter->paintResult($result); + return $result; } /** @@ -107,31 +115,24 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * * @param string $testCaseFile Filename of the test to be run. * @param PHPUnit_Framework_TestListener $reporter Reporter instance to attach to the test case. - * @param boolean $testing Set to true if testing, otherwise test case will be run. + * @throws InvalidArgumentException if the supplied $testCaseFile does not exists * @return mixed Result of test case being run. */ - public function runTestCase($testCaseFile, PHPUnit_Framework_TestListener &$reporter, $testing = false) { + public function runTestCase($testCaseFile, PHPUnit_Framework_TestListener &$reporter) { $testCaseFileWithPath = $this->_getTestsPath() . DS . $testCaseFile; if (!file_exists($testCaseFileWithPath)) { - trigger_error(sprintf(__('Test case %s cannot be found', true), $testCaseFile), E_USER_ERROR); - return false; + throw new InvalidArgumentException(sprintf(__('Unable to load test file %s'), $testCaseFile)); } - if ($testing) { - return true; - } - - $testSuite = new PHPUnit_Framework_TestSuite; - $testSuite->setName(sprintf(__('Individual test case: %s', true), $testCaseFile)); + $testSuite = $this->getTestSuite(sprintf(__('Individual test case: %s', true), $testCaseFile)); $testSuite->addTestFile($testCaseFileWithPath); - $result = new PHPUnit_Framework_TestResult; $result->addListener($reporter); $reporter->paintHeader(); $run = $testSuite->run($result); $reporter->paintResult($result); - return $run; + return $result; } /** @@ -300,13 +301,14 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { return $fileList; } - $files = glob($directory . DS . '*'); - $files = $files ? $files : array(); + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)); foreach ($files as $file) { - if (is_dir($file)) { - $fileList = array_merge($fileList, $this->_getRecursiveFileList($file, $fileTestFunction)); - } elseif ($fileTestFunction[0]->$fileTestFunction[1]($file)) { + if (!$file->isFile()) { + continue; + } + $file = $file->getRealPath(); + if ($fileTestFunction[0]->$fileTestFunction[1]($file)) { $fileList[] = $file; } } @@ -387,6 +389,19 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { return $this->_groupExtension; } +/** + * Get the container testSuite instance for this runner or creates a new one + * + * @param string $name The name for the container test suite + * @return PHPUnit_Framework_TestSuite container test suite + */ + protected function getTestSuite($name = '') { + if (!empty($this->_testSuite)) { + return $this->_testSuite; + } + return $this->_testSuite = new PHPUnit_Framework_TestSuite($name); + } + protected function runFailed($message) { } From c23f66e35c753ed5af26677df536060c98229584 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 20:51:58 -0430 Subject: [PATCH 009/230] Removing "extends" from TestManager as it wasn't used anyway. Making some methods static as they were called statically More testing on TestManager --- cake/tests/cases/libs/test_manager.test.php | 31 ++++--- cake/tests/lib/test_manager.php | 90 +++++++++++---------- 2 files changed, 66 insertions(+), 55 deletions(-) diff --git a/cake/tests/cases/libs/test_manager.test.php b/cake/tests/cases/libs/test_manager.test.php index 1575f7e06..4d0206e68 100644 --- a/cake/tests/cases/libs/test_manager.test.php +++ b/cake/tests/cases/libs/test_manager.test.php @@ -50,12 +50,12 @@ class TestManagerTest extends CakeTestCase { public function setUp() { $this->_countFiles = 0; $this->TestManager = new TestTestManager(); - $testSuiteStub = $this->getMock('PHPUnit_Framework_TestSuite'); - $testSuiteStub + $this->testSuiteStub = $this->getMock('PHPUnit_Framework_TestSuite'); + $this->testSuiteStub ->expects($this->any()) ->method('addTestFile') ->will($this->returnCallback(array(&$this, '_countIncludedTestFiles'))); - $this->TestManager->setTestSuite($testSuiteStub); + $this->TestManager->setTestSuite($this->testSuiteStub); $this->Reporter = $this->getMock('CakeHtmlReporter'); } @@ -68,12 +68,7 @@ class TestManagerTest extends CakeTestCase { $this->_countFiles++; } -/** - * testRunAllTests method - * - * @return void - */ - public function testRunAllTests() { + protected function _getAllTestFiles() { $folder = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(CORE_TEST_CASES)); $extension = str_replace('.', '\.', $this->TestManager->getExtension('test')); $out = new RegexIterator($folder, '#^.+'.$extension.'$#i', RecursiveRegexIterator::GET_MATCH); @@ -82,10 +77,19 @@ class TestManagerTest extends CakeTestCase { foreach ($out as $testFile) { $files[] = $testFile[0]; } + return $files; + } +/** + * testRunAllTests method + * + * @return void + */ + public function testRunAllTests() { + $files = $this->_getAllTestFiles(); $result = $this->TestManager->runAllTests($this->Reporter, true); - $this->assertEqual(count($files), $this->_countFiles); + $this->assertEquals(count($files), $this->_countFiles); $this->assertType('PHPUnit_Framework_TestResult', $result); } @@ -106,7 +110,7 @@ class TestManagerTest extends CakeTestCase { public function testRunTestCase() { $file = str_replace(CORE_TEST_CASES, '', __FILE__); $result = $this->TestManager->runTestCase($file, $this->Reporter, true); - $this->assertEqual(1, $this->_countFiles); + $this->assertEquals(1, $this->_countFiles); $this->assertType('PHPUnit_Framework_TestResult', $result); } @@ -124,6 +128,8 @@ class TestManagerTest extends CakeTestCase { * @return void */ public function testAddTestCasesFromDirectory() { + $this->TestManager->addTestCasesFromDirectory($this->testSuiteStub, CORE_TEST_CASES); + $this->assertEquals(count($this->_getAllTestFiles()), $this->_countFiles); } /** @@ -132,6 +138,9 @@ class TestManagerTest extends CakeTestCase { * @return void */ public function testAddTestFile() { + $file = str_replace(CORE_TEST_CASES, '', __FILE__); + $this->TestManager->addTestFile($this->testSuiteStub, $file); + $this->assertEquals(1, $this->_countFiles); } /** diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index b3bdd4ec4..3792347af 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -29,20 +29,20 @@ define('APP_TEST_GROUPS', TESTS . 'groups'); * @package cake * @subpackage cake.cake.tests.lib */ -class TestManager extends PHPUnit_Runner_BaseTestRunner { +class TestManager { /** * Extension suffix for test case files. * * @var string */ - protected $_testExtension = '.test.php'; + protected static $_testExtension = '.test.php'; /** * Extension suffix for group test case files. * * @var string */ - protected $_groupExtension = '.group.php'; + protected static $_groupExtension = '.group.php'; /** * Is this test an AppTest? @@ -171,8 +171,7 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * @static */ public static function addTestCasesFromDirectory(&$groupTest, $directory = '.') { - $manager = new TestManager(); - $testCases = $manager->_getTestFileList($directory); + $testCases = self::_getTestFileList($directory); foreach ($testCases as $testCase) { $groupTest->addTestFile($testCase); } @@ -187,16 +186,14 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * @access public * @static */ - // public static function addTestFile(&$groupTest, $file) { - // $manager = new TestManager(); - // - // if (file_exists($file . $manager->_testExtension)) { - // $file .= $manager->_testExtension; - // } elseif (file_exists($file . $manager->_groupExtension)) { - // $file .= $manager->_groupExtension; - // } - // $groupTest->addTestFile($file); - // } + public static function addTestFile(&$groupTest, $file) { + if (file_exists($file . self::$_testExtension)) { + $file .= self::$_testExtension; + } elseif (file_exists($file . self::$_groupExtension)) { + $file .= self::$_groupExtension; + } + $groupTest->addTestFile($file); + } /** * Returns a list of test cases found in the current valid test case path @@ -204,9 +201,8 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * @access public * @static */ - function &getTestCaseList() { - $manager = new TestManager(); - $return = $manager->_getTestCaseList($manager->_getTestsPath()); + public static function &getTestCaseList() { + $return = self::_getTestCaseList(self::_getTestsPath()); return $return; } @@ -214,9 +210,10 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * Builds the list of test cases from a given directory * * @param string $directory Directory to get test case list from. + * @static */ - protected function &_getTestCaseList($directory = '.') { - $fileList = $this->_getTestFileList($directory); + protected static function &_getTestCaseList($directory = '.') { + $fileList = self::_getTestFileList($directory); $testCases = array(); foreach ($fileList as $testCaseFile) { $testCases[$testCaseFile] = str_replace($directory . DS, '', $testCaseFile); @@ -228,9 +225,10 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * Returns a list of test files from a given directory * * @param string $directory Directory to get test case files from. + * @static */ - protected function &_getTestFileList($directory = '.') { - $return = $this->_getRecursiveFileList($directory, array(&$this, '_isTestCaseFile')); + protected static function &_getTestFileList($directory = '.') { + $return = self::_getRecursiveFileList($directory, 'self::_isTestCaseFile'); return $return; } @@ -240,9 +238,8 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * @access public * @static */ - function &getGroupTestList() { - $manager = new TestManager(); - $return = $manager->_getTestGroupList($manager->_getTestsPath('groups')); + static function &getGroupTestList() { + $return = self::_getTestGroupList(self::_getTestsPath('groups')); return $return; } @@ -250,9 +247,10 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * Returns a list of group test files from a given directory * * @param string $directory The directory to get group test files from. + * @static */ - protected function &_getTestGroupFileList($directory = '.') { - $return = $this->_getRecursiveFileList($directory, array(&$this, '_isTestGroupFile')); + protected static function &_getTestGroupFileList($directory = '.') { + $return = self::_getRecursiveFileList($directory, array(self, '_isTestGroupFile')); return $return; } @@ -260,13 +258,14 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * Returns a list of group test files from a given directory * * @param string $directory The directory to get group tests from. + * @static */ - protected function &_getTestGroupList($directory = '.') { - $fileList = $this->_getTestGroupFileList($directory); + protected static function &_getTestGroupList($directory = '.') { + $fileList = self::_getTestGroupFileList($directory); $groupTests = array(); foreach ($fileList as $groupTestFile) { - $groupTests[$groupTestFile] = str_replace($this->_groupExtension, '', basename($groupTestFile)); + $groupTests[$groupTestFile] = str_replace(self::$_groupExtension, '', basename($groupTestFile)); } sort($groupTests); return $groupTests; @@ -276,8 +275,9 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * Returns a list of class names from a group test file * * @param string $groupTestFile The groupTest file to scan for TestSuite classnames. + * @static */ - protected function &_getGroupTestClassNames($groupTestFile) { + protected static function &_getGroupTestClassNames($groupTestFile) { $file = implode("\n", file($groupTestFile)); preg_match("~lass\s+?(.*)\s+?extends TestSuite~", $file, $matches); if (!empty($matches)) { @@ -294,8 +294,9 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * * @param string $directory The directory to scan for files. * @param mixed $fileTestFunction + * @static */ - protected function &_getRecursiveFileList($directory = '.', $fileTestFunction) { + protected static function &_getRecursiveFileList($directory = '.', $fileTestFunction) { $fileList = array(); if (!is_dir($directory)) { return $fileList; @@ -308,7 +309,8 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { continue; } $file = $file->getRealPath(); - if ($fileTestFunction[0]->$fileTestFunction[1]($file)) { + + if (call_user_func_array($fileTestFunction, array($file))) { $fileList[] = $file; } } @@ -320,9 +322,10 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * * @param string $file * @return boolean Whether $file is a test case. + * @static */ - protected function _isTestCaseFile($file) { - return $this->_hasExpectedExtension($file, $this->_testExtension); + protected static function _isTestCaseFile($file) { + return self::_hasExpectedExtension($file, self::$_testExtension); } /** @@ -330,9 +333,10 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * * @param string $file * @return boolean Whether $file is a group + * @static */ - protected function _isTestGroupFile($file) { - return $this->_hasExpectedExtension($file, $this->_groupExtension); + protected static function _isTestGroupFile($file) { + return static::_hasExpectedExtension($file, static::$_groupExtension); } /** @@ -341,8 +345,9 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * @param string $file * @param string $extension * @return void + * @static */ - protected function _hasExpectedExtension($file, $extension) { + protected static function _hasExpectedExtension($file, $extension) { return $extension == strtolower(substr($file, (0 - strlen($extension)))); } @@ -382,11 +387,11 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { * @param string $type Type of test to get, either 'test' or 'group' * @return string Extension suffix for test. */ - public function getExtension($type = 'test') { + public static function getExtension($type = 'test') { if ($type == 'test' || $type == 'case') { - return $this->_testExtension; + return self::$_testExtension; } - return $this->_groupExtension; + return self::$_groupExtension; } /** @@ -402,9 +407,6 @@ class TestManager extends PHPUnit_Runner_BaseTestRunner { return $this->_testSuite = new PHPUnit_Framework_TestSuite($name); } - protected function runFailed($message) { - - } } ?> \ No newline at end of file From 41683723f7bfa73cb5089be18378ed94cb09ca3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 21:04:18 -0430 Subject: [PATCH 010/230] Making more methods static in TestManager --- cake/tests/lib/test_manager.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 3792347af..c29d0cec7 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -250,7 +250,7 @@ class TestManager { * @static */ protected static function &_getTestGroupFileList($directory = '.') { - $return = self::_getRecursiveFileList($directory, array(self, '_isTestGroupFile')); + $return = self::_getRecursiveFileList($directory, 'self::_isTestGroupFile'); return $return; } @@ -356,17 +356,18 @@ class TestManager { * * @param string $type either 'cases' or 'groups' * @return string The path tests are located on + * @static */ - protected function _getTestsPath($type = 'cases') { - if (!empty($this->appTest)) { + protected static function _getTestsPath($type = 'cases') { + if (!empty(self::$appTest)) { if ($type == 'cases') { $result = APP_TEST_CASES; } else if ($type == 'groups') { $result = APP_TEST_GROUPS; } - } else if (!empty($this->pluginTest)) { - $_pluginBasePath = APP . 'plugins/' . $this->pluginTest . '/tests'; - $pluginPath = App::pluginPath($this->pluginTest); + } else if (!empty(self::$pluginTest)) { + $_pluginBasePath = APP . 'plugins/' . self::$pluginTest . '/tests'; + $pluginPath = App::pluginPath(self::$pluginTest); if (file_exists($pluginPath . DS . 'tests')) { $_pluginBasePath = $pluginPath . DS . 'tests'; } From 856a52a378005bc24fdd6108ec9c2118c4898761 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 23:11:27 -0430 Subject: [PATCH 011/230] Changing runGrouptTest to find for conventional class names. This commit removes the support for loading more than one groupt test class per file --- cake/tests/lib/test_manager.php | 74 ++++++++++++++------------------- 1 file changed, 32 insertions(+), 42 deletions(-) diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index c29d0cec7..193890a81 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -102,12 +102,7 @@ class TestManager { $test->addTestFile($testCase); } - $result = new PHPUnit_Framework_TestResult; - $result->addListener($reporter); - $reporter->paintHeader(); - $run = $test->run($result); - $reporter->paintResult($result); - return $result; + return $test->run($reporter); } /** @@ -118,7 +113,7 @@ class TestManager { * @throws InvalidArgumentException if the supplied $testCaseFile does not exists * @return mixed Result of test case being run. */ - public function runTestCase($testCaseFile, PHPUnit_Framework_TestListener &$reporter) { + public function runTestCase($testCaseFile, PHPUnit_Framework_TestListener $reporter) { $testCaseFileWithPath = $this->_getTestsPath() . DS . $testCaseFile; if (!file_exists($testCaseFileWithPath)) { @@ -127,38 +122,49 @@ class TestManager { $testSuite = $this->getTestSuite(sprintf(__('Individual test case: %s', true), $testCaseFile)); $testSuite->addTestFile($testCaseFileWithPath); - $result = new PHPUnit_Framework_TestResult; - $result->addListener($reporter); - $reporter->paintHeader(); - $run = $testSuite->run($result); - $reporter->paintResult($result); - return $result; + return $this->run($reporter); } /** * Runs a specific group test file * * @param string $groupTestName GroupTest that you want to run. - * @param Object $reporter Reporter instance to use with the group test being run. + * @param PHPUnit_Framework_TestListener $reporter Reporter instance to use with the group test being run. + * @throws InvalidArgumentException if it was not possible to locate the filename for $groupTestName * @return mixed Results of group test being run. */ - public function runGroupTest($groupTestName, &$reporter) { - $filePath = $this->_getTestsPath('groups') . DS . strtolower($groupTestName) . $this->_groupExtension; + public function runGroupTest($groupTestName, $reporter) { + $filePath = $this->_getTestsPath('groups') . DS . strtolower($groupTestName) . $this->getExtension('group'); if (!file_exists($filePath)) { - trigger_error(sprintf(__('Group test %s cannot be found at %s', true), $groupTestName, $filePath), E_USER_ERROR); + throw new InvalidArgumentException(sprintf(__('Group test %s cannot be found at %s', true), $groupTestName, $filePath)); } require_once $filePath; - $test = new TestSuite(sprintf(__('%s group test', true), $groupTestName)); - foreach ($this->_getGroupTestClassNames($filePath) as $groupTest) { - $testCase = new $groupTest(); - $test->addTestCase($testCase); - if (isset($testCase->label)) { - $test->_label = $testCase->label; - } + $suite = $this->getTestSuite(sprintf(__('%s group test', true), $groupTestName)); + $groupClassName = Inflector::classify($groupTestName) . 'GroupTest'; + $group = new $groupClassName(); + $suite->addTestSuite($group); + if (isset($group->label)) { + $suite->setName($group->label); } - return $test->run($reporter); + + return $this->run($reporter); + } + +/** + * Runs the main testSuite and attaches to it a reporter + * + * @param PHPUnit_Framework_TestListener $reporter Reporter instance to use with the group test being run. + * @return mixed Results of group test being run. + */ + protected function run($reporter) { + $result = new PHPUnit_Framework_TestResult; + $result->addListener($reporter); + $reporter->paintHeader(); + $this->getTestSuite()->run($result); + $reporter->paintResult($result); + return $result; } /** @@ -238,7 +244,7 @@ class TestManager { * @access public * @static */ - static function &getGroupTestList() { + public static function &getGroupTestList() { $return = self::_getTestGroupList(self::_getTestsPath('groups')); return $return; } @@ -271,22 +277,6 @@ class TestManager { return $groupTests; } -/** - * Returns a list of class names from a group test file - * - * @param string $groupTestFile The groupTest file to scan for TestSuite classnames. - * @static - */ - protected static function &_getGroupTestClassNames($groupTestFile) { - $file = implode("\n", file($groupTestFile)); - preg_match("~lass\s+?(.*)\s+?extends TestSuite~", $file, $matches); - if (!empty($matches)) { - unset($matches[0]); - return $matches; - } - $matches = array(); - return $matches; - } /** * Gets a recursive list of files from a given directory and matches then against From fd4a82d6e909ebddf2b3b3f97a4af18ceb78d6c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 23:56:40 -0430 Subject: [PATCH 012/230] Adding test for TestManager::runGroupTest() --- cake/tests/cases/libs/test_manager.test.php | 22 ++++++++++++++++++--- cake/tests/lib/test_manager.php | 2 +- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/cake/tests/cases/libs/test_manager.test.php b/cake/tests/cases/libs/test_manager.test.php index 4d0206e68..6ef14596e 100644 --- a/cake/tests/cases/libs/test_manager.test.php +++ b/cake/tests/cases/libs/test_manager.test.php @@ -51,10 +51,17 @@ class TestManagerTest extends CakeTestCase { $this->_countFiles = 0; $this->TestManager = new TestTestManager(); $this->testSuiteStub = $this->getMock('PHPUnit_Framework_TestSuite'); + $this->testSuiteStub ->expects($this->any()) ->method('addTestFile') ->will($this->returnCallback(array(&$this, '_countIncludedTestFiles'))); + + $this->testSuiteStub + ->expects($this->any()) + ->method('addTestSuite') + ->will($this->returnCallback(array(&$this, '_countIncludedTestFiles'))); + $this->TestManager->setTestSuite($this->testSuiteStub); $this->Reporter = $this->getMock('CakeHtmlReporter'); } @@ -68,9 +75,9 @@ class TestManagerTest extends CakeTestCase { $this->_countFiles++; } - protected function _getAllTestFiles() { - $folder = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(CORE_TEST_CASES)); - $extension = str_replace('.', '\.', $this->TestManager->getExtension('test')); + protected function _getAllTestFiles($directory = CORE_TEST_CASES, $type = 'test') { + $folder = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)); + $extension = str_replace('.', '\.', $this->TestManager->getExtension($type)); $out = new RegexIterator($folder, '#^.+'.$extension.'$#i', RecursiveRegexIterator::GET_MATCH); $files = array(); @@ -120,6 +127,15 @@ class TestManagerTest extends CakeTestCase { * @return void */ public function testRunGroupTest() { + $groups = $this->_getAllTestFiles(CORE_TEST_GROUPS, 'group'); + if (empty($groups)) { + $this->markTestSkipped('No test group files'); + return; + } + list($groupFile,) = explode('.', array_pop($groups), 2); + $result = $this->TestManager->runGroupTest(basename($groupFile), $this->Reporter); + $this->assertGreaterThan(0, $this->_countFiles); + $this->assertType('PHPUnit_Framework_TestResult', $result); } /** diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 193890a81..a9c14bade 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -102,7 +102,7 @@ class TestManager { $test->addTestFile($testCase); } - return $test->run($reporter); + return $this->run($reporter); } /** From b53d21ff523a0021f7dc78c6cc451b9f33f4c259 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 4 May 2010 23:58:17 -0430 Subject: [PATCH 013/230] Fixing a group test case to show how to create one, and to make pass TestManager test case --- cake/tests/cases/libs/view/helpers/xml.test.php | 2 +- cake/tests/groups/xml.group.php | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cake/tests/cases/libs/view/helpers/xml.test.php b/cake/tests/cases/libs/view/helpers/xml.test.php index 2e3e06d63..111018dd1 100644 --- a/cake/tests/cases/libs/view/helpers/xml.test.php +++ b/cake/tests/cases/libs/view/helpers/xml.test.php @@ -28,7 +28,7 @@ App::import('Helper', 'Xml'); * @package cake * @subpackage cake.tests.cases.libs.view.helpers */ -class TestXml extends Object { +class TestXmlHelper extends Object { /** * content property diff --git a/cake/tests/groups/xml.group.php b/cake/tests/groups/xml.group.php index 5025822b7..1038437e0 100644 --- a/cake/tests/groups/xml.group.php +++ b/cake/tests/groups/xml.group.php @@ -26,7 +26,7 @@ * @package cake * @subpackage cake.tests.groups */ -class XmlGroupTest extends TestSuite { +class XmlGroupTest extends PHPUnit_Framework_TestSuite { /** * label property @@ -37,12 +37,12 @@ class XmlGroupTest extends TestSuite { public $label = 'Xml based classes (Xml, XmlHelper and RssHelper)'; /** - * XmlGroupTest method + * __construct method * * @access public * @return void */ - function XmlGroupTest() { + function __construct() { TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'xml'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS .'rss'); TestManager::addTestFile($this, CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS .'xml'); From bed87b87c69533afab09e7e52cf28bfa79e85335 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Wed, 5 May 2010 22:42:56 -0430 Subject: [PATCH 014/230] Removing code from CakeTestCase around the method "testAction" which was a bad way of testing controllers, often making it more difficult. This also removes class contamination in newly created test cases --- cake/tests/cases/libs/cake_test_case.test.php | 194 +------------- cake/tests/lib/cake_test_case.php | 240 +----------------- .../tests/lib/reporter/cake_html_reporter.php | 8 +- 3 files changed, 17 insertions(+), 425 deletions(-) diff --git a/cake/tests/cases/libs/cake_test_case.test.php b/cake/tests/cases/libs/cake_test_case.test.php index 82fc9bda8..58961ae5f 100644 --- a/cake/tests/cases/libs/cake_test_case.test.php +++ b/cake/tests/cases/libs/cake_test_case.test.php @@ -27,11 +27,11 @@ if (!class_exists('AppController')) { define('APP_CONTROLLER_EXISTS', true); } -Mock::generate('CakeHtmlReporter'); -Mock::generate('CakeTestCase', 'CakeDispatcherMockTestCase'); +//Mock::generate('CakeHtmlReporter'); +//Mock::generate('CakeTestCase', 'CakeDispatcherMockTestCase'); -SimpleTest::ignore('SubjectCakeTestCase'); -SimpleTest::ignore('CakeDispatcherMockTestCase'); +//SimpleTest::ignore('SubjectCakeTestCase'); +//SimpleTest::ignore('CakeDispatcherMockTestCase'); /** * SubjectCakeTestCase @@ -41,18 +41,6 @@ SimpleTest::ignore('CakeDispatcherMockTestCase'); */ class SubjectCakeTestCase extends CakeTestCase { -/** - * Feed a Mocked Reporter to the subject case - * prevents its pass/fails from affecting the real test - * - * @param string $reporter - * @access public - * @return void - */ - function setReporter(&$reporter) { - $this->_reporter = &$reporter; - } - /** * testDummy method * @@ -78,10 +66,9 @@ class CakeTestCaseTest extends CakeTestCase { */ function setUp() { $this->_debug = Configure::read('debug'); - $this->Case =& new SubjectCakeTestCase(); - $reporter =& new MockCakeHtmlReporter(); - $this->Case->setReporter($reporter); - $this->Reporter = $reporter; + $this->Case = new SubjectCakeTestCase(); + $this->Result = new PHPUnit_Framework_TestResult; + $this->Reporter = $this->getMock('CakeHtmlReporter'); } /** @@ -93,6 +80,7 @@ class CakeTestCaseTest extends CakeTestCase { function tearDown() { Configure::write('debug', $this->_debug); unset($this->Case); + unset($this->Result); unset($this->Reporter); } @@ -113,8 +101,7 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function testAssertGoodTags() { - $this->Reporter->expectAtLeastOnce('paintPass'); - $this->Reporter->expectNever('paintFail'); + $this->Reporter->expects($this->atLeastOnce())->method('paintPass'); $input = '

    Text

    '; $pattern = array( @@ -122,7 +109,7 @@ class CakeTestCaseTest extends CakeTestCase { 'Text', '/p', ); - $this->assertTrue($this->Case->assertTags($input, $pattern)); + $this->Case->assertTags($input, $pattern); $input = 'My link'; $pattern = array( @@ -250,8 +237,8 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function testBadAssertTags() { - $this->Reporter->expectAtLeastOnce('paintFail'); - $this->Reporter->expectNever('paintPass'); +// $this->Reporter->expectAtLeastOnce('paintFail'); +// $this->Reporter->expectNever('paintPass'); $input = 'My link'; $pattern = array( @@ -331,137 +318,6 @@ class CakeTestCaseTest extends CakeTestCase { $this->assertEqual(array_slice($result, -2), array('endCase', 'end')); } -/** - * TestTestAction - * - * @access public - * @return void - */ - function testTestAction() { - App::build(array( - 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS), - 'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS), - 'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS), - 'controllers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS) - ), true); - - $result = $this->Case->testAction('/tests_apps/index', array('return' => 'view')); - $this->assertPattern('/This is the TestsAppsController index view/', $result); - - $result = $this->Case->testAction('/tests_apps/index', array('return' => 'contents')); - $this->assertPattern('/This is the TestsAppsController index view/', $result); - $this->assertPattern('/assertPattern('/<\/html>/', $result); - - $result = $this->Case->testAction('/tests_apps/some_method', array('return' => 'result')); - $this->assertEqual($result, 5); - - $result = $this->Case->testAction('/tests_apps/set_action', array('return' => 'vars')); - $this->assertEqual($result, array('var' => 'string')); - - $db =& ConnectionManager::getDataSource('test_suite'); - $fixture =& new PostFixture(); - $fixture->create($db); - - $result = $this->Case->testAction('/tests_apps_posts/add', array('return' => 'vars')); - $this->assertTrue(array_key_exists('posts', $result)); - $this->assertEqual(count($result['posts']), 1); - - $result = $this->Case->testAction('/tests_apps_posts/url_var/var1:value1/var2:val2', array( - 'return' => 'vars', - 'method' => 'get', - )); - $this->assertTrue(isset($result['params']['url']['url'])); - $this->assertEqual(array_keys($result['params']['named']), array('var1', 'var2')); - - $result = $this->Case->testAction('/tests_apps_posts/url_var/gogo/val2', array( - 'return' => 'vars', - 'method' => 'get', - )); - $this->assertEqual($result['params']['pass'], array('gogo', 'val2')); - - - $result = $this->Case->testAction('/tests_apps_posts/url_var', array( - 'return' => 'vars', - 'method' => 'get', - 'data' => array( - 'red' => 'health', - 'blue' => 'mana' - ) - )); - $this->assertTrue(isset($result['params']['url']['red'])); - $this->assertTrue(isset($result['params']['url']['blue'])); - $this->assertTrue(isset($result['params']['url']['url'])); - - $result = $this->Case->testAction('/tests_apps_posts/post_var', array( - 'return' => 'vars', - 'method' => 'post', - 'data' => array( - 'name' => 'is jonas', - 'pork' => 'and beans', - ) - )); - $this->assertEqual(array_keys($result['data']), array('name', 'pork')); - $fixture->drop($db); - - $db =& ConnectionManager::getDataSource('test_suite'); - $_backPrefix = $db->config['prefix']; - $db->config['prefix'] = 'cake_testaction_test_suite_'; - - $config = $db->config; - $config['prefix'] = 'cake_testcase_test_'; - - ConnectionManager::create('cake_test_case', $config); - $db2 =& ConnectionManager::getDataSource('cake_test_case'); - - $fixture =& new PostFixture($db2); - $fixture->create($db2); - $fixture->insert($db2); - - $result = $this->Case->testAction('/tests_apps_posts/fixtured', array( - 'return' => 'vars', - 'fixturize' => true, - 'connection' => 'cake_test_case', - )); - $this->assertTrue(isset($result['posts'])); - $this->assertEqual(count($result['posts']), 3); - $tables = $db2->listSources(); - $this->assertFalse(in_array('cake_testaction_test_suite_posts', $tables)); - - $fixture->drop($db2); - - $db =& ConnectionManager::getDataSource('test_suite'); - - //test that drop tables behaves as exepected with testAction - $db =& ConnectionManager::getDataSource('test_suite'); - $_backPrefix = $db->config['prefix']; - $db->config['prefix'] = 'cake_testaction_test_suite_'; - - $config = $db->config; - $config['prefix'] = 'cake_testcase_test_'; - - ConnectionManager::create('cake_test_case', $config); - $db =& ConnectionManager::getDataSource('cake_test_case'); - $fixture =& new PostFixture($db); - $fixture->create($db); - $fixture->insert($db); - - $this->Case->dropTables = false; - $result = $this->Case->testAction('/tests_apps_posts/fixtured', array( - 'return' => 'vars', - 'fixturize' => true, - 'connection' => 'cake_test_case', - )); - - $tables = $db->listSources(); - $this->assertTrue(in_array('cake_testaction_test_suite_posts', $tables)); - - $fixture->drop($db); - $db =& ConnectionManager::getDataSource('test_suite'); - $db->config['prefix'] = $_backPrefix; - $fixture->drop($db); - } - /** * testSkipIf * @@ -471,31 +327,5 @@ class CakeTestCaseTest extends CakeTestCase { $this->assertTrue($this->Case->skipIf(true)); $this->assertFalse($this->Case->skipIf(false)); } - -/** - * testTestDispatcher - * - * @access public - * @return void - */ - function testTestDispatcher() { - App::build(array( - 'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS), - 'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS), - 'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS), - 'controllers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS) - ), true); - - $Dispatcher =& new CakeTestDispatcher(); - $Case =& new CakeDispatcherMockTestCase(); - - $Case->expectOnce('startController'); - $Case->expectOnce('endController'); - - $Dispatcher->testCase($Case); - $this->assertTrue(isset($Dispatcher->testCase)); - - $return = $Dispatcher->dispatch('/tests_apps/index', array('autoRender' => 0, 'return' => 1, 'requested' => 1)); - } } ?> \ No newline at end of file diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index 50aebfe76..66111c648 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -17,64 +17,9 @@ * @since CakePHP(tm) v 1.2.0.4667 * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -if (!class_exists('dispatcher')) { - require CAKE . 'dispatcher.php'; -} + require_once CAKE_TESTS_LIB . 'cake_test_model.php'; require_once CAKE_TESTS_LIB . 'cake_test_fixture.php'; -App::import('Vendor', 'simpletest' . DS . 'unit_tester'); - -/** - * CakeTestDispatcher - * - * @package cake - * @subpackage cake.cake.tests.lib - */ -class CakeTestDispatcher extends Dispatcher { - -/** - * controller property - * - * @var Controller - * @access public - */ - public $controller; - public $testCase; - -/** - * testCase method - * - * @param CakeTestCase $testCase - * @return void - */ - public function testCase(&$testCase) { - $this->testCase =& $testCase; - } - -/** - * invoke method - * - * @param Controller $controller - * @param array $params - * @param boolean $missingAction - * @return Controller - */ - protected function _invoke(&$controller, $params, $missingAction = false) { - $this->controller =& $controller; - - if (isset($this->testCase) && method_exists($this->testCase, 'startController')) { - $this->testCase->startController($this->controller, $params); - } - - $result = parent::_invoke($this->controller, $params, $missingAction); - - if (isset($this->testCase) && method_exists($this->testCase, 'endController')) { - $this->testCase->endController($this->controller, $params); - } - - return $result; - } -} /** * CakeTestCase class @@ -198,189 +143,6 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { return $shouldSkip; } -/** - * Callback issued when a controller's action is about to be invoked through testAction(). - * - * @param Controller $controller Controller that's about to be invoked. - * @param array $params Additional parameters as sent by testAction(). - * @return void - */ - public function startController(&$controller, $params = array()) { - if (isset($params['fixturize']) && ((is_array($params['fixturize']) && !empty($params['fixturize'])) || $params['fixturize'] === true)) { - if (!isset($this->db)) { - $this->_initDb(); - } - - if ($controller->uses === false) { - $list = array($controller->modelClass); - } else { - $list = is_array($controller->uses) ? $controller->uses : array($controller->uses); - } - - $models = array(); - ClassRegistry::config(array('ds' => $params['connection'])); - - foreach ($list as $name) { - if ((is_array($params['fixturize']) && in_array($name, $params['fixturize'])) || $params['fixturize'] === true) { - if (class_exists($name) || App::import('Model', $name)) { - $object =& ClassRegistry::init($name); - //switch back to specified datasource. - $object->setDataSource($params['connection']); - $db =& ConnectionManager::getDataSource($object->useDbConfig); - $db->cacheSources = false; - - $models[$object->alias] = array( - 'table' => $object->table, - 'model' => $object->alias, - 'key' => strtolower($name), - ); - } - } - } - ClassRegistry::config(array('ds' => 'test_suite')); - - if (!empty($models) && isset($this->db)) { - $this->_actionFixtures = array(); - - foreach ($models as $model) { - $fixture =& new CakeTestFixture($this->db); - - $fixture->name = $model['model'] . 'Test'; - $fixture->table = $model['table']; - $fixture->import = array('model' => $model['model'], 'records' => true); - $fixture->init(); - - $fixture->create($this->db); - $fixture->insert($this->db); - $this->_actionFixtures[] =& $fixture; - } - - foreach ($models as $model) { - $object =& ClassRegistry::getObject($model['key']); - if ($object !== false) { - $object->setDataSource('test_suite'); - $object->cacheSources = false; - } - } - } - } - } - -/** - * Callback issued when a controller's action has been invoked through testAction(). - * - * @param Controller $controller Controller that has been invoked. - * @param array $params Additional parameters as sent by testAction(). - * @return void - */ - public function endController(&$controller, $params = array()) { - if (isset($this->db) && isset($this->_actionFixtures) && !empty($this->_actionFixtures) && $this->dropTables) { - foreach ($this->_actionFixtures as $fixture) { - $fixture->drop($this->db); - } - } - } - -/** - * Executes a Cake URL, and can get (depending on the $params['return'] value): - * - * Params: - * - 'return' has several possible values: - * 1. 'result': Whatever the action returns (and also specifies $this->params['requested'] for controller) - * 2. 'view': The rendered view, without the layout - * 3. 'contents': The rendered view, within the layout. - * 4. 'vars': the view vars - * - * - 'fixturize' - Set to true if you want to copy model data from 'connection' to the test_suite connection - * - 'data' - The data you want to insert into $this->data in the controller. - * - 'connection' - Which connection to use in conjunction with fixturize (defaults to 'default') - * - 'method' - What type of HTTP method to simulate (defaults to post) - * - * @param string $url Cake URL to execute (e.g: /articles/view/455) - * @param mixed $params Parameters (see above), or simply a string of what to return - * @return mixed Whatever is returned depending of requested result - */ - public function runTestAction($url, $params = array()) { - $default = array( - 'return' => 'result', - 'fixturize' => false, - 'data' => array(), - 'method' => 'post', - 'connection' => 'default' - ); - - if (is_string($params)) { - $params = array('return' => $params); - } - $params = array_merge($default, $params); - - $toSave = array( - 'case' => null, - 'group' => null, - 'app' => null, - 'output' => null, - 'show' => null, - 'plugin' => null - ); - $this->__savedGetData = (empty($this->__savedGetData)) - ? array_intersect_key($_GET, $toSave) - : $this->__savedGetData; - - $data = (!empty($params['data'])) ? $params['data'] : array(); - - if (strtolower($params['method']) == 'get') { - $_GET = array_merge($this->__savedGetData, $data); - $_POST = array(); - } else { - $_POST = array('data' => $data); - $_GET = $this->__savedGetData; - } - - $return = $params['return']; - $params = array_diff_key($params, array('data' => null, 'method' => null, 'return' => null)); - - $dispatcher =& new CakeTestDispatcher(); - $dispatcher->testCase($this); - - if ($return != 'result') { - if ($return != 'contents') { - $params['layout'] = false; - } - - ob_start(); - @$dispatcher->dispatch($url, $params); - $result = ob_get_clean(); - - if ($return == 'vars') { - $view =& ClassRegistry::getObject('view'); - $viewVars = $view->getVars(); - - $result = array(); - - foreach ($viewVars as $var) { - $result[$var] = $view->getVar($var); - } - - if (!empty($view->pageTitle)) { - $result = array_merge($result, array('title' => $view->pageTitle)); - } - } - } else { - $params['return'] = 1; - $params['bare'] = 1; - $params['requested'] = 1; - - $result = @$dispatcher->dispatch($url, $params); - } - - if (isset($this->_actionFixtures)) { - unset($this->_actionFixtures); - } - ClassRegistry::flush(); - - return $result; - } - /** * Announces the start of a test. * diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index e59269562..159541005 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -318,9 +318,9 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes '] in ['. $exception->getFile() . ' line ' . $exception->getLine() . ']'; echo "
    " . $this->_htmlEntities($message) . "
    \n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - echo "
    " . implode(" -> ", $breadcrumb) . "
    \n"; + //$breadcrumb = $this->getTestList(); + //array_shift($breadcrumb); + //echo "
    " . implode(" -> ", $breadcrumb) . "
    \n"; echo "
  • \n"; } @@ -386,7 +386,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * @param float $time */ public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { - + $this->paintException($e); } /** From ef142b1659f1a6a1646c89339223854dafa61ce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Fri, 7 May 2010 18:06:17 -0430 Subject: [PATCH 015/230] Adding the class CakeFixtureManager to delegate the task of creating and droping the fixtures Tests and docs still pending --- cake/tests/lib/cake_fixture_manager.php | 179 ++++++++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 cake/tests/lib/cake_fixture_manager.php diff --git a/cake/tests/lib/cake_fixture_manager.php b/cake/tests/lib/cake_fixture_manager.php new file mode 100644 index 000000000..b50b879c8 --- /dev/null +++ b/cake/tests/lib/cake_fixture_manager.php @@ -0,0 +1,179 @@ +fixtures)) { + return; + } + if (!self::$_initialized) { + self::_initDb(); + if (!empty(self::$_db)) { + $test->db = self::$_db; + } + } + if (!is_array($test->fixtures)) { + $test->fixtures = array_map('trim', explode(',', $test->fixtures)); + } + if (isset($test->fixtures)) { + self::_loadFixtures($test->fixtures); + } + } + + protected static function _initDb() { + $testDbAvailable = in_array('test', array_keys(ConnectionManager::enumConnectionObjects())); + + $_prefix = null; + + if ($testDbAvailable) { + // Try for test DB + @$db = ConnectionManager::getDataSource('test'); + $testDbAvailable = $db->isConnected(); + } + + // Try for default DB + if (!$testDbAvailable) { + $db = ConnectionManager::getDataSource('default'); + $_prefix = $db->config['prefix']; + $db->config['prefix'] = 'test_suite_'; + } + + ConnectionManager::create('test_suite', $db->config); + $db->config['prefix'] = $_prefix; + + // Get db connection + self::$_db = ConnectionManager::getDataSource('test_suite'); + self::$_db->cacheSources = false; + + ClassRegistry::config(array('ds' => 'test_suite')); + } + + protected static function _loadFixtures($fixtures) { + foreach ($fixtures as $index => $fixture) { + $fixtureFile = null; + $fixtureIndex = $fixture; + if (isset(self::$_loaded[$fixture])) { + continue; + } + if (strpos($fixture, 'core.') === 0) { + $fixture = substr($fixture, strlen('core.')); + foreach (App::core('cake') as $key => $path) { + $fixturePaths[] = $path . 'tests' . DS . 'fixtures'; + } + } elseif (strpos($fixture, 'app.') === 0) { + $fixture = substr($fixture, strlen('app.')); + $fixturePaths = array( + TESTS . 'fixtures', + VENDORS . 'tests' . DS . 'fixtures' + ); + } elseif (strpos($fixture, 'plugin.') === 0) { + $parts = explode('.', $fixture, 3); + $pluginName = $parts[1]; + $fixture = $parts[2]; + $fixturePaths = array( + App::pluginPath($pluginName) . 'tests' . DS . 'fixtures', + TESTS . 'fixtures', + VENDORS . 'tests' . DS . 'fixtures' + ); + } else { + $fixturePaths = array( + TESTS . 'fixtures', + VENDORS . 'tests' . DS . 'fixtures', + TEST_CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'tests' . DS . 'fixtures' + ); + } + + foreach ($fixturePaths as $path) { + if (is_readable($path . DS . $fixture . '_fixture.php')) { + $fixtureFile = $path . DS . $fixture . '_fixture.php'; + break; + } + } + + if (isset($fixtureFile)) { + require_once($fixtureFile); + $fixtureClass = Inflector::camelize($fixture) . 'Fixture'; + self::$_loaded[$fixtureIndex] = new $fixtureClass(self::$_db); + self::$_fixtureMap[$fixtureClass] = self::$_loaded[$fixtureIndex]; + } + } + } + + protected static function setupTable($fixture, $db = null, $drop = true) { + if (!empty($fixture->created)) { + return; + } + if (!$db) { + $db = self::$_db; + } + + $cacheSources = $db->cacheSources; + $db->cacheSources = false; + $db->cacheSources = $cacheSources; + $sources = $db->listSources(); + $table = $db->config['prefix'] . $fixture->table; + + if ($drop && in_array($table, $sources)) { + $fixture->drop($db); + $fixture->create($db); + $fixture->created = true; + } elseif (!in_array($table, $sources)) { + $fixture->create($db); + $fixture->created = true; + } + } + + public static function load(CakeTestCase $test) { + if (empty($test->fixtures)) { + return; + } + $fixtures = $test->fixtures; + if (empty($fixtures) || $test->autoFixtures == false) { + return; + } + + foreach ($fixtures as $f) { + if (!empty(self::$_loaded[$f])) { + $fixture = self::$_loaded[$f]; + self::setupTable($fixture, $test->db, $test->dropTables); + $fixture->insert($test->db); + } + } + } + + public static function unload(CakeTestCase $test) { + if (empty($test->fixtures)) { + return; + } + $fixtures = $test->fixtures; + if (empty($fixtures)) { + return; + } + foreach ($fixtures as $f) { + if (isset(self::$_loaded[$f])) { + $fixture = self::$_loaded[$f]; + if (!empty($fixture->created)) { + $fixture->truncate($test->db); + } + } + } + } + + public static function loadSingle($name, $db = null) { + $name .= 'Fixture'; + if (isset(self::$_fixtureMap[$name])) { + if (!$db) { + $db = self::$_db; + } + $fixture = self::$_fixtureMap[$name]; + $fixture->truncate($db); + $fixture->insert($db); + } else { + throw new UnexpectedValueException(sprintf(__('Referenced fixture class %s not found'), $name)); + } + } +} \ No newline at end of file From 7124e6db3ede91c74c7ab493d73ce08f69c3e641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Fri, 7 May 2010 18:07:02 -0430 Subject: [PATCH 016/230] Refactoring CakeTestCase to remove fixture specific code and use the new class CakeFixtureManager. It lacks support to auto-drop tables after test case end, but it is already usable for testing --- cake/tests/lib/cake_test_case.php | 203 +++--------------------------- 1 file changed, 18 insertions(+), 185 deletions(-) diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index 50aebfe76..a1da4aead 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -20,6 +20,7 @@ if (!class_exists('dispatcher')) { require CAKE . 'dispatcher.php'; } +require_once CAKE_TESTS_LIB . 'cake_fixture_manager.php'; require_once CAKE_TESTS_LIB . 'cake_test_model.php'; require_once CAKE_TESTS_LIB . 'cake_test_fixture.php'; App::import('Vendor', 'simpletest' . DS . 'unit_tester'); @@ -133,6 +134,12 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { */ private $__savedGetData = array(); + public function __construct($name = null, array $data = array(), $dataName = '') { + parent::__construct($name, $data, $dataName); + if (!empty($this->fixtures)) { + CakeFixtureManager::fixturize($this); + } + } /** * Called when a test case (group of methods) is about to start (to be overriden when needed.) * @@ -387,56 +394,11 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { * @param string $method Test method just started. * @return void */ - public function before($method) { - parent::before($method); - - if (isset($this->fixtures) && (!is_array($this->fixtures) || empty($this->fixtures))) { - unset($this->fixtures); - } - - // Set up DB connection - if (isset($this->fixtures) && strtolower($method) == 'start') { - $this->_initDb(); - $this->_loadFixtures(); - } - - // Create records - if (isset($this->_fixtures) && isset($this->db) && !in_array(strtolower($method), array('start', 'end')) && $this->__truncated && $this->autoFixtures == true) { - foreach ($this->_fixtures as $fixture) { - $inserts = $fixture->insert($this->db); - } - } - - if (!in_array(strtolower($method), $this->methods)) { - $this->startTest($method); - } - } - -/** - * Runs as first test to create tables. - * - * @return void - */ - public function start() { - if (isset($this->_fixtures) && isset($this->db)) { - Configure::write('Cache.disable', true); - $cacheSources = $this->db->cacheSources; - $this->db->cacheSources = false; - $sources = $this->db->listSources(); - $this->db->cacheSources = $cacheSources; - - if (!$this->dropTables) { - return; - } - foreach ($this->_fixtures as $fixture) { - $table = $this->db->config['prefix'] . $fixture->table; - if (in_array($table, $sources)) { - $fixture->drop($this->db); - $fixture->create($this->db); - } elseif (!in_array($table, $sources)) { - $fixture->create($this->db); - } - } + protected function assertPreConditions() { + parent::assertPreConditions(); + CakeFixtureManager::load($this); + if (!in_array(strtolower($this->getName()), $this->methods)) { + $this->startTest($this->getName()); } } @@ -467,24 +429,12 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { * @param string $method Test method just finished. * @return void */ - public function after($method) { - $isTestMethod = !in_array(strtolower($method), array('start', 'end')); - - if (isset($this->_fixtures) && isset($this->db) && $isTestMethod) { - foreach ($this->_fixtures as $fixture) { - $fixture->truncate($this->db); - } - $this->__truncated = true; - } else { - $this->__truncated = false; + protected function assertPostConditions() { + parent::assertPostConditions(); + CakeFixtureManager::unload($this); + if (!in_array(strtolower($this->getName()), $this->methods)) { + $this->endTest($this->getName()); } - - if (!in_array(strtolower($method), $this->methods)) { - $this->endTest($method); - } - $this->_should_skip = false; - - parent::after($method); } /** @@ -501,14 +451,6 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { ); } -/** - * Accessor for checking whether or not fixtures were truncated - * - * @return void - */ - public function getTruncated() { - return $this->__truncated; - } /** * Chooses which fixtures to load for a given test * @@ -521,14 +463,7 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { function loadFixtures() { $args = func_get_args(); foreach ($args as $class) { - if (isset($this->_fixtureClassMap[$class])) { - $fixture = $this->_fixtures[$this->_fixtureClassMap[$class]]; - - $fixture->truncate($this->db); - $fixture->insert($this->db); - } else { - trigger_error(sprintf(__('Referenced fixture class %s not found', true), $class), E_USER_WARNING); - } + CakeFixtureManager::loadSingle($class); } } @@ -690,108 +625,6 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { return $this->assertTrue(true, '%s'); } -/** - * Initialize DB connection. - * - * @return void - */ - protected function _initDb() { - $testDbAvailable = in_array('test', array_keys(ConnectionManager::enumConnectionObjects())); - - $_prefix = null; - - if ($testDbAvailable) { - // Try for test DB - restore_error_handler(); - @$db = ConnectionManager::getDataSource('test'); - set_error_handler('simpleTestErrorHandler'); - $testDbAvailable = $db->isConnected(); - } - - // Try for default DB - if (!$testDbAvailable) { - $db = ConnectionManager::getDataSource('default'); - $_prefix = $db->config['prefix']; - $db->config['prefix'] = 'test_suite_'; - } - - ConnectionManager::create('test_suite', $db->config); - $db->config['prefix'] = $_prefix; - - // Get db connection - $this->db = ConnectionManager::getDataSource('test_suite'); - $this->db->cacheSources = false; - - ClassRegistry::config(array('ds' => 'test_suite')); - } - -/** - * Load fixtures specified in public $fixtures. - * - * @return void - */ - protected function _loadFixtures() { - if (!isset($this->fixtures) || empty($this->fixtures)) { - return; - } - - if (!is_array($this->fixtures)) { - $this->fixtures = array_map('trim', explode(',', $this->fixtures)); - } - - $this->_fixtures = array(); - - foreach ($this->fixtures as $index => $fixture) { - $fixtureFile = null; - - if (strpos($fixture, 'core.') === 0) { - $fixture = substr($fixture, strlen('core.')); - foreach (App::core('cake') as $key => $path) { - $fixturePaths[] = $path . 'tests' . DS . 'fixtures'; - } - } elseif (strpos($fixture, 'app.') === 0) { - $fixture = substr($fixture, strlen('app.')); - $fixturePaths = array( - TESTS . 'fixtures', - VENDORS . 'tests' . DS . 'fixtures' - ); - } elseif (strpos($fixture, 'plugin.') === 0) { - $parts = explode('.', $fixture, 3); - $pluginName = $parts[1]; - $fixture = $parts[2]; - $fixturePaths = array( - App::pluginPath($pluginName) . 'tests' . DS . 'fixtures', - TESTS . 'fixtures', - VENDORS . 'tests' . DS . 'fixtures' - ); - } else { - $fixturePaths = array( - TESTS . 'fixtures', - VENDORS . 'tests' . DS . 'fixtures', - TEST_CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'tests' . DS . 'fixtures' - ); - } - - foreach ($fixturePaths as $path) { - if (is_readable($path . DS . $fixture . '_fixture.php')) { - $fixtureFile = $path . DS . $fixture . '_fixture.php'; - break; - } - } - - if (isset($fixtureFile)) { - require_once($fixtureFile); - $fixtureClass = Inflector::camelize($fixture) . 'Fixture'; - $this->_fixtures[$this->fixtures[$index]] =& new $fixtureClass($this->db); - $this->_fixtureClassMap[Inflector::camelize($fixture)] = $this->fixtures[$index]; - } - } - - if (empty($this->_fixtures)) { - unset($this->_fixtures); - } - } - /** * Generates all permutation of an array $items and returns them in a new array. * From 82a1bd6f80bf6f1a5388179931b675d6b8d39e86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 01:19:45 -0430 Subject: [PATCH 017/230] Cleaning up CakeTestCase and adding some tests for it --- cake/tests/cases/libs/cake_test_case.test.php | 263 +++--------------- cake/tests/fixtures/assert_tags_test_case.php | 122 ++++++++ cake/tests/lib/cake_test_case.php | 37 +-- 3 files changed, 163 insertions(+), 259 deletions(-) create mode 100644 cake/tests/fixtures/assert_tags_test_case.php diff --git a/cake/tests/cases/libs/cake_test_case.test.php b/cake/tests/cases/libs/cake_test_case.test.php index 58961ae5f..81b913cfa 100644 --- a/cake/tests/cases/libs/cake_test_case.test.php +++ b/cake/tests/cases/libs/cake_test_case.test.php @@ -19,7 +19,6 @@ * @since CakePHP v 1.2.0.4487 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ -App::import('Core', 'CakeTestCase'); if (!class_exists('AppController')) { require_once LIBS . 'controller' . DS . 'app_controller.php'; @@ -27,29 +26,6 @@ if (!class_exists('AppController')) { define('APP_CONTROLLER_EXISTS', true); } -//Mock::generate('CakeHtmlReporter'); -//Mock::generate('CakeTestCase', 'CakeDispatcherMockTestCase'); - -//SimpleTest::ignore('SubjectCakeTestCase'); -//SimpleTest::ignore('CakeDispatcherMockTestCase'); - -/** - * SubjectCakeTestCase - * - * @package cake - * @subpackage cake.tests.cases.libs - */ -class SubjectCakeTestCase extends CakeTestCase { - -/** - * testDummy method - * - * @return void - */ - public function testDummy() { - } -} - /** * CakeTestCaseTest * @@ -58,6 +34,11 @@ class SubjectCakeTestCase extends CakeTestCase { */ class CakeTestCaseTest extends CakeTestCase { + public static function setUpBeforeClass() { + require_once TEST_CAKE_CORE_INCLUDE_PATH . DS . 'tests' . DS . 'fixtures' . DS . 'assert_tags_test_case.php'; + require_once TEST_CAKE_CORE_INCLUDE_PATH . DS . 'tests' . DS . 'fixtures' . DS . 'fixturized_test_case.php'; + } + /** * setUp * @@ -66,8 +47,6 @@ class CakeTestCaseTest extends CakeTestCase { */ function setUp() { $this->_debug = Configure::read('debug'); - $this->Case = new SubjectCakeTestCase(); - $this->Result = new PHPUnit_Framework_TestResult; $this->Reporter = $this->getMock('CakeHtmlReporter'); } @@ -84,100 +63,18 @@ class CakeTestCaseTest extends CakeTestCase { unset($this->Reporter); } -/** - * endTest - * - * @access public - * @return void - */ - function endTest() { - App::build(); - } - /** * testAssertGoodTags * * @access public * @return void - */ - function testAssertGoodTags() { - $this->Reporter->expects($this->atLeastOnce())->method('paintPass'); - - $input = '

    Text

    '; - $pattern = array( - 'Case->assertTags($input, $pattern); - - $input = 'My link'; - $pattern = array( - 'a' => array('href' => '/test.html', 'class' => 'active'), - 'My link', - '/a' - ); - $this->assertTrue($this->Case->assertTags($input, $pattern)); - - $pattern = array( - 'a' => array('class' => 'active', 'href' => '/test.html'), - 'My link', - '/a' - ); - $this->assertTrue($this->Case->assertTags($input, $pattern), 'Attributes in wrong order. %s'); - - $input = "\tMy link"; - $pattern = array( - 'a' => array('id' => 'primary', 'href' => '/test.html', 'class' => 'active'), - 'assertTrue($this->Case->assertTags($input, $pattern), 'Whitespace consumption %s'); - - $input = '

    My link

    '; - $pattern = array( - 'p' => array('class' => 'info'), - 'a' => array('class' => 'active', 'href' => '/test.html' ), - 'strong' => array('onClick' => 'alert(\'hey\');'), - 'My link', - '/strong', - '/a', - '/p' - ); - $this->assertTrue($this->Case->assertTags($input, $pattern)); - } - -/** - * test that assertTags knows how to handle correct quoting. - * - * @return void */ function testAssertTagsQuotes() { - $input = 'My link'; - $pattern = array( - 'a' => array('href' => '/test.html', 'class' => 'active'), - 'My link', - '/a' - ); - $this->assertTrue($this->Case->assertTags($input, $pattern), 'Double quoted attributes %s'); - - $input = "My link"; - $pattern = array( - 'a' => array('href' => '/test.html', 'class' => 'active'), - 'My link', - '/a' - ); - $this->assertTrue($this->Case->assertTags($input, $pattern), 'Single quoted attributes %s'); - - $input = "My link"; - $pattern = array( - 'a' => array('href' => 'preg:/.*\.html/', 'class' => 'active'), - 'My link', - '/a' - ); - $this->assertTrue($this->Case->assertTags($input, $pattern), 'Single quoted attributes %s'); + $test = new AssertTagsTestCase('testAssertTagsQuotes'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertTrue($result->wasSuccessful()); + $this->assertEquals(0, $result->failureCount()); } /** @@ -187,109 +84,31 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function testNumericValuesInExpectationForAssertTags() { - $value = 220985; - - $input = '

    ' . $value . '

    '; - $pattern = array( - 'assertTrue($this->Case->assertTags($input, $pattern)); - - $input = '

    ' . $value . '

    ' . $value . '

    '; - $pattern = array( - 'assertTrue($this->Case->assertTags($input, $pattern)); - - $input = '

    ' . $value . '

    ' . $value . '

    '; - $pattern = array( - ' array('id' => $value), - 'assertTrue($this->Case->assertTags($input, $pattern)); + $test = new AssertTagsTestCase('testNumericValuesInExpectationForAssertTags'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertTrue($result->wasSuccessful()); + $this->assertEquals(0, $result->failureCount()); } - /** +/** * testBadAssertTags * * @access public * @return void */ function testBadAssertTags() { -// $this->Reporter->expectAtLeastOnce('paintFail'); -// $this->Reporter->expectNever('paintPass'); + $test = new AssertTagsTestCase('testBadAssertTags'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertFalse($result->wasSuccessful()); + $this->assertEquals(1, $result->failureCount()); - $input = 'My link'; - $pattern = array( - 'a' => array('hRef' => '/test.html', 'clAss' => 'active'), - 'My link', - '/a' - ); - $this->assertFalse($this->Case->assertTags($input, $pattern)); - - $input = 'My link'; - $pattern = array( - ' array('href' => '/test.html', 'class' => 'active'), - 'My link', - '/a' - ); - $this->assertFalse($this->Case->assertTags($input, $pattern)); - } - -/** - * testBefore - * - * @access public - * @return void - */ - function testBefore() { - $this->Case->before('testDummy'); - $this->assertFalse(isset($this->Case->db)); - - $this->Case->fixtures = array('core.post'); - $this->Case->before('start'); - $this->assertTrue(isset($this->Case->db)); - $this->assertTrue(isset($this->Case->_fixtures['core.post'])); - $this->assertTrue(is_a($this->Case->_fixtures['core.post'], 'CakeTestFixture')); - $this->assertEqual($this->Case->_fixtureClassMap['Post'], 'core.post'); - } - -/** - * testAfter - * - * @access public - * @return void - */ - function testAfter() { - $this->Case->after('testDummy'); - $this->assertFalse($this->Case->getTruncated()); - - $this->Case->fixtures = array('core.post'); - $this->Case->before('start'); - $this->Case->start(); - $this->Case->after('testDummy'); - $this->assertTrue($this->Case->getTruncated()); + $test = new AssertTagsTestCase('testBadAssertTags2'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + $this->assertFalse($result->wasSuccessful()); + $this->assertEquals(1, $result->failureCount()); } /** @@ -299,23 +118,14 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function testLoadFixtures() { - $this->Case->fixtures = array('core.post'); - $this->Case->autoFixtures = false; - $this->Case->before('start'); - $this->expectError(); - $this->Case->loadFixtures('Wrong!'); - $this->Case->end(); - } - -/** - * testGetTests Method - * - * @return void - */ - public function testGetTests() { - $result = $this->Case->getTests(); - $this->assertEqual(array_slice($result, 0, 2), array('start', 'startCase')); - $this->assertEqual(array_slice($result, -2), array('endCase', 'end')); + $test = new FixturizedTestCase('testFixturePresent'); + $result = $test->run(); + //$this->Case->fixtures = array('core.post'); + //$this->Case->autoFixtures = false; + //$this->Case->before('start'); + //$this->expectError(); + //$this->Case->loadFixtures('Wrong!'); + //$this->Case->end(); } /** @@ -324,8 +134,9 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function testSkipIf() { - $this->assertTrue($this->Case->skipIf(true)); - $this->assertFalse($this->Case->skipIf(false)); + //$this->Case = new SubjectCakeTestCase; + //$this->assertTrue($this->Case->skipIf(true)); + //$this->assertFalse($this->Case->skipIf(false)); } } ?> \ No newline at end of file diff --git a/cake/tests/fixtures/assert_tags_test_case.php b/cake/tests/fixtures/assert_tags_test_case.php new file mode 100644 index 000000000..9ec62c035 --- /dev/null +++ b/cake/tests/fixtures/assert_tags_test_case.php @@ -0,0 +1,122 @@ +My link'; + $pattern = array( + 'a' => array('href' => '/test.html', 'class' => 'active'), + 'My link', + '/a' + ); + $this->assertTags($input, $pattern); + + $input = "My link"; + $pattern = array( + 'a' => array('href' => '/test.html', 'class' => 'active'), + 'My link', + '/a' + ); + $this->assertTags($input, $pattern); + + $input = "My link"; + $pattern = array( + 'a' => array('href' => 'preg:/.*\.html/', 'class' => 'active'), + 'My link', + '/a' + ); + $this->assertTags($input, $pattern); + } + +/** + * testNumericValuesInExpectationForAssertTags + * + * @access public + * @return void + */ + function testNumericValuesInExpectationForAssertTags() { + $value = 220985; + + $input = '

    ' . $value . '

    '; + $pattern = array( + 'assertTags($input, $pattern); + + $input = '

    ' . $value . '

    ' . $value . '

    '; + $pattern = array( + 'assertTags($input, $pattern); + + $input = '

    ' . $value . '

    ' . $value . '

    '; + $pattern = array( + ' array('id' => $value), + 'assertTags($input, $pattern); + } + + /** + * testBadAssertTags + * + * @access public + * @return void + */ + function testBadAssertTags() { + $input = 'My link'; + $pattern = array( + 'a' => array('hRef' => '/test.html', 'clAss' => 'active'), + 'My link2', + '/a' + ); + $this->assertTags($input, $pattern); + } + +/** + * testBadAssertTags + * + * @access public + * @return void + */ + function testBadAssertTags2() { + $input = 'My link'; + $pattern = array( + ' array('href' => '/test.html', 'class' => 'active'), + 'My link', + '/a' + ); + $this->assertTags($input, $pattern); + } +} \ No newline at end of file diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index 652db1cdf..b242a184a 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -55,22 +55,6 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { */ public $dropTables = true; -/** - * Maps fixture class names to fixture identifiers as included in CakeTestCase::$fixtures - * - * @var array - * @access protected - */ - protected $_fixtureClassMap = array(); - -/** - * truncated property - * - * @var boolean - * @access private - */ - private $__truncated = true; - /** * savedGetData property * @@ -121,21 +105,6 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { public function endTest($method) { } -/** - * Overrides SimpleTestCase::assert to enable calling of skipIf() from within tests - * - * @param Expectation $expectation - * @param mixed $compare - * @param string $message - * @return boolean|null - */ - public function assert(&$expectation, $compare, $message = '%s') { - if ($this->_should_skip) { - return; - } - return parent::assert($expectation, $compare, $message); - } - /** * Overrides SimpleTestCase::skipIf to provide a boolean return value * @@ -376,7 +345,7 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { } } if (!$matches) { - $this->assert(new TrueExpectation(), false, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description)); + $this->assertTrue(false, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description)); if ($fullDebug) { debug($string, true); debug($regex, true); @@ -384,7 +353,9 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { return false; } } - return $this->assertTrue(true, '%s'); + + $this->assertTrue(true, '%s'); + return true; } /** From e7ff0bdf661f2b2ebee386bc235a699b756d3e8a Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 11:42:04 -0400 Subject: [PATCH 018/230] Adding missing parameters to assertEqual() wrapper. Adding assertNotEqual() wrapper. Adding expectError() but it doesn't work because of Debugger's error handler being set. Fixing fatal error where getDescription would not be defined. --- cake/tests/lib/cake_test_case.php | 15 +++++++++++++-- cake/tests/lib/reporter/cake_html_reporter.php | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index b242a184a..153668c10 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -386,8 +386,12 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { } } - protected function assertEqual($a, $b) { - return $this->assertEquals($a, $b); + protected function assertEqual($a, $b, $message = '') { + return $this->assertEquals($a, $b, $message); + } + + protected function assertNotEqual($a, $b, $message = '') { + return $this->assertNotEquals($a, $b, $message); } protected function assertPattern($pattern, $string, $message = '') { @@ -404,6 +408,13 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { protected function assertNoErrors() { } + + protected function expectError($expected = false, $message = '') { + if (!$expected) { + $expected = 'Exception'; + } + $this->setExpectedException($expected, $message); + } protected function expectException($name = null) { $this->setExpectedException($name); diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 159541005..8380adf9e 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -257,7 +257,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo "
  • \n"; echo "Failed"; - echo "
    " . $this->_htmlEntities($message->getDescription()) . "
    \n"; + echo "
    " . $this->_htmlEntities($message->toString()) . "
    \n"; echo "
    " . sprintf(__('File: %s'), $context['file']) . "
    \n"; echo "
    " . sprintf(__('Method: %s'), $realContext['function']) . "
    \n"; echo "
    " . sprintf(__('Line: %s'), $context['line']) . "
    \n"; From 933378223b0731530298ae5dceab02a0a8220a5e Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 16:17:20 -0400 Subject: [PATCH 019/230] Updating CakeLog tests to use @expectedException annotation. --- cake/tests/cases/libs/cake_log.test.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cake/tests/cases/libs/cake_log.test.php b/cake/tests/cases/libs/cake_log.test.php index 2ed6ce66f..98a4f82fe 100644 --- a/cake/tests/cases/libs/cake_log.test.php +++ b/cake/tests/cases/libs/cake_log.test.php @@ -69,20 +69,20 @@ class CakeLogTest extends CakeTestCase { /** * test all the errors from failed logger imports * + * @expectedException Exception * @return void */ function testImportingLoggerFailure() { - $this->expectException(); CakeLog::config('fail', array()); } /** * test that loggers have to implement the correct interface. * + * @expectedException Exception * @return void */ function testNotImplementingInterface() { - $this->expectException(); CakeLog::config('fail', array('engine' => 'stdClass')); } From 507c3b2d94e7c1d7175cb206e0caf53f090147ec Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 16:18:45 -0400 Subject: [PATCH 020/230] Adding the CakePHP testing classes to the coverage ignore filter for PHPUnit. Starting to refactor how coverage is generated, to use more features of PHPUnit. --- cake/tests/lib/cake_fixture_manager.php | 2 ++ cake/tests/lib/cake_test_case.php | 2 ++ cake/tests/lib/cake_test_fixture.php | 2 ++ cake/tests/lib/cake_test_suite_dispatcher.php | 8 +++++--- cake/tests/lib/reporter/cake_base_reporter.php | 2 ++ cake/tests/lib/reporter/cake_html_reporter.php | 4 +++- cake/tests/lib/test_manager.php | 16 +++++++++++----- 7 files changed, 27 insertions(+), 9 deletions(-) diff --git a/cake/tests/lib/cake_fixture_manager.php b/cake/tests/lib/cake_fixture_manager.php index b50b879c8..b6f75f27c 100644 --- a/cake/tests/lib/cake_fixture_manager.php +++ b/cake/tests/lib/cake_fixture_manager.php @@ -1,5 +1,7 @@ params['codeCoverage'] = true; - require_once CAKE_TESTS_LIB . 'code_coverage_manager.php'; $this->_checkXdebug(); + require_once CAKE_TESTS_LIB . 'code_coverage_manager.php'; } $this->params['baseUrl'] = $this->_baseUrl; $this->params['baseDir'] = $this->_baseDir; @@ -254,7 +256,7 @@ class CakeTestSuiteDispatcher { if ('all' == $this->params['group']) { $this->Manager->runAllTests($Reporter); } else { - $this->Manager->runGroupTest(ucfirst($this->params['group']), $Reporter); + $this->Manager->runGroupTest(ucfirst($this->params['group']), $Reporter, $this->params['codeCoverage']); } } @@ -268,7 +270,7 @@ class CakeTestSuiteDispatcher { if ($this->params['codeCoverage']) { CodeCoverageManager::init($this->params['case'], $Reporter); } - $this->Manager->runTestCase($this->params['case'], $Reporter); + $this->Manager->runTestCase($this->params['case'], $Reporter, $this->params['codeCoverage']); } } ?> \ No newline at end of file diff --git a/cake/tests/lib/reporter/cake_base_reporter.php b/cake/tests/lib/reporter/cake_base_reporter.php index c0b5653f9..d1455462c 100644 --- a/cake/tests/lib/reporter/cake_base_reporter.php +++ b/cake/tests/lib/reporter/cake_base_reporter.php @@ -18,6 +18,8 @@ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT'); + /** * CakeBaseReporter contains common reporting features used in the CakePHP Test suite * diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 8380adf9e..68d6dbd09 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -19,6 +19,8 @@ */ include_once dirname(__FILE__) . DS . 'cake_base_reporter.php'; +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT'); + /** * CakeHtmlReporter Reports Results of TestSuites and Test Cases * in an HTML format / context. @@ -178,7 +180,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes $this->params['codeCoverage'] && class_exists('CodeCoverageManager') ) { - CodeCoverageManager::report(); + //CodeCoverageManager::report(); } $this->paintDocumentEnd(); } diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index a9c14bade..07bb09993 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -22,6 +22,8 @@ define('CORE_TEST_GROUPS', TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'groups' define('APP_TEST_CASES', TESTS . 'cases'); define('APP_TEST_GROUPS', TESTS . 'groups'); +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT'); + /** * TestManager is the base class that handles loading and initiating the running * of TestCase and TestSuite classes that the user has selected. @@ -113,7 +115,7 @@ class TestManager { * @throws InvalidArgumentException if the supplied $testCaseFile does not exists * @return mixed Result of test case being run. */ - public function runTestCase($testCaseFile, PHPUnit_Framework_TestListener $reporter) { + public function runTestCase($testCaseFile, PHPUnit_Framework_TestListener $reporter, $codeCoverage = false) { $testCaseFileWithPath = $this->_getTestsPath() . DS . $testCaseFile; if (!file_exists($testCaseFileWithPath)) { @@ -122,7 +124,7 @@ class TestManager { $testSuite = $this->getTestSuite(sprintf(__('Individual test case: %s', true), $testCaseFile)); $testSuite->addTestFile($testCaseFileWithPath); - return $this->run($reporter); + return $this->run($reporter, $codeCoverage); } /** @@ -133,7 +135,7 @@ class TestManager { * @throws InvalidArgumentException if it was not possible to locate the filename for $groupTestName * @return mixed Results of group test being run. */ - public function runGroupTest($groupTestName, $reporter) { + public function runGroupTest($groupTestName, $reporter, $codeCoverage = false) { $filePath = $this->_getTestsPath('groups') . DS . strtolower($groupTestName) . $this->getExtension('group'); if (!file_exists($filePath)) { @@ -149,7 +151,7 @@ class TestManager { $suite->setName($group->label); } - return $this->run($reporter); + return $this->run($reporter, $codeCoverage); } /** @@ -158,12 +160,16 @@ class TestManager { * @param PHPUnit_Framework_TestListener $reporter Reporter instance to use with the group test being run. * @return mixed Results of group test being run. */ - protected function run($reporter) { + protected function run($reporter, $codeCoverage = false) { $result = new PHPUnit_Framework_TestResult; + $result->collectCodeCoverageInformation($codeCoverage); $result->addListener($reporter); $reporter->paintHeader(); $this->getTestSuite()->run($result); $reporter->paintResult($result); + // echo '
    ';
    +		// var_dump($result->getCodeCoverageInformation());
    +		// echo '
    '; return $result; } From acb9733d0e0227753f9b688e74c4709c2d0e1094 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 15:52:11 -0430 Subject: [PATCH 021/230] Convertint CakeFixtureManager into a non-static class to be able to replace it with custom implementations and to test it more easily --- cake/tests/lib/cake_fixture_manager.php | 77 ++++++++++++++----------- 1 file changed, 44 insertions(+), 33 deletions(-) diff --git a/cake/tests/lib/cake_fixture_manager.php b/cake/tests/lib/cake_fixture_manager.php index b50b879c8..238931a62 100644 --- a/cake/tests/lib/cake_fixture_manager.php +++ b/cake/tests/lib/cake_fixture_manager.php @@ -1,30 +1,32 @@ fixtures)) { + public function fixturize(CakeTestCase $test) { + if (empty($test->fixtures) || !empty($this->_processed[get_class($test)])) { + $test->db = $this->_db; return; } - if (!self::$_initialized) { - self::_initDb(); - if (!empty(self::$_db)) { - $test->db = self::$_db; - } - } + $this->_initDb(); + $test->db = $this->_db; if (!is_array($test->fixtures)) { $test->fixtures = array_map('trim', explode(',', $test->fixtures)); } if (isset($test->fixtures)) { - self::_loadFixtures($test->fixtures); + $this->_loadFixtures($test->fixtures); } + + $this->_processed[get_class($test)] = true; } - protected static function _initDb() { + protected function _initDb() { + if ($this->_initialized) { + return; + } $testDbAvailable = in_array('test', array_keys(ConnectionManager::enumConnectionObjects())); $_prefix = null; @@ -46,17 +48,18 @@ class CakeFixtureManager { $db->config['prefix'] = $_prefix; // Get db connection - self::$_db = ConnectionManager::getDataSource('test_suite'); - self::$_db->cacheSources = false; + $this->_db = ConnectionManager::getDataSource('test_suite'); + $this->_db->cacheSources = false; ClassRegistry::config(array('ds' => 'test_suite')); + $this->_initialized = true; } - protected static function _loadFixtures($fixtures) { + protected function _loadFixtures($fixtures) { foreach ($fixtures as $index => $fixture) { $fixtureFile = null; $fixtureIndex = $fixture; - if (isset(self::$_loaded[$fixture])) { + if (isset($this->_loaded[$fixture])) { continue; } if (strpos($fixture, 'core.') === 0) { @@ -97,18 +100,18 @@ class CakeFixtureManager { if (isset($fixtureFile)) { require_once($fixtureFile); $fixtureClass = Inflector::camelize($fixture) . 'Fixture'; - self::$_loaded[$fixtureIndex] = new $fixtureClass(self::$_db); - self::$_fixtureMap[$fixtureClass] = self::$_loaded[$fixtureIndex]; + $this->_loaded[$fixtureIndex] = new $fixtureClass($this->_db); + $this->_fixtureMap[$fixtureClass] = $this->_loaded[$fixtureIndex]; } } } - protected static function setupTable($fixture, $db = null, $drop = true) { + protected function _setupTable($fixture, $db = null, $drop = true) { if (!empty($fixture->created)) { return; } if (!$db) { - $db = self::$_db; + $db = $this->_db; } $cacheSources = $db->cacheSources; @@ -127,7 +130,7 @@ class CakeFixtureManager { } } - public static function load(CakeTestCase $test) { + public function load(CakeTestCase $test) { if (empty($test->fixtures)) { return; } @@ -137,15 +140,15 @@ class CakeFixtureManager { } foreach ($fixtures as $f) { - if (!empty(self::$_loaded[$f])) { - $fixture = self::$_loaded[$f]; - self::setupTable($fixture, $test->db, $test->dropTables); + if (!empty($this->_loaded[$f])) { + $fixture = $this->_loaded[$f]; + $this->_setupTable($fixture, $test->db, $test->dropTables); $fixture->insert($test->db); } } } - public static function unload(CakeTestCase $test) { + public function unload(CakeTestCase $test) { if (empty($test->fixtures)) { return; } @@ -154,8 +157,8 @@ class CakeFixtureManager { return; } foreach ($fixtures as $f) { - if (isset(self::$_loaded[$f])) { - $fixture = self::$_loaded[$f]; + if (isset($this->_loaded[$f])) { + $fixture = $this->_loaded[$f]; if (!empty($fixture->created)) { $fixture->truncate($test->db); } @@ -163,17 +166,25 @@ class CakeFixtureManager { } } - public static function loadSingle($name, $db = null) { + public function loadSingle($name, $db = null) { $name .= 'Fixture'; - if (isset(self::$_fixtureMap[$name])) { + if (isset($this->_fixtureMap[$name])) { if (!$db) { - $db = self::$_db; + $db = $this->_db; } - $fixture = self::$_fixtureMap[$name]; + $fixture = $this->_fixtureMap[$name]; $fixture->truncate($db); $fixture->insert($db); } else { throw new UnexpectedValueException(sprintf(__('Referenced fixture class %s not found'), $name)); } } + + public function shutDown() { + foreach ($this->_loaded as $fixture) { + if (!empty($fixture->created)) { + $fixture->drop($this->_db); + } + } + } } \ No newline at end of file From ec9c8b4d49f1e675f66bdd4ae57c32ee26212fdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 15:53:29 -0430 Subject: [PATCH 022/230] Adding the new class CakeTestSuite to setup some utility stuff like fixtures outside of CakeTestCase --- cake/tests/lib/cake_test_suite.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 cake/tests/lib/cake_test_suite.php diff --git a/cake/tests/lib/cake_test_suite.php b/cake/tests/lib/cake_test_suite.php new file mode 100644 index 000000000..c83612509 --- /dev/null +++ b/cake/tests/lib/cake_test_suite.php @@ -0,0 +1,29 @@ +_fixtureManager = $manager; + } + + protected function setUp() { + parent::setUp(); + if (!$this->_fixtureManager) { + return; + } + $classes = array(); + foreach ($this->getIterator() as $test) { + $this->_fixtureManager->fixturize($test); + } + $this->sharedFixture = $this->_fixtureManager; + } + + protected function tearDown() { + parent::tearDown(); + $this->_fixtureManager->shutDown(); + $this->_fixtureManager = null; + $this->sharedFixture = null; + } +} \ No newline at end of file From 5d041c58b7d781acf85969686ac373e9e4b10e5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 15:55:16 -0430 Subject: [PATCH 023/230] Using the CakeTesSuite in TestManager and calling accordingly the load and unload of fixtures using the variable $sharedFixture --- cake/tests/lib/cake_test_case.php | 21 ++++++++++++--------- cake/tests/lib/test_manager.php | 22 +++++++++++++++++++--- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index b242a184a..27ec7a586 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -63,12 +63,6 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { */ private $__savedGetData = array(); - public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct($name, $data, $dataName); - if (!empty($this->fixtures)) { - CakeFixtureManager::fixturize($this); - } - } /** * Called when a test case (group of methods) is about to start (to be overriden when needed.) * @@ -127,7 +121,9 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { */ protected function assertPreConditions() { parent::assertPreConditions(); - CakeFixtureManager::load($this); + if (!empty($this->sharedFixture)) { + $this->sharedFixture->load($this); + } if (!in_array(strtolower($this->getName()), $this->methods)) { $this->startTest($this->getName()); } @@ -162,7 +158,9 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { */ protected function assertPostConditions() { parent::assertPostConditions(); - CakeFixtureManager::unload($this); + if (!empty($this->sharedFixture)) { + $this->sharedFixture->unload($this); + } if (!in_array(strtolower($this->getName()), $this->methods)) { $this->endTest($this->getName()); } @@ -192,9 +190,14 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { * @see CakeTestCase::$autoFixtures */ function loadFixtures() { + if (empty($this->sharedFixture)) { + throw new Exception(__('No fixture manager to load the test fixture')); + } $args = func_get_args(); foreach ($args as $class) { - CakeFixtureManager::loadSingle($class); + if (!empty($this->sharedFixture)) { + $this->sharedFixture->unload($this); + } } } diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index a9c14bade..8bf9f0706 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -22,6 +22,7 @@ define('CORE_TEST_GROUPS', TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'groups' define('APP_TEST_CASES', TESTS . 'cases'); define('APP_TEST_GROUPS', TESTS . 'groups'); +require_once CAKE_TESTS_LIB . 'cake_test_suite.php'; /** * TestManager is the base class that handles loading and initiating the running * of TestCase and TestSuite classes that the user has selected. @@ -61,10 +62,17 @@ class TestManager { /** * TestSuite container for single or grouped test files * - * @var PHPUnit_Framework_TestSuiteboolean + * @var PHPUnit_Framework_TestSuite */ protected $_testSuit = null; +/** + * Object instance responsible for managing the test fixtures + * + * @var CakeFixtureManager + */ + protected $_fixtureManager = null; + /** * Constructor for the TestManager class * @@ -162,7 +170,9 @@ class TestManager { $result = new PHPUnit_Framework_TestResult; $result->addListener($reporter); $reporter->paintHeader(); - $this->getTestSuite()->run($result); + $testSuite = $this->getTestSuite(); + $testSuite->setFixtureManager($this->getFixtureManager()); + $testSuite->run($result); $reporter->paintResult($result); return $result; } @@ -395,9 +405,15 @@ class TestManager { if (!empty($this->_testSuite)) { return $this->_testSuite; } - return $this->_testSuite = new PHPUnit_Framework_TestSuite($name); + return $this->_testSuite = new CakeTestSuite($name); } + protected function getFixtureManager() { + if (!empty($this->_fixtureManager)) { + return $this->_fixtureManager; + } + return $this->_fixtureManager = new CakeFixtureManager; + } } ?> \ No newline at end of file From 2b5cd26fc6faf3022a5180d6b0c7a35486983045 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 15:56:21 -0430 Subject: [PATCH 024/230] Adding tests for CakeTestCase fixtures --- cake/tests/cases/libs/cake_test_case.test.php | 14 ++++++++------ cake/tests/fixtures/fixturized_test_case.php | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) create mode 100644 cake/tests/fixtures/fixturized_test_case.php diff --git a/cake/tests/cases/libs/cake_test_case.test.php b/cake/tests/cases/libs/cake_test_case.test.php index 81b913cfa..93cc04239 100644 --- a/cake/tests/cases/libs/cake_test_case.test.php +++ b/cake/tests/cases/libs/cake_test_case.test.php @@ -119,13 +119,15 @@ class CakeTestCaseTest extends CakeTestCase { */ function testLoadFixtures() { $test = new FixturizedTestCase('testFixturePresent'); + $manager = $this->getMock('CakeFixtureManager'); + $manager->fixturize($test); + $test->sharedFixture = $manager; + $manager->expects($this->once())->method('load'); + $manager->expects($this->once())->method('unload'); $result = $test->run(); - //$this->Case->fixtures = array('core.post'); - //$this->Case->autoFixtures = false; - //$this->Case->before('start'); - //$this->expectError(); - //$this->Case->loadFixtures('Wrong!'); - //$this->Case->end(); + $this->assertEquals(0, $result->errorCount()); + $this->assertTrue($result->wasSuccessful()); + $this->assertEquals(0, $result->failureCount()); } /** diff --git a/cake/tests/fixtures/fixturized_test_case.php b/cake/tests/fixtures/fixturized_test_case.php new file mode 100644 index 000000000..8cdb0a1f2 --- /dev/null +++ b/cake/tests/fixtures/fixturized_test_case.php @@ -0,0 +1,18 @@ +assertType('CakeFixtureManager', $this->sharedFixture); + //debug($this->sharedFixture); + } + +} \ No newline at end of file From 4d3a6e8ca6745270132c59d1d317edbe59e396d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 16:14:22 -0430 Subject: [PATCH 025/230] Fixing and testing for CakeTestCase::loadFixtures() --- cake/tests/cases/libs/cake_test_case.test.php | 17 +++++++++++++++++ cake/tests/fixtures/fixturized_test_case.php | 9 +++++---- cake/tests/lib/cake_test_case.php | 4 +--- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/cake/tests/cases/libs/cake_test_case.test.php b/cake/tests/cases/libs/cake_test_case.test.php index 93cc04239..27ae9bb6e 100644 --- a/cake/tests/cases/libs/cake_test_case.test.php +++ b/cake/tests/cases/libs/cake_test_case.test.php @@ -130,6 +130,23 @@ class CakeTestCaseTest extends CakeTestCase { $this->assertEquals(0, $result->failureCount()); } +/** + * testLoadFixturesOnDemand + * + * @access public + * @return void + */ + function testLoadFixturesOnDemand() { + $test = new FixturizedTestCase('testFixtureLoadOnDemand'); + $test->autoFixtures = false; + $manager = $this->getMock('CakeFixtureManager'); + $manager->fixturize($test); + $test->sharedFixture = $manager; + $manager->expects($this->once())->method('loadSingle'); + $result = $test->run(); + $this->assertEquals(0, $result->errorCount()); + } + /** * testSkipIf * diff --git a/cake/tests/fixtures/fixturized_test_case.php b/cake/tests/fixtures/fixturized_test_case.php index 8cdb0a1f2..25611a695 100644 --- a/cake/tests/fixtures/fixturized_test_case.php +++ b/cake/tests/fixtures/fixturized_test_case.php @@ -6,13 +6,14 @@ * @subpackage cake.tests.fixtures */ class FixturizedTestCase extends CakeTestCase { - - public $name = 'FixturizedTestCase'; + public $fixtures = array('core.category'); public function testFixturePresent() { $this->assertType('CakeFixtureManager', $this->sharedFixture); - //debug($this->sharedFixture); } - + + public function testFixtureLoadOnDemand() { + $this->loadFixtures('Category'); + } } \ No newline at end of file diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index 27ec7a586..deb345ead 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -195,9 +195,7 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { } $args = func_get_args(); foreach ($args as $class) { - if (!empty($this->sharedFixture)) { - $this->sharedFixture->unload($this); - } + $this->sharedFixture->loadSingle($class); } } From fb09adca68dc21ca0aa01dadad1875b8ef511d0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 16:36:11 -0430 Subject: [PATCH 026/230] Adding tests for skipIf --- cake/tests/cases/libs/cake_test_case.test.php | 12 ++++--- cake/tests/fixtures/assert_tags_test_case.php | 3 ++ cake/tests/fixtures/fixturized_test_case.php | 35 +++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/cake/tests/cases/libs/cake_test_case.test.php b/cake/tests/cases/libs/cake_test_case.test.php index 27ae9bb6e..c03b14c2d 100644 --- a/cake/tests/cases/libs/cake_test_case.test.php +++ b/cake/tests/cases/libs/cake_test_case.test.php @@ -4,7 +4,7 @@ * * Test Case for CakeTestCase class * - * PHP versions 4 and 5 + * PHP version 5 * * CakePHP : Rapid Development Framework (http://cakephp.org) * Copyright 2006-2010, Cake Software Foundation, Inc. @@ -153,9 +153,13 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function testSkipIf() { - //$this->Case = new SubjectCakeTestCase; - //$this->assertTrue($this->Case->skipIf(true)); - //$this->assertFalse($this->Case->skipIf(false)); + $test = new FixturizedTestCase('testSkipIfTrue'); + $result = $test->run(); + $this->assertEquals(1, $result->skippedCount()); + + $test = new FixturizedTestCase('testSkipIfFalse'); + $result = $test->run(); + $this->assertEquals(0, $result->skippedCount()); } } ?> \ No newline at end of file diff --git a/cake/tests/fixtures/assert_tags_test_case.php b/cake/tests/fixtures/assert_tags_test_case.php index 9ec62c035..7062ab8ca 100644 --- a/cake/tests/fixtures/assert_tags_test_case.php +++ b/cake/tests/fixtures/assert_tags_test_case.php @@ -1,4 +1,7 @@ assertType('CakeFixtureManager', $this->sharedFixture); } +/** + * test that it is possible to load fixtures on demand + * + * @return void + */ public function testFixtureLoadOnDemand() { $this->loadFixtures('Category'); } + +/** + * test that a test is marked as skipped using skipIf and its first parameter evaluates to true + * + * @return void + */ + public function testSkipIfTrue() { + $this->skipIf(true); + } + +/** + * test that a test is not marked as skipped using skipIf and its first parameter evaluates to false + * + * @return void + */ + public function testSkipIfFalse() { + $this->skipIf(false); + } } \ No newline at end of file From fd073809d047244559b8c132c1d2043351fdd5f1 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 17:14:47 -0400 Subject: [PATCH 027/230] Removing references to non phpunit code coverage parsing. Adding stub of new code coverage report generator. Updating related files. --- cake/tests/lib/cake_test_suite_dispatcher.php | 7 ---- .../lib/coverage/html_coverage_report.php | 35 +++++++++++++++++++ .../tests/lib/reporter/cake_html_reporter.php | 21 +++++++---- .../tests/lib/reporter/cake_text_reporter.php | 9 ++--- cake/tests/lib/test_manager.php | 3 -- 5 files changed, 53 insertions(+), 22 deletions(-) create mode 100644 cake/tests/lib/coverage/html_coverage_report.php diff --git a/cake/tests/lib/cake_test_suite_dispatcher.php b/cake/tests/lib/cake_test_suite_dispatcher.php index cc91a8226..1a4f48503 100644 --- a/cake/tests/lib/cake_test_suite_dispatcher.php +++ b/cake/tests/lib/cake_test_suite_dispatcher.php @@ -236,7 +236,6 @@ class CakeTestSuiteDispatcher { if (isset($_GET['code_coverage'])) { $this->params['codeCoverage'] = true; $this->_checkXdebug(); - require_once CAKE_TESTS_LIB . 'code_coverage_manager.php'; } $this->params['baseUrl'] = $this->_baseUrl; $this->params['baseDir'] = $this->_baseDir; @@ -250,9 +249,6 @@ class CakeTestSuiteDispatcher { */ function _runGroupTest() { $Reporter = CakeTestSuiteDispatcher::getReporter(); - if ($this->params['codeCoverage']) { - CodeCoverageManager::init($this->params['group'], $Reporter); - } if ('all' == $this->params['group']) { $this->Manager->runAllTests($Reporter); } else { @@ -267,9 +263,6 @@ class CakeTestSuiteDispatcher { */ function _runTestCase() { $Reporter = CakeTestSuiteDispatcher::getReporter(); - if ($this->params['codeCoverage']) { - CodeCoverageManager::init($this->params['case'], $Reporter); - } $this->Manager->runTestCase($this->params['case'], $Reporter, $this->params['codeCoverage']); } } diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php new file mode 100644 index 000000000..4c1840a7e --- /dev/null +++ b/cake/tests/lib/coverage/html_coverage_report.php @@ -0,0 +1,35 @@ +_coverage = $coverage; + } + +/** + * Generates report html to display. + * + * @return string compiled html report. + */ + public function report() { + + } +} \ No newline at end of file diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 68d6dbd09..eec5de136 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -175,16 +175,25 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes } echo $this->_paintLinks(); echo ''; - if ( - isset($this->params['codeCoverage']) && - $this->params['codeCoverage'] && - class_exists('CodeCoverageManager') - ) { - //CodeCoverageManager::report(); + if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) { + $coverage = $result->getCodeCoverageInformation(); + echo $this->paintCoverage($coverage); } $this->paintDocumentEnd(); } +/** + * Paints a code coverage report. + * + * @return void + */ + public function paintCoverage($coverage) { + $file = dirname(dirname(__FILE__)) . '/coverage/html_coverage_report.php'; + include $file; + $reporter = new HtmlCoverageReport($coverage); + echo $reporter->report(); + } + /** * Renders the links that for accessing things in the test suite. * diff --git a/cake/tests/lib/reporter/cake_text_reporter.php b/cake/tests/lib/reporter/cake_text_reporter.php index 4bc51d509..31cec5c3e 100644 --- a/cake/tests/lib/reporter/cake_text_reporter.php +++ b/cake/tests/lib/reporter/cake_text_reporter.php @@ -61,12 +61,9 @@ class CakeTextReporter extends CakeBaseReporter { if (function_exists('memory_get_peak_usage')) { echo 'Peak memory use: (in bytes): ' . number_format(memory_get_peak_usage()) . "\n"; } - if ( - isset($this->params['codeCoverage']) && - $this->params['codeCoverage'] && - class_exists('CodeCoverageManager') - ) { - CodeCoverageManager::report(); + if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) { + $coverage = $result->getCodeCoverageInformation(); + echo $this->paintCoverage($coverage); } } diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 07bb09993..67e35bc61 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -167,9 +167,6 @@ class TestManager { $reporter->paintHeader(); $this->getTestSuite()->run($result); $reporter->paintResult($result); - // echo '
    ';
    -		// var_dump($result->getCodeCoverageInformation());
    -		// echo '
    '; return $result; } From 72f162f52a2fda3b1cbfabd1432252a783b7ec60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 16:52:29 -0430 Subject: [PATCH 028/230] Adding docs to CakeTestSuite --- cake/tests/lib/cake_test_suite.php | 40 +++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/cake/tests/lib/cake_test_suite.php b/cake/tests/lib/cake_test_suite.php index c83612509..7ac3ce63c 100644 --- a/cake/tests/lib/cake_test_suite.php +++ b/cake/tests/lib/cake_test_suite.php @@ -1,13 +1,46 @@ _fixtureManager = $manager; } +/** + * Method that is called before the tests of this test suite are run. + * It will load fixtures accordingly for each test + * @return void + * @access protected + */ protected function setUp() { parent::setUp(); if (!$this->_fixtureManager) { @@ -20,6 +53,11 @@ class CakeTestSuite extends PHPUnit_Framework_TestSuite { $this->sharedFixture = $this->_fixtureManager; } +/** + * Method that is called after all the tests of this test suite are run. + * @return void + * @access protected + */ protected function tearDown() { parent::tearDown(); $this->_fixtureManager->shutDown(); From ac5f73194072af3ac7453f9341d784cefb939fbc Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 17:59:14 -0400 Subject: [PATCH 029/230] Starting work on HtmlCoverageReport and adding a test case. --- .../cases/libs/html_coverage_report.test.php | 46 ++++++++++ .../lib/coverage/html_coverage_report.php | 87 ++++++++++++++++++- 2 files changed, 129 insertions(+), 4 deletions(-) create mode 100644 cake/tests/cases/libs/html_coverage_report.test.php diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php new file mode 100644 index 000000000..7ee39d107 --- /dev/null +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -0,0 +1,46 @@ +params = array('app' => false, 'plugin' => false, 'group' => false); + $coverage = array(); + $this->Coverage = new HtmlCoverageReport($coverage, $reporter); + } + +/** + * test getting the path filters. + * + * @return void + */ + function testGetPathFilter() { + $this->Coverage->appTest = false; + $result = $this->Coverage->getPathFilter(); + $this->assertEquals(TEST_CAKE_CORE_INCLUDE_PATH, $result); + + $this->Coverage->appTest = true; + $result = $this->Coverage->getPathFilter(); + $this->assertEquals(ROOT . DS . APP_DIR . DS, $result); + + $this->Coverage->appTest = false; + $this->Coverage->pluginTest = 'test_plugin'; + $result = $this->Coverage->getPathFilter(); + $this->assertEquals(ROOT . DS . APP_DIR . DS . 'plugins' . DS .'test_plugin' . DS, $result); + } + +/** + * teardown + * + * @return void + */ + function tearDown() { + unset($this->Coverage); + } +} \ No newline at end of file diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php index 4c1840a7e..0e47a8335 100644 --- a/cake/tests/lib/coverage/html_coverage_report.php +++ b/cake/tests/lib/coverage/html_coverage_report.php @@ -12,7 +12,11 @@ class HtmlCoverageReport { * * @var string */ - protected $_coverage; + protected $_rawCoverage; + + public $appTest = false; + public $pluginTest = false; + public $groupTest = false; /** * Constructor @@ -20,8 +24,35 @@ class HtmlCoverageReport { * @param array $coverage Array of coverage data from PHPUnit_Test_Result * @return void */ - public function __construct($coverage) { - $this->_coverage = $coverage; + public function __construct($coverage, CakeBaseReporter $reporter) { + $this->_rawCoverage = $coverage; + $this->setParams($reporter); + } + +/** + * Pulls params out of the reporter. + * + * @return void + */ + protected function setParams(CakeBaseReporter $reporter) { + if ($reporter->params['app']) { + $this->appTest = true; + } + if ($reporter->params['group']) { + $this->groupTest = true; + } + if ($reporter->params['plugin']) { + $this->pluginTest = Inflector::underscore($reporter->params['plugin']); + } + } + +/** + * Set the coverage data array + * + * @return void + */ + public function setCoverage($coverage) { + $this->_rawCoverage = $coverage; } /** @@ -30,6 +61,54 @@ class HtmlCoverageReport { * @return string compiled html report. */ public function report() { - + $pathFilter = $this->getPathFilter(); + $coverageData = $this->filterCoverageDataByPath($pathFilter); + } + +/** + * Gets the base path that the files we are interested in live in. + * If appTest ist + * + * @return void + */ + public function getPathFilter() { + $path = ROOT . DS; + if ($this->appTest) { + $path .= APP_DIR . DS; + } elseif ($this->pluginTest) { + $path = App::pluginPath($this->pluginTest); + } else { + $path = TEST_CAKE_CORE_INCLUDE_PATH; + } + return $path; + } + +/** + * Filters the coverage data by path. Files not in the provided path will be removed. + * This method will merge all the various test run reports as well into a single report per file. + * + * @param string $path Path to filter files by. + * @return array Array of coverage data for files that match the given path. + */ + public function filterCoverageDataByPath($path) { + $files = array(); + foreach ($this->_rawCoverage as $testRun) { + foreach ($testRun['files'] as $filename => $fileCoverage) { + if (strpos($filename, $path) !== 0) { + continue; + } + if (!isset($files[$filename])) { + $files[$filename] = array(); + } + foreach ($fileCoverage as $line => $value) { + if (!isset($files[$filename][$line])) { + $files[$filename][$line] = $value; + } elseif ($files[$filename][$line] < $value) { + $files[$filename][$line] = $value; + } + } + } + } + return $files; } } \ No newline at end of file From f5cfc325f8660bcf83cfa7dd742fe37346cac829 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 8 May 2010 17:29:33 -0430 Subject: [PATCH 030/230] Adding some missing doc blocks --- cake/tests/lib/cake_test_case.php | 55 ++++++++++++++++++++++++++++--- cake/tests/lib/test_manager.php | 5 +++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index e35350383..e577581f5 100644 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -389,29 +389,70 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { } } +/** +* Compatibility wrapper function for assertEquals +* @param mixed $a +* @param mixed $b +* @param string $message the text to display if the assertion is not correct +* @return void +*/ protected function assertEqual($a, $b, $message = '') { return $this->assertEquals($a, $b, $message); } - + +/** +* Compatibility wrapper function for assertNotEquals +* @param mixed $a +* @param mixed $b +* @param string $message the text to display if the assertion is not correct +* @return void +*/ protected function assertNotEqual($a, $b, $message = '') { return $this->assertNotEquals($a, $b, $message); } +/** +* Compatibility wrapper function for assertRegexp +* @param mixed $pattern a regular expression +* @param string $string the text to be matched +* @param string $message the text to display if the assertion is not correct +* @return void +*/ protected function assertPattern($pattern, $string, $message = '') { return $this->assertRegExp($pattern, $string, $message); } +/** +* Compatibility wrapper function for assertSame +* @param mixed $expected +* @param mixed $actual +* @param string $message the text to display if the assertion is not correct +* @return void +*/ protected function assertIdentical($expected, $actual, $message = '') { return $this->assertSame($expected, $actual, $message); } +/** +* Compatibility wrapper function for assertNotRegExp +* @param mixed $pattern a regular expression +* @param string $string the text to be matched +* @param string $message the text to display if the assertion is not correct +* @return void +*/ protected function assertNoPattern($pattern, $string, $message = '') { return $this->assertNotRegExp($pattern, $string, $message); } protected function assertNoErrors() { } - + +/** +* Compatibility wrapper function for setExpectedException +* @param mixed $expected the name of the Exception or error +* @param string $message the text to display if the assertion is not correct +* @return void +*/ protected function expectError($expected = false, $message = '') { if (!$expected) { $expected = 'Exception'; @@ -419,8 +460,14 @@ class CakeTestCase extends PHPUnit_Framework_TestCase { $this->setExpectedException($expected, $message); } - protected function expectException($name = null) { - $this->setExpectedException($name); +/** +* Compatibility wrapper function for setExpectedException +* @param mixed $expected the name of the Exception +* @param string $message the text to display if the assertion is not correct +* @return void +*/ + protected function expectException($name = null, $message = '') { + $this->setExpectedException($name, $message); } } ?> \ No newline at end of file diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 496e9be93..749bd8cce 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -414,6 +414,11 @@ class TestManager { return $this->_testSuite = new CakeTestSuite($name); } +/** + * Get an instance of a Fixture manager to be used by the test cases + * + * @return CakeFixtureManager fixture manager + */ protected function getFixtureManager() { if (!empty($this->_fixtureManager)) { return $this->_fixtureManager; From fad99ad1f4e1a89e06de18e5168bfa8d106a758e Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 18:08:02 -0400 Subject: [PATCH 031/230] Adding tests for merging of report data. --- .../cases/libs/html_coverage_report.test.php | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index 7ee39d107..626dfef07 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -35,6 +35,69 @@ class HtmlCoverageReportTest extends CakeTestCase { $this->assertEquals(ROOT . DS . APP_DIR . DS . 'plugins' . DS .'test_plugin' . DS, $result); } +/** + * test filtering coverage data. + * + * @return void + */ + function testFilterCoverageDataByPathRemovingElements() { + $data = array( + array( + 'files' => array( + TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( + 10 => -1, + 12 => 1 + ), + APP . 'app_model.php' => array( + 50 => 1, + 52 => -1 + ) + ) + ) + ); + $this->Coverage->setCoverage($data); + $result = $this->Coverage->filterCoverageDataByPath(TEST_CAKE_CORE_INCLUDE_PATH); + $this->assertTrue(isset($result[TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php'])); + $this->assertFalse(isset($result[APP . 'app_model.php'])); + } + +/** + * test that filterCoverageDataByPath correctly merges data sets in each test run. + * + * @return void + */ + function testFilterCoverageDataCorrectlyMergingValues() { + $data = array( + array( + 'files' => array( + TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( + 10 => -1, + 12 => 1 + ), + ) + ), + array( + 'files' => array( + TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( + 10 => 1, + 12 => -1, + 50 => 1, + 51 => -1 + ), + ) + ), + ); + $this->Coverage->setCoverage($data); + $result = $this->Coverage->filterCoverageDataByPath(TEST_CAKE_CORE_INCLUDE_PATH); + + $path = TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php'; + $this->assertTrue(isset($result[$path])); + $this->assertEquals(1, $result[$path][10]); + $this->assertEquals(1, $result[$path][12]); + $this->assertEquals(1, $result[$path][50]); + $this->assertEquals(-1, $result[$path][51]); + } + /** * teardown * From ccf5601a6939f0fce2dfbdae0c99d006711903e2 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 18:12:03 -0400 Subject: [PATCH 032/230] Updating coverage report initialization. --- cake/tests/lib/reporter/cake_html_reporter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index eec5de136..3c4d33548 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -190,7 +190,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes public function paintCoverage($coverage) { $file = dirname(dirname(__FILE__)) . '/coverage/html_coverage_report.php'; include $file; - $reporter = new HtmlCoverageReport($coverage); + $reporter = new HtmlCoverageReport($coverage, $this); echo $reporter->report(); } From f6b49cd865b1c5f428db646ea489ecb143bb09ee Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sat, 8 May 2010 18:12:20 -0400 Subject: [PATCH 033/230] Updating file headers. --- .../cases/libs/html_coverage_report.test.php | 18 ++++++++++++++++++ .../lib/coverage/html_coverage_report.php | 19 +++++++++++++++---- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index 626dfef07..82b1cf705 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -1,4 +1,22 @@ Date: Sat, 8 May 2010 17:50:55 -0430 Subject: [PATCH 034/230] Adding documentation for CakeFixtureManager --- cake/tests/lib/cake_fixture_manager.php | 92 ++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 1 deletion(-) diff --git a/cake/tests/lib/cake_fixture_manager.php b/cake/tests/lib/cake_fixture_manager.php index 53852f397..05d21a5fd 100644 --- a/cake/tests/lib/cake_fixture_manager.php +++ b/cake/tests/lib/cake_fixture_manager.php @@ -1,13 +1,60 @@ fixtures) || !empty($this->_processed[get_class($test)])) { $test->db = $this->_db; @@ -25,6 +72,11 @@ class CakeFixtureManager { $this->_processed[get_class($test)] = true; } +/** + * Initializes this class with a DataSource object to use as default for all fixtures + * + * @return void + */ protected function _initDb() { if ($this->_initialized) { return; @@ -57,6 +109,12 @@ class CakeFixtureManager { $this->_initialized = true; } +/** + * Looks for fixture files and instantiates the classes accordingly + * + * @param array $fixtures the fixture names to load using the notation {type}.{name} + * @return void + */ protected function _loadFixtures($fixtures) { foreach ($fixtures as $index => $fixture) { $fixtureFile = null; @@ -108,6 +166,14 @@ class CakeFixtureManager { } } +/** + * Runs the drop and create commands on the fixtures if necessary + * + * @param CakeTestFixture $fixture the fixture object to create + * @param DataSource $db the datasource instance to use + * @param boolean $drop whether drop the fixture if it is already created or not + * @return void + */ protected function _setupTable($fixture, $db = null, $drop = true) { if (!empty($fixture->created)) { return; @@ -132,6 +198,12 @@ class CakeFixtureManager { } } +/** + * Crates the fixtures tables and inserts data on them + * + * @param CakeTestCase $test the test to inspect for fixture loading + * @return void + */ public function load(CakeTestCase $test) { if (empty($test->fixtures)) { return; @@ -150,6 +222,12 @@ class CakeFixtureManager { } } +/** + * Trucantes the fixtures tables + * + * @param CakeTestCase $test the test to inspect for fixture unloading + * @return void + */ public function unload(CakeTestCase $test) { if (empty($test->fixtures)) { return; @@ -168,6 +246,13 @@ class CakeFixtureManager { } } +/** + * Trucantes the fixtures tables + * + * @param CakeTestCase $test the test to inspect for fixture unloading + * @return void + * @throws UnexpectedValueException if $name is not a previously loaded class + */ public function loadSingle($name, $db = null) { $name .= 'Fixture'; if (isset($this->_fixtureMap[$name])) { @@ -182,6 +267,11 @@ class CakeFixtureManager { } } +/** + * Drop all fixture tables loaded by this class + * + * @return void + */ public function shutDown() { foreach ($this->_loaded as $fixture) { if (!empty($fixture->created)) { From 955c6bea9f6d745a5ccc516843c4ab13115ba078 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 9 May 2010 00:04:03 -0400 Subject: [PATCH 035/230] Verbose coverage generation has been added and tests added. --- .../cases/libs/html_coverage_report.test.php | 90 +++++++++++++ .../lib/coverage/html_coverage_report.php | 123 ++++++++++++++++++ 2 files changed, 213 insertions(+) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index 82b1cf705..136528e36 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -116,6 +116,96 @@ class HtmlCoverageReportTest extends CakeTestCase { $this->assertEquals(-1, $result[$path][51]); } +/** + * test the features of getExecutableLines + * + * @return void + */ + function testGetExecutableLines() { + $contents = << +PHP; + $result = $this->Coverage->getExecutableLines(explode("\n", $contents)); + $expected = array( + 0 => false, + 1 => true, + 2 => true, + 3 => true, + 4 => true, + 5 => true, + 6 => false, + 7 => true, + 8 => true, + 9 => true, + 10 => true, + 11 => false, + 12 => true, + 13 => false, + 14 => false, + 15 => false + ); + $this->assertEquals($expected, $result); + } + +/** + * test generating HTML reports from file arrays. + * + * @return void + */ + function testGenerateDiff() { + $file = array( + 'line 1', + 'line 2', + 'line 3', + 'line 4', + 'line 5', + 'line 6', + 'line 7', + 'line 8', + 'line 9', + 'line 10', + ); + $coverage = array( + 1 => 1, + 2 => -2, + 3 => 1, + 4 => 1, + 5 => -1, + 6 => -1, + 7 => -1, + 8 => 1, + 9 => -1, + 10 => 1, + ); + $result = $this->Coverage->generateDiff('myfile.php', $file, $coverage); + $this->assertRegExp('/

    myfile\.php Code coverage\: \d+\.\d+\%<\/h2>/', $result); + $this->assertRegExp('/
    /', $result); + $this->assertRegExp('/
    /', $result);
    +		foreach ($file as $i => $line) {
    +			$this->assertTrue(strpos($line, $result) !== 0, 'Content is missing ' . $i);
    +			$class = 'uncovered';
    +			if ($coverage[$i + 1] > 0) {
    +				$class = 'covered';
    +			}
    +			$this->assertTrue(strpos($class, $result) !== 0, 'Class name is wrong ' . $i);
    +		}
    +	}
    +
     /**
      * teardown
      *
    diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php
    index 566650457..2f6510f4c 100644
    --- a/cake/tests/lib/coverage/html_coverage_report.php
    +++ b/cake/tests/lib/coverage/html_coverage_report.php
    @@ -29,6 +29,13 @@ class HtmlCoverageReport {
     	public $pluginTest = false;
     	public $groupTest = false;
     
    +/**
    + * Number of lines to provide around an uncovered code block
    + *
    + * @var integer
    + */
    +	public $numDiffContextLines = 7;
    +
     /**
      * Constructor
      *
    @@ -74,6 +81,15 @@ class HtmlCoverageReport {
     	public function report() {
     		$pathFilter = $this->getPathFilter();
     		$coverageData = $this->filterCoverageDataByPath($pathFilter);
    +		if (empty($coverageData)) {
    +			return '

    No files to generate coverage for

    '; + } + $output = ''; + foreach ($coverageData as $file => $coverageData) { + $fileData = file($file); + $output .= $this->generateDiff($file, $fileData, $coverageData); + } + return $output; } /** @@ -122,4 +138,111 @@ class HtmlCoverageReport { } return $files; } + +/** + * Removes non executable lines of code from a file contents string. + * + * @param array $lines in the file. + * @return array Array for the file with lines marked as not runnable. + */ + public function getExecutableLines($lines) { + $output = array(); + + $phpTagPattern = '/^[ |\t]*[<\?php|\?>]+[ |\t]*/'; + $basicallyEmptyPattern = '/^[ |\t]*[{|}|\(|\)]+[ |\t]*/'; + $ignoreStart = '/@codeCoverageIgnoreStart/'; + $ignoreStop = '/@codeCoverageIgnoreEnd/'; + + foreach ($lines as $lineno => $line) { + $runnable = true; + if (preg_match($phpTagPattern, $line) || preg_match($basicallyEmptyPattern, $line)) { + $runnable = false; + } + $output[$lineno] = $runnable; + } + return $output; + } + +/** + * Generates an HTML diff for $file based on $coverageData. + * + * @param array $fileData File data as an array. See file() for how to get one of these. + * @param array $coverageData Array of coverage data to use to generate HTML diffs with + * @return string HTML diff. + */ + function generateDiff($filename, $fileLines, $coverageData) { + $output = ''; + $diff = array(); + $covered = 0; + $total = 0; + + //shift line numbers forward one; + array_unshift($fileLines, ' '); + unset($fileLines[0]); + + $executableLines = $this->getExecutableLines($fileLines); + + foreach ($fileLines as $lineno => $line) { + $isExecutable = (isset($executableLines[$lineno]) && $executableLines[$lineno] == true); + + $class = 'uncovered'; + if (!$isExecutable) { + $class = 'ignored'; + } elseif (isset($coverageData[$lineno]) && $coverageData[$lineno] > 0) { + $class = 'covered'; + } + $diff[] = $this->_paintLine($line, $lineno, $class); + + if ($class == 'covered') { + $covered++; + } + if ($class == 'uncovered' || $class == 'covered') { + $total++; + } + } + + $percentCovered = round($covered / $total, 2); + + $output .= $this->coverageHeader($filename, $percentCovered); + $output .= implode("", $diff); + $output .= $this->coverageFooter(); + return $output; + } + +/** + * Renders the html for a single line in the html diff. + * + * @return void + */ + protected function _paintLine($line, $linenumber, $class) { + return sprintf( + '
    %s%s
    ', + $class, + $linenumber, + htmlspecialchars($line) + ); + } + + +/** + * Generate an HTML snippet for coverage headers + * + * @return void + */ + public function coverageHeader($filename, $percent) { + return <<$filename Code coverage: $percent%

    +
    +
    +HTML;
    +	}
    +
    +/**
    + * Generate an HTML snippet for coverage footers
    + *
    + * @return void
    + */
    +	public function coverageFooter() {
    +		return "
    "; + } } \ No newline at end of file From 9a20a2344b122e5df46c0a654e0cfcb17c7e109d Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 9 May 2010 00:40:05 -0400 Subject: [PATCH 036/230] Continuing work on updated code coverage reports. --- .../cases/libs/html_coverage_report.test.php | 12 +++--- .../lib/coverage/html_coverage_report.php | 39 ++++++++++++------- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index 136528e36..5e2786907 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -143,9 +143,9 @@ PHP; $result = $this->Coverage->getExecutableLines(explode("\n", $contents)); $expected = array( 0 => false, - 1 => true, - 2 => true, - 3 => true, + 1 => false, + 2 => false, + 3 => false, 4 => true, 5 => true, 6 => false, @@ -186,14 +186,14 @@ PHP; 3 => 1, 4 => 1, 5 => -1, - 6 => -1, - 7 => -1, + 6 => 1, + 7 => 1, 8 => 1, 9 => -1, 10 => 1, ); $result = $this->Coverage->generateDiff('myfile.php', $file, $coverage); - $this->assertRegExp('/

    myfile\.php Code coverage\: \d+\.\d+\%<\/h2>/', $result); + $this->assertRegExp('/

    myfile\.php Code coverage\: \d+\.?\d*\%<\/h2>/', $result); $this->assertRegExp('/
    /', $result); $this->assertRegExp('/
    /', $result);
     		foreach ($file as $i => $line) {
    diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php
    index 2f6510f4c..e4440b995 100644
    --- a/cake/tests/lib/coverage/html_coverage_report.php
    +++ b/cake/tests/lib/coverage/html_coverage_report.php
    @@ -150,14 +150,27 @@ class HtmlCoverageReport {
     
     		$phpTagPattern = '/^[ |\t]*[<\?php|\?>]+[ |\t]*/';
     		$basicallyEmptyPattern = '/^[ |\t]*[{|}|\(|\)]+[ |\t]*/';
    +		$commentStart = '/\/\*\*/';
    +		$commentEnd = '/\*\//';
     		$ignoreStart = '/@codeCoverageIgnoreStart/';
     		$ignoreStop = '/@codeCoverageIgnoreEnd/';
    +		$inComment = false;
     
     		foreach ($lines as $lineno => $line) {
     			$runnable = true;
     			if (preg_match($phpTagPattern, $line) || preg_match($basicallyEmptyPattern, $line)) {
     				$runnable = false;
     			}
    +			if ($runnable && preg_match($commentStart, $line)) {
    +				$runnable = false;
    +				$inComment = true;
    +			}
    +			if ($inComment == true) {
    +				$runnable = false;
    +			}
    +			if (!$runnable && preg_match($commentEnd, $line)) {
    +				$inComment = false;
    +			}
     			$output[$lineno] = $runnable;
     		}
     		return $output;
    @@ -183,22 +196,22 @@ class HtmlCoverageReport {
     		$executableLines = $this->getExecutableLines($fileLines);
     
     		foreach ($fileLines as $lineno => $line) {
    -			$isExecutable = (isset($executableLines[$lineno]) && $executableLines[$lineno] == true);
    +			$manualFind = (
    +				isset($executableLines[$lineno]) && 
    +				$executableLines[$lineno] == true &&
    +				trim($line) != ''
    +			);
     
    -			$class = 'uncovered';
    -			if (!$isExecutable) {
    -				$class = 'ignored';
    -			} elseif (isset($coverageData[$lineno]) && $coverageData[$lineno] > 0) {
    -				$class = 'covered';
    +			$class = 'ignored';
    +			if ($manualFind) {
    +				$class = 'uncovered';
    +				$total++;
    +				if (isset($coverageData[$lineno]) && $coverageData[$lineno] > 0) {
    +					$class = 'covered';
    +					$covered++;
    +				}
     			}
     			$diff[] = $this->_paintLine($line, $lineno, $class);
    -
    -			if ($class == 'covered') {
    -				$covered++;
    -			}
    -			if ($class == 'uncovered' || $class == 'covered') {
    -				$total++;
    -			}
     		}
     
     		$percentCovered = round($covered / $total, 2);
    
    From 75d7146bd0323bee80f488d05e6b7d346ac64aa7 Mon Sep 17 00:00:00 2001
    From: Mark Story 
    Date: Sun, 9 May 2010 01:15:57 -0400
    Subject: [PATCH 037/230] Updating code coverage tools to use raw data which
     includes dead and uncovered line data.
    
    ---
     cake/tests/lib/coverage/html_coverage_report.php | 6 ++++--
     cake/tests/lib/reporter/cake_html_reporter.php   | 2 +-
     cake/tests/lib/test_manager.php                  | 2 +-
     3 files changed, 6 insertions(+), 4 deletions(-)
    
    diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php
    index e4440b995..6122acd3d 100644
    --- a/cake/tests/lib/coverage/html_coverage_report.php
    +++ b/cake/tests/lib/coverage/html_coverage_report.php
    @@ -120,7 +120,7 @@ class HtmlCoverageReport {
     	public function filterCoverageDataByPath($path) {
     		$files = array();
     		foreach ($this->_rawCoverage as $testRun) {
    -			foreach ($testRun['files'] as $filename => $fileCoverage) {
    +			foreach ($testRun['data'] as $filename => $fileCoverage) {
     				if (strpos($filename, $path) !== 0) {
     					continue;
     				}
    @@ -136,6 +136,7 @@ class HtmlCoverageReport {
     				}
     			}
     		}
    +		ksort($files);
     		return $files;
     	}
     
    @@ -214,7 +215,7 @@ class HtmlCoverageReport {
     			$diff[] = $this->_paintLine($line, $lineno, $class);
     		}
     
    -		$percentCovered = round($covered / $total, 2);
    +		$percentCovered = round(100 * $covered / $total, 2);
     
     		$output .= $this->coverageHeader($filename, $percentCovered);
     		$output .= implode("", $diff);
    @@ -243,6 +244,7 @@ class HtmlCoverageReport {
      * @return void
      */
     	public function coverageHeader($filename, $percent) {
    +		$filename = basename($filename);
     		return <<$filename Code coverage: $percent%

    diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 3c4d33548..d36ea0d06 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -176,7 +176,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo $this->_paintLinks(); echo '
    '; if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) { - $coverage = $result->getCodeCoverageInformation(); + $coverage = $result->getRawCodeCoverageInformation(); echo $this->paintCoverage($coverage); } $this->paintDocumentEnd(); diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 67e35bc61..bef977808 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -162,7 +162,7 @@ class TestManager { */ protected function run($reporter, $codeCoverage = false) { $result = new PHPUnit_Framework_TestResult; - $result->collectCodeCoverageInformation($codeCoverage); + $result->collectRawCodeCoverageInformation($codeCoverage); $result->addListener($reporter); $reporter->paintHeader(); $this->getTestSuite()->run($result); From 3c3655aefddf1bbb906d866479f0f8e61479ef1e Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 9 May 2010 01:16:44 -0400 Subject: [PATCH 038/230] Fixing failing tests. --- cake/tests/cases/libs/html_coverage_report.test.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index 5e2786907..e1a89fdc0 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -61,7 +61,7 @@ class HtmlCoverageReportTest extends CakeTestCase { function testFilterCoverageDataByPathRemovingElements() { $data = array( array( - 'files' => array( + 'data' => array( TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( 10 => -1, 12 => 1 @@ -87,7 +87,7 @@ class HtmlCoverageReportTest extends CakeTestCase { function testFilterCoverageDataCorrectlyMergingValues() { $data = array( array( - 'files' => array( + 'data' => array( TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( 10 => -1, 12 => 1 @@ -95,7 +95,7 @@ class HtmlCoverageReportTest extends CakeTestCase { ) ), array( - 'files' => array( + 'data' => array( TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( 10 => 1, 12 => -1, From ac318faf5ac08888a01564bc9a4530dbb4c003ca Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 9 May 2010 02:08:32 -0400 Subject: [PATCH 039/230] Switching back to using non raw code coverage data as it has been filtered by phpunit's filters. combining the data from phpunit into a singular cohesive report. --- .../cases/libs/html_coverage_report.test.php | 29 ++++++++++++------- .../lib/coverage/html_coverage_report.php | 13 ++++----- .../tests/lib/reporter/cake_html_reporter.php | 2 +- cake/tests/lib/test_manager.php | 2 +- 4 files changed, 26 insertions(+), 20 deletions(-) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index e1a89fdc0..38bc9aff9 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -61,7 +61,7 @@ class HtmlCoverageReportTest extends CakeTestCase { function testFilterCoverageDataByPathRemovingElements() { $data = array( array( - 'data' => array( + 'files' => array( TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( 10 => -1, 12 => 1 @@ -87,28 +87,37 @@ class HtmlCoverageReportTest extends CakeTestCase { function testFilterCoverageDataCorrectlyMergingValues() { $data = array( array( - 'data' => array( - TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( - 10 => -1, + 'files' => array( + '/something/dispatcher.php' => array( + 10 => 1, 12 => 1 ), + ), + 'executable' => array( + '/something/dispatcher.php' => array( + 10 => -1 + ) ) ), array( - 'data' => array( - TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array( + 'files' => array( + '/something/dispatcher.php' => array( 10 => 1, - 12 => -1, 50 => 1, - 51 => -1 ), + ), + 'executable' => array( + '/something/dispatcher.php' => array( + 12 => -1, + 51 => -1 + ) ) ), ); $this->Coverage->setCoverage($data); - $result = $this->Coverage->filterCoverageDataByPath(TEST_CAKE_CORE_INCLUDE_PATH); + $result = $this->Coverage->filterCoverageDataByPath('/something/'); - $path = TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php'; + $path = '/something/dispatcher.php'; $this->assertTrue(isset($result[$path])); $this->assertEquals(1, $result[$path][10]); $this->assertEquals(1, $result[$path][12]); diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php index 6122acd3d..16b09dffa 100644 --- a/cake/tests/lib/coverage/html_coverage_report.php +++ b/cake/tests/lib/coverage/html_coverage_report.php @@ -120,20 +120,17 @@ class HtmlCoverageReport { public function filterCoverageDataByPath($path) { $files = array(); foreach ($this->_rawCoverage as $testRun) { - foreach ($testRun['data'] as $filename => $fileCoverage) { + foreach ($testRun['files'] as $filename => $fileCoverage) { if (strpos($filename, $path) !== 0) { continue; } + $dead = isset($testRun['dead'][$filename]) ? $testRun['dead'][$filename] : array(); + $executable = isset($testRun['executable'][$filename]) ? $testRun['executable'][$filename] : array(); + if (!isset($files[$filename])) { $files[$filename] = array(); } - foreach ($fileCoverage as $line => $value) { - if (!isset($files[$filename][$line])) { - $files[$filename][$line] = $value; - } elseif ($files[$filename][$line] < $value) { - $files[$filename][$line] = $value; - } - } + $files[$filename] = $files[$filename] + $fileCoverage + $executable + $dead; } } ksort($files); diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index d36ea0d06..3c4d33548 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -176,7 +176,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo $this->_paintLinks(); echo ''; if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) { - $coverage = $result->getRawCodeCoverageInformation(); + $coverage = $result->getCodeCoverageInformation(); echo $this->paintCoverage($coverage); } $this->paintDocumentEnd(); diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index bef977808..67e35bc61 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -162,7 +162,7 @@ class TestManager { */ protected function run($reporter, $codeCoverage = false) { $result = new PHPUnit_Framework_TestResult; - $result->collectRawCodeCoverageInformation($codeCoverage); + $result->collectCodeCoverageInformation($codeCoverage); $result->addListener($reporter); $reporter->paintHeader(); $this->getTestSuite()->run($result); From f084a82dfcbad0aaaeac108ac7c7484467208d37 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 9 May 2010 12:30:55 -0400 Subject: [PATCH 040/230] Refactoring how coverage diffs are generated to better use data from phpunit. Removing methods made redundant by data changes. --- .../cases/libs/html_coverage_report.test.php | 102 +++++++----------- .../lib/coverage/html_coverage_report.php | 67 +++--------- 2 files changed, 53 insertions(+), 116 deletions(-) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index 38bc9aff9..d3beb6758 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -95,7 +95,13 @@ class HtmlCoverageReportTest extends CakeTestCase { ), 'executable' => array( '/something/dispatcher.php' => array( - 10 => -1 + 9 => -1 + ) + ), + 'dead' => array( + '/something/dispatcher.php' => array( + 22 => -2, + 23 => -2 ) ) ), @@ -111,6 +117,12 @@ class HtmlCoverageReportTest extends CakeTestCase { 12 => -1, 51 => -1 ) + ), + 'dead' => array( + '/something/dispatcher.php' => array( + 13 => -2, + 42 => -2 + ) ) ), ); @@ -119,56 +131,9 @@ class HtmlCoverageReportTest extends CakeTestCase { $path = '/something/dispatcher.php'; $this->assertTrue(isset($result[$path])); - $this->assertEquals(1, $result[$path][10]); - $this->assertEquals(1, $result[$path][12]); - $this->assertEquals(1, $result[$path][50]); - $this->assertEquals(-1, $result[$path][51]); - } - -/** - * test the features of getExecutableLines - * - * @return void - */ - function testGetExecutableLines() { - $contents = << -PHP; - $result = $this->Coverage->getExecutableLines(explode("\n", $contents)); - $expected = array( - 0 => false, - 1 => false, - 2 => false, - 3 => false, - 4 => true, - 5 => true, - 6 => false, - 7 => true, - 8 => true, - 9 => true, - 10 => true, - 11 => false, - 12 => true, - 13 => false, - 14 => false, - 15 => false - ); - $this->assertEquals($expected, $result); + $this->assertEquals(array(10, 12, 50), array_keys($result[$path]['covered'])); + $this->assertEquals(array(9, 12, 51), array_keys($result[$path]['executable'])); + $this->assertEquals(array(22, 23, 13, 42), array_keys($result[$path]['dead'])); } /** @@ -190,16 +155,22 @@ PHP; 'line 10', ); $coverage = array( - 1 => 1, - 2 => -2, - 3 => 1, - 4 => 1, - 5 => -1, - 6 => 1, - 7 => 1, - 8 => 1, - 9 => -1, - 10 => 1, + 'covered' => array( + 1 => 1, + 3 => 1, + 4 => 1, + 6 => 1, + 7 => 1, + 8 => 1, + 10 => 1 + ), + 'executable' => array( + 5 => -1, + 9 => -1 + ), + 'dead' => array( + 2 => -2 + ) ); $result = $this->Coverage->generateDiff('myfile.php', $file, $coverage); $this->assertRegExp('/

    myfile\.php Code coverage\: \d+\.?\d*\%<\/h2>/', $result); @@ -207,9 +178,12 @@ PHP; $this->assertRegExp('/
    /', $result);
     		foreach ($file as $i => $line) {
     			$this->assertTrue(strpos($line, $result) !== 0, 'Content is missing ' . $i);
    -			$class = 'uncovered';
    -			if ($coverage[$i + 1] > 0) {
    -				$class = 'covered';
    +			$class = 'covered';
    +			if (in_array($i + 1, array(5, 9, 2))) {
    +				$class = 'uncovered';
    +			}
    +			if ($i + 1 == 2) {
    +				$class .= ' dead';
     			}
     			$this->assertTrue(strpos($class, $result) !== 0, 'Class name is wrong ' . $i);
     		}
    diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php
    index 16b09dffa..63d2d0dba 100644
    --- a/cake/tests/lib/coverage/html_coverage_report.php
    +++ b/cake/tests/lib/coverage/html_coverage_report.php
    @@ -128,52 +128,21 @@ class HtmlCoverageReport {
     				$executable = isset($testRun['executable'][$filename]) ? $testRun['executable'][$filename] : array();
     		
     				if (!isset($files[$filename])) {
    -					$files[$filename] = array();
    +					$files[$filename] = array(
    +						'covered' => array(),
    +						'dead' => array(),
    +						'executable' => array()
    +					);
     				}
    -				$files[$filename] = $files[$filename] + $fileCoverage + $executable + $dead;
    +				$files[$filename]['covered'] += $fileCoverage;
    +				$files[$filename]['executable'] += $executable;
    +				$files[$filename]['dead'] += $dead;
     			}
     		}
     		ksort($files);
     		return $files;
     	}
     
    -/**
    - * Removes non executable lines of code from a file contents string.
    - *
    - * @param array $lines in the file.
    - * @return array Array for the file with lines marked as not runnable.
    - */
    -	public function getExecutableLines($lines) {
    -		$output = array();
    -
    -		$phpTagPattern = '/^[ |\t]*[<\?php|\?>]+[ |\t]*/';
    -		$basicallyEmptyPattern = '/^[ |\t]*[{|}|\(|\)]+[ |\t]*/';
    -		$commentStart = '/\/\*\*/';
    -		$commentEnd = '/\*\//';
    -		$ignoreStart = '/@codeCoverageIgnoreStart/';
    -		$ignoreStop = '/@codeCoverageIgnoreEnd/';
    -		$inComment = false;
    -
    -		foreach ($lines as $lineno => $line) {
    -			$runnable = true;
    -			if (preg_match($phpTagPattern, $line) || preg_match($basicallyEmptyPattern, $line)) {
    -				$runnable = false;
    -			}
    -			if ($runnable && preg_match($commentStart, $line)) {
    -				$runnable = false;
    -				$inComment = true;
    -			}
    -			if ($inComment == true) {
    -				$runnable = false;
    -			}
    -			if (!$runnable && preg_match($commentEnd, $line)) {
    -				$inComment = false;
    -			}
    -			$output[$lineno] = $runnable;
    -		}
    -		return $output;
    -	}
    -
     /**
      * Generates an HTML diff for $file based on $coverageData.
      *
    @@ -191,23 +160,17 @@ class HtmlCoverageReport {
     		array_unshift($fileLines, ' ');
     		unset($fileLines[0]);
     
    -		$executableLines = $this->getExecutableLines($fileLines);
    -
     		foreach ($fileLines as $lineno => $line) {
    -			$manualFind = (
    -				isset($executableLines[$lineno]) && 
    -				$executableLines[$lineno] == true &&
    -				trim($line) != ''
    -			);
    -
     			$class = 'ignored';
    -			if ($manualFind) {
    +			if (isset($coverageData['covered'][$lineno])) {
    +				$class = 'covered';
    +				$covered++;
    +				$total++;
    +			} elseif (isset($coverageData['executable'][$lineno])) {
     				$class = 'uncovered';
     				$total++;
    -				if (isset($coverageData[$lineno]) && $coverageData[$lineno] > 0) {
    -					$class = 'covered';
    -					$covered++;
    -				}
    +			} elseif (isset($coverageData['dead'][$lineno])) {
    +				$class .= ' dead';
     			}
     			$diff[] = $this->_paintLine($line, $lineno, $class);
     		}
    
    From d252fdeb524150be194dc324d6cd47bf74e2a3e0 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 16:09:02 -0430
    Subject: [PATCH 041/230] Fixing View test case to be compatible with PHPUnit
    
    ---
     cake/tests/cases/libs/view/view.test.php | 16 +++++++---------
     1 file changed, 7 insertions(+), 9 deletions(-)
    
    diff --git a/cake/tests/cases/libs/view/view.test.php b/cake/tests/cases/libs/view/view.test.php
    index 705e76c6a..4e433d712 100644
    --- a/cake/tests/cases/libs/view/view.test.php
    +++ b/cake/tests/cases/libs/view/view.test.php
    @@ -20,9 +20,6 @@
     App::import('Core', array('View', 'Controller'));
     App::import('Helper', 'Cache');
     
    -Mock::generate('Helper', 'CallbackMockHelper');
    -Mock::generate('CacheHelper', 'ViewTestMockCacheHelper');
    -
     if (!class_exists('ErrorHandler')) {
     	App::import('Core', array('Error'));
     }
    @@ -608,14 +605,15 @@ class ViewTest extends CakeTestCase {
      * @return void
      */
     	function testHelperCallbackTriggering() {
    +		$mockHelper = $this->getMock('Helper', array(), array(), 'CallbackMockHelper');
     		$this->PostsController->helpers = array('Session', 'Html', 'CallbackMock');
     		$View = new TestView($this->PostsController);
     		$loaded = array();
     		$View->loaded = $View->loadHelpers($loaded, $this->PostsController->helpers);
    -		$View->loaded['CallbackMock']->expectOnce('beforeRender');
    -		$View->loaded['CallbackMock']->expectOnce('afterRender');
    -		$View->loaded['CallbackMock']->expectOnce('beforeLayout');
    -		$View->loaded['CallbackMock']->expectOnce('afterLayout');
    +		$View->loaded['CallbackMock']->expects($this->once())->method('beforeRender');
    +		$View->loaded['CallbackMock']->expects($this->once())->method('afterRender');
    +		$View->loaded['CallbackMock']->expects($this->once())->method('beforeLayout');
    +		$View->loaded['CallbackMock']->expects($this->once())->method('afterLayout');
     		$View->render('index');
     	}
     
    @@ -745,8 +743,8 @@ class ViewTest extends CakeTestCase {
     		$Controller = new ViewPostsController();
     		$Controller->cacheAction = '1 day';
     		$View = new View($Controller);
    -		$View->loaded['cache'] = new ViewTestMockCacheHelper();
    -		$View->loaded['cache']->expectCallCount('cache', 2);
    +		$View->loaded['cache'] = $this->getMock('CacheHelper');
    +		$View->loaded['cache']->expects($this->exactly(2))->method('cache');
     
     		$result = $View->render('index');
     		$this->assertPattern('/posts index/', $result);
    
    From c96b14541d805c350d77104b84b0885cc9e023de Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 16:09:57 -0430
    Subject: [PATCH 042/230] Adding new compatibility method for CakeTestCase
    
    ---
     cake/tests/lib/cake_test_case.php | 11 +++++++++++
     1 file changed, 11 insertions(+)
    
    diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php
    index e577581f5..e56cfbf3f 100644
    --- a/cake/tests/lib/cake_test_case.php
    +++ b/cake/tests/lib/cake_test_case.php
    @@ -469,5 +469,16 @@ class CakeTestCase extends PHPUnit_Framework_TestCase {
     	protected function expectException($name = null, $message = '') {
     		$this->setExpectedException($name, $message);
     	}
    +
    +/**
    +* Compatibility wrapper function for assertSame
    +* @param mixed $expected
    +* @param mixed $actual
    +* @param string $message the text to display if the assertion is not correct
    +* @return void
    +*/
    +	protected function assertReference(&$first,  &$second, $message = '') {
    +		return $this->assertSame($first, $second, $message);
    +	}
     }
     ?>
    \ No newline at end of file
    
    From 809550087c0ff6bf0f505af5031efd35d184ef87 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 16:27:09 -0430
    Subject: [PATCH 043/230] Finxing ThemeTest to be compatible with PHPUnit
    
    ---
     cake/tests/cases/libs/view/theme.test.php | 5 +----
     1 file changed, 1 insertion(+), 4 deletions(-)
    
    diff --git a/cake/tests/cases/libs/view/theme.test.php b/cake/tests/cases/libs/view/theme.test.php
    index 2541fbbb9..6a145d860 100644
    --- a/cake/tests/cases/libs/view/theme.test.php
    +++ b/cake/tests/cases/libs/view/theme.test.php
    @@ -294,7 +294,6 @@ class ThemeViewTest extends CakeTestCase {
     
     /**
      * testMissingLayout method
    - *
      * @access public
      * @return void
      */
    @@ -305,12 +304,10 @@ class ThemeViewTest extends CakeTestCase {
     		$this->Controller->layout = 'whatever';
     		$this->Controller->theme = 'my_theme';
     
    -		restore_error_handler();
     		$View =& new TestThemeView($this->Controller);
     		ob_start();
     		$result = $View->getLayoutFileName();
     		$expected = str_replace(array("\t", "\r\n", "\n"), "", ob_get_clean());
    -		set_error_handler('simpleTestErrorHandler');
     		$this->assertPattern("/Missing Layout/", $expected);
     		$this->assertPattern("/views(\/|\\\)themed(\/|\\\)my_theme(\/|\\\)layouts(\/|\\\)whatever.ctp/", $expected);
     	}
    @@ -338,7 +335,7 @@ class ThemeViewTest extends CakeTestCase {
     			$View->element('test_element');
     		}
     		$end = memory_get_usage();
    -		$this->assertWithinMargin($start, $end, 3500);
    +		$this->assertLessThanOrEqual($start + 3500, $end);
     	}
     }
     ?>
    \ No newline at end of file
    
    From 88d21fbea44dd05d04b5eb7e3f8963bd25f2f804 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 18:15:51 -0430
    Subject: [PATCH 044/230] Experimental change: restoring the error handler to
     steps back in the stack to let PHPUnit take over when running tests
    
    ---
     cake/tests/lib/cake_test_suite.php | 2 ++
     1 file changed, 2 insertions(+)
    
    diff --git a/cake/tests/lib/cake_test_suite.php b/cake/tests/lib/cake_test_suite.php
    index 7ac3ce63c..66ae74b18 100644
    --- a/cake/tests/lib/cake_test_suite.php
    +++ b/cake/tests/lib/cake_test_suite.php
    @@ -43,6 +43,8 @@ class CakeTestSuite extends PHPUnit_Framework_TestSuite {
      */
     	protected function setUp() {
     		parent::setUp();
    +		restore_error_handler();
    +		restore_error_handler();
     		if (!$this->_fixtureManager) {
     			return;
     		}
    
    From 508d707a7ac9128bac504aaeba9aac16c715e68c Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 18:16:42 -0430
    Subject: [PATCH 045/230] Adding another compatibility test method:
     assertWithinMargin
    
    ---
     cake/tests/lib/cake_test_case.php | 14 ++++++++++++++
     1 file changed, 14 insertions(+)
    
    diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php
    index e56cfbf3f..55778491b 100644
    --- a/cake/tests/lib/cake_test_case.php
    +++ b/cake/tests/lib/cake_test_case.php
    @@ -480,5 +480,19 @@ class CakeTestCase extends PHPUnit_Framework_TestCase {
     	protected function assertReference(&$first,  &$second, $message = '') {
     		return $this->assertSame($first, $second, $message);
     	}
    +
    +/**
    +* Compatibility function to test if value is between an acceptable range
    +* @param mixed $value
    +* @param mixed $expected
    +* @param mixed $margin the rage of acceptation
    +* @param string $message the text to display if the assertion is not correct
    +* @return void
    +*/
    +	protected function assertWithinMargin($value, $expected, $margin, $message = '') {
    +		$upper = $value + $margin;
    +		$lower = $value - $margin;
    +		$this->assertTrue((($expected <= $upper) && ($expected >= $lower)), $message);
    +	}
     }
     ?>
    \ No newline at end of file
    
    From bc9479efcf4c41c6a3ac4cc28c7be86932e01417 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 18:18:40 -0430
    Subject: [PATCH 046/230] Fixing XmlTest to be compatible with PHPUnit
    
    ---
     cake/tests/cases/libs/xml.test.php | 1 -
     1 file changed, 1 deletion(-)
    
    diff --git a/cake/tests/cases/libs/xml.test.php b/cake/tests/cases/libs/xml.test.php
    index a47606216..a6671c221 100644
    --- a/cake/tests/cases/libs/xml.test.php
    +++ b/cake/tests/cases/libs/xml.test.php
    @@ -1340,7 +1340,6 @@ class XmlTest extends CakeTestCase {
     		$parentNode->append($string);
     		$last =& $parentNode->last();
     		$this->assertEqual($last->name, 'ourChildNode');
    -
     		$this->expectError();
     		$parentNode->append($parentNode);
     	}
    
    From 1e01e21bf9435460b98ec2d0d9e729315749c9ed Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 18:48:39 -0430
    Subject: [PATCH 047/230] Impriving the default for expectExpection
    
    ---
     cake/tests/lib/cake_test_case.php | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php
    index 55778491b..b9f2eb470 100644
    --- a/cake/tests/lib/cake_test_case.php
    +++ b/cake/tests/lib/cake_test_case.php
    @@ -466,7 +466,7 @@ class CakeTestCase extends PHPUnit_Framework_TestCase {
     * @param string $message the text to display if the assertion is not correct
     * @return void
     */
    -	protected function expectException($name = null, $message = '') {
    +	protected function expectException($name = 'Exception', $message = '') {
     		$this->setExpectedException($name, $message);
     	}
     
    
    From 765de657e6caba1dfe9b9c5fdab5fd2e7df58027 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= 
    Date: Sun, 9 May 2010 18:49:04 -0430
    Subject: [PATCH 048/230] Fixing PaginatorHelperTest to be compatible with
     PHPUnit
    
    ---
     cake/libs/view/helpers/paginator.php | 5 +++--
     1 file changed, 3 insertions(+), 2 deletions(-)
    
    diff --git a/cake/libs/view/helpers/paginator.php b/cake/libs/view/helpers/paginator.php
    index 4b6e2bc60..230ff9a5d 100644
    --- a/cake/libs/view/helpers/paginator.php
    +++ b/cake/libs/view/helpers/paginator.php
    @@ -91,8 +91,9 @@ class PaginatorHelper extends AppHelper {
     		$ajaxProvider = isset($config['ajax']) ? $config['ajax'] : 'Js';
     		$this->helpers[] = $ajaxProvider;
     		$this->_ajaxHelperClass = $ajaxProvider;
    -
    -		App::import('Helper', $ajaxProvider);
    +		if (!class_exists($ajaxProvider . 'Helper')) {
    +			App::import('Helper', $ajaxProvider);
    +		}
     		$classname = $ajaxProvider . 'Helper';
     		if (!method_exists($classname, 'link')) {
     			throw new Exception(sprintf(
    
    From e8e2235cfa2c48d7bd1e1daf757060bda94dfa8e Mon Sep 17 00:00:00 2001
    From: Mark Story 
    Date: Sun, 9 May 2010 22:15:20 -0400
    Subject: [PATCH 049/230] Updating coverage report and tests to include hiding
     javascript.
    
    ---
     .../cases/libs/html_coverage_report.test.php  |  4 +--
     .../lib/coverage/html_coverage_report.php     | 25 ++++++++++++++++---
     2 files changed, 24 insertions(+), 5 deletions(-)
    
    diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php
    index d3beb6758..68a5d9262 100644
    --- a/cake/tests/cases/libs/html_coverage_report.test.php
    +++ b/cake/tests/cases/libs/html_coverage_report.test.php
    @@ -173,8 +173,8 @@ class HtmlCoverageReportTest extends CakeTestCase {
     			)
     		);
     		$result = $this->Coverage->generateDiff('myfile.php', $file, $coverage);
    -		$this->assertRegExp('/

    myfile\.php Code coverage\: \d+\.?\d*\%<\/h2>/', $result); - $this->assertRegExp('/
    /', $result); + $this->assertRegExp('/myfile\.php Code coverage\: \d+\.?\d*\%/', $result); + $this->assertRegExp('/
    assertRegExp('/
    /', $result);
     		foreach ($file as $i => $line) {
     			$this->assertTrue(strpos($line, $result) !== 0, 'Content is missing ' . $i);
    diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php
    index 63d2d0dba..2bf406ef2 100644
    --- a/cake/tests/lib/coverage/html_coverage_report.php
    +++ b/cake/tests/lib/coverage/html_coverage_report.php
    @@ -84,7 +84,7 @@ class HtmlCoverageReport {
     		if (empty($coverageData)) {
     			return '

    No files to generate coverage for

    '; } - $output = ''; + $output = $this->coverageScript(); foreach ($coverageData as $file => $coverageData) { $fileData = file($file); $output .= $this->generateDiff($file, $fileData, $coverageData); @@ -197,6 +197,21 @@ class HtmlCoverageReport { ); } +/** + * generate some javascript for the coverage report. + * + * @return void + */ + public function coverageScript() { + return << + function coverage_show_hide(selector) { + var element = document.getElementById(selector); + element.style.display = (element.style.display == 'none') ? '' : 'none'; + } + +HTML; + } /** * Generate an HTML snippet for coverage headers @@ -206,8 +221,12 @@ class HtmlCoverageReport { public function coverageHeader($filename, $percent) { $filename = basename($filename); return <<$filename Code coverage: $percent%

    -
    +

    + + $filename Code coverage: $percent% + +

    +

    +HTML; foreach ($coverageData as $file => $coverageData) { $fileData = file($file); $output .= $this->generateDiff($file, $fileData, $coverageData); @@ -138,6 +161,11 @@ class HtmlCoverageReport { $files[$filename]['executable'] += $executable; $files[$filename]['dead'] += $dead; } + if (isset($testRun['test'])) { + $testReflection = new ReflectionClass(get_class($testRun['test'])); + list($fileBasename, $x) = explode('.', basename($testReflection->getFileName()), 2); + $this->_testNames[] = $fileBasename; + } } ksort($files); return $files; @@ -209,6 +237,15 @@ class HtmlCoverageReport { var element = document.getElementById(selector); element.style.display = (element.style.display == 'none') ? '' : 'none'; } + function coverage_toggle_all () { + var divs = document.querySelectorAll('div.coverage-container'); + var i = divs.length; + while (i--) { + if (divs[i] && divs[i].className.indexOf('primary') == -1) { + divs[i].style.display = (divs[i].style.display == 'none') ? '' : 'none'; + } + } + } HTML; } @@ -220,7 +257,11 @@ HTML; */ public function coverageHeader($filename, $percent) { $filename = basename($filename); + list($file, $ext) = explode('.', $filename); + $display = in_array($file, $this->_testNames) ? 'block' : 'none'; + $primary = $display == 'block' ? 'primary' : ''; return <<

    $filename Code coverage: $percent% @@ -237,6 +278,6 @@ HTML; * @return void */ public function coverageFooter() { - return ""; + return ""; } } \ No newline at end of file diff --git a/cake/tests/lib/templates/header.php b/cake/tests/lib/templates/header.php index 38ad1a624..3a8ac12b0 100644 --- a/cake/tests/lib/templates/header.php +++ b/cake/tests/lib/templates/header.php @@ -79,6 +79,14 @@ display:block; margin-left:10px; } + .coverage-toggle { + float:right; + margin-top:10px; + font-size:12px; + } + .coverage-container { + margin-top:1em; + } div.code-coverage-results div.uncovered span.content { background:#ecc; } div.code-coverage-results div.covered span.content { background:#cec; } div.code-coverage-results div.ignored span.content { color:#aaa; } From cb9d6f478def88c781d6f312bd7758808d2e8b7b Mon Sep 17 00:00:00 2001 From: Mark Story Date: Wed, 12 May 2010 22:13:12 -0400 Subject: [PATCH 051/230] Making coverage reports show what tests covered the line being hovered over. Updating CSS to help facilitate hover effects. --- .../lib/coverage/html_coverage_report.php | 19 ++++++++++++++++--- cake/tests/lib/templates/header.php | 3 +++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php index f4cf26827..1e581f787 100644 --- a/cake/tests/lib/coverage/html_coverage_report.php +++ b/cake/tests/lib/coverage/html_coverage_report.php @@ -190,7 +190,11 @@ HTML; foreach ($fileLines as $lineno => $line) { $class = 'ignored'; + $coveringTests = array(); if (isset($coverageData['covered'][$lineno])) { + $coveringTests = PHPUnit_Util_CodeCoverage::getCoveringTests( + $this->_rawCoverage, $filename, $lineno + ); $class = 'covered'; $covered++; $total++; @@ -200,7 +204,7 @@ HTML; } elseif (isset($coverageData['dead'][$lineno])) { $class .= ' dead'; } - $diff[] = $this->_paintLine($line, $lineno, $class); + $diff[] = $this->_paintLine($line, $lineno, $class, $coveringTests); } $percentCovered = round(100 * $covered / $total, 2); @@ -216,10 +220,19 @@ HTML; * * @return void */ - protected function _paintLine($line, $linenumber, $class) { + protected function _paintLine($line, $linenumber, $class, $coveringTests) { + $coveredBy = ''; + if (!empty($coveringTests)) { + $coveredBy = "Covered by:\n"; + foreach ($coveringTests as &$test) { + $coveredBy .= $test->getName() . "\n"; + } + } + return sprintf( - '
    %s%s
    ', + '
    %s%s
    ', $class, + $coveredBy, $linenumber, htmlspecialchars($line) ); diff --git a/cake/tests/lib/templates/header.php b/cake/tests/lib/templates/header.php index 3a8ac12b0..1ff307050 100644 --- a/cake/tests/lib/templates/header.php +++ b/cake/tests/lib/templates/header.php @@ -90,6 +90,9 @@ div.code-coverage-results div.uncovered span.content { background:#ecc; } div.code-coverage-results div.covered span.content { background:#cec; } div.code-coverage-results div.ignored span.content { color:#aaa; } + div.code-coverage-results div:hover { background:#e8e8e8;} + div.code-coverage-results div.covered:hover span.content { background:#b4edb4;} + div.code-coverage-results div.uncovered:hover span.content { background:#edb4b4;} div.code-coverage-results span.line-num { color:#666; display:block; From d349551dd76dfd788ae0e1ed1902fd10aa8f666d Mon Sep 17 00:00:00 2001 From: Mark Story Date: Wed, 12 May 2010 22:43:44 -0400 Subject: [PATCH 052/230] Adding tests for generating method coverage with the reporter. Adding method visibility --- .../cases/libs/html_coverage_report.test.php | 68 +++++++++++++++++++ .../lib/coverage/html_coverage_report.php | 2 +- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php index 68a5d9262..227205816 100644 --- a/cake/tests/cases/libs/html_coverage_report.test.php +++ b/cake/tests/cases/libs/html_coverage_report.test.php @@ -189,6 +189,74 @@ class HtmlCoverageReportTest extends CakeTestCase { } } +/** + * test that covering methods show up as title attributes for lines. + * + * @return void + */ + function testCoveredLinesTitleAttributes() { + $file = array( + 'line 1', + 'line 2', + 'line 3', + 'line 4', + 'line 5', + ); + $mock = $this->getMock('PHPUnit_Framework_TestCase'); + $mock->expects($this->any())->method('getName')->will($this->returnValue('testAwesomeness')); + + $rawdata = array( + array( + 'test' => $mock, + 'files' => array( + 'myfile.php' => array( + 1 => 1, + 3 => 1, + 4 => 1, + ) + ), + 'executable' => array( + 'myfile.php' => array( + 5 => -1 + ) + ) + ) + ); + + $coverage = array( + 'covered' => array( + 1 => 1, + 3 => 1, + 4 => 1, + ), + 'executable' => array( + 5 => -1, + ), + 'dead' => array( + 2 => -2 + ) + ); + $this->Coverage->setCoverage($rawdata); + $result = $this->Coverage->generateDiff('myfile.php', $file, $coverage); + + $this->assertTrue( + strpos($result, "title=\"Covered by:\ntestAwesomeness\n\">1") !== false, + 'Missing method coverage for line 1' + ); + $this->assertTrue( + strpos($result, "title=\"Covered by:\ntestAwesomeness\n\">3") !== false, + 'Missing method coverage for line 3' + ); + $this->assertTrue( + strpos($result, "title=\"Covered by:\ntestAwesomeness\n\">4") !== false, + 'Missing method coverage for line 4' + ); + $this->assertTrue( + strpos($result, "title=\"\">5") !== false, + 'Coverage report is wrong for line 5' + ); + } + /** * teardown * diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php index 1e581f787..4d778e03e 100644 --- a/cake/tests/lib/coverage/html_coverage_report.php +++ b/cake/tests/lib/coverage/html_coverage_report.php @@ -178,7 +178,7 @@ HTML; * @param array $coverageData Array of coverage data to use to generate HTML diffs with * @return string HTML diff. */ - function generateDiff($filename, $fileLines, $coverageData) { + public function generateDiff($filename, $fileLines, $coverageData) { $output = ''; $diff = array(); $covered = 0; From 17f338a9b22ccbc9b7d58fafd2b3dea2e794d900 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 13 May 2010 00:18:22 -0400 Subject: [PATCH 053/230] Moving methods up into CakeBaseReporter. Starting to make CakeTextReporter work well with PHPUnit so the Text code coverage reporting can be implemented. --- .../tests/lib/reporter/cake_base_reporter.php | 85 ++++++++++++++- .../tests/lib/reporter/cake_html_reporter.php | 102 +----------------- .../tests/lib/reporter/cake_text_reporter.php | 83 ++++++++------ 3 files changed, 141 insertions(+), 129 deletions(-) diff --git a/cake/tests/lib/reporter/cake_base_reporter.php b/cake/tests/lib/reporter/cake_base_reporter.php index d1455462c..643c1ed73 100644 --- a/cake/tests/lib/reporter/cake_base_reporter.php +++ b/cake/tests/lib/reporter/cake_base_reporter.php @@ -26,7 +26,7 @@ PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT'); * @package cake * @subpackage cake.tests.lib */ -class CakeBaseReporter { +class CakeBaseReporter implements PHPUnit_Framework_TestListener { /** * Time the test runs started. @@ -214,5 +214,88 @@ class CakeBaseReporter { return ''; } + public function paintResult(PHPUnit_Framework_TestResult $result) { + $this->paintFooter($result); + } + +/** +* An error occurred. +* +* @param PHPUnit_Framework_Test $test +* @param Exception $e +* @param float $time +*/ + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { + $this->paintException($e); + } + +/** +* A failure occurred. +* +* @param PHPUnit_Framework_Test $test +* @param PHPUnit_Framework_AssertionFailedError $e +* @param float $time +*/ + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { + $this->paintFail($e); + } + +/** +* Incomplete test. +* +* @param PHPUnit_Framework_Test $test +* @param Exception $e +* @param float $time +*/ + public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) { + + } + +/** +* Skipped test. +* +* @param PHPUnit_Framework_Test $test +* @param Exception $e +* @param float $time +*/ + public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { + } + +/** + * A test suite started. + * + * @param PHPUnit_Framework_TestSuite $suite + */ + public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { + echo sprintf(__('Running %s'), $suite->getName()) . "\n"; + } + +/** + * A test suite ended. + * + * @param PHPUnit_Framework_TestSuite $suite + */ + public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { + } + +/** + * A test started. + * + * @param PHPUnit_Framework_Test $test + */ + public function startTest(PHPUnit_Framework_Test $test) { + } + +/** + * A test ended. + * + * @param PHPUnit_Framework_Test $test + * @param float $time + */ + public function endTest(PHPUnit_Framework_Test $test, $time) { + $this->numAssertions += $test->getNumAssertions(); + $this->paintPass($test, $time); + } + } ?> \ No newline at end of file diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 3c4d33548..3206f3153 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -28,7 +28,7 @@ PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT'); * @package cake * @subpackage cake.tests.lib */ -class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_TestListener { +class CakeHtmlReporter extends CakeBaseReporter { /** * Paints the top of the web page setting the @@ -152,7 +152,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes * Paints the end of the test with a summary of * the passes and failures. * - * @param string $test_name Name class of test. + * @param PHPUnit_Framework_TestResult $result Result object * @return void */ public function paintFooter($result) { @@ -161,7 +161,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo "
    "; - echo $result->count() . "/" . $result->count() - $result->skippedCount(); + echo $result->count() . "/" . ($result->count() - $result->skippedCount()); echo " test methods complete:\n"; echo "" . count($result->passed()) . " passes, "; echo "" . $result->failureCount() . " fails, "; @@ -272,9 +272,6 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes echo "
    " . sprintf(__('File: %s'), $context['file']) . "
    \n"; echo "
    " . sprintf(__('Method: %s'), $realContext['function']) . "
    \n"; echo "
    " . sprintf(__('Line: %s'), $context['line']) . "
    \n"; - //$breadcrumb = $this->getTestList(); - //array_shift($breadcrumb); - //echo "
    " . implode(" -> ", $breadcrumb) . "
    \n"; echo "

  • \n"; } @@ -368,104 +365,13 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes return htmlentities($message, ENT_COMPAT, $this->_characterSet); } - public function paintResult(PHPUnit_Framework_TestResult $result) { - - /*if ($result->errorCount() > 0) { - $this->printErrors($result); - } - - if ($result->failureCount() > 0) { - $this->printFailures($result); - } - - if ($result->skippedCount() > 0) { - $this->printIncompletes($result); - } - - if ($result->skippedCount() > 0) { - $this->printSkipped($result); - }*/ - - $this->paintFooter($result); - } - -/** -* An error occurred. -* -* @param PHPUnit_Framework_Test $test -* @param Exception $e -* @param float $time -*/ - public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { - $this->paintException($e); - } - -/** -* A failure occurred. -* -* @param PHPUnit_Framework_Test $test -* @param PHPUnit_Framework_AssertionFailedError $e -* @param float $time -*/ - public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { - $this->paintFail($e); - } - -/** -* Incomplete test. -* -* @param PHPUnit_Framework_Test $test -* @param Exception $e -* @param float $time -*/ - public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) { - - } - -/** -* Skipped test. -* -* @param PHPUnit_Framework_Test $test -* @param Exception $e -* @param float $time -*/ - public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { - } - /** * A test suite started. * * @param PHPUnit_Framework_TestSuite $suite */ public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { - echo '

    ' . sprintf(__('Running %s'), $suite->getName()) . '

    '; - } - -/** - * A test suite ended. - * - * @param PHPUnit_Framework_TestSuite $suite - */ - public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { - } - -/** - * A test started. - * - * @param PHPUnit_Framework_Test $test - */ - public function startTest(PHPUnit_Framework_Test $test) { - } - -/** - * A test ended. - * - * @param PHPUnit_Framework_Test $test - * @param float $time - */ - public function endTest(PHPUnit_Framework_Test $test, $time) { - $this->numAssertions += $test->getNumAssertions(); - $this->paintPass($test, $time); + echo '

    ' . sprintf(__('Running %s'), $suite->getName()) . '

    '; } } ?> \ No newline at end of file diff --git a/cake/tests/lib/reporter/cake_text_reporter.php b/cake/tests/lib/reporter/cake_text_reporter.php index 31cec5c3e..8f32b3c43 100644 --- a/cake/tests/lib/reporter/cake_text_reporter.php +++ b/cake/tests/lib/reporter/cake_text_reporter.php @@ -17,8 +17,11 @@ * @since CakePHP(tm) v 1.3 * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ + include_once dirname(__FILE__) . DS . 'cake_base_reporter.php'; +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT'); + /** * CakeTextReporter contains reporting features used for plain text based output * @@ -33,31 +36,57 @@ class CakeTextReporter extends CakeBaseReporter { * @return void */ public function paintDocumentStart() { - if (!SimpleReporter::inCli()) { - header('Content-type: text/plain'); - } + header('Content-type: text/plain'); + } + +/** + * undocumented function + * + * @return void + */ + public function paintPass() { + + } + +/** + * Paints a failing test. + * + * @param $message PHPUnit_Framework_AssertionFailedError $message Failure object displayed in + * the context of the other tests. + * @return void + */ + public function paintFail($message) { + $context = $message->getTrace(); + $realContext = $context[3]; + $context = $context[2]; + + printf( + "FAIL on line %s\n%s in\n%s %s()\n\n", + $context['line'], $message->toString(), $context['file'], $realContext['function'] + ); } /** * Paints the end of the test with a summary of * the passes and failures. * - * @param string $test_name Name class of test. + * @param PHPUnit_Framework_TestResult $result Result object * @return void */ - public function paintFooter($test_name) { - if ($this->getFailCount() + $this->getExceptionCount() == 0) { + public function paintFooter($result) { + if ($result->failureCount() + $result->errorCount() == 0) { echo "OK\n"; } else { echo "FAILURES!!!\n"; } - echo "Test cases run: " . $this->getTestCaseProgress() . - "/" . $this->getTestCaseCount() . - ", Passes: " . $this->getPassCount() . - ", Failures: " . $this->getFailCount() . - ", Exceptions: " . $this->getExceptionCount() . "\n"; - echo 'Time taken by tests (in seconds): ' . $this->_timeDuration . "\n"; + echo "Test cases run: " . $result->count() . + "/" . ($result->count() - $result->skippedCount()) . + ', Passes: ' . $this->numAssertions . + ', Failures: ' . $result->failureCount() . + ', Exceptions: ' . $result->errorCount() . "\n"; + + echo 'Time taken by tests (in seconds): ' . $result->time() . "\n"; if (function_exists('memory_get_peak_usage')) { echo 'Peak memory use: (in bytes): ' . number_format(memory_get_peak_usage()) . "\n"; } @@ -73,28 +102,11 @@ class CakeTextReporter extends CakeBaseReporter { * @param string $test_name Name class of test. * @return void */ - public function paintHeader($test_name) { + public function paintHeader() { $this->paintDocumentStart(); - echo "$test_name\n"; flush(); } -/** - * Paints the test failure as a stack trace. - * - * @param string $message Failure message displayed in - * the context of the other tests. - * @return void - */ - public function paintFail($message) { - parent::paintFail($message); - echo $this->getFailCount() . ") $message\n"; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - echo "\tin " . implode("\n\tin ", array_reverse($breadcrumb)); - echo "\n"; - } - /** * Paints a PHP error. * @@ -185,5 +197,16 @@ class CakeTextReporter extends CakeBaseReporter { $buffer .= "\n"; echo $buffer; } + +/** + * Generates a Text summary of the coverage data. + * + * @param array $coverage Array of coverage data. + * @return string + */ + public function paintCoverage($coverage) { + return ''; + } + } ?> \ No newline at end of file From c1dc753be5981466450a82175c88c536ff23d4e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Thu, 13 May 2010 00:08:35 -0430 Subject: [PATCH 054/230] Replacing call of static:: for self as it is php 5.3 specific --- cake/tests/lib/test_manager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 3b1e82520..9478246a5 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -344,7 +344,7 @@ class TestManager { * @static */ protected static function _isTestGroupFile($file) { - return static::_hasExpectedExtension($file, static::$_groupExtension); + return self::_hasExpectedExtension($file, self::$_groupExtension); } /** From 6613cfb662d77a6baca07d057485e3d0da32e7c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Thu, 13 May 2010 00:13:40 -0430 Subject: [PATCH 055/230] Migrating CacheTest to phpunit --- cake/tests/cases/libs/cache.test.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cake/tests/cases/libs/cache.test.php b/cake/tests/cases/libs/cache.test.php index 4b44e0ee5..7afb181e3 100644 --- a/cake/tests/cases/libs/cache.test.php +++ b/cake/tests/cases/libs/cache.test.php @@ -21,8 +21,6 @@ if (!class_exists('Cache')) { require LIBS . 'cache.php'; } -Mock::generate('StdClass', 'RubbishEngine'); - /** * CacheTest class * @@ -139,6 +137,7 @@ class CacheTest extends CakeTestCase { * @return void */ function testAttemptingToConfigureANonCacheEngineClass() { + $this->getMock('StdClass', array(), array(), 'RubbishEngine'); $this->expectException(); Cache::config('Garbage', array( 'engine' => 'Rubbish' From 72959e787224e3bf4ee395909a5d7fad188c2ede Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Thu, 13 May 2010 00:21:16 -0430 Subject: [PATCH 056/230] Converting CAkeSessionTest to phpunit --- cake/tests/cases/libs/cake_session.test.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cake/tests/cases/libs/cake_session.test.php b/cake/tests/cases/libs/cake_session.test.php index dedc888da..1ef290b2f 100644 --- a/cake/tests/cases/libs/cake_session.test.php +++ b/cake/tests/cases/libs/cake_session.test.php @@ -222,7 +222,7 @@ class CakeSessionTest extends CakeTestCase { $this->Session->write('Watching', "I'm watching you"); $this->Session->watch('Watching'); - $this->expectError('Writing session key {Watching}: "They found us!"'); + $this->expectError(); $this->Session->write('Watching', 'They found us!'); $this->expectError('Deleting session key {Watching}'); @@ -386,7 +386,7 @@ class CakeSessionTest extends CakeTestCase { $this->assertEqual($this->Session->read('SessionTestCase'), 'This was updated'); $this->Session->destroy(); - $this->assertFalse($this->Session->read('SessionTestCase')); + $this->assertNull($this->Session->read('SessionTestCase')); } /** @@ -423,7 +423,7 @@ class CakeSessionTest extends CakeTestCase { $this->assertEqual($this->Session->read('SessionTestCase'), 'This was updated'); $this->Session->destroy(); - $this->assertFalse($this->Session->read('SessionTestCase')); + $this->assertNull($this->Session->read('SessionTestCase')); } /** @@ -461,7 +461,7 @@ class CakeSessionTest extends CakeTestCase { $this->assertEqual($this->Session->read('SessionTestCase'), 'Some additional data'); $this->Session->destroy(); - $this->assertFalse($this->Session->read('SessionTestCase')); + $this->assertNull($this->Session->read('SessionTestCase')); session_write_close(); unset($_SESSION); From 01e36ce2c48fb59e86ba9d44915fe403f91336a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Thu, 13 May 2010 00:48:03 -0430 Subject: [PATCH 057/230] Improving compatobility method detection in paintError, so the failing line and method is correctly pointed out in the reporter --- cake/tests/lib/reporter/cake_html_reporter.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index 9f6f8eea7..ff128bc2f 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -264,7 +264,13 @@ class CakeHtmlReporter extends CakeBaseReporter { public function paintFail($message) { $context = $message->getTrace(); $realContext = $context[3]; - $context = $context[2]; + $class = new ReflectionClass($realContext['class']); + if ($class->getParentClass()->getName() === 'PHPUnit_Framework_TestCase') { + $realContext = $context[4]; + $context = $context[3]; + } else { + $context = $context[2]; + } echo "
  • \n"; echo "Failed"; From f3f37a126fa72edd21594dd4a21ef55c4ad26250 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Thu, 13 May 2010 00:50:30 -0430 Subject: [PATCH 058/230] Converting CakeSocketTest to phpunit --- cake/tests/cases/libs/cake_socket.test.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cake/tests/cases/libs/cake_socket.test.php b/cake/tests/cases/libs/cake_socket.test.php index 79eb37e85..0b5a0e52e 100644 --- a/cake/tests/cases/libs/cake_socket.test.php +++ b/cake/tests/cases/libs/cake_socket.test.php @@ -131,7 +131,7 @@ class CakeSocketTest extends CakeTestCase { */ function testSocketWriting() { $request = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n"; - $this->assertTrue($this->Socket->write($request)); + $this->assertTrue((bool)$this->Socket->write($request)); } /** From 689e46be4ff2ebe77b692732f9c7ab3ab42ad9f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Thu, 13 May 2010 00:52:38 -0430 Subject: [PATCH 059/230] Converting ConfigureTest to phpunit --- cake/tests/cases/libs/configure.test.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cake/tests/cases/libs/configure.test.php b/cake/tests/cases/libs/configure.test.php index 8b7499d43..3f4bb6112 100644 --- a/cake/tests/cases/libs/configure.test.php +++ b/cake/tests/cases/libs/configure.test.php @@ -648,14 +648,14 @@ class AppImportTest extends CakeTestCase { */ function testFileLoadingReturnValue () { $file = App::import('File', 'Name', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php', true); - $this->assertTrue($file); + $this->assertTrue(!empty($file)); $this->assertTrue(isset($file['Cake.version'])); $type = array('type' => 'File', 'name' => 'OtherName', 'parent' => false, 'file' => TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php', 'return' => true); $file = App::import($type); - $this->assertTrue($file); + $this->assertTrue(!empty($file)); $this->assertTrue(isset($file['Cake.version'])); } From db4f7a2625c979206046cd6004a858125e3e9fad Mon Sep 17 00:00:00 2001 From: Juan Basso Date: Thu, 13 May 2010 18:48:34 -0300 Subject: [PATCH 060/230] Fixing search of test cases and groups for PHP 5.2. --- cake/tests/lib/test_manager.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index 9478246a5..42db7a6c6 100644 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -252,7 +252,7 @@ class TestManager { * @static */ protected static function &_getTestFileList($directory = '.') { - $return = self::_getRecursiveFileList($directory, 'self::_isTestCaseFile'); + $return = self::_getRecursiveFileList($directory, array('self', '_isTestCaseFile')); return $return; } @@ -274,7 +274,7 @@ class TestManager { * @static */ protected static function &_getTestGroupFileList($directory = '.') { - $return = self::_getRecursiveFileList($directory, 'self::_isTestGroupFile'); + $return = self::_getRecursiveFileList($directory, array('self', '_isTestGroupFile')); return $return; } From 5e29cfc21e0ffd20ebfee790ddf41520da1ab2f7 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 13 May 2010 21:36:23 -0400 Subject: [PATCH 061/230] Adding TextCoverageReport and extracting a base class. Updating the coverage classes to use the new class structure. --- .../lib/coverage/base_coverage_report.php | 175 ++++++++++++++++++ .../lib/coverage/html_coverage_report.php | 133 +------------ .../lib/coverage/text_coverage_report.php | 74 ++++++++ .../tests/lib/reporter/cake_text_reporter.php | 6 +- 4 files changed, 258 insertions(+), 130 deletions(-) create mode 100644 cake/tests/lib/coverage/base_coverage_report.php create mode 100644 cake/tests/lib/coverage/text_coverage_report.php diff --git a/cake/tests/lib/coverage/base_coverage_report.php b/cake/tests/lib/coverage/base_coverage_report.php new file mode 100644 index 000000000..5ef10a64e --- /dev/null +++ b/cake/tests/lib/coverage/base_coverage_report.php @@ -0,0 +1,175 @@ +_rawCoverage = $coverage; + $this->setParams($reporter); + } + +/** + * Pulls params out of the reporter. + * + * @param CakeBaseReporter $reporter Reporter to suck params out of. + * @return void + */ + protected function setParams(CakeBaseReporter $reporter) { + if ($reporter->params['app']) { + $this->appTest = true; + } + if ($reporter->params['group']) { + $this->groupTest = true; + } + if ($reporter->params['plugin']) { + $this->pluginTest = Inflector::underscore($reporter->params['plugin']); + } + } + +/** + * Set the coverage data array + * + * @param array $coverage Coverage data to use. + * @return void + */ + public function setCoverage($coverage) { + $this->_rawCoverage = $coverage; + } + +/** + * Gets the base path that the files we are interested in live in. + * If appTest ist + * + * @return void + */ + public function getPathFilter() { + $path = ROOT . DS; + if ($this->appTest) { + $path .= APP_DIR . DS; + } elseif ($this->pluginTest) { + $path = App::pluginPath($this->pluginTest); + } else { + $path = TEST_CAKE_CORE_INCLUDE_PATH; + } + return $path; + } + +/** + * Filters the coverage data by path. Files not in the provided path will be removed. + * This method will merge all the various test run reports as well into a single report per file. + * + * @param string $path Path to filter files by. + * @return array Array of coverage data for files that match the given path. + */ + public function filterCoverageDataByPath($path) { + $files = array(); + foreach ($this->_rawCoverage as $testRun) { + foreach ($testRun['files'] as $filename => $fileCoverage) { + if (strpos($filename, $path) !== 0) { + continue; + } + $dead = isset($testRun['dead'][$filename]) ? $testRun['dead'][$filename] : array(); + $executable = isset($testRun['executable'][$filename]) ? $testRun['executable'][$filename] : array(); + + if (!isset($files[$filename])) { + $files[$filename] = array( + 'covered' => array(), + 'dead' => array(), + 'executable' => array() + ); + } + $files[$filename]['covered'] += $fileCoverage; + $files[$filename]['executable'] += $executable; + $files[$filename]['dead'] += $dead; + } + if (isset($testRun['test'])) { + $testReflection = new ReflectionClass(get_class($testRun['test'])); + list($fileBasename, $x) = explode('.', basename($testReflection->getFileName()), 2); + $this->_testNames[] = $fileBasename; + } + } + ksort($files); + return $files; + } + +/** + * Generates report to display. + * + * @return string compiled html report. + */ + abstract public function report(); + +/** + * Generates an coverage 'diff' for $file based on $coverageData. + * + * @param string $filename Name of the file having coverage generated + * @param array $fileLines File data as an array. See file() for how to get one of these. + * @param array $coverageData Array of coverage data to use to generate HTML diffs with + * @return string prepared report for a single file. + */ + abstract public function generateDiff($filename, $fileLines, $coverageData); + +} \ No newline at end of file diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php index 4d778e03e..c173aa068 100644 --- a/cake/tests/lib/coverage/html_coverage_report.php +++ b/cake/tests/lib/coverage/html_coverage_report.php @@ -17,79 +17,11 @@ * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ -class HtmlCoverageReport { -/** - * coverage data - * - * @var string - */ - protected $_rawCoverage; +require_once dirname(__FILE__) . '/base_coverage_report.php'; -/** - * is the test an app test - * - * @var string - */ - public $appTest = false; +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT'); -/** - * is the test a plugin test - * - * @var string - */ - public $pluginTest = false; - -/** - * is the test a group test? - * - * @var string - */ - public $groupTest = false; - -/** - * Array of test case file names. Used to do basename() matching with - * files that have coverage to decide which results to show on page load. - * - * @var array - */ - protected $_testNames = array(); - -/** - * Constructor - * - * @param array $coverage Array of coverage data from PHPUnit_Test_Result - * @return void - */ - public function __construct($coverage, CakeBaseReporter $reporter) { - $this->_rawCoverage = $coverage; - $this->setParams($reporter); - } - -/** - * Pulls params out of the reporter. - * - * @return void - */ - protected function setParams(CakeBaseReporter $reporter) { - if ($reporter->params['app']) { - $this->appTest = true; - } - if ($reporter->params['group']) { - $this->groupTest = true; - } - if ($reporter->params['plugin']) { - $this->pluginTest = Inflector::underscore($reporter->params['plugin']); - } - } - -/** - * Set the coverage data array - * - * @return void - */ - public function setCoverage($coverage) { - $this->_rawCoverage = $coverage; - } +class HtmlCoverageReport extends BaseCoverageReport { /** * Generates report html to display. @@ -115,66 +47,11 @@ HTML; return $output; } -/** - * Gets the base path that the files we are interested in live in. - * If appTest ist - * - * @return void - */ - public function getPathFilter() { - $path = ROOT . DS; - if ($this->appTest) { - $path .= APP_DIR . DS; - } elseif ($this->pluginTest) { - $path = App::pluginPath($this->pluginTest); - } else { - $path = TEST_CAKE_CORE_INCLUDE_PATH; - } - return $path; - } - -/** - * Filters the coverage data by path. Files not in the provided path will be removed. - * This method will merge all the various test run reports as well into a single report per file. - * - * @param string $path Path to filter files by. - * @return array Array of coverage data for files that match the given path. - */ - public function filterCoverageDataByPath($path) { - $files = array(); - foreach ($this->_rawCoverage as $testRun) { - foreach ($testRun['files'] as $filename => $fileCoverage) { - if (strpos($filename, $path) !== 0) { - continue; - } - $dead = isset($testRun['dead'][$filename]) ? $testRun['dead'][$filename] : array(); - $executable = isset($testRun['executable'][$filename]) ? $testRun['executable'][$filename] : array(); - - if (!isset($files[$filename])) { - $files[$filename] = array( - 'covered' => array(), - 'dead' => array(), - 'executable' => array() - ); - } - $files[$filename]['covered'] += $fileCoverage; - $files[$filename]['executable'] += $executable; - $files[$filename]['dead'] += $dead; - } - if (isset($testRun['test'])) { - $testReflection = new ReflectionClass(get_class($testRun['test'])); - list($fileBasename, $x) = explode('.', basename($testReflection->getFileName()), 2); - $this->_testNames[] = $fileBasename; - } - } - ksort($files); - return $files; - } - /** * Generates an HTML diff for $file based on $coverageData. * - * @param array $fileData File data as an array. See file() for how to get one of these. + * @param string $filename Name of the file having coverage generated + * @param array $fileLines File data as an array. See file() for how to get one of these. * @param array $coverageData Array of coverage data to use to generate HTML diffs with * @return string HTML diff. */ diff --git a/cake/tests/lib/coverage/text_coverage_report.php b/cake/tests/lib/coverage/text_coverage_report.php new file mode 100644 index 000000000..bfe406b1b --- /dev/null +++ b/cake/tests/lib/coverage/text_coverage_report.php @@ -0,0 +1,74 @@ +getPathFilter(); + $coverageData = $this->filterCoverageDataByPath($pathFilter); + if (empty($coverageData)) { + return 'No files to generate coverage for'; + } + $output = "\nCoverage Report:\n\n"; + foreach ($coverageData as $file => $coverageData) { + $fileData = file($file); + $output .= $this->generateDiff($file, $fileData, $coverageData); + } + return $output; + } + +/** + * Generates a 'diff' report for a file. + * Since diffs are too big for plain text reports a simple file => % covered is done. + * + * @param string $filename Name of the file having coverage generated + * @param array $fileLines File data as an array. See file() for how to get one of these. + * @param array $coverageData Array of coverage data to use to generate HTML diffs with + * @return string + */ + public function generateDiff($filename, $fileLines, $coverageData) { + $covered = 0; + $total = 0; + + //shift line numbers forward one; + array_unshift($fileLines, ' '); + unset($fileLines[0]); + + foreach ($fileLines as $lineno => $line) { + if (isset($coverageData['covered'][$lineno])) { + $covered++; + $total++; + } elseif (isset($coverageData['executable'][$lineno])) { + $total++; + } + } + $percentCovered = round(100 * $covered / $total, 2); + return "$filename : $percentCovered%\n"; + } + +} \ No newline at end of file diff --git a/cake/tests/lib/reporter/cake_text_reporter.php b/cake/tests/lib/reporter/cake_text_reporter.php index 8f32b3c43..65eb03ed9 100644 --- a/cake/tests/lib/reporter/cake_text_reporter.php +++ b/cake/tests/lib/reporter/cake_text_reporter.php @@ -205,8 +205,10 @@ class CakeTextReporter extends CakeBaseReporter { * @return string */ public function paintCoverage($coverage) { - return ''; + $file = dirname(dirname(__FILE__)) . '/coverage/text_coverage_report.php'; + include $file; + $reporter = new TextCoverageReport($coverage, $this); + echo $reporter->report(); } } -?> \ No newline at end of file From 9303de936e4b058a578ea8cafd80cf49261c14e2 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 13 May 2010 21:44:30 -0400 Subject: [PATCH 062/230] Fixing fatal error trying to run coverage on the coverage reporter. Removing old CodeCoverageManager implementation. --- .../cases/libs/code_coverage_manager.test.php | 512 ----------- cake/tests/lib/code_coverage_manager.php | 801 ------------------ .../tests/lib/reporter/cake_html_reporter.php | 2 +- 3 files changed, 1 insertion(+), 1314 deletions(-) delete mode 100644 cake/tests/cases/libs/code_coverage_manager.test.php delete mode 100644 cake/tests/lib/code_coverage_manager.php diff --git a/cake/tests/cases/libs/code_coverage_manager.test.php b/cake/tests/cases/libs/code_coverage_manager.test.php deleted file mode 100644 index 80104ef2d..000000000 --- a/cake/tests/cases/libs/code_coverage_manager.test.php +++ /dev/null @@ -1,512 +0,0 @@ - - * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The Open Group Test Suite License - * Redistributions of files must retain the above copyright notice. - * - * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests - * @package cake - * @subpackage cake.tests.cases.libs - * @since CakePHP(tm) v 1.2.0.4206 - * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License - */ -require_once CAKE . 'tests' . DS . 'lib' . DS . 'code_coverage_manager.php'; -require_once CAKE . 'tests' . DS . 'lib' . DS . 'reporter' . DS . 'cake_cli_reporter.php'; - -/** - * CodeCoverageManagerTest class - * - * @package cake - * @subpackage cake.tests.cases.libs - */ -class CodeCoverageManagerTest extends CakeTestCase { - -/** - * Skip if XDebug not installed - * - */ - public function skip() { - $this->skipIf(!extension_loaded('xdebug'), '%s XDebug not installed'); - } - -/** - * startTest Method - * Store reference of $_GET to restore later. - * - * @return void - */ - function startCase() { - $this->_get = $_GET; - } - -/** - * End Case - restore GET vars. - * - * @return void - */ - function endCase() { - $_GET = $this->_get; - } - -/** - * testNoTestCaseSupplied method - * - * @access public - * @return void - */ - function testNoTestCaseSupplied() { - if ($this->skipIf(PHP_SAPI == 'cli', 'Is cli, cannot run this test %s')) { - return; - } - $reporter =& new CakeHtmlReporter(null, array('group' => false, 'app' => false, 'plugin' => false)); - - CodeCoverageManager::init(substr(md5(microtime()), 0, 5), $reporter); - CodeCoverageManager::report(false); - $this->assertError(); - - CodeCoverageManager::init('tests' . DS . 'lib' . DS . basename(__FILE__), $reporter); - CodeCoverageManager::report(false); - $this->assertError(); - } - -/** - * Test that test cases don't cause errors - * - * @return void - */ - function testNoTestCaseSuppliedNoErrors() { - if ($this->skipIf(PHP_SAPI == 'cli', 'Is cli, cannot run this test %s')) { - return; - } - $reporter =& new CakeHtmlReporter(null, array('group' => false, 'app' => false, 'plugin' => false)); - $path = LIBS; - if (strpos(LIBS, ROOT) === false) { - $path = ROOT.DS.LIBS; - } - App::import('Core', 'Folder'); - $folder = new Folder(); - $folder->cd($path); - $contents = $folder->read(); - - $contents[1] = array_filter($contents[1], array(&$this, '_basenameFilter')); - - foreach ($contents[1] as $file) { - CodeCoverageManager::init('libs' . DS . $file, $reporter); - CodeCoverageManager::report(false); - $this->assertNoErrors('libs' . DS . $file); - } - } - -/** - * Remove file names that don't share a basename with the current file. - * - * @return void - */ - function _basenameFilter($var) { - return ($var != basename(__FILE__)); - } - -/** - * testGetTestObjectFileNameFromTestCaseFile method - * - * @access public - * @return void - */ - function testGetTestObjectFileNameFromTestCaseFile() { - $manager =& CodeCoverageManager::getInstance(); - $manager->reporter = new CakeHtmlReporter(); - - $expected = $manager->__testObjectFileFromCaseFile('models/some_file.test.php', true); - $this->assertIdentical(APP.'models'.DS.'some_file.php', $expected); - - $expected = $manager->__testObjectFileFromCaseFile('models/datasources/some_file.test.php', true); - $this->assertIdentical(APP.'models'.DS.'datasources'.DS.'some_file.php', $expected); - - $expected = $manager->__testObjectFileFromCaseFile('controllers/some_file.test.php', true); - $this->assertIdentical(APP.'controllers'.DS.'some_file.php', $expected); - - $expected = $manager->__testObjectFileFromCaseFile('views/some_file.test.php', true); - $this->assertIdentical(APP.'views'.DS.'some_file.php', $expected); - - $expected = $manager->__testObjectFileFromCaseFile('behaviors/some_file.test.php', true); - $this->assertIdentical(APP.'models'.DS.'behaviors'.DS.'some_file.php', $expected); - - $expected = $manager->__testObjectFileFromCaseFile('components/some_file.test.php', true); - $this->assertIdentical(APP.'controllers'.DS.'components'.DS.'some_file.php', $expected); - - $expected = $manager->__testObjectFileFromCaseFile('helpers/some_file.test.php', true); - $this->assertIdentical(APP.'views'.DS.'helpers'.DS.'some_file.php', $expected); - - $manager->pluginTest = 'bugs'; - $expected = $manager->__testObjectFileFromCaseFile('models/some_file.test.php', false); - $this->assertIdentical(APP.'plugins'.DS.'bugs'.DS.'models'.DS.'some_file.php', $expected); - - $manager->pluginTest = false; - $manager->reporter = new CakeCliReporter; - $expected = $manager->__testObjectFileFromCaseFile('libs/set.test.php', false); - $this->assertIdentical(ROOT.DS.'cake'.DS.'libs'.DS.'set.php', $expected); - } - -/** - * testOfHtmlDiffReport method - * - * @access public - * @return void - */ - function testOfHtmlDiffReport() { - $manager =& CodeCoverageManager::getInstance(); - $code = <<value = func_get_arg(0); - } else { - \$this->value = func_get_args(); - } - } - -/** - * Returns the contents of the Set object - * - * @return array - */ - public function &get() { - return \$this->value; - } - -/** - * This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive. The difference - * to the two is that if an array key contains another array then the function behaves recursive (unlike array_merge) - * but does not do if for keys containing strings (unlike array_merge_recursive). See the unit test for more information. - * - * Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays. - * - * @param array \$arr1 Array to be merged - * @param array \$arr2 Array to merge with - * @return array Merged array - */ - public function merge(\$arr1, \$arr2 = null) { - \$args = func_get_args(); - - if (isset(\$this) && is_a(\$this, 'set')) { - \$backtrace = debug_backtrace(); - \$previousCall = strtolower(\$backtrace[1]['class'].'::'.\$backtrace[1]['function']); - if (\$previousCall != 'set::merge') { - \$r =& \$this->value; - array_unshift(\$args, null); - } - } - if (!isset(\$r)) { - \$r = (array)current(\$args); - } - - while ((\$arg = next(\$args)) !== false) { - if (is_a(\$arg, 'set')) { - \$arg = \$arg->get(); - } - - foreach ((array)\$arg as \$key => \$val) { - if (is_array(\$val) && isset(\$r[\$key]) && is_array(\$r[\$key])) { - \$r[\$key] = Set::merge(\$r[\$key], \$val); - } elseif (is_int(\$key)) { - - } else { - \$r[\$key] = \$val; - } - } - } - return \$r; - } -PHP; - - $testObjectFile = explode("\n", $code); - $coverageData = array( - 0 => 1, - 1 => 1, - 2 => -2, - 3 => -2, - 4 => -2, - 5 => -2, - 6 => -2, - 7 => -2, - 8 => -1, - 9 => -2, - 10 => -2, - 11 => -2, - 12 => -2, - 13 => -2, - 14 => 1, - 15 => 1, - 16 => -1, - 17 => 1, - 18 => 1, - 19 => -1, - 20 => 1, - 21 => -2, - 22 => -2, - 23 => -2, - 24 => -2, - 25 => -2, - 26 => -2, - 27 => 1, - 28 => -1, - 29 => 1, - 30 => 1, - 31 => -2, - 32 => -2, - 33 => -2, - 34 => -2, - 35 => -2, - 36 => -2, - 37 => -2, - 38 => -2, - 39 => -2, - 40 => -2, - 41 => -2, - 42 => -2, - 43 => -1, - 44 => -2, - 45 => -2, - 46 => -2, - 47 => -2, - 48 => 1, - 49 => 1, - 50 => -1, - 51 => 1, - 52 => 1, - 53 => -2, - 54 => -2, - 55 => 1, - 56 => 1, - 57 => 1, - 58 => 1, - 59 => -1, - 60 => 1, - 61 => 1, - 62 => -2, - 63 => -2, - 64 => 1, - 65 => -2, - 66 => 1, - 67 => -1, - 68 => -2, - 69 => -1, - 70 => -1, - 71 => 1, - 72 => -2, - ); - $expected = array( - 0 => 'ignored', - 1 => 'ignored', - 2 => 'ignored', - 3 => 'ignored', - 4 => 'ignored', - 5 => 'ignored show start realstart', - 6 => 'ignored show', - 7 => 'ignored show', - 8 => 'uncovered show', - 9 => 'ignored show', - 10 => 'ignored show', - 11 => 'ignored show end', - 12 => 'ignored', - 13 => 'ignored show start', - 14 => 'covered show', - 15 => 'covered show', - 16 => 'uncovered show', - 17 => 'covered show show', - 18 => 'covered show show', - 19 => 'uncovered show', - 20 => 'covered show', - 21 => 'ignored show', - 22 => 'ignored show end', - 23 => 'ignored', - 24 => 'ignored', - 25 => 'ignored show start', - 26 => 'ignored show', - 27 => 'covered show', - 28 => 'uncovered show', - 29 => 'covered show', - 30 => 'covered show', - 31 => 'ignored show end', - 32 => 'ignored', - 33 => 'ignored', - 34 => 'ignored', - 35 => 'ignored', - 36 => 'ignored', - 37 => 'ignored', - 38 => 'ignored', - 39 => 'ignored', - 40 => 'ignored show start', - 41 => 'ignored show', - 42 => 'ignored show', - 43 => 'uncovered show', - 41 => 'ignored show', - 42 => 'ignored show', - 43 => 'uncovered show', - 44 => 'ignored show', - 45 => 'ignored show', - 46 => 'ignored show', - 47 => 'ignored show', - 48 => 'covered show', - 49 => 'covered show', - 50 => 'uncovered show', - 51 => 'covered show', - 52 => 'covered show', - 53 => 'ignored show end', - 54 => 'ignored', - 55 => 'covered', - 56 => 'covered show start', - 57 => 'covered show', - 58 => 'covered show', - 59 => 'uncovered show', - 60 => 'covered show', - 61 => 'covered show', - 62 => 'ignored show end', - 63 => 'ignored', - 64 => 'covered show start', - 65 => 'ignored show', - 66 => 'covered show show', - 67 => 'uncovered show', - 68 => 'ignored show', - 69 => 'uncovered show', - 70 => 'uncovered show', - 71 => 'covered show', - 72 => 'ignored show', - 73 => 'ignored show end end', - ); - $execCodeLines = range(0, 72); - $result = explode("", $report = $manager->reportCaseHtmlDiff($testObjectFile, $coverageData, $execCodeLines, 3)); - - foreach ($result as $line) { - preg_match('/(.*?)<\/span>/', $line, $matches); - if (!isset($matches[1])) { - continue; - } - - $num = $matches[1]; - $class = $expected[$num]; - $pattern = '/
    /'; - $this->assertPattern($pattern, $line, $num.': '.$line." fails"); - } - } - -/** - * testArrayStrrpos method - * - * @access public - * @return void - */ - function testArrayStrrpos() { - $manager =& CodeCoverageManager::getInstance(); - - $a = array( - 'apples', - 'bananas', - 'oranges' - ); - $this->assertEqual(1, $manager->__array_strpos($a, 'ba', true)); - $this->assertEqual(2, $manager->__array_strpos($a, 'range', true)); - $this->assertEqual(0, $manager->__array_strpos($a, 'pp', true)); - $this->assertFalse($manager->__array_strpos('', 'ba', true)); - $this->assertFalse($manager->__array_strpos(false, 'ba', true)); - $this->assertFalse($manager->__array_strpos(array(), 'ba', true)); - - $a = array( - 'rang', - 'orange', - 'oranges' - ); - $this->assertEqual(0, $manager->__array_strpos($a, 'rang')); - $this->assertEqual(2, $manager->__array_strpos($a, 'rang', true)); - $this->assertEqual(1, $manager->__array_strpos($a, 'orange', false)); - $this->assertEqual(1, $manager->__array_strpos($a, 'orange')); - $this->assertEqual(2, $manager->__array_strpos($a, 'orange', true)); - } - -/** - * testGetExecutableLines method - * - * @access public - * @return void - */ - function testGetExecutableLines() { - $manager =& CodeCoverageManager::getInstance(); - $code = <<__getExecutableLines($code); - foreach ($result as $line) { - $this->assertNotIdentical($line, ''); - } - - $code = << - ?> - __getExecutableLines($code); - foreach ($result as $line) { - $this->assertIdentical(trim($line), ''); - } - } - -/** - * testCalculateCodeCoverage method - * - * @access public - * @return void - */ - function testCalculateCodeCoverage() { - $manager =& CodeCoverageManager::getInstance(); - $data = array( - '25' => array(100, 25), - '50' => array(100, 50), - '0' => array(0, 0), - '0' => array(100, 0), - '100' => array(100, 100), - ); - foreach ($data as $coverage => $lines) { - $this->assertEqual($coverage, $manager->__calcCoverage($lines[0], $lines[1])); - } - - $manager->__calcCoverage(100, 1000); - $this->assertError(); - } -} diff --git a/cake/tests/lib/code_coverage_manager.php b/cake/tests/lib/code_coverage_manager.php deleted file mode 100644 index b7088597a..000000000 --- a/cake/tests/lib/code_coverage_manager.php +++ /dev/null @@ -1,801 +0,0 @@ - - * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) - * - * Licensed under The Open Group Test Suite License - * Redistributions of files must retain the above copyright notice. - * - * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org) - * @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests - * @package cake - * @subpackage cake.cake.tests.lib - * @since CakePHP(tm) v 1.2.0.4433 - * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License - */ -App::import('Core', 'Folder'); - -/** - * Short description for class. - * - * @package cake - * @subpackage cake.cake.tests.lib - */ -class CodeCoverageManager { - -/** - * Is this an app test case? - * - * @var string - */ - public $appTest = false; - -/** - * Is this an app test case? - * - * @var string - */ - public $pluginTest = false; - -/** - * Is this a grouptest? - * - * @var string - * @access public - */ - public $groupTest = false; - -/** - * The test case file to analyze - * - * @var string - */ - public $testCaseFile = ''; - -/** - * The currently used CakeTestReporter - * - * @var string - */ - public $reporter = ''; - -/** - * undocumented variable - * - * @var string - */ - public $numDiffContextLines = 7; - -/** - * Returns a singleton instance - * - * @return object - */ - public static function &getInstance() { - static $instance = array(); - if (!$instance) { - $instance[0] =& new CodeCoverageManager(); - } - return $instance[0]; - } - -/** - * Initializes a new Coverage Analyzation for a given test case file - * - * @param string $testCaseFile The test case file being covered. - * @param object $reporter Instance of the reporter running. - * @return void - * @static - */ - public static function init($testCaseFile, &$reporter) { - $manager = CodeCoverageManager::getInstance(); - $manager->reporter =& $reporter; - $testCaseFile = str_replace(DS . DS, DS, $testCaseFile); - $thisFile = str_replace('.php', '.test.php', basename(__FILE__)); - - if (strpos($testCaseFile, $thisFile) !== false) { - trigger_error(__('Xdebug supports no parallel coverage analysis - so this is not possible.', true), E_USER_ERROR); - } - $manager->setParams($reporter); - $manager->testCaseFile = $testCaseFile; - } - -/** - * Start/resume Code coverage collection. - * - * @return void - * @static - */ - public static function start() { - xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); - } - -/** - * Stops/pauses code coverage collection. Does not clean the - * code coverage memory. Use clean() to clear code coverage memory - * - * @return void - * @static - */ - public static function stop() { - xdebug_stop_code_coverage(false); - } - -/** - * Clears the existing code coverage information. Also stops any - * running collection. - * - * @return void - * @static - */ - public static function clear() { - xdebug_stop_code_coverage(); - } - -/** - * Set the parameters from a reporter to the CodeCoverageManager - * - * @return void - */ - public static function setParams(&$reporter) { - if ($reporter->params['app']) { - $this->appTest = true; - } - - if ($reporter->params['group']) { - $this->groupTest = true; - } - - if ($reporter->params['plugin']) { - $this->pluginTest = Inflector::underscore($reporter->params['plugin']); - } - } - -/** - * Stops the current code coverage analyzation and dumps a nice report - * depending on the reporter that was passed to start() - * - * @return void - * @static - */ - public static function report($output = true) { - $manager = CodeCoverageManager::getInstance(); - - CodeCoverageManager::stop(); - CodeCoverageManager::clear(); - - list($coverageData, $testObjectFile) = $manager->_getCoverageData(); - - if (empty($coverageData) && $output) { - echo "The test object file is never loaded.\n"; - } - - if (!$manager->groupTest) { - $execCodeLines = $manager->__getExecutableLines(file_get_contents($testObjectFile)); - $result = ''; - - switch (get_class($manager->reporter)) { - case 'CakeHtmlReporter': - $result = $manager->reportCaseHtmlDiff(@file($testObjectFile), $coverageData, $execCodeLines, $manager->numDiffContextLines); - break; - case 'CakeCliReporter': - default: - $result = $manager->reportCaseCli(@file($testObjectFile), $coverageData, $execCodeLines, $manager->numDiffContextLines); - break; - } - } else { - $execCodeLines = $manager->__getExecutableLines($testObjectFile); - $result = ''; - - switch (get_class($manager->reporter)) { - case 'CakeHtmlReporter': - $result = $manager->reportGroupHtml($testObjectFile, $coverageData, $execCodeLines, $manager->numDiffContextLines); - break; - case 'CakeCliReporter': - default: - $result = $manager->reportGroupCli($testObjectFile, $coverageData, $execCodeLines, $manager->numDiffContextLines); - break; - } - } - - if ($output) { - echo $result; - } - } - -/** - * Gets the coverage data for the test case or group test that is being run. - * - * @return void - */ - protected function _getCoverageData() { - $coverageData = array(); - $dump = xdebug_get_code_coverage(); - - if ($this->groupTest) { - $testObjectFile = $this->__testObjectFilesFromGroupFile($this->testCaseFile, $this->appTest); - foreach ($testObjectFile as $file) { - if (!file_exists($file)) { - trigger_error(sprintf(__('This test object file is invalid: %s', true), $file)); - return ; - } - } - foreach ($testObjectFile as $file) { - if (isset($dump[$file])) { - $coverageData[$file] = $dump[$file]; - } - } - } else { - $testObjectFile = $this->__testObjectFileFromCaseFile($this->testCaseFile, $this->appTest); - - if (!file_exists($testObjectFile)) { - trigger_error(sprintf(__('This test object file is invalid: %s', true), $testObjectFile)); - return ; - } - - if (isset($dump[$testObjectFile])) { - $coverageData = $dump[$testObjectFile]; - } - } - return array($coverageData, $testObjectFile); - } - -/** - * Diff reporting - * - * @param string $testObjectFile - * @param string $coverageData - * @param string $execCodeLines - * @param string $output - * @return void - * @static - */ - public static function reportCaseHtmlDiff($testObjectFile, $coverageData, $execCodeLines, $numContextLines) { - $manager = CodeCoverageManager::getInstance(); - $total = count($testObjectFile); - $lines = array(); - - for ($i = 1; $i < $total + 1; $i++) { - $foundByManualFinder = isset($execCodeLines[$i]) && trim($execCodeLines[$i]) != ''; - $foundByXdebug = isset($coverageData[$i]); - - if (!$foundByManualFinder || !$foundByXdebug || $coverageData[$i] === -2) { - if (isset($lines[$i])) { - $lines[$i] = 'ignored ' . $lines[$i]; - } else { - $lines[$i] = 'ignored'; - } - continue; - } - - if ($coverageData[$i] !== -1) { - if (isset($lines[$i])) { - $lines[$i] = 'covered ' . $lines[$i]; - } else { - $lines[$i] = 'covered'; - } - continue; - } - $lines[$i] = 'uncovered show'; - $foundEndBlockInContextSearch = false; - - for ($j = 1; $j <= $numContextLines; $j++) { - $key = $i - $j; - - if ($key > 0 && isset($lines[$key])) { - if (strpos($lines[$key], 'end') !== false) { - $foundEndBlockInContextSearch = true; - if ($j < $numContextLines) { - $lines[$key] = str_replace('end', '', $lines[$key-1]); - } - } - - if (strpos($lines[$key], 'uncovered') === false) { - if (strpos($lines[$key], 'covered') !== false) { - $lines[$key] .= ' show'; - } else { - $lines[$key] = 'ignored show'; - } - } - - if ($j == $numContextLines) { - $lineBeforeIsEndBlock = strpos($lines[$key-1], 'end') !== false; - $lineBeforeIsShown = strpos($lines[$key-1], 'show') !== false; - $lineBeforeIsUncovered = strpos($lines[$key-1], 'uncovered') !== false; - - if (!$foundEndBlockInContextSearch && !$lineBeforeIsUncovered && ($lineBeforeIsEndBlock)) { - $lines[$key-1] = str_replace('end', '', $lines[$key-1]); - } - - if (!$lineBeforeIsShown && !$lineBeforeIsUncovered) { - $lines[$key] .= ' start'; - } - } - } - $key = $i + $j; - - if ($key < $total) { - $lines[$key] = 'show'; - - if ($j == $numContextLines) { - $lines[$key] .= ' end'; - } - } - } - } - - // find the last "uncovered" or "show"n line and "end" its block - $lastShownLine = $manager->__array_strpos($lines, 'show', true); - if (isset($lines[$lastShownLine])) { - $lines[$lastShownLine] .= ' end'; - } - - // give the first start line another class so we can control the top padding of the entire results - $firstShownLine = $manager->__array_strpos($lines, 'show'); - if (isset($lines[$firstShownLine])) { - $lines[$firstShownLine] .= ' realstart'; - } - - // get the output - $lineCount = $coveredCount = 0; - $report = ''; - foreach ($testObjectFile as $num => $line) { - // start line count at 1 - $num++; - $class = $lines[$num]; - - if (strpos($class, 'ignored') === false) { - $lineCount++; - - if (strpos($class, 'covered') !== false && strpos($class, 'uncovered') === false) { - $coveredCount++; - } - } - - if (strpos($class, 'show') !== false) { - $report .= $manager->__paintCodeline($class, $num, $line); - } - } - return $manager->__paintHeader($lineCount, $coveredCount, $report); - } - -/** - * CLI reporting - * - * @param string $testObjectFile - * @param string $coverageData - * @param string $execCodeLines - * @param string $output - * @return void - * @static - */ - public static function reportCaseCli($testObjectFile, $coverageData, $execCodeLines) { - $manager = CodeCoverageManager::getInstance(); - $lineCount = $coveredCount = 0; - $report = ''; - - foreach ($testObjectFile as $num => $line) { - $num++; - $foundByManualFinder = isset($execCodeLines[$num]) && trim($execCodeLines[$num]) != ''; - $foundByXdebug = isset($coverageData[$num]) && $coverageData[$num] !== -2; - - if ($foundByManualFinder && $foundByXdebug) { - $lineCount++; - - if ($coverageData[$num] > 0) { - $coveredCount++; - } - } - } - return $manager->__paintHeaderCli($lineCount, $coveredCount, $report); - } - -/** - * Diff reporting - * - * @param string $testObjectFile - * @param string $coverageData - * @param string $execCodeLines - * @param string $output - * @return void - * @static - */ - public static function reportGroupHtml($testObjectFiles, $coverageData, $execCodeLines, $numContextLines) { - $manager = CodeCoverageManager::getInstance(); - $report = ''; - - foreach ($testObjectFiles as $testObjectFile) { - $lineCount = $coveredCount = 0; - $objFilename = $testObjectFile; - $testObjectFile = file($testObjectFile); - - foreach ($testObjectFile as $num => $line) { - $num++; - $foundByManualFinder = isset($execCodeLines[$objFilename][$num]) && trim($execCodeLines[$objFilename][$num]) != ''; - $foundByXdebug = isset($coverageData[$objFilename][$num]) && $coverageData[$objFilename][$num] !== -2; - - if ($foundByManualFinder && $foundByXdebug) { - $class = 'uncovered'; - $lineCount++; - - if ($coverageData[$objFilename][$num] > 0) { - $class = 'covered'; - $coveredCount++; - } - } else { - $class = 'ignored'; - } - } - $report .= $manager->__paintGroupResultLine($objFilename, $lineCount, $coveredCount); - } - return $manager->__paintGroupResultHeader($report); - } - -/** - * CLI reporting - * - * @param string $testObjectFile - * @param string $coverageData - * @param string $execCodeLines - * @param string $output - * @return void - * @static - */ - public static function reportGroupCli($testObjectFiles, $coverageData, $execCodeLines) { - $manager = CodeCoverageManager::getInstance(); - $report = ''; - - foreach ($testObjectFiles as $testObjectFile) { - $lineCount = $coveredCount = 0; - $objFilename = $testObjectFile; - $testObjectFile = file($testObjectFile); - - foreach ($testObjectFile as $num => $line) { - $num++; - $foundByManualFinder = isset($execCodeLines[$objFilename][$num]) && trim($execCodeLines[$objFilename][$num]) != ''; - $foundByXdebug = isset($coverageData[$objFilename][$num]) && $coverageData[$objFilename][$num] !== -2; - - if ($foundByManualFinder && $foundByXdebug) { - $lineCount++; - - if ($coverageData[$objFilename][$num] > 0) { - $coveredCount++; - } - } - } - $report .= $manager->__paintGroupResultLineCli($objFilename, $lineCount, $coveredCount); - } - return $report; - } - -/** - * Returns the name of the test object file based on a given test case file name - * - * @param string $file - * @param string $isApp - * @return string name of the test object file - * @access private - */ - private function __testObjectFileFromCaseFile($file, $isApp = true) { - $manager = CodeCoverageManager::getInstance(); - $path = $manager->__getTestFilesPath($isApp); - $folderPrefixMap = array( - 'behaviors' => 'models', - 'components' => 'controllers', - 'helpers' => 'views' - ); - - foreach ($folderPrefixMap as $dir => $prefix) { - if (strpos($file, $dir) === 0) { - $path .= $prefix . DS; - break; - } - } - $testManager = new TestManager(); - $testFile = str_replace(array('/', $testManager->getExtension('test')), array(DS, '.php'), $file); - - $folder = new Folder(); - $folder->cd(ROOT . DS . CAKE_TESTS_LIB); - $contents = $folder->read(); - - if (in_array(basename($testFile), $contents[1])) { - $testFile = basename($testFile); - $path = ROOT . DS . CAKE_TESTS_LIB; - } - $path .= $testFile; - $realpath = realpath($path); - - if ($realpath) { - return $realpath; - } - return $path; - } - -/** - * Returns an array of names of the test object files based on a given test group file name - * - * @param array $files - * @param string $isApp - * @return array names of the test object files - * @access private - */ - private function __testObjectFilesFromGroupFile($groupFile, $isApp = true) { - $manager = CodeCoverageManager::getInstance(); - $testManager = new TestManager(); - - $path = TESTS; - if (!$isApp) { - $path = ROOT . DS . 'cake' . DS . 'tests'; - } - if (!!$manager->pluginTest) { - $path = App::pluginPath($manager->pluginTest) . DS . 'tests'; - } - - $result = array(); - if ($groupFile == 'all') { - $files = array_keys($testManager->getTestCaseList()); - foreach ($files as $file) { - $file = str_replace(DS . 'tests' . DS . 'cases' . DS, DS, $file); - $file = str_replace('.test.php', '.php', $file); - $file = str_replace(DS . DS, DS, $file); - $result[] = $file; - } - } else { - $path .= DS . 'groups' . DS . $groupFile . $testManager->_groupExtension; - if (!file_exists($path)) { - trigger_error(__('This group file does not exist!', true)); - return array(); - } - - $result = array(); - $groupContent = file_get_contents($path); - $ds = '\s*\.\s*DS\s*\.\s*'; - $pluginTest = 'APP\.\'plugins\'' . $ds . '\'' . $manager->pluginTest . '\'' . $ds . '\'tests\'' . $ds . '\'cases\''; - $pluginTest .= '|App::pluginPath\(\'' . $manager->pluginTest . '\'\)' . $ds . '\'tests\'' . $ds . '\'cases\''; - $pattern = '/\s*TestManager::addTestFile\(\s*\$this,\s*(' . $pluginTest . '|APP_TEST_CASES|CORE_TEST_CASES)' . $ds . '(.*?)\)/i'; - preg_match_all($pattern, $groupContent, $matches); - - foreach ($matches[2] as $file) { - $patterns = array( - '/\s*\.\s*DS\s*\.\s*/', - '/\s*APP_TEST_CASES\s*/', - '/\s*CORE_TEST_CASES\s*/', - ); - - $replacements = array(DS, '', ''); - $file = preg_replace($patterns, $replacements, $file); - $file = str_replace("'", '', $file); - $result[] = $manager->__testObjectFileFromCaseFile($file, $isApp) . '.php'; - } - } - return $result; - } - -/** - * Parses a given code string into an array of lines and replaces some non-executable code lines with the needed - * amount of new lines in order for the code line numbers to stay in sync - * - * @param string $content - * @return array array of lines - * @access private - */ - private function __getExecutableLines($content) { - if (is_array($content)) { - $manager = CodeCoverageManager::getInstance(); - $result = array(); - foreach ($content as $file) { - $result[$file] = $manager->__getExecutableLines(file_get_contents($file)); - } - return $result; - } - $content = h($content); - // arrays are 0-indexed, but we want 1-indexed stuff now as we are talking code lines mind you (**) - $content = "\n" . $content; - // // strip unwanted lines - $content = preg_replace_callback("/(@codeCoverageIgnoreStart.*?@codeCoverageIgnoreEnd)/is", array('CodeCoverageManager', '__replaceWithNewlines'), $content); - // strip php | ?\> tag only lines - $content = preg_replace('/[ |\t]*[<\?php|\?>]+[ |\t]*/', '', $content); - - // strip lines that contain only braces and parenthesis - $content = preg_replace('/[ |\t]*[{|}|\(|\)]+[ |\t]*/', '', $content); - $result = explode("\n", $content); - // unset the zero line again to get the original line numbers, but starting at 1, see (**) - unset($result[0]); - return $result; - } - -/** - * Replaces a given arg with the number of newlines in it - * - * @return string the number of newlines in a given arg - * @access private - */ - private function __replaceWithNewlines() { - $args = func_get_args(); - $numLineBreaks = count(explode("\n", $args[0][0])); - return str_pad('', $numLineBreaks - 1, "\n"); - } - -/** - * Paints the headline for code coverage analysis - * - * @param string $codeCoverage - * @param string $report - * @return void - * @access private - */ - private function __paintHeader($lineCount, $coveredCount, $report) { - $manager = CodeCoverageManager::getInstance(); - $codeCoverage = $manager->__calcCoverage($lineCount, $coveredCount); - return $report = '

    Code Coverage: ' . $codeCoverage . '%

    -
    ' . $report . '
    '; - } - -/** - * Displays a notification concerning group test results - * - * @return void - */ - private function __paintGroupResultHeader($report) { - return '

    Please keep in mind that the coverage can vary a little bit depending on how much the different tests in the group interfere. If for example, TEST A calls a line from TEST OBJECT B, the coverage for TEST OBJECT B will be a little greater than if you were running the corresponding test case for TEST OBJECT B alone.

    ' . $report . '
    '; - } - -/** - * Paints the headline for code coverage analysis - * - * @param string $codeCoverage - * @param string $report - * @return void - * @access private - */ - private function __paintGroupResultLine($file, $lineCount, $coveredCount) { - $manager = CodeCoverageManager::getInstance(); - $codeCoverage = $manager->__calcCoverage($lineCount, $coveredCount); - $class = 'result-bad'; - - if ($codeCoverage > 50) { - $class = 'result-ok'; - } - if ($codeCoverage > 80) { - $class = 'result-good'; - } - return '

    Code Coverage for ' . $file . ': ' . $codeCoverage . '%

    '; - } - -/** - * Paints the headline for code coverage analysis - * - * @param string $codeCoverage - * @param string $report - * @return void - * @access private - */ - private function __paintGroupResultLineCli($file, $lineCount, $coveredCount) { - $manager = CodeCoverageManager::getInstance(); - $codeCoverage = $manager->__calcCoverage($lineCount, $coveredCount); - $class = 'bad'; - if ($codeCoverage > 50) { - $class = 'ok'; - } - if ($codeCoverage > 80) { - $class = 'good'; - } - return "\n" . 'Code Coverage for ' . $file . ': ' . $codeCoverage . '% (' . $class . ')' . "\n"; - } - -/** - * Paints the headline for code coverage analysis in the CLI - * - * @param string $codeCoverage - * @param string $report - * @return void - * @access private - */ - private function __paintHeaderCli($lineCount, $coveredCount, $report) { - $manager = CodeCoverageManager::getInstance(); - $codeCoverage = $manager->__calcCoverage($lineCount, $coveredCount); - $class = 'bad'; - if ($codeCoverage > 50) { - $class = 'ok'; - } - if ($codeCoverage > 80) { - $class = 'good'; - } - return $report = "Code Coverage: $codeCoverage% ($class)\n"; - } - -/** - * Paints a code line for html output - * - * @package default - * @access private - */ - private function __paintCodeline($class, $num, $line) { - $line = h($line); - - if (trim($line) == '') { - $line = ' '; // Win IE fix - } - return '
    ' . $num . '' . $line . '
    '; - } - -/** - * Calculates the coverage percentage based on a line count and a covered line count - * - * @param string $lineCount - * @param string $coveredCount - * @return void - * @access private - */ - private function __calcCoverage($lineCount, $coveredCount) { - if ($coveredCount > $lineCount) { - trigger_error(__('Sorry, you cannot have more covered lines than total lines!', true)); - } - return ($lineCount != 0) - ? round(100 * $coveredCount / $lineCount, 2) - : '0.00'; - } - -/** - * Gets us the base path to look for the test files - * - * @param string $isApp - * @return void - */ - private function __getTestFilesPath($isApp = true) { - $manager = CodeCoverageManager::getInstance(); - $path = ROOT . DS; - - if ($isApp) { - $path .= APP_DIR . DS; - } elseif (!!$manager->pluginTest) { - $pluginPath = APP . 'plugins' . DS . $manager->pluginTest . DS; - - $pluginPaths = App::path('plugins'); - foreach ($pluginPaths as $tmpPath) { - $tmpPath = $tmpPath . $manager->pluginTest . DS; - if (file_exists($tmpPath)) { - $pluginPath = $tmpPath; - break; - } - } - - $path = $pluginPath; - } else { - $path = TEST_CAKE_CORE_INCLUDE_PATH; - } - - return $path; - } - -/** - * Finds the last element of an array that contains $needle in a strpos computation - * - * @param array $arr - * @param string $needle - * @return void - * @access private - */ - private function __array_strpos($arr, $needle, $reverse = false) { - if (!is_array($arr) || empty($arr)) { - return false; - } - - if ($reverse) { - $arr = array_reverse($arr, true); - } - - foreach ($arr as $key => $val) { - if (strpos($val, $needle) !== false) { - return $key; - } - } - return false; - } -} diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index ff128bc2f..ef6c3bb5e 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -189,7 +189,7 @@ class CakeHtmlReporter extends CakeBaseReporter { */ public function paintCoverage($coverage) { $file = dirname(dirname(__FILE__)) . '/coverage/html_coverage_report.php'; - include $file; + include_once $file; $reporter = new HtmlCoverageReport($coverage, $this); echo $reporter->report(); } From 67e32e292d6ac22f79ef8e8314cad9011e5a0af8 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Thu, 13 May 2010 21:51:59 -0400 Subject: [PATCH 063/230] Additional refactoring in the coverage classes. --- .../lib/coverage/base_coverage_report.php | 25 +++++++++++++++++++ .../lib/coverage/html_coverage_report.php | 7 ++---- .../lib/coverage/text_coverage_report.php | 16 +----------- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/cake/tests/lib/coverage/base_coverage_report.php b/cake/tests/lib/coverage/base_coverage_report.php index 5ef10a64e..2e4826846 100644 --- a/cake/tests/lib/coverage/base_coverage_report.php +++ b/cake/tests/lib/coverage/base_coverage_report.php @@ -155,6 +155,31 @@ abstract class BaseCoverageReport { return $files; } +/** + * Calculates how many lines are covered and what the total number of executable lines is + * + * @param array $fileLines + * @param array $coverageData + * @return array. Array of covered, total lines. + */ + protected function _calculateCoveredLines($fileLines, $coverageData) { + $covered = $total = 0; + + //shift line numbers forward one; + array_unshift($fileLines, ' '); + unset($fileLines[0]); + + foreach ($fileLines as $lineno => $line) { + if (isset($coverageData['covered'][$lineno])) { + $covered++; + $total++; + } elseif (isset($coverageData['executable'][$lineno])) { + $total++; + } + } + return array($covered, $total); + } + /** * Generates report to display. * diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php index c173aa068..24e0cbe35 100644 --- a/cake/tests/lib/coverage/html_coverage_report.php +++ b/cake/tests/lib/coverage/html_coverage_report.php @@ -58,8 +58,8 @@ HTML; public function generateDiff($filename, $fileLines, $coverageData) { $output = ''; $diff = array(); - $covered = 0; - $total = 0; + + list($covered, $total) = $this->_calculateCoveredLines($fileLines, $coverageData); //shift line numbers forward one; array_unshift($fileLines, ' '); @@ -73,11 +73,8 @@ HTML; $this->_rawCoverage, $filename, $lineno ); $class = 'covered'; - $covered++; - $total++; } elseif (isset($coverageData['executable'][$lineno])) { $class = 'uncovered'; - $total++; } elseif (isset($coverageData['dead'][$lineno])) { $class .= ' dead'; } diff --git a/cake/tests/lib/coverage/text_coverage_report.php b/cake/tests/lib/coverage/text_coverage_report.php index bfe406b1b..addfeb1dd 100644 --- a/cake/tests/lib/coverage/text_coverage_report.php +++ b/cake/tests/lib/coverage/text_coverage_report.php @@ -52,21 +52,7 @@ class TextCoverageReport extends BaseCoverageReport { * @return string */ public function generateDiff($filename, $fileLines, $coverageData) { - $covered = 0; - $total = 0; - - //shift line numbers forward one; - array_unshift($fileLines, ' '); - unset($fileLines[0]); - - foreach ($fileLines as $lineno => $line) { - if (isset($coverageData['covered'][$lineno])) { - $covered++; - $total++; - } elseif (isset($coverageData['executable'][$lineno])) { - $total++; - } - } + list($covered, $total) = $this->_calculateCoveredLines($fileLines, $coverageData); $percentCovered = round(100 * $covered / $total, 2); return "$filename : $percentCovered%\n"; } From 32a46e9edad89c43499db815d3945fcb3ce54d79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Sat, 15 May 2010 21:05:22 -0430 Subject: [PATCH 064/230] Converting HtmlHelperTest to phpunit --- .../cases/libs/view/helpers/html.test.php | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/cake/tests/cases/libs/view/helpers/html.test.php b/cake/tests/cases/libs/view/helpers/html.test.php index 8a8b25f04..0b6b9ee0e 100644 --- a/cake/tests/cases/libs/view/helpers/html.test.php +++ b/cake/tests/cases/libs/view/helpers/html.test.php @@ -49,8 +49,6 @@ class TheHtmlTestController extends Controller { public $uses = null; } -Mock::generate('View', 'HtmlHelperMockView'); - /** * HtmlHelperTest class * @@ -474,14 +472,18 @@ class HtmlHelperTest extends CakeTestCase { $this->assertEqual(count($result), 2); ClassRegistry::removeObject('view'); - $view =& new HtmlHelperMockView(); + $view = $this->getMock('View', array(), array(), '', false); ClassRegistry::addObject('view', $view); - $view->expectAt(0, 'addScript', array(new PatternExpectation('/css_in_head.css/'))); + $view->expects($this->any())->method('addScript')->with($this->matchesRegularExpression('/css_in_head.css/')); $result = $this->Html->css('css_in_head', null, array('inline' => false)); $this->assertNull($result); - $view =& ClassRegistry::getObject('view'); - $view->expectAt(1, 'addScript', array(new NoPatternExpectation('/inline=""/'))); + ClassRegistry::removeObject('view'); + $view = $this->getMock('View', array(), array(), '', false); + ClassRegistry::addObject('view', $view); + $view->expects($this->any()) + ->method('addScript') + ->with($this->matchesRegularExpression('/more_css_in_head.css/')); $result = $this->Html->css('more_css_in_head', null, array('inline' => false)); $this->assertNull($result); } @@ -607,9 +609,10 @@ class HtmlHelperTest extends CakeTestCase { ); $this->assertTags($result, $expected); - $view =& ClassRegistry::getObject('view'); - $view =& new HtmlHelperMockView(); - $view->expectAt(0, 'addScript', array(new PatternExpectation('/script_in_head.js/'))); + ClassRegistry::removeObject('view'); + $view = $this->getMock('View', array(), array(), '', false); + ClassRegistry::addObject('view', $view); + $view->expects($this->any())->method('addScript')->with($this->matchesRegularExpression('/script_in_head.js/')); $result = $this->Html->script('script_in_head', array('inline' => false)); $this->assertNull($result); } @@ -648,9 +651,11 @@ class HtmlHelperTest extends CakeTestCase { ); $this->assertTags($result, $expected); - $view =& ClassRegistry::getObject('view'); - $view =& new HtmlHelperMockView(); - $view->expectAt(0, 'addScript', array(new PatternExpectation('/window\.foo\s\=\s2;/'))); + ClassRegistry::removeObject('view'); + $view = $this->getMock('View', array(), array(), '', false); + ClassRegistry::addObject('view', $view); + $view->expects($this->any())->method('addScript') + ->with($this->matchesRegularExpression('/window\.foo\s\=\s2;/')); $result = $this->Html->scriptBlock('window.foo = 2;', array('inline' => false)); $this->assertNull($result); @@ -698,10 +703,10 @@ class HtmlHelperTest extends CakeTestCase { $this->assertTags($result, $expected); ClassRegistry::removeObject('view'); - $View =& new HtmlHelperMockView(); + $view = $this->getMock('View', array(), array(), '', false); + ClassRegistry::addObject('view', $view); - $View->expectOnce('addScript'); - ClassRegistry::addObject('view', $View); + $view->expects($this->once())->method('addScript'); $result = $this->Html->scriptStart(array('safe' => false, 'inline' => false)); $this->assertNull($result); @@ -1121,10 +1126,10 @@ class HtmlHelperTest extends CakeTestCase { $result = $this->Html->meta(array('name' => 'ROBOTS', 'content' => 'ALL')); $this->assertTags($result, array('meta' => array('name' => 'ROBOTS', 'content' => 'ALL'))); - $viewMock = new HtmlHelperMockView(); - $viewMock->expectOnce('addScript', array(new PatternExpectation('/^getMock('View', array(), array(), '', false); + ClassRegistry::addObject('view', $view); + $view->expects($this->any())->method('addScript')->with($this->matchesRegularExpression('/^assertNull($this->Html->meta(array('name' => 'ROBOTS', 'content' => 'ALL'), null, array('inline' => false))); } From 6c2fe39bc0cce628ba4333825b80c318e0d23e3f Mon Sep 17 00:00:00 2001 From: mark_story Date: Sun, 16 May 2010 12:34:39 -0400 Subject: [PATCH 065/230] Changing how the cursor appears. --- cake/tests/lib/templates/header.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cake/tests/lib/templates/header.php b/cake/tests/lib/templates/header.php index 1ff307050..eed6a68f0 100644 --- a/cake/tests/lib/templates/header.php +++ b/cake/tests/lib/templates/header.php @@ -90,7 +90,10 @@ div.code-coverage-results div.uncovered span.content { background:#ecc; } div.code-coverage-results div.covered span.content { background:#cec; } div.code-coverage-results div.ignored span.content { color:#aaa; } - div.code-coverage-results div:hover { background:#e8e8e8;} + div.code-coverage-results div:hover { + background:#e8e8e8; + cursor: pointer; + } div.code-coverage-results div.covered:hover span.content { background:#b4edb4;} div.code-coverage-results div.uncovered:hover span.content { background:#edb4b4;} div.code-coverage-results span.line-num { From f7949d6aceb6dea59e60a63497e671be8de95c37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Mon, 17 May 2010 22:30:04 -0430 Subject: [PATCH 066/230] Fixing FormHelperTest for phpunit --- .../cases/libs/view/helpers/form.test.php | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/cake/tests/cases/libs/view/helpers/form.test.php b/cake/tests/cases/libs/view/helpers/form.test.php index 5428ab53d..4223ec303 100644 --- a/cake/tests/cases/libs/view/helpers/form.test.php +++ b/cake/tests/cases/libs/view/helpers/form.test.php @@ -1306,7 +1306,8 @@ class FormHelperTest extends CakeTestCase { 'OpenidUrl' => array('url' => 'http://www.cakephp.org') ); - $this->assertTrue($this->UserForm->OpenidUrl->create($data)); + $result = $this->UserForm->OpenidUrl->create($data); + $this->assertFalse(empty($result)); $this->assertFalse($this->UserForm->OpenidUrl->validates()); $result = $this->Form->create('UserForm', array('type' => 'post', 'action' => 'login')); @@ -1322,7 +1323,7 @@ class FormHelperTest extends CakeTestCase { ); $this->assertTags($result, $expected); - $expected = array('OpenidUrl' => array('openid_not_registered' => 1)); + $expected = array('OpenidUrl' => array('openid_not_registered' => true)); $this->assertEqual($this->Form->validationErrors, $expected); $result = $this->Form->error( @@ -1350,7 +1351,8 @@ class FormHelperTest extends CakeTestCase { 'ValidateProfile' => array('full_name' => 'Mariano Iglesias') ); - $this->assertTrue($this->ValidateUser->create($data)); + $result = $this->ValidateUser->create($data); + $this->assertFalse(empty($result)); $this->assertFalse($this->ValidateUser->validates()); $this->assertFalse($this->ValidateUser->ValidateProfile->validates()); @@ -1365,8 +1367,8 @@ class FormHelperTest extends CakeTestCase { $this->assertTags($result, $expected); $expected = array( - 'ValidateUser' => array('email' => 1), - 'ValidateProfile' => array('full_name' => 1, 'city' => 1) + 'ValidateUser' => array('email' => true), + 'ValidateProfile' => array('full_name' => true, 'city' => true) ); $this->assertEqual($this->Form->validationErrors, $expected); @@ -1393,7 +1395,8 @@ class FormHelperTest extends CakeTestCase { 'ValidateItem' => array('name' => 'Item') ); - $this->assertTrue($this->ValidateUser->create($data)); + $result = $this->ValidateUser->create($data); + $this->assertFalse(empty($result)); $this->assertFalse($this->ValidateUser->validates()); $this->assertFalse($this->ValidateUser->ValidateProfile->validates()); $this->assertFalse($this->ValidateUser->ValidateProfile->ValidateItem->validates()); @@ -1409,9 +1412,9 @@ class FormHelperTest extends CakeTestCase { $this->assertTags($result, $expected); $expected = array( - 'ValidateUser' => array('email' => 1), - 'ValidateProfile' => array('full_name' => 1, 'city' => 1), - 'ValidateItem' => array('description' => 1) + 'ValidateUser' => array('email' => true), + 'ValidateProfile' => array('full_name' => true, 'city' => true), + 'ValidateItem' => array('description' => true) ); $this->assertEqual($this->Form->validationErrors, $expected); From d7803dc7bfc2befdef918a29e97ff04412954253 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Mon, 17 May 2010 22:31:22 -0430 Subject: [PATCH 067/230] Implementing skipped tests message in html reporter --- cake/tests/lib/reporter/cake_base_reporter.php | 1 + cake/tests/lib/reporter/cake_html_reporter.php | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/cake/tests/lib/reporter/cake_base_reporter.php b/cake/tests/lib/reporter/cake_base_reporter.php index 8aa65ba01..c45036cd7 100644 --- a/cake/tests/lib/reporter/cake_base_reporter.php +++ b/cake/tests/lib/reporter/cake_base_reporter.php @@ -259,6 +259,7 @@ class CakeBaseReporter implements PHPUnit_Framework_TestListener { * @param float $time */ public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { + $this->paintSkip($e, $test); } /** diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index ef6c3bb5e..cf7424822 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -265,7 +265,9 @@ class CakeHtmlReporter extends CakeBaseReporter { $context = $message->getTrace(); $realContext = $context[3]; $class = new ReflectionClass($realContext['class']); - if ($class->getParentClass()->getName() === 'PHPUnit_Framework_TestCase') { + $deeper = $class->getParentClass()->getName() === 'PHPUnit_Framework_TestCase'; + $deeper = $deeper || !$class->isSubclassOf('PHPUnit_Framework_TestCase'); + if ($deeper) { $realContext = $context[4]; $context = $context[3]; } else { @@ -342,12 +344,13 @@ class CakeHtmlReporter extends CakeBaseReporter { * Prints the message for skipping tests. * * @param string $message Text of skip condition. + * @param PHPUnit_Framework_TestCase $test the test method skipped * @return void */ - public function paintSkip($message) { + public function paintSkip($message, $test) { echo "
  • \n"; echo "Skipped "; - echo $this->_htmlEntities($message); + echo $test->getName() . ': ' . $this->_htmlEntities($message->getMessage()); echo "
  • \n"; } From 327d42d6de214f182b2c816a88e6ef8e9c4d0e54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Mon, 17 May 2010 22:35:54 -0430 Subject: [PATCH 068/230] Fixing CacheHelperTest for phpunit --- .../cases/libs/view/helpers/cache.test.php | 20 +------------------ 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/cake/tests/cases/libs/view/helpers/cache.test.php b/cake/tests/cases/libs/view/helpers/cache.test.php index 5061184b7..df7c5b0c1 100644 --- a/cake/tests/cases/libs/view/helpers/cache.test.php +++ b/cake/tests/cases/libs/view/helpers/cache.test.php @@ -80,30 +80,11 @@ class CacheHelperTest extends CakeTestCase { $this->_cacheSettings = Configure::read('Cache'); Configure::write('Cache.check', true); Configure::write('Cache.disable', false); - } - -/** - * Start Case - switch view paths - * - * @access public - * @return void - */ - function startCase() { App::build(array( 'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS) ), true); } -/** - * End Case - restore view Paths - * - * @access public - * @return void - */ - function endCase() { - App::build(); - } - /** * tearDown method * @@ -114,6 +95,7 @@ class CacheHelperTest extends CakeTestCase { clearCache(); unset($this->Cache); Configure::write('Cache', $this->_cacheSettings); + App::build(); } /** From 3f881aee35af60daaa2b4e8ef7aa6b11c6026b29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Mon, 17 May 2010 23:44:08 -0430 Subject: [PATCH 069/230] Fixing message for completed test cases --- cake/tests/lib/reporter/cake_html_reporter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php index cf7424822..7d5168671 100755 --- a/cake/tests/lib/reporter/cake_html_reporter.php +++ b/cake/tests/lib/reporter/cake_html_reporter.php @@ -161,7 +161,7 @@ class CakeHtmlReporter extends CakeBaseReporter { echo "
    "; - echo $result->count() . "/" . ($result->count() - $result->skippedCount()); + echo ($result->count() - $result->skippedCount()) . "/" . $result->count(); echo " test methods complete:\n"; echo "" . count($result->passed()) . " passes, "; echo "" . $result->failureCount() . " fails, "; From 07c957e827aeb507fbef7541aeadf7a83b5a8b1a Mon Sep 17 00:00:00 2001 From: mark_story Date: Wed, 19 May 2010 00:14:37 -0400 Subject: [PATCH 070/230] Making PaginatorHelper test run under PHPUnit. --- .../cases/libs/view/helpers/paginator.test.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/cake/tests/cases/libs/view/helpers/paginator.test.php b/cake/tests/cases/libs/view/helpers/paginator.test.php index bbfbfb101..182548dca 100644 --- a/cake/tests/cases/libs/view/helpers/paginator.test.php +++ b/cake/tests/cases/libs/view/helpers/paginator.test.php @@ -19,8 +19,6 @@ */ App::import('Helper', array('Html', 'Paginator', 'Form', 'Js')); -Mock::generate('JsHelper', 'PaginatorMockJsHelper'); - /** * PaginatorHelperTest class * @@ -58,7 +56,7 @@ class PaginatorHelperTest extends CakeTestCase { ) ); $this->Paginator->Html = new HtmlHelper(); - $this->Paginator->Js = new PaginatorMockJsHelper(); + $this->Paginator->Js = $this->getMock('PaginatorHelper'); Configure::write('Routing.prefixes', array()); Router::reload(); @@ -1851,8 +1849,10 @@ class PaginatorHelperTest extends CakeTestCase { * @return void */ function testAjaxLinkGenerationLink() { - $this->Paginator->Js->expectCallCount('link', 1); - $this->Paginator->Js->setReturnValue('link', 'I am a link'); + $this->Paginator->Js->expects($this->once()) + ->method('link') + ->will($this->returnValue('I am a link')); + $result = $this->Paginator->link('test', array('controller' => 'posts'), array('update' => '#content')); $this->assertEqual($result, 'I am a link'); } @@ -1863,6 +1863,7 @@ class PaginatorHelperTest extends CakeTestCase { * @return void */ function testMockAjaxProviderClassInjection() { + $mock = $this->getMock('PaginatorHelper', array(), array(), 'PaginatorMockJsHelper'); $Paginator = new PaginatorHelper(array('ajax' => 'PaginatorMockJs')); $Paginator->params['paging'] = array( 'Article' => array( @@ -1875,8 +1876,8 @@ class PaginatorHelperTest extends CakeTestCase { 'options' => array() ) ); - $Paginator->PaginatorMockJs = new PaginatorMockJsHelper(); - $Paginator->PaginatorMockJs->expectOnce('link'); + $Paginator->PaginatorMockJs = $mock; + $Paginator->PaginatorMockJs->expects($this->once())->method('link'); $result = $Paginator->link('Page 2', array('page' => 2), array('update' => '#content')); $this->expectException(); From 103d5c250562b2ab21a4dfa1d1972f6c66150e12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Lorenzo=20Rodr=C3=ADguez?= Date: Tue, 18 May 2010 23:56:50 -0430 Subject: [PATCH 071/230] Partially migrated JsHelperTest to phpunit --- .../tests/cases/libs/view/helpers/js.test.php | 215 +++++++++++++----- 1 file changed, 152 insertions(+), 63 deletions(-) diff --git a/cake/tests/cases/libs/view/helpers/js.test.php b/cake/tests/cases/libs/view/helpers/js.test.php index 122c61303..ead91a11f 100644 --- a/cake/tests/cases/libs/view/helpers/js.test.php +++ b/cake/tests/cases/libs/view/helpers/js.test.php @@ -22,9 +22,6 @@ App::import('Helper', array('Js', 'Html', 'Form')); App::import('Core', array('View', 'ClassRegistry')); -Mock::generate('JsBaseEngineHelper', 'TestJsEngineHelper', array('methodOne')); -Mock::generate('View', 'JsHelperMockView'); - class OptionEngineHelper extends JsBaseEngineHelper { protected $_optionMap = array( 'request' => array( @@ -73,13 +70,14 @@ class JsHelperTestCase extends CakeTestCase { */ public $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/'; + /** - * startTest method + * setUp method * * @access public * @return void */ - function startTest() { + function setUp() { $this->_asset = Configure::read('Asset.timestamp'); Configure::write('Asset.timestamp', false); @@ -89,17 +87,17 @@ class JsHelperTestCase extends CakeTestCase { $this->Js->Form->Html = new HtmlHelper(); $this->Js->JsBaseEngine = new JsBaseEngineHelper(); - $view = new JsHelperMockView(); + $view = $this->getMock('View', array(), array(), '', false); ClassRegistry::addObject('view', $view); } /** - * endTest method + * tearDown method * * @access public * @return void */ - function endTest() { + function tearDown() { Configure::write('Asset.timestamp', $this->_asset); ClassRegistry::removeObject('view'); unset($this->Js); @@ -111,6 +109,9 @@ class JsHelperTestCase extends CakeTestCase { * @return void */ function _useMock() { + if (!class_exists('TestJsEngineHelper', false)) { + $this->getMock('JsBaseEngineHelper', array(), array(), 'TestJsEngineHelper'); + } $this->Js = new JsHelper(array('TestJs')); $this->Js->TestJsEngine = new TestJsEngineHelper($this); $this->Js->Html = new HtmlHelper(); @@ -144,25 +145,31 @@ class JsHelperTestCase extends CakeTestCase { */ function testMethodDispatching() { $this->_useMock(); - $this->Js->TestJsEngine->expectOnce('dispatchMethod', array(new PatternExpectation('/methodOne/i'), array())); - $this->Js->methodOne(); + $this->Js->TestJsEngine + ->expects($this->once()) + ->method('dispatchMethod') + ->with($this->matchesRegularExpression('/event/i')); + $this->Js->event(); - $this->Js->TestEngine = new StdClass(); + $this->Js->TestJsEngine = new StdClass(); $this->expectError(); $this->Js->someMethodThatSurelyDoesntExist(); } /** - * Test that method dispatching respects buffer parameters and bufferedMethods Lists. + * Test that method dispatching for events respects buffer parameters and bufferedMethods Lists. * * @return void */ - function testMethodDispatchWithBuffering() { + function testEventDispatchWithBuffering() { $this->_useMock(); $this->Js->TestJsEngine->bufferedMethods = array('event', 'sortables'); - $this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'This is an event call', array('event', '*')); + $this->Js->TestJsEngine->expects($this->exactly(3)) + ->method('dispatchMethod') + ->with($this->equalTo('event')) + ->will($this->returnValue('This is an event call')); $this->Js->event('click', 'foo'); $result = $this->Js->getBuffer(); @@ -178,8 +185,19 @@ class JsHelperTestCase extends CakeTestCase { $buffer = $this->Js->getBuffer(); $this->assertTrue(empty($buffer)); $this->assertEqual($result, 'This is an event call'); + } - $this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'I am not buffered.', array('effect', '*')); +/** + * Test that method dispatching for effects respects buffer parameters and bufferedMethods Lists. + * + * @return void + */ + function testEffectDispatchWithBuffering() { + $this->_useMock(); + $this->Js->TestJsEngine->expects($this->exactly(4)) + ->method('dispatchMethod') + ->with($this->equalTo('effect')) + ->will($this->returnValue('I am not buffered.')); $result = $this->Js->effect('slideIn'); $buffer = $this->Js->getBuffer(); @@ -224,15 +242,16 @@ class JsHelperTestCase extends CakeTestCase { ); $this->assertTags($result, $expected, true); - $this->Js->TestJsEngine->expectAtLeastOnce('domReady'); + $this->Js->TestJsEngine->expects($this->atLeastOnce())->method('domReady'); $result = $this->Js->writeBuffer(array('onDomReady' => true, 'cache' => false, 'clear' => false)); ClassRegistry::removeObject('view'); - $view = new JsHelperMockView(); + $view = $this->getMock('View', array(), array(), '', false); ClassRegistry::addObject('view', $view); - $view->expectCallCount('addScript', 1); - $view->expectAt(0, 'addScript', array(new PatternExpectation('/one\s\=\s1;\ntwo\s\=\s2;/'))); + $this->Js->TestJsEngine->expects($this->once()) + ->method('addScript') + ->with($this->matchesRegularExpression('/one\s\=\s1;\ntwo\s\=\s2;/')); $result = $this->Js->writeBuffer(array('onDomReady' => false, 'inline' => false, 'cache' => false)); } @@ -244,13 +263,12 @@ class JsHelperTestCase extends CakeTestCase { function testWriteBufferNotInline() { $this->Js->set('foo', 1); - $view = new JsHelperMockView(); + $view = $this->getMock('View', array(), array(), '', false); ClassRegistry::removeObject('view'); ClassRegistry::addObject('view', $view); - $view->expectCallCount('addScript', 1); - - $pattern = new PatternExpectation('#