Symfony 2功能测试:验证自己User类的用户

时间:2013-05-14 08:17:46

标签: php security testing symfony phpunit

How to use an authenticated user in a Symfony2 functional test?的回答所述,Symfony\Component\Security\Core\User\User有一个简单的解决方案。

但是我有不同的User类(一些必要的附加字段),我想用它来验证用户。

如何为它设置提供者?

4 个答案:

答案 0 :(得分:11)

这是一个棘手的问题:https://github.com/symfony/symfony/issues/5228 虽然它是2.1,但我仍然使用2.2。

以下是我如何进行测试验证:

// Create a new client to browse the application
$client = static::createClient();
$client->getCookieJar()->set(new Cookie(session_name(), true));

// dummy call to bypass the hasPreviousSession check
$crawler = $client->request('GET', '/');

$em = $client->getContainer()->get('doctrine')->getEntityManager();
$user = $em->getRepository('MyOwnBundle:User')->findOneByUsername('username');

$token = new UsernamePasswordToken($user, $user->getPassword(), 'main_firewall', $user->getRoles());
self::$kernel->getContainer()->get('security.context')->setToken($token);

$session = $client->getContainer()->get('session');
$session->set('_security_' . 'main_firewall', serialize($token));
$session->save();

$crawler = $client->request('GET', '/login/required/page/');

$this->assertTrue(200 === $client->getResponse()->getStatusCode());

// perform tests in the /login/required/page here..

哦,使用声明:

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

答案 1 :(得分:1)

你正在使用表格登录吗?还是http安全?

使用表单登录时我在测试中所做的就是模拟用户通过登录表单登录...

    /**
     * test of superuser ingelogd geraakt
     */
    public function testSuperAdminLogin()
    {
        $crawler = $this->client->request('GET', '/login');
        $form = $crawler->selectButton('Sign In')->form();
        $user = $this->em->getRepository('NonoAcademyBundle:User')
            ->findOneByUsername('superadmin');
        $crawler = $this->client
            ->submit($form,
                array('_username' => $user->getUsername(),
                        '_password' => $user->getPassword()));

        $this->assertTrue($this->client->getResponse()->isSuccessful());

        $this
            ->assertRegExp('/\/admin\/notifications/',
                $this->client->getResponse()->getContent());
    }

然后只使用该客户端和抓取工具,因为他们将充当登录用户。 希望这可以帮助你

答案 2 :(得分:1)

如果您使用表单登录

,也可能会发现这些有用
private function doLogin()
{
    $this->client = static::createClient();
    $username = 'your-username';
    $password = 'your-password';

    $crawler = $this->client->request('GET', '/login');
    $form = $crawler->filter('your-submit-button-classname')->form();

    $crawler = $this->client
        ->submit($form,
            array(
                '_username' => $username,
                '_password' => $password,
            )
       );
}

答案 3 :(得分:0)

我找到了解决方案。

首先,我们必须按照here所述创建新的用户提供商:FakeUserProvider 它应该实现UserProviderInterface

它的loadUserByUsername应该创建必要的用户对象。