File: RedisTraitTest.php

package info (click to toggle)
symfony 7.4.2%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 138,116 kB
  • sloc: php: 1,597,029; xml: 7,156; javascript: 979; sh: 591; makefile: 250; pascal: 70
file content (205 lines) | stat: -rw-r--r-- 7,018 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Cache\Tests\Traits;

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Traits\RedisTrait;

#[RequiresPhpExtension('redis')]
class RedisTraitTest extends TestCase
{
    #[DataProvider('provideCreateConnection')]
    public function testCreateConnection(string $dsn, string $expectedClass)
    {
        if (!class_exists($expectedClass)) {
            self::markTestSkipped(\sprintf('The "%s" class is required.', $expectedClass));
        }
        if (!getenv('REDIS_CLUSTER_HOSTS')) {
            self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.');
        }

        $mock = new class {
            use RedisTrait;
        };
        $connection = $mock::createConnection($dsn);

        self::assertInstanceOf($expectedClass, $connection);
    }

    public function testUrlDecodeParameters()
    {
        if (!getenv('REDIS_AUTHENTICATED_HOST')) {
            self::markTestSkipped('REDIS_AUTHENTICATED_HOST env var is not defined.');
        }

        $mock = new class {
            use RedisTrait;
        };
        $connection = $mock::createConnection('redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST'));

        self::assertInstanceOf(\Redis::class, $connection);
        self::assertSame('p@ssword', $connection->getAuth());
    }

    public static function provideCreateConnection(): array
    {
        $hosts = array_map(fn ($host) => \sprintf('host[%s]', $host), explode(' ', getenv('REDIS_CLUSTER_HOSTS') ?: ''));

        return [
            [
                \sprintf('redis:?%s&redis_cluster=1', $hosts[0]),
                'RedisCluster',
            ],
            [
                \sprintf('redis:?%s&redis_cluster=true', $hosts[0]),
                'RedisCluster',
            ],
            [
                \sprintf('redis:?%s', $hosts[0]),
                'Redis',
            ],
            [
                \sprintf('redis:?%s', implode('&', \array_slice($hosts, 0, 2))),
                'RedisArray',
            ],
        ];
    }

    /**
     * Due to a bug in phpredis, the persistent connection will keep its last selected database. So when reusing
     * a persistent connection, the database has to be re-selected, too.
     *
     * @see https://github.com/phpredis/phpredis/issues/1920
     */
    #[Group('integration')]
    #[Group('network')]
    public function testPconnectSelectsCorrectDatabase()
    {
        if (!class_exists(\Redis::class)) {
            self::markTestSkipped('The "Redis" class is required.');
        }
        if (!getenv('REDIS_HOST')) {
            self::markTestSkipped('REDIS_HOST env var is not defined.');
        }
        if (!\ini_get('redis.pconnect.pooling_enabled')) {
            self::markTestSkipped('The bug only occurs when pooling is enabled.');
        }

        // Limit the connection pool size to 1:
        if (false === $prevPoolSize = ini_set('redis.pconnect.connection_limit', 1)) {
            self::markTestSkipped('Unable to set pool size');
        }

        try {
            $mock = new class {
                use RedisTrait;
            };

            $dsn = 'redis://'.getenv('REDIS_HOST');

            $cacheKey = 'testPconnectSelectsCorrectDatabase';
            $cacheValueOnDb1 = 'I should only be on database 1';

            // First connect to database 1 and set a value there so we can identify this database:
            $db1 = $mock::createConnection($dsn, ['dbindex' => 1, 'persistent' => 1]);
            self::assertInstanceOf(\Redis::class, $db1);
            self::assertSame(1, $db1->getDbNum());
            $db1->set($cacheKey, $cacheValueOnDb1);
            self::assertSame($cacheValueOnDb1, $db1->get($cacheKey));

            // Unset the connection - do not use `close()` or we will lose the persistent connection:
            unset($db1);

            // Now connect to database 0 and see that we do not actually ended up on database 1 by checking the value:
            $db0 = $mock::createConnection($dsn, ['dbindex' => 0, 'persistent' => 1]);
            self::assertInstanceOf(\Redis::class, $db0);
            self::assertSame(0, $db0->getDbNum()); // Redis is lying here! We could actually be on any database!
            self::assertNotSame($cacheValueOnDb1, $db0->get($cacheKey)); // This value should not exist if we are actually on db 0
        } finally {
            ini_set('redis.pconnect.connection_limit', $prevPoolSize);
        }
    }

    #[DataProvider('provideDbIndexDsnParameter')]
    public function testDbIndexDsnParameter(string $dsn, int $expectedDb)
    {
        if (!getenv('REDIS_AUTHENTICATED_HOST')) {
            self::markTestSkipped('REDIS_AUTHENTICATED_HOST env var is not defined.');
        }

        $mock = new class {
            use RedisTrait;
        };
        $connection = $mock::createConnection($dsn);
        self::assertSame($expectedDb, $connection->getDbNum());
    }

    public static function provideDbIndexDsnParameter(): array
    {
        return [
            [
                'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST'),
                0,
            ],
            [
                'redis:?host['.getenv('REDIS_HOST').']',
                0,
            ],
            [
                'redis:?host['.getenv('REDIS_HOST').']&dbindex=1',
                1,
            ],
            [
                'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'?dbindex=2',
                2,
            ],
            [
                'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/4',
                4,
            ],
            [
                'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/?dbindex=5',
                5,
            ],
        ];
    }

    #[DataProvider('provideInvalidDbIndexDsnParameter')]
    public function testInvalidDbIndexDsnParameter(string $dsn)
    {
        if (!getenv('REDIS_AUTHENTICATED_HOST')) {
            self::markTestSkipped('REDIS_AUTHENTICATED_HOST env var is not defined.');
        }
        $this->expectException(InvalidArgumentException::class);

        $mock = new class {
            use RedisTrait;
        };
        $mock::createConnection($dsn);
    }

    public static function provideInvalidDbIndexDsnParameter(): array
    {
        return [
            [
                'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/abc',
            ],
            [
                'redis://:p%40ssword@'.getenv('REDIS_AUTHENTICATED_HOST').'/3?dbindex=6',
            ],
        ];
    }
}