代码之家  ›  专栏  ›  技术社区  ›  Christopher Altman

如何使用用户身份验证编写功能测试?

  •  4
  • Christopher Altman  · 技术社区  · 14 年前

    我正在为需要用户身份验证的页面编写功能测试。我正在使用sfdoctrineguard插件。

    如何在测试中验证用户?

    我是否必须通过登录屏幕进入每个测试?

    这是我的错误代码:

    $b->post('/sfGuardAuth/signin',
           array('signin[password]' => 'password',
                 'signin[username]' => 'user',
                 'signin[_csrf_token]' => '7bd809388ed8bf763fc5fccc255d042e'))->
           with('response')->begin()->
             checkElement('h2', 'Welcome Humans')->
           end()
    

    谢谢你

    2 回复  |  直到 13 年前
        1
  •  3
  •   lonesomeday    14 年前

    是的,您必须登录才能进行测试。幸运的是,这比您上面演示的方法简单得多。看到“更好更简单的方法” on this blog post .

    你可以做 signin 任何方法的一部分 TestFunctional 根据您的测试结构分类。

        2
  •  6
  •   user212218    13 年前

    执行登录的棘手部分是测试浏览器在每个请求之前清除上下文对象(请参见 sfBrowser::call() )

    您可以通过插入调用用户的 signIn() 方法当 context.load_factories 在上下文初始化期间激发事件:

    function signin( sfEvent $event )
    {
      /* @var $user sfGuardSecurityUser */
      if( ! $user = $event->getSubject()->getUser() )
      {
        throw new RuntimeException('User object not created.');
      }
    
      if( ! $user instanceof sfGuardSecurityUser )
      {
        throw new LogicException(sprintf(
          'Cannot log in %s; sfGuardSecurityUser expected.',
            get_class($user)
        ));
      }
    
      if( $user->isAuthenticated() )
      {
        $user->signOut();
      }
    
      /* Magic happens here: */
      $user->signIn($desired_user_to_log_in_as);
    
      $event->getSubject()->getEventDispatcher()->notify(new sfEvent(
        $this,
        'application.log',
        array(sprintf('User is logged in as "%s".', $user->getUsername()))
      ));
    }
    
    /* Set signin() to fire when the browser inits the context for subsequent
     *  requests.
     */
    $b->addListener('context.load_factories', 'signin');
    

    这将导致浏览器登录用户 全部的 后续请求。注意 sfBrowser 有一个 removeListener() 方法。

    改编自 sfJwtPhpUnitPlugin (我是这个项目的主要开发人员)。