Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get('security.context')->isGranted in functional test

I want do one functional test over on service Symfony2. The idea is call before to the controller and after that, load the service with the function. The function is this one:

function save($title,$description,$setId,$html,$validate,$articles){
    $articles = explode(',', $articles);

    if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
        throw new \Exception("Not allowed");
    }else{
        $profileId  = $this->container->get('security.context')->getToken()->getUser()->getId();
        $userName   = $this->container->get('security.context')->getToken()->getUser()->getUserName();
    }
}

and now my test code is :

    $client = static::createClient();

    $crawler = $client->request('GET','/sets/save',
            array(
                    "title"=>"rtyui",
                    "description"=>"aksdjhashdkjahskjdh",
                    "set_id"=>"",
                    "html"=>"",
                    "validate"=>1,
                    "articels"=>"3,4"
                )
        ); 

but doesn't work already that I have this lines:

if (false === $this->container->get('security.context')->isGranted('ROLE_USER')) {
        throw new \Exception("Not allowed");

Now, the question is, how i can do the validation process? I've tried to do this validation process as show the documentation:

$client = static::createClient(array(), array(
    'PHP_AUTH_USER' => 'username',
    'PHP_AUTH_PW'   => 'pa$$word',
));

but I got the same error.

like image 346
Rubén Fanjul Estrada Avatar asked Aug 19 '26 19:08

Rubén Fanjul Estrada


1 Answers

Also you can login user by Security Token:

$client = static::createClient();
$container = $client->getContainer();
$container->get('security.context')->setToken(
    new UsernamePasswordToken(
        $user, null, 'main', $user->getRoles()
    )
);

Where:

  1. $user - instance of User entity with role ROLE_USER,
  2. main - your security provider name
like image 121
Tereza Tomcova Avatar answered Aug 22 '26 16:08

Tereza Tomcova



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!