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