Symfony2在功能测试中登录FOS UserBundle

时间:2012-02-07 19:49:33

标签: unit-testing symfony phpunit fosuserbundle

如何登录内部测试以便能够执行特定于用户的操作?

5 个答案:

答案 0 :(得分:5)

实际上,身份验证必须像真实用户那样进行。在这种情况下,您必须知道普通密码并填写登录表单

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class XXX extends WebTestCase {
  public function testUserLogin() {

   $client = static::createClient();
   $crawler = $client->request('GET', '/login');

   $form = $crawler->selectButton('_submit')->form(array(
     '_username'  => 'user',
     '_password'  => 'pa$$word',
   ));

   $client->submit($form);
   $crawler = $client->followRedirect(); // "/" page

   // if credentials were correct, you should be logged in and ready to test your app
  }
}

答案 1 :(得分:4)

这个问题的现有答案很有帮助,但没有一个直接解决了我的问题。我正在使用Symfony 2.3。

这是我的解决方案:

<?php

namespace CDE\TestBundle\Base;

use FOS\UserBundle\Model\User;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class BaseUserTest extends WebTestCase {

    protected $client;
    protected $container;
    protected $storage;
    protected $session;
    protected $user;
    protected $cookieJar;
    protected $cookie;
    protected $token;

    public function __construct() {
        $this->client = static::createClient();
        $this->container = $this->client->getContainer();
        $this->storage = new MockFileSessionStorage(__dir__.'/../../../../app/cache/test/sessions');
        $this->session = new Session($this->storage);

    }

    public function getUserManager() {
        return $this->container->get('cde_user.manager.user');

    }

    public function getSecurityManager() {
        return $this->container->get('fos_user.security.login_manager');

    }

    public function getUser($role = null) {
        if (!isset($this->user)) {
            $user = $this->getUserManager()->loadByUsername('user');

            if (isset($user)) {
                $this->user = $user;
            } else {
                $this->user = $this->getUserManager()->create();

                $this->user->setEnabled(true);
                $this->user->setUsername('user');
                $this->user->setEmail('user@quiver.is');
                $this->user->setPlainPassword('user');
                $this->getUserManager()->updatePassword($this->user);
                if (isset($role)) {
                    $this->user->addRole($role);
                }
                $this->getUserManager()->add($this->user);
            }

        }

        return $this->user;
    }

    public function logIn(User $user, Response $response) {
        $this->session->start();

        $this->cookie = new Cookie('MOCKSESSID', $this->storage->getId());
        $this->cookieJar = new CookieJar();
        $this->cookieJar->set($this->cookie);
        $this->token = new UsernamePasswordToken($user, 'user', 'main', $user->getRoles());
        $this->session->set('_security_main', serialize($this->token));


        $this->getSecurityManager()->loginUser(
            $this->container->getParameter('fos_user.firewall_name'),
            $user,
            $response
        );

        $this->session->save();
    }

    public function removeUser(User $user) {

    }
}

RestControllerTest.php

<?php

namespace CDE\ContentBundle\Tests\Controller;

use CDE\TestBundle\Base\BaseUserTest;
use Symfony\Component\HttpFoundation\Response;

class RestControllerTest extends BaseUserTest
{
    protected $comment;

    public function __construct() {
        parent::__construct();
        $this->logIn($this->getUser('ROLE_ADMIN'), new Response());

    }

    public function getGalleryManager() {
        return $this->container->get('cde_content.manager.gallery');
    }

    public function getAWSManager() {
        return $this->container->get('cde_utility.manager.aws');
    }

    public function createGallery()
    {
        //        Copy test.jpeg into the web folder
        $filename = 'gallery/user-test.jpg';
        copy(__DIR__.'/../Mock/test.jpeg', __DIR__.'/../../../../../web/'.$filename);
        $this->getAWSManager()->copyGalleryFile($filename);


        $gallery = $this->getGalleryManager()->create();
        $gallery->setUser($this->getUser());
        $gallery->setFilename($filename);
        $gallery->setTitle('test gallery');
        $gallery->setDescription('test gallery description');
        $gallery->setMarked(false);
        $this->getGalleryManager()->add($gallery);
        $this->assertEquals($gallery->getMarked(), false);
    }

    public function createComment()
    {
        $galleries = $this->getGalleryManager()->findByUser($this->getUser());
        $gallery = $galleries[0];

        $client = static::createClient();
        $client->getCookieJar()->set($this->cookie);
//        $client = static::createClient(array(), new History(), $cookieJar);

        $crawler = $client->request('POST', 'api/createComment/'.$gallery->getId(), array(
            'comment' => 'testing testing 123',
            'marked' => 'false'
        ));

        $response = $client->getResponse();
        $this->comment = json_decode($response->getContent());
        $this->assertEquals($this->comment->comment, 'testing testing 123');
        $this->assertFalse($this->comment->marked);
        $this->assertEquals($response->getStatusCode(), 200);
    }

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

