如何在Symfony 2.3的功能测试中的会话中登录用户? [英] How to log in User in Session within a Functional Test in Symfony 2.3?

查看:109
本文介绍了如何在Symfony 2.3的功能测试中的会话中登录用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于stackoverflow的帖子.但是大多数方法在Symfony 2.3中没有用. 因此,我尝试在测试中手动登录用户以在后端执行一些操作. 这是我的security.yml

I have read many posts on stackoverflow about this. But most of the methods not useful in Symfony 2.3. So I have try to log in user manually in test to make some actions in back-end. Here is my security.yml

security:
...
  role_hierarchy:
        ROLE_SILVER: [ROLE_BRONZE]
        ROLE_GOLD: [ROLE_BRONZE, ROLE_SILVER]
        ROLE_PLATINUM: [ROLE_BRONZE, ROLE_SILVER, ROLE_GOLD]
        ROLE_ADMIN: [ROLE_BRONZE, ROLE_SILVER, ROLE_GOLD, ROLE_PLATINUM, ROLE_ALLOWED_TO_SWITCH]

    providers:
        database:
            entity: { class: Fox\PersonBundle\Entity\Person, property: username }

    firewalls:
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login:
            pattern:  ^/person/login$
            security: false

        main:
            pattern:    ^/
            provider:   database
            form_login:
                check_path: /person/login-check
                login_path: /person/login
                default_target_path: /person/view
                always_use_default_target_path: true
            logout:
                path:   /person/logout
                target: /
            anonymous: true

    access_control:
        - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/person/registration, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/person, roles: ROLE_BRONZE }

这是我的考试:

class ProfileControllerTest extends WebTestCase
{
    public function setUp()
    {
        $kernel = self::getKernelClass();

        self::$kernel = new $kernel('dev', true);
        self::$kernel->boot();
    }

    public function testView()
    {
        $client = static::createClient();

        $person = self::$kernel->getContainer()->get('doctrine')->getRepository('FoxPersonBundle:Person')->findOneByUsername('master');

        $token = new UsernamePasswordToken($person, $person->getPassword(), 'main', $person->getRoles());

        self::$kernel->getContainer()->get('security.context')->setToken($token);

        self::$kernel->getContainer()->get('event_dispatcher')->dispatch(
        AuthenticationEvents::AUTHENTICATION_SUCCESS,
        new AuthenticationEvent($token));

        $crawler = $client->request('GET', '/person/view');
    }

当我运行此测试时,$person = $this->get(security.context)->getToken()->getUser();方法在测试Controller中不起作用.说如果在控制器调用$person->getId();中,我将出现错误Call to a member function getId() on a non-object in....

And when I run this test, $person = $this->get(security.context)->getToken()->getUser(); method is not working in testing Controller. Say if in controller call $person->getId(); I will have an error Call to a member function getId() on a non-object in... .

那么您能告诉我在Symfony 2.3的功能测试中登录用户的正确方法吗?

So can you tell the properly way to log in user in functional test in Symfony 2.3?

谢谢!

EDIT_1 : 如果我更改Symfony/Component/Security/Http/Firewall/ContextListener.php并注释一个字符串:

EDIT_1: If I change Symfony/Component/Security/Http/Firewall/ContextListener.php and comment one string:

if (null === $session || null === $token = $session->get('_security_'.$this->contextKey)) {
            // $this->context->setToken(null);

            return;
        }

所有测试均正常进行.

EDIT_2 : 这是我尝试使用的参考: 第一 第三 第四 第五 第六 第七 第八 第九个

EDIT_2: This is reference that i have trying to use: first second third fourth fifth sixth seventh eighth nineth

推荐答案

最后,我解决了!这是工作代码的示例:

Finaly i solve it! This is example of working code:

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\BrowserKit\Cookie;

class ProfileControllerTest extends WebTestCase
{
    protected function createAuthorizedClient()
    {
        $client = static::createClient();
        $container = static::$kernel->getContainer();
        $session = $container->get('session');
        $person = self::$kernel->getContainer()->get('doctrine')->getRepository('FoxPersonBundle:Person')->findOneByUsername('master');

        $token = new UsernamePasswordToken($person, null, 'main', $person->getRoles());
        $session->set('_security_main', serialize($token));
        $session->save();

        $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));

        return $client;
    }

    public function testView()
    {
        $client = $this->createAuthorizedClient();
        $crawler = $client->request('GET', '/person/view');
        $this->assertEquals(
            200,
            $client->getResponse()->getStatusCode()
        );
    }   

希望它可以帮助您节省时间和精力;)

Hope it helps to save your time and nerves ;)

这篇关于如何在Symfony 2.3的功能测试中的会话中登录用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