File: AbstractTestCase.php

package info (click to toggle)
phpmyadmin 4%3A5.2.2-really%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 140,312 kB
  • sloc: javascript: 228,447; php: 166,904; xml: 17,847; sql: 504; sh: 275; makefile: 209; python: 205
file content (336 lines) | stat: -rw-r--r-- 9,398 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
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Tests;

use PhpMyAdmin\Cache;
use PhpMyAdmin\Config;
use PhpMyAdmin\Core;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Dbal\DbiExtension;
use PhpMyAdmin\LanguageManager;
use PhpMyAdmin\SqlParser\Translator;
use PhpMyAdmin\Tests\Stubs\DbiDummy;
use PhpMyAdmin\Tests\Stubs\ResponseRenderer;
use PhpMyAdmin\Theme;
use PhpMyAdmin\ThemeManager;
use PhpMyAdmin\Utils\HttpRequest;
use PHPUnit\Framework\TestCase;
use ReflectionClass;

use function array_keys;
use function in_array;
use function method_exists;

use const DIRECTORY_SEPARATOR;

/**
 * Abstract class to hold some usefull methods used in tests
 * And make tests clean
 */
abstract class AbstractTestCase extends TestCase
{
    /**
     * The variables to keep between tests
     *
     * @var string[]
     */
    private $globalsAllowList = [
        '__composer_autoload_files',
        'GLOBALS',
        '_SERVER',
        '__composer_autoload_files',
        '__PHPUNIT_CONFIGURATION_FILE',
        '__PHPUNIT_BOOTSTRAP',
    ];

    /**
     * The DatabaseInterface loaded by setGlobalDbi
     *
     * @var DatabaseInterface
     */
    protected $dbi;

    /**
     * The DbiDummy loaded by setGlobalDbi
     *
     * @var DbiDummy
     */
    protected $dummyDbi;

    /**
     * Prepares environment for the test.
     * Clean all variables
     */
    protected function setUp(): void
    {
        foreach (array_keys($GLOBALS) as $key) {
            if (in_array($key, $this->globalsAllowList)) {
                continue;
            }

            unset($GLOBALS[$key]);
        }

        $_GET = [];
        $_POST = [];
        $_SERVER = [
            // https://github.com/sebastianbergmann/phpunit/issues/4033
            'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
            'REQUEST_TIME' => $_SERVER['REQUEST_TIME'],
            'REQUEST_TIME_FLOAT' => $_SERVER['REQUEST_TIME_FLOAT'],
            'PHP_SELF' => $_SERVER['PHP_SELF'],
            'argv' => $_SERVER['argv'],
        ];
        $_SESSION = [' PMA_token ' => 'token'];
        $_COOKIE = [];
        $_FILES = [];
        $_REQUEST = [];

        $GLOBALS['server'] = 1;
        $GLOBALS['text_dir'] = 'ltr';
        $GLOBALS['db'] = '';
        $GLOBALS['table'] = '';
        $GLOBALS['PMA_PHP_SELF'] = '';
        $GLOBALS['lang'] = 'en';

        // Config before DBI
        $this->setGlobalConfig();
        $this->loadContainerBuilder();
        $this->setGlobalDbi();
        $this->loadDbiIntoContainerBuilder();
        Cache::purge();
    }

    protected function createDatabaseInterface(?DbiExtension $extension = null): DatabaseInterface
    {
        return new DatabaseInterface($extension ?? $this->createDbiDummy());
    }

    protected function createDbiDummy(): DbiDummy
    {
        return new DbiDummy();
    }

    public function consecutiveCalls(...$args): callable
    {
        $count = 0;
        return function ($arg) use (&$count, $args) {
            return $arg === $args[$count++];
        };
    }

    protected function assertAllQueriesConsumed(): void
    {
        $unUsedQueries = $this->dummyDbi->getUnUsedQueries();
        self::assertSame([], $unUsedQueries, 'Some queries where not used !');
    }

    protected function assertAllSelectsConsumed(): void
    {
        $unUsedSelects = $this->dummyDbi->getUnUsedDatabaseSelects();
        self::assertSame([], $unUsedSelects, 'Some database selects where not used !');
    }

    protected function assertAllErrorCodesConsumed(): void
    {
        if ($this->dummyDbi->hasUnUsedErrors() === false) {
            self::assertTrue(true);// increment the assertion count

            return;
        }

        $this->fail('Some error codes where not used !');
    }

    /**
     * PHPUnit 8 compatibility
     */
    public static function assertMatchesRegularExpressionCompat(
        string $pattern,
        string $string,
        string $message = ''
    ): void {
        if (method_exists(TestCase::class, 'assertMatchesRegularExpression')) {
            /** @phpstan-ignore-next-line */
            parent::assertMatchesRegularExpression($pattern, $string, $message);
        } else {
            /** @psalm-suppress DeprecatedMethod */
            self::assertRegExp($pattern, $string, $message);
        }
    }

