gpt4 book ai didi

php - Symfony2功能测试Unreachable字段 "_token"

转载 作者:可可西里 更新时间:2023-10-31 23:18:06 24 4
gpt4 key购买 nike

我正在使用 Liip functional test bundle 在 Symfony 中创建一个功能测试.

我目前无法提交表单。
我正在尝试使用功能测试添加一个新的“日志”。

如果我尝试通过 UI 添加新日志,我会收到以下请求参数:

'WorkLog' => array(
'submit' => '',
'hours' => '8',
'minutes' => '0',
'note' => 'some text',
'_token' => '4l5oPcdCRzxDKKlJt_RG-B1342X52o0C187ZLLVWre4'
);

但是当测试提交表单时,我得到相同的参数但没有 token

 'WorkLog' => array(
'submit' => '',
'hours' => '8',
'minutes' => '0',
'note' => 'some text'
);

我以为我可以通过将“_token”字段添加到表单请求来解决问题,但是当我运行然后再次测试时它给了我一个错误:

InvalidArgumentException: Unreachable field "_token"

功能测试代码:

namespace App\AdminBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;

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

class LogControllerTest extends WebTestCase
{
private $client;
private $em;
private $fixtures;

public function setUp()
{
$this->client = static::makeClient();
$this->em = $this->client->getContainer()->get('doctrine')->getManager();

$this->fixtures = $this->loadFixtures(array(
'App\AdminBundle\DataFixtures\ORM\LoadUserData',
'App\AdminBundle\DataFixtures\ORM\LoadSubscriptionTypesData',
'App\AdminBundle\DataFixtures\ORM\LoadSubscriptionData',
'App\AdminBundle\DataFixtures\ORM\LoadWorkLogData',
))->getReferenceRepository();
}

public function testAddNewLog()
{
$accountId = $this->fixtures->getReference('userAccount')->getId();

// log in with admin account
$this->logIn('adminAccount');

$crawler = $this->client->request('GET', '/admin/worklog/account/'.$accountId.'/add');
$csrfToken = $this->client->getContainer()->get('form.csrf_provider')->generateCsrfToken('post_type');

$form = $crawler->selectButton('WorkLog_submit')->form(array(
'WorkLog' => array(
'hours' => '8',
'minutes' => '0',
'note' => 'some text',
'_token' => $csrfToken
),
), 'POST');

$crawler = $this->client->submit($form);
}
}

我的问题:如何使用 token 提交表单?

最佳答案

我不使用 Liip 功能测试包,但我通常按以下方式使用表单和 _token:

    $crawler = $this->client->request('GET', $url);

// retrieves the form token
$token = $crawler->filter('[name="select_customer[_token]"]')->attr("value");

// makes the POST request
$crawler = $this->client->request('POST', $url, array(
'select_customer' => array(
'_token' => $token,
'customerId' => $customerId,
),
));

希望这对您有所帮助。

关于php - Symfony2功能测试Unreachable字段 "_token",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com