Back to index

php5  5.3.10
quicktester.inc
Go to the documentation of this file.
00001 <?php
00002  /*
00003   Helper for simple tests to check return-value. Usage:
00004 
00005   $tests = <<<TESTS
00006    expected_return_value === expression
00007    2                     === 1+1
00008    4                     === 2*2
00009    FALSE                 === @ fopen('non_existent_file')
00010 TESTS;
00011   include( 'tests/quicktester.inc' );
00012 
00013   Expect: OK
00014 
00015   Remember to NOT put a trailing ; after a line!
00016 
00017  */
00018 error_reporting(E_ALL);  
00019 $tests = explode("\n",$tests);
00020 $success = TRUE;
00021 foreach ($tests as $n=>$test)
00022 {
00023        // ignore empty lines
00024        if (!$test) continue;
00025 
00026        // warn for trailing ;
00027        if (substr(trim($test), -1, 1) === ';') {
00028               echo "WARNING: trailing ';' found in test ".($n+1)."\n";
00029               exit;
00030        }
00031 
00032        // try for operators
00033        $operators = array('===', '~==');
00034        $operator = NULL;
00035        foreach ($operators as $a_operator) {
00036               if (strpos($test, $a_operator)!== FALSE) {
00037                      $operator = $a_operator;
00038                      list($left,$right) = explode($operator, $test);
00039                      break;
00040               }
00041        }
00042        if (!$operator) {
00043               echo "WARNING: unknown operator in '$test' (1)\n";
00044               exit;
00045        }
00046 
00047        $left  = eval("return ($left );");
00048        $right = eval("return ($right);");
00049        switch (@$operator) {
00050               case '===': // exact match
00051                      $result = $left === $right;
00052                      break;
00053               case '~==': // may differ after 12th significant number
00054                      if (   !is_float($left ) && !is_int($left )
00055                             || !is_float($right) && !is_int($right)) {
00056                             $result = FALSE;
00057                             break;
00058                      }
00059                      $result = abs(($left-$right) / $left) < 1e-12;
00060                      break;
00061               default:
00062                      echo "WARNING: unknown operator in '$test' (2)\n";
00063                      exit;
00064        }
00065 
00066        $success = $success && $result;
00067        if (!$result) {
00068               echo "\nAssert failed:\n";
00069               echo "$test\n";
00070               echo "Left:  ";var_dump($left );
00071               echo "Right: ";var_dump($right);
00072        }
00073 }
00074 if ($success) echo "OK";
00075