2 /* Copyright (C) 2004 Dan Frankowski <dfrankow@cs.umn.edu>
3 * Copyright (C) 2004,2005,2006 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 along
18 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
65 . $rootdir . $ini_sep . $rootdir . "lib/pear";
66 ini_set('include_path', $include_path);
67 define('DEFAULT_LANGUAGE','en'); // don't use browser detection
69 if (!isset($HTTP_SERVER_VARS)) {
70 $HTTP_SERVER_VARS =& $_SERVER;
71 $HTTP_GET_VARS =& $_GET;
72 $HTTP_POST_VARS =& $_POST;
75 if (!empty($HTTP_SERVER_VARS) and $HTTP_SERVER_VARS["SERVER_NAME"] == 'phpwiki.sourceforge.net') {
76 ini_set('include_path', ini_get('include_path') . ":/usr/share/pear");
77 //define('ENABLE_PAGEPERM',false); // costs nothing
78 define('USECACHE',false); // really?
79 //define('WIKIDB_NOCACHE_MARKUP',1);
82 // available database backends to test:
83 $database_backends = array(
85 'flatfile', // not yet committed
87 'SQL', // default backend defined in the config.ini DSN
88 'ADODB', // same backend as defined in the config.ini DSN
89 // specific backends (need to be setup as db=test_phpwiki)
90 'PearDB_pgsql', 'PearDB_sqlite', 'PearDB_mysql',
91 //'PearDB_oci8','PearDB_mssql',
92 'ADODB_postgres7', 'ADODB_sqlite', 'ADODB_mysql',
93 //'ADODB_oci8', 'ADODB_mssql',
96 if ((int)substr(phpversion(), 1) >= 5)
97 array_push($database_backends, 'PDO_pqsql', 'PDO_sqlite', 'PDO_mysql');
98 //'PDO_oci', 'PDO_odbc'
100 //TODO: convert cvs test
101 // For "cvs" see the separate tests/unit_test_backend_cvs.php (cvs is experimental)
102 //TODO: read some database values from config.ini, just use the "test_" prefix
103 // "flatfile" testing occurs in "tests/unit/.testbox/flatfile"
104 // "dba" needs the DATABASE_DBA_HANDLER, also in the .textbox directory
105 //$database_dba_handler = (substr(PHP_OS,0,3) == 'WIN') ? "db3" : "gdbm";
106 // "SQL" and "ADODB" need delete permissions to the test db
107 // You have to create that database beforehand with our schema
108 //$database_dsn = "mysql://wikiuser:@localhost/phpwiki";
109 $database_prefix = "test_";
111 // Quiet warnings in IniConfig.php
112 $HTTP_SERVER_VARS['REMOTE_ADDR'] = '127.0.0.1';
113 $HTTP_SERVER_VARS['HTTP_USER_AGENT'] = "PHPUnit";
115 function printMemoryUsage($msg = '') {
118 if ($msg) echo $msg,"\n";
119 if ((defined('DEBUG') and (DEBUG & 8)) or !defined('DEBUG')) {
120 require_once 'lib/stdlib.php';
121 echo "-- MEMORY USAGE: ";
123 $mem = getMemoryUsage();
124 if (!$initmem) $initmem = $mem;
125 // old libc on sf.net server doesn't understand "%+4d"
126 echo sprintf("%8d\t[%s%4d]\t[+%4d]\n", $mem, $mem > $oldmem ? "+" : ($mem == $oldmem ? " " : ""),
127 $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," :";
149 printSimpleTrace(debug_backtrace());
152 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
155 // Get error reporting to call back, too
157 // set the error reporting level for this script
158 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
159 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
161 error_reporting(E_ALL); // php4
163 // This is too strict, fails on every notice and warning.
165 function myErrorHandler$errno, $errstr, $errfile, $errline) {
166 echo "$errfile: $errline: error# $errno: $errstr\n";
168 printSimpleTrace(debug_backtrace());
170 // The ErrorManager version
171 function _ErrorHandler_CB(&$error) {
173 printSimpleTrace(debug_backtrace());
174 if ($error->isFatal()) {
175 $error->errno = E_USER_WARNING;
176 return true; // ignore error
180 // set to the user defined error handler
181 // $old_error_handler = set_error_handler("myErrorHandler");
182 // This is already done via _DEBUG_TRACE
183 //$ErrorManager->pushErrorHandler(new WikiFunctionCb('_ErrorHandler_CB'));
186 function purge_dir($dir) {
188 if (!isset($finder)) {
189 $finder = new FileFinder;
191 $fileSet = new fileSet($dir);
192 assert(!empty($dir));
193 foreach ($fileSet->getFiles() as $f) {
198 function purge_testbox() {
200 if (isset($GLOBALS['request'])) {
201 $dbi = $GLOBALS['request']->getDbh();
203 $dir = $DBParams['directory'];
204 switch ($DBParams['dbtype']) {
207 assert(!empty($dir));
208 foreach (array('latest_ver','links','page_data','ver_data') as $d) {
209 purge_dir("$dir/$d");
215 foreach (array_reverse($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('title' => 'doubleclick to (un)select all', 'style'=>'font-weight: bold; padding: 1px; border: 2px outset;','onDblClick'=>'flipAll(\'test[\')'),
249 foreach ($GLOBALS['alltests'] as $s) {
250 $id = preg_replace("/\W/", "", $s) . $i++;
251 $input = array('type' => 'checkbox', 'name' => 'test['.$s.']', 'value' => '1', 'id' => $id);
252 if (in_array($s,$GLOBALS['runtests'])) $input['checked'] = 'checked';
253 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), $s), HTML::br());
255 $form->pushContent(HTML::td($option));
257 $option = HTML::div(array('class' => 'option'),
258 HTML::span(array('title' => 'doubleclick to (un)select all', 'style'=>'font-weight: bold; padding: 1px; border: 2px outset;', 'onDblClick'=>'flipAll(\'db[\')'),
261 foreach ($GLOBALS['database_backends'] as $s) {
262 $id = preg_replace("/\W/", "", $s) . $i++;
263 $input = array('type' => 'checkbox', 'name' => 'db['.$s.']', 'value' => '1', 'id' => $id);
264 if (in_array($s,$GLOBALS['run_database_backends'])) $input['checked'] = 'checked';
265 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), $s), HTML::br());
267 $form->pushContent(HTML::td($option));
270 "function flipAll(formName) {
272 formObj = document.forms[0];
273 for (var i=0; i < formObj.length; i++) {
274 fldObj = formObj.elements[i];
275 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,formName.length) == formName)) {
276 if (isFirstSet == -1)
277 isFirstSet = (fldObj.checked) ? true : false;
278 fldObj.checked = (isFirstSet) ? false : true;
282 function updateDebugEdit(formObj) {
284 for (var i=0; i < formObj.length; i++) {
285 fldObj = formObj.elements[i];
286 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,7) == '_debug[')) {
287 if (fldObj.checked) val = val + parseInt(fldObj.value);
290 formObj.debug.value = val;
292 function updateLevelEdit(formObj) {
293 for (var i=0; i < formObj.length; i++) {
294 fldObj = formObj.elements[i];
295 if ((fldObj.type == 'radio') && (fldObj.name.substring(0,7) == '_level[')) {
296 if (fldObj.checked) {
297 formObj.level.value = fldObj.value;
303 $option = HTML::div(array('class' => 'option'),
304 HTML::span(array('title' => 'doubleclick to (un)select all', 'style'=>'font-weight: bold; padding: 1px; border: 2px outset;',
305 'onDblClick'=>'flipAll(\'_debug[\')'),
307 HTML::input(array('name'=>'debug','id'=>'debug',
308 'value'=>$debug_level,'size'=>5)),
310 foreach (array('VERBOSE' => 1,
320 $id = preg_replace("/\W/", "", $s) . $i++;
321 $input = array('type' => 'checkbox', 'name' => '_debug[]', 'value' => $v, 'id' => $id,
322 'onClick' => 'updateDebugEdit(this.form)');
323 if ($debug_level & $v) $input['checked'] = 'checked';
324 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), "_DEBUG_".$s), HTML::br());
326 $form->pushContent(HTML::td($option));
328 $option = HTML::div(array('class' => 'option'),
329 HTML::span(array('style'=>'font-weight: bold;'), "level: "),
330 HTML::input(array('name'=>'level','id'=>'level',
331 'value'=>$user_level,'size'=>5)),
333 foreach (array('FORBIDDEN' => -1,
338 'UNOBTAINABLE'=> 100,
340 $id = preg_replace("/\W/", "", $s) . $i++;
341 $input = array('type' => 'radio', 'name' => '_level[]', 'value' => $v, 'id' => $id,
342 'onClick' => 'updateLevelEdit(this.form)');
343 if ($user_level & $v) $input['checked'] = 'checked';
344 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), "WIKIAUTH_".$s), HTML::br());
346 $form->pushContent(HTML::td($option));
349 $option = HTML::div(array('class' => 'option'), 'defines: ', HTML::br());
350 if (!empty($GLOBALS['define']))
351 foreach ($GLOBALS['define'] as $s) {
353 $input = array('type' => 'edit', 'name' => $s, 'value' => constant($s));
354 $option->pushContent(HTML::input($input), HTML::label(array('for' => $id), $s), HTML::br());
358 $form->pushContent(HTML::td($option));
359 $table = HTML::form(array('action' => $_SERVER['PHP_SELF'],
361 'accept-charset' => $GLOBALS['charset']),
363 HTML::table(HTML::tr(array('valign'=>'top'), $form)),
364 HTML::input(array('type' => 'submit')),
365 HTML::input(array('type' => 'reset')));
367 $table->pushContent(HiddenInputs(array('start_debug' => $start_debug)));
368 return $table->printXml();
371 //####################################################################
373 // End of preamble, run the test suite ..
375 //####################################################################
379 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
381 elseif (!empty($HTTP_SERVER_VARS['argv']))
382 $argv = $HTTP_SERVER_VARS['argv'];
383 elseif (!ini_get("register_argc_argv"))
384 echo "Could not read cmd args (register_argc_argv=Off?)\n";
387 $debug_level = 1; //was 9, _DEBUG_VERBOSE | _DEBUG_TRACE
388 //if (defined('E_STRICT')) $debug_level = 5; // add PARSER flag on php5
389 $user_level = 1; // BOGO (conflicts with RateIt)
390 // use argv (from cli) or tests (from browser) params to run only certain tests
391 // avoid pear: Console::Getopt
392 $alltests = array(/* valid tests without clean virgin setup */
393 'InlineParserTest','HtmlParserTest',
394 'PageListTest','ListPagesTest','XmlRpcTest',
397 /* valid tests only with clean virgin setup */
398 'AllPagesTest','AllUsersTest','OrphanedPagesTest',
399 'WantedPagesTest','TextSearchTest','IncludePageTest',
400 'AtomParserTest','AtomFeedTest',
401 /* final tests which require all valid pages and consumes > 32MB */
403 // support db=file db=dba test=SetupWiki test=DumpHtml debug=num -dconstant=value
404 // or db=file,dba test=SetupWiki,DumpHtml debug=num -dconstant=value
405 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
407 foreach ($HTTP_GET_VARS as $key => $val) {
409 foreach ($val as $k => $v) $argv[] = $key."=".$k;
410 elseif (strstr($val,",") and in_array($key, array("test","db")))
411 foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
413 $argv[] = $key."=".$val;
415 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0])) {
421 $run_database_backends = array();
423 foreach ($argv as $arg) {
424 if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
426 elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
427 $run_database_backends[] = $m[1];
428 elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
429 $debug_level = $m[1];
430 elseif (preg_match("/^level=(\d+)$/",$arg,$m))
432 elseif (preg_match("/^\-d(\w+)=(.+)$/",$arg,$m)) {
433 $define[$m[1]] = $m[2];
434 if ($m[2] == 'true') $m[2] = true;
435 elseif ($m[2] == 'false') $m[2] = false;
436 if (!defined($m[1])) define($m[1], $m[2]);
437 } elseif (in_array($arg, $alltests))
439 elseif ($debug_level & 1)
440 echo "ignored arg: ", $arg, "\n";
444 if (empty($run_database_backends))
445 $run_database_backends = $database_backends;
446 if (empty($runtests))
447 $runtests = $alltests;
448 if ($debug_level & 1) {
450 echo "PHP_SAPI=",php_sapi_name(), "\n";
451 echo "PHP_OS=",PHP_OS, "\n";
452 echo "PHP_VERSION=",PHP_VERSION, "\n";
453 echo "test=", join(",",$runtests),"\n";
454 echo "db=", join(",",$run_database_backends),"\n";
455 echo "debug=", $debug_level,"\n";
456 echo "level=", $user_level,"\n";
457 if (!empty($define)) {
458 foreach ($define as $k => $v) printConstant($k);
460 if ($debug_level & 8) {
461 echo "pid=",getmypid(),"\n";
467 if (!defined('DEBUG'))
468 define('DEBUG', $debug_level);
469 // override defaults:
470 if (!defined('RATING_STORAGE'))
471 define('RATING_STORAGE', 'WIKIPAGE');
472 if (!defined('GROUP_METHOD'))
473 define('GROUP_METHOD', 'NONE');
476 printMemoryUsage("beforePEAR");
479 printMemoryUsage("beforePhpWiki");
481 define('PHPWIKI_NOMAIN', true);
482 // Other needed files
483 require_once $rootdir.'index.php';
484 require_once $rootdir.'lib/main.php';
486 // init filefinder for pear path fixup.
487 FindFile ('PHPUnit.php', 'missing_okay');
488 // PEAR library (requires version ??)
489 require_once 'PHPUnit.php';
493 if ($debug_level & 1) {
495 echo "PHPWIKI_VERSION=",PHPWIKI_VERSION,
496 strstr(PHPWIKI_VERSION,"pre") ? strftime(" / %Y%m%d") : "","\n";
497 if ($debug_level & 9) {
498 // which constants affect memory?
499 foreach (explode(",","USECACHE,WIKIDB_NOCACHE_MARKUP,"
500 ."ENABLE_USER_NEW,ENABLE_PAGEPERM") as $v) {
507 global $ErrorManager;
508 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
509 // FIXME: ignore cached requests (if-modified-since) from cli
510 class MockRequest extends WikiRequest {
511 function MockRequest($dbparams) {
512 $this->_dbi = WikiDB::open($dbparams);
513 $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
514 $this->_group = new GroupNone();
515 $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
518 function getGroup() {
519 if (is_object($this->_group))
520 return $this->_group;
521 else // FIXME: this is set to "/f:" somewhere.
522 return new GroupNone();
526 if (ENABLE_USER_NEW) {
527 class MockUser extends _WikiUser {
528 function MockUser($name, $level) {
529 $this->_userid = $name;
530 $this->_isSignedIn = $level > 1;
531 $this->_level = $level;
533 function isSignedIn() {
534 return $this->_isSignedIn;
538 class MockUser extends WikiUser {
539 function MockUser($name, $level) {
540 $this->_userid = $name;
541 $this->_isSignedIn = $level > 1;
542 $this->_level = $level;
544 function isSignedIn() {
545 return $this->_isSignedIn;
552 $request->_user = WikiUser('AnonUser');
554 $request->_user = new WikiUser($request, 'AnonUser');
555 $request->_prefs = $request->_user->getPreferences();
558 if (DEBUG & _DEBUG_TRACE)
559 printMemoryUsage("PhpWikiLoaded");
561 // provide a nice input form for all options
562 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
563 echo html_option_form();
567 // save and restore all args for each test.
568 class phpwiki_TestCase extends PHPUnit_TestCase {
570 global $request, $WikiTheme;
571 include_once 'themes/'. THEME . "/themeinfo.php";
572 $this->_savedargs = $request->_args;
573 $request->_args = array();
575 echo $this->_name,"\n";
579 function tearDown() {
581 $request->_args = $this->_savedargs;
582 if (DEBUG & _DEBUG_TRACE)
587 // Test all db backends.
588 foreach ($run_database_backends as $dbtype) {
589 global $request, $DBParams;
590 // if (DEBUG & _DEBUG_TRACE)
591 // printMemoryUsage("PHPUnitInitialized");
592 $DBParams['dbtype'] = $dbtype;
593 if (string_starts_with($dbtype, 'PearDB_')) {
594 $DBParams['dbtype'] = 'SQL';
595 $DBParams['dsn'] = preg_replace("/^([^:]+):/", substr($dbtype, 7).":", $DBParams['dsn']);
596 echo "dsn: ",$DBParams['dsn'],"\n";
598 if (string_starts_with($dbtype, 'ADODB_')) {
599 $DBParams['dbtype'] = 'ADODB';
600 $DBParams['dsn'] = preg_replace("/^([^:]+):/", substr($dbtype, 6).":", $DBParams['dsn']);
601 echo "dsn: ",$DBParams['dsn'],"\n";
603 if (string_starts_with($dbtype, 'PDO_')) {
604 $DBParams['dbtype'] = 'PDO';
605 $DBParams['dsn'] = preg_replace("/^([^:]+):/", substr($dbtype, 4).":", $DBParams['dsn']);
606 echo "dsn: ",$DBParams['dsn'],"\n";
609 if (preg_match('/sqlite$/', $dbtype)) {
610 $DBParams['dsn'] = preg_replace("/127\.0\.0\.1/", '', $DBParams['dsn']);
611 echo "dsn: ",$DBParams['dsn'],"\n";
613 $DBParams['directory'] = $cur_dir . '/.testbox';
614 if ($dbtype == 'flatfile')
615 $DBParams['directory'] = $cur_dir . '/.testbox/flatfile';
616 $DBParams['prefix'] = $database_prefix;
618 //$DBParams['dba_handler'] = $database_dba_handler;
620 echo "Testing DB Backend \"$dbtype\" ...\n";
622 $request = new MockRequest($DBParams);
623 if ( ! ENABLE_USER_NEW ) {
624 $request->_user->_request =& $request;
625 $request->_user->_dbi =& $request->_dbi;
627 if (DEBUG & _DEBUG_TRACE)
628 printMemoryUsage("PhpWikiInitialized");
630 foreach ($runtests as $test) {
631 if (!@ob_get_level()) ob_start();
632 $suite = new PHPUnit_TestSuite("phpwiki");
633 if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
634 require_once dirname(__FILE__).'/lib/'.$test.'.php';
636 require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
637 $suite->addTest( new PHPUnit_TestSuite($test) );
639 @set_time_limit(240);
640 $result = PHPUnit::run($suite);
641 echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
643 if ($result->failureCount() > 0) {
644 echo "More detail:\n";
645 echo $result->toString();
649 $request->chunkOutput();
650 $request->_dbi->close();
651 unset($request->_user);
652 unset($request->_dbi);
658 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
665 // c-hanging-comment-ender-p: nil
666 // indent-tabs-mode: nil