Test Failed
Push — master ( d3f723...421eba )
by Alexis
02:13 queued 14s
created

WebTestCase::getDecorated()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.7085

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 4
cts 7
cp 0.5714
rs 9.7333
c 0
b 0
f 0
cc 3
nc 4
nop 0
crap 3.7085
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Liip/FunctionalTestBundle
7
 *
8
 * (c) Lukas Kahwe Smith <[email protected]>
9
 *
10
 * This source file is subject to the MIT license that is bundled
11
 * with this source code in the file LICENSE.
12
 */
13
14
namespace Liip\FunctionalTestBundle\Test;
15
16
use Liip\FunctionalTestBundle\Utils\HttpAssertions;
17
use PHPUnit\Framework\MockObject\MockBuilder;
18
use Symfony\Bundle\FrameworkBundle\Client;
19
use Symfony\Bundle\FrameworkBundle\Console\Application;
20
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
21
use Symfony\Component\BrowserKit\Cookie;
22
use Symfony\Component\Console\Tester\CommandTester;
23
use Symfony\Component\DependencyInjection\ContainerInterface;
24
use Symfony\Component\DependencyInjection\ResettableContainerInterface;
25
use Symfony\Component\DomCrawler\Crawler;
26
use Symfony\Component\HttpFoundation\Response;
27
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
28
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
29
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
30
use Symfony\Component\Security\Core\User\UserInterface;
31
32
/**
33
 * @author Lea Haensenberger
34
 * @author Lukas Kahwe Smith <[email protected]>
35
 * @author Benjamin Eberlei <[email protected]>
36
 */
