使用 HttpFoundation 创建要在 Behat 测试中使用的 JSON 请求

问题描述 投票:0回答:1

我有一个在curl 中工作的JSON 登录查询(即我正在发送数据并且它找到用户)。我想创建一个行为测试来检查它,但我无法在行为测试中重现它,并且测试失败。我确保数据库设置正确(用户及其密码设置正确),但错误消息告诉我这些字段无论如何都丢失了。

我的curl调用(成功):

curl --request POST \
  --url http://localhost/login \
  --header 'content-type: application/json' \
  --data '{
  "username": "my_username",
  "password": "my_password"
}'

我的登录控制器:

<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class LoginController extends AbstractController
{
    #[Route('/login', name: 'app_login', methods: ['POST'])]
    public function index(#[CurrentUser] ?User $user): Response
    {
        if ($user === null) {
            return $this->json([
                'message' => 'An error occured',
                'errors' => ['missing credentials'],
            ], Response::HTTP_UNAUTHORIZED);
        }

        $token = 'RANDOM_TOKEN';

        return $this->json([
            'user' => $user->getUserIdentifier(),
            'token' => $token,
        ]);
    }
}

我的行为场景和相关功能:

    Scenario: Login successful
     Given I am an unlogged user
        And these users already exist
            | email       | username | password |
            | [email protected] | test     | test_pwd |
        When I POST to the login route with the following JSON data:
            | username | password  |
            | test     | test_pwd  |
        Then the response status code should be 200
        And the response should be valid JSON
        And the "user" key should contain "test"
        And the "token" key should not be empty
    /**
     * @When I :verb to the :route route with the following JSON data:
     */
    public function iVerbToTheRouteWithJSONData(string $verb, string $route, TableNode $table): void
    {
        Assert::count($table->getLines(), 2); // One for the header, one for the data
        $params = [];
        foreach ($table as $row) {
            Assert::isArray($row);
            $params = $row;
        }

        $encoded = json_encode($params);

        $this->response = $this->kernel->handle(
            Request::create($route, $verb, [], [], [], ['Content-Type' => 'application/json'], $encoded)
        );
    }

如果我转储 de

$encoded
,它看起来就像我想要的 (
{"username":"test","password":"test_pwd"}
)。

如果我转储响应的内容,我会收到此错误消息,这是 Symfony 在缺少字段时发送的消息:

{"message":"An error occured","errors":["missing credentials"]}

我觉得我在请求创建中遗漏了一件简单的事情,但我找不到什么。

php symfony behat symfony-http-foundation
1个回答
0
投票

如果基本身份验证对您来说足够了,请尝试以下操作:

$response = $client->request('GET', 'https://...', [
    'auth_basic' => ['the-username', 'the-password']
]);

请参阅 https://symfony.com/doc/current/http_client.html 了解更多信息;)

© www.soinside.com 2019 - 2024. All rights reserved.