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

   }
   //...
 }

次に、これをコントローラーで使用して、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
        ));
    }
    // ...

}

私の質問は:

WebTestCaseでテストを行うときに、これを偽造するにはどうすればよいですか?

4

2 に答える 2

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 に答える
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 に答える