File: PredisTestCase.php

package info (click to toggle)
php-nrk-predis 3.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 8,680 kB
  • sloc: php: 71,678; xml: 50; makefile: 12
file content (640 lines) | stat: -rw-r--r-- 21,021 bytes parent folder | download
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
<?php

/*
 * This file is part of the Predis package.
 *
 * (c) 2009-2020 Daniele Alessandri
 * (c) 2021-2025 Till Krüss
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use PHPUnit\AssertSameWithPrecisionConstraint;
use PHPUnit\Framework\Attributes\RequiresPhpunit;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\OneOfConstraint;
use PHPUnit\Util\Test as TestUtil;
use Predis\Client;
use Predis\Command;
use Predis\Connection;

/**
 * Base test case class for the Predis test suite.
 */
abstract class PredisTestCase extends PHPUnit\Framework\TestCase
{
    protected $redisServerVersion;
    protected $redisJsonVersion;

    /**
     * @var string[]
     */
    private $modulesMapping = [
        'json' => ['annotation' => 'requiresRedisJsonVersion', 'name' => 'ReJSON'],
        'bloomFilter' => ['annotation' => 'requiresRedisBfVersion', 'name' => 'bf'],
        'search' => ['annotation' => 'requiresRediSearchVersion', 'name' => 'search'],
        'timeSeries' => ['annotation' => 'requiresRedisTimeSeriesVersion', 'name' => 'timeseries'],
    ];

    /**
     * Info of current Redis instance.
     *
     * @var array
     */
    private $info;

    /**
     * {@inheritdoc}
     */
    protected function setUp(): void
    {
        $this->checkRequiredRedisServerVersion();

        foreach ($this->modulesMapping as $module => $config) {
            $this->checkRequiredRedisModuleVersion($module);
        }
    }

    /**
     * Pauses the test case for the specified amount of time in seconds.
     *
     * @param float $seconds Seconds to sleep
     */
    protected function sleep(float $seconds): void
    {
        usleep($seconds * 1000000);
    }

    /**
     * Verifies that a Redis command is a valid Predis\Command\CommandInterface
     * instance with the specified ID and command arguments.
     *
     * @param Command\CommandInterface|string $command   Expected command instance or command ID
     * @param ?array                          $arguments Expected command arguments
     *
     * @return RedisCommandConstraint
     */
    public function isRedisCommand($command = null, ?array $arguments = null): RedisCommandConstraint
    {
        return new RedisCommandConstraint($command, $arguments);
    }

    /**
     * Ensures that two Redis commands are similar.
     *
     * This method supports can test for different constraints by accepting a few
     * combinations of values as indicated below:
     *
     * - a string identifying a Redis command by its ID
     * - an instance of Predis\Command\CommandInterface
     * - an array of [(string) $commandID, (array) $commandArguments]
     *
     * Internally this method uses the RedisCommandConstraint class.
     *
     * @param Command\CommandInterface|string|array $expected Expected command instance or command ID
     * @param mixed                                 $actual   Actual command
     * @param string                                $message  Optional assertion message
     */
    public function assertRedisCommand($expected, $actual, string $message = ''): void
    {
        if (is_array($expected)) {
            @[$command, $arguments] = $expected;
        } else {
            $command = $expected;
            $arguments = null;
        }

        $this->assertThat($actual, new RedisCommandConstraint($command, $arguments), $message);
    }

    /**
     * Asserts that two arrays have the same values (even with different order).
     *
     * @param array  $expected Expected array
     * @param array  $actual   Actual array
     * @param string $message  Optional assertion message
     */
    public function assertSameValues(array $expected, array $actual, $message = ''): void
    {
        $this->assertThat($actual, new ArrayHasSameValuesConstraint($expected), $message);
    }

    /**
     * Asserts that actual value is one of the values from expected array.
     *
     * @param  mixed  $expected Expected array.
     * @param  mixed  $actual   Actual value. If array given searching for any matching value between two arrays.
     * @param  string $message  Optional assertion message
     * @return void
     */
    public function assertOneOf(array $expected, $actual, string $message = ''): void
    {
        $this->assertThat($actual, new OneOfConstraint($expected), $message);
    }

    /**
     * Asserts that two values (of the same type) have the same values with given precision.
     *
     * @param  mixed  $expected  Expected value
     * @param  mixed  $actual    Actual value
     * @param  int    $precision Precision value should be round to
     * @param  string $message   Optional assertion message
     * @return void
     */
    public function assertSameWithPrecision($expected, $actual, int $precision = 0, string $message = ''): void
    {
        $this->assertThat($actual, new AssertSameWithPrecisionConstraint($expected, $precision), $message);
    }

