如何在Guzzle 3中模拟响应超时或拒绝连接?

时间:2015-03-20 17:49:43

标签: php curl connection-timeout guzzle http-status

我在Guzzle 3中使用事件订阅者(在Goutte 1.0.6中)来测试HTTP操作,而不必实际运行它们。所以如果我想看看404中会发生什么,我就这么做:

class SavedPageLoaderPlugin implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'request.before_send' => 'onRequestBeforeSend',
        );
    }

    /**
     * Handles a Guzzle event before an HTTP op is attempted
     * 
     * @param \Guzzle\Common\Event $event
     * @throws \WebScraper\PauseException
     */
    public function onRequestBeforeSend(Event $event)
    {
        // @var $request Guzzle\Http\Message\Request
        $request = $event['request'];

        // {{ Fetch $html and $htmlPage, removed for brevity }}

        // Set a notification message for all subscribers, then set response
        $response = new Response(
            404,
            $this->convertHeadersIntoKeyedArray($httpPage->getHeaders())
        );
        $response->setBody($html);
        $request->setResponse($response);
    }
}

我发现这非常适合模拟失败(4xx / 5xx)和成功操作(2xx),Guzzle在我的其他插件上正确调用the success/failure events

但是,我不确定如何在超时或连接被拒绝的情况下执行此操作,这两者都没有响应(或状态代码)。我已经尝试null作为Response的第一个参数,但这不会触发任何事件;我假设没有像真正的超时那样被理解。


更新:我刚刚注意到in the MockPlugin Request类有一个getEventDispatcher()方法,后者又返回一个EventDispatcher类,其中dispatch()方法。这听起来值得研究 - 我需要做的就是看看实际超时或连接拒绝触发了什么事件,然后将它们自己扔到自定义插件中。

如果我有任何工作,我会在这里添加一个解决方案。

0 个答案:

没有答案