Slim 3集成测试的POST方法总是不包括头



我目前正在开发一个使用Slim 3框架编写的应用程序,并尝试使用TDD概念,但我面临几个问题,包括在使用POST方法的测试时,我嵌入的头总是被认为缺失。

下面是我的代码
<?php
namespace Testsroutesshopify;
use PHPUnitFrameworkTestCase;
use SlimApp;
use SlimHttpEnvironment;
use SlimHttpHeaders;
use SlimHttpRequest;
use SlimHttpRequestBody;
use SlimHttpResponse;
use SlimHttpUploadedFile;
use SlimHttpUri;
class ShopifyRoutesTest extends TestCase
{
private $app;
protected function setUp(): void
{
// Use the application settings
$settings = require __DIR__ . '/../../../src/settings.php';
// Instantiate the application
$this->app = new App($settings);
// Set up dependencies
$dependencies = require __DIR__ . '/../../../src/dependencies.php';
$dependencies($this->app);
// Register middleware
$middleware = require __DIR__ . '/../../../src/middleware.php';
$middleware($this->app);
// Register routes
$routes = require __DIR__ . '/../../../src/app/routes/api/shopify/routes.php';
$routes($this->app);
}
public function testPostSyncProductBySkuWithEmptyApikeyShouldReturnBadRequest()
{
// Create a mock environment for testing with
$environment = Environment::mock();
$uri = Uri::createFromString("/channel/shopify/v1/product/sync-by-sku");
$headers = new Headers(array(
"Content-Type" => "application/json",
"Authorization" => "client-apikey",
"x-api-key" => ""
));
$cookies = [];
$serverParams = $environment->all();
$body = new RequestBody();
$uploadedFiles = UploadedFile::createFromEnvironment($environment);
// Set up a request object based on the environment
$request = new Request("POST", $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles);
$reqBody = array(
"shop_name" => "STORE ABCE",
"sku" => "SKU-001"
);
$body->write(json_encode($reqBody));

// Add request data, if it exists
$request = $request->withParsedBody($reqBody);
// Set up a response object
$response = new Response();
$response = $this->app->process($request, $response);
self::assertEquals(400, $response->getStatusCode());
self::assertStringContainsString("Header: x-api-key cannot be empty", $response->getBody());
}
protected function tearDown(): void
{
$this->app = null;
}
}

第一个断言成功,值为400,但在第二个断言中失败,字符串不包含值"头:x-api-key不能为空">但是这个

Failed asserting that '{n
"error": "AUTH_FAIL",n
"errorDetail": "Header: Authorization, x-api-key required",n
"status": 400,n
"message": "BAD_REQUEST",n
"data": ""n
}' contains "Header: x-api-key cannot be empty".

奇怪的是当我var_dump($request->getHeaders())我所做的请求的报头值结果是那里

array(3) {
["Content-Type"]=>
array(1) {
[0]=>
string(16) "application/json"
}
["Authorization"]=>
array(1) {
[0]=>
string(13) "client-apikey"
}
["x-api-key"]=>
array(1) {
[0]=>
string(0) ""
}
}

我还尝试使用Postman测试我的API端点,结果与预期一致

curl --location --request POST 'http://localhost:8080/channel/shopify/v1/product/sync-by-sku' 
--header 'Authorization: client-apikey' 
--header 'x-api-key: 1293129382938' 
--header 'Content-Type: application/json' 
--header 'Cookie: PHPSESSID=tll8s24tp253rda1harv0koapi' 
--data-raw '{
"shop_name" : "STORE ABC",
"sku" : "SKU-991"
}'
<<p>反应/strong>
{
"error": "AUTH_FAIL",
"errorDetail": "Header: x-api-key cannot be empty",
"status": 400,
"message": "BAD_REQUEST",
"data": ""
}

我也读过这里描述的stakoverflow的答案用PHPUnit模拟Slim端点POST请求

