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