簡體   English   中英

代碼接收 rest api 授權 header

[英]codeception rest api auth header

當測試代碼接收 rest api 時,我如何發送身份驗證 header?

我現在擁有的:

  1. Yii2 項目
  2. "codeception/module-yii2": "^1.0.0"
  3. "codeception/module-rest": "^1.3"
  4. 通過命令codecept generate:cest api TestName生成測試 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中發送 auth header 在編寫測試期間最好將身份驗證令牌存儲在一個地方以避免代碼重復?

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

這記錄在本頁的中途。 這個其他頁面上還有一個關於授權的部分。

有一些內置的授權方法,例如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',
        ]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM