forked from liip/LiipFunctionalTestBundle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebTestCase.php
854 lines (728 loc) · 29.5 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
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
<?php
/*
* This file is part of the Liip/FunctionalTestBundle
*
* (c) Lukas Kahwe Smith <[email protected]>
*
* 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 Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Bridge\Doctrine\ManagerRegistry;
use Symfony\Bundle\DoctrineFixturesBundle\Common\DataFixtures\Loader;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Common\DataFixtures\Executor\AbstractExecutor;
use Doctrine\Common\DataFixtures\ProxyReferenceRepository;
use Doctrine\DBAL\Driver\PDOSqlite\Driver as SqliteDriver;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\ORM\Tools\SchemaTool;
use Nelmio\Alice\Fixtures;
/**
* @author Lea Haensenberger
* @author Lukas Kahwe Smith <[email protected]>
* @author Benjamin Eberlei <[email protected]>
*/
abstract class WebTestCase extends BaseWebTestCase
{
protected $environment = 'test';
protected $containers;
protected $kernelDir;
// 5 * 1024 * 1024 KB
protected $maxMemory = 5242880;
// RUN COMMAND
protected $verbosityLevel;
protected $decorated;
/**
* @var array
*/
private $firewallLogins = array();
/**
* @var array
*/
private static $cachedMetadatas = array();
protected static function getKernelClass()
{
$dir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : self::getPhpUnitXmlDir();
list($appname) = explode('\\', get_called_class());
$class = $appname.'Kernel';
$file = $dir.'/'.strtolower($appname).'/'.$class.'.php';
if (!file_exists($file)) {
return parent::getKernelClass();
}
require_once $file;
return $class;
}
/**
* Creates a mock object of a service identified by its id.
*
* @param string $id
*
* @return PHPUnit_Framework_MockObject_MockBuilder
*/
protected function getServiceMockBuilder($id)
{
$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 string
*/
protected function runCommand($name, array $params = array(), $reuseKernel = false)
{
array_unshift($params, $name);
if (!$reuseKernel) {
if (null !== static::$kernel) {
static::$kernel->shutdown();
}
$kernel = static::$kernel = $this->createKernel(array('environment' => $this->environment));
$kernel->boot();
} else {
$kernel = $this->getContainer()->get('kernel');
}
$application = new Application($kernel);
$application->setAutoExit(false);
// @codeCoverageIgnoreStart
if ('20301' === Kernel::VERSION_ID) {
$params = $this->configureVerbosityForSymfony20301($params);
}
// @codeCoverageIgnoreEnd
$input = new ArrayInput($params);
$input->setInteractive(false);
$fp = fopen('php://temp/maxmemory:'.$this->maxMemory, 'r+');
$output = new StreamOutput($fp, $this->getVerbosityLevel(), $this->getDecorated());
$application->run($input, $output);
rewind($fp);
return stream_get_contents($fp);
}
/**
* Retrieves the output verbosity level.
*
* @see Symfony\Component\Console\Output\OutputInterface for available levels
*
* @return int
*
* @throws \OutOfBoundsException If the set value isn't accepted
*/
protected function getVerbosityLevel()
{
// 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 (null === constant($verbosity)) {
throw new \OutOfBoundsException(
'The set value "%s" for verbosityLevel is not valid. Accepted are: "quiet", "normal", "verbose", "very_verbose" and "debug".
');
}
$this->verbosityLevel = constant($verbosity);
}
return $this->verbosityLevel;
}
/**
* In Symfony 2.3.1 the verbosity level has to be set through {Symfony\Component\Console\Input\ArrayInput} and not
* in {Symfony\Component\Console\Output\OutputInterface}.
*
* This method builds $params to be passed to {Symfony\Component\Console\Input\ArrayInput}.
*
* @codeCoverageIgnore
*
* @param array $params
*
* @return array
*/
private function configureVerbosityForSymfony20301(array $params)
{
switch ($this->getVerbosityLevel()) {
case OutputInterface::VERBOSITY_QUIET:
$params['-q'] = '-q';
break;
case OutputInterface::VERBOSITY_VERBOSE:
$params['-v'] = '';
break;
case OutputInterface::VERBOSITY_VERY_VERBOSE:
$params['-vv'] = '';
break;
case OutputInterface::VERBOSITY_DEBUG:
$params['-vvv'] = '';
break;
}
return $params;
}
public function setVerbosityLevel($level)
{
$this->verbosityLevel = $level;
}
/**
* Retrieves the flag indicating if the output should be decorated or not.
*
* @return bool
*/
protected function getDecorated()
{
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($decorated)
{
$this->decorated = $decorated;
}
/**
* Get an instance of the dependency injection container.
* (this creates a kernel *without* parameters).
*
* @return ContainerInterface
*/
protected function getContainer()
{
if (!empty($this->kernelDir)) {
$tmpKernelDir = isset($_SERVER['KERNEL_DIR']) ? $_SERVER['KERNEL_DIR'] : null;
$_SERVER['KERNEL_DIR'] = getcwd().$this->kernelDir;
}
$cacheKey = $this->kernelDir.'|'.$this->environment;
if (empty($this->containers[$cacheKey])) {
$options = array(
'environment' => $this->environment,
);
$kernel = $this->createKernel($options);
$kernel->boot();
$this->containers[$cacheKey] = $kernel->getContainer();
}
if (isset($tmpKernelDir)) {
$_SERVER['KERNEL_DIR'] = $tmpKernelDir;
}
return $this->containers[$cacheKey];
}
/**
* This function finds the time when the data blocks of a class definition
* file were being written to, that is, the time when the content of the
* file was changed.
*
* @param string $class The fully qualified class name of the fixture class to
* check modification date on.
*
* @return \DateTime|null
*/
protected function getFixtureLastModified($class)
{
$lastModifiedDateTime = null;
$reflClass = new \ReflectionClass($class);
$classFileName = $reflClass->getFileName();
if (file_exists($classFileName)) {
$lastModifiedDateTime = new \DateTime();
$lastModifiedDateTime->setTimestamp(filemtime($classFileName));
}
return $lastModifiedDateTime;
}
/**
* Determine if the Fixtures that define a database backup have been
* modified since the backup was made.
*
* @param array $classNames The fixture classnames to check
* @param string $backup The fixture backup SQLite database file path
*
* @return bool TRUE if the backup was made since the modifications to the
* fixtures; FALSE otherwise
*/
protected function isBackupUpToDate(array $classNames, $backup)
{
$backupLastModifiedDateTime = new \DateTime();
$backupLastModifiedDateTime->setTimestamp(filemtime($backup));
foreach ($classNames as &$className) {
$fixtureLastModifiedDateTime = $this->getFixtureLastModified($className);
if ($backupLastModifiedDateTime < $fixtureLastModifiedDateTime) {
return false;
}
}
return true;
}
/**
* 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 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, $omName = null, $registryName = 'doctrine', $purgeMode = null)
{
$container = $this->getContainer();
/** @var ManagerRegistry $registry */
$registry = $container->get($registryName);
$om = $registry->getManager($omName);
$type = $registry->getName();
$executorClass = 'PHPCR' === $type && class_exists('Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor')
? 'Doctrine\Bundle\PHPCRBundle\DataFixtures\PHPCRExecutor'
: 'Doctrine\\Common\\DataFixtures\\Executor\\'.$type.'Executor';
$referenceRepository = new ProxyReferenceRepository($om);
$cacheDriver = $om->getMetadataFactory()->getCacheDriver();
if ($cacheDriver) {
$cacheDriver->deleteAll();
}
if ('ORM' === $type) {
$connection = $om->getConnection();
if ($connection->getDriver() instanceof SqliteDriver) {
$params = $connection->getParams();
if (isset($params['master'])) {
$params = $params['master'];
}
$name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
if (!$name) {
throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped.");
}
if (!isset(self::$cachedMetadatas[$omName])) {
self::$cachedMetadatas[$omName] = $om->getMetadataFactory()->getAllMetadata();
usort(self::$cachedMetadatas[$omName], function ($a, $b) { return strcmp($a->name, $b->name); });
}
$metadatas = self::$cachedMetadatas[$omName];
if ($container->getParameter('liip_functional_test.cache_sqlite_db')) {
$backup = $container->getParameter('kernel.cache_dir').'/test_'.md5(serialize($metadatas).serialize($classNames)).'.db';
if (file_exists($backup) && file_exists($backup.'.ser') && $this->isBackupUpToDate($classNames, $backup)) {
$om->flush();
$om->clear();
$this->preFixtureRestore($om, $referenceRepository);
copy($backup, $name);
$executor = new $executorClass($om);
$executor->setReferenceRepository($referenceRepository);
$executor->getReferenceRepository()->load($backup);
$this->postFixtureRestore();
return $executor;
}
}
// TODO: handle case when using persistent connections. Fail loudly?
$schemaTool = new SchemaTool($om);
$schemaTool->dropDatabase($name);
if (!empty($metadatas)) {
$schemaTool->createSchema($metadatas);
}
$this->postFixtureSetup();
$executor = new $executorClass($om);
$executor->setReferenceRepository($referenceRepository);
}
}
if (empty($executor)) {
$purgerClass = 'Doctrine\\Common\\DataFixtures\\Purger\\'.$type.'Purger';
if ('PHPCR' === $type) {
$purger = new $purgerClass($om);
$initManager = $container->has('doctrine_phpcr.initializer_manager')
? $container->get('doctrine_phpcr.initializer_manager')
: null;
$executor = new $executorClass($om, $purger, $initManager);
} else {
$purger = new $purgerClass();
if (null !== $purgeMode) {
$purger->setPurgeMode($purgeMode);
}
$executor = new $executorClass($om, $purger);
}
$executor->setReferenceRepository($referenceRepository);
$executor->purge();
}
$loader = $this->getFixtureLoader($container, $classNames);
$executor->execute($loader->getFixtures(), true);
if (isset($name) && isset($backup)) {
$this->preReferenceSave($om, $executor, $backup);
$executor->getReferenceRepository()->save($backup);
copy($name, $backup);
$this->postReferenceSave($om, $executor, $backup);
}
return $executor;
}
/**
* @param array $paths Either symfony resource locators (@ BundleName/etc) or actual file paths
* @param bool $append
* @param null $omName
* @param string $registryName
*
* @return array
*
* @throws \BadMethodCallException
*/
public function loadFixtureFiles(array $paths = array(), $append = false, $omName = null, $registryName = 'doctrine')
{
if (!class_exists('Nelmio\Alice\Fixtures')) {
throw new \BadMethodCallException('nelmio/alice should be installed to use this method.');
}
/** @var ManagerRegistry $registry */
$registry = $this->getContainer()->get($registryName);
$om = $registry->getManager($omName);
if ($append === false) {
//Clean database
$connection = $om->getConnection();
if ($registry->getName() === 'ORM' && $connection->getDatabasePlatform() instanceof MySqlPlatform) {
$connection->query('SET FOREIGN_KEY_CHECKS=0');
}
$this->loadFixtures(array());
if ($registry->getName() === 'ORM' && $connection->getDatabasePlatform() instanceof MySqlPlatform) {
$connection->query('SET FOREIGN_KEY_CHECKS=1');
}
}
$files = array();
$kernel = $this->getContainer()->get('kernel');
foreach ($paths as $path) {
if ($path[0] !== '@' && file_exists($path) === true) {
$files[] = $path;
continue;
}
$files[] = $kernel->locateResource($path);
}
return Fixtures::load($files, $om);
}
/**
* Callback function to be executed after Schema creation.
* Use this to execute acl:init or other things necessary.
*/
protected function postFixtureSetup()
{
}
/**
* Callback function to be executed after Schema restore.
*
* @return WebTestCase
*/
protected function postFixtureRestore()
{
}
/**
* Callback function to be executed before Schema restore.
*
* @param ObjectManager $manager The object manager
* @param ProxyReferenceRepository $referenceRepository The reference repository
*
* @return WebTestCase
*/
protected function preFixtureRestore(ObjectManager $manager, ProxyReferenceRepository $referenceRepository)
{
}
/**
* 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
*/
protected function postReferenceSave(ObjectManager $manager, AbstractExecutor $executor, $backupFilePath)
{
}
/**
* 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
*/
protected function preReferenceSave(ObjectManager $manager, AbstractExecutor $executor, $backupFilePath)
{
}
/**
* Retrieve Doctrine DataFixtures loader.
*
* @param ContainerInterface $container
* @param array $classNames
*
* @return Loader
*/
protected function getFixtureLoader(ContainerInterface $container, array $classNames)
{
$loaderClass = class_exists('Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader')
? 'Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader'
: (class_exists('Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader')
? 'Doctrine\Bundle\FixturesBundle\Common\DataFixtures\Loader'
: 'Symfony\Bundle\DoctrineFixturesBundle\Common\DataFixtures\Loader');
$loader = new $loaderClass($container);
foreach ($classNames as $className) {
$this->loadFixtureClass($loader, $className);
}
return $loader;
}
/**
* Load a data fixture class.
*
* @param Loader $loader
* @param string $className
*/
protected function loadFixtureClass($loader, $className)
{
$fixture = new $className();
if ($loader->hasFixture($fixture)) {
unset($fixture);
return;
}
$loader->addFixture($fixture);
if ($fixture instanceof DependentFixtureInterface) {
foreach ($fixture->getDependencies() as $dependency) {
$this->loadFixtureClass($loader, $dependency);
}
}
}
/**
* 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 = array())
{
if ($authentication) {
if ($authentication === true) {
$authentication = $this->getContainer()->getParameter('liip_functional_test.authentication');
}
$params = array_merge($params, array(
'PHP_AUTH_USER' => $authentication['username'],
'PHP_AUTH_PW' => $authentication['password'],
));
}
$client = static::createClient(array('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);
// BC: security.token_storage is available on Symfony 2.6+
// see http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
if ($client->getContainer()->has('security.token_storage')) {
$tokenStorage = $client->getContainer()->get('security.token_storage');
} else {
// This block will never be reached with Symfony 2.5+
// @codeCoverageIgnoreStart
$tokenStorage = $client->getContainer()->get('security.context');
// @codeCoverageIgnoreEnd
}
$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, $firewallName)
{
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 bool $absolute
*
* @return string
*/
protected function getUrl($route, $params = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
{
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')
{
try {
$crawler = new Crawler();
$crawler->addContent($response->getContent(), $type);
if (!count($crawler->filter('title'))) {
$title = '['.$response->getStatusCode().'] - '.$response->getContent();
} else {
$title = $crawler->filter('title')->text();
}
} catch (\Exception $e) {
$title = $e->getMessage();
}
if ($success) {
$this->assertTrue($response->isSuccessful(), 'The Response was not successful: '.$title);
} else {
$this->assertFalse($response->isSuccessful(), 'The Response was successful: '.$title);
}
}
/**
* 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($path, $method = 'GET', $authentication = false, $success = true)
{
$client = $this->makeClient($authentication);
$client->request($method, $path);
$content = $client->getResponse()->getContent();
if (is_bool($success)) {
$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($path, $method = 'GET', $authentication = false, $success = true)
{
$client = $this->makeClient($authentication);
$crawler = $client->request($method, $path);
$this->isSuccessful($client->getResponse(), $success);
return $crawler;
}
/**
* @param UserInterface $user
*
* @return WebTestCase
*/
public function loginAs(UserInterface $user, $firewallName)
{
$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 $expectedStatusCode
* @param Client $client
*/
public function assertStatusCode($expectedStatusCode, Client $client)
{
$helpfulErrorMessage = null;
if ($expectedStatusCode !== $client->getResponse()->getStatusCode()) {
// Get a more useful error message, if available
if ($exception = $client->getContainer()->get('liip_functional_test.exception_listener')->getLastException()) {
$helpfulErrorMessage = $exception->getMessage();
} elseif (count($validationErrors = $client->getContainer()->get('liip_functional_test.validator')->getLastErrors())) {
$helpfulErrorMessage = "Unexpected validation errors:\n";
foreach ($validationErrors as $error) {
$helpfulErrorMessage .= sprintf("+ %s: %s\n", $error->getPropertyPath(), $error->getMessage());
}
} else {
$helpfulErrorMessage = substr($client->getResponse(), 0, 200);
}
}
self::assertEquals($expectedStatusCode, $client->getResponse()->getStatusCode(), $helpfulErrorMessage);
}
/**
* 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 function assertValidationErrors(array $expected, ContainerInterface $container)
{
self::assertThat(
$container->get('liip_functional_test.validator')->getLastErrors(),
new ValidationErrorsConstraint($expected),
'Validation errors should match.'
);
}
}