Skip to content

Instantly share code, notes, and snippets.

@DanieleGBX
Created December 13, 2018 19:47
Show Gist options
  • Save DanieleGBX/b470c881e8e1453514a7b8d96b8321b6 to your computer and use it in GitHub Desktop.
Save DanieleGBX/b470c881e8e1453514a7b8d96b8321b6 to your computer and use it in GitHub Desktop.
SupportControllerTest.php
<?php
namespace Tests\AppBundle\Controller\Resource;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class SupportControllerTest extends WebTestCase
{
/**
* @dataProvider getUrlsForRegularUsers
*/
public function testAccessDeniedForGuestUsers(string $httpMethod, string $url): void
{
// $client = static::createClient([], [
// 'PHP_AUTH_USER' => 'preview_user',
// 'PHP_AUTH_PW' => 'preview_user_pa$$word',
// ]);
$client = static::createClient();
$this->logIn($client, 'preview_user', [
'ROLE_USER',
'ROLE_PREVIEW',
]);
$client->request($httpMethod, $url);
$token = $client->getContainer()->get('security.token_storage')->getToken();
dump($token);
dump($user);
dump((string) $client->getResponse()->getStatusCode());
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
}
public function getUrlsForRegularUsers(): ?\Generator
{
yield ['GET', '/support/get-started'];
}
private function logIn(Client $client, string $userName, array $roles = []): void
{
$session = $client->getContainer()->get('session');
$firewallName = 'main';
$firewallContext = 'main';
// you may need to use a different token class depending on your application.
// for example, when using Guard authentication you must instantiate PostAuthenticationGuardToken
$token = new UsernamePasswordToken($userName, null, $firewallName, $roles);
$session->set('_security_'.$firewallContext, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment