Answer the question
In order to leave comments, you need to log in
How to test actions that require authorization in symfony 2.4?
Can't write a test to test a page that is only allowed to access by a specific group of users (ROLE_USER). At the same time, the SecurityContext->isGranted('ROLE_USER') check passes. And when I knock on the page, there is a redirect to /login . What's wrong?
Sample test file code:
//...src/...Tests/SomeTest.php
private function login()
{
$session = $this->container->get('session');
$user = $this->doctrine->getManager()
->getRepository('ApplicationSonataUserBundle:User')
->findOneBy(
array(
'username' => self::LOGIN
)
);
$userManager = $this->container->get('fos_user.user_manager');
$sfUser = $userManager->findUserByUsername(self::LOGIN);
$token = new UsernamePasswordToken($sfUser, $user->getPassword(),'main', $user->getRoles() );
$session->set('_security_'.self::FIREWALL, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
$this->container->get('security.context')->setToken($token);
return $session->getId();
}
public function testPriceListPageActive()
{
$PHPSESSID = $this->login();
$securityContext = $this->container->get('security.context');
//вот здесь проверка проходит - все ок
if( $securityContext->isGranted('ROLE_USER') ){
//а request не проходит, делает редирект на /login
$crawler = $this->client->request( 'GET', '/pricelist/page' ,[],[],['Cookie' => 'PHPSESSID='.$PHPSESSID] );
}
else {
throw new \Exception("Error Access Denied");
}
}
Answer the question
In order to leave comments, you need to log in
How to simulate HTTP Authentication in a Functiona...
How to simulate Authentication with a Token in a F...
There was the same problem, as for me it is better to use codeception and phantomjs and write an acceptance test. Do authorization as a normal user does on the site.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question