]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - tests/unit/test.php
handle defaults without any args
[SourceForge/phpwiki.git] / tests / unit / test.php
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>
4  *
5  * This file is part of PhpWiki.
6  * 
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.
11  * 
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.
16  * 
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
20  */
21
22 /**
23  * Unit tests for PhpWiki. 
24  *
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.
29  *
30  * $ tests.php test=<testname1> test=<testname2> ... db=dba debug=9 level=10
31  */
32 /****************************************************************
33    User definable options
34 *****************************************************************/
35 // common cfg options are taken from config/config.ini
36
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);
40
41 // memory usage: (8MB limit on certain servers)
42 // setupwiki
43 // cli:  Mem16712 => Mem16928
44 // web:  Mem21216 => Mem26332 (5MB)
45
46 // dumphtml:
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);
51
52 ####################################################################
53 #
54 # Preamble needed to get the tests to run.
55 #
56 ####################################################################
57
58 $cur_dir = getcwd();
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);
66
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);
72 }
73
74 // available database backends to test:
75 $database_backends = array(
76                            'file',
77                            'dba',
78                            'SQL',
79                            'ADODB',
80                            );
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
90
91 # Quiet warnings in IniConfig.php
92 $HTTP_SERVER_VARS['REMOTE_ADDR'] = '127.0.0.1';
93 $HTTP_SERVER_VARS['HTTP_USER_AGENT'] = "PHPUnit";
94
95 function printMemoryUsage($msg = '') {
96     static $mem = 0;
97     static $initmem = 0;
98     if ($msg) echo $msg,"\n";
99     if ((defined('DEBUG') and (DEBUG & 8)) or !defined('DEBUG')) {
100         echo "-- MEMORY USAGE: ";
101         $oldmem = $mem;
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
108             $pid = getmypid();
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);
115         } else {
116             $pid = getmypid();
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);
124         }
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);
128         // TODO: print time
129         flush();
130     }
131 }
132 /* // now in stdlib.php
133 function printSimpleTrace($bt) {
134     //print_r($bt);
135     echo "Traceback:\n";
136     foreach ($bt as $i => $elem) {
137         if (!array_key_exists('file', $elem)) {
138             continue;
139         }
140         print "  " . $elem['file'] . ':' . $elem['line'] . "\n";
141     }
142 }
143 */
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," :";
147    echo "$message";
148    if (function_exists('debug_backtrace')) { // >= 4.3.0
149        echo "Traceback:\n";
150        printSimpleTrace(debug_backtrace());
151    }
152    exit;
153 }
154 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
155
156 #
157 # Get error reporting to call back, too
158 #
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
162 else
163     error_reporting(E_ALL); // php4
164
165 // This is too strict, fails on every notice and warning. 
166 /*
167 function myErrorHandler$errno, $errstr, $errfile, $errline) {
168    echo "$errfile: $errline: error# $errno: $errstr\n";
169    echo "Traceback:\n";
170    printSimpleTrace(debug_backtrace());
171 }
172 // The ErrorManager version
173 function _ErrorHandler_CB(&$error) {
174    echo "Traceback:\n";
175    printSimpleTrace(debug_backtrace());
176    if ($error->isFatal()) {
177         $error->errno = E_USER_WARNING;
178         return true; // ignore error
179    }
180    return true;
181 }
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'));
186 */
187
188 function purge_dir($dir) {
189     static $finder;
190     if (!isset($finder)) {
191         $finder = new FileFinder;
192     }
193     $fileSet = new fileSet($dir);
194     assert(!empty($dir));
195     foreach ($fileSet->getFiles() as $f) {
196         unlink("$dir/$f");
197     }
198 }
199
200 function purge_testbox() {
201     global $DBParams;   
202     if (isset($GLOBALS['request'])) {
203         $dbi = $GLOBALS['request']->getDbh();
204     }
205     $dir = $DBParams['directory'];
206     switch ($DBParams['dbtype']) {
207     case 'file':
208         assert(!empty($dir));
209         foreach (array('latest_ver','links','page_data','ver_data') as $d) {
210             purge_dir("$dir/$d");
211         }
212         break;
213     case 'SQL':
214     case 'ADODB':
215         foreach ($dbi->_backend->_table_names as $table) {
216             $dbi->genericSqlQuery("DELETE FROM $table");
217         }
218         break;
219     case 'dba':
220         purge_dir($dir);
221         break;
222     }
223     if (isset($dbi)) {
224         $dbi->_cache->close();
225         $dbi->_backend->_latest_versions = array();
226     }
227 }
228
229 function printConstant($v) {
230     echo "$v=";
231     if (defined($v)) {
232         if (constant($v) or constant($v)===0 or constant($v)==='0') echo constant($v);
233         else echo "false";
234     } else echo "undefined";
235     echo "\n";
236 }
237 /**
238  * via the HTML sapi interface print a form to easily change the current cmdline settings.
239  */
240 function html_option_form() {
241     global $debug_level,$user_level,$start_debug;
242
243     $form = HTML::tr(array('valign'=>'top'));
244     $option = HTML::div(array('class' => 'option'), 'test: ', HTML::br());
245     foreach ($GLOBALS['alltests'] as $s) {
246         $input = array('type' => 'checkbox', 'name' => 'test['.$s.']', 'value' => '1');
247         if (in_array($s,$GLOBALS['runtests'])) $input['checked'] = 'checked';
248         $option->pushContent(HTML::input($input), $s, HTML::br());
249     }
250     $form->pushContent(HTML::td($option));
251     $option = HTML::div(array('class' => 'option'), 'db: ', HTML::br());
252     foreach ($GLOBALS['database_backends'] as $s) {
253         $input = array('type' => 'checkbox', 'name' => 'db['.$s.']', 'value' => '1');
254         if (in_array($s,$GLOBALS['run_database_backends'])) $input['checked'] = 'checked';
255         $option->pushContent(HTML::input($input), $s, HTML::br());
256     }
257     $form->pushContent(HTML::td($option));
258     $form->pushContent(HTML::td(array('class' => 'option'), 'debug: ', 
259                                 HTML::input(array('name'=>'debug','value'=>$debug_level)),
260                                 HTML::br(),
261                                 'level: ', 
262                                 HTML::input(array('name'=>'level','value'=>$user_level)),
263                                 HTML::br()));
264     unset($input);
265     $option = HTML::div(array('class' => 'option'), 'defines: ', HTML::br());
266     if (!empty($GLOBALS['define']))
267       foreach ($GLOBALS['define'] as $s) {
268         if (defined($s)) {
269             $input = array('type' => 'edit', 'name' => $s, 'value' => constant($s));
270             $option->pushContent(HTML::input($input), $s, HTML::br());
271         }
272     }
273     if (!empty($input))
274         $form->pushContent(HTML::td($option));
275     $table = HTML::form(array('action' => $_SERVER['PHP_SELF'],
276                                           'method' => 'GET',
277                               'accept-charset' => $GLOBALS['charset']),
278                         HiddenInputs(array('start_debug' => $start_debug)),
279                         HTML::table($form),
280                         HTML::input(array('type' => 'submit')),
281                         HTML::input(array('type' => 'reset')));
282     return $table->printXml();
283 }
284
285 ####################################################################
286 #
287 # End of preamble, run the test suite ..
288 #
289 ####################################################################
290
291 ob_start();
292
293 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
294     echo "<pre>\n";
295 elseif (!empty($HTTP_SERVER_VARS['argv']))
296     $argv = $HTTP_SERVER_VARS['argv'];
297 elseif (!ini_get("register_argc_argv"))
298     echo "Could not read cmd args (register_argc_argv=Off?)\n";
299 // purge the testbox
300     
301 $debug_level = 1; //was 9, _DEBUG_VERBOSE | _DEBUG_TRACE
302 $user_level  = 1; // BOGO (conflicts with RateIt)
303 // use argv (from cli) or tests (from browser) params to run only certain tests
304 // avoid pear: Console::Getopt
305 $alltests = array('InlineParserTest','HtmlParserTest',
306                   'PageListTest','ListPagesTest',
307                   'SetupWiki',
308                   'AllPagesTest','AllUsersTest','OrphanedPagesTest','WantedPagesTest',
309                   'DumpHtml');
310 // support db=file db=dba test=SetupWiki test=DumpHtml debug=num -dconstant=value
311 // or  db=file,dba test=SetupWiki,DumpHtml debug=num -dconstant=value
312 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
313     $argv = array();
314     foreach ($HTTP_GET_VARS as $key => $val) {
315         if (is_array($val))
316             foreach ($val as $k => $v) $argv[] = $key."=".$k;
317         elseif (strstr($val,",") and in_array($key,array("test","db")))
318             foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
319         else
320             $argv[] = $key."=".$val;
321     }
322 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0])) {
323     array_shift($argv);
324 }    
325 if (!empty($argv)) {
326     $runtests = array();
327     $define = array();
328     $run_database_backends = array();
329     foreach ($argv as $arg) {
330         if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
331             $runtests[] = $m[1];
332         elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
333             $run_database_backends[] = $m[1];
334         elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
335             $debug_level = $m[1];
336         elseif (preg_match("/^level=(\d+)$/",$arg,$m))
337             $user_level = $m[1];
338         elseif (preg_match("/^\-d(\w+)=(.+)$/",$arg,$m)) {
339             $define[$m[1]] = $m[2];
340             if ($m[2] == 'true') $m[2] = true;
341             elseif ($m[2] == 'false') $m[2] = false;
342             if (!defined($m[1])) define($m[1], $m[2]);
343         } elseif (in_array($arg, $alltests))
344             $runtests[] = $arg;
345         elseif ($debug_level & 1)
346             echo "ignored arg: ", $arg, "\n";
347     }
348     if (empty($run_database_backends))
349         $run_database_backends = $database_backends;
350     if (empty($runtests))
351         $runtests = $alltests;
352     if ($debug_level & 1) {
353         //echo "\n";
354         echo "PHP_SAPI=",php_sapi_name(), "\n";
355         echo "PHP_OS=",PHP_OS, "\n";
356         echo "PHP_VERSION=",PHP_VERSION, "\n";
357         echo "test=", join(",",$runtests),"\n";
358         echo "db=", join(",",$run_database_backends),"\n";
359         echo "debug=", $debug_level,"\n";
360         echo "level=", $user_level,"\n";
361         if (!empty($define)) {
362             foreach ($define as $k => $v) printConstant($k);
363         }
364         if ($debug_level & 8) {
365             echo "pid=",getmypid(),"\n";
366         }
367         echo "\n";
368     }
369     flush();
370 } else {
371     if (empty($run_database_backends))
372         $run_database_backends = $database_backends;
373     if (empty($runtests))
374         $runtests = $alltests;
375 }
376 if (!defined('DEBUG'))
377     define('DEBUG', $debug_level);
378 // override defaults:
379 if (!defined('RATING_STORAGE')) 
380    define('RATING_STORAGE', 'WIKIPAGE');
381 if (!defined('GROUP_METHOD'))
382     define('GROUP_METHOD', 'NONE');
383
384 if (DEBUG & 8)
385     printMemoryUsage("beforePEAR");
386
387 if (DEBUG & 8)
388     printMemoryUsage("beforePhpWiki");
389
390 define('PHPWIKI_NOMAIN', true);
391 # Other needed files
392 require_once $rootdir.'index.php';
393 require_once $rootdir.'lib/main.php';
394
395 // init filefinder for pear path fixup.
396 FindFile ('PHPUnit.php', 'missing_okay');
397 // PEAR library (requires version ??)
398 require_once 'PHPUnit.php';
399
400 ob_end_flush();
401
402 if ($debug_level & 1) {
403     //echo "\n";
404     echo "PHPWIKI_VERSION=",PHPWIKI_VERSION, strstr(PHPWIKI_VERSION,"pre") ? strftime("-%Y%m%d") : "","\n";
405     if ($debug_level & 9) {
406         // which constants affect memory?
407         foreach (explode(",","USECACHE,WIKIDB_NOCACHE_MARKUP,ENABLE_USER_NEW,ENABLE_PAGEPERM") as $v) {
408             printConstant($v);
409         }
410     }
411     echo "\n";
412 }
413
414 global $ErrorManager;
415 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
416 //FIXME: ignore cached requests (if-modified-since) from cli
417 class MockRequest extends WikiRequest {
418     function MockRequest(&$dbparams) {
419         $this->_dbi = WikiDB::open($dbparams);
420         $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
421         $this->_group = new GroupNone();
422         $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
423         $this->Request();
424     }
425     function getGroup() {
426         if (is_object($this->_group))
427             return $this->_group;
428         else // FIXME: this is set to "/f:" somewhere.
429             return new GroupNone();
430     }
431 }
432
433 if (ENABLE_USER_NEW) {
434     class MockUser extends _WikiUser {
435         function MockUser($name, $level) {
436             $this->_userid = $name;
437             $this->_isSignedIn = $level > 1;
438             $this->_level = $level;
439         }
440         function isSignedIn() {
441             return $this->_isSignedIn;
442         }
443     }
444 } else {
445     class MockUser extends WikiUser {
446         function MockUser($name, $level) {
447             $this->_userid = $name;
448             $this->_isSignedIn = $level > 1;
449             $this->_level = $level;
450         }
451         function isSignedIn() {
452             return $this->_isSignedIn;
453         }
454     }
455 }
456
457 /*
458 if (ENABLE_USER_NEW)
459     $request->_user = WikiUser('AnonUser');
460 else {
461     $request->_user = new WikiUser($request, 'AnonUser');
462     $request->_prefs = $request->_user->getPreferences();
463 }
464 */
465 include_once("themes/" . THEME . "/themeinfo.php");
466 if (DEBUG & _DEBUG_TRACE)
467     printMemoryUsage("PhpWikiLoaded");
468
469 // provide a nice input form for all options
470 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
471     echo html_option_form();
472 }
473
474 // save and restore all args for each test.
475 class phpwiki_TestCase extends PHPUnit_TestCase {
476     function setUp() { 
477         global $request;
478         $this->_savedargs = $request->_args;
479         $request->_args = array();
480         if (DEBUG & 1) {
481             echo $this->_name,"\n";
482             flush();
483         }
484     }
485     function tearDown() {
486         global $request;
487         $request->_args = $this->_savedargs;
488         if (DEBUG & _DEBUG_TRACE)
489             printMemoryUsage();
490     }
491 }
492
493 # Test all db backends.
494 foreach ($database_backends as $dbtype) {
495
496     //    if (DEBUG & _DEBUG_TRACE)
497     //        printMemoryUsage("PHPUnitInitialized");
498
499     $DBParams['dbtype']               = $dbtype;
500     $DBParams['directory']            = $cur_dir . '/.testbox';
501     $DBParams['prefix']               = $database_prefix;
502     // from config.ini
503     //$DBParams['dsn']                  = $database_dsn;
504     //$DBParams['dba_handler']          = $database_dba_handler;
505
506     echo "Testing DB Backend \"$dbtype\" ...\n";
507     $request = new MockRequest($DBParams);
508     if ( ! ENABLE_USER_NEW ) {
509         $request->_user->_request =& $request;
510         $request->_user->_dbi =& $request->_dbi;
511     }
512     if (DEBUG & _DEBUG_TRACE)
513         printMemoryUsage("PhpWikiInitialized");
514
515     foreach ($runtests as $test) {
516         if (!@ob_get_level()) ob_start();
517         $suite  = new PHPUnit_TestSuite("phpwiki");
518         if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
519             require_once dirname(__FILE__).'/lib/'.$test.'.php';
520         else    
521             require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
522         $suite->addTest( new PHPUnit_TestSuite($test) );
523
524         @set_time_limit(240); 
525         $result = PHPUnit::run($suite); 
526         echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
527         ob_end_flush();
528         if ($result->failureCount() > 0) {
529             echo "More detail:\n";
530             echo $result->toString();
531         }
532     }
533
534     $request->chunkOutput();
535     $request->_dbi->close();
536     unset($request->_user);
537     unset($request->_dbi);
538     unset($request);
539     unset($suite);
540     unset($result);
541 }
542
543 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
544     echo "</pre>\n";
545
546 // (c-file-style: "gnu")
547 // Local Variables:
548 // mode: php
549 // tab-width: 8
550 // c-basic-offset: 4
551 // c-hanging-comment-ender-p: nil
552 // indent-tabs-mode: nil
553 // End:   
554 ?>