简体   繁体   中英

codeception rest api auth header

How can i send auth header, when test codeception rest api?

What i have now:

  1. Yii2 project
  2. "codeception/module-yii2": "^1.0.0"
  3. "codeception/module-rest": "^1.3"
  4. Generated test class by command codecept generate:cest api TestName

My class with test

 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',
        ]);
    }
}

Now it fails with 403 code, because backend expects header JWT-Key: <TOKEN>

How can i send auth header in sendPost And where it is better to store auth token in one place to avoid code duplication, during writing tests?

Codeception has a method called haveHttpHeader you can add any header using it.

This is documented half-way down this page . There is also a section on authorization on this other page .

There are a few built-in authorization methods, like amBearerAuthenticated , amAWSAuthenticated , but I believe that there isn't a specific method for 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',
        ]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM