Completed
Pull Request — master (#545)
by Rhodri
06:20
created

WebTestCase::setInputs()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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 13
    protected function runCommand(string $name, array $params = [], bool $reuseKernel = false): CommandTester
86
    {
87 13
        if (!$reuseKernel) {
88 13
            if (null !== static::$kernel) {
89 11
                static::$kernel->shutdown();
90
            }
91
92 13
            $kernel = static::$kernel = static::createKernel(['environment' => $this->environment]);
93 13
            $kernel->boot();
94
        } else {
95 2
            $kernel = $this->getContainer()->get('kernel');
96
        }
97
98 13
        $application = new Application($kernel);
99
100
        $options = [
101 13
            'interactive' => false,
102 13
            'decorated' => $this->getDecorated(),
103 13
            'verbosity' => $this->getVerbosityLevel(),
104
        ];
105
106 12
        $command = $application->find($name);
107 12
        $commandTester = new CommandTester($command);
108
109 12
        if (null !== $inputs = $this->getInputs()) {
110 1
            $commandTester->setInputs($inputs);
111 1
            $options['interactive'] = true;
112 1
            $this->inputs = null;
113
        }
114
115 12
        $commandTester->execute(
116 12
            array_merge(['command' => $command->getName()], $params),
117 12
            $options
118
        );
119
120 12
        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 13
    protected function getVerbosityLevel(): int
133
    {
134
        // If `null`, is not yet set
135 13
        if (null === $this->verbosityLevel) {
136
            // Set the global verbosity level that is set as NORMAL by the TreeBuilder in Configuration
137 7
            $level = strtoupper($this->getContainer()->getParameter('liip_functional_test.command_verbosity'));
138 7
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
139
140 7
            $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 13
        if (is_string($this->verbosityLevel)) {
145 6
            $level = strtoupper($this->verbosityLevel);
146 6
            $verbosity = '\Symfony\Component\Console\Output\StreamOutput::VERBOSITY_'.$level;
147
148 6
            if (!defined($verbosity)) {
149 1
                throw new \OutOfBoundsException(
150 1
                    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 12
        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 12
    protected function getInputs(): ?array
171
    {
172 12
        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 13
    protected function getDecorated(): bool
193
    {
194 13
        if (null === $this->decorated) {
195
            // Set the global decoration flag that is set to `true` by the TreeBuilder in Configuration
196 7
            $this->decorated = $this->getContainer()->getParameter('liip_functional_test.command_decoration');
197
        }
198
199
        // Check the local decorated flag
200 13
        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 13
        return $this->decorated;
207
    }
208
209 6
    public function isDecorated(bool $decorated): void
210
    {
211 6
        $this->decorated = $decorated;
212 6
    }
213
214
    /**
215
     * Get an instance of the dependency injection container.
216
     * (this creates a kernel *without* parameters).
217
     *
218
     * @return ContainerInterface
219
     */
220 14
    protected function getContainer(): ContainerInterface
221
    {
222 14
        $cacheKey = $this->environment;
223 14
        if (empty($this->containers[$cacheKey])) {
224
            $options = [
225 14
                'environment' => $this->environment,
226
            ];
227 14
            $kernel = $this->createKernel($options);
228 14
            $kernel->boot();
229
230 14
            $container = $kernel->getContainer();
231 14
            if ($container->has('test.service_container')) {
232
                $this->containers[$cacheKey] = $container->get('test.service_container');
233
            } else {
234 14
                $this->containers[$cacheKey] = $container;
235
            }
236
        }
237
238 14
        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 36
    protected function makeClient(array $params = []): Client
253
    {
254 36
        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 1
    protected function makeAuthenticatedClient(array $params = []): Client
269
    {
270 1
        $username = $this->getContainer()
271 1
            ->getParameter('liip_functional_test.authentication.username');
272 1
        $password = $this->getContainer()
273 1
            ->getParameter('liip_functional_test.authentication.password');
274
275 1
        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 1
    protected function makeClientWithCredentials(string $username, string $password, array $params = []): Client
293
    {
294 1
        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 2
    protected function createUserToken(UserInterface $user, string $firewallName): TokenInterface
311
    {
312 2
        return new UsernamePasswordToken(
313 2
            $user,
314 2
            null,
315 2
            $firewallName,
316 2
            $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 1
    protected function getUrl(string $route, array $params = [], int $absolute = UrlGeneratorInterface::ABSOLUTE_PATH): string
330
    {
331 1
        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 6
    public function isSuccessful(Response $response, $success = true, $type = 'text/html'): void
342
    {
343 6
        HttpAssertions::isSuccessful($response, $success, $type);
344 5
    }
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 1
    public function fetchContent(string $path, string $method = 'GET', bool $authentication = false, bool $success = true): string
359
    {
360 1
        $client = ($authentication) ? $this->makeAuthenticatedClient() : $this->makeClient();
361
362 1
        $client->request($method, $path);
363
364 1
        $content = $client->getResponse()->getContent();
365 1
        $this->isSuccessful($client->getResponse(), $success);
366
367 1
        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 1
    public function fetchCrawler(string $path, string $method = 'GET', bool $authentication = false, bool $success = true): Crawler
383
    {
384 1
        $client = ($authentication) ? $this->makeAuthenticatedClient() : $this->makeClient();
385
386 1
        $crawler = $client->request($method, $path);
387
388 1
        $this->isSuccessful($client->getResponse(), $success);
389
390 1
        return $crawler;
391
    }
392
393
    /**
394
     * @param UserInterface $user
395
     * @param string        $firewallName
396
     *
397
     * @return WebTestCase
398
     */
399 2
    public function loginAs(UserInterface $user, string $firewallName): self
400
    {
401 2
        $this->firewallLogins[$firewallName] = $user;
402
403 2
        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 12
    public static function assertStatusCode(int $expectedStatusCode, Client $client): void
415
    {
416 12
        HttpAssertions::assertStatusCode($expectedStatusCode, $client);
417 9
    }
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 4
    public static function assertValidationErrors(array $expected, ContainerInterface $container): void
427
    {
428 4
        HttpAssertions::assertValidationErrors($expected, $container);
429 2
    }
430
431 51
    protected function tearDown(): void
432
    {
433 51
        if (null !== $this->containers) {
434 14
            foreach ($this->containers as $container) {
435 14
                if ($container instanceof ResettableContainerInterface) {
436 14
                    $container->reset();
437
                }
438
            }
439
        }
440
441 51
        $this->containers = null;
442
443 51
        parent::tearDown();
444 51
    }
445
446 38
    protected function createClientWithParams(array $params, ?string $username = null, ?string $password = null): Client
447
    {
448 38
        if ($username && $password) {
449 2
            $params = array_merge($params, [
450 2
                'PHP_AUTH_USER' => $username,
451 2
                'PHP_AUTH_PW' => $password,
452
            ]);
453
        }
454
455 38
        $client = static::createClient(['environment' => $this->environment], $params);
456
457 38
        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 2
            $options = $client->getContainer()->getParameter('session.storage.options');
460
461 2
            if (!$options || !isset($options['name'])) {
462
                throw new \InvalidArgumentException('Missing session.storage.options#name');
463
            }
464
465 2
            $session = $client->getContainer()->get('session');
466 2
            $session->setId(uniqid());
467
468 2
            $client->getCookieJar()->set(new Cookie($options['name'], $session->getId()));
469
470
            /** @var $user UserInterface */
471 2
            foreach ($this->firewallLogins as $firewallName => $user) {
472 2
                $token = $this->createUserToken($user, $firewallName);
473
474 2
                $tokenStorage = $client->getContainer()->get('security.token_storage');
475
476 2
                $tokenStorage->setToken($token);
477 2
                $session->set('_security_'.$firewallName, serialize($token));
478
            }
479
480 2
            $session->save();
481
        }
482
483 38
        return $client;
484
    }
485
}
486