2012-10-07 81 views
1

該測試針對的是POST api端點,其中數據包含在JSON文章的正文中。在撥打電話之前,我將Content-Type設置爲'application/json'。但是,當我測試格式isFormat('JSON')時,響應爲空。如果我轉儲$request->contentType()這也產生空。內容類型未在使用Symfony 1.4中的sfBrowser進行功能測試時傳入

爲什麼setHttpHeader('Content-Type','application/json')在功能測試期間沒有正確設置標題?

回答

1

你的設置方法是正確的,但裏面sfBrowserBase有此錯誤:

foreach ($this->headers as $header => $value) 
{ 
    $_SERVER['HTTP_'.strtoupper(str_replace('-', '_', $header))] = $value; 
} 

該設置的CONTENT_TYPE前綴HTTP。但是在你的動作$ request-> getContentType()方法中,假設你沒有前綴。

所以如果你改變了這個:

foreach ($this->headers as $header => $value) 
{ 
    $_SERVER[strtoupper(str_replace('-', '_', $header))] = $value; 
} 

可以正確地作出$request->getContentType()

你可以找到更新here

+0

這實際上打破了其他頭。因爲'$ request-> getContentType()'在不使用HTTP的情況下查找標題,所以需要爲ContentType設置一個例外,但是其他的例如$ request-> isXmlHttpRequest()不需要使用HTTP_前綴。因此,foreach循環變成:'foreach($ this-> headers爲$ header => value){if(strtolower($ header)=='content-type'|| strtolower($ header)=='content_type'){ $ _SERVER [strtoupper(str_replace(' - ','_',$ header))] = $ value; }其他{$ _SERVER ['HTTP_'。strtoupper(str_replace(' - ','_',$ header))] = $ value; }' –

1

非常感謝@nicolx我可以更多地解釋發生了什麼,並提供一些進一步的指導。

正如@nicolx $request->getContentType()所指出的那樣,您正在尋找HTTP頭部,但前綴爲HTTP_(請參閱sfWebRequest中的第163至173行)。但是,sfBrowserBase總是爲所有頭添加HTTP_前綴。所以加在這個mod:

foreach($this->headers as $header => $value) 
{ 
    if(strotolower($header) == 'content-type' || strtolower($header) == 'content_type') 
    { 
    $_SERVER[strtoupper(str_replace('-','_',$header))] = $value; 
    } else { 
    $_SERVER['HTTP_'.strtoupper(str_replace('-','_',$header))] = $value; 
    } 
} 

這將處理ContentType頭被設置,並在檢測到你的行動。如果您不包含HTTP_前綴,則其他標頭將不起作用(例如,即使在測試文件中設置此項,$request->isXmlHtttpHeader()也會失敗)。

測試方法isFormat()未測試ContentType標頭,而是測試了Symfony路由設置sf_format。如果我將路線設置爲具有sf_format: json例如

some_route: 
    url: /something/to/do 
    param: {module: top, action: index, sf_format: json} 

那麼測試

with('request')->begin()-> 
    isFormat('json')-> 
end()-> 

返回true。

由於我想測試標題設置,我在sfTesterRequest中添加了一個名爲isContentType()的新測試器方法。此方法的代碼是:

public function isContentType($type) 
{ 
    $this->tester->is($this->request->getContentType(),$type, sprintf('request method is "%s"',strtoupper($type))); 

    return $this->getObjectToReturn(); 
} 

調用此測試純粹變成:

with('request')->begin()-> 
    isContentType('Application/Json')-> 
end()-> 
相關問題