1 <?php // #!/usr/local/bin/php -Cq
2 /* Copyright (C) 2004 Dan Frankowski <dfrankow@cs.umn.edu>
3 * Copyright (C) 2004,2005,2006 Reini Urban <rurban@x-ray.at>
6 * This file is part of PhpWiki.
8 * PhpWiki is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * PhpWiki is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with PhpWiki; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 * Unit tests for PhpWiki.
26 * You must have PEAR's PHPUnit package <http://pear.php.net/package/PHPUnit>.
27 * These tests are unrelated to test/maketest.pl, which do not use PHPUnit.
28 * These tests run from the command-line as well as from the browser.
29 * Use the argv (from cli) or tests (from browser) params to run only certain tests.
31 * $ tests.php test=<testname1> test=<testname2> ... db=dba debug=9 level=10
33 /****************************************************************
34 User definable options
35 *****************************************************************/
36 // common cfg options are taken from config/config.ini
38 //TODO: let the user decide which constants to use: define="x=y"
39 //define('USE_DB_SESSION', false);
40 //define('ENABLE_USER_NEW', false);
42 // memory usage: (8MB limit on certain servers)
44 // cli: Mem16712 => Mem16928
45 // web: Mem21216 => Mem26332 (5MB)
48 // cli: Mem20696 => Mem31240 (with USECACHE) (10MB)
49 // cli: Mem20240 => Mem30212 (without USECACHE) (10MB)
50 // web: Mem29424 => Mem35400 (without USECACHE) (6MB)
51 //define('USECACHE', false);
53 //##################################################################
55 // Preamble needed to get the tests to run.
57 //##################################################################
60 // Add root dir to the path
61 if (substr(PHP_OS,0,3) == 'WIN')
62 $cur_dir = str_replace("\\","/", $cur_dir);
63 $rootdir = $cur_dir . '/../../';
64 $ini_sep = substr(PHP_OS,0,3) == 'WIN' ? ';' : ':';
65 $include_path = ini_get('include_path') . $ini_sep
66 . $rootdir . $ini_sep . $rootdir . "lib/pear";
67 ini_set('include_path', $include_path);
68 define('DEFAULT_LANGUAGE','en'); // don't use browser detection
70 if (!isset($HTTP_SERVER_VARS)) {
71 $HTTP_SERVER_VARS =& $_SERVER;
72 $HTTP_GET_VARS =& $_GET;
73 $HTTP_POST_VARS =& $_POST;
76 if (!empty($HTTP_SERVER_VARS) and $HTTP_SERVER_VARS["SERVER_NAME"] == 'phpwiki.sourceforge.net') {
77 ini_set('include_path', ini_get('include_path') . ":/usr/share/pear");
78 //define('ENABLE_PAGEPERM',false); // costs nothing
79 define('USECACHE',false); // really?
80 //define('WIKIDB_NOCACHE_MARKUP',1);
83 // available database backends to test:
84 $database_backends = array(
86 'flatfile', // not yet committed
88 'SQL', // default backend defined in the config.ini DSN
89 'ADODB', // same backend as defined in the config.ini DSN
90 // specific backends (need to be setup as db=test_phpwiki)
91 'PearDB_pgsql', 'PearDB_sqlite', 'PearDB_mysql',
92 //'PearDB_oci8','PearDB_mssql',
93 'ADODB_postgres7', 'ADODB_sqlite', 'ADODB_mysql',
94 //'ADODB_oci8', 'ADODB_mssql',
97 if ((int)substr(phpversion(), 1) >= 5)
98 array_push($database_backends, 'PDO_pqsql', 'PDO_sqlite', 'PDO_mysql');
99 //'PDO_oci', 'PDO_odbc'
101 //TODO: convert cvs test
102 // For "cvs" see the seperate tests/unit_test_backend_cvs.php (cvs is experimental)
103 //TODO: read some database values from config.ini, just use the "test_" prefix
104 // "flatfile" testing occurs in "tests/unit/.testbox/flatfile"
105 // "dba" needs the DATABASE_DBA_HANDLER, also in the .textbox directory
106 //$database_dba_handler = (substr(PHP_OS,0,3) == 'WIN') ? "db3" : "gdbm";
107 // "SQL" and "ADODB" need delete permissions to the test db
108 // You have to create that database beforehand with our schema
109 //$database_dsn = "mysql://wikiuser:@localhost/phpwiki";
110 $database_prefix = "test_";
112 // Quiet warnings in IniConfig.php
113 $HTTP_SERVER_VARS['REMOTE_ADDR'] = '127.0.0.1';
114 $HTTP_SERVER_VARS['HTTP_USER_AGENT'] = "PHPUnit";
116 function printMemoryUsage($msg = '') {
119 if ($msg) echo $msg,"\n";
120 if ((defined('DEBUG') and (DEBUG & 8)) or !defined('DEBUG')) {
121 require_once("lib/stdlib.php");
122 echo "-- MEMORY USAGE: ";
124 $mem = getMemoryUsage();
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 ? " " : ""),
128 $mem - $oldmem, $mem - $initmem);
133 /* // now in stdlib.php
134 function printSimpleTrace($bt) {
137 foreach ($bt as $i => $elem) {
138 if (!array_key_exists('file', $elem)) {
141 print " " . $elem['file'] . ':' . $elem['line'] . "\n";
145 // Show lots of detail when an assert() in the code fails
146 function assert_callback( $script, $line, $message ) {
147 echo "assert failed: script ", $script," line ", $line," :";
149 if (function_exists('debug_backtrace')) { // >= 4.3.0
151 printSimpleTrace(debug_backtrace());
155 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
158 // Get error reporting to call back, too
160 // set the error reporting level for this script
161 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
162 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
164 error_reporting(E_ALL); // php4
166 // This is too strict, fails on every notice and warning.
168 function myErrorHandler$errno, $errstr, $errfile, $errline) {
169 echo "$errfile: $errline: error# $errno: $errstr\n";
171 printSimpleTrace(debug_backtrace());
173 // The ErrorManager version
174 function _ErrorHandler_CB(&$error) {
176 printSimpleTrace(debug_backtrace());
177 if ($error->isFatal()) {
178 $error->errno = E_USER_WARNING;
179 return true; // ignore error
183 // set to the user defined error handler
184 // $old_error_handler = set_error_handler("myErrorHandler");
185 // This is already done via _DEBUG_TRACE
186 //$ErrorManager->pushErrorHandler(new WikiFunctionCb('_ErrorHandler_CB'));
189 function purge_dir($dir) {
191 if (!isset($finder)) {
192 $finder = new FileFinder;
194 $fileSet = new fileSet($dir);
195 assert(!empty($dir));
196 foreach ($fileSet->getFiles() as $f) {
201 function purge_testbox() {
203 if (isset($GLOBALS['request'])) {
204 $dbi = $GLOBALS['request']->getDbh();
206 $dir = $DBParams['directory'];
207 switch ($DBParams['dbtype']) {
210 assert(!empty($dir));
211 foreach (array('latest_ver','links','page_data','ver_data') as $d) {
212 purge_dir("$dir/$d");
218 foreach (array_reverse($dbi->_backend->_table_names) as $table) {
219 $dbi->genericSqlQuery("DELETE FROM $table");
227 $dbi->_cache->close();
228 $dbi->_backend->_latest_versions = array();
232 function printConstant($v) {
235 if (constant($v) or constant($v)===0 or constant($v)==='0') echo constant($v);
237 } else echo "undefined";
241 * via the HTML sapi interface print a form to easily change the current cmdline settings.
243 function html_option_form() {
244 global $debug_level, $user_level, $start_debug;
247 $option = HTML::div(array('class' => 'option'),
248 HTML::span(array('title' => 'doubleclick to (un)select all', 'style'=>'font-weight: bold; padding: 1px; border: 2px outset;','onDblClick'=>'flipAll(\'test[\')'),
252 foreach ($GLOBALS['alltests'] as $s) {
253 $id = preg_replace("/\W/", "", $s) . $i++;
254 $input = array('type' => 'checkbox', 'name' => 'test['.$s.']', 'value' => '1', 'id' => $id);
255 if (in_array($s,$GLOBALS['runtests'])) $input['checked'] = 'checked';
256 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), $s), HTML::br());
258 $form->pushContent(HTML::td($option));
260 $option = HTML::div(array('class' => 'option'),
261 HTML::span(array('title' => 'doubleclick to (un)select all', 'style'=>'font-weight: bold; padding: 1px; border: 2px outset;', 'onDblClick'=>'flipAll(\'db[\')'),
264 foreach ($GLOBALS['database_backends'] as $s) {
265 $id = preg_replace("/\W/", "", $s) . $i++;
266 $input = array('type' => 'checkbox', 'name' => 'db['.$s.']', 'value' => '1', 'id' => $id);
267 if (in_array($s,$GLOBALS['run_database_backends'])) $input['checked'] = 'checked';
268 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), $s), HTML::br());
270 $form->pushContent(HTML::td($option));
273 "function flipAll(formName) {
275 formObj = document.forms[0];
276 for (var i=0; i < formObj.length; i++) {
277 fldObj = formObj.elements[i];
278 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,formName.length) == formName)) {
279 if (isFirstSet == -1)
280 isFirstSet = (fldObj.checked) ? true : false;
281 fldObj.checked = (isFirstSet) ? false : true;
285 function updateDebugEdit(formObj) {
287 for (var i=0; i < formObj.length; i++) {
288 fldObj = formObj.elements[i];
289 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,7) == '_debug[')) {
290 if (fldObj.checked) val = val + parseInt(fldObj.value);
293 formObj.debug.value = val;
295 function updateLevelEdit(formObj) {
296 for (var i=0; i < formObj.length; i++) {
297 fldObj = formObj.elements[i];
298 if ((fldObj.type == 'radio') && (fldObj.name.substring(0,7) == '_level[')) {
299 if (fldObj.checked) {
300 formObj.level.value = fldObj.value;
306 $option = HTML::div(array('class' => 'option'),
307 HTML::span(array('title' => 'doubleclick to (un)select all', 'style'=>'font-weight: bold; padding: 1px; border: 2px outset;',
308 'onDblClick'=>'flipAll(\'_debug[\')'),
310 HTML::input(array('name'=>'debug','id'=>'debug',
311 'value'=>$debug_level,'size'=>5)),
313 foreach (array('VERBOSE' => 1,
323 $id = preg_replace("/\W/", "", $s) . $i++;
324 $input = array('type' => 'checkbox', 'name' => '_debug[]', 'value' => $v, 'id' => $id,
325 'onClick' => 'updateDebugEdit(this.form)');
326 if ($debug_level & $v) $input['checked'] = 'checked';
327 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), "_DEBUG_".$s), HTML::br());
329 $form->pushContent(HTML::td($option));
331 $option = HTML::div(array('class' => 'option'),
332 HTML::span(array('style'=>'font-weight: bold;'), "level: "),
333 HTML::input(array('name'=>'level','id'=>'level',
334 'value'=>$user_level,'size'=>5)),
336 foreach (array('FORBIDDEN' => -1,
341 'UNOBTAINABLE'=> 100,
343 $id = preg_replace("/\W/", "", $s) . $i++;
344 $input = array('type' => 'radio', 'name' => '_level[]', 'value' => $v, 'id' => $id,
345 'onClick' => 'updateLevelEdit(this.form)');
346 if ($user_level & $v) $input['checked'] = 'checked';
347 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), "WIKIAUTH_".$s), HTML::br());
349 $form->pushContent(HTML::td($option));
352 $option = HTML::div(array('class' => 'option'), 'defines: ', HTML::br());
353 if (!empty($GLOBALS['define']))
354 foreach ($GLOBALS['define'] as $s) {
356 $input = array('type' => 'edit', 'name' => $s, 'value' => constant($s));
357 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), $s), HTML::br());
361 $form->pushContent(HTML::td($option));
362 $table = HTML::form(array('action' => $_SERVER['PHP_SELF'],
364 'accept-charset' => $GLOBALS['charset']),
366 HTML::table(HTML::tr(array('valign'=>'top'), $form)),
367 HTML::input(array('type' => 'submit')),
368 HTML::input(array('type' => 'reset')));
370 $table->pushContent(HiddenInputs(array('start_debug' => $start_debug)));
371 return $table->printXml();
374 //####################################################################
376 // End of preamble, run the test suite ..
378 //####################################################################
382 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
384 elseif (!empty($HTTP_SERVER_VARS['argv']))
385 $argv = $HTTP_SERVER_VARS['argv'];
386 elseif (!ini_get("register_argc_argv"))
387 echo "Could not read cmd args (register_argc_argv=Off?)\n";
390 $debug_level = 1; //was 9, _DEBUG_VERBOSE | _DEBUG_TRACE
391 //if (defined('E_STRICT')) $debug_level = 5; // add PARSER flag on php5
392 $user_level = 1; // BOGO (conflicts with RateIt)
393 // use argv (from cli) or tests (from browser) params to run only certain tests
394 // avoid pear: Console::Getopt
395 $alltests = array(/* valid tests without clean virgin setup */
396 'InlineParserTest','HtmlParserTest',
397 'PageListTest','ListPagesTest','XmlRpcTest',
400 /* valid tests only with clean virgin setup */
401 'AllPagesTest','AllUsersTest','OrphanedPagesTest',
402 'WantedPagesTest','TextSearchTest','IncludePageTest',
403 'AtomParserTest','AtomFeedTest',
404 /* final tests which require all valid pages and consumes > 32MB */
406 // support db=file db=dba test=SetupWiki test=DumpHtml debug=num -dconstant=value
407 // or db=file,dba test=SetupWiki,DumpHtml debug=num -dconstant=value
408 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
410 foreach ($HTTP_GET_VARS as $key => $val) {
412 foreach ($val as $k => $v) $argv[] = $key."=".$k;
413 elseif (strstr($val,",") and in_array($key, array("test","db")))
414 foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
416 $argv[] = $key."=".$val;
418 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0])) {
424 $run_database_backends = array();
426 foreach ($argv as $arg) {
427 if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
429 elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
430 $run_database_backends[] = $m[1];
431 elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
432 $debug_level = $m[1];
433 elseif (preg_match("/^level=(\d+)$/",$arg,$m))
435 elseif (preg_match("/^\-d(\w+)=(.+)$/",$arg,$m)) {
436 $define[$m[1]] = $m[2];
437 if ($m[2] == 'true') $m[2] = true;
438 elseif ($m[2] == 'false') $m[2] = false;
439 if (!defined($m[1])) define($m[1], $m[2]);
440 } elseif (in_array($arg, $alltests))
442 elseif ($debug_level & 1)
443 echo "ignored arg: ", $arg, "\n";
447 if (empty($run_database_backends))
448 $run_database_backends = $database_backends;
449 if (empty($runtests))
450 $runtests = $alltests;
451 if ($debug_level & 1) {
453 echo "PHP_SAPI=",php_sapi_name(), "\n";
454 echo "PHP_OS=",PHP_OS, "\n";
455 echo "PHP_VERSION=",PHP_VERSION, "\n";
456 echo "test=", join(",",$runtests),"\n";
457 echo "db=", join(",",$run_database_backends),"\n";
458 echo "debug=", $debug_level,"\n";
459 echo "level=", $user_level,"\n";
460 if (!empty($define)) {
461 foreach ($define as $k => $v) printConstant($k);
463 if ($debug_level & 8) {
464 echo "pid=",getmypid(),"\n";
470 if (!defined('DEBUG'))
471 define('DEBUG', $debug_level);
472 // override defaults:
473 if (!defined('RATING_STORAGE'))
474 define('RATING_STORAGE', 'WIKIPAGE');
475 if (!defined('GROUP_METHOD'))
476 define('GROUP_METHOD', 'NONE');
479 printMemoryUsage("beforePEAR");
482 printMemoryUsage("beforePhpWiki");
484 define('PHPWIKI_NOMAIN', true);
485 // Other needed files
486 require_once $rootdir.'index.php';
487 require_once $rootdir.'lib/main.php';
489 // init filefinder for pear path fixup.
490 FindFile ('PHPUnit.php', 'missing_okay');
491 // PEAR library (requires version ??)
492 require_once 'PHPUnit.php';
496 if ($debug_level & 1) {
498 echo "PHPWIKI_VERSION=",PHPWIKI_VERSION,
499 strstr(PHPWIKI_VERSION,"pre") ? strftime(" / %Y%m%d") : "","\n";
500 if ($debug_level & 9) {
501 // which constants affect memory?
502 foreach (explode(",","USECACHE,WIKIDB_NOCACHE_MARKUP,"
503 ."ENABLE_USER_NEW,ENABLE_PAGEPERM") as $v) {
510 global $ErrorManager;
511 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
512 // FIXME: ignore cached requests (if-modified-since) from cli
513 class MockRequest extends WikiRequest {
514 function MockRequest($dbparams) {
515 $this->_dbi = WikiDB::open($dbparams);
516 $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
517 $this->_group = new GroupNone();
518 $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
521 function getGroup() {
522 if (is_object($this->_group))
523 return $this->_group;
524 else // FIXME: this is set to "/f:" somewhere.
525 return new GroupNone();
529 if (ENABLE_USER_NEW) {
530 class MockUser extends _WikiUser {
531 function MockUser($name, $level) {
532 $this->_userid = $name;
533 $this->_isSignedIn = $level > 1;
534 $this->_level = $level;
536 function isSignedIn() {
537 return $this->_isSignedIn;
541 class MockUser extends WikiUser {
542 function MockUser($name, $level) {
543 $this->_userid = $name;
544 $this->_isSignedIn = $level > 1;
545 $this->_level = $level;
547 function isSignedIn() {
548 return $this->_isSignedIn;
555 $request->_user = WikiUser('AnonUser');
557 $request->_user = new WikiUser($request, 'AnonUser');
558 $request->_prefs = $request->_user->getPreferences();
561 if (DEBUG & _DEBUG_TRACE)
562 printMemoryUsage("PhpWikiLoaded");
564 // provide a nice input form for all options
565 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
566 echo html_option_form();
570 // save and restore all args for each test.
571 class phpwiki_TestCase extends PHPUnit_TestCase {
573 global $request, $WikiTheme;
574 include_once("themes/" . THEME . "/themeinfo.php");
575 $this->_savedargs = $request->_args;
576 $request->_args = array();
578 echo $this->_name,"\n";
582 function tearDown() {
584 $request->_args = $this->_savedargs;
585 if (DEBUG & _DEBUG_TRACE)
590 // Test all db backends.
591 foreach ($run_database_backends as $dbtype) {
592 global $request, $DBParams;
593 // if (DEBUG & _DEBUG_TRACE)
594 // printMemoryUsage("PHPUnitInitialized");
595 $DBParams['dbtype'] = $dbtype;
596 if (string_starts_with($dbtype, 'PearDB_')) {
597 $DBParams['dbtype'] = 'SQL';
598 $DBParams['dsn'] = preg_replace("/^([^:]+):/", substr($dbtype, 7).":", $DBParams['dsn']);
599 echo "dsn: ",$DBParams['dsn'],"\n";
601 if (string_starts_with($dbtype, 'ADODB_')) {
602 $DBParams['dbtype'] = 'ADODB';
603 $DBParams['dsn'] = preg_replace("/^([^:]+):/", substr($dbtype, 6).":", $DBParams['dsn']);
604 echo "dsn: ",$DBParams['dsn'],"\n";
606 if (string_starts_with($dbtype, 'PDO_')) {
607 $DBParams['dbtype'] = 'PDO';
608 $DBParams['dsn'] = preg_replace("/^([^:]+):/", substr($dbtype, 4).":", $DBParams['dsn']);
609 echo "dsn: ",$DBParams['dsn'],"\n";
612 if (preg_match('/sqlite$/', $dbtype)) {
613 $DBParams['dsn'] = preg_replace("/127\.0\.0\.1/", '', $DBParams['dsn']);
614 echo "dsn: ",$DBParams['dsn'],"\n";
616 $DBParams['directory'] = $cur_dir . '/.testbox';
617 if ($dbtype == 'flatfile')
618 $DBParams['directory'] = $cur_dir . '/.testbox/flatfile';
619 $DBParams['prefix'] = $database_prefix;
621 //$DBParams['dba_handler'] = $database_dba_handler;
623 echo "Testing DB Backend \"$dbtype\" ...\n";
625 $request = new MockRequest($DBParams);
626 if ( ! ENABLE_USER_NEW ) {
627 $request->_user->_request =& $request;
628 $request->_user->_dbi =& $request->_dbi;
630 if (DEBUG & _DEBUG_TRACE)
631 printMemoryUsage("PhpWikiInitialized");
633 foreach ($runtests as $test) {
634 if (!@ob_get_level()) ob_start();
635 $suite = new PHPUnit_TestSuite("phpwiki");
636 if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
637 require_once dirname(__FILE__).'/lib/'.$test.'.php';
639 require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
640 $suite->addTest( new PHPUnit_TestSuite($test) );
642 @set_time_limit(240);
643 $result = PHPUnit::run($suite);
644 echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
646 if ($result->failureCount() > 0) {
647 echo "More detail:\n";
648 echo $result->toString();
652 $request->chunkOutput();
653 $request->_dbi->close();
654 unset($request->_user);
655 unset($request->_dbi);
661 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
664 // (c-file-style: "gnu")
669 // c-hanging-comment-ender-p: nil
670 // indent-tabs-mode: nil