    /**
     * Returns a named array with default values for connection parameters.
     *
     * @return array Default connection parameters
     */
    protected function getDefaultParametersArray(): array
    {
        if ($this->isClusterTest()) {
            return $this->prepareClusterEndpoints();
        }

        $password = getenv('REDIS_PASSWORD') ?: constant('REDIS_PASSWORD');

        if ($this->isStackTest()) {
            $port = getenv('REDIS_STACK_SERVER_PORT');
        } elseif ($this->isUnprotectedTest()) {
            $port = constant('REDIS_UNPROTECTED_SERVER_PORT');
            $password = '';
        } else {
            $port = constant('REDIS_SERVER_PORT');
        }

        return [
            'scheme' => 'tcp',
            'host' => constant('REDIS_SERVER_HOST'),
            'port' => $port,
            'database' => constant('REDIS_SERVER_DBNUM'),
            'password' => $password,
        ];
    }

    /**
     * Returns a named array with default values for client options.
     *
     * @return array Default connection parameters
     */
    protected function getDefaultOptionsArray(): array
    {
        return [
            'commands' => new Command\RedisFactory(),
        ];
    }

    /**
     * Merges a named array of connection parameters with current defaults.
     *
     * @param array $additional Additional connection parameters
     *
     * @return array
     */
    protected function getParametersArray(array $additional): array
    {
        return array_merge($this->getDefaultParametersArray(), $additional);
    }

    /**
     * Returns a new instance of connection parameters.
     *
     * Values in the optional $additional named array are merged with defaults.
     *
     * @param array $additional Additional connection parameters
     *
     * @return Connection\ParametersInterface
     */
    protected function getParameters($additional = []): Connection\ParametersInterface
    {
        $parameters = array_merge($this->getDefaultParametersArray(), $additional);
        $parameters = new Connection\Parameters($parameters);

        return $parameters;
    }

    /**
     * Returns a new instance of command factory.
     *
     * @return Command\Factory
     */
    protected function getCommandFactory(): Command\Factory
    {
        return new Command\RedisFactory();
    }

    /**
     * Returns a new instance of Predis\Client.
     *
     * Values in the optional $parameters named array are merged with defaults.
     * Values in the ottional $options named array are merged with defaults.
     *
     * @param array $parameters Additional connection parameters
     * @param array $options    Additional client options
     * @param bool  $flushdb    Flush selected database before returning the client
     *
     * @return Client
     */
    protected function createClient(?array $parameters = null, ?array $options = null, ?bool $flushdb = true): Client
    {
        $parameters = array_merge(
            $this->getDefaultParametersArray(),
            $parameters ?: []
        );

        $options = array_merge(
            ['commands' => $this->getCommandFactory()],
            $options ?: [],
            getenv('USE_RELAY') ? ['connections' => 'relay'] : []
        );

        if ($this->isClusterTest()) {
            $options = array_merge(
                [
                    'cluster' => 'redis',
                ],
                $options
            );
        }

        $client = new Client($parameters, $options);
        $client->connect();

        if ($flushdb) {
            $client->flushdb();
        }

        return $client;
    }

    /**
     * Returns a basic mock object of a connection to a single Redis node.
     *
     * The specified target interface used for the mock object must implement
     * Predis\Connection\NodeConnectionInterface.
     *
     * The mock object responds to getParameters() and __toString() by returning
     * the default connection parameters used by Predis or a set of connection
     * parameters specified in the optional second argument.
     *
     * @param string       $interface  Fully-qualified name of the target interface
     * @param array|string $parameters Optional connection parameters
     *
     * @return MockObject|Connection\NodeConnectionInterface
     */
    protected function getMockConnectionOfType(string $interface, $parameters = null)
    {
        if (!is_a($interface, '\Predis\Connection\NodeConnectionInterface', true)) {
            $method = __METHOD__;

            throw new InvalidArgumentException(
                "Argument `\$interface` for $method() expects a type implementing Predis\Connection\NodeConnectionInterface"
            );
        }

        $connection = $this->getMockBuilder($interface)->getMock();

        if ($parameters) {
            $parameters = Connection\Parameters::create($parameters);
            $hash = "{$parameters->host}:{$parameters->port}";

            $connection
                ->expects($this->any())
                ->method('getParameters')
                ->willReturn($parameters);
            $connection
                ->expects($this->any())
                ->method('__toString')
                ->willReturn($hash);
        }

        return $connection;
    }

