From 6d593620d69f7ce187b4153dc7b07fc41db7301e Mon Sep 17 00:00:00 2001 From: "Alexander A. Klimov" Date: Mon, 13 Feb 2017 14:30:27 +0100 Subject: [PATCH] Test RestRequest refs #2674 --- .../Monitoring/Web/Rest/RestRequest.php | 42 ++++++++++++------- .../Monitoring/Web/Rest/RestRequestTest.php | 27 ++++++++++++ 2 files changed, 55 insertions(+), 14 deletions(-) create mode 100644 modules/monitoring/test/php/library/Monitoring/Web/Rest/RestRequestTest.php diff --git a/modules/monitoring/library/Monitoring/Web/Rest/RestRequest.php b/modules/monitoring/library/Monitoring/Web/Rest/RestRequest.php index 81c4a3e42..cc0c3b222 100644 --- a/modules/monitoring/library/Monitoring/Web/Rest/RestRequest.php +++ b/modules/monitoring/library/Monitoring/Web/Rest/RestRequest.php @@ -213,15 +213,12 @@ class RestRequest 'Expect:' ); - $ch = curl_init(); - $options = array( CURLOPT_URL => $this->uri, CURLOPT_TIMEOUT => $this->timeout, // Ignore proxy settings CURLOPT_PROXY => '', - CURLOPT_CUSTOMREQUEST => $this->method, - CURLOPT_RETURNTRANSFER => true + CURLOPT_CUSTOMREQUEST => $this->method ); // Record cURL command line for debugging @@ -250,27 +247,20 @@ class RestRequest $options[CURLOPT_HTTPHEADER] = $headers; $stream = null; - if (Logger::getInstance()->getLevel() === Logger::DEBUG) { + $logger = Logger::getInstance(); + if ($logger !== null && $logger->getLevel() === Logger::DEBUG) { $stream = fopen('php://temp', 'w'); $options[CURLOPT_VERBOSE] = true; $options[CURLOPT_STDERR] = $stream; } - curl_setopt_array($ch, $options); - Logger::debug( 'Executing %s %s', implode(' ', $curlCmd), escapeshellarg($this->uri) ); - $result = curl_exec($ch); - - if ($result === false) { - throw new CurlException('%s', curl_error($ch)); - } - - curl_close($ch); + $result = $this->curlExec($options); if (is_resource($stream)) { rewind($stream); @@ -280,4 +270,28 @@ class RestRequest return Json::decode($result, true); } + + /** + * Set up a new cURL handle with the given options and call {@link curl_exec()} + * + * @param array $options + * + * @return string The response + * + * @throws CurlException + */ + protected function curlExec(array $options) + { + $ch = curl_init(); + $options[CURLOPT_RETURNTRANSFER] = true; + curl_setopt_array($ch, $options); + $result = curl_exec($ch); + + if ($result === false) { + throw new CurlException('%s', curl_error($ch)); + } + + curl_close($ch); + return $result; + } } diff --git a/modules/monitoring/test/php/library/Monitoring/Web/Rest/RestRequestTest.php b/modules/monitoring/test/php/library/Monitoring/Web/Rest/RestRequestTest.php new file mode 100644 index 000000000..432ff8a26 --- /dev/null +++ b/modules/monitoring/test/php/library/Monitoring/Web/Rest/RestRequestTest.php @@ -0,0 +1,27 @@ +Unauthorized'; + } +} + +class RestRequestTest extends BaseTestCase +{ + /** + * @expectedException JsonDecodeException + */ + public function testInvalidServerResponseHandling() + { + MockedRestRequest::get('http://localhost')->send(); + } +}