-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
ContaoTestCase.php
427 lines (353 loc) · 13.8 KB
/
ContaoTestCase.php
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
<?php
declare(strict_types=1);
/*
* This file is part of Contao.
*
* (c) Leo Feyer
*
* @license LGPL-3.0-or-later
*/
namespace Contao\TestCase;
use Contao\BackendUser;
use Contao\Config;
use Contao\CoreBundle\DependencyInjection\ContaoCoreExtension;
use Contao\CoreBundle\Framework\Adapter;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\User;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Roave\BetterReflection\BetterReflection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
abstract class ContaoTestCase extends TestCase
{
private static array $tempDirs = [];
private static array $betterReflectionCache = [];
private array $backupServerEnvGetPost = [];
public static function tearDownAfterClass(): void
{
parent::tearDownAfterClass();
$key = basename(strtr(static::class, '\\', '/'));
if (!isset(self::$tempDirs[$key])) {
return;
}
$fs = new Filesystem();
if ($fs->exists(self::$tempDirs[$key])) {
$fs->remove(self::$tempDirs[$key]);
}
unset(self::$tempDirs[$key]);
}
protected function tearDown(): void
{
// Unset TL_CONFIG as we populate it in loadDefaultConfiguration (see #4656)
unset($GLOBALS['TL_CONFIG']);
parent::tearDown();
}
/**
* Returns the path to the temporary directory and creates it if it does not yet exist.
*/
protected static function getTempDir(): string
{
$key = basename(strtr(static::class, '\\', '/'));
if (!isset(self::$tempDirs[$key])) {
self::$tempDirs[$key] = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid($key.'_', true);
$fs = new Filesystem();
if (!$fs->exists(self::$tempDirs[$key])) {
$fs->mkdir(self::$tempDirs[$key]);
}
}
return self::$tempDirs[$key];
}
/**
* Returns a Symfony container with the Contao core extension configuration.
*/
protected function getContainerWithContaoConfiguration(string $projectDir = ''): ContainerBuilder
{
static $cachedContainers = [];
if (!isset($cachedContainers[$projectDir])) {
$cachedContainers[$projectDir] = new ContainerBuilder();
$cachedContainers[$projectDir]->setParameter('kernel.debug', false);
$cachedContainers[$projectDir]->setParameter('kernel.charset', 'UTF-8');
$cachedContainers[$projectDir]->setParameter('kernel.default_locale', 'en');
$cachedContainers[$projectDir]->setParameter('kernel.cache_dir', $projectDir.'/var/cache');
$cachedContainers[$projectDir]->setParameter('kernel.project_dir', $projectDir);
$cachedContainers[$projectDir]->setParameter('kernel.root_dir', $projectDir.'/app');
$cachedContainers[$projectDir]->setDefinition('request_stack', new Definition(RequestStack::class));
// Load the default configuration
$extension = new ContaoCoreExtension();
$extension->load([], $cachedContainers[$projectDir]);
}
$container = new ContainerBuilder();
$container->merge($cachedContainers[$projectDir]);
return $container;
}
/**
* Mocks the Contao framework with optional adapters.
*
* A Config adapter with the default Contao configuration will be added
* automatically if no Config adapter is given.
*
* @return ContaoFramework&MockObject
*/
protected function mockContaoFramework(array $adapters = []): ContaoFramework
{
$this->addConfigAdapter($adapters);
$framework = $this->createMock(ContaoFramework::class);
$framework
->method('isInitialized')
->willReturn(true)
;
$framework
->method('getAdapter')
->willReturnCallback(static fn (string $key): ?Adapter => $adapters[$key] ?? null)
;
return $framework;
}
/**
* Mocks an adapter with the given methods.
*
* @return Adapter&MockObject
*/
protected function mockAdapter(array $methods): Adapter
{
return $this
->getMockBuilder(Adapter::class)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->addMethods($methods)
->getMock()
;
}
/**
* Mocks a configured adapter with the given methods and return values.
*
* @return Adapter&MockObject
*/
protected function mockConfiguredAdapter(array $configuration): Adapter
{
$adapter = $this->mockAdapter(array_keys($configuration));
foreach ($configuration as $method => $return) {
$adapter
->method($method)
->willReturn($return)
;
}
return $adapter;
}
/**
* Mocks a class with magic properties.
*
* @template T
*
* @param class-string<T> $class
*
* @return T&MockObject
*/
protected function mockClassWithProperties(string $class, array $properties = []): MockObject
{
$mock = $this->createMock($class);
$mock
->method('__get')
->willReturnCallback(
static function (string $key) use (&$properties) {
return $properties[$key] ?? null;
}
)
;
if (\in_array('__set', get_class_methods($class), true)) {
$mock
->method('__set')
->willReturnCallback(
static function (string $key, $value) use (&$properties): void {
$properties[$key] = $value;
}
)
;
}
if (\in_array('__isset', get_class_methods($class), true)) {
$mock
->method('__isset')
->willReturnCallback(
static function (string $key) use (&$properties) {
return isset($properties[$key]);
}
)
;
}
return $mock;
}
/**
* Mocks a token storage with a Contao user.
*/
protected function mockTokenStorage(string $class): TokenStorageInterface
{
if (!is_a($class, User::class, true)) {
throw new \InvalidArgumentException(sprintf('Class "%s" is not a Contao\User class', $class));
}
$token = $this->createMock(TokenInterface::class);
$token
->method('getUser')
->willReturn($this->createMock($class))
;
$token
->method('isAuthenticated')
->willReturn(true)
;
$token
->method('getRoleNames')
->willReturn([is_a($class, BackendUser::class, true) ? 'ROLE_USER' : 'ROLE_MEMBER'])
;
$tokenStorage = $this->createMock(TokenStorageInterface::class);
$tokenStorage
->method('getToken')
->willReturn($token)
;
return $tokenStorage;
}
protected function backupServerEnvGetPost(): void
{
$this->backupServerEnvGetPost = [
'_SERVER' => $_SERVER,
'_ENV' => $_ENV,
'_GET' => $_GET,
'_POST' => $_POST,
];
}
protected function restoreServerEnvGetPost(): void
{
$_SERVER = $this->backupServerEnvGetPost['_SERVER'] ?? $_SERVER;
$_ENV = $this->backupServerEnvGetPost['_ENV'] ?? $_ENV;
$_GET = $this->backupServerEnvGetPost['_GET'] ?? [];
$_POST = $this->backupServerEnvGetPost['_POST'] ?? [];
}
/**
* @param array<int, class-string|array{0: class-string, 1: array<int, string>}> $classNames
*/
protected function resetStaticProperties(array $classNames): void
{
foreach ($classNames as $class) {
$properties = null;
if (\is_array($class)) {
$properties = $class[1];
$class = $class[0];
}
if (!class_exists($class, false)) {
continue;
}
$reflectionClass = new \ReflectionClass($class);
if (
null === $properties
&& \is_callable([$class, 'reset'])
&& method_exists($class, 'reset')
&& $reflectionClass->getMethod('reset')->isStatic()
&& $reflectionClass->getMethod('reset')->getDeclaringClass()->getName() === $class
&& 0 === \count($reflectionClass->getMethod('reset')->getParameters())
) {
$class::reset();
continue;
}
foreach ($reflectionClass->getProperties(\ReflectionProperty::IS_STATIC) as $property) {
if (null !== $properties && !\in_array($property->getName(), $properties, true)) {
continue;
}
if ($property->getDeclaringClass()->getName() !== $class) {
continue;
}
$property->setAccessible(true);
if (!$property->isInitialized()) {
continue;
}
[$hasDefaultValue, $defaultValue] = $this->getDefaultStaticProperty($property);
if (!$hasDefaultValue || $property->getValue() === $defaultValue) {
continue;
}
$property->setValue(null, $defaultValue);
}
}
}
private function getDefaultStaticProperty(\ReflectionProperty $property): array
{
// See https://github.com/php/php-src/commit/3eb97a456648c739533d92c81102cb919eab01c9
if (\PHP_VERSION_ID >= 80100) {
return [$property->hasDefaultValue(), $property->getDefaultValue()];
}
if (!class_exists(BetterReflection::class)) {
throw new \RuntimeException('To use the ContaoTestCase::resetStaticProperties() method on PHP 8.0 or lower please install "roave/better-reflection".');
}
$class = $property->getDeclaringClass()->getName();
$name = $property->getName();
$cacheKey = $class.'::'.$name;
if (isset(self::$betterReflectionCache[$cacheKey])) {
return self::$betterReflectionCache[$cacheKey];
}
if (method_exists(BetterReflection::class, 'reflector')) {
$betterProperty = (new BetterReflection())->reflector()->reflectClass($class)->getProperty($name);
} else {
$betterProperty = (new BetterReflection())->classReflector()->reflect($class)->getProperty($name);
}
return self::$betterReflectionCache[$cacheKey] = [
$betterProperty->isDefault(),
$betterProperty->getDefaultValue(),
];
}
/**
* Adds the Config adapter if not present.
*/
private function addConfigAdapter(array &$adapters): void
{
if (isset($adapters[Config::class])) {
return;
}
$this->loadDefaultConfiguration();
$adapter = $this->mockAdapter(['isComplete', 'get']);
$adapter
->method('isComplete')
->willReturn(true)
;
$adapter
->method('get')
->willReturnCallback(static fn (string $key) => $GLOBALS['TL_CONFIG'][$key] ?? null)
;
$adapters[Config::class] = $adapter;
}
/**
* Loads the default configuration from the Contao core bundle.
*/
private function loadDefaultConfiguration(): void
{
switch (true) {
// The core-bundle is in the vendor folder of the monorepo
case file_exists(__DIR__.'/../../../../core-bundle/src/Resources/contao/config/default.php'):
include __DIR__.'/../../../../core-bundle/src/Resources/contao/config/default.php';
break;
// The test-case is in the vendor-bin folder
case file_exists(__DIR__.'/../../../../../../core-bundle/src/Resources/contao/config/default.php'):
include __DIR__.'/../../../../../../core-bundle/src/Resources/contao/config/default.php';
break;
// The core-bundle is in the vendor folder of the managed edition
case file_exists(__DIR__.'/../../../../../core-bundle/src/Resources/contao/config/default.php'):
include __DIR__.'/../../../../../core-bundle/src/Resources/contao/config/default.php';
break;
// The core-bundle is the root package and the test-case folder is in vendor/contao
case file_exists(__DIR__.'/../../../../src/Resources/contao/config/default.php'):
include __DIR__.'/../../../../src/Resources/contao/config/default.php';
break;
// Another bundle is the root package and the core-bundle folder is in vendor/contao
case file_exists(__DIR__.'/../../core-bundle/src/Resources/contao/config/default.php'):
include __DIR__.'/../../core-bundle/src/Resources/contao/config/default.php';
break;
// The test-case is the root package and the core-bundle folder is in vendor/contao
case file_exists(__DIR__.'/../vendor/contao/core-bundle/src/Resources/contao/config/default.php'):
include __DIR__.'/../vendor/contao/core-bundle/src/Resources/contao/config/default.php';
break;
default:
throw new \RuntimeException('Cannot find the Contao configuration file');
}
}
}