    protected function loadContainerBuilder(): void
    {
        global $containerBuilder;

        $containerBuilder = Core::getContainerBuilder();
    }

    protected function loadDbiIntoContainerBuilder(): void
    {
        global $containerBuilder, $dbi;

        $containerBuilder->set(DatabaseInterface::class, $dbi);
        $containerBuilder->setAlias('dbi', DatabaseInterface::class);
    }

    protected function loadResponseIntoContainerBuilder(): void
    {
        global $containerBuilder;

        $response = new ResponseRenderer();
        $containerBuilder->set(ResponseRenderer::class, $response);
        $containerBuilder->setAlias('response', ResponseRenderer::class);
    }

    protected function setResponseIsAjax(): void
    {
        global $containerBuilder;

        /** @var ResponseRenderer $response */
        $response = $containerBuilder->get(ResponseRenderer::class);

        $response->setAjax(true);
    }

    protected function getResponseHtmlResult(): string
    {
        global $containerBuilder;

        /** @var ResponseRenderer $response */
        $response = $containerBuilder->get(ResponseRenderer::class);

        return $response->getHTMLResult();
    }

    protected function getResponseJsonResult(): array
    {
        global $containerBuilder;

        /** @var ResponseRenderer $response */
        $response = $containerBuilder->get(ResponseRenderer::class);

        return $response->getJSONResult();
    }

    protected function assertResponseWasNotSuccessfull(): void
    {
        global $containerBuilder;
        /** @var ResponseRenderer $response */
        $response = $containerBuilder->get(ResponseRenderer::class);

        self::assertFalse($response->hasSuccessState(), 'expected the request to fail');
    }

    protected function assertResponseWasSuccessfull(): void
    {
        global $containerBuilder;
        /** @var ResponseRenderer $response */
        $response = $containerBuilder->get(ResponseRenderer::class);

        self::assertTrue($response->hasSuccessState(), 'expected the request not to fail');
    }

    protected function setGlobalDbi(): void
    {
        global $dbi;
        $this->dummyDbi = new DbiDummy();
        $this->dbi = DatabaseInterface::load($this->dummyDbi);
        $dbi = $this->dbi;
    }

    protected function setGlobalConfig(): void
    {
        global $config, $cfg;
        $config = new Config();
        $config->checkServers();
        $config->set('environment', 'development');
        $cfg = $config->settings;
    }

    protected function setTheme(): void
    {
        global $theme;
        $theme = Theme::load(
            ThemeManager::getThemesDir() . 'pmahomme',
            ThemeManager::getThemesFsDir() . 'pmahomme' . DIRECTORY_SEPARATOR,
            'pmahomme'
        );
    }

    protected function setLanguage(string $code = 'en'): void
    {
        global $lang;

        $lang = $code;
        /* Ensure default language is active */
        $languageEn = LanguageManager::getInstance()->getLanguage($code);
        if ($languageEn === false) {
            return;
        }

        $languageEn->activate();
        Translator::load();
    }

    protected function setProxySettings(): void
    {
        HttpRequest::setProxySettingsFromEnv();
    }

    /**
     * Destroys the environment built for the test.
     * Clean all variables
     */
    protected function tearDown(): void
    {
        foreach (array_keys($GLOBALS) as $key) {
            if (in_array($key, $this->globalsAllowList)) {
                continue;
            }

            unset($GLOBALS[$key]);
        }
    }

    /**
     * Call protected functions by setting visibility to public.
     *
     * @param object|null $object     The object to inspect, pass null for static objects()
     * @param string      $className  The class name
     * @param string      $methodName The method name
     * @param array       $params     The parameters for the invocation
     * @phpstan-param class-string $className
     *
     * @return mixed the output from the protected method.
     */
    protected function callFunction($object, string $className, string $methodName, array $params)
    {
        $class = new ReflectionClass($className);
        $method = $class->getMethod($methodName);
        $method->setAccessible(true);

        return $method->invokeArgs($object, $params);
    }

    /**
     * Get a private or protected property via reflection.
     *
     * @param object $object       The object to inspect, pass null for static objects()
     * @param string $className    The class name
     * @param string $propertyName The method name
     * @phpstan-param class-string $className
     *
     * @return mixed
     */
    protected function getProperty(object $object, string $className, string $propertyName)
    {
        $class = new ReflectionClass($className);
        $property = $class->getProperty($propertyName);
        $property->setAccessible(true);

        return $property->getValue($object);
    }
}