Passed
Pull Request — master (#11)
by Pavel
06:35
created

JsonRpcControllerTest::testBatchRequestHandling()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 10

Duplication

Lines 18
Ratio 100 %

Code Coverage

Tests 13
CRAP Score 1

Importance

Changes 0
Metric Value
dl 18
loc 18
ccs 13
cts 13
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Bankiru\Api\JsonRpc\Tests;
4
5
use Bankiru\Api\JsonRpc\Controller\JsonRpcController;
6
use Bankiru\Api\JsonRpc\Http\JsonRpcHttpResponse;
7
use Bankiru\Api\JsonRpc\Specification\JsonRpcResponse;
8
use Bankiru\Api\Rpc\Event\FilterControllerEvent;
9
use Bankiru\Api\Rpc\Event\FilterResponseEvent;
10
use Bankiru\Api\Rpc\Event\FinishRequestEvent;
11
use Bankiru\Api\Rpc\Event\GetExceptionResponseEvent;
12
use Bankiru\Api\Rpc\Event\GetResponseEvent;
13
use Bankiru\Api\Rpc\Routing\ControllerResolver\ControllerResolverInterface;
14
use Bankiru\Api\Rpc\RpcEvents;
15
use PHPUnit\Framework\TestCase;
16
use Prophecy\Argument;
17
use ScayTrase\Api\JsonRpc\JsonRpcError;
18
use ScayTrase\Api\JsonRpc\JsonRpcRequestInterface;
19
use ScayTrase\Api\Rpc\RpcRequestInterface;
20
use Symfony\Component\DependencyInjection\ContainerInterface;
21
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
22
use Symfony\Component\HttpFoundation\Request;
23
use Symfony\Component\HttpKernel\KernelInterface;
24
25
final class JsonRpcControllerTest extends TestCase
26
{
27 1
    public function testEmptyBatchRequestHandling()
28
    {
29 1
        $controller = $this->createController();
30
31 1
        $request  = $this->createJsonRequest('/', []);
32 1
        $response = $controller->jsonRpcAction($request);
33
34 1
        self::assertInstanceOf(JsonRpcHttpResponse::class, $response);
35 1
        self::assertTrue($response->isSuccessful());
36 1
        self::assertEquals('[]', $response->getContent());
37 1
    }
38
39 1
    public function getInvalidJsonRequests()
40
    {
41
        return [
42
            'empty'        => [null],
43
            'string'       => ['test'],
44 1
            'invalid_json' => [substr(json_encode(['test']), 2)],
45
        ];
46
    }
47
48
    /**
49
     * @dataProvider getInvalidJsonRequests
50
     * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
51
     *
52
     * @param $content
53
     */
54 3
    public function testInvalidJsonHandling($content)
55
    {
56 3
        $controller = $this->createController();
57
58 3
        $request = $this->createJsonRequest('/', $content);
59 3
        $controller->jsonRpcAction($request);
60
    }
61
62
    public function getInvalidJsonRpcRequests()
63
    {
64
        return [
65
            'invalid version' => [['jsonrpc' => '1.0']],
66
            'no method'       => [['jsonrpc' => '2.0']],
67
            'no version'      => [['method' => 'test']],
68
        ];
69
    }
70
71
    /**
72
     * @dataProvider getInvalidJsonRpcRequests
73
     * @expectedException \Bankiru\Api\JsonRpc\Exception\InvalidRequestException
74
     *
75
     * @param $content
76
     */
77 4
    public function testInvalidJsonRpcHandling($content)
78
    {
79 4
        $controller = $this->createController();
80
81 3
        $request = $this->createJsonRequest('/', $content);
82 3
        $controller->jsonRpcAction($request);
83
    }
84
85 1 View Code Duplication
    public function testSingleRequestHandling()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
    {
87 1
        $controller = $this->createController();
88 1
        $request    = $this->createJsonRequest(
89 1
            '/',
90
            [
91 1
                'jsonrpc' => '2.0',
92 1
                'id'      => 'test',
93 1
                'method'  => 'test',
94
            ]
95 1
        );
96 1
        $response   = $controller->jsonRpcAction($request);
97
98 1
        self::assertTrue($response->isSuccessful());
99 1
        self::assertEquals('{"jsonrpc":"2.0","id":"test","result":{"success":true}}', $response->getContent());
100 1
    }
101
102 1 View Code Duplication
    public function testBatchRequestHandling()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
    {
104 1
        $controller = $this->createController();
105 1
        $request    = $this->createJsonRequest(
106 1
            '/',
107
            [
108
                [
109 1
                    'jsonrpc' => '2.0',
110 1
                    'id'      => 'test',
111 1
                    'method'  => 'test',
112 1
                ],
113
            ]
114 1
        );
115 1
        $response   = $controller->jsonRpcAction($request);
116
117 1
        self::assertTrue($response->isSuccessful());
118 1
        self::assertEquals('[{"jsonrpc":"2.0","id":"test","result":{"success":true}}]', $response->getContent());
119 1
    }
120
121 1 View Code Duplication
    public function testExceptionHandling()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
    {
123 1
        $controller = $this->createController();
124 1
        $request    = $this->createJsonRequest(
125 1
            '/',
126
            [
127 1
                'jsonrpc' => '2.0',
128 1
                'id'      => 'test',
129 1
                'method'  => 'exception',
130
            ]
131 1
        );
132 1
        $response   = $controller->jsonRpcAction($request);
133
134 1
        self::assertTrue($response->isSuccessful());
135 1
        self::assertEquals(
136 1
            '{"jsonrpc":"2.0","id":"test","error":{"code":-32603,"message":"Failure!","data":null}}',
137 1
            $response->getContent()
138 1
        );
139 1
    }
140
141 2
    public function testExceptionHandlingAmongBatchRequest()
142
    {
143 1
        $controller = $this->createController();
144 1
        $request    = $this->createJsonRequest(
145 1
            '/',
146
            [
147
                [
148 2
                    'jsonrpc' => '2.0',
149 1
                    'id'      => 'test1',
150 1
                    'method'  => 'test',
151 1
                ],
152
                [
153 1
                    'jsonrpc' => '2.0',
154 1
                    'id'      => 'test2',
155 1
                    'method'  => 'exception',
156 1
                ],
157
            ]
158 1
        );
159 1
        $response   = $controller->jsonRpcAction($request);
160
161 1
        self::assertTrue($response->isSuccessful());
162 1
        self::assertEquals(
163 1
            '[{"jsonrpc":"2.0","id":"test1","result":{"success":true}},{"jsonrpc":"2.0","id":"test2","error":{"code":-32603,"message":"Failure!","data":null}}]',
164 1
            $response->getContent()
165 1
        );
166 1
    }
167
168 11
    private function createJsonRequest($uri, $content)
169
    {
170 11
        return Request::create($uri, 'POST', [], [], [], [], json_encode($content));
171
    }
172
173 11
    private function getContainerMock()
174
    {
175 11
        $mock     = $this->prophesize(ContainerInterface::class);
176 11
        $kernel   = $this->prophesize(KernelInterface::class);
177 11
        $resolver = $this->prophesize(ControllerResolverInterface::class);
178 11
        $resolver->getController(Argument::type(RpcRequestInterface::class))->willReturn(
179
            function (JsonRpcRequestInterface $request) {
180 5
                if ($request->getMethod() === 'exception') {
181 2
                    throw new \LogicException('Failure!');
182
                }
183
184 3
                return new JsonRpcResponse($request->getId(), ['success' => true]);
0 ignored issues
show
Documentation introduced by
array('success' => true) is of type array<string,boolean,{"success":"boolean"}>, but the function expects a null|object<stdClass>|ar...teger,object<stdClass>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
185
            }
186 11
        );
187 11
        $resolver->getArguments(Argument::type(RpcRequestInterface::class), Argument::any())->will(
188
            function (array $args) {
189
                return [
190 4
                    $args[0],
191 4
                ];
192
            }
193 11
        );
194
195 11
        $evm = $this->prophesize(EventDispatcherInterface::class);
196 11
        $evm->dispatch(Argument::exact(RpcEvents::EXCEPTION), Argument::type(GetExceptionResponseEvent::class))
197 11
            ->will(
198 2
                function ($args) {
199
                    /** @var GetExceptionResponseEvent $event */
200 2
                    $event = $args[1];
201
202
                    /** @var JsonRpcRequestInterface $request */
203 2
                    $request = $event->getRequest();
204
205 2
                    $event->setResponse(
206 2
                        new JsonRpcResponse(
207 2
                            $request->getId(),
208 2
                            null, new JsonRpcError(
209 2
                                JsonRpcError::INTERNAL_ERROR,
210 2
                                $event->getException()->getMessage()
211 2
                            )
212 2
                        )
213 2
                    );
214 2
                }
215 11
            );
216 11
        $evm->dispatch(Argument::exact(RpcEvents::FINISH_REQUEST), Argument::type(FinishRequestEvent::class))
217 11
            ->willReturn(null);
218 11
        $evm->dispatch(Argument::exact(RpcEvents::CONTROLLER), Argument::type(FilterControllerEvent::class))
219 11
            ->willReturn(null);
220 11
        $evm->dispatch(Argument::exact(RpcEvents::REQUEST), Argument::type(GetResponseEvent::class))->willReturn(null);
221 11
        $evm->dispatch(Argument::exact(RpcEvents::RESPONSE), Argument::type(FilterResponseEvent::class))
222 11
            ->willReturn(null);
223
224 11
        $mock->get(Argument::exact('jsonrpc_server.controller_resolver'))->willReturn($resolver->reveal());
225 11
        $mock->get(Argument::exact('event_dispatcher'))->willReturn($evm->reveal());
226 11
        $mock->get(Argument::exact('kernel'))->willReturn($kernel->reveal());
227
228 11
        return $mock->reveal();
229
    }
230
231 11
    private function createController()
232
    {
233 11
        $controller = new JsonRpcController();
234 11
        $controller->setContainer($this->getContainerMock());
235
236 11
        return $controller;
237
    }
238
}
239