gpt4 book ai didi

php - 在phpunit测试中为filter_input_array(INPUT_POST)设置$_POST

转载 作者:行者123 更新时间:2023-12-02 07:31:02 24 4
gpt4 key购买 nike

使用 PHPUnit 测试我的 Controller 时遇到一些问题。

到目前为止我正在处理的代码正在实现 $_POST 或其他请求变量:

$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = array(
'test' => true
);

大多数测试都以这种方式完美运行,直到我遇到使用 filter_input_array 函数的方法:

$_SERVER['REQUEST_METHOD'] = 'POST';
$_REQUEST = $_POST = $GLOBALS['_POST'] = array(
'test' => true
);

// ....

var_dump(filter_input_array(INPUT_POST));

NULL

我不愿意从非我的代码中删除 filter_input 函数,但我无法让它们在测试中工作。

Versionings:
PHP 5.5.9-1ubuntu4.9 (cli) (built: Apr 17 2015 11:44:57)
Apache/2.4.7 (Ubuntu)
PHPUnit 4.6.6 by Sebastian Bergmann and contributors.

任何帮助将不胜感激。

编辑2015.05.11

使用 CONTENT_LENGTHCONTENT_TYPE 设置 $_SERVER 并不能解决问题。我的 PHP 版本不允许我以 PHP 5.6.0 chagelog 中描述的方式(或我理解的方式)写入 php://stdin ,但是 file_put_contents(STDIN,. .) 成功但无论如何都不起作用。

因为这是一个 phpunit 测试,也许有某种我还不知道的注释或 phpunit.xml 条目,这可能会在 php-cgi POST setting 中解决这个问题。方式。

最佳答案

如果 filter_input_array 的输入只能由初始请求设置,并且不能在运行时更改,那么仍然测试它的唯一方法就是让您的基本测试代理另一个测试通过使用正确的 POST 数据发出 HTTP 请求并处理响应来编写脚本。

main_test.php:

<?php
$data = array(
'testname' => 'yourtestname',
'some_post_var' => 'some_value'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/proxy_test.php");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

if ($response == 'pass') {
// test passed
}

proxy_test.php

<?php
$test_name $_POST['testname']; // what test to run?
$response = run_test($test_name); // run test that uses filter_input_array
if ($response) {
echo "pass"; // used by main_test.php to check if test passed
} else {
echo "fail";
}

关于php - 在phpunit测试中为filter_input_array(INPUT_POST)设置$_POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30123803/

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