加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Symfony2功能测试无法访问的字段“_token”

发布时间:2020-12-13 16:58:32 所属栏目:PHP教程 来源:网络整理
导读:我正在使用 Liip functional test bundle在Symfony中创建功能测试. 我目前不愿提交表格. 我正在尝试使用功能测试添加新的“日志”. 如果我尝试通过UI添加新日志,我会得到以下请求参数: 'WorkLog' = array( 'submit' = '','hours' = '8','minutes' = '0','no
我正在使用 Liip functional test bundle在Symfony中创建功能测试.

我目前不愿提交表格.
我正在尝试使用功能测试添加新的“日志”.

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

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

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

'WorkLog' => array(
    'submit' => '','note' => 'some text'
);

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

InvalidArgumentException: Unreachable field “_token”

功能测试的代码:

namespace AppAdminBundleTestsController;

use LiipFunctionalTestBundleTestWebTestCase;

use SymfonyBundleFrameworkBundleClient;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentBrowserKitCookie;

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(
            'AppAdminBundleDataFixturesORMLoadUserData','AppAdminBundleDataFixturesORMLoadSubscriptionTypesData','AppAdminBundleDataFixturesORMLoadSubscriptionData','AppAdminBundleDataFixturesORMLoadWorkLogData',))->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','_token' => $csrfToken
            ),),'POST');

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

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

解决方法

我不使用Liip Functional Test Bundle,但我通常以下列方式使用form和_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,));

希望这可以帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读