]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - tests/unit/test.php
use config.ini for SQL settings, extra test per unit to reset timeout and avoid PHPUn...
[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 define('GROUP_METHOD', 'NONE');
38 define('USE_DB_SESSION', false);
39 define('RATING_STORAGE', 'WIKIPAGE');
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 ini_set('include_path', ini_get('include_path')
65         . $ini_sep . $rootdir 
66         . $ini_sep . $rootdir . "lib/pear");
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);
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    echo "Traceback:\n";
147    printSimpleTrace(debug_backtrace());
148    exit;
149 }
150 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
151
152 #
153 # Get error reporting to call back, too
154 #
155 // set the error reporting level for this script
156 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
157     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
158 else
159     error_reporting(E_ALL); // php4
160
161 // This is too strict, fails on every notice and warning. 
162 /*
163 function myErrorHandler$errno, $errstr, $errfile, $errline) {
164    echo "$errfile: $errline: error# $errno: $errstr\n";
165    echo "Traceback:\n";
166    printSimpleTrace(debug_backtrace());
167 }
168 // The ErrorManager version
169 function _ErrorHandler_CB(&$error) {
170    echo "Traceback:\n";
171    printSimpleTrace(debug_backtrace());
172    if ($error->isFatal()) {
173         $error->errno = E_USER_WARNING;
174         return true; // ignore error
175    }
176    return true;
177 }
178 // set to the user defined error handler
179 // $old_error_handler = set_error_handler("myErrorHandler");
180 // This is already done via _DEBUG_TRACE
181 //$ErrorManager->pushErrorHandler(new WikiFunctionCb('_ErrorHandler_CB'));
182 */
183
184 function purge_dir($dir) {
185     static $finder;
186     if (!isset($finder)) {
187         $finder = new FileFinder;
188     }
189     $fileSet = new fileSet($dir);
190     assert(!empty($dir));
191     foreach ($fileSet->getFiles() as $f) {
192         unlink("$dir/$f");
193     }
194 }
195
196 function purge_testbox() {
197     global $DBParams;   
198     if (isset($GLOBALS['request'])) {
199         $dbi = $GLOBALS['request']->getDbh();
200     }
201     $dir = $DBParams['directory'];
202     switch ($DBParams['dbtype']) {
203     case 'file':
204         assert(!empty($dir));
205         foreach (array('latest_ver','links','page_data','ver_data') as $d) {
206             purge_dir("$dir/$d");
207         }
208         break;
209     case 'SQL':
210     case 'ADODB':
211         foreach ($dbi->_backend->_table_names as $table) {
212             $dbi->genericSqlQuery("DELETE FROM $table");
213         }
214         break;
215     case 'dba':
216         purge_dir($dir);
217         break;
218     }
219     if (isset($dbi)) {
220         $dbi->_cache->close();
221         $dbi->_backend->_latest_versions = array();
222     }
223 }
224
225 ####################################################################
226 #
227 # End of preamble, run the test suite ..
228 #
229 ####################################################################
230
231 # lib/config.php might do a cwd()
232
233 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
234     echo "<pre>\n";
235 elseif (!empty($HTTP_SERVER_VARS['argv']))
236     $argv = $HTTP_SERVER_VARS['argv'];
237 elseif (!ini_get("register_argc_argv"))
238     echo "Could not read cmd args (register_argc_argv=Off?)\n";
239 // purge the testbox
240     
241 $debug_level = 9; //_DEBUG_VERBOSE | _DEBUG_TRACE
242 $user_level  = 1; // BOGO
243 // use argv (from cli) or tests (from browser) params to run only certain tests
244 // avoid pear: Console::Getopt
245 $alltests = array('InlineParserTest','HtmlParserTest','PageListTest','ListPagesTest',
246                   'SetupWiki','DumpHtml','AllPagesTest','AllUsersTest','OrphanedPagesTest');
247 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
248     $argv = array();
249     foreach ($HTTP_GET_VARS as $key => $val) {
250         if (is_array($val)) 
251             foreach ($val as $v) $argv[] = $key."=".$v;
252         elseif (strstr($val,",") and in_array($key,array("test","db")))
253             foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
254         else
255             $argv[] = $key."=".$val;
256     }
257 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0]))
258     array_shift($argv);
259 if (!empty($argv)) {
260     //support db=file db=dba test=SetupWiki test=DumpHtml debug=num
261     $runtests = array();
262     $run_database_backends = array();
263     foreach ($argv as $arg) {
264         if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
265             $runtests[] = $m[1];
266         elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
267             $run_database_backends[] = $m[1];
268         elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
269             $debug_level = $m[1];
270         elseif (preg_match("/^level=(\d+)$/",$arg,$m))
271             $user_level = $m[1];
272         elseif (in_array($arg, $alltests))
273             $runtests[] = $arg;
274         elseif ($debug_level & 1)
275             echo "ignored arg: ", $arg, "\n";
276     }
277     if (!empty($run_database_backends))
278         $database_backends = $run_database_backends;
279     if (!empty($runtests))
280         $alltests = $runtests;
281     if ($debug_level & 1) {
282         echo "PHP_OS=",PHP_OS, "\n";
283         echo "PHP_VERSION=",PHP_VERSION, "\n";
284         echo "test=", join(",",$alltests),"\n";
285         echo "db=", join(",",$database_backends),"\n";
286         echo "debug=", $debug_level,"\n";
287         echo "level=", $user_level,"\n";
288         if ($debug_level & 8) {
289             echo "pid=",getmypid(),"\n";
290         }
291         echo "\n";
292     }
293     flush();
294 }
295 define('DEBUG', $debug_level); 
296
297 if (DEBUG & 8)
298     printMemoryUsage("before PEAR");
299
300 # Test files
301 require_once 'PHPUnit.php';
302
303 if (DEBUG & 8)
304     printMemoryUsage("after PEAR, before PhpWiki");
305
306 define('PHPWIKI_NOMAIN', true);
307 # Other needed files
308 require_once $rootdir.'index.php';
309 require_once $rootdir.'lib/main.php';
310
311 if ($debug_level & 9) {
312     // which constants affect memory?
313     foreach (explode(",","ENABLE_PAGEPERM,USECACHE,WIKIDB_NOCACHE_MARKUP") as $v)
314         echo "$v=",(defined($v) and constant($v)) ? constant($v) : "false","\n";
315 }
316
317 global $ErrorManager;
318 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
319 //FIXME: ignore cached requests (if-modified-since) from cli
320 class MockRequest extends WikiRequest {
321     function MockRequest(&$dbparams) {
322         $this->_dbi = WikiDB::open($dbparams);
323         $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
324         $this->_group = WikiGroup::getGroup();
325         $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
326         $this->Request();
327     }
328     function getGroup() {
329         if (is_object($this->_group))
330             return $this->_group;
331         else // FIXME: this is set to "/f:" somewhere.
332             return WikiGroup::getGroup();
333     }
334 }
335
336 if (ENABLE_USER_NEW) {
337     class MockUser extends _WikiUser {
338         function MockUser($name, $level) {
339             $this->_userid = $name;
340             $this->_isSignedIn = $level > 1;
341             $this->_level = $level;
342         }
343         function isSignedIn() {
344             return $this->_isSignedIn;
345         }
346     }
347 } else {
348     class MockUser extends WikiUser {
349         function MockUser($name, $level) {
350             $this->_userid = $name;
351             $this->_isSignedIn = $level > 1;
352             $this->_level = $level;
353         }
354         function isSignedIn() {
355             return $this->_isSignedIn;
356         }
357     }
358 }
359
360 /*
361 if (ENABLE_USER_NEW)
362     $request->_user = WikiUser('AnonUser');
363 else {
364     $request->_user = new WikiUser($request, 'AnonUser');
365     $request->_prefs = $request->_user->getPreferences();
366 }
367 */
368 include_once("themes/" . THEME . "/themeinfo.php");
369
370 if (DEBUG & _DEBUG_TRACE)
371     printMemoryUsage("PhpWiki loaded, not initialized");
372
373 // save and restore all args for each test.
374 class phpwiki_TestCase extends PHPUnit_TestCase {
375     function setUp() { 
376         global $request;
377         $this->_savedargs = $request->_args;
378         $request->_args = array();
379         if (DEBUG & 1) {
380             echo $this->_name,"\n";
381             flush();
382         }
383     }
384     function tearDown() {
385         global $request;
386         $request->_args = $this->_savedargs;
387         if (DEBUG & _DEBUG_TRACE)
388             printMemoryUsage();
389     }
390 }
391
392 # Test all db backends.
393 foreach ($database_backends as $dbtype) {
394
395     //    if (DEBUG & _DEBUG_TRACE)
396     //        printMemoryUsage("PHPUnit initialized");
397
398     $DBParams['dbtype']               = $dbtype;
399     $DBParams['directory']            = $cur_dir . '/.testbox';
400     $DBParams['prefix']               = $database_prefix;
401     // from config.ini
402     //$DBParams['dsn']                  = $database_dsn;
403     //$DBParams['dba_handler']          = $database_dba_handler;
404
405     echo "Testing DB Backend \"$dbtype\" ...\n";
406     $request = new MockRequest($DBParams);
407     if (DEBUG & _DEBUG_TRACE)
408         printMemoryUsage("PhpWiki initialized");
409
410     foreach ($alltests as $test) {
411         $suite  = new PHPUnit_TestSuite("phpwiki");
412         if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
413             require_once dirname(__FILE__).'/lib/'.$test.'.php';
414         else    
415             require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
416         $suite->addTest( new PHPUnit_TestSuite($test) );
417
418         @set_time_limit(240); 
419         $result = PHPUnit::run($suite); 
420         echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
421         flush();
422         if ($result->failureCount() > 0) {
423             echo "More detail:\n";
424             echo $result->toString();
425         }
426     }
427     unset($request);
428     unset($suite);
429     unset($result);
430 }
431
432 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
433     echo "</pre>\n";
434
435 // (c-file-style: "gnu")
436 // Local Variables:
437 // mode: php
438 // tab-width: 8
439 // c-basic-offset: 4
440 // c-hanging-comment-ender-p: nil
441 // indent-tabs-mode: nil
442 // End:   
443 ?>