37
abstract class WebTestCase extends BaseWebTestCase
38
{
39
    protected $environment = 'test';
40
41
    protected $containers;
42
43
    // 5 * 1024 * 1024 KB
44
    protected $maxMemory = 5242880;
45
46
    // RUN COMMAND
47
    protected $verbosityLevel;
48
49
    protected $decorated;
50
51
    /**
52
     * @var array|null
53
     */
54
    private $inputs = null;
55
56
    /**
57
     * @var array
58
     */
59
    private $firewallLogins = [];
60
61
    /**
62
     * Creates a mock object of a service identified by its id.
63
     *
64
     * @param string $id
65
     *
66
     * @return MockBuilder
67
     */
68
    protected function getServiceMockBuilder(string $id): MockBuilder
69
    {
70
        $service = $this->getContainer()->get($id);
71
        $class = get_class($service);
72
73
        return $this->getMockBuilder($class)->disableOriginalConstructor();
74
    }
75
76
    /**
77
     * Builds up the environment to run the given command.
78
     *
79
     * @param string $name
80
     * @param array  $params
81
     * @param bool   $reuseKernel
82
     *
83
     * @return CommandTester
84
     */
85 7
    protected function runCommand(string $name, array $params = [], bool $reuseKernel = false): CommandTester
86
    {
87 7
        if (!$reuseKernel) {
88 7
            if (null !== static::$kernel) {
89
                static::$kernel->shutdown();
90
            }
91
92 7
            $kernel = static::$kernel = static::createKernel(['environment' => $this->environment]);
93 7
            $kernel->boot();
94
        } else {
95
            $kernel = $this->getContainer()->get('kernel');
96
        }
97
98
        $application = new Application($kernel);
0 ignored issues
show
Documentation introduced by
$kernel is of type object|null, but the function expects a object<Symfony\Component...Kernel\KernelInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
99
100
        $options = [
101
            'interactive' => false,
102
            'decorated' => $this->getDecorated(),
103
            'verbosity' => $this->getVerbosityLevel(),
104
        ];
105
106
        $command = $application->find($name);
107
        $commandTester = new CommandTester($command);
108
109
        if (null !== $inputs = $this->getInputs()) {
110
            $commandTester->setInputs($inputs);
111
            $options['interactive'] = true;
112
            $this->inputs = null;
113
        }
114
115
        $commandTester->execute(
116
            array_merge(['command' => $command->getName()], $params),
117
            $options
118
        );
119
120
        return $commandTester;
121
    }
122
123
    /**
124
     * Retrieves the output verbosity level.
125
     *
126
     * @see \Symfony\Component\Console\Output\OutputInterface for available levels
127
     *
128
     * @throws \OutOfBoundsException If the set value isn't accepted
129
     *
130
     * @return int
131
     */
132 5
    protected function getVerbosityLevel(): int
133
    {
134
        // If `null`, is not yet set
135 5
        if (null === $this->verbosityLevel) {
136
            // Set the global verbosity level that is set as NORMAL by the TreeBuilder in Configuration
137
            $level = strtoupper($this->getContainer()->getParameter('liip_functional_test.command_verbosity'));
138
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
139
140
            $this->verbosityLevel = constant($verbosity);
141
        }
142
143
        // If string, it is set by the developer, so check that the value is an accepted one
144 5
        if (is_string($this->verbosityLevel)) {
145 5
            $level = strtoupper($this->verbosityLevel);
146 5
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
147
148 5
            if (!defined($verbosity)) {
149
                throw new \OutOfBoundsException(
150
                    sprintf('The set value "%s" for verbosityLevel is not valid. Accepted are: "quiet", "normal", "verbose", "very_verbose" and "debug".', $level)
151
                );
152
            }
153
154 5
            $this->verbosityLevel = constant($verbosity);
155
        }
156
157 5
        return $this->verbosityLevel;
158
    }
159
160 6
    public function setVerbosityLevel($level): void
161
    {
162 6
        $this->verbosityLevel = $level;
163 6
    }
164
165 1
    protected function setInputs(array $inputs): void
166
    {
167 1
        $this->inputs = $inputs;
168 1
    }
169
170 1
    protected function getInputs(): ?array
171
    {
172 1
        return $this->inputs;
173
    }
174
175
    /**
176
     * Set verbosity for Symfony 3.4+.
177
     *
178
     * @see https://github.com/symfony/symfony/pull/24425
179
     *
180
     * @param $level
181
     */
182
    private function setVerbosityLevelEnv($level): void
183
    {
184
        putenv('SHELL_VERBOSITY='.$level);
185
    }
186
187
    /**
188
     * Retrieves the flag indicating if the output should be decorated or not.
189
     *
190
     * @return bool
191
     */
192 3
    protected function getDecorated(): bool
193
    {
194 3
        if (null === $this->decorated) {
195
            // Set the global decoration flag that is set to `true` by the TreeBuilder in Configuration
196
            $this->decorated = $this->getContainer()->getParameter('liip_functional_test.command_decoration');
197
        }
198
199
        // Check the local decorated flag
200 3
        if (false === is_bool($this->decorated)) {
201
            throw new \OutOfBoundsException(
202
                sprintf('`WebTestCase::decorated` has to be `bool`. "%s" given.', gettype($this->decorated))
203
            );
204
        }
205
206 3
        return $this->decorated;
207
    }
208
209 4
    public function isDecorated(bool $decorated): void
210
    {
211 4
        $this->decorated = $decorated;
212 4
    }
213
214
    /**
215
     * Get an instance of the dependency injection container.
216
     * (this creates a kernel *without* parameters).
217
     *
218
     * @return ContainerInterface
219
     */
220
    protected function getContainer(): ContainerInterface
221
    {
222
        $cacheKey = $this->environment;
223
        if (empty($this->containers[$cacheKey])) {
224
            $options = [
225
                'environment' => $this->environment,
226
            ];
227
            $kernel = $this->createKernel($options);
228
            $kernel->boot();
229
230
            $container = $kernel->getContainer();
231
            if ($container->has('test.service_container')) {
232
                $this->containers[$cacheKey] = $container->get('test.service_container');
233
            } else {
234
                $this->containers[$cacheKey] = $container;
235
            }
236
        }
237
238
        return $this->containers[$cacheKey];
239
    }
240
241
    /**
242
     * Creates an instance of a lightweight Http client.
243
     *
244
     * $params can be used to pass headers to the client, note that they have
245
     * to follow the naming format used in $_SERVER.
246
     * Example: 'HTTP_X_REQUESTED_WITH' instead of 'X-Requested-With'
247
     *
248
     * @param array $params
249
     *
250
     * @return Client
251
     */
252
    protected function makeClient(array $params = []): Client
253
    {
254
        return $this->createClientWithParams($params);
255
    }
256
257
    /**
258
     * Creates an instance of a lightweight Http client.
259
     *
260
     * $params can be used to pass headers to the client, note that they have
261
     * to follow the naming format used in $_SERVER.
262
     * Example: 'HTTP_X_REQUESTED_WITH' instead of 'X-Requested-With'
263
     *
264
     * @param array $params
265
     *
266
     * @return Client
267
     */
268
    protected function makeAuthenticatedClient(array $params = []): Client
269
    {
270
        $username = $this->getContainer()
271
            ->getParameter('liip_functional_test.authentication.username');
272
        $password = $this->getContainer()
273
            ->getParameter('liip_functional_test.authentication.password');
274
275
        return $this->createClientWithParams($params, $username, $password);
276
    }
277
278
    /**
279
     * Creates an instance of a lightweight Http client and log in user with
280
     * username and password params.
281
     *
282
     * $params can be used to pass headers to the client, note that they have
283
     * to follow the naming format used in $_SERVER.
284
     * Example: 'HTTP_X_REQUESTED_WITH' instead of 'X-Requested-With'
285
     *
286
     * @param string $username
287
     * @param string $password
288
     * @param array  $params
289
     *
290
     * @return Client
291
     */
292
    protected function makeClientWithCredentials(string $username, string $password, array $params = []): Client
293
    {
294
        return $this->createClientWithParams($params, $username, $password);
295
    }
296
297
    /**
298
     * Create User Token.
299
     *
300
     * Factory method for creating a User Token object for the firewall based on
301
     * the user object provided. By default it will be a Username/Password
302
     * Token based on the user's credentials, but may be overridden for custom
303
     * tokens in your applications.
304
     *
305
     * @param UserInterface $user         The user object to base the token off of
306
     * @param string        $firewallName name of the firewall provider to use
307
     *
308
     * @return TokenInterface The token to be used in the security context
309
     */
310
    protected function createUserToken(UserInterface $user, string $firewallName): TokenInterface
311
    {
312
        return new UsernamePasswordToken(
313
            $user,
314
            null,
315
            $firewallName,
316
            $user->getRoles()
0 ignored issues
show
Documentation introduced by
$user->getRoles() is of type array<integer,object<Sym...Core\Role\Role>|string>, but the function expects a array<integer,string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
317
        );
318
    }
319
320
    /**
321
     * Extracts the location from the given route.
322
     *
323
     * @param string $route    The name of the route
324
     * @param array  $params   Set of parameters
325
     * @param int    $absolute
326
     *
327
     * @return string
328
     */
329
    protected function getUrl(string $route, array $params = [], int $absolute = UrlGeneratorInterface::ABSOLUTE_PATH): string
330
    {
331
        return $this->getContainer()->get('router')->generate($route, $params, $absolute);
332
    }
333
334
    /**
335
     * Checks the success state of a response.
336
     *
337
     * @param Response $response Response object
338
     * @param bool     $success  to define whether the response is expected to be successful
339
     * @param string   $type
340
     */
341
    public function isSuccessful(Response $response, $success = true, $type = 'text/html'): void
342
    {
343
        HttpAssertions::isSuccessful($response, $success, $type);
344
    }
345
346
    /**
347
     * Executes a request on the given url and returns the response contents.
348
     *
349
     * This method also asserts the request was successful.
350
     *
351
     * @param string $path           path of the requested page
352
     * @param string $method         The HTTP method to use, defaults to GET
353
     * @param bool   $authentication Whether to use authentication, defaults to false
354
     * @param bool   $success        to define whether the response is expected to be successful
355
     *
356
     * @return string
357
     */
358
    public function fetchContent(string $path, string $method = 'GET', bool $authentication = false, bool $success = true): string
359
    {
360
        $client = ($authentication) ? $this->makeAuthenticatedClient() : $this->makeClient();
361
362
        $client->request($method, $path);
363
364
        $content = $client->getResponse()->getContent();
365
        $this->isSuccessful($client->getResponse(), $success);
366
367
        return $content;
368
    }
369
370
    /**
371
     * Executes a request on the given url and returns a Crawler object.
372
     *
373
     * This method also asserts the request was successful.
374
     *
375
     * @param string $path           path of the requested page
376
     * @param string $method         The HTTP method to use, defaults to GET
377
     * @param bool   $authentication Whether to use authentication, defaults to false
378
     * @param bool   $success        Whether the response is expected to be successful
379
     *
380
     * @return Crawler
381
     */
382
    public function fetchCrawler(string $path, string $method = 'GET', bool $authentication = false, bool $success = true): Crawler
383
    {
384
        $client = ($authentication) ? $this->makeAuthenticatedClient() : $this->makeClient();
385
386
        $crawler = $client->request($method, $path);
387
388
        $this->isSuccessful($client->getResponse(), $success);
389
390
        return $crawler;
391
    }
392
393
    /**
394
     * @param UserInterface $user
395
     * @param string        $firewallName
396
     *
397
     * @return WebTestCase
398
     */
399
    public function loginAs(UserInterface $user, string $firewallName): self
400
    {
401
        $this->firewallLogins[$firewallName] = $user;
402
403
        return $this;
404
    }
405
406
    /**
407
     * Asserts that the HTTP response code of the last request performed by
408
     * $client matches the expected code. If not, raises an error with more
409
     * information.
410
     *
411
     * @param int    $expectedStatusCode
412
     * @param Client $client
413
     */
414
    public static function assertStatusCode(int $expectedStatusCode, Client $client): void
415
    {
416
        HttpAssertions::assertStatusCode($expectedStatusCode, $client);
417
    }
418
419
    /**
420
     * Assert that the last validation errors within $container match the
421
     * expected keys.
422
     *
423
     * @param array              $expected  A flat array of field names
424
     * @param ContainerInterface $container
425
     */
426
    public static function assertValidationErrors(array $expected, ContainerInterface $container): void
427
    {
428
        HttpAssertions::assertValidationErrors($expected, $container);
429
    }
430
431 7
    protected function tearDown(): void
432
    {
433 7
        if (null !== $this->containers) {
434
            foreach ($this->containers as $container) {
435
                if ($container instanceof ResettableContainerInterface) {
436
                    $container->reset();
437
                }
438
            }
439
        }
440
441 7
        $this->containers = null;
442
443 7
        parent::tearDown();
444 7
    }
445
446
    protected function createClientWithParams(array $params, ?string $username = null, ?string $password = null): Client
447
    {
448
        if ($username && $password) {
449
            $params = array_merge($params, [
450
                'PHP_AUTH_USER' => $username,
451
                'PHP_AUTH_PW' => $password,
452
            ]);
453
        }
454
455
        $client = static::createClient(['environment' => $this->environment], $params);
456
457
        if ($this->firewallLogins) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->firewallLogins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
458
            // has to be set otherwise "hasPreviousSession" in Request returns false.
459
            $options = $client->getContainer()->getParameter('session.storage.options');
460
461
            if (!$options || !isset($options['name'])) {
462
                throw new \InvalidArgumentException('Missing session.storage.options#name');
463
            }
464
465
            $session = $client->getContainer()->get('session');
466
            $session->setId(uniqid());
467
468
            $client->getCookieJar()->set(new Cookie($options['name'], $session->getId()));
469
470
            /** @var $user UserInterface */
471
            foreach ($this->firewallLogins as $firewallName => $user) {
472
                $token = $this->createUserToken($user, $firewallName);
473
474
                $tokenStorage = $client->getContainer()->get('security.token_storage');
475
476
                $tokenStorage->setToken($token);
477
                $session->set('_security_'.$firewallName, serialize($token));
478
            }
479
480
            $session->save();
481
        }
482
483
        return $client;
484
    }
485
}
486