Completed
Push — master ( ec60ba...653322 )
by Guillaume
05:20
created

BreakerTest::testAllowedException()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 28
rs 8.8571
cc 2
eloc 16
nc 2
nop 0
1
<?php
2
3
namespace Eljam\CircuitBreaker;
4
5
use Doctrine\Common\Cache\FilesystemCache;
6
use Eljam\CircuitBreaker\Event\CircuitEvent;
7
use Eljam\CircuitBreaker\Event\CircuitEvents;
8
use Eljam\CircuitBreaker\Exception\CircuitOpenException;
9
use Eljam\CircuitBreaker\Exception\CustomException;
10
11
/**
12
 * Class BreakerTest.
13
 */
14
class BreakerTest extends \PHPUnit_Framework_TestCase
15
{
16
    protected $dir;
17
18
    public function setUp()
19
    {
20
        $this->dir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'store';
21
    }
22
23
    /**
24
     * testMultiProcess.
25
     */
26
    public function testMultiProcess()
27
    {
28
        $fileCache = new FilesystemCache($this->dir, 'txt');
29
        $breaker = new Breaker('github_api', ['ignore_exceptions' => true], $fileCache);
30
        $breaker2 = new Breaker('github_api', ['ignore_exceptions' => true], $fileCache);
31
32
        $breaker1FailureCount = 0;
33
34
        $breaker->addListener(CircuitEvents::FAILURE, function (CircuitEvent $event) use (&$breaker1FailureCount) {
35
            $breaker1FailureCount = $event->getCircuit()->getFailures();
36
        });
37
38
        $breaker2->addListener(CircuitEvents::FAILURE, function (CircuitEvent $event) use (&$breaker1FailureCount) {
39
            $this->assertEquals($breaker1FailureCount, $event->getCircuit()->getFailures());
40
        });
41
42
        $fn = function () {
43
            throw new CustomException("An error as occurred");
44
        };
45
46
        $breaker->protect($fn);
47
48
        $breaker2->protect($fn);
49
    }
50
51
    /**
52
     * testOpenBehavior.
53
     */
54
    public function testOpenBehavior()
55
    {
56
        $breaker = new Breaker(
57
            'exception breaker',
58
            ['exclude_exceptions' => ['Eljam\CircuitBreaker\Exception\CustomException']]
59
        );
60
61
        $breaker->addListener(CircuitEvents::OPEN, function (CircuitEvent $event) {
62
            $this->assertInstanceOf('Eljam\CircuitBreaker\Circuit', $event->getCircuit());
63
        });
64
65
        $this->setExpectedException('Eljam\CircuitBreaker\Exception\CircuitOpenException');
66
67
        $fn = function () {
68
            throw new CustomException("An error as occurred");
69
        };
70
71
        for ($i = 0; $i <= 5; $i++) {
72
            $breaker->protect($fn);
73
        }
74
    }
75
76
    /**
77
     * testHalfOpenBehavior.
78
     */
79
    public function testHalfOpenBehavior()
80
    {
81
        $breaker = new Breaker(
82
            'exception breaker',
83
            [
84
                'reset_timeout' => 1,
85
                'ignore_exceptions' => true,
86
            ]
87
        );
88
89
        $breaker->addListener(CircuitEvents::HALF_OPEN, function (CircuitEvent $event) {
90
            $this->assertInstanceOf('Eljam\CircuitBreaker\Circuit', $event->getCircuit());
91
        });
92
93
        $fn = function () {
94
            throw new CustomException("An error as occurred");
95
        };
96
97
        try {
98
            for ($i = 0; $i <= 5; $i++) {
99
                $breaker->protect($fn);
100
            }
101
        } catch (CircuitOpenException $e) {
102
            $this->assertSame('Eljam\CircuitBreaker\Exception\CircuitOpenException', get_class($e));
103
        }
104
105
        sleep(2);
106
107
        $fnPass = function () {
108
            return 'ok';
109
        };
110
111
        $breaker->protect($fnPass);
112
    }
113
114
    /**
115
     * testGetTheResult.
116
     */
117
    public function testGetTheResult()
118
    {
119
        $breaker = new Breaker('simple_echo');
120
        $hello = 'eljam';
121
122
        $fn = function () use ($hello) {
123
            return $hello;
124
        };
125
126
        $result = $breaker->protect($fn);
127
128
        $this->assertSame($hello, $result);
129
    }
130
131
    /**
132
     * testIgnoreException.
133
     */
134 View Code Duplication
    public function testIgnoreAllException()
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...
135
    {
136
        $breaker = new Breaker(
137
            'simple_echo',
138
            ['ignore_exceptions' => true]
139
        );
140
        $hello = 'eljam';
141
142
        $fn = function () use ($hello) {
143
            throw new CustomException("An error as occurred");
144
145
            return $hello;
0 ignored issues
show
Unused Code introduced by
return $hello; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
146
        };
147
148
        $result = $breaker->protect($fn);
149
150
        $this->assertNull($result);
151
    }
152
153
    /**
154
     * testThrowCustomException.
155
     */
156 View Code Duplication
    public function testThrowCustomException()
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...
157
    {
158
        $breaker = new Breaker(
159
            'custom_exception'
160
        );
161
        $hello = 'eljam';
162
163
        $this->setExpectedException('Eljam\CircuitBreaker\Exception\CustomException');
164
165
        $fn = function () use ($hello) {
166
            throw new CustomException("An error as occurred");
167
168
            return $hello;
0 ignored issues
show
Unused Code introduced by
return $hello; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
169
        };
170
171
        $breaker->protect($fn);
172
    }
173
174
    public function testAllowedException()
175
    {
176
        $breaker = new Breaker(
177
            'allowed_exception',
178
            [
179
                'ignore_exceptions' => false,
180
                'allowed_exceptions' => [
181
                    'Eljam\CircuitBreaker\Exception\CustomException',
182
                ],
183
            ]
184
        );
185
186
        $breaker1FailureCount = 0;
187
        $breaker->addListener(CircuitEvents::FAILURE, function (CircuitEvent $event) use (&$breaker1FailureCount) {
188
            $breaker1FailureCount = $event->getCircuit()->getFailures();
189
        });
190
191
        $fn = function () {
192
            throw new CustomException("An error as occurred");
193
        };
194
195
        try {
196
            $breaker->protect($fn);
197
        } catch (CustomException $e) {
198
            $this->assertInstanceOf('Eljam\CircuitBreaker\Exception\CustomException', $e);
199
        }
200
        $this->assertSame(0, $breaker1FailureCount);
201
    }
202
203
    public function tearDown()
204
    {
205
        @unlink($this->dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
206
    }
207
}
208