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