]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - tests/unit/test.php
more diagnostics, more sf.net overrides.
[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 // available database backends to test:
53 $database_backends = array(
54                            'file',
55                            'dba',
56                            'SQL',
57                            'ADODB',
58                            );
59 // "flatfile" testing occurs in "tests/unit/.testbox/"
60 // "dba" needs the DATABASE_DBA_HANDLER, also in the .textbox directory
61 $database_dba_handler = (substr(PHP_OS,0,3) == 'WIN') ? "db3" : "gdbm";
62 // "SQL" and "ADODB" need delete permissions to the test db
63 //  You have to create that database beforehand with our schema
64 $database_dsn = "mysql://wikiuser:@localhost/phpwiki_test";
65 // For "cvs" see the seperate tests/unit_test_backend_cvs.php
66
67 ####################################################################
68 #
69 # Preamble needed to get the tests to run.
70 #
71 ####################################################################
72
73 $cur_dir = getcwd();
74 # Add root dir to the path
75 if (substr(PHP_OS,0,3) == 'WIN')
76     $cur_dir = str_replace("\\","/", $cur_dir);
77 $rootdir = $cur_dir . '/../../';
78 $ini_sep = substr(PHP_OS,0,3) == 'WIN' ? ';' : ':';
79 ini_set('include_path', ini_get('include_path')
80         . $ini_sep . $rootdir 
81         . $ini_sep . $rootdir . "lib/pear");
82 if ($HTTP_SERVER_VARS["SERVER_NAME"] == 'phpwiki.sourceforge.net') {
83     ini_set('include_path', ini_get('include_path') . ":/usr/share/pear");
84     //define('ENABLE_PAGEPERM',false); // costs nothing
85     define('USECACHE',false);
86     define('WIKIDB_NOCACHE_MARKUP',1);
87 }
88
89 # Quiet warnings in IniConfig.php
90 $HTTP_SERVER_VARS['REMOTE_ADDR'] = '127.0.0.1';
91 $HTTP_SERVER_VARS['HTTP_USER_AGENT'] = "PHPUnit";
92
93 function printMemoryUsage($msg = '') {
94     if ($msg) echo $msg,"\n";
95     if ((defined('DEBUG') and (DEBUG & 8)) or !defined('DEBUG')) {
96         echo "-- MEMORY USAGE: ";
97         if (function_exists('memory_get_usage') and memory_get_usage()) {
98             echo memory_get_usage(),"\n";
99         /*
100         } elseif (function_exists('getrusage')) {
101             $u = getrusage();
102             echo $u['ru_maxrss'],"\n";
103         */
104         } elseif (substr(PHP_OS,0,3)=='WIN') { // requires a newer cygwin
105             // what we want is the process memory only: apache or php
106             $pid = getmypid();
107             // this works only if it's a cygwin process (apache or php)
108             //echo `cat /proc/$pid/statm |cut -f1`,"\n";
109
110             // if it's native windows use something like this: 
111             // (requires pslist from systinternals.com)
112             echo `pslist $pid|grep -A1 Mem|perl -ane"print \$F[5]"`,"\n";
113         } else {
114             $pid = getmypid();
115             //%MEM: Percentage of total memory in use by this process
116             //VSZ: Total virtual memory size, in 1K blocks.
117             //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
118             //CPU time used by process since it started.
119             echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
120         }
121         flush();
122     }
123 }
124 function printSimpleTrace($bt) {
125     //print_r($bt);
126     echo "Traceback:\n";
127     foreach ($bt as $i => $elem) {
128         if (!array_key_exists('file', $elem)) {
129             continue;
130         }
131         print "  " . $elem['file'] . ':' . $elem['line'] . "\n";
132     }
133 }
134 # Show lots of detail when an assert() in the code fails
135 function assert_callback( $script, $line, $message ) {
136    echo "assert failed: script ", $script," line ", $line," :";
137    echo "$message";
138    echo "Traceback:\n";
139    printSimpleTrace(debug_backtrace());
140    exit;
141 }
142 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
143
144 #
145 # Get error reporting to call back, too
146 #
147 // set the error reporting level for this script
148 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
149     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
150 else
151     error_reporting(E_ALL); // php4
152
153 // This is too strict, fails on every notice and warning. 
154 /*
155 function myErrorHandler$errno, $errstr, $errfile, $errline) {
156    echo "$errfile: $errline: error# $errno: $errstr\n";
157    echo "Traceback:\n";
158    printSimpleTrace(debug_backtrace());
159 }
160 // The ErrorManager version
161 function _ErrorHandler_CB(&$error) {
162    echo "Traceback:\n";
163    printSimpleTrace(debug_backtrace());
164    if ($error->isFatal()) {
165         $error->errno = E_USER_WARNING;
166         return true; // ignore error
167    }
168    return true;
169 }
170 // set to the user defined error handler
171 // $old_error_handler = set_error_handler("myErrorHandler");
172 // This is already done via _DEBUG_TRACE
173 //$ErrorManager->pushErrorHandler(new WikiFunctionCb('_ErrorHandler_CB'));
174 */
175
176 function purge_dir($dir) {
177     static $finder;
178     if (!isset($finder)) {
179         $finder = new FileFinder;
180     }
181     $fileSet = new fileSet($dir);
182     assert(!empty($dir));
183     foreach ($fileSet->getFiles() as $f) {
184         unlink("$dir/$f");
185     }
186 }
187
188 function purge_testbox() {
189     global $db_params;  
190     if (isset($GLOBALS['request'])) {
191         $dbi = $GLOBALS['request']->getDbh();
192     }
193     $dir = $db_params['directory'];
194     switch ($db_params['dbtype']) {
195     case 'file':
196         assert(!empty($dir));
197         foreach (array('latest_ver','links','page_data','ver_data') as $d) {
198             purge_dir("$dir/$d");
199         }
200         break;
201     case 'SQL':
202     case 'ADODB':
203         foreach ($dbi->_backend->_table_names as $table) {
204             $dbi->genericSqlQuery("DELETE FROM $table");
205         }
206         break;
207     case 'dba':
208         purge_dir($dir);
209         break;
210     }
211     if (isset($dbi)) {
212         $dbi->_cache->close();
213         $dbi->_backend->_latest_versions = array();
214     }
215 }
216
217 ####################################################################
218 #
219 # End of preamble, run the test suite ..
220 #
221 ####################################################################
222
223 # lib/config.php might do a cwd()
224
225 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
226     echo "<pre>\n";
227 elseif (!empty($HTTP_SERVER_VARS['argv']))
228     $argv = $HTTP_SERVER_VARS['argv'];
229 elseif (!ini_get("register_argc_argv"))
230     echo "Could not read cmd args (register_argc_argv=Off?)\n";
231 // purge the testbox
232     
233 $debug_level = 9; //_DEBUG_VERBOSE | _DEBUG_TRACE
234 $user_level  = 1; // BOGO
235 // use argv (from cli) or tests (from browser) params to run only certain tests
236 // avoid pear: Console::Getopt
237 $alltests = array('InlineParserTest','HtmlParserTest','PageListTest','ListPagesTest',
238                   'SetupWiki','DumpHtml','AllPagesTest','AllUsersTest','OrphanedPagesTest');
239 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
240     $argv = array();
241     foreach ($HTTP_GET_VARS as $key => $val) {
242         if (is_array($val)) 
243             foreach ($val as $v) $argv[] = $key."=".$v;
244         elseif (strstr($val,",") and in_array($key,array("test","db")))
245             foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
246         else
247             $argv[] = $key."=".$val;
248     }
249 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0]))
250     array_shift($argv);
251 if (!empty($argv)) {
252     //support db=file db=dba test=SetupWiki test=DumpHtml debug=num
253     $runtests = array();
254     $run_database_backends = array();
255     foreach ($argv as $arg) {
256         if (preg_match("/^test=(.+)$/",$arg,$m) and in_array($m[1], $alltests))
257             $runtests[] = $m[1];
258         elseif (preg_match("/^db=(.+)$/",$arg,$m) and in_array($m[1], $database_backends))
259             $run_database_backends[] = $m[1];
260         elseif (preg_match("/^debug=(\d+)$/",$arg,$m))
261             $debug_level = $m[1];
262         elseif (preg_match("/^level=(\d+)$/",$arg,$m))
263             $user_level = $m[1];
264         elseif (in_array($arg, $alltests))
265             $runtests[] = $arg;
266         elseif ($debug_level & 1)
267             echo "ignored arg: ", $arg, "\n";
268     }
269     if (!empty($run_database_backends))
270         $database_backends = $run_database_backends;
271     if (!empty($runtests))
272         $alltests = $runtests;
273     if ($debug_level & 1) {
274         echo "test=", join(",",$alltests),"\n";
275         echo "db=", join(",",$database_backends),"\n";
276         echo "debug=", $debug_level,"\n";
277         echo "level=", $user_level,"\n";
278         if ($debug_level & 8) {
279             echo "pid=",getmypid(),"\n";
280         }
281         echo "\n";
282     }
283     flush();
284 }
285 define('DEBUG', $debug_level); 
286
287 if (DEBUG & 8)
288     printMemoryUsage("before PEAR");
289
290 # Test files
291 require_once 'PHPUnit.php';
292
293 if (DEBUG & 8)
294     printMemoryUsage("after PEAR, before PhpWiki");
295
296 define('PHPWIKI_NOMAIN', true);
297 # Other needed files
298 require_once $rootdir.'index.php';
299 require_once $rootdir.'lib/main.php';
300
301 if ($debug_level & 9) {
302     echo "PHP_OS: ",PHP_OS, "\n";
303     echo "PHP_VERSION: ",PHP_VERSION, "\n";
304     foreach (explode(",","ENABLE_PAGEPERM,USECACHE,WIKIDB_NOCACHE_MARKUP") as $v)
305         echo "$v=",(defined($v) and constant($v)) ? constant($v) : "false","\n";
306 }
307
308 global $ErrorManager;
309 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
310 //FIXME: ignore cached requests (if-modified-since) from cli
311 class MockRequest extends WikiRequest {
312     function MockRequest(&$dbparams) {
313         $this->_dbi = WikiDB::open($dbparams);
314         $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
315         $this->_group = WikiGroup::getGroup();
316         $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
317         $this->Request();
318     }
319     function getGroup() {
320         if (is_object($this->_group))
321             return $this->_group;
322         else // FIXME: this is set to "/f:" somewhere.
323             return WikiGroup::getGroup();
324     }
325 }
326
327 if (ENABLE_USER_NEW) {
328     class MockUser extends _WikiUser {
329         function MockUser($name, $level) {
330             $this->_userid = $name;
331             $this->_isSignedIn = $level > 1;
332             $this->_level = $level;
333         }
334         function isSignedIn() {
335             return $this->_isSignedIn;
336         }
337     }
338 } else {
339     class MockUser extends WikiUser {
340         function MockUser($name, $level) {
341             $this->_userid = $name;
342             $this->_isSignedIn = $level > 1;
343             $this->_level = $level;
344         }
345         function isSignedIn() {
346             return $this->_isSignedIn;
347         }
348     }
349 }
350
351 /*
352 if (ENABLE_USER_NEW)
353     $request->_user = WikiUser('AnonUser');
354 else {
355     $request->_user = new WikiUser($request, 'AnonUser');
356     $request->_prefs = $request->_user->getPreferences();
357 }
358 */
359 include_once("themes/" . THEME . "/themeinfo.php");
360
361 if (DEBUG & _DEBUG_TRACE)
362     printMemoryUsage("after PhpWiki, before tests");
363
364 // save and restore all args for each test.
365 class phpwiki_TestCase extends PHPUnit_TestCase {
366     function setUp() { 
367         global $request;
368         $this->_savedargs = $request->_args;
369         $request->_args = array();
370         if (DEBUG & 1) {
371             echo $this->_name,"\n";
372             flush();
373         }
374     }
375     function tearDown() {
376         global $request;
377         $request->_args = $this->_savedargs;
378         if (DEBUG & _DEBUG_TRACE)
379             printMemoryUsage();
380     }
381 }
382
383 # Test all db backends.
384 foreach ($database_backends as $dbtype) {
385
386     $suite  = new PHPUnit_TestSuite("phpwiki");
387
388     $db_params                         = array();
389     $db_params['directory']            = $cur_dir . '/.testbox';
390     $db_params['dsn']                  = $database_dsn;
391     $db_params['dba_handler']          = $database_dba_handler;
392     $db_params['dbtype']               = $dbtype;
393
394     echo "Testing DB Backend \"$dbtype\" ...\n";
395     $request = new MockRequest($db_params);
396
397     foreach ($alltests as $test) {
398         if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
399             require_once dirname(__FILE__).'/lib/'.$test.'.php';
400         else    
401             require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
402         $suite->addTest( new PHPUnit_TestSuite($test) );
403     }
404
405     $result = PHPUnit::run($suite); 
406     echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
407     flush();
408
409     if ($result->failureCount() > 0) {
410         echo "More detail:\n";
411         echo $result->toString();
412     }
413 }
414
415 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
416     echo "</pre>\n";
417
418 // (c-file-style: "gnu")
419 // Local Variables:
420 // mode: php
421 // tab-width: 8
422 // c-basic-offset: 4
423 // c-hanging-comment-ender-p: nil
424 // indent-tabs-mode: nil
425 // End:   
426 ?>