我目前正在尝试使用功能测试来测试已保护页面的symfony应用程序。
当我浏览安全页面时,而不是200 HTTP
代码,我得到401 "Unauthorized" HTTP code
,这意味着我正在尝试访问页面而未经过身份验证/没有拥有正确的证书。
即使我以普通用户身份登录,但拥有正确的symfony凭据,我仍然可以获得401 error
。
//CapWebndfTestFunctional.class.php
class CapWebndfTestFunctional extends sfTestFunctional
{
/**
* Login as a user
* @param string $username User's username
*/
public function signInAs($username)
{
$user = Doctrine_Core::getTable('sfGuardUser')->findOneByUsername($username);
//force the context to be created
$this->browser->getContext(true)->getUser()->signIn($user);
$this->info(sprintf('Signin user using username "%s"', $username));
if ($user->getIsSuperAdmin())
{
$this->info('Beware, you are logged as a superadmin!');
}
return $this;
}
}
测试套件:
<?php
$browser = new CapWebndfTestFunctional(new sfBrowser());
$browser->
signInAs('superadmin')->
with('user')->begin()->
isAuthenticated()-> //ensure that I'm well authenticated
end()->
get('/document')-> //a secured page
with('request')->begin()->
isParameter('module', 'document')->
isParameter('action', 'index')->
end()->
with('response')->begin()->
isStatusCode(200)-> //as superadmin is a sfGuard superadmin, this should be 200;
end()->
// Here some other tests...
/* Outputs :
clem@ubuntu:/var/www/cap_webndf/trunk$ php symfony test:functional backend documentActions
> Signin user using username "superadmin"
> Beware, you are logged as a superadmin!
ok 1 - user is authenticated
# get /document
ok 2 - request parameter module is document
ok 3 - request parameter action is index
not ok 4 - status code is 200
# Failed test (./lib/vendor/symfony/lib/test/sfTesterResponse.class.php at line 412)
# got: 401
# expected: 200
*/
我真的坚持这个,所以谢谢你的帮助。
修改:如果您愿意,此处为the used code on a gist
编辑:进入登录页面和发送(假)帖子请求,并使用专用的sfGuard方法直接登录有什么区别?
答案 0 :(得分:0)
我认为你不能像这样使用SignIn(),因为它不会在浏览器中设置cookie,所以在下一页你将再次注销。
每当我对用户进行功能测试时,我都会进入登录页面并输入用户的用户名/密码并以其身份登录。
我没有测试过这个,但是这样的东西应该可行,我通常使用测试用户并知道他们的密码
// CapWebndfTestFunctionnal.class.php
class CapWebndfTestFunctionnal extends sfTestFunctional
{
/**
* Login as a user
* @param string $username User's username
*/
public function signInAs($username)
{
$tempPassword = rand(1000, 9999999);
$user = Doctrine_Core::getTable('sfGuardUser')->findOneByUsername($username);
$oldPassword = $user->getPassword();
$user->setPassword($tempPassword);
$user->save();
$this->info(sprintf('Signin user using username "%s"', $username));
$this->post('/login', array('username' => $user->getUsername(), 'password' => $tempPassword))->isRedirected();
if ($user->getIsSuperAdmin())
{
$this->info('Beware, you are logged as a superadmin!');
}
$user->setPasswordHash($oldPassword);
$user->save();
return $this;
}
}