testThrowExceptionOnInabilityToCreateResource()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
cc 4
nc 6
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Phive Queue package.
5
 *
6
 * (c) Eugene Leonovich <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Phive\Queue\Tests\Queue;
13
14
use Phive\Queue\NoItemAvailableException;
15
use Phive\Queue\QueueException;
16
use Phive\Queue\SysVQueue;
17
use Phive\Queue\Tests\Handler\SysVHandler;
18
19
/**
20
 * @requires extension sysvmsg
21
 */
22
class SysVQueueTest extends QueueTest
23
{
24
    use Performance {
25
        Performance::testPushPopPerformance as baseTestPushPopPerformance;
26
    }
27
    use Concurrency;
28
29
    protected function getUnsupportedItemTypes()
30
    {
31
        return [Types::TYPE_NULL, Types::TYPE_ARRAY, Types::TYPE_OBJECT];
32
    }
33
34
    /**
35
     * @dataProvider provideItemsOfUnsupportedTypes
36
     * @expectedException Phive\Queue\QueueException
37
     * @expectedExceptionMessageRegExp /^Message parameter must be either a string or a number\./
38
     */
39
    public function testUnsupportedItemType($item)
40
    {
41
        @$this->queue->push($item);
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...
42
    }
43
44
    /**
45
     * @dataProvider provideItemsOfVariousTypes
46
     */
47
    public function testSupportItemTypeWithSerializerLoose($item)
48
    {
49
        $handler = self::getHandler();
50
        $key = $handler->getOption('key');
51
52
        $queue = new SysVQueue($key, true);
53
54
        $queue->push($item);
55
        $this->assertEquals($item, $queue->pop());
56
    }
57
58
    /**
59
     * @dataProvider provideQueueInterfaceMethods
60
     */
61
    public function testThrowExceptionOnMissingResource($method)
62
    {
63
        // force a resource creation
64
        $this->queue->count();
65
66
        self::getHandler()->clear();
67
68
        try {
69
            // suppress notices/warnings triggered by msg_* functions
70
            // to avoid a PHPUnit_Framework_Error_Notice to be thrown
71
            @$this->callQueueMethod($this->queue, $method);
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...
72
        } catch (NoItemAvailableException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
73
        } catch (QueueException $e) {
74
            return;
75
        }
76
77
        $this->fail();
78
    }
79
80
    /**
81
     * @requires extension uopz
82
     * @dataProvider provideQueueInterfaceMethods
83
     */
84
    public function testThrowExceptionOnInabilityToCreateResource($method)
85
    {
86
        uopz_backup('msg_get_queue');
87
        uopz_function('msg_get_queue', function () { return false; });
88
89
        $passed = false;
90
91
        try {
92
            // suppress notices/warnings triggered by msg_* functions
93
            // to avoid a PHPUnit_Framework_Error_Notice to be thrown
94
            @$this->callQueueMethod($this->queue, $method);
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...
95
        } catch (NoItemAvailableException $e) {
96
        } catch (QueueException $e) {
97
            $this->assertSame('Failed to create/attach to the queue.', $e->getMessage());
98
            $passed = true;
99
        }
100
101
        uopz_restore('msg_get_queue');
102
103
        if (!$passed) {
104
            $this->fail();
105
        }
106
    }
107
108
    public function testSetPermissions()
109
    {
110
        $handler = self::getHandler();
111
        $key = $handler->getOption('key');
112
113
        $queue = new SysVQueue($key, null, 0606);
114
115
        // force a resource creation
116
        $queue->count();
117
118
        $meta = $handler->getMeta();
119
120
        $this->assertEquals(0606, $meta['msg_perm.mode']);
121
    }
122
123
    public function testSetItemMaxLength()
124
    {
125
        $this->queue->push('xx');
126
        $this->queue->setItemMaxLength(1);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Phive\Queue\Queue as the method setItemMaxLength() does only exist in the following implementations of said interface: Phive\Queue\SysVQueue.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
127
128
        try {
129
            $this->queue->pop();
130
        } catch (\Exception $e) {
131
            if (7 === $e->getCode() && 'Argument list too long.' === $e->getMessage()) {
132
                return;
133
            }
134
        }
135
136
        $this->fail();
137
    }
138
139
    /**
140
     * @group performance
141
     * @dataProvider providePerformancePopDelay
142
     */
143
    public function testPushPopPerformance($delay)
144
    {
145
        exec('sysctl kernel.msgmnb 2> /dev/null', $output);
146
147
        if (!$output) {
148
            $this->markTestSkipped('Unable to determine the maximum size of the System V queue.');
149
        }
150
151
        $maxSizeInBytes = (int) str_replace('kernel.msgmnb = ', '', $output[0]);
152
        $queueSize = static::getPerformanceQueueSize();
153
        $itemLength = static::getPerformanceItemLength();
154
155
        if ($itemLength * $queueSize > $maxSizeInBytes) {
156
            $this->markTestSkipped(sprintf(
157
                'The System V queue size is too small (%d bytes) to run this test. '.
158
                'Try to decrease the "PHIVE_PERF_QUEUE_SIZE" environment variable to %d.',
159
                $maxSizeInBytes,
160
                floor($maxSizeInBytes / $itemLength)
161
            ));
162
        }
163
164
        self::baseTestPushPopPerformance($delay);
165
    }
166
167
    public static function createHandler(array $config)
168
    {
169
        return new SysVHandler([
170
            'key' => $config['PHIVE_SYSV_KEY'],
171
        ]);
172
    }
173
}
174