9

ユーザー固有のアクションを実行できるようにテスト内にログインする方法は?

4

5 に答える 5

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
  }
}
于 2012-08-24T17:39:51.707 に答える
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 を設定する必要があります。

于 2013-08-30T16:31:03.377 に答える
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);
于 2012-12-09T02:19:46.030 に答える
0

それが私がプロジェクトの1つにそれを実装した方法です(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;
}

ユーザーオブジェクトの期待される結果をモックすることを忘れないでください。

于 2012-07-29T08:03:08.027 に答える
0

あなたのソリューションについてコメントできないので、新しい回答を作成する必要があります。実際には、機能テストを使用して特定のシナリオをテストするという点で、他のソリューションは正しいです。単体テストを使用して、機能テストに属するシナリオをテストしているため、ユーザーのログインをハッキングする必要がありました。他の解決策を検討し、正しいメニュー項目の DOM オブジェクトをチェックして機能テストを行ってください。

于 2014-06-04T15:21:08.627 に答える