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

max*_*max 6 phpunit functional-testing symfony

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

foo.domain.dev -> Agency:showAction(foo)
bar.domain.dev -> Agency:showAction(bar)
domain.dev     -> Agency:indexAction()
Run Code Online (Sandbox Code Playgroud)

这些都对应于代理实体和控制器.

我有一个监听器,它监听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']);
       }

   }
   //...
 }
Run Code Online (Sandbox Code Playgroud)

然后我在控制器中使用它来重新路由到show动作:

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
        ));
    }
    // ...

}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

在使用WebTestCase进行测试时如何伪装?

ila*_*nco 7

通过覆盖请求的HTTP标头并测试右侧页面来访问子域:

未经测试,可能包含错误

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());
    }
}
Run Code Online (Sandbox Code Playgroud)


faz*_*azy 7

基于基于主机的路由上的Symfony文档,测试您的控制器:

$crawler = $client->request(
    'GET',
    '/',
    array(),
    array(),
    array('HTTP_HOST' => 'foo.domain.dev')
);
Run Code Online (Sandbox Code Playgroud)

如果您不想使用数组参数填充所有请求,则可能更好:

$client->setServerParameter('HTTP_HOST', 'foo.domain.dev');
$crawler = $client->request('GET', '/');

...

$crawler2 = $client->request('GET', /foo'); // still sends the HTTP_HOST
Run Code Online (Sandbox Code Playgroud)

setServerParameters()如果您要更改一些参数,客户端上还有一个方法.