PageRenderTime 260ms CodeModel.GetById 191ms app.highlight 33ms RepoModel.GetById 31ms app.codeStats 0ms

/tests/Zend/Json/ServerTest.php

https://bitbucket.org/ksekar/campus
PHP | 494 lines | 374 code | 49 blank | 71 comment | 11 complexity | c577e2098e438987e033c8a512acb683 MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Json_Server
 17 * @subpackage UnitTests
 18 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 19 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 20 * @version    $Id: ServerTest.php 24594 2012-01-05 21:27:01Z matthew $
 21 */
 22
 23// Call Zend_Json_ServerTest::main() if this source file is executed directly.
 24if (!defined("PHPUnit_MAIN_METHOD")) {
 25    define("PHPUnit_MAIN_METHOD", "Zend_Json_ServerTest::main");
 26}
 27
 28require_once 'Zend/Json/Server.php';
 29require_once 'Zend/Json/Server/Request.php';
 30require_once 'Zend/Json/Server/Response.php';
 31require_once 'Zend/Json.php';
 32
 33/**
 34 * Test class for Zend_Json_Server
 35 *
 36 * @category   Zend
 37 * @package    Zend_Json_Server
 38 * @subpackage UnitTests
 39 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 40 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 41 * @group      Zend_Json
 42 * @group      Zend_Json_Server
 43 */
 44class Zend_Json_ServerTest extends PHPUnit_Framework_TestCase
 45{
 46    /**
 47     * Runs the test methods of this class.
 48     *
 49     * @return void
 50     */
 51    public static function main()
 52    {
 53
 54        $suite  = new PHPUnit_Framework_TestSuite("Zend_Json_ServerTest");
 55        $result = PHPUnit_TextUI_TestRunner::run($suite);
 56    }
 57
 58    /**
 59     * Sets up the fixture, for example, open a network connection.
 60     * This method is called before a test is executed.
 61     *
 62     * @return void
 63     */
 64    public function setUp()
 65    {
 66        $this->server = new Zend_Json_Server();
 67    }
 68
 69    /**
 70     * Tears down the fixture, for example, close a network connection.
 71     * This method is called after a test is executed.
 72     *
 73     * @return void
 74     */
 75    public function tearDown()
 76    {
 77    }
 78
 79    public function testShouldBeAbleToBindFunctionToServer()
 80    {
 81        $this->server->addFunction('strtolower');
 82        $methods = $this->server->getFunctions();
 83        $this->assertTrue($methods->hasMethod('strtolower'));
 84    }
 85
 86    public function testShouldBeAbleToBindCallback1ToServer()
 87    {
 88        $this->server->addFunction(array('Zend_Json_ServerTest_Foo', 'bar'));
 89        $methods = $this->server->getFunctions();
 90        $this->assertTrue($methods->hasMethod('bar'));
 91    }
 92
 93    public function testShouldBeAbleToBindCallback2ToServer()
 94    {
 95        $this->server->addFunction(array(new Zend_Json_ServerTest_Foo, 'bar'));
 96        $methods = $this->server->getFunctions();
 97        $this->assertTrue($methods->hasMethod('bar'));
 98    }
 99
100    public function testShouldBeAbleToBindClassToServer()
101    {
102        $this->server->setClass('Zend_Json_Server');
103        $test = $this->server->getFunctions();
104        $this->assertTrue(0 < count($test));
105    }
106
107    public function testBindingClassToServerShouldRegisterAllPublicMethods()
108    {
109        $this->server->setClass('Zend_Json_Server');
110        $test = $this->server->getFunctions();
111        $methods = get_class_methods('Zend_Json_Server');
112        foreach ($methods as $method) {
113            if ('_' == $method[0]) {
114                continue;
115            }
116            $this->assertTrue($test->hasMethod($method), 'Testing for method ' . $method . ' against ' . var_export($test, 1));
117        }
118    }
119
120    public function testShouldBeAbleToBindObjectToServer()
121    {
122        $object = new Zend_Json_Server();
123        $this->server->setClass($object);
124        $test = $this->server->getFunctions();
125        $this->assertTrue(0 < count($test));
126    }
127
128    public function testBindingObjectToServerShouldRegisterAllPublicMethods()
129    {
130        $object = new Zend_Json_Server();
131        $this->server->setClass($object);
132        $test = $this->server->getFunctions();
133        $methods = get_class_methods($object);
134        foreach ($methods as $method) {
135            if ('_' == $method[0]) {
136                continue;
137            }
138            $this->assertTrue($test->hasMethod($method), 'Testing for method ' . $method . ' against ' . var_export($test, 1));
139        }
140    }
141
142    public function testShouldBeAbleToBindMultipleClassesAndObjectsToServer()
143    {
144        $this->server->setClass('Zend_Json_Server')
145                     ->setClass(new Zend_Json());
146        $methods = $this->server->getFunctions();
147        $zjsMethods = get_class_methods('Zend_Json_Server');
148        $zjMethods  = get_class_methods('Zend_Json');
149        $this->assertTrue(count($zjsMethods) < count($methods));
150        $this->assertTrue(count($zjMethods) < count($methods));
151    }
152
153    public function testNamingCollisionsShouldResolveToLastRegisteredMethod()
154    {
155        $this->server->setClass('Zend_Json_Server_Request')
156                     ->setClass('Zend_Json_Server_Response');
157        $methods = $this->server->getFunctions();
158        $this->assertTrue($methods->hasMethod('toJson'));
159        $toJson = $methods->getMethod('toJson');
160        $this->assertEquals('Zend_Json_Server_Response', $toJson->getCallback()->getClass());
161    }
162
163    public function testGetRequestShouldInstantiateRequestObjectByDefault()
164    {
165        $request = $this->server->getRequest();
166        $this->assertTrue($request instanceof Zend_Json_Server_Request);
167    }
168
169    public function testShouldAllowSettingRequestObjectManually()
170    {
171        $orig = $this->server->getRequest();
172        $new  = new Zend_Json_Server_Request();
173        $this->server->setRequest($new);
174        $test = $this->server->getRequest();
175        $this->assertSame($new, $test);
176        $this->assertNotSame($orig, $test);
177    }
178
179    public function testGetResponseShouldInstantiateResponseObjectByDefault()
180    {
181        $response = $this->server->getResponse();
182        $this->assertTrue($response instanceof Zend_Json_Server_Response);
183    }
184
185    public function testShouldAllowSettingResponseObjectManually()
186    {
187        $orig = $this->server->getResponse();
188        $new  = new Zend_Json_Server_Response();
189        $this->server->setResponse($new);
190        $test = $this->server->getResponse();
191        $this->assertSame($new, $test);
192        $this->assertNotSame($orig, $test);
193    }
194
195    public function testFaultShouldCreateErrorResponse()
196    {
197        $response = $this->server->getResponse();
198        $this->assertFalse($response->isError());
199        $this->server->fault('error condition', -32000);
200        $this->assertTrue($response->isError());
201        $error = $response->getError();
202        $this->assertEquals(-32000, $error->getCode());
203        $this->assertEquals('error condition', $error->getMessage());
204    }
205
206    public function testResponseShouldBeEmittedAutomaticallyByDefault()
207    {
208        $this->assertTrue($this->server->autoEmitResponse());
209    }
210
211    public function testShouldBeAbleToDisableAutomaticResponseEmission()
212    {
213        $this->testResponseShouldBeEmittedAutomaticallyByDefault();
214        $this->server->setAutoEmitResponse(false);
215        $this->assertFalse($this->server->autoEmitResponse());
216    }
217
218    public function testShouldBeAbleToRetrieveSmdObject()
219    {
220        $smd = $this->server->getServiceMap();
221        $this->assertTrue($smd instanceof Zend_Json_Server_Smd);
222    }
223
224    public function testShouldBeAbleToSetArbitrarySmdMetadata()
225    {
226        $this->server->setTransport('POST')
227                     ->setEnvelope('JSON-RPC-1.0')
228                     ->setContentType('application/x-json')
229                     ->setTarget('/foo/bar')
230                     ->setId('foobar')
231                     ->setDescription('This is a test service');
232
233        $this->assertEquals('POST', $this->server->getTransport());
234        $this->assertEquals('JSON-RPC-1.0', $this->server->getEnvelope());
235        $this->assertEquals('application/x-json', $this->server->getContentType());
236        $this->assertEquals('/foo/bar', $this->server->getTarget());
237        $this->assertEquals('foobar', $this->server->getId());
238        $this->assertEquals('This is a test service', $this->server->getDescription());
239    }
240
241    public function testSmdObjectRetrievedFromServerShouldReflectServerState()
242    {
243        $this->server->addFunction('strtolower')
244                     ->setClass('Zend_Json_Server')
245                     ->setTransport('POST')
246                     ->setEnvelope('JSON-RPC-1.0')
247                     ->setContentType('application/x-json')
248                     ->setTarget('/foo/bar')
249                     ->setId('foobar')
250                     ->setDescription('This is a test service');
251        $smd = $this->server->getServiceMap();
252        $this->assertEquals('POST', $this->server->getTransport());
253        $this->assertEquals('JSON-RPC-1.0', $this->server->getEnvelope());
254        $this->assertEquals('application/x-json', $this->server->getContentType());
255        $this->assertEquals('/foo/bar', $this->server->getTarget());
256        $this->assertEquals('foobar', $this->server->getId());
257        $this->assertEquals('This is a test service', $this->server->getDescription());
258
259        $services = $smd->getServices();
260        $this->assertTrue(is_array($services));
261        $this->assertTrue(0 < count($services));
262        $this->assertTrue(array_key_exists('strtolower', $services));
263        $methods = get_class_methods('Zend_Json_Server');
264        foreach ($methods as $method) {
265            if ('_' == $method[0]) {
266                continue;
267            }
268            $this->assertTrue(array_key_exists($method, $services));
269        }
270    }
271
272    public function testHandleValidMethodShouldWork()
273    {
274        $this->server->setClass('Zend_Json_ServerTest_Foo')
275                     ->addFunction('Zend_Json_ServerTest_FooFunc')
276                     ->setAutoEmitResponse(false);
277        $request = $this->server->getRequest();
278        $request->setMethod('bar')
279                ->setParams(array(true, 'foo', 'bar'))
280                ->setId('foo');
281        $response = $this->server->handle();
282        $this->assertTrue($response instanceof Zend_Json_Server_Response);
283        $this->assertFalse($response->isError());
284
285
286        $request->setMethod('Zend_Json_ServerTest_FooFunc')
287                ->setId('foo');
288        $response = $this->server->handle();
289        $this->assertTrue($response instanceof Zend_Json_Server_Response);
290        $this->assertFalse($response->isError());
291    }
292
293    public function testHandleValidMethodWithTooFewParamsShouldPassDefaultsOrNullsForMissingParams()
294    {
295        $this->server->setClass('Zend_Json_ServerTest_Foo')
296                     ->setAutoEmitResponse(false);
297        $request = $this->server->getRequest();
298        $request->setMethod('bar')
299                ->setParams(array(true))
300                ->setId('foo');
301        $response = $this->server->handle();
302        $this->assertTrue($response instanceof Zend_Json_Server_Response);
303        $this->assertFalse($response->isError());
304        $result = $response->getResult();
305        $this->assertTrue(is_array($result));
306        $this->assertTrue(3 == count($result));
307        $this->assertEquals('two', $result[1], var_export($result, 1));
308        $this->assertNull($result[2]);
309    }
310
311    public function testHandleValidMethodWithTooManyParamsShouldWork()
312    {
313        $this->server->setClass('Zend_Json_ServerTest_Foo')
314                     ->setAutoEmitResponse(false);
315        $request = $this->server->getRequest();
316        $request->setMethod('bar')
317                ->setParams(array(true, 'foo', 'bar', 'baz'))
318                ->setId('foo');
319        $response = $this->server->handle();
320        $this->assertTrue($response instanceof Zend_Json_Server_Response);
321        $this->assertFalse($response->isError());
322        $result = $response->getResult();
323        $this->assertTrue(is_array($result));
324        $this->assertTrue(3 == count($result));
325        $this->assertEquals('foo', $result[1]);
326        $this->assertEquals('bar', $result[2]);
327    }
328
329    public function testHandleShouldAllowNamedParamsInAnyOrder1()
330    {
331        $this->server->setClass('Zend_Json_ServerTest_Foo')
332                     ->setAutoEmitResponse( false );
333        $request = $this->server->getRequest();
334        $request->setMethod('bar')
335                ->setParams( array(
336                    'three' => 3,
337                    'two'   => 2,
338                    'one'   => 1
339                ))
340                ->setId( 'foo' );
341        $response = $this->server->handle();
342        $result = $response->getResult();
343
344        $this->assertTrue( is_array( $result ) );
345        $this->assertEquals( 1, $result[0] );
346        $this->assertEquals( 2, $result[1] );
347        $this->assertEquals( 3, $result[2] );
348    }
349
350    public function testHandleShouldAllowNamedParamsInAnyOrder2()
351    {
352        $this->server->setClass('Zend_Json_ServerTest_Foo')
353                     ->setAutoEmitResponse( false );
354        $request = $this->server->getRequest();
355        $request->setMethod('bar')
356                ->setParams( array(
357                    'three' => 3,
358                    'one'   => 1,
359                    'two'   => 2,
360                ) )
361                ->setId( 'foo' );
362        $response = $this->server->handle();
363        $result = $response->getResult();
364
365        $this->assertTrue( is_array( $result ) );
366        $this->assertEquals( 1, $result[0] );
367        $this->assertEquals( 2, $result[1] );
368        $this->assertEquals( 3, $result[2] );
369    }
370
371    public function testHandleRequestWithErrorsShouldReturnErrorResponse()
372    {
373        $this->server->setClass('Zend_Json_ServerTest_Foo')
374                     ->setAutoEmitResponse(false);
375        $response = $this->server->handle();
376        $this->assertTrue($response instanceof Zend_Json_Server_Response);
377        $this->assertTrue($response->isError());
378        $this->assertEquals(Zend_Json_Server_Error::ERROR_INVALID_REQUEST, $response->getError()->getCode());
379    }
380
381    public function testHandleRequestWithInvalidMethodShouldReturnErrorResponse()
382    {
383        $this->server->setClass('Zend_Json_ServerTest_Foo')
384                     ->setAutoEmitResponse(false);
385        $request = $this->server->getRequest();
386        $request->setMethod('bogus')
387                ->setId('foo');
388        $response = $this->server->handle();
389        $this->assertTrue($response instanceof Zend_Json_Server_Response);
390        $this->assertTrue($response->isError());
391        $this->assertEquals(Zend_Json_Server_Error::ERROR_INVALID_METHOD, $response->getError()->getCode());
392    }
393
394    public function testHandleRequestWithExceptionShouldReturnErrorResponse()
395    {
396        $this->server->setClass('Zend_Json_ServerTest_Foo')
397                     ->setAutoEmitResponse(false);
398        $request = $this->server->getRequest();
399        $request->setMethod('baz')
400                ->setId('foo');
401        $response = $this->server->handle();
402        $this->assertTrue($response instanceof Zend_Json_Server_Response);
403        $this->assertTrue($response->isError());
404        $this->assertEquals(Zend_Json_Server_Error::ERROR_OTHER, $response->getError()->getCode());
405        $this->assertEquals('application error', $response->getError()->getMessage());
406    }
407
408    public function testHandleShouldEmitResponseByDefault()
409    {
410        $this->server->setClass('Zend_Json_ServerTest_Foo');
411        $request = $this->server->getRequest();
412        $request->setMethod('bar')
413                ->setParams(array(true, 'foo', 'bar'))
414                ->setId('foo');
415        ob_start();
416        $this->server->handle();
417        $buffer = ob_get_clean();
418
419        $decoded = Zend_Json::decode($buffer);
420        $this->assertTrue(is_array($decoded));
421        $this->assertTrue(array_key_exists('result', $decoded));
422        $this->assertTrue(array_key_exists('id', $decoded));
423
424        $response = $this->server->getResponse();
425        $this->assertEquals($response->getResult(), $decoded['result']);
426        $this->assertEquals($response->getId(), $decoded['id']);
427    }
428
429    public function testResponseShouldBeEmptyWhenRequestHasNoId()
430    {
431        $this->server->setClass('Zend_Json_ServerTest_Foo');
432        $request = $this->server->getRequest();
433        $request->setMethod('bar')
434                ->setParams(array(true, 'foo', 'bar'));
435        ob_start();
436        $this->server->handle();
437        $buffer = ob_get_clean();
438
439        $this->assertTrue(empty($buffer));
440    }
441
442    public function testLoadFunctionsShouldLoadResultOfGetFunctions()
443    {
444        $this->server->setClass('Zend_Json_ServerTest_Foo');
445        $functions = $this->server->getFunctions();
446        $server = new Zend_Json_Server();
447        $server->loadFunctions($functions);
448        $this->assertEquals($functions->toArray(), $server->getFunctions()->toArray());
449    }
450}
451
452/**
453 * Class for testing JSON-RPC server
454 */
455class Zend_Json_ServerTest_Foo
456{
457    /**
458     * Bar
459     *
460     * @param  bool $one
461     * @param  string $two
462     * @param  mixed $three
463     * @return array
464     */
465    public function bar($one, $two = 'two', $three = null)
466    {
467        return array($one, $two, $three);
468    }
469
470    /**
471     * Baz
472     *
473     * @return void
474     */
475    public function baz()
476    {
477        throw new Exception('application error');
478    }
479}
480
481/**
482 * Test function for JSON-RPC server
483 *
484 * @return bool
485 */
486function Zend_Json_ServerTest_FooFunc()
487{
488    return true;
489}
490
491// Call Zend_Json_ServerTest::main() if this source file is executed directly.
492if (PHPUnit_MAIN_METHOD == "Zend_Json_ServerTest::main") {
493    Zend_Json_ServerTest::main();
494}