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