1 <?php // #!/usr/local/bin/php -Cq
2 /* Copyright (C) 2004 Dan Frankowski <dfrankow@cs.umn.edu>
3 * Copyright (C) 2004 Reini Urban <rurban@x-ray.at>
5 * This file is part of PhpWiki.
7 * PhpWiki is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * PhpWiki is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with PhpWiki; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * Unit tests for PhpWiki.
25 * You must have PEAR's PHPUnit package <http://pear.php.net/package/PHPUnit>.
26 * These tests are unrelated to test/maketest.pl, which do not use PHPUnit.
27 * These tests run from the command-line as well as from the browser.
28 * Use the argv (from cli) or tests (from browser) params to run only certain tests.
30 * $ tests.php test=<testname1> test=<testname2> ... db=dba debug=9 level=10
32 /****************************************************************
33 User definable options
34 *****************************************************************/
35 // common cfg options are taken from config/config.ini
37 //TODO: let the user decide which constants to use: define="x=y"
38 //define('USE_DB_SESSION', false);
39 //define('ENABLE_USER_NEW', false);
41 // memory usage: (8MB limit on certain servers)
43 // cli: Mem16712 => Mem16928
44 // web: Mem21216 => Mem26332 (5MB)
47 // cli: Mem20696 => Mem31240 (with USECACHE) (10MB)
48 // cli: Mem20240 => Mem30212 (without USECACHE) (10MB)
49 // web: Mem29424 => Mem35400 (without USECACHE) (6MB)
50 //define('USECACHE', false);
52 ####################################################################
54 # Preamble needed to get the tests to run.
56 ####################################################################
59 # Add root dir to the path
60 if (substr(PHP_OS,0,3) == 'WIN')
61 $cur_dir = str_replace("\\","/", $cur_dir);
62 $rootdir = $cur_dir . '/../../';
63 $ini_sep = substr(PHP_OS,0,3) == 'WIN' ? ';' : ':';
64 $include_path = ini_get('include_path') . $ini_sep . $rootdir . $ini_sep . $rootdir . "lib/pear";
65 ini_set('include_path', $include_path);
67 if ($HTTP_SERVER_VARS["SERVER_NAME"] == 'phpwiki.sourceforge.net') {
68 ini_set('include_path', ini_get('include_path') . ":/usr/share/pear");
69 //define('ENABLE_PAGEPERM',false); // costs nothing
70 define('USECACHE',false); // really?
71 //define('WIKIDB_NOCACHE_MARKUP',1);
74 // available database backends to test:
75 $database_backends = array(
81 //TODO: read some database values from config.ini, just use the "test_" prefix
82 // "flatfile" testing occurs in "tests/unit/.testbox/"
83 // "dba" needs the DATABASE_DBA_HANDLER, also in the .textbox directory
84 //$database_dba_handler = (substr(PHP_OS,0,3) == 'WIN') ? "db3" : "gdbm";
85 // "SQL" and "ADODB" need delete permissions to the test db
86 // You have to create that database beforehand with our schema
87 //$database_dsn = "mysql://wikiuser:@localhost/phpwiki";
88 $database_prefix = "test_";
89 // For "cvs" see the seperate tests/unit_test_backend_cvs.php
91 # Quiet warnings in IniConfig.php
92 $HTTP_SERVER_VARS['REMOTE_ADDR'] = '127.0.0.1';
93 $HTTP_SERVER_VARS['HTTP_USER_AGENT'] = "PHPUnit";
95 function printMemoryUsage($msg = '') {
98 if ($msg) echo $msg,"\n";
99 if ((defined('DEBUG') and (DEBUG & 8)) or !defined('DEBUG')) {
100 echo "-- MEMORY USAGE: ";
102 if (function_exists('memory_get_usage') and memory_get_usage()) {
103 $mem = memory_get_usage();
104 // } elseif (function_exists('getrusage') and ($u = getrusage()) and !empty($u['ru_maxrss'])) {
105 // $mem = $u['ru_maxrss'];
106 } elseif (substr(PHP_OS,0,3)=='WIN') { // requires a newer cygwin
107 // what we want is the process memory only: apache or php
109 // This works only if it's a cygwin process (apache or php)
110 //$mem = (integer) trim(system("cat /proc/$pid/statm |cut -f1"));
111 // if it's native windows use something like this:
112 // (requires pslist from sysinternals.com)
113 $memstr = system("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
114 $mem = (integer) trim($memstr);
117 //%MEM: Percentage of total memory in use by this process
118 //VSZ: Total virtual memory size, in 1K blocks.
119 //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
120 //CPU time used by process since it started.
121 //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
122 $memstr = system("ps -orss -p $pid|sed 1d");
123 $mem = (integer) trim($memstr);
125 if (!$initmem) $initmem = $mem;
126 // old libc on sf.net server doesn't understand "%+4d"
127 echo sprintf("%8d\t[%s%4d]\t[+%4d]\n", $mem, $mem > $oldmem ? "+" : ($mem == $oldmem ? " " : ""), $mem - $oldmem, $mem - $initmem);
132 /* // now in stdlib.php
133 function printSimpleTrace($bt) {
136 foreach ($bt as $i => $elem) {
137 if (!array_key_exists('file', $elem)) {
140 print " " . $elem['file'] . ':' . $elem['line'] . "\n";
144 # Show lots of detail when an assert() in the code fails
145 function assert_callback( $script, $line, $message ) {
146 echo "assert failed: script ", $script," line ", $line," :";
148 if (function_exists('debug_backtrace')) { // >= 4.3.0
150 printSimpleTrace(debug_backtrace());
154 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
157 # Get error reporting to call back, too
159 // set the error reporting level for this script
160 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
161 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
163 error_reporting(E_ALL); // php4
165 // This is too strict, fails on every notice and warning.
167 function myErrorHandler$errno, $errstr, $errfile, $errline) {
168 echo "$errfile: $errline: error# $errno: $errstr\n";
170 printSimpleTrace(debug_backtrace());
172 // The ErrorManager version
173 function _ErrorHandler_CB(&$error) {
175 printSimpleTrace(debug_backtrace());
176 if ($error->isFatal()) {
177 $error->errno = E_USER_WARNING;
178 return true; // ignore error
182 // set to the user defined error handler
183 // $old_error_handler = set_error_handler("myErrorHandler");
184 // This is already done via _DEBUG_TRACE
185 //$ErrorManager->pushErrorHandler(new WikiFunctionCb('_ErrorHandler_CB'));
188 function purge_dir($dir) {
190 if (!isset($finder)) {
191 $finder = new FileFinder;
193 $fileSet = new fileSet($dir);
194 assert(!empty($dir));
195 foreach ($fileSet->getFiles() as $f) {
200 function purge_testbox() {
202 if (isset($GLOBALS['request'])) {
203 $dbi = $GLOBALS['request']->getDbh();
205 $dir = $DBParams['directory'];
206 switch ($DBParams['dbtype']) {
208 assert(!empty($dir));
209 foreach (array('latest_ver','links','page_data','ver_data') as $d) {
210 purge_dir("$dir/$d");
215 foreach ($dbi->_backend->_table_names as $table) {
216 $dbi->genericSqlQuery("DELETE FROM $table");
224 $dbi->_cache->close();
225 $dbi->_backend->_latest_versions = array();
229 function printConstant($v) {
232 if (constant($v) or constant($v)===0 or constant($v)==='0') echo constant($v);
234 } else echo "undefined";
238 * via the HTML sapi interface print a form to easily change the current cmdline settings.
240 function html_option_form() {
241 global $debug_level, $user_level, $start_debug;
244 $option = HTML::div(array('class' => 'option'),
245 HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'test[\')'), 'test: '),
247 foreach ($GLOBALS['alltests'] as $s) {
248 $input = array('type' => 'checkbox', 'name' => 'test['.$s.']', 'value' => '1');
249 if (in_array($s,$GLOBALS['runtests'])) $input['checked'] = 'checked';
250 $option->pushContent(HTML::input($input), $s, HTML::br());
252 $form->pushContent(HTML::td($option));
254 $option = HTML::div(array('class' => 'option'),
255 HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'db[\')'), 'db: '),
257 foreach ($GLOBALS['database_backends'] as $s) {
258 $input = array('type' => 'checkbox', 'name' => 'db['.$s.']', 'value' => '1');
259 if (in_array($s,$GLOBALS['run_database_backends'])) $input['checked'] = 'checked';
260 $option->pushContent(HTML::input($input), $s, HTML::br());
262 $form->pushContent(HTML::td($option));
265 "function flipAll(formName) {
267 formObj = document.forms[0];
268 for (var i=0; i < formObj.length; i++) {
269 fldObj = formObj.elements[i];
270 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,formName.length) == formName)) {
271 if (isFirstSet == -1)
272 isFirstSet = (fldObj.checked) ? true : false;
273 fldObj.checked = (isFirstSet) ? false : true;
277 function updateDebugEdit(formObj) {
279 for (var i=0; i < formObj.length; i++) {
280 fldObj = formObj.elements[i];
281 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,7) == '_debug[')) {
282 if (fldObj.checked) val = val + parseInt(fldObj.value);
285 formObj.debug.value = val;
287 function updateLevelEdit(formObj) {
288 for (var i=0; i < formObj.length; i++) {
289 fldObj = formObj.elements[i];
290 if ((fldObj.type == 'radio') && (fldObj.name.substring(0,7) == '_level[')) {
291 if (fldObj.checked) {
292 formObj.level.value = fldObj.value;
298 $option = HTML::div(array('class' => 'option'),
299 HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'_debug[\')'), 'debug: '),
300 HTML::input(array('name'=>'debug','id'=>'debug','value'=>$debug_level,'size'=>5)),
302 foreach (array('VERBOSE' => 1,
311 $input = array('type' => 'checkbox', 'name' => '_debug[]', 'value' => $v,
312 'onClick' => 'updateDebugEdit(this.form)');
313 if ($debug_level & $v) $input['checked'] = 'checked';
314 $option->pushContent(HTML::input($input), "_DEBUG_".$s, HTML::br());
316 $form->pushContent(HTML::td($option));
318 $option = HTML::div(array('class' => 'option'),
319 HTML::span(array('style'=>'font-weight: bold'), "level: "),
320 HTML::input(array('name'=>'level','id'=>'level','value'=>$user_level,'size'=>5)),
322 foreach (array('FORBIDDEN' => -1,
327 'UNOBTAINABLE'=> 100,
329 $input = array('type' => 'radio', 'name' => '_level[]', 'value' => $v,
330 'onClick' => 'updateLevelEdit(this.form)');
331 if ($user_level & $v) $input['checked'] = 'checked';
332 $option->pushContent(HTML::input($input), "WIKIAUTH_".$s, HTML::br());
334 $form->pushContent(HTML::td($option));
337 $option = HTML::div(array('class' => 'option'), 'defines: ', HTML::br());
338 if (!empty($GLOBALS['define']))
339 foreach ($GLOBALS['define'] as $s) {
341 $input = array('type' => 'edit', 'name' => $s, 'value' => constant($s));
342 $option->pushContent(HTML::input($input), $s, HTML::br());
346 $form->pushContent(HTML::td($option));
347 $table = HTML::form(array('action' => $_SERVER['PHP_SELF'],
349 'accept-charset' => $GLOBALS['charset']),
350 HiddenInputs(array('start_debug' => $start_debug)),
352 HTML::table(HTML::tr(array('valign'=>'top'), $form)),
353 HTML::input(array('type' => 'submit')),
354 HTML::input(array('type' => 'reset')));
355 return $table->printXml();
358 ####################################################################
360 # End of preamble, run the test suite ..
362 ####################################################################
366 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
368 elseif (!empty($HTTP_SERVER_VARS['argv']))
369 $argv = $HTTP_SERVER_VARS['argv'];
370 elseif (!ini_get("register_argc_argv"))
371 echo "Could not read cmd args (register_argc_argv=Off?)\n";
374 $debug_level = 1; //was 9, _DEBUG_VERBOSE | _DEBUG_TRACE
375 $user_level = 1; // BOGO (conflicts with RateIt)
376 // use argv (from cli) or tests (from browser) params to run only certain tests
377 // avoid pear: Console::Getopt
378 $alltests = array('InlineParserTest','HtmlParserTest',
379 'PageListTest','ListPagesTest',
381 'AllPagesTest','AllUsersTest','OrphanedPagesTest','WantedPagesTest',
383 // support db=file db=dba test=SetupWiki test=DumpHtml debug=num -dconstant=value
384 // or db=file,dba test=SetupWiki,DumpHtml debug=num -dconstant=value
385 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
387 foreach ($HTTP_GET_VARS as $key => $val) {
389 foreach ($val as $k => $v) $argv[] = $key."=".$k;
390 elseif (strstr($val,",") and in_array($key, array("test","db")))
391 foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
393 $argv[] = $key."=".$val;
395 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0])) {
401 $run_database_backends = array();
402 foreach ($argv as $arg) {
403 if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
405 elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
406 $run_database_backends[] = $m[1];
407 elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
408 $debug_level = $m[1];
409 elseif (preg_match("/^level=(\d+)$/",$arg,$m))
411 elseif (preg_match("/^\-d(\w+)=(.+)$/",$arg,$m)) {
412 $define[$m[1]] = $m[2];
413 if ($m[2] == 'true') $m[2] = true;
414 elseif ($m[2] == 'false') $m[2] = false;
415 if (!defined($m[1])) define($m[1], $m[2]);
416 } elseif (in_array($arg, $alltests))
418 elseif ($debug_level & 1)
419 echo "ignored arg: ", $arg, "\n";
423 if (empty($run_database_backends))
424 $run_database_backends = $database_backends;
425 if (empty($runtests))
426 $runtests = $alltests;
427 if ($debug_level & 1) {
429 echo "PHP_SAPI=",php_sapi_name(), "\n";
430 echo "PHP_OS=",PHP_OS, "\n";
431 echo "PHP_VERSION=",PHP_VERSION, "\n";
432 echo "test=", join(",",$runtests),"\n";
433 echo "db=", join(",",$run_database_backends),"\n";
434 echo "debug=", $debug_level,"\n";
435 echo "level=", $user_level,"\n";
436 if (!empty($define)) {
437 foreach ($define as $k => $v) printConstant($k);
439 if ($debug_level & 8) {
440 echo "pid=",getmypid(),"\n";
446 if (!defined('DEBUG'))
447 define('DEBUG', $debug_level);
448 // override defaults:
449 if (!defined('RATING_STORAGE'))
450 define('RATING_STORAGE', 'WIKIPAGE');
451 if (!defined('GROUP_METHOD'))
452 define('GROUP_METHOD', 'NONE');
455 printMemoryUsage("beforePEAR");
458 printMemoryUsage("beforePhpWiki");
460 define('PHPWIKI_NOMAIN', true);
462 require_once $rootdir.'index.php';
463 require_once $rootdir.'lib/main.php';
465 // init filefinder for pear path fixup.
466 FindFile ('PHPUnit.php', 'missing_okay');
467 // PEAR library (requires version ??)
468 require_once 'PHPUnit.php';
472 if ($debug_level & 1) {
474 echo "PHPWIKI_VERSION=",PHPWIKI_VERSION, strstr(PHPWIKI_VERSION,"pre") ? strftime(" / %Y%m%d") : "","\n";
475 if ($debug_level & 9) {
476 // which constants affect memory?
477 foreach (explode(",","USECACHE,WIKIDB_NOCACHE_MARKUP,ENABLE_USER_NEW,ENABLE_PAGEPERM") as $v) {
484 global $ErrorManager;
485 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
486 //FIXME: ignore cached requests (if-modified-since) from cli
487 class MockRequest extends WikiRequest {
488 function MockRequest(&$dbparams) {
489 $this->_dbi = WikiDB::open($dbparams);
490 $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
491 $this->_group = new GroupNone();
492 $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
495 function getGroup() {
496 if (is_object($this->_group))
497 return $this->_group;
498 else // FIXME: this is set to "/f:" somewhere.
499 return new GroupNone();
503 if (ENABLE_USER_NEW) {
504 class MockUser extends _WikiUser {
505 function MockUser($name, $level) {
506 $this->_userid = $name;
507 $this->_isSignedIn = $level > 1;
508 $this->_level = $level;
510 function isSignedIn() {
511 return $this->_isSignedIn;
515 class MockUser extends WikiUser {
516 function MockUser($name, $level) {
517 $this->_userid = $name;
518 $this->_isSignedIn = $level > 1;
519 $this->_level = $level;
521 function isSignedIn() {
522 return $this->_isSignedIn;
529 $request->_user = WikiUser('AnonUser');
531 $request->_user = new WikiUser($request, 'AnonUser');
532 $request->_prefs = $request->_user->getPreferences();
535 include_once("themes/" . THEME . "/themeinfo.php");
536 if (DEBUG & _DEBUG_TRACE)
537 printMemoryUsage("PhpWikiLoaded");
539 // provide a nice input form for all options
540 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
541 echo html_option_form();
544 // save and restore all args for each test.
545 class phpwiki_TestCase extends PHPUnit_TestCase {
548 $this->_savedargs = $request->_args;
549 $request->_args = array();
551 echo $this->_name,"\n";
555 function tearDown() {
557 $request->_args = $this->_savedargs;
558 if (DEBUG & _DEBUG_TRACE)
563 # Test all db backends.
564 foreach ($run_database_backends as $dbtype) {
565 // if (DEBUG & _DEBUG_TRACE)
566 // printMemoryUsage("PHPUnitInitialized");
568 $DBParams['dbtype'] = $dbtype;
569 $DBParams['directory'] = $cur_dir . '/.testbox';
570 $DBParams['prefix'] = $database_prefix;
572 //$DBParams['dsn'] = $database_dsn;
573 //$DBParams['dba_handler'] = $database_dba_handler;
575 echo "Testing DB Backend \"$dbtype\" ...\n";
576 $request = new MockRequest($DBParams);
577 if ( ! ENABLE_USER_NEW ) {
578 $request->_user->_request =& $request;
579 $request->_user->_dbi =& $request->_dbi;
581 if (DEBUG & _DEBUG_TRACE)
582 printMemoryUsage("PhpWikiInitialized");
584 foreach ($runtests as $test) {
585 if (!@ob_get_level()) ob_start();
586 $suite = new PHPUnit_TestSuite("phpwiki");
587 if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
588 require_once dirname(__FILE__).'/lib/'.$test.'.php';
590 require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
591 $suite->addTest( new PHPUnit_TestSuite($test) );
593 @set_time_limit(240);
594 $result = PHPUnit::run($suite);
595 echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
597 if ($result->failureCount() > 0) {
598 echo "More detail:\n";
599 echo $result->toString();
603 $request->chunkOutput();
604 $request->_dbi->close();
605 unset($request->_user);
606 unset($request->_dbi);
612 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
615 // (c-file-style: "gnu")
620 // c-hanging-comment-ender-p: nil
621 // indent-tabs-mode: nil