gpt4 book ai didi

php - 设置 session 变量以在 Symfony Controller 中使用重定向 PHPUnit 测试

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:53 24 4
gpt4 key购买 nike

我正在尝试创建一个功能测试,该测试涉及跨重定向保留 session 变量。登录部分似乎有效,但我无法设置和保留 session 变量。

测试类扩展 WebTestCase。

$this->client = static::createClient();
$this->client->followRedirects();

身份验证

$user = $em->getRepository('MyApp\AppBundle\Entity\User')
->findOneByUsername('gagarin');
$firewall = 'secured_area';
$token = new UsernamePasswordToken($user, $user->getPassword(),
$firewall, $user->getRoles());
self::$kernel->getContainer()->get('security.context')->setToken($token);
$session = $this->client->getContainer()->get('session');
$session->set('_security_' . $firewall, serialize($token));
// tried $session->set('color_id', 1234) here
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);

“/”路由将重定向到登录页面,然后返回到“/”页面 因为 followRedirects 设置为 true。

$crawler = $this->client->request(
'GET',
'http://myapp.test/');
$this->assertTrue($this->client->getResponse()->isSuccessful());

我想做的是设置一个 session 变量(color_id),我可以断言它存在于请求的路由上,然后重定向到登录或“/”路由到的其他页面基于颜色_id。我该怎么做?

最佳答案

我已将身份验证放在自己的类 AbstractControllerTest 中。以下是 session 处理的相关代码:

abstract class AbstractControllerTest extends WebTestCase
{
protected $session = [];

public function addSession($session): void
{
$this->session = array_merge($this->session, $session);
}

protected function createAuthorizedClient()
{
//Here comes your client logic...

foreach ($this->session as $sessionKey => $sessionValue) {
$session->set($sessionKey, $sessionValue);
}

$container->get('session')->save();
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));

return $client;
}
}

在您的测试中使用 AbstractControllerTest 并在您的 setUp() 方法中设置额外的 session 变量,如下所示:

class MyTest extends AbstractControllerTest
{
public function setUp(): void
{
$this->addSession(['variable' => 'value']);

parent::setUp();
}
}

关于php - 设置 session 变量以在 Symfony Controller 中使用重定向 PHPUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38011003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com