但我仍然找不到解决方案,头总是被认为是缺失的。我真的很欣赏这个问题的解决方案,提前谢谢你

最后在弄清楚Slim 3中的Header和Request的结构和行为后,Slim 3中的Header类总是使关键值变为小写,我不知道这意味着什么,但最后我需要在我的中间件中调整这种行为,从以前使用的$ Request ->getHeaders()到$ Request ->getHeaderLine()和$ Request ->hasHeader(),$request->getHeaders()把报头的值改成大写,并把HTTP_加到键的前面

在我的例子中,这是问题的原因,因为我在单元测试中使用的请求必须传递小写值,并且在键的前面没有HTTP_,因此中间件假设应该存在的键从未存在过

中间件在

// Common Channel Auth with client-apikey
$app->add(function (Request $request, Response $response, callable $next) use ($container) {
$uri = $request->getUri();
$path = $uri->getPath();
$headers = $request->getHeaders();
$arrayPath = explode("/", $path);
if ($arrayPath[1] == "channel" && $arrayPath[3] == "tools")
{
return $next($request, $response);
}
elseif ($arrayPath[1] == "channel" && $arrayPath[4] != "webhook")
{
/** @var ClientRepository $clientRepository */
$clientRepository = $container->get("ClientRepository");
// Get Header With Name x-api-key & Authorization
if (isset($headers["HTTP_AUTHORIZATION"]) && isset($headers["HTTP_X_API_KEY"]))
{
if ($headers["HTTP_AUTHORIZATION"][0] == "client-apikey")
{
$reqClientApikey = $headers["HTTP_X_API_KEY"][0];
if (v::notBlank()->validate($reqClientApikey))
{
if ($clientRepository->findByClientApiKey($reqClientApikey))
{
return $next($request, $response);

中间件后

// Common Channel Auth with client-apikey
$app->add(function (Request $request, Response $response, callable $next) use ($container) {
$uri = $request->getUri();
$path = $uri->getPath();
$arrayPath = explode("/", $path);
if ($arrayPath[1] == "channel" && $arrayPath[3] == "tools")
{
return $next($request, $response);
}
elseif ($arrayPath[1] == "channel" && $arrayPath[4] != "webhook")
{
/** @var ClientRepository $clientRepository */
$clientRepository = $container->get("ClientRepository");
// Using $request-hasHeader & $request->getHeaderLine instead of $headers["HTTP_AUTHORIZATION"]
if ($request->hasHeader("authorization") != null && $request->hasHeader("x-api-key") != null)
{
if ($request->getHeaderLine("authorization") == "client-apikey")
{
$reqClientApikey = $request->getHeaderLine("x-api-key");
if (v::notBlank()->validate($reqClientApikey))
{
if ($clientRepository->findByClientApiKey($reqClientApikey))
{
return $next($request, $response);
}

public function testPostSyncProductBySkuWithEmptyApikeyShouldReturnBadRequest()
{
// Create a mock environment for testing with
$environment = Environment::mock();
$uri = Uri::createFromString("/channel/shopify/v1/product/sync-by-sku");
$headers = new Headers([
"Content-Type" => "application/json",
"Authorization" => "client-apikey",
"x-api-key" => ""
]);
$cookies = [];
$serverParams = $environment->all();
$body = new RequestBody();
$uploadedFiles = UploadedFile::createFromEnvironment($environment);
// Set up a request object based on the environment
$request = new Request("POST", $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles);
$reqBody = array(
"shop_name" => "STORE ABCE",
"sku" => "SKU-001"
);
$body->write(json_encode($reqBody));

// Add request data, if it exists
$request = $request->withParsedBody($reqBody);
// Set up a response object
$response = new Response();
$response = $this->app->process($request, $response);
self::assertEquals(400, $response->getStatusCode());
self::assertStringContainsString("Header: x-api-key cannot be empty", $response->getBody());
}

再一次,我希望我犯的这个错误将成为别人的记录,谢谢你

相关内容

  • 没有找到相关文章

最新更新