I
I
Ivan Bogomolov2014-05-12 13:22:23
symfony
Ivan Bogomolov, 2014-05-12 13:22:23

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");
        }
}

I will be glad to answer those who have implemented such tests without HTTP_BASIC authorization.
Please advise, maybe I'm sending the wrong headers.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
shagguboy, 2014-05-12
@shagguboy

How to simulate HTTP Authentication in a Functiona...
How to simulate Authentication with a Token in a F...

P
Pavel Solovyov, 2014-05-13
@pavel_salauyou

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.

W
war-tushkan, 2014-06-03
@war-tushkan

you can try behat

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question