gpt4 book ai didi

symfony - 如何在Symfony2中测试基于子域的路由

转载 作者:行者123 更新时间:2023-12-04 13:28:26 25 4
gpt4 key购买 nike

我有一个使用子域路由到代理商的应用程序:

foo.domain.dev -> Agency:showAction(foo)
bar.domain.dev -> Agency:showAction(bar)
domain.dev -> Agency:indexAction()

这些每个都对应一个代理商实体和控制者。

我有一个监听器,监听onDomainParse事件并将子域写入请求属性。
/**
* Listens for on domainParse event
* Writes to request attributes
*/
class SubdomainListener {
public function onDomainParse(Event $event)
{
$request = $event->getRequest();
$session = $request->getSession();
// Split the host name into tokens
$tokens = $this->tokenizeHost($request->getHost());

if (isset($tokens['subdomain'])){
$request->attributes->set('_subdomain',$tokens['subdomain']);
}

}
//...
}

然后,我在 Controller 中使用它来重新路由到show Action :
class AgencyController extends Controller
{

/**
* Lists all Agency entities.
*
*/
public function indexAction()
{
// We reroute to show action here.
$subdomain = $this->getRequest()
->attributes
->get('_subdomain');
if ($subdomain)
return $this->showAction($subdomain);


$em = $this->getDoctrine()->getEntityManager();

$agencies = $em->getRepository('NordRvisnCoreBundle:Agency')->findAll();

return $this->render('NordRvisnCoreBundle:Agency:index.html.twig', array(
'agencies' => $agencies
));
}
// ...

}

我的问题是:

使用WebTestCase进行测试时,我该如何伪造?

最佳答案

通过覆盖请求的HTTP header 来访问子域,并测试正确的页面:

未经测试,可能包含错误

class AgencyControllerTest extends WebTestCase
{
public function testShowFoo()
{
$client = static::createClient();

$crawler = $client->request('GET', '/', array(), array(), array(
'HTTP_HOST' => 'foo.domain.dev',
'HTTP_USER_AGENT' => 'Symfony/2.0',
));

$this->assertGreaterThan(0, $crawler->filter('html:contains("Text of foo domain")')->count());
}
}

关于symfony - 如何在Symfony2中测试基于子域的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677422/

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