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