Completed
Push — master ( 80e59a...607312 )
by François-Xavier
02:52
created

Base::_checkConnection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Elastica\Test;
4
5
use Elastica\Client;
6
use Elastica\Connection;
7
use Elastica\Index;
8
use Elasticsearch\Endpoints\Ingest\Pipeline\Put;
9
use Elasticsearch\Endpoints\Ingest\PutPipeline;
10
use PHPUnit\Framework\TestCase;
11
use PHPUnit\Util\Test as TestUtil;
12
use Psr\Log\LoggerInterface;
13
14
/**
15
 * @internal
16
 */
17
class Base extends TestCase
18
{
19
    protected function setUp(): void
20
    {
21
        parent::setUp();
22
23
        $hasGroup = $this->_isUnitGroup() || $this->_isFunctionalGroup() || $this->_isBenchmarkGroup();
24
        $this->assertTrue($hasGroup, 'Every test must have one of "unit", "functional", "benchmark" group');
25
        $this->showDeprecated();
26
    }
27
28
    protected function tearDown(): void
29
    {
30
        if ($this->_isFunctionalGroup()) {
31
            $this->_getClient()->getIndex('_all')->delete();
32
            $this->_getClient()->getIndex('_all')->clearCache();
33
        }
34
35
        parent::tearDown();
36
    }
37
38
    protected static function hideDeprecated(): void
39
    {
40
        \error_reporting(\error_reporting() & ~\E_USER_DEPRECATED);
41
    }
42
43
    protected static function showDeprecated(): void
44
    {
45
        \error_reporting(\error_reporting() | \E_USER_DEPRECATED);
46
    }
47
48
    /**
49
     * @param array $params Additional configuration params. Host and Port are already set
50
     */
51
    protected function _getClient(array $params = [], ?callable $callback = null, ?LoggerInterface $logger = null): Client
52
    {
53
        $config = [
54
            'host' => $this->_getHost(),
55
            'port' => $this->_getPort(),
56
        ];
57
58
        $config = \array_merge($config, $params);
59
60
        return new Client($config, $callback, $logger);
61
    }
62
63
    /**
64
     * @return string Host to es for elastica tests
65
     */
66
    protected function _getHost()
67
    {
68
        return \getenv('ES_HOST') ?: Connection::DEFAULT_HOST;
69
    }
70
71
    /**
72
     * @return int Port to es for elastica tests
73
     */
74
    protected function _getPort()
75
    {
76
        return \getenv('ES_PORT') ?: Connection::DEFAULT_PORT;
77
    }
78
79
    protected function _getProxyUrl(): string
80
    {
81
        $proxyHost = \getenv('PROXY_HOST') ?: Connection::DEFAULT_HOST;
82
83
        return 'http://'.$proxyHost.':8000';
84
    }
85
86
    protected function _getProxyUrl403(): string
87
    {
88
        $proxyHost = \getenv('PROXY_HOST') ?: Connection::DEFAULT_HOST;
89
90
        return 'http://'.$proxyHost.':8001';
91
    }
92
93
    protected function _createIndex(?string $name = null, bool $delete = true, int $shards = 1): Index
94
    {
95
        $name = $name ?: static::buildUniqueId();
96
97
        $client = $this->_getClient();
98
        $index = $client->getIndex($name);
99
100
        $index->create(['settings' => ['index' => ['number_of_shards' => $shards, 'number_of_replicas' => 1]]], [
101
            'recreate' => $delete,
102
        ]);
103
104
        return $index;
105
    }
106
107
    protected static function buildUniqueId(): string
108
    {
109
        return \preg_replace('/[^a-z]/i', '', \strtolower(static::class).\uniqid());
110
    }
111
112
    protected function _createRenamePipeline(): void
113
    {
114
        $client = $this->_getClient();
115
116
        // TODO: Use only PutPipeline when dropping support for elasticsearch/elasticsearch 7.x
117
        $endpoint = \class_exists(PutPipeline::class) ? new PutPipeline() : new Put();
118
        $endpoint->setID('renaming');
119
        $endpoint->setBody([
120
            'description' => 'Rename field',
121
            'processors' => [
122
                [
123
                    'rename' => [
124
                        'field' => 'old',
125
                        'target_field' => 'new',
126
                    ],
127
                ],
128
            ],
129
        ]);
130
131
        $client->requestEndpoint($endpoint);
132
    }
133
134
    protected function _checkPlugin($plugin): void
135
    {
136
        $nodes = $this->_getClient()->getCluster()->getNodes();
137
        if (!$nodes[0]->getInfo()->hasPlugin($plugin)) {
138
            $this->markTestSkipped($plugin.' plugin not installed.');
139
        }
140
    }
141
142
    protected function _getVersion()
143
    {
144
        $data = $this->_getClient()->request('/')->getData();
145
146
        return \substr($data['version']['number'], 0, 1);
147
    }
148
149
    protected function _checkVersion($version): void
150
    {
151
        $data = $this->_getClient()->request('/')->getData();
152
        $installedVersion = $data['version']['number'];
153
154
        if (\version_compare($installedVersion, $version) < 0) {
155
            $this->markTestSkipped('Test require '.$version.'+ version of Elasticsearch');
156
        }
157
    }
158
159
    protected function _waitForAllocation(Index $index): void
160
    {
161
        do {
162
            $state = $index->getClient()->getCluster()->getState();
163
            $indexState = $state['routing_table']['indices'][$index->getName()];
164
165
            $allocated = true;
166
            foreach ($indexState['shards'] as $shards) {
167
                foreach ($shards as $shard) {
168
                    if ('STARTED' !== $shard['state']) {
169
                        $allocated = false;
170
                    }
171
                }
172
            }
173
        } while (!$allocated);
174
    }
175
176
    protected function _isUnitGroup()
177
    {
178
        $groups = TestUtil::getGroups(\get_class($this), $this->getName(false));
179
180
        return \in_array('unit', $groups, true);
181
    }
182
183
    protected function _isFunctionalGroup()
184
    {
185
        $groups = TestUtil::getGroups(\get_class($this), $this->getName(false));
186
187
        return \in_array('functional', $groups, true);
188
    }
189
190
    protected function _isBenchmarkGroup()
191
    {
192
        $groups = TestUtil::getGroups(\get_class($this), $this->getName(false));
193
194
        return \in_array('benchmark', $groups, true);
195
    }
196
}
197