gpt4 book ai didi

php - Symfony2 从 phpunit 测试中的 Twig 模板访问全局变量

转载 作者:可可西里 更新时间:2023-11-01 13:22:48 26 4
gpt4 key购买 nike

我有一个带有 {{ app.user }} 的 Twig 模板。问题是,在 phpunit 测试(一个扩展 WebTestCase 的类)中,它被定义为 NULL。使用 token ( http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html ) 模拟身份验证或模拟 HTTP 身份验证 ( http://symfony.com/doc/current/cookbook/testing/http_authentication.html ) 没有帮助。那么如何从 phpunit 测试中设置一个 twig 全局变量呢?为什么模拟身份验证在这种情况下不起作用?

最佳答案

我有一个类似的问题(正确登录)最终为我解决的是改变我的登录方式(它基于 http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html 但我以不同的方式处理 session ):

public function setUp() {
parent::setUp();

$this->em = $this->get('doctrine')->getManager();
$this->client = static::createClient(array('environment' => 'test'));
}

protected function logIn() {
$repo = $this->em->getRepository('XXXXXXX');
$user = $repo->findOneByUsername('YYYYYYY');

$session = new Session(new MockFileSessionStorage());
$firewall = 'main';
$token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_ADMIN'));
$this->client->getContainer()->get('security.context')->setToken($token);
$session->set('_security_' . $firewall, serialize($token));
$session->save();

$this->client->getContainer()->set('session', $session);
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);

return $user;
}

关于php - Symfony2 从 phpunit 测试中的 Twig 模板访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23489149/

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