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

JsonRpcControllerTest::getContainerMock()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 57
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 57
ccs 41
cts 41
cp 1
rs 9.6818
c 0
b 0
f 0
cc 2
eloc 36
nc 1
nop 0
crap 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 getInvalidJsonRequests()
28
    {
29
        return [
30
            'empty'        => [null],
31
            'string'       => ['test'],
32 1
            'invalid_json' => [substr(json_encode(['test']), 2)],
33
        ];
34
    }
35
36
    /**
37
     * @dataProvider getInvalidJsonRequests
38
     * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
39
     *
40
     * @param $content
41
     */
42 3
    public function testInvalidJsonHandling($content)
43
    {
44 3
        $controller = $this->createController();
45
46 3
        $request = $this->createJsonRequest('/', $content);
47 3
        $controller->jsonRpcAction($request);
48
    }
49
50
    public function getInvalidJsonRpcRequests()
51
    {
52
        return [
53
            'invalid version' => [['jsonrpc' => '1.0']],
54
            'no method'       => [['jsonrpc' => '2.0']],
55
            'no version'      => [['method' => 'test']],
56
        ];
57
    }
58
59
    /**
60
     * @dataProvider getInvalidJsonRpcRequests
61
     * @expectedException \Bankiru\Api\JsonRpc\Exception\InvalidRequestException
62
     *
63
     * @param $content
64
     */
65 3
    public function testInvalidJsonRpcHandling($content)
66
    {
67 3
        $controller = $this->createController();
68
69 3
        $request = $this->createJsonRequest('/', $content);
70 3
        $controller->jsonRpcAction($request);
71
    }
72
73 1
    public function getValidResponseAndRequests()
74
    {
75
        return [
76
            'empty batch' => [[], '[]'],
77
            'single'      => [
78
                [
79 1
                    'jsonrpc' => '2.0',
80
                    'id'      => 'test',
81
                    'method'  => 'test',
82
                ],
83
                '{"jsonrpc":"2.0","id":"test","result":{"success":true}}',
84
            ],
85
            'batch'       => [
86
                [
87
                    [
88
                        'jsonrpc' => '2.0',
89
                        'id'      => 'test',
90
                        'method'  => 'test',
91
                    ],
92
                ],
93
                '[{"jsonrpc":"2.0","id":"test","result":{"success":true}}]',
94
            ],
95
        ];
96
    }
97
98
    /**
99
     * @dataProvider getValidResponseAndRequests
100
     *
101
     * @param array  $content
102
     * @param string $responseBody
103
     */
104 3
    public function testValidRequestHandling($content, $responseBody)
105
    {
106 3
        $controller = $this->createController();
107 3
        $request    = $this->createJsonRequest(
108 3
            '/',
109
            $content
110 3
        );
111 3
        $response   = $controller->jsonRpcAction($request);
112
113 3
        self::assertInstanceOf(JsonRpcHttpResponse::class, $response);
114 3
        self::assertTrue($response->isSuccessful());
115 3
        self::assertEquals($responseBody, $response->getContent());
116 3
    }
117
118 1
    public function testExceptionHandling()
119
    {
120 1
        $controller = $this->createController();
121 1
        $request    = $this->createJsonRequest(
122 1
            '/',
123
            [
124 1
                'jsonrpc' => '2.0',
125 1
                'id'      => 'test',
126 1
                'method'  => 'exception',
127
            ]
128 1
        );
129 1
        $response   = $controller->jsonRpcAction($request);
130
131 1
        self::assertTrue($response->isSuccessful());
132 1
        self::assertEquals(
133 1
            '{"jsonrpc":"2.0","id":"test","error":{"code":-32603,"message":"Failure!","data":null}}',
134 1
            $response->getContent()
135 1
        );
136 1
    }
137
138 2
    public function testExceptionHandlingAmongBatchRequest()
