codeception rest api auth header

codeception rest api auth header

如何在测试代码接收休息时发送身份验证 header?

我现在拥有的:

  1. Yii2 项目
  2. "codeception/module-yii2": "^1.0.0"
  3. "codeception/module-rest": "^1.3"
  4. 通过命令 codecept generate:cest api TestName
  5. 生成测试 class

我的 class 测试

 class CreateWorkspaceCest
 {
    public function _before(ApiTester $I)
    {

    }

    public function successCreate(ApiTester $I)
    {
        $title = 'create test';
        $description = 'test description';

        $I->sendPost('/workspace/create', [
            'title' => $title,
            'description' => $description,
        ]);

        $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
        $I->seeResponseIsJson();

        $I->seeResponseContainsJson([
            'title' => $title,
            'description' => $description,
            'status' => 'active',
        ]);
    }
}

现在它失败并显示 403 代码,因为后端需要 header JWT-Key: <TOKEN>

如何在 sendPost 中发送验证 header 在编写测试期间,最好将身份验证令牌存储在一个地方以避免代码重复?

Codeception 有一个名为 haveHttpHeader 的方法,您可以使用它添加任何 header。

这被记录在 half-way 下 this page. There is also a section on authorization on this other page

有一些 built-in 授权方法,例如 amBearerAuthenticatedamAWSAuthenticated,但我相信 JWT 没有特定的方法。

 class CreateWorkspaceCest
 {
    public function _before(ApiTester $I)
    {

    }

    public function successCreate(ApiTester $I)
    {
        $title = 'create test';
        $description = 'test description';

        // You can add any header like this:
        $I->haveHttpHeader('Content-Type', 'application/json');
        $I->haveHttpHeader('Authorization', 'Bearer user-one-access-token');

        // To add the header that you show in the question, you can use:
        $I->haveHttpHeader('JWT-Key', '<TOKEN>');

        $I->sendPost('/workspace/create', [
            'title' => $title,
            'description' => $description,
        ]);

        $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
        $I->seeResponseIsJson();

        $I->seeResponseContainsJson([
            'title' => $title,
            'description' => $description,
            'status' => 'active',
        ]);
    }
}