Rename the test files to insure a better test execution order
[plcapi.git] / tests / 3LocalhostTest.php
1 <?php
2
3 include_once __DIR__ . '/../lib/xmlrpc.inc';
4 include_once __DIR__ . '/../lib/xmlrpc_wrappers.inc';
5
6 include_once __DIR__ . '/parse_args.php';
7
8 class LocalhostTest extends PHPUnit_Framework_TestCase
9 {
10     /** @var xmlrpc_client $client */
11     public $client = null;
12     public $method = 'http';
13     public $timeout = 10;
14     public $request_compression = null;
15     public $accepted_compression = '';
16     public $args = array();
17
18     protected static $failed_tests = array();
19
20     public static function fail($message = '')
21     {
22         // save in global var that this particular test has failed
23         // (but only if not called from subclass objects / multitests)
24         if (function_exists('debug_backtrace') && strtolower(get_called_class()) == 'localhosttests') {
25             global $failed_tests;
26             $trace = debug_backtrace();
27             for ($i = 0; $i < count($trace); $i++) {
28                 if (strpos($trace[$i]['function'], 'test') === 0) {
29                     self::$failed_tests[$trace[$i]['function']] = true;
30                     break;
31                 }
32             }
33         }
34
35         parent::fail($message);
36     }
37
38     /**
39      * @todo be smarter with setup, do not use global variables anymore
40      */
41     public function setUp()
42     {
43         $this->args = argParser::getArgs();
44
45         $server = explode(':', $this->args['LOCALSERVER']);
46         if (count($server) > 1) {
47             $this->client = new xmlrpc_client($this->args['URI'], $server[0], $server[1]);
48         } else {
49             $this->client = new xmlrpc_client($this->args['URI'], $this->args['LOCALSERVER']);
50         }
51         if ($this->args['DEBUG']) {
52             $this->client->setDebug($this->args['DEBUG']);
53         }
54         $this->client->request_compression = $this->request_compression;
55         $this->client->accepted_compression = $this->accepted_compression;
56     }
57
58     public function send($msg, $errrorcode = 0, $return_response = false)
59     {
60         $r = $this->client->send($msg, $this->timeout, $this->method);
61         // for multicall, return directly array of responses
62         if (is_array($r)) {
63             return $r;
64         }
65         if (is_array($errrorcode)) {
66             $this->assertContains($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
67         }
68         else {
69             $this->assertEquals($r->faultCode(), $errrorcode, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
70         }
71         if (!$r->faultCode()) {
72             if ($return_response) {
73                 return $r;
74             } else {
75                 return $r->value();
76             }
77         } else {
78             return;
79         }
80     }
81
82     public function testString()
83     {
84         $sendstring = "here are 3 \"entities\": < > & " .
85             "and here's a dollar sign: \$pretendvarname and a backslash too: " . chr(92) .
86             " - isn't that great? \\\"hackery\\\" at it's best " .
87             " also don't want to miss out on \$item[0]. " .
88             "The real weird stuff follows: CRLF here" . chr(13) . chr(10) .
89             "a simple CR here" . chr(13) .
90             "a simple LF here" . chr(10) .
91             "and then LFCR" . chr(10) . chr(13) .
92             "last but not least weird names: G" . chr(252) . "nter, El" . chr(232) . "ne, and an xml comment closing tag: -->";
93         $f = new xmlrpcmsg('examples.stringecho', array(
94             new xmlrpcval($sendstring, 'string'),
95         ));
96         $v = $this->send($f);
97         if ($v) {
98             // when sending/receiving non-US-ASCII encoded strings, XML says cr-lf can be normalized.
99             // so we relax our tests...
100             $l1 = strlen($sendstring);
101             $l2 = strlen($v->scalarval());
102             if ($l1 == $l2) {
103                 $this->assertEquals($sendstring, $v->scalarval());
104             } else {
105                 $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendstring), $v->scalarval());
106             }
107         }
108     }
109
110     public function testAddingDoubles()
111     {
112         // note that rounding errors mean we
113         // keep precision to sensible levels here ;-)
114         $a = 12.13;
115         $b = -23.98;
116         $f = new xmlrpcmsg('examples.addtwodouble', array(
117             new xmlrpcval($a, 'double'),
118             new xmlrpcval($b, 'double'),
119         ));
120         $v = $this->send($f);
121         if ($v) {
122             $this->assertEquals($a + $b, $v->scalarval());
123         }
124     }
125
126     public function testAdding()
127     {
128         $f = new xmlrpcmsg('examples.addtwo', array(
129             new xmlrpcval(12, 'int'),
130             new xmlrpcval(-23, 'int'),
131         ));
132         $v = $this->send($f);
133         if ($v) {
134             $this->assertEquals(12 - 23, $v->scalarval());
135         }
136     }
137
138     public function testInvalidNumber()
139     {
140         $f = new xmlrpcmsg('examples.addtwo', array(
141             new xmlrpcval('fred', 'int'),
142             new xmlrpcval("\"; exec('ls')", 'int'),
143         ));
144         $v = $this->send($f);
145         /// @todo a fault condition should be generated here
146         /// by the server, which we pick up on
147         if ($v) {
148             $this->assertEquals(0, $v->scalarval());
149         }
150     }
151
152     public function testBoolean()
153     {
154         $f = new xmlrpcmsg('examples.invertBooleans', array(
155             new xmlrpcval(array(
156                 new xmlrpcval(true, 'boolean'),
157                 new xmlrpcval(false, 'boolean'),
158                 new xmlrpcval(1, 'boolean'),
159                 new xmlrpcval(0, 'boolean'),
160                 //new xmlrpcval('true', 'boolean'),
161                 //new xmlrpcval('false', 'boolean')
162             ),
163                 'array'
164             ),));
165         $answer = '0101';
166         $v = $this->send($f);
167         if ($v) {
168             $sz = $v->arraysize();
169             $got = '';
170             for ($i = 0; $i < $sz; $i++) {
171                 $b = $v->arraymem($i);
172                 if ($b->scalarval()) {
173                     $got .= '1';
174                 } else {
175                     $got .= '0';
176                 }
177             }
178             $this->assertEquals($answer, $got);
179         }
180     }
181
182     public function testBase64()
183     {
184         $sendstring = 'Mary had a little lamb,
185 Whose fleece was white as snow,
186 And everywhere that Mary went
187 the lamb was sure to go.
188
189 Mary had a little lamb
190 She tied it to a pylon
191 Ten thousand volts went down its back
192 And turned it into nylon';
193         $f = new xmlrpcmsg('examples.decode64', array(
194             new xmlrpcval($sendstring, 'base64'),
195         ));
196         $v = $this->send($f);
197         if ($v) {
198             if (strlen($sendstring) == strlen($v->scalarval())) {
199                 $this->assertEquals($sendstring, $v->scalarval());
200             } else {
201                 $this->assertEquals(str_replace(array("\r\n", "\r"), array("\n", "\n"), $sendstring), $v->scalarval());
202             }
203         }
204     }
205
206     public function testDateTime()
207     {
208         $time = time();
209         $t1 = new xmlrpcval($time, 'dateTime.iso8601');
210         $t2 = new xmlrpcval(iso8601_encode($time), 'dateTime.iso8601');
211         $this->assertEquals($t1->serialize(), $t2->serialize());
212         if (class_exists('DateTime')) {
213             $datetime = new DateTime();
214             // skip this test for php 5.2. It is a bit harder there to build a DateTime from unix timestamp with proper TZ info
215             if (is_callable(array($datetime, 'setTimestamp'))) {
216                 $t3 = new xmlrpcval($datetime->setTimestamp($time), 'dateTime.iso8601');
217                 $this->assertEquals($t1->serialize(), $t3->serialize());
218             }
219         }
220     }
221
222     public function testCountEntities()
223     {
224         $sendstring = "h'fd>onc>>l>>rw&bpu>q>e<v&gxs<ytjzkami<";
225         $f = new xmlrpcmsg('validator1.countTheEntities', array(
226             new xmlrpcval($sendstring, 'string'),
227         ));
228         $v = $this->send($f);
229         if ($v) {
230             $got = '';
231             $expected = '37210';
232             $expect_array = array('ctLeftAngleBrackets', 'ctRightAngleBrackets', 'ctAmpersands', 'ctApostrophes', 'ctQuotes');
233             while (list(, $val) = each($expect_array)) {
234                 $b = $v->structmem($val);
235                 $got .= $b->me['int'];
236             }
237             $this->assertEquals($expected, $got);
238         }
239     }
240
241     public function _multicall_msg($method, $params)
242     {
243         $struct['methodName'] = new xmlrpcval($method, 'string');
244         $struct['params'] = new xmlrpcval($params, 'array');
245
246         return new xmlrpcval($struct, 'struct');
247     }
248
249     public function testServerMulticall()
250     {
251         // We manually construct a system.multicall() call to ensure
252         // that the server supports it.
253
254         // NB: This test will NOT pass if server does not support system.multicall.
255
256         // Based on http://xmlrpc-c.sourceforge.net/hacks/test_multicall.py
257         $good1 = $this->_multicall_msg(
258             'system.methodHelp',
259             array(php_xmlrpc_encode('system.listMethods')));
260         $bad = $this->_multicall_msg(
261             'test.nosuch',
262             array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
263         $recursive = $this->_multicall_msg(
264             'system.multicall',
265             array(new xmlrpcval(array(), 'array')));
266         $good2 = $this->_multicall_msg(
267             'system.methodSignature',
268             array(php_xmlrpc_encode('system.listMethods')));
269         $arg = new xmlrpcval(
270             array($good1, $bad, $recursive, $good2),
271             'array'
272         );
273
274         $f = new xmlrpcmsg('system.multicall', array($arg));
275         $v = $this->send($f);
276         if ($v) {
277             //$this->assertTrue($r->faultCode() == 0, "fault from system.multicall");
278             $this->assertTrue($v->arraysize() == 4, "bad number of return values");
279
280             $r1 = $v->arraymem(0);
281             $this->assertTrue(
282                 $r1->kindOf() == 'array' && $r1->arraysize() == 1,
283                 "did not get array of size 1 from good1"
284             );
285
286             $r2 = $v->arraymem(1);
287             $this->assertTrue(
288                 $r2->kindOf() == 'struct',
289                 "no fault from bad"
290             );
291
292             $r3 = $v->arraymem(2);
293             $this->assertTrue(
294                 $r3->kindOf() == 'struct',
295                 "recursive system.multicall did not fail"
296             );
297
298             $r4 = $v->arraymem(3);
299             $this->assertTrue(
300                 $r4->kindOf() == 'array' && $r4->arraysize() == 1,
301                 "did not get array of size 1 from good2"
302             );
303         }
304     }
305
306     public function testClientMulticall1()
307     {
308         // NB: This test will NOT pass if server does not support system.multicall.
309
310         $this->client->no_multicall = false;
311
312         $good1 = new xmlrpcmsg('system.methodHelp',
313             array(php_xmlrpc_encode('system.listMethods')));
314         $bad = new xmlrpcmsg('test.nosuch',
315             array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
316         $recursive = new xmlrpcmsg('system.multicall',
317             array(new xmlrpcval(array(), 'array')));
318         $good2 = new xmlrpcmsg('system.methodSignature',
319             array(php_xmlrpc_encode('system.listMethods'))
320         );
321
322         $r = $this->send(array($good1, $bad, $recursive, $good2));
323         if ($r) {
324             $this->assertTrue(count($r) == 4, "wrong number of return values");
325         }
326
327         $this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
328         if (!$r[0]->faultCode()) {
329             $val = $r[0]->value();
330             $this->assertTrue(
331                 $val->kindOf() == 'scalar' && $val->scalartyp() == 'string',
332                 "good1 did not return string"
333             );
334         }
335         $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
336         $this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall");
337         $this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
338         if (!$r[3]->faultCode()) {
339             $val = $r[3]->value();
340             $this->assertTrue($val->kindOf() == 'array', "good2 did not return array");
341         }
342         // This is the only assert in this test which should fail
343         // if the test server does not support system.multicall.
344         $this->assertTrue($this->client->no_multicall == false,
345             "server does not support system.multicall"
346         );
347     }
348
349     public function testClientMulticall2()
350     {
351         // NB: This test will NOT pass if server does not support system.multicall.
352
353         $this->client->no_multicall = true;
354
355         $good1 = new xmlrpcmsg('system.methodHelp',
356             array(php_xmlrpc_encode('system.listMethods')));
357         $bad = new xmlrpcmsg('test.nosuch',
358             array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
359         $recursive = new xmlrpcmsg('system.multicall',
360             array(new xmlrpcval(array(), 'array')));
361         $good2 = new xmlrpcmsg('system.methodSignature',
362             array(php_xmlrpc_encode('system.listMethods'))
363         );
364
365         $r = $this->send(array($good1, $bad, $recursive, $good2));
366         if ($r) {
367             $this->assertTrue(count($r) == 4, "wrong number of return values");
368         }
369
370         $this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
371         if (!$r[0]->faultCode()) {
372             $val = $r[0]->value();
373             $this->assertTrue(
374                 $val->kindOf() == 'scalar' && $val->scalartyp() == 'string',
375                 "good1 did not return string");
376         }
377         $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
378         $this->assertTrue($r[2]->faultCode() == 0, "fault from (non recursive) system.multicall");
379         $this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
380         if (!$r[3]->faultCode()) {
381             $val = $r[3]->value();
382             $this->assertTrue($val->kindOf() == 'array', "good2 did not return array");
383         }
384     }
385
386     public function testClientMulticall3()
387     {
388         // NB: This test will NOT pass if server does not support system.multicall.
389
390         $this->client->return_type = 'phpvals';
391         $this->client->no_multicall = false;
392
393         $good1 = new xmlrpcmsg('system.methodHelp',
394             array(php_xmlrpc_encode('system.listMethods')));
395         $bad = new xmlrpcmsg('test.nosuch',
396             array(php_xmlrpc_encode(1), php_xmlrpc_encode(2)));
397         $recursive = new xmlrpcmsg('system.multicall',
398             array(new xmlrpcval(array(), 'array')));
399         $good2 = new xmlrpcmsg('system.methodSignature',
400             array(php_xmlrpc_encode('system.listMethods'))
401         );
402
403         $r = $this->send(array($good1, $bad, $recursive, $good2));
404         if ($r) {
405             $this->assertTrue(count($r) == 4, "wrong number of return values");
406         }
407         $this->assertTrue($r[0]->faultCode() == 0, "fault from good1");
408         if (!$r[0]->faultCode()) {
409             $val = $r[0]->value();
410             $this->assertTrue(
411                 is_string($val), "good1 did not return string");
412         }
413         $this->assertTrue($r[1]->faultCode() != 0, "no fault from bad");
414         $this->assertTrue($r[2]->faultCode() != 0, "no fault from recursive system.multicall");
415         $this->assertTrue($r[3]->faultCode() == 0, "fault from good2");
416         if (!$r[3]->faultCode()) {
417             $val = $r[3]->value();
418             $this->assertTrue(is_array($val), "good2 did not return array");
419         }
420         $this->client->return_type = 'xmlrpcvals';
421     }
422
423     public function testCatchWarnings()
424     {
425         $f = new xmlrpcmsg('examples.generatePHPWarning', array(
426             new xmlrpcval('whatever', 'string'),
427         ));
428         $v = $this->send($f);
429         if ($v) {
430             $this->assertEquals($v->scalarval(), true);
431         }
432     }
433
434     public function testCatchExceptions()
435     {
436         $f = new xmlrpcmsg('examples.raiseException', array(
437             new xmlrpcval('whatever', 'string'),
438         ));
439         $v = $this->send($f, $GLOBALS['xmlrpcerr']['server_error']);
440         $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=1';
441         $v = $this->send($f, 1);
442         $this->client->path = $this->args['URI'] . '?EXCEPTION_HANDLING=2';
443         // depending on whether display_errors is ON or OFF on the server, we will get back a different error here,
444         // as php will generate an http status code of either 200 or 500...
445         $v = $this->send($f, array($GLOBALS['xmlrpcerr']['invalid_return'], $GLOBALS['xmlrpcerr']['http_error']));
446     }
447
448     public function testZeroParams()
449     {
450         $f = new xmlrpcmsg('system.listMethods');
451         $v = $this->send($f);
452     }
453
454     public function testCodeInjectionServerSide()
455     {
456         $f = new xmlrpcmsg('system.MethodHelp');
457         $f->payload = "<?xml version=\"1.0\"?><methodCall><methodName>validator1.echoStructTest</methodName><params><param><value><struct><member><name>','')); echo('gotcha!'); die(); //</name></member></struct></value></param></params></methodCall>";
458         $v = $this->send($f);
459         //$v = $r->faultCode();
460         if ($v) {
461             $this->assertEquals(0, $v->structsize());
462         }
463     }
464
465     public function testAutoRegisteredFunction()
466     {
467         $f = new xmlrpcmsg('examples.php.getStateName', array(
468             new xmlrpcval(23, 'int'),
469         ));
470         $v = $this->send($f);
471         if ($v) {
472             $this->assertEquals('Michigan', $v->scalarval());
473         } else {
474             $this->fail('Note: server can only auto register functions if running with PHP 5.0.3 and up');
475         }
476     }
477
478     public function testAutoRegisteredClass()
479     {
480         $f = new xmlrpcmsg('examples.php2.getStateName', array(
481             new xmlrpcval(23, 'int'),
482         ));
483         $v = $this->send($f);
484         if ($v) {
485             $this->assertEquals('Michigan', $v->scalarval());
486             $f = new xmlrpcmsg('examples.php3.getStateName', array(
487                 new xmlrpcval(23, 'int'),
488             ));
489             $v = $this->send($f);
490             if ($v) {
491                 $this->assertEquals('Michigan', $v->scalarval());
492             }
493         } else {
494             $this->fail('Note: server can only auto register class methods if running with PHP 5.0.3 and up');
495         }
496     }
497
498     public function testAutoRegisteredMethod()
499     {
500         // make a 'deep client copy' as the original one might have many properties set
501         $func = wrap_xmlrpc_method($this->client, 'examples.getStateName', array('simple_client_copy' => 1));
502         if ($func == '') {
503             $this->fail('Registration of examples.getStateName failed');
504         } else {
505             $v = $func(23);
506             // work around bug in current version of phpunit
507             if (is_object($v)) {
508                 $v = var_export($v, true);
509             }
510             $this->assertEquals('Michigan', $v);
511         }
512     }
513
514     public function testGetCookies()
515     {
516         // let server set to us some cookies we tell it
517         $cookies = array(
518             //'c1' => array(),
519             'c2' => array('value' => 'c2'),
520             'c3' => array('value' => 'c3', 'expires' => time() + 60 * 60 * 24 * 30),
521             'c4' => array('value' => 'c4', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/'),
522             'c5' => array('value' => 'c5', 'expires' => time() + 60 * 60 * 24 * 30, 'path' => '/', 'domain' => 'localhost'),
523         );
524         $cookiesval = php_xmlrpc_encode($cookies);
525         $f = new xmlrpcmsg('examples.setcookies', array($cookiesval));
526         $r = $this->send($f, 0, true);
527         if ($r) {
528             $v = $r->value();
529             $this->assertEquals(1, $v->scalarval());
530             // now check if we decoded the cookies as we had set them
531             $rcookies = $r->cookies();
532             // remove extra cookies which might have been set by proxies
533             foreach ($rcookies as $c => $v) {
534                 if (!in_array($c, array('c2', 'c3', 'c4', 'c5'))) {
535                     unset($rcookies[$c]);
536                 }
537                 // Seems like we get this when using php-fpm and php 5.5+ ...
538                 if (isset($rcookies[$c]['Max-Age'])) {
539                     unset($rcookies[$c]['Max-Age']);
540                 }
541             }
542             foreach ($cookies as $c => $v) {
543                 // format for date string in cookies: 'Mon, 31 Oct 2005 13:50:56 GMT'
544                 // but PHP versions differ on that, some use 'Mon, 31-Oct-2005 13:50:56 GMT'...
545                 if (isset($v['expires'])) {
546                     if (isset($rcookies[$c]['expires']) && strpos($rcookies[$c]['expires'], '-')) {
547                         $cookies[$c]['expires'] = gmdate('D, d\-M\-Y H:i:s \G\M\T', $cookies[$c]['expires']);
548                     } else {
549                         $cookies[$c]['expires'] = gmdate('D, d M Y H:i:s \G\M\T', $cookies[$c]['expires']);
550                     }
551                 }
552             }
553
554             $this->assertEquals($cookies, $rcookies);
555         }
556     }
557
558     public function testSetCookies()
559     {
560         // let server set to us some cookies we tell it
561         $cookies = array(
562             'c0' => null,
563             'c1' => 1,
564             'c2' => '2 3',
565             'c3' => '!@#$%^&*()_+|}{":?><,./\';[]\\=-',
566         );
567         $f = new xmlrpcmsg('examples.getcookies', array());
568         foreach ($cookies as $cookie => $val) {
569             $this->client->setCookie($cookie, $val);
570             $cookies[$cookie] = (string)$cookies[$cookie];
571         }
572         $r = $this->client->send($f, $this->timeout, $this->method);
573         $this->assertEquals($r->faultCode(), 0, 'Error ' . $r->faultCode() . ' connecting to server: ' . $r->faultString());
574         if (!$r->faultCode()) {
575             $v = $r->value();
576             $v = php_xmlrpc_decode($v);
577             // on IIS and Apache getallheaders returns something slightly different...
578             $this->assertEquals($v, $cookies);
579         }
580     }
581
582     public function testSendTwiceSameMsg()
583     {
584         $f = new xmlrpcmsg('examples.stringecho', array(
585             new xmlrpcval('hello world', 'string'),
586         ));
587         $v1 = $this->send($f);
588         $v2 = $this->send($f);
589         //$v = $r->faultCode();
590         if ($v1 && $v2) {
591             $this->assertEquals($v2, $v1);
592         }
593     }
594 }