139
    {
140 1
        $controller = $this->createController();
141 1
        $request    = $this->createJsonRequest(
142 1
            '/',
143
            [
144
                [
145 1
                    'jsonrpc' => '2.0',
146 1
                    'id'      => 'test1',
147 1
                    'method'  => 'test',
148 2
                ],
149
                [
150 1
                    'jsonrpc' => '2.0',
151 1
                    'id'      => 'test2',
152 1
                    'method'  => 'exception',
153 1
                ],
154
            ]
155 1
        );
156 1
        $response   = $controller->jsonRpcAction($request);
157
158 1
        self::assertTrue($response->isSuccessful());
159 1
        self::assertEquals(
160 1
            '[{"jsonrpc":"2.0","id":"test1","result":{"success":true}},{"jsonrpc":"2.0","id":"test2","error":{"code":-32603,"message":"Failure!","data":null}}]',
161 1
            $response->getContent()
162 1
        );
163 1
    }
164
165
    /**
166
     * @param string $uri
167
     * @param mixed  $content
168
     *
169
     * @return Request
170
     */
171 11
    private function createJsonRequest($uri, $content)
172
    {
173 11
        return Request::create($uri, 'POST', [], [], [], [], json_encode($content));
174
    }
175
176 11
    private function getContainerMock()
177
    {
178 11
        $mock     = $this->prophesize(ContainerInterface::class);
179 11
        $kernel   = $this->prophesize(KernelInterface::class);
180 11
        $resolver = $this->prophesize(ControllerResolverInterface::class);
181 11
        $resolver->getController(Argument::type(RpcRequestInterface::class))->willReturn(
182
            function (JsonRpcRequestInterface $request) {
183 4
                if ($request->getMethod() === 'exception') {
184 2
                    throw new \LogicException('Failure!');
185
                }
186
187 3
                return new JsonRpcResponse($request->getId(), (object)['success' => true]);
188
            }
189 11
        );
190 11
        $resolver->getArguments(Argument::type(RpcRequestInterface::class), Argument::any())->will(
191
            function (array $args) {
192
                return [
193 4
                    $args[0],
194 4
                ];
195
            }
196 11
        );
197
198 11
        $evm = $this->prophesize(EventDispatcherInterface::class);
199 11
        $evm->dispatch(Argument::exact(RpcEvents::EXCEPTION), Argument::type(GetExceptionResponseEvent::class))
200 11
            ->will(
201 2
                function ($args) {
202
                    /** @var GetExceptionResponseEvent $event */
203 2
                    $event = $args[1];
204
205
                    /** @var JsonRpcRequestInterface $request */
206 2
                    $request = $event->getRequest();
207
208 2
                    $event->setResponse(
209 2
                        new JsonRpcResponse(
210 2
                            $request->getId(),
211 2
                            null, new JsonRpcError(
212 2
                                JsonRpcError::INTERNAL_ERROR,
213 2
                                $event->getException()->getMessage()
214 2
                            )
215 2
                        )
216 2
                    );
217 2
                }
218 11
            );
219 11
        $evm->dispatch(Argument::exact(RpcEvents::FINISH_REQUEST), Argument::type(FinishRequestEvent::class))
220 11
            ->willReturn(null);
221 11
        $evm->dispatch(Argument::exact(RpcEvents::CONTROLLER), Argument::type(FilterControllerEvent::class))
222 11
            ->willReturn(null);
223 11
        $evm->dispatch(Argument::exact(RpcEvents::REQUEST), Argument::type(GetResponseEvent::class))->willReturn(null);
224 11
        $evm->dispatch(Argument::exact(RpcEvents::RESPONSE), Argument::type(FilterResponseEvent::class))
225 11
            ->willReturn(null);
226
227 11
        $mock->get(Argument::exact('jsonrpc_server.controller_resolver'))->willReturn($resolver->reveal());
228 11
        $mock->get(Argument::exact('event_dispatcher'))->willReturn($evm->reveal());
229 11
        $mock->get(Argument::exact('kernel'))->willReturn($kernel->reveal());
230
231 11
        return $mock->reveal();
232
    }
233
234 11
    private function createController()
235
    {
236 11
        $controller = new JsonRpcController();
237 11
        $controller->setContainer($this->getContainerMock());
238
239 11
        return $controller;
240
    }
241
}
242