    /**
     * Returns a basic mock object of a connection to a single Redis node.
     *
     * The mock object is based on Predis\Connection\NodeConnectionInterface.
     *
     * The mock object responds to getParameters() and __toString() by returning
     * the default connection parameters used by Predis or a set of connection
     * parameters specified in the optional second argument.
     *
     * @param array|string|null $parameters Optional connection parameters
     *
     * @return MockObject|Connection\NodeConnectionInterface
     */
    protected function getMockConnection($parameters = null)
    {
        return $this->getMockConnectionOfType('Predis\Connection\NodeConnectionInterface', $parameters);
    }

    /**
     * Returns the server version of the Redis instance used by the test suite.
     *
     * @return string
     * @throws RuntimeException When the client cannot retrieve the current server version
     */
    protected function getRedisServerVersion(): string
    {
        if (isset($this->redisServerVersion)) {
            return $this->redisServerVersion;
        }

        if (isset($this->info)) {
            $info = $this->info;
        } else {
            $client = $this->createClient(null, null, true);
            $info = array_change_key_case($client->info());
            $this->info = $info;
        }

        if (isset($info['server']['redis_version'])) {
            // Redis >= 2.6
            $version = $info['server']['redis_version'];
        } elseif (isset($info['redis_version'])) {
            // Redis < 2.6
            $version = $info['redis_version'];
        } else {
            $client = $this->createClient(null, null, true);
            $connection = $client->getConnection();
            throw new RuntimeException("Unable to retrieve a valid server info payload from $connection");
        }

        $this->redisServerVersion = $version;

        return $version;
    }

    /**
     * Returns the Redis server version required to run a @connected test.
     *
     * This value is retrieved from the @requiresRedisVersion annotation that
     * decorates the target test method.
     *
     * @return string
     */
    #[RequiresPhpunit('< 10')]
    protected function getRequiredRedisServerVersion(): ?string
    {
        $this->markTestSkipped('Skip test failing with PHPUnit 10');
        $annotations = TestUtil::parseTestMethodAnnotations(
            get_class($this),
            $this->getName(false)
        );

        if (isset($annotations['method']['requiresRedisVersion'], $annotations['method']['group'])
            && !empty($annotations['method']['requiresRedisVersion'])
            && in_array('connected', $annotations['method']['group'])
        ) {
            return $annotations['method']['requiresRedisVersion'][0];
        }

        return null;
    }

    /**
     * Compares the specified version string against the Redis server version in
     * use for integration tests.
     *
     * @param string $operator Comparison operator
     * @param string $version  Version to compare
     *
     * @return bool
     */
    public function isRedisServerVersion(string $operator, string $version): bool
    {
        $serverVersion = $this->getRedisServerVersion();
        $comparison = version_compare($serverVersion, $version);

        return (bool) eval("return $comparison $operator 0;");
    }

    /**
     * Ensures the current Redis server matches version requirements for tests.
     *
     * Requirements are retrieved from the @requiresRedisVersion annotation that
     * decorates test methods while the version of the Redis server used to run
     * integration tests is retrieved directly from the server by using `INFO`.
     *
     * @throws PHPUnit\Framework\SkippedTestError When the required Redis server version is not met
     */
    protected function checkRequiredRedisServerVersion(): void
    {
        if (!$requiredVersion = $this->getRequiredRedisServerVersion()) {
            return;
        }

        $requiredVersion = explode(' ', $requiredVersion, 2);

        if (count($requiredVersion) === 1) {
            $reqOperator = '>=';
            $reqVersion = $requiredVersion[0];
        } else {
            $reqOperator = $requiredVersion[0];
            $reqVersion = $requiredVersion[1];
        }

        if (!$this->isRedisServerVersion($reqOperator, $reqVersion)) {
            $serverVersion = $this->getRedisServerVersion();

            $this->markTestSkipped(
                "Test requires a Redis server instance $reqOperator $reqVersion but target server is $serverVersion"
            );
        }
    }

    /**
     * Ensures the current Redis JSON module matches version requirements for tests.
     *
     * @param  string $module
     * @return void
     */
    protected function checkRequiredRedisModuleVersion(string $module): void
    {
        if (null === $requiredVersion = $this->getRequiredModuleVersion($module)) {
            return;
        }

        if (version_compare($this->getRedisServerVersion(), '6.0.0', '<')) {
            $this->markTestSkipped(
                'Test skipped because Redis JSON module available since Redis 6.x'
            );
        }

        $requiredVersion = explode(' ', $requiredVersion, 2);

        if (count($requiredVersion) === 1) {
            $reqVersion = $requiredVersion[0];
        } else {
            $reqVersion = $requiredVersion[1];
        }

        if (!$this->isSatisfiedRedisModuleVersion($reqVersion, $module)) {
            $redisModuleVersion = $this->getRedisModuleVersion($this->modulesMapping[$module]['name']);
            $redisModuleVersion = str_replace('0', '.', $redisModuleVersion);

            $this->markTestSkipped(
                "Test requires a Redis $module module >= $reqVersion but target module is $redisModuleVersion"
            );
        }
    }

