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