xref: /PHP-5.4/tests/quicktester.inc (revision 9ccad4a8)
1<?php
2 /*
3  Helper for simple tests to check return-value. Usage:
4
5  $tests = <<<TESTS
6   expected_return_value === expression
7   2                     === 1+1
8   4                     === 2*2
9   FALSE                 === @ fopen('non_existent_file')
10TESTS;
11  include( 'tests/quicktester.inc' );
12
13  Expect: OK
14
15  Remember to NOT put a trailing ; after a line!
16
17 */
18error_reporting(E_ALL);
19$tests = explode("\n",$tests);
20$success = TRUE;
21foreach ($tests as $n=>$test)
22{
23	// ignore empty lines
24	if (!$test) continue;
25
26	// warn for trailing ;
27	if (substr(trim($test), -1, 1) === ';') {
28		echo "WARNING: trailing ';' found in test ".($n+1)."\n";
29		exit;
30	}
31
32	// try for operators
33	$operators = array('===', '~==');
34	$operator = NULL;
35	foreach ($operators as $a_operator) {
36		if (strpos($test, $a_operator)!== FALSE) {
37			$operator = $a_operator;
38			list($left,$right) = explode($operator, $test);
39			break;
40		}
41	}
42	if (!$operator) {
43		echo "WARNING: unknown operator in '$test' (1)\n";
44		exit;
45	}
46
47	$left  = eval("return ($left );");
48	$right = eval("return ($right);");
49	switch (@$operator) {
50		case '===': // exact match
51			$result = $left === $right;
52			break;
53		case '~==': // may differ after 12th significant number
54			if (   !is_float($left ) && !is_int($left )
55				|| !is_float($right) && !is_int($right)) {
56				$result = FALSE;
57				break;
58			}
59			$result = abs(($left-$right) / $left) < 1e-12;
60			break;
61		default:
62			echo "WARNING: unknown operator in '$test' (2)\n";
63			exit;
64	}
65
66	$success = $success && $result;
67	if (!$result) {
68		echo "\nAssert failed:\n";
69		echo "$test\n";
70		echo "Left:  ";var_dump($left );
71		echo "Right: ";var_dump($right);
72	}
73}
74if ($success) echo "OK";
75
76