]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - tests/unit/test.php
some sample memory usage
[SourceForge/phpwiki.git] / tests / unit / test.php
1 #!/usr/local/bin/php -Cq
2 <?php  
3 /* Copyright (C) 2004 Dan Frankowski <dfrankow@cs.umn.edu>
4  * Copyright (C) 2004 Reini Urban <rurban@x-ray.at>
5  *
6  * This file is part of PhpWiki.
7  * 
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  * 
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with PhpWiki; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /**
24  * Unit tests for PhpWiki. 
25  *
26  * You must have PEAR's PHPUnit package <http://pear.php.net/package/PHPUnit>. 
27  * These tests are unrelated to test/maketest.pl, which do not use PHPUnit.
28  * These tests run from the command-line as well as from the browser.
29  * Use the argv (from cli) or tests (from browser) params to run only certain tests.
30  *
31  * $ tests.php test=<testname1> test=<testname2> ... db=dba debug=9 level=10
32  */
33 /****************************************************************
34    User definable options
35 *****************************************************************/
36 // common cfg options are taken from config/config.ini
37
38 define('GROUP_METHOD', 'NONE');
39 define('USE_DB_SESSION', false);
40 define('RATING_STORAGE', 'WIKIPAGE');
41
42 // memory usage: (8MB limit on certain servers)
43 // setupwiki
44 // cli:  Mem16712 => Mem16928
45 // web:  Mem21216 => Mem26332 (5MB)
46
47 // dumphtml:
48 // cli: Mem20696 => Mem31240  (with USECACHE)    (10MB)
49 // cli: Mem20240 => Mem30212  (without USECACHE) (10MB)
50 // web: Mem29424 => Mem35400  (without USECACHE) (6MB)
51 //define('USECACHE', false);
52
53 // available database backends to test:
54 $database_backends = array(
55                            'file',
56                            'dba',
57                            'SQL',
58                            'ADODB',
59                            );
60 // "flatfile" testing occurs in "tests/unit/.testbox/"
61 // "dba" needs the DATABASE_DBA_HANDLER, also in the .textbox directory
62 $database_dba_handler = "db3";
63 // "SQL" and "ADODB" need delete permissions to the test db
64 //  You have to create that database beforehand with our schema
65 $database_dsn = "mysql://wikiuser:@localhost/phpwiki_test";
66 // For "cvs" see the seperate tests/unit_test_backend_cvs.php
67
68 ####################################################################
69 #
70 # Preamble needed to get the tests to run.
71 #
72 ####################################################################
73
74 $cur_dir = getcwd();
75 # Add root dir to the path
76 if (substr(PHP_OS,0,3) == 'WIN')
77     $cur_dir = str_replace("\\","/",$cur_dir);
78 $rootdir = $cur_dir . '/../../';
79 $ini_sep = substr(PHP_OS,0,3) == 'WIN' ? ';' : ':';
80 ini_set('include_path', ini_get('include_path') . $ini_sep . $rootdir);
81
82 # Quiet warnings in IniConfig.php
83 $HTTP_SERVER_VARS['REMOTE_ADDR'] = '127.0.0.1';
84 $HTTP_SERVER_VARS['HTTP_USER_AGENT'] = "PHPUnit";
85
86 function printMemoryUsage($msg = '') {
87     if ($msg) echo $msg,"\n";
88     if ((defined('DEBUG') and (DEBUG & 8)) or !defined('DEBUG')) {
89         echo "-- MEMORY USAGE: ";
90         if (function_exists('memory_get_usage')) {
91             echo memory_get_usage(),"\n";
92         } elseif (function_exists('getrusage')) {
93             $u = getrusage();
94             echo $u['ru_maxrss'],"\n";
95         } elseif (substr(PHP_OS,0,3)=='WIN') { // requires a newer cygwin
96             // what we want is the process memory only: apache or php
97             $pid = getmypid();
98             // this works only if it's a cygwin process (apache or php)
99             //echo `cat /proc/$pid/statm |cut -f1`,"\n";
100             // if it's native windows use something like this: 
101             // (requires pslist from systinternals.com)
102             echo `pslist $pid|grep -A1 Mem|perl -ane"print \$F[5]"`,"\n";
103         } else {
104             $pid = getmypid();
105             echo `ps -eo%mem,rss,pid | grep $pid`,"\n";
106         }
107         flush();
108     }
109 }
110 function printSimpleTrace($bt) {
111     //print_r($bt);
112     echo "Traceback:\n";
113     foreach ($bt as $i => $elem) {
114         if (!array_key_exists('file', $elem)) {
115             continue;
116         }
117         print "  " . $elem['file'] . ':' . $elem['line'] . "\n";
118     }
119 }
120 # Show lots of detail when an assert() in the code fails
121 function assert_callback( $script, $line, $message ) {
122    echo "assert failed: script ", $script," line ", $line," :";
123    echo "$message";
124    echo "Traceback:\n";
125    printSimpleTrace(debug_backtrace());
126    exit;
127 }
128 $foo = assert_options( ASSERT_CALLBACK, 'assert_callback');
129
130 #
131 # Get error reporting to call back, too
132 #
133 // set the error reporting level for this script
134 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
135     error_reporting(E_ALL & ~E_STRICT);         // exclude E_STRICT
136 else
137     error_reporting(E_ALL); // php4
138
139 // This is too strict, fails on every notice and warning. 
140 /*
141 function myErrorHandler$errno, $errstr, $errfile, $errline) {
142    echo "$errfile: $errline: error# $errno: $errstr\n";
143    echo "Traceback:\n";
144    printSimpleTrace(debug_backtrace());
145 }
146 // The ErrorManager version
147 function _ErrorHandler_CB(&$error) {
148    echo "Traceback:\n";
149    printSimpleTrace(debug_backtrace());
150    if ($error->isFatal()) {
151         $error->errno = E_USER_WARNING;
152         return true; // ignore error
153    }
154    return true;
155 }
156 // set to the user defined error handler
157 // $old_error_handler = set_error_handler("myErrorHandler");
158 // This is already done via _DEBUG_TRACE
159 //$ErrorManager->pushErrorHandler(new WikiFunctionCb('_ErrorHandler_CB'));
160 */
161
162 function purge_dir($dir) {
163     static $finder;
164     if (!isset($finder)) {
165         $finder = new FileFinder;
166     }
167     $fileSet = new fileSet($dir);
168     assert(!empty($dir));
169     foreach ($fileSet->getFiles() as $f) {
170         unlink("$dir/$f");
171     }
172 }
173
174 function purge_testbox() {
175     global $db_params;  
176     if (isset($GLOBALS['request'])) {
177         $dbi = $GLOBALS['request']->getDbh();
178     }
179     $dir = $db_params['directory'];
180     switch ($db_params['dbtype']) {
181     case 'file':
182         assert(!empty($dir));
183         foreach (array('latest_ver','links','page_data','ver_data') as $d) {
184             purge_dir("$dir/$d");
185         }
186         break;
187     case 'SQL':
188     case 'ADODB':
189         foreach ($dbi->_backend->_table_names as $table) {
190             $dbi->genericSqlQuery("DELETE FROM $table");
191         }
192         break;
193     case 'dba':
194         purge_dir($dir);
195         break;
196     }
197     if (isset($dbi)) {
198         $dbi->_cache->close();
199         $dbi->_backend->_latest_versions = array();
200     }
201 }
202
203 ####################################################################
204 #
205 # End of preamble, run the test suite ..
206 #
207 ####################################################################
208
209 # lib/config.php might do a cwd()
210
211 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
212     echo "<pre>\n";
213 // purge the testbox
214     
215 $debug_level = 9; //_DEBUG_VERBOSE | _DEBUG_TRACE
216 $user_level  = 1; // BOGO
217 // use argv (from cli) or tests (from browser) params to run only certain tests
218 // avoid pear: Console::Getopt
219 $alltests = array('InlineParserTest','HtmlParserTest','PageListTest','ListPagesTest',
220                   'SetupWiki','DumpHtml','AllPagesTest','AllUsersTest','OrphanedPagesTest');
221 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
222     $argv = array();
223     foreach ($HTTP_GET_VARS as $key => $val) {
224         if (is_array($val)) 
225             foreach ($val as $v) $argv[] = $key."=".$v;
226         elseif (strstr($val,",") and in_array($key,array("test","db")))
227             foreach (explode(",",$val) as $v) $argv[] = $key."=".$v;
228         else
229             $argv[] = $key."=".$val;
230     }
231 } elseif (!empty($argv) and preg_match("/test\.php$/", $argv[0]))
232     array_shift($argv);
233 if (!empty($argv)) {
234     //support db=file db=dba test=SetupWiki test=DumpHtml debug=num
235     $runtests = array();
236     $run_database_backends = array();
237     foreach ($argv as $arg) {
238         if (in_array($arg, $alltests))
239             $runtests[] = $arg;
240         elseif (preg_match("/test=(.+)/",$arg,$m) and in_array($m[1], $alltests))
241             $runtests[] = $m[1];
242         elseif (preg_match("/db=(.+)/",$arg,$m) and in_array($m[1], $database_backends))
243             $run_database_backends[] = $m[1];
244         elseif (preg_match("/debug=(\d+)/",$arg,$m))
245             $debug_level = $m[1];
246         elseif (preg_match("/level=(\d+)/",$arg,$m))
247             $user_level = $m[1];
248         elseif ($debug_level & 1)
249             echo "ignored arg: ", $arg, "\n";
250     }
251     if (!empty($run_database_backends))
252         $database_backends = $run_database_backends;
253     if (!empty($runtests))
254         $alltests = $runtests;
255     if ($debug_level & 1) {
256         echo "test=", join(",",$alltests),"\n";
257         echo "db=", join(",",$database_backends),"\n";
258         echo "debug=", $debug_level,"\n";
259         echo "level=", $user_level,"\n";
260         echo "pid=",getmypid(),"\n";
261         echo "\n";
262     }
263     flush();
264 }
265 define('DEBUG', $debug_level); 
266
267
268 if (DEBUG & 8)
269     printMemoryUsage("before PEAR");
270
271 # Test files
272 require_once 'PHPUnit.php';
273
274 if (DEBUG & 8)
275     printMemoryUsage("after PEAR, before PhpWiki");
276
277 define('PHPWIKI_NOMAIN', true);
278 # Other needed files
279 require_once $rootdir.'index.php';
280 require_once $rootdir.'lib/main.php';
281
282 global $ErrorManager;
283 $ErrorManager->setPostponedErrorMask(EM_FATAL_ERRORS|EM_WARNING_ERRORS|EM_NOTICE_ERRORS);
284 //FIXME: ignore cached requests (if-modified-since) from cli
285 class MockRequest extends WikiRequest {
286     function MockRequest(&$dbparams) {
287         $this->_dbi = WikiDB::open($dbparams);
288         $this->_user = new MockUser("a_user", $GLOBALS['user_level']);
289         $this->_group = WikiGroup::getGroup();
290         $this->_args = array('pagename' => 'HomePage', 'action' => 'browse');
291         $this->Request();
292     }
293     function getGroup() {
294         if (is_object($this->_group))
295             return $this->_group;
296         else // FIXME: this is set to "/f:" somewhere.
297             return WikiGroup::getGroup();
298     }
299 }
300
301 if (ENABLE_USER_NEW) {
302     class MockUser extends _WikiUser {
303         function MockUser($name, $level) {
304             $this->_userid = $name;
305             $this->_isSignedIn = $level > 1;
306             $this->_level = $level;
307         }
308         function isSignedIn() {
309             return $this->_isSignedIn;
310         }
311     }
312 } else {
313     class MockUser extends WikiUser {
314         function MockUser($name, $level) {
315             $this->_userid = $name;
316             $this->_isSignedIn = $level > 1;
317             $this->_level = $level;
318         }
319         function isSignedIn() {
320             return $this->_isSignedIn;
321         }
322     }
323 }
324
325 /*
326 if (ENABLE_USER_NEW)
327     $request->_user = WikiUser('AnonUser');
328 else {
329     $request->_user = new WikiUser($request, 'AnonUser');
330     $request->_prefs = $request->_user->getPreferences();
331 }
332 */
333 include_once("themes/" . THEME . "/themeinfo.php");
334
335 if (DEBUG & _DEBUG_TRACE)
336     printMemoryUsage("after PhpWiki, before tests");
337
338 // save and restore all args for each test.
339 class phpwiki_TestCase extends PHPUnit_TestCase {
340     function setUp() { 
341         global $request;
342         $this->_savedargs = $request->_args;
343         $request->_args = array();
344         if (DEBUG & 1) {
345             echo $this->_name,"\n";
346             flush();
347         }
348     }
349     function tearDown() {
350         global $request;
351         $request->_args = $this->_savedargs;
352         if (DEBUG & _DEBUG_TRACE)
353             printMemoryUsage();
354     }
355 }
356
357 # Test all db backends.
358 foreach ($database_backends as $dbtype) {
359
360     $suite  = new PHPUnit_TestSuite("phpwiki");
361
362     $db_params                         = array();
363     $db_params['directory']            = $cur_dir . '/.testbox';
364     $db_params['dsn']                  = $database_dsn;
365     $db_params['dba_handler']          = $database_dba_handler;
366     $db_params['dbtype']               = $dbtype;
367
368     echo "Testing DB Backend \"$dbtype\" ...\n";
369     $request = new MockRequest($db_params);
370
371     foreach ($alltests as $test) {
372         if (file_exists(dirname(__FILE__).'/lib/'.$test.'.php'))
373             require_once dirname(__FILE__).'/lib/'.$test.'.php';
374         else    
375             require_once dirname(__FILE__).'/lib/plugin/'.$test.'.php';
376         $suite->addTest( new PHPUnit_TestSuite($test) );
377     }
378
379     $result = PHPUnit::run($suite); 
380     echo "ran " . $result->runCount() . " tests, " . $result->failureCount() . " failures.\n";
381     flush();
382
383     if ($result->failureCount() > 0) {
384         echo "More detail:\n";
385         echo $result->toString();
386     }
387 }
388
389 if (isset($HTTP_SERVER_VARS['REQUEST_METHOD']))
390     echo "</pre>\n";
391
392 // (c-file-style: "gnu")
393 // Local Variables:
394 // mode: php
395 // tab-width: 8
396 // c-basic-offset: 4
397 // c-hanging-comment-ender-p: nil
398 // indent-tabs-mode: nil
399 // End:   
400 ?>