6

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

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']);
       }

   }
   //...
 }

然后我在控制器中使用它来重新路由到显示操作:

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 进行测试时如何伪造这个?

4

2 回答 2

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());
    }
}
于 2012-05-20T21:50:19.447 回答
7

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

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

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

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

...

$crawler2 = $client->request('GET', /foo'); // still sends the HTTP_HOST

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

于 2014-10-23T09:13:40.230 回答