4

Laravel 功能测试中发起多次请求(经过自定义 Guard)时的坑

 1 year ago
source link: https://www.mokeyjay.com/archives/3313
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Laravel

Laravel 功能测试中发起多次请求(经过自定义 Guard)时的坑

TL;DR

laravel 会缓存 guards,如果你在 guard 中对 $request 做了一些操作,则需要在每次请求前

Auth::forgetGuards();

这个项目用到一个自定义 Guard,里面有这么一行代码:

$this->request->attributes->add(['company' => $company]);

也就是在身份校验通过后往请求里面写入一个变量,方便后续在控制器中读取

在这个功能测试中我需要切换多个身份请求同一个接口,我发现只有第一个身份的请求正常,后续身份都取不到这个 company 的值
一番苦苦 debug 无果。后来我在 guard 和控制器中分别使用 spl_object_id() 函数打印 \request() 返回的对象句柄 id,发现它们竟然不是同一个对象

以此思路进一步搜索,发现了这个:How to reset Laravel AuthManager/guards in between API calls in tests?
其中楼主提到:

Laravel caches the fact that the user is logged in

而下面点赞最高的回答提到:

auth()->forgetGuards();

好嘛,看到这里我大致猜到是什么原因了。laravel 会缓存 guards 导致后续的请求根本没过 guard,也就没有写入我需要的 company 了
添加这一行代码之后确实解决了我的问题

LaravelPHP

本站文章除注明转载外,均为原创文章。如需转载请注明出处:https://www.mokeyjay.com/archives/3313

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK