Completed
Push — master ( 386146...a2d301 )
by John
07:40
created

ExceptionListenerTest   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 211
Duplicated Lines 31.28 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 19
c 2
b 0
f 0
lcom 1
cbo 8
dl 66
loc 211
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 22 1
A willLogExceptionsWith4xxCodesAsInputErrorNotices() 15 15 2
A willLogExceptionsWith5xxCodesAsRuntimeErrors() 15 15 2
A willLogExceptionsWithUnexpectedCodesAsCriticalErrors() 0 16 2
A willSetResponseWithVndErrorHeader() 9 9 2
A willSetResponseWithValidJsonContent() 9 9 2
A willSetResponseWithSimpleMessage() 9 9 2
A willSetResponseWithLogRef() 9 9 2
B logrefInResponseAndLogMatch() 0 27 3
A willReturn404Responses() 0 18 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/*
3
 * This file is part of the KleijnWeb\SwaggerBundle package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\SwaggerBundle\Tests\EventListener;
10
11
use KleijnWeb\SwaggerBundle\EventListener\ExceptionListener;
12
use Psr\Log\LoggerInterface;
13
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
14
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
15
16
/**
17
 * @author John Kleijn <[email protected]>
18
 */
19
class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
20
{
21
    /**
22
     * @var GetResponseForExceptionEvent
23
     */
24
    private $event;
25
26
    /**
27
     * @var \ReflectionProperty
28
     */
29
    private $codeProperty;
30
31
    /**
32
     * @var \Exception
33
     */
34
    private $exception;
35
36
    /**
37
     * @var ExceptionListener
38
     */
39
    private $exceptionListener;
40
41
    /**
42
     * Set up mocking
43
     */
44
    protected function setUp()
45
    {
46
        $this->exception = new \Exception("Mary had a little lamb");
47
        $reflection = new \ReflectionClass($this->exception);
48
        $codeProperty = $reflection->getProperty('code');
49
        $this->codeProperty = $codeProperty;
50
        $this->codeProperty->setAccessible(true);
51
52
        $this->event = $this
53
            ->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent')
54
            ->disableOriginalConstructor()
55
            ->setMethods(['getException'])
56
            ->getMock();
57
58
        $this->event->expects($this->any())
59
            ->method('getException')
60
            ->willReturn($this->exception);
61
62
        /** @var LoggerInterface $logger */
63
        $logger = $this->getMockForAbstractClass('Psr\Log\LoggerInterface');
64
        $this->exceptionListener = new ExceptionListener($logger);
65
    }
66
67
    /**
68
     * @test
69
     */
70 View Code Duplication
    public function willLogExceptionsWith4xxCodesAsInputErrorNotices()
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...
71
    {
72
        for ($i = 0; $i < 99; $i++) {
73
            $logger = $this->getMockForAbstractClass('Psr\Log\LoggerInterface');
74
            $logger
75
                ->expects($this->once())
76
                ->method('notice')
77
                ->with($this->stringStartsWith('Input error'));
78
79
            /** @var LoggerInterface $logger */
80
            $this->exceptionListener->setLogger($logger);
81
            $this->codeProperty->setValue($this->exception, 400 + $i);
82
            $this->exceptionListener->onKernelException($this->event);
83
        }
84
    }
85
86
    /**
87
     * @test
88
     */
89 View Code Duplication
    public function willLogExceptionsWith5xxCodesAsRuntimeErrors()
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...
90
    {
91
        for ($i = 0; $i < 99; $i++) {
92
            $logger = $this->getMockForAbstractClass('Psr\Log\LoggerInterface');
93
            $logger
94
                ->expects($this->once())
95
                ->method('error')
96
                ->with($this->stringStartsWith('Runtime error'));
97
98
            /** @var LoggerInterface $logger */
99
            $this->exceptionListener->setLogger($logger);
100
            $this->codeProperty->setValue($this->exception, 500 + $i);
101
            $this->exceptionListener->onKernelException($this->event);
102
        }
103
    }
104
105
    /**
106
     * @test
107
     */
108
    public function willLogExceptionsWithUnexpectedCodesAsCriticalErrors()
109
    {
110
        $sample = [4096, 777, 22, 5, 0];
111
        foreach ($sample as $code) {
112
            $logger = $this->getMockForAbstractClass('Psr\Log\LoggerInterface');
113
            $logger
114
                ->expects($this->once())
115
                ->method('critical')
116
                ->with($this->stringStartsWith('Runtime error'));
117
118
            /** @var LoggerInterface $logger */
119
            $this->exceptionListener->setLogger($logger);
120
            $this->codeProperty->setValue($this->exception, $code);
121
            $this->exceptionListener->onKernelException($this->event);
122
        }
123
    }
124
125
    /**
126
     * @test
127
     */
128 View Code Duplication
    public function willSetResponseWithVndErrorHeader()
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...
129
    {
130
        foreach ([400, 500] as $code) {
131
            $this->codeProperty->setValue($this->exception, $code);
132
            $this->exceptionListener->onKernelException($this->event);
133
            $response = $this->event->getResponse();
134
            $this->assertContains('application/vnd.error', $response->headers->get('Content-Type'));
135
        }
136
    }
137
138
    /**
139
     * @test
140
     */
141 View Code Duplication
    public function willSetResponseWithValidJsonContent()
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...
142
    {
143
        foreach ([400, 500] as $code) {
144
            $this->codeProperty->setValue($this->exception, $code);
145
            $this->exceptionListener->onKernelException($this->event);
146
            $response = $this->event->getResponse();
147
            $this->assertNotNull(json_decode($response->getContent()));
148
        }
149
    }
150
151
    /**
152
     * @test
153
     */
154 View Code Duplication
    public function willSetResponseWithSimpleMessage()
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...
155
    {
156
        foreach ([400 => 'Input Error', 500 => 'Server Error'] as $code => $message) {
157
            $this->codeProperty->setValue($this->exception, $code);
158
            $this->exceptionListener->onKernelException($this->event);
159
            $response = $this->event->getResponse();
160
            $this->assertEquals($message, json_decode($response->getContent())->message);
161
        }
162
    }
163
164
    /**
165
     * @test
166
     */
167 View Code Duplication
    public function willSetResponseWithLogRef()
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...
168
    {
169
        foreach ([400, 500] as $code) {
170
            $this->codeProperty->setValue($this->exception, $code);
171
            $this->exceptionListener->onKernelException($this->event);
172
            $response = $this->event->getResponse();
173
            $this->assertNotNull(json_decode($response->getContent())->logref);
174
        }
175
    }
176
177
    /**
178
     * @test
179
     */
180
    public function logrefInResponseAndLogMatch()
181
    {
182
        foreach ([400, 500] as $code) {
183
            $logref = null;
184
            $logger = $this->getMockForAbstractClass('Psr\Log\LoggerInterface');
185
            $logger
186
                ->expects($this->once())
187
                ->method($this->anything())
188
                ->with($this->callback(function ($message) use (&$logref) {
189
                    $matches = [];
190
                    if (preg_match('/logref ([a-z0-9]*)/', $message, $matches)) {
191
                        $logref = $matches[1];
192
193
                        return true;
194
                    }
195
196
                    return false;
197
                }));
198
199
            /** @var LoggerInterface $logger */
200
            $this->exceptionListener->setLogger($logger);
201
            $this->codeProperty->setValue($this->exception, $code);
202
            $this->exceptionListener->onKernelException($this->event);
203
            $response = $this->event->getResponse();
204
            $this->assertEquals($logref, json_decode($response->getContent())->logref);
205
        }
206
    }
207
208
    /**
209
     * @test
210
     */
211
    public function willReturn404Responses()
212
    {
213
        $event = $this
214
            ->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent')
215
            ->disableOriginalConstructor()
216
            ->setMethods(['getException'])
217
            ->getMock();
218
219
        $event->expects($this->any())
220
            ->method('getException')
221
            ->willReturn(new NotFoundHttpException());
222
223
        $this->exceptionListener->onKernelException($event);
224
225
        $response = $event->getResponse();
226
227
        $this->assertSame(404, $response->getStatusCode());
228
    }
229
}
230