Test Failed
Pull Request — master (#11)
by Pavel
11:44
created

testExceptionHandlingAmongBatchRequest()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 15
nc 1
nop 0
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
    public function testEmptyBatchRequestHandling()
28
    {
29
        $controller = $this->createController();
30
31
        $request  = $this->createJsonRequest('/', []);
32
        $response = $controller->jsonRpcAction($request);
33
34
        self::assertInstanceOf(JsonRpcHttpResponse::class, $response);
35
        self::assertTrue($response->isSuccessful());
36
        self::assertEquals('[]', $response->getContent());
37
    }
38
39
    public function getInvalidJsonRequests()
40
    {
41
        return [
42
            'empty'        => [null],
43
            'string'       => ['test'],
44
            '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
    public function testInvalidJsonHandling($content)
55
    {
56
        $controller = $this->createController();
57
58
        $request = $this->createJsonRequest('/', $content);
59
        $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
    public function testInvalidJsonRpcHandling($content)
78
    {
79
        $controller = $this->createController();
80
81
        $request = $this->createJsonRequest('/', $content);
82
        $controller->jsonRpcAction($request);
83
    }
84
85 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
        $controller = $this->createController();
88
        $request    = $this->createJsonRequest(
89
            '/',
90
            [
91
                'jsonrpc' => '2.0',
92
                'id'      => 'test',
93
                'method'  => 'test',
94
            ]
95
        );
96
        $response   = $controller->jsonRpcAction($request);
97
98
        self::assertTrue($response->isSuccessful());
99
        self::assertEquals('{"jsonrpc":"2.0","id":"test","result":{"success":true}}', $response->getContent());
100
    }
101
102 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
        $controller = $this->createController();
105
        $request    = $this->createJsonRequest(
106
            '/',
107
            [
108
                [
109
                    'jsonrpc' => '2.0',
110
                    'id'      => 'test',
111
                    'method'  => 'test',
112
                ],
113
            ]
114
        );
115
        $response   = $controller->jsonRpcAction($request);
116
117
        self::assertTrue($response->isSuccessful());
118
        self::assertEquals('[{"jsonrpc":"2.0","id":"test","result":{"success":true}}]', $response->getContent());
119
    }
120
121 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
        $controller = $this->createController();
124
        $request    = $this->createJsonRequest(
125
            '/',
126
            [
127
                'jsonrpc' => '2.0',
128
                'id'      => 'test',
129
                'method'  => 'exception',
130
            ]
131
        );
132
        $response   = $controller->jsonRpcAction($request);
133
134
        self::assertTrue($response->isSuccessful());
135
        self::assertEquals(
136
            '{"jsonrpc":"2.0","id":"test","error":{"code":-32603,"message":"Failure!","data":null}}',
137
            $response->getContent()
138
        );
139
    }
140
141
    public function testExceptionHandlingAmongBatchRequest()
142
    {
143
        $controller = $this->createController();
144
        $request    = $this->createJsonRequest(
145
            '/',
146
            [
147
                [
148
                    'jsonrpc' => '2.0',
149
                    'id'      => 'test1',
150
                    'method'  => 'test',
151
                ],
152
                [
153
                    'jsonrpc' => '2.0',
154
                    'id'      => 'test2',
155
                    'method'  => 'exception',
156
                ],
157
            ]
158
        );
159
        $response   = $controller->jsonRpcAction($request);
160
161
        self::assertTrue($response->isSuccessful());
162
        self::assertEquals(
163
            '[{"jsonrpc":"2.0","id":"test1","result":{"success":true}},{"jsonrpc":"2.0","id":"test2","error":{"code":-32603,"message":"Failure!","data":null}}]',
164
            $response->getContent()
165
        );
166
    }
167
168
    private function createJsonRequest($uri, $content)
169
    {
170
        return Request::create($uri, 'POST', [], [], [], [], json_encode($content));
171
    }
172
173
    private function getContainerMock()
174
    {
175
        $mock     = $this->prophesize(ContainerInterface::class);
176
        $kernel   = $this->prophesize(KernelInterface::class);
177
        $resolver = $this->prophesize(ControllerResolverInterface::class);
178
        $resolver->getController(Argument::type(RpcRequestInterface::class))->willReturn(
179
            function (JsonRpcRequestInterface $request) {
180
                if ($request->getMethod() === 'exception') {
181
                    throw new \LogicException('Failure!');
182
                }
183
184
                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
        );
187
        $resolver->getArguments(Argument::type(RpcRequestInterface::class), Argument::any())->will(
188
            function (array $args) {
189
                return [
190
                    $args[0],
191
                ];
192
            }
193
        );
194
195
        $evm = $this->prophesize(EventDispatcherInterface::class);
196
        $evm->dispatch(Argument::exact(RpcEvents::EXCEPTION), Argument::type(GetExceptionResponseEvent::class))
197
            ->will(
198
                function ($args) {
199
                    /** @var GetExceptionResponseEvent $event */
200
                    $event = $args[1];
201
202
                    /** @var JsonRpcRequestInterface $request */
203
                    $request = $event->getRequest();
204
205
                    $event->setResponse(
206
                        new JsonRpcResponse(
207
                            $request->getId(),
208
                            null, new JsonRpcError(
209
                                JsonRpcError::INTERNAL_ERROR,
210
                                $event->getException()->getMessage()
211
                            )
212
                        )
213
                    );
214
                }
215
            );
216
        $evm->dispatch(Argument::exact(RpcEvents::FINISH_REQUEST), Argument::type(FinishRequestEvent::class))
217
            ->willReturn(null);
218
        $evm->dispatch(Argument::exact(RpcEvents::CONTROLLER), Argument::type(FilterControllerEvent::class))
219
            ->willReturn(null);
220
        $evm->dispatch(Argument::exact(RpcEvents::REQUEST), Argument::type(GetResponseEvent::class))->willReturn(null);
221
        $evm->dispatch(Argument::exact(RpcEvents::RESPONSE), Argument::type(FilterResponseEvent::class))
222
            ->willReturn(null);
223
224
        $mock->get(Argument::exact('jsonrpc_server.controller_resolver'))->willReturn($resolver->reveal());
225
        $mock->get(Argument::exact('event_dispatcher'))->willReturn($evm->reveal());
226
        $mock->get(Argument::exact('kernel'))->willReturn($kernel->reveal());
227
228
        return $mock->reveal();
229
    }
230
231
    private function createController()
232
    {
233
        $controller = new JsonRpcController();
234
        $controller->setContainer($this->getContainerMock());
235
236
        return $controller;
237
    }
238
}
239