-
Notifications
You must be signed in to change notification settings - Fork 182
/
WebTestCase.php
570 lines (497 loc) · 19.2 KB
/
WebTestCase.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
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
<?php
declare(strict_types=1);
/*
* This file is part of the Liip/FunctionalTestBundle
*
* (c) Lukas Kahwe Smith <smith@pooteeweet.org>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Liip\FunctionalTestBundle\Test;
use Doctrine\Common\DataFixtures\Executor\AbstractExecutor;
use Doctrine\Common\DataFixtures\ProxyReferenceRepository;
use Doctrine\Common\Persistence\ObjectManager;
use Liip\FunctionalTestBundle\Utils\HttpAssertions;
use PHPUnit\Framework\MockObject\MockBuilder;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ResettableContainerInterface;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @author Lea Haensenberger
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
abstract class WebTestCase extends BaseWebTestCase
{
protected $environment = 'test';
protected $containers;
// 5 * 1024 * 1024 KB
protected $maxMemory = 5242880;
// RUN COMMAND
protected $verbosityLevel;
protected $decorated;
/**
* @var array
*/
private $firewallLogins = [];
/**
* @var array
*/
private $excludedDoctrineTables = [];
/**
* Creates a mock object of a service identified by its id.
*
* @param string $id
*
* @return MockBuilder
*/
protected function getServiceMockBuilder(string $id): MockBuilder
{
$service = $this->getContainer()->get($id);
$class = get_class($service);
return $this->getMockBuilder($class)->disableOriginalConstructor();
}
/**
* Builds up the environment to run the given command.
*
* @param string $name
* @param array $params
* @param bool $reuseKernel
*
* @return CommandTester
*/
protected function runCommand(string $name, array $params = [], bool $reuseKernel = false): CommandTester
{
if (!$reuseKernel) {
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
$kernel = static::$kernel = static::createKernel(['environment' => $this->environment]);
$kernel->boot();
} else {
$kernel = $this->getContainer()->get('kernel');
}
$application = new Application($kernel);
$command = $application->find($name);
$commandTester = new CommandTester($command);
$commandTester->execute(
array_merge(['command' => $command->getName()], $params),
[
'interactive' => false,
'decorated' => $this->getDecorated(),
'verbosity' => $this->getVerbosityLevel(),
]
);
return $commandTester;
}
/**
* Retrieves the output verbosity level.
*
* @see \Symfony\Component\Console\Output\OutputInterface for available levels
*
* @throws \OutOfBoundsException If the set value isn't accepted
*
* @return int
*/
protected function getVerbosityLevel(): int
{
// If `null`, is not yet set
if (null === $this->verbosityLevel) {
// Set the global verbosity level that is set as NORMAL by the TreeBuilder in Configuration
$level = strtoupper($this->getContainer()->getParameter('liip_functional_test.command_verbosity'));
$verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
$this->verbosityLevel = constant($verbosity);
}
// If string, it is set by the developer, so check that the value is an accepted one
if (is_string($this->verbosityLevel)) {
$level = strtoupper($this->verbosityLevel);
$verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
if (!defined($verbosity)) {
throw new \OutOfBoundsException(
sprintf('The set value "%s" for verbosityLevel is not valid. Accepted are: "quiet", "normal", "verbose", "very_verbose" and "debug".', $level)
);
}
$this->verbosityLevel = constant($verbosity);
}
return $this->verbosityLevel;
}
public function setVerbosityLevel($level): void
{
$this->verbosityLevel = $level;
}
/**
* Set verbosity for Symfony 3.4+.
*
* @see https://github.com/symfony/symfony/pull/24425
*
* @param $level
*/
private function setVerbosityLevelEnv($level): void
{
putenv('SHELL_VERBOSITY='.$level);
}
/**
* Retrieves the flag indicating if the output should be decorated or not.
*
* @return bool
*/
protected function getDecorated(): bool
{
if (null === $this->decorated) {
// Set the global decoration flag that is set to `true` by the TreeBuilder in Configuration
$this->decorated = $this->getContainer()->getParameter('liip_functional_test.command_decoration');
}
// Check the local decorated flag
if (false === is_bool($this->decorated)) {
throw new \OutOfBoundsException(
sprintf('`WebTestCase::decorated` has to be `bool`. "%s" given.', gettype($this->decorated))
);
}
return $this->decorated;
}
public function isDecorated(bool $decorated): void
{
$this->decorated = $decorated;
}
/**
* Get an instance of the dependency injection container.
* (this creates a kernel *without* parameters).
*
* @return ContainerInterface
*/
protected function getContainer(): ContainerInterface
{
$cacheKey = $this->environment;
if (empty($this->containers[$cacheKey])) {
$options = [
'environment' => $this->environment,
];
$kernel = $this->createKernel($options);
$kernel->boot();
$container = $kernel->getContainer();
if ($container->has('test.service_container')) {
$this->containers[$cacheKey] = $container->get('test.service_container');
} else {
$this->containers[$cacheKey] = $container;
}
}
return $this->containers[$cacheKey];
}
/**
* Set the database to the provided fixtures.
*
* Drops the current database and then loads fixtures using the specified
* classes. The parameter is a list of fully qualified class names of
* classes that implement Doctrine\Common\DataFixtures\FixtureInterface
* so that they can be loaded by the DataFixtures Loader::addFixture
*
* When using SQLite this method will automatically make a copy of the
* loaded schema and fixtures which will be restored automatically in
* case the same fixture classes are to be loaded again. Caveat: changes
* to references and/or identities may go undetected.
*
* Depends on the doctrine data-fixtures library being available in the
* class path.
*
* @param array $classNames List of fully qualified class names of fixtures to load
* @param bool $append
* @param string $omName The name of object manager to use
* @param string $registryName The service id of manager registry to use
* @param int $purgeMode Sets the ORM purge mode
*
* @return null|AbstractExecutor
*/
protected function loadFixtures(array $classNames = [], bool $append = false, ?string $omName = null, string $registryName = 'doctrine', ?int $purgeMode = null): ?AbstractExecutor
{
$container = $this->getContainer();
$dbToolCollection = $container->get('liip_functional_test.services.database_tool_collection');
$dbTool = $dbToolCollection->get($omName, $registryName, $purgeMode, $this);
$dbTool->setExcludedDoctrineTables($this->excludedDoctrineTables);
return $dbTool->loadFixtures($classNames, $append);
}
/**
* @param array $paths Either symfony resource locators (@ BundleName/etc) or actual file paths
* @param bool $append
* @param null $omName
* @param string $registryName
* @param int $purgeMode
*
* @throws \BadMethodCallException
*
* @return array
*/
public function loadFixtureFiles(array $paths = [], bool $append = false, ?string $omName = null, $registryName = 'doctrine', ?int $purgeMode = null)
{
/** @var ContainerInterface $container */
$container = $this->getContainer();
$dbToolCollection = $container->get('liip_functional_test.services.database_tool_collection');
$dbTool = $dbToolCollection->get($omName, $registryName, $purgeMode, $this);
$dbTool->setExcludedDoctrineTables($this->excludedDoctrineTables);
return $dbTool->loadAliceFixture($paths, $append);
}
/**
* Callback function to be executed after Schema creation.
* Use this to execute acl:init or other things necessary.
*/
public function postFixtureSetup(): void
{
}
/**
* Callback function to be executed after Schema restore.
*
* @param string $backupFilePath Path of file used to backup the references of the data fixtures
*
* @return WebTestCase
*/
public function postFixtureBackupRestore($backupFilePath): self
{
return $this;
}
/**
* Callback function to be executed before Schema restore.
*
* @param ObjectManager $manager The object manager
* @param ProxyReferenceRepository $referenceRepository The reference repository
* @param string $backupFilePath Path of file used to backup the references of the data fixtures
*
* @return WebTestCase
*/
public function preFixtureBackupRestore(
ObjectManager $manager,
ProxyReferenceRepository $referenceRepository,
string $backupFilePath
): self {
return $this;
}
/**
* Callback function to be executed after save of references.
*
* @param ObjectManager $manager The object manager
* @param AbstractExecutor $executor Executor of the data fixtures
* @param string $backupFilePath Path of file used to backup the references of the data fixtures
*
* @return WebTestCase|null
*/
public function postReferenceSave(ObjectManager $manager, AbstractExecutor $executor, string $backupFilePath): self
{
return $this;
}
/**
* Callback function to be executed before save of references.
*
* @param ObjectManager $manager The object manager
* @param AbstractExecutor $executor Executor of the data fixtures
* @param string $backupFilePath Path of file used to backup the references of the data fixtures
*
* @return WebTestCase|null
*/
public function preReferenceSave(ObjectManager $manager, AbstractExecutor $executor, ?string $backupFilePath): self
{
return $this;
}
/**
* Creates an instance of a lightweight Http client.
*
* If $authentication is set to 'true' it will use the content of
* 'liip_functional_test.authentication' to log in.
*
* $params can be used to pass headers to the client, note that they have
* to follow the naming format used in $_SERVER.
* Example: 'HTTP_X_REQUESTED_WITH' instead of 'X-Requested-With'
*
* @param bool|array $authentication
* @param array $params
*
* @return Client
*/
protected function makeClient($authentication = false, array $params = []): Client
{
if ($authentication) {
if (true === $authentication) {
$authentication = [
'username' => $this->getContainer()
->getParameter('liip_functional_test.authentication.username'),
'password' => $this->getContainer()
->getParameter('liip_functional_test.authentication.password'),
];
}
$params = array_merge($params, [
'PHP_AUTH_USER' => $authentication['username'],
'PHP_AUTH_PW' => $authentication['password'],
]);
}
$client = static::createClient(['environment' => $this->environment], $params);
if ($this->firewallLogins) {
// has to be set otherwise "hasPreviousSession" in Request returns false.
$options = $client->getContainer()->getParameter('session.storage.options');
if (!$options || !isset($options['name'])) {
throw new \InvalidArgumentException('Missing session.storage.options#name');
}
$session = $client->getContainer()->get('session');
// Since the namespace of the session changed in symfony 2.1, instanceof can be used to check the version.
if ($session instanceof Session) {
$session->setId(uniqid());
}
$client->getCookieJar()->set(new Cookie($options['name'], $session->getId()));
/** @var $user UserInterface */
foreach ($this->firewallLogins as $firewallName => $user) {
$token = $this->createUserToken($user, $firewallName);
$tokenStorage = $client->getContainer()->get('security.token_storage');
$tokenStorage->setToken($token);
$session->set('_security_'.$firewallName, serialize($token));
}
$session->save();
}
return $client;
}
/**
* Create User Token.
*
* Factory method for creating a User Token object for the firewall based on
* the user object provided. By default it will be a Username/Password
* Token based on the user's credentials, but may be overridden for custom
* tokens in your applications.
*
* @param UserInterface $user The user object to base the token off of
* @param string $firewallName name of the firewall provider to use
*
* @return TokenInterface The token to be used in the security context
*/
protected function createUserToken(UserInterface $user, string $firewallName): TokenInterface
{
return new UsernamePasswordToken(
$user,
null,
$firewallName,
$user->getRoles()
);
}
/**
* Extracts the location from the given route.
*
* @param string $route The name of the route
* @param array $params Set of parameters
* @param int $absolute
*
* @return string
*/
protected function getUrl(string $route, array $params = [], int $absolute = UrlGeneratorInterface::ABSOLUTE_PATH): string
{
return $this->getContainer()->get('router')->generate($route, $params, $absolute);
}
/**
* Checks the success state of a response.
*
* @param Response $response Response object
* @param bool $success to define whether the response is expected to be successful
* @param string $type
*/
public function isSuccessful(Response $response, $success = true, $type = 'text/html'): void
{
HttpAssertions::isSuccessful($response, $success, $type);
}
/**
* Executes a request on the given url and returns the response contents.
*
* This method also asserts the request was successful.
*
* @param string $path path of the requested page
* @param string $method The HTTP method to use, defaults to GET
* @param bool $authentication Whether to use authentication, defaults to false
* @param bool $success to define whether the response is expected to be successful
*
* @return string
*/
public function fetchContent(string $path, string $method = 'GET', bool $authentication = false, bool $success = true): string
{
$client = $this->makeClient($authentication);
$client->request($method, $path);
$content = $client->getResponse()->getContent();
$this->isSuccessful($client->getResponse(), $success);
return $content;
}
/**
* Executes a request on the given url and returns a Crawler object.
*
* This method also asserts the request was successful.
*
* @param string $path path of the requested page
* @param string $method The HTTP method to use, defaults to GET
* @param bool $authentication Whether to use authentication, defaults to false
* @param bool $success Whether the response is expected to be successful
*
* @return Crawler
*/
public function fetchCrawler(string $path, string $method = 'GET', bool $authentication = false, bool $success = true): Crawler
{
$client = $this->makeClient($authentication);
$crawler = $client->request($method, $path);
$this->isSuccessful($client->getResponse(), $success);
return $crawler;
}
/**
* @param UserInterface $user
* @param string $firewallName
*
* @return WebTestCase
*/
public function loginAs(UserInterface $user, string $firewallName): self
{
$this->firewallLogins[$firewallName] = $user;
return $this;
}
/**
* Asserts that the HTTP response code of the last request performed by
* $client matches the expected code. If not, raises an error with more
* information.
*
* @param int $expectedStatusCode
* @param Client $client
*/
public static function assertStatusCode(int $expectedStatusCode, Client $client): void
{
HttpAssertions::assertStatusCode($expectedStatusCode, $client);
}
/**
* Assert that the last validation errors within $container match the
* expected keys.
*
* @param array $expected A flat array of field names
* @param ContainerInterface $container
*/
public static function assertValidationErrors(array $expected, ContainerInterface $container): void
{
HttpAssertions::assertValidationErrors($expected, $container);
}
/**
* @param array $excludedDoctrineTables
*/
public function setExcludedDoctrineTables(array $excludedDoctrineTables): void
{
$this->excludedDoctrineTables = $excludedDoctrineTables;
}
protected function tearDown()
{
if (null !== $this->containers) {
foreach ($this->containers as $container) {
if ($container instanceof ResettableContainerInterface) {
$container->reset();
}
}
}
$this->containers = null;
parent::tearDown();
}
}