Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
To use with Panther (https://github.com/symfony/panther)

A few test cases traits for PHPUnit that helps log users in your functional tests in Symfony

<?php
declare(strict_types=1);
namespace Tests;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase as BaseWebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Repository\UserRepository;
trait GetHttpClientTestTrait
{
protected function loginAsUser(KernelBrowser $client, string $username = 'lambda-user'): void
{
if (!$this instanceof BaseWebTestCase) {
throw new \RuntimeException(\sprintf('Test case must extend %s to use Kernel features', BaseWebTestCase::class));
}
/** @var UserRepository $repo */
$repo = static::$container->get(UserRepository::class);
$user = $repo->findByUsernameOrEmail($username);
if (!$user) {
static::fail(\sprintf('Cannot find user "%s" to log in.', $username));
}
static::setToken($client, $user);
}
/**
* @param string|UserInterface $username
*/
protected static function setToken(KernelBrowser $client, $username = 'user', array $roles = ['ROLE_USER']): void
{
$firewallName = 'main';
$session = $client->getContainer()->get('session');
$token = new UsernamePasswordToken($username, null, $firewallName, $roles);
$session->set('_security_'.$firewallName, \serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
}
}
<?php
declare(strict_types=1);
namespace Tests;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use PHPUnit\Framework\Assert;
use Symfony\Component\Panther\Client;
trait PantherLoginTrait
{
protected function loginAs(Client $client, string $username, string $plainPassword): void
{
$crawler = $client->request('GET', '/login');
Assert::assertSame(200, $client->getInternalResponse()->getStatusCode());
$htmlFormSelector = '#form_login';
$driver = $client->getWebDriver();
$driver->wait(2, 500)->until(WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::cssSelector($htmlFormSelector)));
$form = $crawler->filter($htmlFormSelector)->form();
$client->submit($form, [
'_username' => $username,
'_password' => $plainPassword,
]);
$crawler = $client->request('GET', '/profile');
Assert::assertSame('Update my profile', $crawler->filter('h1')->text());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.