PageRenderTime 42ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/tests/AwsClientTest.php

https://gitlab.com/github-cloud-corp/aws-sdk-php
PHP | 376 lines | 311 code | 37 blank | 28 comment | 7 complexity | 94d35b94c262a024d6e4f4353019426c MD5 | raw file
  1. <?php
  2. namespace Aws\Test;
  3. use Aws\Api\ErrorParser\JsonRpcErrorParser;
  4. use Aws\AwsClient;
  5. use Aws\CommandInterface;
  6. use Aws\Credentials\Credentials;
  7. use Aws\Ec2\Ec2Client;
  8. use Aws\Ses\SesClient;
  9. use Aws\MockHandler;
  10. use Aws\Result;
  11. use Aws\S3\S3Client;
  12. use Aws\Signature\SignatureV4;
  13. use Aws\Sts\StsClient;
  14. use Aws\WrappedHttpHandler;
  15. use GuzzleHttp\Promise\RejectedPromise;
  16. use Psr\Http\Message\RequestInterface;
  17. /**
  18. * @covers Aws\AwsClient
  19. */
  20. class AwsClientTest extends \PHPUnit_Framework_TestCase
  21. {
  22. use UsesServiceTrait;
  23. private function getApiProvider()
  24. {
  25. return function () {
  26. return [
  27. 'metadata' => [
  28. 'protocol' => 'query',
  29. 'endpointPrefix' => 'foo'
  30. ],
  31. 'shapes' => []
  32. ];
  33. };
  34. }
  35. public function testHasGetters()
  36. {
  37. $config = [
  38. 'handler' => function () {},
  39. 'credentials' => new Credentials('foo', 'bar'),
  40. 'region' => 'foo',
  41. 'endpoint' => 'http://us-east-1.foo.amazonaws.com',
  42. 'serializer' => function () {},
  43. 'api_provider' => $this->getApiProvider(),
  44. 'service' => 'foo',
  45. 'error_parser' => function () {},
  46. 'version' => 'latest'
  47. ];
  48. $client = new AwsClient($config);
  49. $this->assertSame($config['handler'], $this->readAttribute($client->getHandlerList(), 'handler'));
  50. $this->assertSame($config['credentials'], $client->getCredentials()->wait());
  51. $this->assertSame($config['region'], $client->getRegion());
  52. $this->assertEquals('foo', $client->getApi()->getEndpointPrefix());
  53. }
  54. /**
  55. * @expectedException \InvalidArgumentException
  56. * @expectedExceptionMessage Operation not found: Foo
  57. */
  58. public function testEnsuresOperationIsFoundWhenCreatingCommands()
  59. {
  60. $this->createClient()->getCommand('foo');
  61. }
  62. public function testReturnsCommandForOperation()
  63. {
  64. $client = $this->createClient([
  65. 'operations' => [
  66. 'foo' => [
  67. 'http' => ['method' => 'POST']
  68. ]
  69. ]
  70. ]);
  71. $this->assertInstanceOf(
  72. 'Aws\CommandInterface',
  73. $client->getCommand('foo')
  74. );
  75. }
  76. /**
  77. * @expectedException \Aws\S3\Exception\S3Exception
  78. * @expectedExceptionMessage Error executing "foo" on "http://us-east-1.foo.amazonaws.com"; AWS HTTP error: Baz Bar!
  79. */
  80. public function testWrapsExceptions()
  81. {
  82. $parser = function () {};
  83. $errorParser = new JsonRpcErrorParser();
  84. $h = new WrappedHttpHandler(
  85. function () {
  86. return new RejectedPromise([
  87. 'exception' => new \Exception('Baz Bar!'),
  88. 'connection_error' => true,
  89. 'response' => null
  90. ]);
  91. },
  92. $parser,
  93. $errorParser,
  94. 'Aws\S3\Exception\S3Exception'
  95. );
  96. $client = $this->createClient(
  97. ['operations' => ['foo' => ['http' => ['method' => 'POST']]]],
  98. ['handler' => $h]
  99. );
  100. $command = $client->getCommand('foo');
  101. $client->execute($command);
  102. }
  103. public function testChecksBothLowercaseAndUppercaseOperationNames()
  104. {
  105. $client = $this->createClient(['operations' => ['Foo' => [
  106. 'http' => ['method' => 'POST']
  107. ]]]);
  108. $this->assertInstanceOf(
  109. 'Aws\CommandInterface',
  110. $client->getCommand('foo')
  111. );
  112. }
  113. public function testReturnsAsyncResultsUsingMagicCall()
  114. {
  115. $client = $this->createClient(['operations' => ['Foo' => [
  116. 'http' => ['method' => 'POST']
  117. ]]]);
  118. $client->getHandlerList()->setHandler(new MockHandler([new Result()]));
  119. $result = $client->fooAsync();
  120. $this->assertInstanceOf('GuzzleHttp\Promise\PromiseInterface', $result);
  121. }
  122. public function testCanGetIterator()
  123. {
  124. $client = $this->getTestClient('s3');
  125. $this->assertInstanceOf(
  126. 'Generator',
  127. $client->getIterator('ListObjects', ['Bucket' => 'foobar'])
  128. );
  129. }
  130. public function testCanGetIteratorWithoutDefinedPaginator()
  131. {
  132. $client = $this->getTestClient('ec2');
  133. $data = ['foo', 'bar', 'baz'];
  134. $this->addMockResults($client, [new Result([
  135. 'Subnets' => [$data],
  136. ])]);
  137. $iterator = $client->getIterator('DescribeSubnets');
  138. $this->assertInstanceOf('Traversable', $iterator);
  139. foreach ($iterator as $iterated) {
  140. $this->assertSame($data, $iterated);
  141. }
  142. }
  143. /**
  144. * @expectedException \UnexpectedValueException
  145. */
  146. public function testGetIteratorFailsForMissingConfig()
  147. {
  148. $client = $this->createClient();
  149. $client->getIterator('ListObjects');
  150. }
  151. public function testCanGetPaginator()
  152. {
  153. $client = $this->createClient(['pagination' => [
  154. 'ListObjects' => [
  155. 'input_token' => 'foo',
  156. 'output_token' => 'foo',
  157. ]
  158. ]]);
  159. $this->assertInstanceOf(
  160. 'Aws\ResultPaginator',
  161. $client->getPaginator('ListObjects', ['Bucket' => 'foobar'])
  162. );
  163. }
  164. /**
  165. * @expectedException \UnexpectedValueException
  166. */
  167. public function testGetPaginatorFailsForMissingConfig()
  168. {
  169. $client = $this->createClient();
  170. $client->getPaginator('ListObjects');
  171. }
  172. /**
  173. * @expectedException \InvalidArgumentException
  174. * @expectedExceptionMessage Operation not found
  175. */
  176. public function testCanWaitSynchronously()
  177. {
  178. $client = $this->createClient(['waiters' => ['PigsFly' => [
  179. 'acceptors' => [],
  180. 'delay' => 1,
  181. 'maxAttempts' => 1,
  182. 'operation' => 'DescribePigs',
  183. ]]]);
  184. $client->waitUntil('PigsFly');
  185. }
  186. /**
  187. * @expectedException \UnexpectedValueException
  188. */
  189. public function testGetWaiterFailsForMissingConfig()
  190. {
  191. $client = $this->createClient();
  192. $client->waitUntil('PigsFly');
  193. }
  194. public function testGetWaiterPromisor()
  195. {
  196. $s3 = new S3Client(['region' => 'us-east-1', 'version' => 'latest']);
  197. $s3->getHandlerList()->setHandler(new MockHandler([
  198. new Result(['@metadata' => ['statusCode' => '200']])
  199. ]));
  200. $waiter = $s3->getWaiter('BucketExists', ['Bucket' => 'foo']);
  201. $this->assertInstanceOf('Aws\Waiter', $waiter);
  202. $promise = $waiter->promise();
  203. $promise->wait();
  204. }
  205. public function testCreatesClientsFromConstructor()
  206. {
  207. $client = new StsClient([
  208. 'region' => 'us-west-2',
  209. 'version' => 'latest'
  210. ]);
  211. $this->assertInstanceOf('Aws\Sts\StsClient', $client);
  212. $this->assertEquals('us-west-2', $client->getRegion());
  213. }
  214. public function testCanGetEndpoint()
  215. {
  216. $client = $this->createClient();
  217. $this->assertEquals(
  218. 'http://us-east-1.foo.amazonaws.com',
  219. $client->getEndpoint()
  220. );
  221. }
  222. public function testSignsRequestsUsingSigner()
  223. {
  224. $mock = new MockHandler([new Result([])]);
  225. $conf = [
  226. 'region' => 'us-east-1',
  227. 'version' => 'latest',
  228. 'credentials' => [
  229. 'key' => 'foo',
  230. 'secret' => 'bar'
  231. ],
  232. 'handler' => $mock
  233. ];
  234. $client = new Ec2Client($conf);
  235. $client->describeInstances();
  236. $request = $mock->getLastRequest();
  237. $str = \GuzzleHttp\Psr7\str($request);
  238. $this->assertContains('AWS4-HMAC-SHA256', $str);
  239. }
  240. public function testAllowsFactoryMethodForBc()
  241. {
  242. Ec2Client::factory([
  243. 'region' => 'us-west-2',
  244. 'version' => 'latest'
  245. ]);
  246. }
  247. public function testCanInstantiateAliasedClients()
  248. {
  249. new SesClient([
  250. 'region' => 'us-west-2',
  251. 'version' => 'latest'
  252. ]);
  253. }
  254. public function testCanGetSignatureProvider()
  255. {
  256. $client = $this->createClient([]);
  257. $ref = new \ReflectionMethod($client, 'getSignatureProvider');
  258. $ref->setAccessible(true);
  259. $provider = $ref->invoke($client);
  260. $this->assertTrue(is_callable($provider));
  261. }
  262. /**
  263. * @expectedException \RuntimeException
  264. * @expectedExceptionMessage Instances of Aws\AwsClient cannot be serialized
  265. */
  266. public function testDoesNotPermitSerialization()
  267. {
  268. $client = $this->createClient();
  269. \serialize($client);
  270. }
  271. public function testDoesNotSignOperationsWithAnAuthTypeOfNone()
  272. {
  273. $client = $this->createClient(
  274. [
  275. 'metadata' => [
  276. 'signatureVersion' => 'v4',
  277. ],
  278. 'operations' => [
  279. 'Foo' => [
  280. 'http' => ['method' => 'POST'],
  281. ],
  282. 'Bar' => [
  283. 'http' => ['method' => 'POST'],
  284. 'authtype' => 'none',
  285. ],
  286. ],
  287. ],
  288. [
  289. 'handler' => function (
  290. CommandInterface $command,
  291. RequestInterface $request
  292. ) {
  293. foreach (['Authorization', 'X-Amz-Date'] as $signatureHeader) {
  294. if ('Bar' === $command->getName()) {
  295. $this->assertFalse($request->hasHeader($signatureHeader));
  296. } else {
  297. $this->assertTrue($request->hasHeader($signatureHeader));
  298. }
  299. }
  300. return new Result;
  301. }
  302. ]
  303. );
  304. $client->foo();
  305. $client->bar();
  306. }
  307. private function createClient(array $service = [], array $config = [])
  308. {
  309. $apiProvider = function ($type) use ($service, $config) {
  310. if ($type == 'paginator') {
  311. return isset($service['pagination'])
  312. ? ['pagination' => $service['pagination']]
  313. : ['pagination' => []];
  314. } elseif ($type == 'waiter') {
  315. return isset($service['waiters'])
  316. ? ['waiters' => $service['waiters'], 'version' => 2]
  317. : ['waiters' => [], 'version' => 2];
  318. } else {
  319. if (!isset($service['metadata'])) {
  320. $service['metadata'] = [];
  321. }
  322. $service['metadata']['protocol'] = 'query';
  323. return $service;
  324. }
  325. };
  326. return new AwsClient($config + [
  327. 'handler' => new MockHandler(),
  328. 'credentials' => new Credentials('foo', 'bar'),
  329. 'signature' => new SignatureV4('foo', 'bar'),
  330. 'endpoint' => 'http://us-east-1.foo.amazonaws.com',
  331. 'region' => 'foo',
  332. 'service' => 'foo',
  333. 'api_provider' => $apiProvider,
  334. 'serializer' => function () {},
  335. 'error_parser' => function () {},
  336. 'version' => 'latest'
  337. ]);
  338. }
  339. }