codeigniter CI4单元测试的发布请求

von4xj4u  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(138)

我在CI 4.1.2中运行了以下代码:

public function testForgotten(){

    fwrite(STDERR,"\n\nProcess Forgotten:\n");

    $_COOKIE[csrf_token()] = csrf_hash();

    $result = $this->post('site/forgotten',array(
        'Username'      => 'my@email.com',
        csrf_token()        => csrf_hash(),
    ));

    print'<pre>';print_r($result->response());print'</pre>';

    $result->assertRedirect();
}

正如您所看到的,我只是想检查忘记密码的表单/页面是否正常工作。然而,$result->response()的输出包括未发布到的页面沿着<form action="http://example.com/site/forgotten" id="Config\Forms::reset" enctype="multipart/form-data" method="post" accept-charset="utf-8">作为表单的一部分(注意**我没有在www.example.com中放置example.com- Codeigniter做了!**所以,只是想知道我在让这个测试运行/工作方面遗漏了什么?
仅供参考,我正在一个PHAR文件下运行php punit.phar tests/app/Controllers/SiteTests.php,它在运行简单的get('/path/to/page');调用时工作正常。
我后来发现example.com可以在phpunit.xml.dist中更改www.example.com,但这仍然没有解决assertRedirect问题。

ecfsfe2w

ecfsfe2w1#

因此,答案似乎是CI 4实际上并不填充$_GET$_POST变量,而是它自己的内部机制用途:

$request = \Config\Services::request();

print_r($request->getPost('Username'));

而不是$_POST
解决方案是a)使用getPost()类型函数或B)修改system/HTTP/RequestTrait.phpsetGlobal中的框架(是的,震惊/恐怖!),以包括:

switch ($method){
    case 'post': $_POST = $value; break;
    case 'get': $_GET = $value; break;
}
gstyhher

gstyhher2#

这是一个仅用于测试控制器的工作解决方案。不适用于HTTP Testing
您的代码可以重写为:

/**
 * @throws \Exception
 */
public function testForgotten()
{
    fwrite(STDERR, "\n\nProcess Forgotten:\n");

    $_COOKIE[csrf_token()] = csrf_hash();

    $request = $this->request
        ->withMethod('post')
        // parameter 'post' for post method parameters
        ->setGlobal('post', [
            'Username' => 'my@email.com',
            csrf_token() => csrf_hash()
        ]);

    $result = $this
        ->withRequest($request)
        ->controller(YourSiteController::class)
        ->execute('forgotten');

    print'<pre>';
    print_r($result->response());
    print'</pre>';

    $result->assertRedirect();
}

注意要点:
1.使用$request = $this->request;,然后通过withMethod()setGlobal()链接,用于适配POST请求方法和接受POST请求参数;
1.用$this->withRequest($request)绑定$request变量;
1.以controller()execute()链接$this->withRequest($request),以取得结果。

相关问题