ApiTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. # Copyright (c) 2013-2016, OVH SAS.
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # * Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. # * Neither the name of OVH SAS nor the
  14. # names of its contributors may be used to endorse or promote products
  15. # derived from this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS ``AS IS'' AND ANY
  18. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. # DISCLAIMED. IN NO EVENT SHALL OVH SAS AND CONTRIBUTORS BE LIABLE FOR ANY
  21. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. namespace Ovh\tests;
  28. use GuzzleHttp\Client;
  29. use GuzzleHttp\Middleware;
  30. use GuzzleHttp\Psr7\Response;
  31. use GuzzleHttp\Psr7\Request;
  32. use Ovh\Api;
  33. /**
  34. * Test Api class
  35. *
  36. * @package Ovh
  37. * @category Ovh
  38. */
  39. class ApiTest extends \PHPUnit_Framework_TestCase
  40. {
  41. /**
  42. * @var Client
  43. */
  44. private $client;
  45. /**
  46. * @var string
  47. */
  48. private $application_key;
  49. /**
  50. * @var string
  51. */
  52. private $consumer_key;
  53. /**
  54. * @var string
  55. */
  56. private $endpoint;
  57. /**
  58. * @var string
  59. */
  60. private $application_secret;
  61. /**
  62. * Define id to create object
  63. */
  64. protected function setUp()
  65. {
  66. $this->application_key = 'app_key';
  67. $this->application_secret = 'app_secret';
  68. $this->consumer_key = 'consumer';
  69. $this->endpoint = 'ovh-eu';
  70. $this->client = new Client();
  71. }
  72. /**
  73. * Get private and protected method to unit test it
  74. *
  75. * @param string $name
  76. *
  77. * @return \ReflectionMethod
  78. */
  79. protected static function getPrivateMethod($name)
  80. {
  81. $class = new \ReflectionClass('Ovh\Api');
  82. $method = $class->getMethod($name);
  83. $method->setAccessible(true);
  84. return $method;
  85. }
  86. /**
  87. * Get private and protected property to unit test it
  88. *
  89. * @param string $name
  90. *
  91. * @return \ReflectionProperty
  92. */
  93. protected static function getPrivateProperty($name)
  94. {
  95. $class = new \ReflectionClass('Ovh\Api');
  96. $property = $class->getProperty($name);
  97. $property->setAccessible(true);
  98. return $property;
  99. }
  100. /**
  101. * Test missing $application_key
  102. */
  103. public function testMissingApplicationKey()
  104. {
  105. $this->setExpectedException('\\Ovh\\Exceptions\\InvalidParameterException', 'Application key');
  106. new Api(null, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  107. }
  108. /**
  109. * Test missing $application_secret
  110. */
  111. public function testMissingApplicationSecret()
  112. {
  113. $this->setExpectedException('\\Ovh\\Exceptions\\InvalidParameterException', 'Application secret');
  114. new Api($this->application_key, null, $this->endpoint, $this->consumer_key, $this->client);
  115. }
  116. /**
  117. * Test missing $api_endpoint
  118. */
  119. public function testMissingApiEndpoint()
  120. {
  121. $this->setExpectedException('\\Ovh\\Exceptions\\InvalidParameterException', 'Endpoint');
  122. new Api($this->application_key, $this->application_secret, null, $this->consumer_key, $this->client);
  123. }
  124. /**
  125. * Test bad $api_endpoint
  126. */
  127. public function testBadApiEndpoint()
  128. {
  129. $this->setExpectedException('\\Ovh\\Exceptions\\InvalidParameterException', 'Unknown');
  130. new Api($this->application_key, $this->application_secret, 'i_am_invalid', $this->consumer_key, $this->client);
  131. }
  132. /**
  133. * Test creating Client if none is provided
  134. */
  135. public function testClientCreation()
  136. {
  137. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key);
  138. $this->assertInstanceOf('\\GuzzleHttp\\Client', $api->getHttpClient());
  139. }
  140. /**
  141. * Test the compute of time delta
  142. */
  143. public function testTimeDeltaCompute()
  144. {
  145. $delay = 10;
  146. $handlerStack = $this->client->getConfig('handler');
  147. $handlerStack->push(Middleware::mapResponse(function (Response $response) {
  148. $body = $response->getBody();
  149. $body->write(time() - 10);
  150. return $response
  151. ->withStatus(200)
  152. ->withBody($body);
  153. }));
  154. $invoker = self::getPrivateMethod('calculateTimeDelta');
  155. $property = self::getPrivateProperty('time_delta');
  156. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  157. $invoker->invokeArgs($api, []);
  158. $time_delta = $property->getValue($api);
  159. $this->assertNotNull($time_delta);
  160. $this->assertEquals($time_delta, $delay * -1);
  161. }
  162. /**
  163. * Test if consumer key is replaced
  164. */
  165. public function testIfConsumerKeyIsReplace()
  166. {
  167. $handlerStack = $this->client->getConfig('handler');
  168. $handlerStack->push(Middleware::mapResponse(function (Response $response) {
  169. $body = $response->getBody();
  170. $body->write('{"validationUrl":"https://api.ovh.com/login/?credentialToken=token","consumerKey":"consumer_remote","state":"pendingValidation"}');
  171. return $response
  172. ->withStatus(200)
  173. ->withBody($body);
  174. }));
  175. $property = self::getPrivateProperty('consumer_key');
  176. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  177. $accessRules = [json_decode(' { "method": "GET", "path": "/*" } ')];
  178. $credentials = $api->requestCredentials($accessRules);
  179. $consumer_key = $property->getValue($api);
  180. $this->assertEquals($consumer_key, $credentials["consumerKey"]);
  181. $this->assertNotEquals($consumer_key, $this->consumer_key);
  182. }
  183. /**
  184. * Test invalid applicationKey
  185. */
  186. public function testInvalidApplicationKey()
  187. {
  188. $this->setExpectedException(
  189. '\GuzzleHttp\Exception\ClientException'
  190. );
  191. $handlerStack = $this->client->getConfig('handler');
  192. $handlerStack->push(Middleware::mapResponse(function (Response $response) {
  193. $body = $response->getBody();
  194. $body->write('{\"message\":\"Invalid application key\"}');
  195. return $response
  196. ->withStatus(401, 'POUET')
  197. ->withHeader('Content-Type', 'application/json; charset=utf-8')
  198. ->withHeader('Content-Length', 37)
  199. ->withBody($body);
  200. }));
  201. $property = self::getPrivateProperty('consumer_key');
  202. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  203. $accessRules = [json_decode(' { "method": "GET", "path": "/*" } ')];
  204. $credentials = $api->requestCredentials($accessRules);
  205. $consumer_key = $property->getValue($api);
  206. $this->assertEquals($consumer_key, $credentials["consumerKey"]);
  207. $this->assertNotEquals($consumer_key, $this->consumer_key);
  208. }
  209. /**
  210. * Test invalid rights
  211. */
  212. public function testInvalidRight()
  213. {
  214. $this->setExpectedException(
  215. '\GuzzleHttp\Exception\ClientException'
  216. );
  217. $handlerStack = $this->client->getConfig('handler');
  218. $handlerStack->push(Middleware::mapResponse(function (Response $response) {
  219. $body = $response->getBody();
  220. $body->write('{\"message\":\"Invalid credentials\"}');
  221. return $response
  222. ->withStatus(403)
  223. ->withHeader('Content-Type', 'application/json; charset=utf-8')
  224. ->withHeader('Content-Length', 37)
  225. ->withBody($body);
  226. }));
  227. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  228. $invoker = self::getPrivateMethod('rawCall');
  229. $invoker->invokeArgs($api, ['GET', '/me']);
  230. }
  231. public function testGetConsumerKey()
  232. {
  233. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  234. $this->assertEquals($this->consumer_key, $api->getConsumerKey());
  235. }
  236. /**
  237. * Test GET query args
  238. */
  239. public function testGetQueryArgs()
  240. {
  241. $handlerStack = $this->client->getConfig('handler');
  242. $handlerStack->push(Middleware::mapRequest(function (Request $request) {
  243. if($request->getUri()->getPath() == "/1.0/auth/time") {
  244. return $request;
  245. }
  246. $query_string = $request->getUri()->getQuery();
  247. $this->assertEquals($query_string, 'applicationId=49&status=pendingValidation');
  248. $request = $request->withUri($request->getUri()
  249. ->withHost('httpbin.org')
  250. ->withPath('/')
  251. ->withQuery(''));
  252. return $request;
  253. }));
  254. //$handlerStack->push(Middleware::mapResponse(function (Response $response) {
  255. // return $response;
  256. //}));
  257. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  258. $api->get('/me/api/credential?applicationId=49', ['status' => 'pendingValidation']);
  259. }
  260. /**
  261. * Test GET overlapping query args
  262. */
  263. public function testGetOverlappingQueryArgs()
  264. {
  265. $handlerStack = $this->client->getConfig('handler');
  266. $handlerStack->push(Middleware::mapRequest(function (Request $request) {
  267. if($request->getUri()->getPath() == "/1.0/auth/time") {
  268. return $request;
  269. }
  270. $query_string = $request->getUri()->getQuery();
  271. $this->assertEquals($query_string, 'applicationId=49&status=expired&test=success');
  272. $request = $request->withUri($request->getUri()
  273. ->withHost('httpbin.org')
  274. ->withPath('/')
  275. ->withQuery(''));
  276. return $request;
  277. }));
  278. //$handlerStack->push(Middleware::mapResponse(function (Response $response) {
  279. // return $response;
  280. //}));
  281. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  282. $api->get('/me/api/credential?applicationId=49&status=pendingValidation', ['status' => 'expired', 'test' => "success"]);
  283. }
  284. /**
  285. * Test GET boolean query args
  286. */
  287. public function testGetBooleanQueryArgs()
  288. {
  289. $handlerStack = $this->client->getConfig('handler');
  290. $handlerStack->push(Middleware::mapRequest(function (Request $request) {
  291. if($request->getUri()->getPath() == "/1.0/auth/time") {
  292. return $request;
  293. }
  294. $query_string = $request->getUri()->getQuery();
  295. $this->assertEquals($query_string, 'dryRun=true&notDryRun=false');
  296. $request = $request->withUri($request->getUri()
  297. ->withHost('httpbin.org')
  298. ->withPath('/')
  299. ->withQuery(''));
  300. return $request;
  301. }));
  302. //$handlerStack->push(Middleware::mapResponse(function (Response $response) {
  303. // return $response;
  304. //}));
  305. $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
  306. $api->get('/me/api/credential', ['dryRun' => true, 'notDryRun' => false]);
  307. }
  308. }