]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - tests/unit/test.php
add getMemoryUsage to stdlib
[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 define('DEFAULT_LANGUAGE','en'); // don't use browser detection
67
68 if (!empty($HTTP_SERVER_VARS) and $HTTP_SERVER_VARS["SERVER_NAME"] == 'phpwiki.sourceforge.net') {
69     ini_set('include_path', ini_get('include_path') . ":/usr/share/pear");
70     //define('ENABLE_PAGEPERM',false); // costs nothing
71     define('USECACHE',false); // really?
72     //define('WIKIDB_NOCACHE_MARKUP',1);
73 }
74
75 // available database backends to test:
76 $database_backends = array(
77                            'file',
78                            'dba',
79                            'SQL',
80                            'ADODB',
81                            );
82 //TODO: convert cvs test                           
83 //TODO: read some database values from config.ini, just use the "test_" prefix
84 // "flatfile" testing occurs in "tests/unit/.testbox/"
85 // "dba" needs the DATABASE_DBA_HANDLER, also in the .textbox directory
86 //$database_dba_handler = (substr(PHP_OS,0,3) == 'WIN') ? "db3" : "gdbm";
87 // "SQL" and "ADODB" need delete permissions to the test db
88 //  You have to create that database beforehand with our schema
89 //$database_dsn = "mysql://wikiuser:@localhost/phpwiki";
90 $database_prefix = "test_";
91 // For "cvs" see the seperate tests/unit_test_backend_cvs.php
92
93 # Quiet warnings in IniConfig.php
94 $HTTP_SERVER_VARS['REMOTE_ADDR'] = '127.0.0.1';
95 $HTTP_SERVER_VARS['HTTP_USER_AGENT'] = "PHPUnit";
96
97 function printMemoryUsage($msg = '') {
98     static $mem = 0;
99     static $initmem = 0;
100     if ($msg) echo $msg,"\n";
101     if ((defined('DEBUG') and (DEBUG & 8)) or !defined('DEBUG')) {
102         echo "-- MEMORY USAGE: ";
103         $oldmem = $mem;
104         $mem = getMemoryUsage();
105         if (!$initmem) $initmem = $mem;
106         // old libc on sf.net server doesn't understand "%+4d"
107         echo sprintf("%8d\t[%s%4d]\t[+%4d]\n", $mem, $mem > $oldmem ? "+" : ($mem == $oldmem ? " " : ""), 
108                      $mem - $oldmem, $mem - $initmem);
109         // TODO: print time
110         flush();
111     }
112 }
113 /* // now in stdlib.php
114 function printSimpleTrace($bt) {
115     //print_r($bt);
116     echo "Traceback:\n";
117     foreach ($bt as $i => $elem) {
118         if (!array_key_exists('file', $elem)) {
119             continue;
120         }
121         print "  " . $elem['file'] . ':' . $elem['line'] . "\n";
122     }
123 }
124 */
125 # Show lots of detail when an assert() in the code fails
126 function assert_callback( $script, $line, $message ) {
127    echo "assert failed: script ", $script," line ", $line," :";
128    echo "$message";
129    if (function_exists('debug_backtrace')) { // >= 4.3.0
130        echo "Traceback:\n";
131        printSimpleTrace(debug_backtrace());
132    }
133    exit;
134 }
135 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
136
137 #
138 # Get error reporting to call back, too
139 #
140 // set the error reporting level for this script
141 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
142     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
143 else
144     error_reporting(E_ALL); // php4
145
146 // This is too strict, fails on every notice and warning. 
147 /*
148 function myErrorHandler$errno, $errstr, $errfile, $errline) {
149    echo "$errfile: $errline: error# $errno: $errstr\n";
150    echo "Traceback:\n";
151    printSimpleTrace(debug_backtrace());
152 }
153 // The ErrorManager version
154 function _ErrorHandler_CB(&$error) {
155    echo "Traceback:\n";
156    printSimpleTrace(debug_backtrace());
157    if ($error->isFatal()) {
158         $error->errno = E_USER_WARNING;
159         return true; // ignore error
160    }
161    return true;
162 }
163 // set to the user defined error handler
164 // $old_error_handler = set_error_handler("myErrorHandler");
165 // This is already done via _DEBUG_TRACE
166 //$ErrorManager->pushErrorHandler(new WikiFunctionCb('_ErrorHandler_CB'));
167 */
168
169 function purge_dir($dir) {
170     static $finder;
171     if (!isset($finder)) {
172         $finder = new FileFinder;
173     }
174     $fileSet = new fileSet($dir);
175     assert(!empty($dir));
176     foreach ($fileSet->getFiles() as $f) {
177         unlink("$dir/$f");
178     }
179 }
180
181 function purge_testbox() {
182     global $DBParams;   
183     if (isset($GLOBALS['request'])) {
184         $dbi = $GLOBALS['request']->getDbh();
185     }
186     $dir = $DBParams['directory'];
187     switch ($DBParams['dbtype']) {
188     case 'file':
189         assert(!empty($dir));
190         foreach (array('latest_ver','links','page_data','ver_data') as $d) {
191             purge_dir("$dir/$d");
192         }
193         break;
194     case 'SQL':
195     case 'ADODB':
196         foreach ($dbi->_backend->_table_names as $table) {
197             $dbi->genericSqlQuery("DELETE FROM $table");
198         }
199         break;
200     case 'dba':
201         purge_dir($dir);
202         break;
203     }
204     if (isset($dbi)) {
205         $dbi->_cache->close();
206         $dbi->_backend->_latest_versions = array();
207     }
208 }
209
210 function printConstant($v) {
211     echo "$v=";
212     if (defined($v)) {
213         if (constant($v) or constant($v)===0 or constant($v)==='0') echo constant($v);
214         else echo "false";
215     } else echo "undefined";
216     echo "\n";
217 }
218 /**
219  * via the HTML sapi interface print a form to easily change the current cmdline settings.
220  */
221 function html_option_form() {
222     global $debug_level, $user_level, $start_debug;
223
224     $form = HTML();
225     $option = HTML::div(array('class' => 'option'), 
226                         HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'test[\')'), 'test: '),
227                         HTML::br());
228     foreach ($GLOBALS['alltests'] as $s) {
229         $input = array('type' => 'checkbox', 'name' => 'test['.$s.']', 'value' => '1');
230         if (in_array($s,$GLOBALS['runtests'])) $input['checked'] = 'checked';
231         $option->pushContent(HTML::input($input), $s, HTML::br());
232     }
233     $form->pushContent(HTML::td($option));
234
235     $option = HTML::div(array('class' => 'option'), 
236                         HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'db[\')'), 'db: '),
237                         HTML::br());
238     foreach ($GLOBALS['database_backends'] as $s) {
239         $input = array('type' => 'checkbox', 'name' => 'db['.$s.']', 'value' => '1');
240         if (in_array($s,$GLOBALS['run_database_backends'])) $input['checked'] = 'checked';
241         $option->pushContent(HTML::input($input), $s, HTML::br());
242     }
243     $form->pushContent(HTML::td($option));
244
245     $js = JavaScript(
246 "function flipAll(formName) {
247   var isFirstSet = -1;
248   formObj = document.forms[0];
249   for (var i=0; i < formObj.length; i++) {
250       fldObj = formObj.elements[i];
251       if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,formName.length) == formName)) { 
252          if (isFirstSet == -1)
253            isFirstSet = (fldObj.checked) ? true : false;
254          fldObj.checked = (isFirstSet) ? false : true;
255        }
256    }
257 }
258 function updateDebugEdit(formObj) {
259   val=0;
260   for (var i=0; i < formObj.length; i++) {
261       fldObj = formObj.elements[i];
262       if ((fldObj.type == 'checkbox') && (fldObj.name.substring(0,7) == '_debug[')) { 
263          if (fldObj.checked) val = val + parseInt(fldObj.value);
264        }
265    }
266    formObj.debug.value = val;
267 }
268 function updateLevelEdit(formObj) {
269   for (var i=0; i < formObj.length; i++) {
270       fldObj = formObj.elements[i];
271       if ((fldObj.type == 'radio') && (fldObj.name.substring(0,7) == '_level[')) {
272          if (fldObj.checked) {
273             formObj.level.value = fldObj.value;
274             return;
275          }
276       }
277    }
278 }");
279     $option = HTML::div(array('class' => 'option'),
280                         HTML::span(array('style'=>'font-weight: bold','onDblClick'=>'flipAll(\'_debug[\')'), 'debug: '),
281                         HTML::input(array('name'=>'debug','id'=>'debug','value'=>$debug_level,'size'=>5)),
282                         HTML::br());
283     foreach (array('VERBOSE'    => 1,
284                    'PAGELINKS'  => 2,
285                    'PARSER'     => 4,
286                    'TRACE'      => 8,
287                    'INFO'       => 16,
288                    'APD'        => 32,
289                    'LOGIN'      => 64,
290                    'SQL'        => 128,
291                    ) as $s => $v) {
292         $input = array('type' => 'checkbox', 'name' => '_debug[]', 'value' => $v, 
293                        'onClick' => 'updateDebugEdit(this.form)');
294         if ($debug_level & $v) $input['checked'] = 'checked';
295         $option->pushContent(HTML::input($input), "_DEBUG_".$s, HTML::br());
296     }
297     $form->pushContent(HTML::td($option));
298
299     $option = HTML::div(array('class' => 'option'), 
300                         HTML::span(array('style'=>'font-weight: bold'), "level: "),
301                         HTML::input(array('name'=>'level','id'=>'level','value'=>$user_level,'size'=>5)),
302                         HTML::br());
303     foreach (array('FORBIDDEN'  => -1,
304                    'ANON'       => 0,
305                    'BOGO'       => 1,
306                    'USER'       => 2,
307                    'ADMIN'      => 10,
308                    'UNOBTAINABLE'=> 100,
309                    ) as $s => $v) {
310         $input = array('type' => 'radio', 'name' => '_level[]', 'value' => $v,
311                        'onClick' => 'updateLevelEdit(this.form)');
312         if ($user_level & $v) $input['checked'] = 'checked';
313         $option->pushContent(HTML::input($input), "WIKIAUTH_".$s, HTML::br());
314     }
315     $form->pushContent(HTML::td($option));
316
317     unset($input);
318     $option = HTML::div(array('class' => 'option'), 'defines: ', HTML::br());
319     if (!empty($GLOBALS['define']))
320       foreach ($GLOBALS['define'] as $s) {
321         if (defined($s)) {
322             $input = array('type' => 'edit', 'name' => $s, 'value' => constant($s));
323             $option->pushContent(HTML::input($input), $s, HTML::br());
324         }
325     }
326     if (!empty($input))
327         $form->pushContent(HTML::td($option));
328     $table = HTML::form(array('action' => $_SERVER['PHP_SELF'],
329                                           'method' => 'GET',
330                               'accept-charset' => $GLOBALS['charset']),
331                         $js,
332                         HTML::table(HTML::tr(array('valign'=>'top'), $form)),
333                         HTML::input(array('type' => 'submit')),
334                         HTML::input(array('type' => 'reset')));
335     if ($start_debug)
336         $table->pushContent(HiddenInputs(array('start_debug' => $start_debug)));
337     return $table->printXml();
338 }
339
340 ####################################################################
341 #
342 # End of preamble, run the test suite ..
343 #
344 ####################################################################
345
346 ob_start();
347
348 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
349     echo "<pre>\n";
350 elseif (!empty($HTTP_SERVER_VARS['argv']))
351     $argv = $HTTP_SERVER_VARS['argv'];
352 elseif (!ini_get("register_argc_argv"))
353     echo "Could not read cmd args (register_argc_argv=Off?)\n";
354 // purge the testbox
355     
356 $debug_level = 1; //was 9, _DEBUG_VERBOSE | _DEBUG_TRACE
357 if (defined('E_STRICT')) $debug_level = 5; // add PARSER flag on php5
358 $user_level  = 1; // BOGO (conflicts with RateIt)
359 // use argv (from cli) or tests (from browser) params to run only certain tests
360 // avoid pear: Console::Getopt
361 $alltests = array('InlineParserTest','HtmlParserTest',
362                   'PageListTest','ListPagesTest',
363                   'SetupWiki',
364                   'AllPagesTest','AllUsersTest','OrphanedPagesTest','WantedPagesTest',
365                   'DumpHtml');
366 // support db=file db=dba test=SetupWiki test=DumpHtml debug=num -dconstant=value
367 // or  db=file,dba test=SetupWiki,DumpHtml debug=num -dconstant=value
368 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
369     $argv = array();
370     foreach ($HTTP_GET_VARS as $key => $val) {
371         if (is_array($val))
372             foreach ($val as $k => $v) $argv[] = $key."=".$k;
373         elseif (strstr($val,",") and in_array($key, array("test","db")))
374             foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
375         else
376             $argv[] = $key."=".$val;
377     }
378 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0])) {
379     array_shift($argv);
380 }    
381 if (!empty($argv)) {
382     $runtests = array();
383     $define = array();
384     $run_database_backends = array();
385     foreach ($argv as $arg) {
386         if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
387             $runtests[] = $m[1];
388         elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
389             $run_database_backends[] = $m[1];
390         elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
391             $debug_level = $m[1];
392         elseif (preg_match("/^level=(\d+)$/",$arg,$m))
393             $user_level = $m[1];
394         elseif (preg_match("/^\-d(\w+)=(.+)$/",$arg,$m)) {
395             $define[$m[1]] = $m[2];
396             if ($m[2] == 'true') $m[2] = true;
397             elseif ($m[2] == 'false') $m[2] = false;
398             if (!defined($m[1])) define($m[1], $m[2]);
399         } elseif (in_array($arg, $alltests))
400             $runtests[] = $arg;
401         elseif ($debug_level & 1)
402             echo "ignored arg: ", $arg, "\n";
403     }
404 }
405
406 if (empty($run_database_backends))
407     $run_database_backends = $database_backends;
408 if (empty($runtests))
409     $runtests = $alltests;
410 if ($debug_level & 1) {
411     //echo "\n";
412     echo "PHP_SAPI=",php_sapi_name(), "\n";
413     echo "PHP_OS=",PHP_OS, "\n";
414     echo "PHP_VERSION=",PHP_VERSION, "\n";
415     echo "test=", join(",",$runtests),"\n";
416     echo "db=", join(",",$run_database_backends),"\n";
417     echo "debug=", $debug_level,"\n";
418     echo "level=", $user_level,"\n";
419     if (!empty($define)) {
420         foreach ($define as $k => $v) printConstant($k);
421     }
422     if ($debug_level & 8) {
423         echo "pid=",getmypid(),"\n";
424     }
425     echo "\n";
426 }
427 flush();
428
429 if (!defined('DEBUG'))
430     define('DEBUG', $debug_level);
431 // override defaults:
432 if (!defined('RATING_STORAGE')) 
433    define('RATING_STORAGE', 'WIKIPAGE');
434 if (!defined('GROUP_METHOD'))
435     define('GROUP_METHOD', 'NONE');
436
437 if (DEBUG & 8)
438     printMemoryUsage("beforePEAR");
439
440 if (DEBUG & 8)
441     printMemoryUsage("beforePhpWiki");
442
443 define('PHPWIKI_NOMAIN', true);
444 # Other needed files
445 require_once $rootdir.'index.php';
446 require_once $rootdir.'lib/main.php';
447
448 // init filefinder for pear path fixup.
449 FindFile ('PHPUnit.php', 'missing_okay');
450 // PEAR library (requires version ??)
451 require_once 'PHPUnit.php';
452
453 ob_end_flush();
454
455 if ($debug_level & 1) {
456     //echo "\n";
457     echo "PHPWIKI_VERSION=",PHPWIKI_VERSION, strstr(PHPWIKI_VERSION,"pre") ? strftime(" / %Y%m%d") : "","\n";
458     if ($debug_level & 9) {
459         // which constants affect memory?
460         foreach (explode(",","USECACHE,WIKIDB_NOCACHE_MARKUP,ENABLE_USER_NEW,ENABLE_PAGEPERM") as $v) {
461             printConstant($v);
462         }
463     }
464     echo "\n";
465 }
466
467 global $ErrorManager;
468 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
469 //FIXME: ignore cached requests (if-modified-since) from cli
470 class MockRequest extends WikiRequest {
471     function MockRequest(&$dbparams) {
472         $this->_dbi = WikiDB::open($dbparams);
473         $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
474         $this->_group = new GroupNone();
475         $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
476         $this->Request();
477     }
478     function getGroup() {
479         if (is_object($this->_group))
480             return $this->_group;
481         else // FIXME: this is set to "/f:" somewhere.
482             return new GroupNone();
483     }
484 }
485
486 if (ENABLE_USER_NEW) {
487     class MockUser extends _WikiUser {
488         function MockUser($name, $level) {
489             $this->_userid = $name;
490             $this->_isSignedIn = $level > 1;
491             $this->_level = $level;
492         }
493         function isSignedIn() {
494             return $this->_isSignedIn;
495         }
496     }
497 } else {
498     class MockUser extends WikiUser {
499         function MockUser($name, $level) {
500             $this->_userid = $name;
501             $this->_isSignedIn = $level > 1;
502             $this->_level = $level;
503         }
504         function isSignedIn() {
505             return $this->_isSignedIn;
506         }
507     }
508 }
509
510 /*
511 if (ENABLE_USER_NEW)
512     $request->_user = WikiUser('AnonUser');
513 else {
514     $request->_user = new WikiUser($request, 'AnonUser');
515     $request->_prefs = $request->_user->getPreferences();
516 }
517 */
518 include_once("themes/" . THEME . "/themeinfo.php");
519 if (DEBUG & _DEBUG_TRACE)
520     printMemoryUsage("PhpWikiLoaded");
521
522 // provide a nice input form for all options
523 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
524     echo html_option_form();
525 }
526
527 // save and restore all args for each test.
528 class phpwiki_TestCase extends PHPUnit_TestCase {
529     function setUp() { 
530         global $request;
531         $this->_savedargs = $request->_args;
532         $request->_args = array();
533         if (DEBUG & 1) {
534             echo $this->_name,"\n";
535             flush();
536         }
537     }
538     function tearDown() {
539         global $request;
540         $request->_args = $this->_savedargs;
541         if (DEBUG & _DEBUG_TRACE)
542             printMemoryUsage();
543     }
544 }
545
546 # Test all db backends.
547 foreach ($run_database_backends as $dbtype) {
548     //    if (DEBUG & _DEBUG_TRACE)
549     //        printMemoryUsage("PHPUnitInitialized");
550
551     $DBParams['dbtype']               = $dbtype;
552     $DBParams['directory']            = $cur_dir . '/.testbox';
553     $DBParams['prefix']               = $database_prefix;
554     // from config.ini
555     //$DBParams['dsn']                  = $database_dsn;
556     //$DBParams['dba_handler']          = $database_dba_handler;
557
558     echo "Testing DB Backend \"$dbtype\" ...\n";
559     $request = new MockRequest($DBParams);
560     if ( ! ENABLE_USER_NEW ) {
561         $request->_user->_request =& $request;
562         $request->_user->_dbi =& $request->_dbi;
563     }
564     if (DEBUG & _DEBUG_TRACE)
565         printMemoryUsage("PhpWikiInitialized");
566
567     foreach ($runtests as $test) {
568         if (!@ob_get_level()) ob_start();
569         $suite  = new PHPUnit_TestSuite("phpwiki");
570         if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
571             require_once dirname(__FILE__).'/lib/'.$test.'.php';
572         else    
573             require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
574         $suite->addTest( new PHPUnit_TestSuite($test) );
575
576         @set_time_limit(240); 
577         $result = PHPUnit::run($suite); 
578         echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
579         ob_end_flush();
580         if ($result->failureCount() > 0) {
581             echo "More detail:\n";
582             echo $result->toString();
583         }
584     }
585
586     $request->chunkOutput();
587     $request->_dbi->close();
588     unset($request->_user);
589     unset($request->_dbi);
590     unset($request);
591     unset($suite);
592     unset($result);
593 }
594
595 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
596     echo "</pre>\n";
597
598 // (c-file-style: "gnu")
599 // Local Variables:
600 // mode: php
601 // tab-width: 8
602 // c-basic-offset: 4
603 // c-hanging-comment-ender-p: nil
604 // indent-tabs-mode: nil
605 // End:   
606 ?>