]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - tests/unit/test.php
some unit tests fixes and updates
[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('RATING_STORAGE', 'WIKIPAGE');
39 define('GROUP_METHOD', 'NONE');
40 //define('USE_DB_SESSION', false);
41 //define('ENABLE_USER_NEW', false);
42
43 // memory usage: (8MB limit on certain servers)
44 // setupwiki
45 // cli:  Mem16712 => Mem16928
46 // web:  Mem21216 => Mem26332 (5MB)
47
48 // dumphtml:
49 // cli: Mem20696 => Mem31240  (with USECACHE)    (10MB)
50 // cli: Mem20240 => Mem30212  (without USECACHE) (10MB)
51 // web: Mem29424 => Mem35400  (without USECACHE) (6MB)
52 //define('USECACHE', false);
53
54 ####################################################################
55 #
56 # Preamble needed to get the tests to run.
57 #
58 ####################################################################
59
60 $cur_dir = getcwd();
61 # Add root dir to the path
62 if (substr(PHP_OS,0,3) == 'WIN')
63     $cur_dir = str_replace("\\","/", $cur_dir);
64 $rootdir = $cur_dir . '/../../';
65 $ini_sep = substr(PHP_OS,0,3) == 'WIN' ? ';' : ':';
66 ini_set('include_path', ini_get('include_path')
67         . $ini_sep . $rootdir 
68         . $ini_sep . $rootdir . "lib/pear");
69 if ($HTTP_SERVER_VARS["SERVER_NAME"] == 'phpwiki.sourceforge.net') {
70     ini_set('include_path', ini_get('include_path') . ":/usr/share/pear");
71     //define('ENABLE_PAGEPERM',false); // costs nothing
72     define('USECACHE',false);
73     //define('WIKIDB_NOCACHE_MARKUP',1);
74 }
75
76 // available database backends to test:
77 $database_backends = array(
78                            'file',
79                            'dba',
80                            'SQL',
81                            'ADODB',
82                            );
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         if (function_exists('memory_get_usage') and memory_get_usage()) {
105             $mem = memory_get_usage();
106             //        } elseif (function_exists('getrusage') and ($u = getrusage()) and !empty($u['ru_maxrss'])) {
107             //            $mem = $u['ru_maxrss'];
108         } elseif (substr(PHP_OS,0,3)=='WIN') { // requires a newer cygwin
109             // what we want is the process memory only: apache or php
110             $pid = getmypid();
111             // This works only if it's a cygwin process (apache or php)
112             //$mem = (integer) trim(system("cat /proc/$pid/statm |cut -f1"));
113             // if it's native windows use something like this: 
114             //   (requires pslist from sysinternals.com)
115             $memstr = system("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
116             $mem = (integer) trim($memstr);
117         } else {
118             $pid = getmypid();
119             //%MEM: Percentage of total memory in use by this process
120             //VSZ: Total virtual memory size, in 1K blocks.
121             //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
122             //CPU time used by process since it started.
123             //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
124             $memstr = system("ps -orss -p $pid|sed 1d");
125             $mem = (integer) trim($memstr);
126         }
127         if (!$initmem) $initmem = $mem;
128         // old libc on sf.net server doesn't understand "%+4d"
129         echo sprintf("%8d\t[%s%4d]\t[+%4d]\n", $mem, $mem > $oldmem ? "+" : ($mem == $oldmem ? " " : ""), $mem - $oldmem, $mem - $initmem);
130         // TODO: print time
131         flush();
132     }
133 }
134 function printSimpleTrace($bt) {
135     //print_r($bt);
136     echo "Traceback:\n";
137     foreach ($bt as $i => $elem) {
138         if (!array_key_exists('file', $elem)) {
139             continue;
140         }
141         print "  " . $elem['file'] . ':' . $elem['line'] . "\n";
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 #
239 # End of preamble, run the test suite ..
240 #
241 ####################################################################
242
243 ob_start();
244
245 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
246     echo "<pre>\n";
247 elseif (!empty($HTTP_SERVER_VARS['argv']))
248     $argv = $HTTP_SERVER_VARS['argv'];
249 elseif (!ini_get("register_argc_argv"))
250     echo "Could not read cmd args (register_argc_argv=Off?)\n";
251 // purge the testbox
252     
253 $debug_level = 1; //was 9, _DEBUG_VERBOSE | _DEBUG_TRACE
254 $user_level  = 1; // BOGO (conflicts with RateIt)
255 // use argv (from cli) or tests (from browser) params to run only certain tests
256 // avoid pear: Console::Getopt
257 $alltests = array('InlineParserTest','HtmlParserTest',
258                   'PageListTest','ListPagesTest',
259                   'SetupWiki',
260                   'AllPagesTest','AllUsersTest','OrphanedPagesTest',
261                   'DumpHtml');
262 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
263     $argv = array();
264     foreach ($HTTP_GET_VARS as $key => $val) {
265         if (is_array($val)) 
266             foreach ($val as $v) $argv[] = $key."=".$v;
267         elseif (strstr($val,",") and in_array($key,array("test","db")))
268             foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
269         else
270             $argv[] = $key."=".$val;
271     }
272 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0]))
273     array_shift($argv);
274 if (!empty($argv)) {
275     //support db=file db=dba test=SetupWiki test=DumpHtml debug=num -dconstant=value
276     $runtests = array();
277     $define = array();
278     $run_database_backends = array();
279     foreach ($argv as $arg) {
280         if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
281             $runtests[] = $m[1];
282         elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
283             $run_database_backends[] = $m[1];
284         elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
285             $debug_level = $m[1];
286         elseif (preg_match("/^level=(\d+)$/",$arg,$m))
287             $user_level = $m[1];
288         elseif (preg_match("/^\-d(\w+)=(.+)$/",$arg,$m)) {
289             $define[$m[1]] = $m[2];
290             if ($m[2] == 'true') $m[2] = true;
291             elseif ($m[2] == 'false') $m[2] = false;
292             if (!defined($m[1])) define($m[1], $m[2]);
293         } elseif (in_array($arg, $alltests))
294             $runtests[] = $arg;
295         elseif ($debug_level & 1)
296             echo "ignored arg: ", $arg, "\n";
297     }
298     if (!empty($run_database_backends))
299         $database_backends = $run_database_backends;
300     if (!empty($runtests))
301         $alltests = $runtests;
302     if ($debug_level & 1) {
303         echo "\n";
304         echo "PHP_SAPI=",php_sapi_name(), "\n";
305         echo "PHP_OS=",PHP_OS, "\n";
306         echo "PHP_VERSION=",PHP_VERSION, "\n";
307         echo "test=", join(",",$alltests),"\n";
308         echo "db=", join(",",$database_backends),"\n";
309         echo "debug=", $debug_level,"\n";
310         echo "level=", $user_level,"\n";
311         if (!empty($define)) {
312             foreach ($define as $k => $v) printConstant($k);
313         }
314         if ($debug_level & 8) {
315             echo "pid=",getmypid(),"\n";
316         }
317         echo "\n";
318     }
319     flush();
320 }
321 define('DEBUG', $debug_level); 
322
323 if (DEBUG & 8)
324     printMemoryUsage("beforePEAR");
325
326 # Test files
327 require_once 'PHPUnit.php';
328
329 if (DEBUG & 8)
330     printMemoryUsage("beforePhpWiki");
331
332 define('PHPWIKI_NOMAIN', true);
333 # Other needed files
334 require_once $rootdir.'index.php';
335 require_once $rootdir.'lib/main.php';
336 ob_end_flush();
337
338 if ($debug_level & 1) {
339     echo "\n";
340     echo "PHPWIKI_VERSION=",PHPWIKI_VERSION, strstr(PHPWIKI_VERSION,"pre") ? strftime("-%Y%m%d") : "","\n";
341     if ($debug_level & 9) {
342         // which constants affect memory?
343         foreach (explode(",","USECACHE,WIKIDB_NOCACHE_MARKUP,ENABLE_USER_NEW,ENABLE_PAGEPERM") as $v) {
344             printConstant($v);
345         }
346     }
347     echo "\n";
348 }
349
350 global $ErrorManager;
351 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
352 //FIXME: ignore cached requests (if-modified-since) from cli
353 class MockRequest extends WikiRequest {
354     function MockRequest(&$dbparams) {
355         $this->_dbi = WikiDB::open($dbparams);
356         $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
357         $this->_group = new GroupNone();
358         $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
359         $this->Request();
360     }
361     function getGroup() {
362         if (is_object($this->_group))
363             return $this->_group;
364         else // FIXME: this is set to "/f:" somewhere.
365             return new GroupNone();
366     }
367 }
368
369 if (ENABLE_USER_NEW) {
370     class MockUser extends _WikiUser {
371         function MockUser($name, $level) {
372             $this->_userid = $name;
373             $this->_isSignedIn = $level > 1;
374             $this->_level = $level;
375         }
376         function isSignedIn() {
377             return $this->_isSignedIn;
378         }
379     }
380 } else {
381     class MockUser extends WikiUser {
382         function MockUser($name, $level) {
383             $this->_userid = $name;
384             $this->_isSignedIn = $level > 1;
385             $this->_level = $level;
386         }
387         function isSignedIn() {
388             return $this->_isSignedIn;
389         }
390     }
391 }
392
393 /*
394 if (ENABLE_USER_NEW)
395     $request->_user = WikiUser('AnonUser');
396 else {
397     $request->_user = new WikiUser($request, 'AnonUser');
398     $request->_prefs = $request->_user->getPreferences();
399 }
400 */
401 include_once("themes/" . THEME . "/themeinfo.php");
402 if (DEBUG & _DEBUG_TRACE)
403     printMemoryUsage("PhpWikiLoaded");
404
405 // save and restore all args for each test.
406 class phpwiki_TestCase extends PHPUnit_TestCase {
407     function setUp() { 
408         global $request;
409         $this->_savedargs = $request->_args;
410         $request->_args = array();
411         if (DEBUG & 1) {
412             echo $this->_name,"\n";
413             flush();
414         }
415     }
416     function tearDown() {
417         global $request;
418         $request->_args = $this->_savedargs;
419         if (DEBUG & _DEBUG_TRACE)
420             printMemoryUsage();
421     }
422 }
423
424 # Test all db backends.
425 foreach ($database_backends as $dbtype) {
426
427     //    if (DEBUG & _DEBUG_TRACE)
428     //        printMemoryUsage("PHPUnitInitialized");
429
430     $DBParams['dbtype']               = $dbtype;
431     $DBParams['directory']            = $cur_dir . '/.testbox';
432     $DBParams['prefix']               = $database_prefix;
433     // from config.ini
434     //$DBParams['dsn']                  = $database_dsn;
435     //$DBParams['dba_handler']          = $database_dba_handler;
436
437     echo "Testing DB Backend \"$dbtype\" ...\n";
438     $request = new MockRequest($DBParams);
439     if ( ! ENABLE_USER_NEW ) {
440         $request->_user->_request =& $request;
441         $request->_user->_dbi =& $request->_dbi;
442     }
443     if (DEBUG & _DEBUG_TRACE)
444         printMemoryUsage("PhpWikiInitialized");
445
446     foreach ($alltests as $test) {
447         if (!@ob_get_level()) ob_start();
448         $suite  = new PHPUnit_TestSuite("phpwiki");
449         if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
450             require_once dirname(__FILE__).'/lib/'.$test.'.php';
451         else    
452             require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
453         $suite->addTest( new PHPUnit_TestSuite($test) );
454
455         @set_time_limit(240); 
456         $result = PHPUnit::run($suite); 
457         echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
458         ob_end_flush();
459         if ($result->failureCount() > 0) {
460             echo "More detail:\n";
461             echo $result->toString();
462         }
463     }
464
465     $request->chunkOutput();
466     $request->_dbi->close();
467     unset($request->_user);
468     unset($request->_dbi);
469     unset($request);
470     unset($suite);
471     unset($result);
472 }
473
474 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
475     echo "</pre>\n";
476
477 // (c-file-style: "gnu")
478 // Local Variables:
479 // mode: php
480 // tab-width: 8
481 // c-basic-offset: 4
482 // c-hanging-comment-ender-p: nil
483 // indent-tabs-mode: nil
484 // End:   
485 ?>