    /**
     * @param  string $versionToCheck
     * @param  string $module
     * @return bool
     */
    protected function isSatisfiedRedisModuleVersion(string $versionToCheck, string $module): bool
    {
        $currentVersion = $this->getRedisModuleVersion($this->modulesMapping[$module]['name']);
        $versionToCheck = str_replace('.', '', $versionToCheck);

        return (int) $currentVersion >= (int) $versionToCheck;
    }

    /**
     * Returns version of Redis JSON module if it's available.
     *
     * @param  string $module
     * @return string
     */
    protected function getRedisModuleVersion(string $module): string
    {
        if (isset($this->info)) {
            $info = $this->info;
        } else {
            $client = $this->createClient(null, null, true);
            $info = array_change_key_case($client->info());
            $this->info = $info;
        }

        return $info['modules'][$module]['ver'] ?? '0';
    }

    /**
     * Returns version of given module for current Redis instance.
     * Runs if command belong to one of modules and marked with appropriate annotation
     * Runs on @connected tests.
     *
     * @param  string $module
     * @return string
     */
    #[RequiresPhpunit('< 10')]
    protected function getRequiredModuleVersion(string $module): ?string
    {
        if (!isset($this->modulesMapping[$module])) {
            throw new InvalidArgumentException('No existing annotation for given module');
        }

        $moduleAnnotation = $this->modulesMapping[$module]['annotation'];
        $this->markTestSkipped('Skip test failing with PHPUnit 10');
        $annotations = TestUtil::parseTestMethodAnnotations(
            get_class($this),
            $this->getName(false)
        );

        if (isset($annotations['method'][$moduleAnnotation], $annotations['method']['group'])
            && !empty($annotations['method'][$moduleAnnotation])
            && in_array('connected', $annotations['method']['group'], true)
        ) {
            return $annotations['method'][$moduleAnnotation][0];
        }

        return null;
    }

    /**
     * Marks current test skipped when test suite is running on CI environments.
     *
     * @param string $message
     */
    protected function markTestSkippedOnCIEnvironment(string $message = 'Test skipped on CI environment'): void
    {
        if (getenv('GITHUB_ACTIONS') || getenv('TRAVIS')) {
            $this->markTestSkipped($message);
        }
    }

    /**
     * Check annotations if it's matches to cluster test scenario.
     *
     * @return bool
     */
    #[RequiresPhpunit('< 10')]
    protected function isClusterTest(): bool
    {
        $this->markTestSkipped('Skip test failing with PHPUnit 10');
        $annotations = TestUtil::parseTestMethodAnnotations(
            get_class($this),
            $this->getName(false)
        );

        $annotationExists = isset($annotations['method']['requiresRedisVersion']);

        if (!$annotationExists) {
            foreach ($this->modulesMapping as $module => $configuration) {
                if (isset($annotations['method'][$configuration['annotation']])) {
                    $annotationExists = true;
                }
            }
        }

        return $annotationExists
            && isset($annotations['method']['group'])
            && in_array('connected', $annotations['method']['group'], true)
            && in_array('cluster', $annotations['method']['group'], true);
    }

    /**
     * Check annotations if it's matches to stack test scenario.
     *
     * @return bool
     */
    protected function isStackTest(): bool
    {
        $annotations = TestUtil::parseTestMethodAnnotations(
            get_class($this),
            $this->getName(false)
        );

        return isset($annotations['class']['group'])
        && in_array('realm-stack', $annotations['class']['group'], true);
    }

    /**
     * Check annotations if it's matches to unprotected test scenario.
     *
     * @return bool
     */
    protected function isUnprotectedTest(): bool
    {
        $annotations = TestUtil::parseTestMethodAnnotations(
            get_class($this),
            $this->getName(false)
        );

        return isset($annotations['method']['group'])
            && in_array('unprotected', $annotations['method']['group'], true);
    }

    /**
     * Parse comma-separated cluster endpoints and convert them into tcp strings.
     *
     * @return array
     */
    protected function prepareClusterEndpoints(): array
    {
        $endpoints = explode(',', constant('REDIS_CLUSTER_ENDPOINTS'));

        return array_map(static function (string $elem) {
            return 'tcp://' . $elem;
        }, $endpoints);
    }
}