编程语言
首页 > 编程语言> > php – Symfony2功能测试无法访问的字段“_token”

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

作者:互联网

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

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

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

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

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

 '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);
    }
}

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

解决方法:

我不使用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,
        ),
    ));

希望这可以帮助.

标签:php,phpunit,symfony,functional-testing,liipfunctionaltestbundle
来源: https://codeday.me/bug/20190628/1314093.html