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>
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
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 seperate 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/"
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," :";
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']) {
209 assert(!empty($dir));
210 foreach (array('latest_ver','links','page_data','ver_data') as $d) {
211 purge_dir("$dir/$d");
217 foreach ($dbi->_backend->_table_names as $table) {
218 $dbi->genericSqlQuery("DELETE FROM $table");
226 $dbi->_cache->close();
227 $dbi->_backend->_latest_versions = array();
231 function printConstant($v) {
234 if (constant($v) or constant($v)===0 or constant($v)==='0') echo constant($v);
236 } else echo "undefined";
240 * via the HTML sapi interface print a form to easily change the current cmdline settings.
242 function html_option_form() {
243 global $debug_level, $user_level, $start_debug;
246 $option = HTML::div(array('class' => 'option'),
247 HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'test[\')'), 'test: '),
249 foreach ($GLOBALS['alltests'] as $s) {
250 $input = array('type' => 'checkbox', 'name' => 'test['.$s.']', 'value' => '1');
251 if (in_array($s,$GLOBALS['runtests'])) $input['checked'] = 'checked';
252 $option->pushContent(HTML::input($input), $s, HTML::br());
254 $form->pushContent(HTML::td($option));
256 $option = HTML::div(array('class' => 'option'),
257 HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'db[\')'), 'db: '),
259 foreach ($GLOBALS['database_backends'] as $s) {
260 $input = array('type' => 'checkbox', 'name' => 'db['.$s.']', 'value' => '1');
261 if (in_array($s,$GLOBALS['run_database_backends'])) $input['checked'] = 'checked';
262 $option->pushContent(HTML::input($input), $s, HTML::br());
264 $form->pushContent(HTML::td($option));
267 "function flipAll(formName) {
269 formObj = document.forms[0];
270 for (var i=0; i < formObj.length; i++) {
271 fldObj = formObj.elements[i];
272 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,formName.length) == formName)) {
273 if (isFirstSet == -1)
274 isFirstSet = (fldObj.checked) ? true : false;
275 fldObj.checked = (isFirstSet) ? false : true;
279 function updateDebugEdit(formObj) {
281 for (var i=0; i < formObj.length; i++) {
282 fldObj = formObj.elements[i];
283 if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,7) == '_debug[')) {
284 if (fldObj.checked) val = val + parseInt(fldObj.value);
287 formObj.debug.value = val;
289 function updateLevelEdit(formObj) {
290 for (var i=0; i < formObj.length; i++) {
291 fldObj = formObj.elements[i];
292 if ((fldObj.type == 'radio') && (fldObj.name.substring(0,7) == '_level[')) {
293 if (fldObj.checked) {
294 formObj.level.value = fldObj.value;
300 $option = HTML::div(array('class' => 'option'),
301 HTML::span(array('style'=>'font-weight: bold',
302 'onDblClick'=>'flipAll(\'_debug[\')'),
304 HTML::input(array('name'=>'debug','id'=>'debug',
305 'value'=>$debug_level,'size'=>5)),
307 foreach (array('VERBOSE' => 1,
316 $input = array('type' => 'checkbox', 'name' => '_debug[]', 'value' => $v,
317 'onClick' => 'updateDebugEdit(this.form)');
318 if ($debug_level & $v) $input['checked'] = 'checked';
319 $option->pushContent(HTML::input($input), "_DEBUG_".$s, HTML::br());
321 $form->pushContent(HTML::td($option));
323 $option = HTML::div(array('class' => 'option'),
324 HTML::span(array('style'=>'font-weight: bold'), "level: "),
325 HTML::input(array('name'=>'level','id'=>'level',
326 'value'=>$user_level,'size'=>5)),
328 foreach (array('FORBIDDEN' => -1,
333 'UNOBTAINABLE'=> 100,
335 $input = array('type' => 'radio', 'name' => '_level[]', 'value' => $v,
336 'onClick' => 'updateLevelEdit(this.form)');
337 if ($user_level & $v) $input['checked'] = 'checked';
338 $option->pushContent(HTML::input($input), "WIKIAUTH_".$s, HTML::br());
340 $form->pushContent(HTML::td($option));
343 $option = HTML::div(array('class' => 'option'), 'defines: ', HTML::br());
344 if (!empty($GLOBALS['define']))
345 foreach ($GLOBALS['define'] as $s) {
347 $input = array('type' => 'edit', 'name' => $s, 'value' => constant($s));
348 $option->pushContent(HTML::input($input), $s, HTML::br());
352 $form->pushContent(HTML::td($option));
353 $table = HTML::form(array('action' => $_SERVER['PHP_SELF'],
355 'accept-charset' => $GLOBALS['charset']),
357 HTML::table(HTML::tr(array('valign'=>'top'), $form)),
358 HTML::input(array('type' => 'submit')),
359 HTML::input(array('type' => 'reset')));
361 $table->pushContent(HiddenInputs(array('start_debug' => $start_debug)));
362 return $table->printXml();
365 //####################################################################
367 // End of preamble, run the test suite ..
369 //####################################################################
373 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
375 elseif (!empty($HTTP_SERVER_VARS['argv']))
376 $argv = $HTTP_SERVER_VARS['argv'];
377 elseif (!ini_get("register_argc_argv"))
378 echo "Could not read cmd args (register_argc_argv=Off?)\n";
381 $debug_level = 1; //was 9, _DEBUG_VERBOSE | _DEBUG_TRACE
382 //if (defined('E_STRICT')) $debug_level = 5; // add PARSER flag on php5
383 $user_level = 1; // BOGO (conflicts with RateIt)
384 // use argv (from cli) or tests (from browser) params to run only certain tests
385 // avoid pear: Console::Getopt
386 $alltests = array('InlineParserTest','HtmlParserTest',
387 'PageListTest','ListPagesTest',
389 'AllPagesTest','AllUsersTest','OrphanedPagesTest',
391 'TextSearchTest','IncludePageTest',
393 // support db=file db=dba test=SetupWiki test=DumpHtml debug=num -dconstant=value
394 // or db=file,dba test=SetupWiki,DumpHtml debug=num -dconstant=value
395 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
397 foreach ($HTTP_GET_VARS as $key => $val) {
399 foreach ($val as $k => $v) $argv[] = $key."=".$k;
400 elseif (strstr($val,",") and in_array($key, array("test","db")))
401 foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
403 $argv[] = $key."=".$val;
405 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0])) {
411 $run_database_backends = array();
413 foreach ($argv as $arg) {
414 if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
416 elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
417 $run_database_backends[] = $m[1];
418 elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
419 $debug_level = $m[1];
420 elseif (preg_match("/^level=(\d+)$/",$arg,$m))
422 elseif (preg_match("/^\-d(\w+)=(.+)$/",$arg,$m)) {
423 $define[$m[1]] = $m[2];
424 if ($m[2] == 'true') $m[2] = true;
425 elseif ($m[2] == 'false') $m[2] = false;
426 if (!defined($m[1])) define($m[1], $m[2]);
427 } elseif (in_array($arg, $alltests))
429 elseif ($debug_level & 1)
430 echo "ignored arg: ", $arg, "\n";
434 if (empty($run_database_backends))
435 $run_database_backends = $database_backends;
436 if (empty($runtests))
437 $runtests = $alltests;
438 if ($debug_level & 1) {
440 echo "PHP_SAPI=",php_sapi_name(), "\n";
441 echo "PHP_OS=",PHP_OS, "\n";
442 echo "PHP_VERSION=",PHP_VERSION, "\n";
443 echo "test=", join(",",$runtests),"\n";
444 echo "db=", join(",",$run_database_backends),"\n";
445 echo "debug=", $debug_level,"\n";
446 echo "level=", $user_level,"\n";
447 if (!empty($define)) {
448 foreach ($define as $k => $v) printConstant($k);
450 if ($debug_level & 8) {
451 echo "pid=",getmypid(),"\n";
457 if (!defined('DEBUG'))
458 define('DEBUG', $debug_level);
459 // override defaults:
460 if (!defined('RATING_STORAGE'))
461 define('RATING_STORAGE', 'WIKIPAGE');
462 if (!defined('GROUP_METHOD'))
463 define('GROUP_METHOD', 'NONE');
466 printMemoryUsage("beforePEAR");
469 printMemoryUsage("beforePhpWiki");
471 define('PHPWIKI_NOMAIN', true);
472 // Other needed files
473 require_once $rootdir.'index.php';
474 require_once $rootdir.'lib/main.php';
476 // init filefinder for pear path fixup.
477 FindFile ('PHPUnit.php', 'missing_okay');
478 // PEAR library (requires version ??)
479 require_once 'PHPUnit.php';
483 if ($debug_level & 1) {
485 echo "PHPWIKI_VERSION=",PHPWIKI_VERSION,
486 strstr(PHPWIKI_VERSION,"pre") ? strftime(" / %Y%m%d") : "","\n";
487 if ($debug_level & 9) {
488 // which constants affect memory?
489 foreach (explode(",","USECACHE,WIKIDB_NOCACHE_MARKUP,"
490 ."ENABLE_USER_NEW,ENABLE_PAGEPERM") as $v) {
497 global $ErrorManager;
498 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
499 // FIXME: ignore cached requests (if-modified-since) from cli
500 class MockRequest extends WikiRequest {
501 function MockRequest($dbparams) {
502 $this->_dbi = WikiDB::open($dbparams);
503 $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
504 $this->_group = new GroupNone();
505 $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
508 function getGroup() {
509 if (is_object($this->_group))
510 return $this->_group;
511 else // FIXME: this is set to "/f:" somewhere.
512 return new GroupNone();
516 if (ENABLE_USER_NEW) {
517 class MockUser extends _WikiUser {
518 function MockUser($name, $level) {
519 $this->_userid = $name;
520 $this->_isSignedIn = $level > 1;
521 $this->_level = $level;
523 function isSignedIn() {
524 return $this->_isSignedIn;
528 class MockUser extends WikiUser {
529 function MockUser($name, $level) {
530 $this->_userid = $name;
531 $this->_isSignedIn = $level > 1;
532 $this->_level = $level;
534 function isSignedIn() {
535 return $this->_isSignedIn;
542 $request->_user = WikiUser('AnonUser');
544 $request->_user = new WikiUser($request, 'AnonUser');
545 $request->_prefs = $request->_user->getPreferences();
548 if (DEBUG & _DEBUG_TRACE)
549 printMemoryUsage("PhpWikiLoaded");
551 // provide a nice input form for all options
552 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
553 echo html_option_form();
557 // save and restore all args for each test.
558 class phpwiki_TestCase extends PHPUnit_TestCase {
560 global $request, $WikiTheme;
561 include_once("themes/" . THEME . "/themeinfo.php");
562 $this->_savedargs = $request->_args;
563 $request->_args = array();
565 echo $this->_name,"\n";
569 function tearDown() {
571 $request->_args = $this->_savedargs;
572 if (DEBUG & _DEBUG_TRACE)
577 // Test all db backends.
578 foreach ($run_database_backends as $dbtype) {
580 // if (DEBUG & _DEBUG_TRACE)
581 // printMemoryUsage("PHPUnitInitialized");
582 $DBParams['dbtype'] = $dbtype;
583 if (string_starts_with($dbtype, 'PearDB_')) {
584 $DBParams['dbtype'] = 'SQL';
585 preg_replace("/^([^:]+):/", substr($dbtype, 7).":", $DBParams['dsn']);
587 if (string_starts_with($dbtype, 'ADODB_')) {
588 $DBParams['dbtype'] = 'ADODB';
589 preg_replace("/^([^:]+):/", substr($dbtype, 6).":", $DBParams['dsn']);
591 if (string_starts_with($dbtype, 'PDO_')) {
592 $DBParams['dbtype'] = 'PDO';
593 preg_replace("/^([^:]+):/", substr($dbtype, 4).":", $DBParams['dsn']);
595 $DBParams['directory'] = $cur_dir . '/.testbox';
596 if ($dbtype == 'flatfile')
597 $DBParams['directory'] = $cur_dir . '/.testbox/flatfile';
598 $DBParams['prefix'] = $database_prefix;
600 //$DBParams['dba_handler'] = $database_dba_handler;
602 echo "Testing DB Backend \"$dbtype\" ...\n";
603 $request = new MockRequest($DBParams);
604 if ( ! ENABLE_USER_NEW ) {
605 $request->_user->_request =& $request;
606 $request->_user->_dbi =& $request->_dbi;
608 if (DEBUG & _DEBUG_TRACE)
609 printMemoryUsage("PhpWikiInitialized");
611 foreach ($runtests as $test) {
612 if (!@ob_get_level()) ob_start();
613 $suite = new PHPUnit_TestSuite("phpwiki");
614 if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
615 require_once dirname(__FILE__).'/lib/'.$test.'.php';
617 require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
618 $suite->addTest( new PHPUnit_TestSuite($test) );
620 @set_time_limit(240);
621 $result = PHPUnit::run($suite);
622 echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
624 if ($result->failureCount() > 0) {
625 echo "More detail:\n";
626 echo $result->toString();
630 $request->chunkOutput();
631 $request->_dbi->close();
632 unset($request->_user);
633 unset($request->_dbi);
639 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
642 // $Log: not supported by cvs2svn $
644 // (c-file-style: "gnu")
649 // c-hanging-comment-ender-p: nil
650 // indent-tabs-mode: nil