        $crawler = $client->request('GET', 'api/getComment/'.$this->comment->id);

        $response = $client->getResponse();
        $comment = json_decode($response->getContent());
        $this->assertEquals($comment->comment, 'testing testing 123');
        $this->assertFalse($comment->marked);
        $this->assertEquals($response->getStatusCode(), 200);

    }

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

        $crawler = $client->request('GET', 'api/updateComment');
    }

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

        $crawler = $client->request('DELETE', 'api/deleteComment');
    }

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

        $crawler = $client->request('GET', 'api/getComments');
    }

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

        $crawler = $client->request('GET', 'api/getGalleries');
    }

    public function removeGallery() {
        $galleries = $this->getGalleryManager()->findByUser($this->getUser());
        foreach ($galleries as $gallery) {
            $this->getGalleryManager()->remove($gallery);
        }

    }

    public function testComments() {
        $this->createGallery();
        $this->createComment();
        $this->getComment();
        $this->updateComment();
        $this->deleteComment();
        $this->getComments();
        $this->getGalleries();
        $this->removeGallery();
    }

}

该代码包含一个基本测试类(BaseUserTest.php),可以扩展为轻松登录用户。

我还提供了一个如何在示例测试(RestControllerTest.php)中使用基类的示例。请注意RestControllerTest.php中的此代码块:

$client = static::createClient();
$client->getCookieJar()->set($this->cookie);

BaseUserTest背后的想法是,它可以创建自己的会话,与用户填充会话,然后使用MockFileSessionStorage将会话保存到文件系统。

测试本身必须在客户端上设置cookie。

答案 2 :(得分:2)

我知道为时已晚..但是如果有人需要这个,我设法在我的单元测试中记录用户:

1-首先定义一个可以访问服务的类:

<?php
namespace Tests;

class ContainerAwareUnitTestCase extends \PHPUnit_Framework_TestCase
{
    protected static $kernel;
    protected static $container;

    public static function setUpBeforeClass()
    {
        self::$kernel = new \AppKernel('dev', true);
        self::$kernel->boot();

        self::$container = self::$kernel->getContainer();
    }

    public function get($serviceId)
    {
        return self::$kernel->getContainer()->get($serviceId);
    }
}

2-然后宣布测试如下:

<?php

namespace Tests\Menu;

use Tests\ContainerAwareUnitTestCase;
use UserBundle\Entity\User;
use FOS\UserBundle\Security\UserProvider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use Menu\MenuBuilder;

class MenuBuilderTest extends ContainerAwareUnitTestCase
{
    public function provider()
    {
        return array(array('/'));

    }

    /**
     * @dataProvider provider
     */
    public function testNoAuth($uri) 
    {
        /* @var $securityContext SecurityContext */
        $securityContext = $this->get('security.context');
        $userProvider = $this->get('fos_user.user_provider.username');
        $user = $userProvider->loadUserByUsername('alex');
        $token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER'));
        $securityContext->setToken($token);

        /* @var $menuBuilder MenuBuilder */
        $menuBuilder = $this->get('event_flow_analyser.menu_builder');

        $this->assertNotNull($menuBuilder);

        $request = new Request();
        $request->attributes->set('projectName', 'ucs');

        $menu = $menuBuilder->createMainMenu($request);

        $this->assertNotNull($menu);

        $this->assertNotNull($menu->getChild('Home'));
        $this->assertNotNull($menu->getChild('Profile'));

        $this->assertEquals(null, $menu->getChild('Projects'));
    }

}    

这是测试menuBuilder创建的完整例子,但是虽然有点超出范围,但该提取应该可以满足您的需求:

        $securityContext = $this->get('security.context');
        $userProvider = $this->get('fos_user.user_provider.username');
        $user = $userProvider->loadUserByUsername('alex');
        $token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER'));
        $securityContext->setToken($token);

答案 3 :(得分:0)

这就是我为其中一个项目实现的方式(不是使用FOSUserBundle,但可能你会觉得它很有帮助)

private function createAuthorizedClient($role)
{
    $userProvider = new YourUserProvider(...);
    $user = $userProvider->createUserMethod(...);

    $client = $this->createClient(); //Normal WebTestCase client
    $client->getCookieJar()->set(new Cookie(session_name(), true));
    $session = self::$kernel->getContainer()->get('session');
    $token =  new UsernamePasswordToken($user, 'password', 'main', array($role));
    $client->getContainer()->get('security.context')->setToken($token);
    $session->set('_security_main', serialize($token));

    return $client;
}

不要忘记模拟用户对象的预期结果。

答案 4 :(得分:0)

由于我无法对您的解决方案发表评论,因此我必须创建一个新答案。实际上其他解决方案是正确的,因为他们使用功能测试来测试特定场景。您正在使用单元测试来测试属于功能测试的场景,这就是您必须破解用户登录的原因。请考虑其他解决方案,并通过检查DOM对象中的正确菜单项来进行功能测试。