Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * System exceptions
- */
- class Assert_Exception extends Exception {}
- class Php_Error_Exception extends Exception {}
- /**
- * Parent class for test's classes
- */
- class TestCase {
- protected function assertEq($tested, $sample, $mode = true) {
- if ($mode) {
- if ($tested !== $sample) {
- throw new Assert_Exception;
- } else {
- return true;
- }
- } else {
- return $tested === $sample;
- }
- }
- }
- /**
- * Tests class with public methods, names must started from 'test'
- * Constructor not tested in this version
- */
- class SomeTests extends TestCase {
- public function testOne() {
- $this->assertEq(1,2);
- }
- public function testTwo() {
- $this->assertEq(1,1);
- }
- public function testThree() {
- $a[] = $a['dsd'];
- }
- }
- /**
- * Test engine and test-results storage
- * Return array with results or message
- */
- class Test_Runner {
- private $_results = array();
- private $_ready = false;
- private function _test_method($instance, $method_name) {
- try {
- set_error_handler(function($c,$m) {throw new Php_Error_Exception($m,$c);}, E_ALL);
- $instance->{$method_name}();
- restore_error_handler();
- return array('test' => 'Passed');
- } catch (Php_Error_Exception $e) {
- return array('test' => 'Failed on php error', 'exception' => $e);
- } catch (Assert_Exception $e) {
- return array('test' => 'Failed on assertion', 'exception' => $e);
- } catch (Exception $e) {
- return array('test' => 'Failed on unexpected exception', 'exception' => $e);
- }
- }
- public function getResults() {
- if ($this->_ready) {
- return $this->_results;
- } else {
- return 'Not ready';
- }
- }
- function __construct($instance) {
- $methods = get_class_methods($instance);
- if (!empty($methods)) {
- $filtered = array_filter($methods, function($meth) {return preg_match("/^test.*/U", $meth) ? true : false;});
- if (!empty($filtered)) {
- foreach ($filtered as $method) {
- $this->_results[$method] = $this->_test_method($instance, $method);
- }
- $this->_ready = true;
- unset($instance);
- } else {
- $this->_results = 'No valid test names';
- }
- } else {
- $this->_results = 'No methods to test';
- }
- }
- }
- $run = new Test_Runner(new SomeTests());
- print_r($run->getResults());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement