環境
概要
認証付きエンドポイントを何もせずにテストすると、(未ログインで)302転送されてしまう。
セッションに偽の認証情報を入れることで、認証を通り抜けてテストできる。
やり方
公式ドキュメントにある通り。
IntegrationTestTrait を使って、セッションに偽の認証情報を格納しておくだけ。
class FooControllerTest extends TestCase
{
use IntegrationTestTrait;
public function testSomething()
{
// セッションに偽の認証情報を格納
$this->session(
[
'Auth' => [
'User' => [
'id' => 1,
'username' => 'testing',
]
]
]
);
$this->get('/hoge');
$this->assertResponseOk();
}
}
Session を直接確認する
じゃあなんでこれで動くのかと思って、画面からログインして Controller 側で Session を直接確認すると、確かに Auth がキーで入っている。
class FooController extends AppController
{
public function hoge()
{
// key を指定せずに取得
$this->request->getSession()->read();
// key を指定して取得
$this->request->getSession()->read('Auth');
// ...do something
}
}
どこで入れている?
そしてどこで入れているのかというと SessionAuthenticator ( \Authentication\Authenticator\SessionAuthenticator::persistIdentity )でやってる。
authentication/SessionAuthenticator.php at 2.5.0 · cakephp/authentication · GitHub
デフォルトだと、 sessionKey が Auth になっているので、その Key で格納されているということだった。
protected $_defaultConfig = [
'fields' => [
IdentifierInterface::CREDENTIAL_USERNAME => 'username',
],
'sessionKey' => 'Auth',
'identify' => false,
'identityAttribute' => 'identity',
];