UtilsTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <?php
  2. namespace AlibabaCloud\Tea\Utils\Tests;
  3. use AlibabaCloud\Tea\Model;
  4. use AlibabaCloud\Tea\Utils\Utils;
  5. use AlibabaCloud\Tea\Utils\Utils\ExtendsParameters;
  6. use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
  7. use GuzzleHttp\Psr7\Stream;
  8. use PHPUnit\Framework\TestCase;
  9. use Psr\Http\Message\StreamInterface;
  10. /**
  11. * @internal
  12. * @coversNothing
  13. */
  14. final class UtilsTest extends TestCase
  15. {
  16. public function getStream()
  17. {
  18. return new Stream(fopen('http://httpbin.org/get', 'r'));
  19. }
  20. public function testToBytes()
  21. {
  22. $this->assertEquals([
  23. 115, 116, 114, 105, 110, 103,
  24. ], Utils::toBytes('string'));
  25. $this->assertEquals([
  26. 115, 116, 114, 105, 110, 103,
  27. ], Utils::toBytes([
  28. 115, 116, 114, 105, 110, 103,
  29. ]));
  30. }
  31. public function testToString()
  32. {
  33. $this->assertEquals('string', Utils::toString([
  34. 115, 116, 114, 105, 110, 103,
  35. ]));
  36. $this->assertEquals('string', Utils::toString('string'));
  37. }
  38. public function testParseJSON()
  39. {
  40. $this->assertEquals([
  41. 'a' => 'b',
  42. ], Utils::parseJSON('{"a":"b"}'));
  43. }
  44. public function testReadAsBytes()
  45. {
  46. $bytes = Utils::readAsBytes($this->getStream());
  47. $this->assertEquals(123, $bytes[0]);
  48. }
  49. public function testReadAsString()
  50. {
  51. $string = Utils::readAsString($this->getStream());
  52. $this->assertEquals($string[0], '{');
  53. }
  54. public function testReadAsJSON()
  55. {
  56. $result = Utils::readAsJSON($this->getStream());
  57. $this->assertEquals('http://httpbin.org/get', $result['url']);
  58. }
  59. public function testGetNonce()
  60. {
  61. $nonce1 = Utils::getNonce();
  62. $nonce2 = Utils::getNonce();
  63. $this->assertNotEquals($nonce1, $nonce2);
  64. }
  65. public function testGetDateUTCString()
  66. {
  67. $gmdate = Utils::getDateUTCString();
  68. $now = time();
  69. $this->assertTrue(abs($now - strtotime($gmdate)) <= 1);
  70. }
  71. public function testDefaultString()
  72. {
  73. $this->assertEquals('', Utils::defaultString(null));
  74. $this->assertEquals('default', Utils::defaultString(null, 'default'));
  75. $this->assertEquals('real', Utils::defaultString('real', 'default'));
  76. }
  77. public function testDefaultNumber()
  78. {
  79. $this->assertEquals(0, Utils::defaultNumber(null));
  80. $this->assertEquals(0, Utils::defaultNumber(0, 3));
  81. $this->assertEquals(404, Utils::defaultNumber(null, 404));
  82. $this->assertEquals(200, Utils::defaultNumber(200, 404));
  83. }
  84. public function testToFormString()
  85. {
  86. $query = [
  87. 'foo' => 'bar',
  88. 'empty' => '',
  89. 'a' => null,
  90. 'withWhiteSpace' => 'a b',
  91. ];
  92. $this->assertEquals('foo=bar&empty=&withWhiteSpace=a%20b', Utils::toFormString($query));
  93. $object = json_decode(json_encode($query));
  94. $this->assertEquals('foo=bar&empty=&withWhiteSpace=a%20b', Utils::toFormString($object));
  95. }
  96. public function testToJSONString()
  97. {
  98. $object = new \stdClass();
  99. $this->assertJson(Utils::toJSONString($object));
  100. $this->assertEquals('[]', Utils::toJSONString([]));
  101. $this->assertEquals('["foo"]', Utils::toJSONString(['foo']));
  102. $this->assertEquals(
  103. '{"str":"test","number":1,"bool":false,"null":null,"chinese":"中文","http":"https://aliyun.com:8080/zh/中文.html"}',
  104. Utils::toJSONString([
  105. 'str' => 'test',
  106. 'number' => 1,
  107. 'bool' => FALSE,
  108. 'null' => null,
  109. 'chinese' => '中文',
  110. 'http' => 'https://aliyun.com:8080/zh/中文.html',
  111. ])
  112. );
  113. $this->assertEquals('1', Utils::toJSONString(1));
  114. $this->assertEquals('true', Utils::toJSONString(TRUE));
  115. $this->assertEquals('null', Utils::toJSONString(null));
  116. }
  117. public function testEmpty()
  118. {
  119. $this->assertTrue(Utils::_empty(''));
  120. $this->assertFalse(Utils::_empty('not empty'));
  121. }
  122. public function testEqualString()
  123. {
  124. $this->assertTrue(Utils::equalString('a', 'a'));
  125. $this->assertFalse(Utils::equalString('a', 'b'));
  126. }
  127. public function testEqualNumber()
  128. {
  129. $this->assertTrue(Utils::equalNumber(1, 1));
  130. $this->assertFalse(Utils::equalNumber(1, 2));
  131. }
  132. public function testIsUnset()
  133. {
  134. $this->assertTrue(Utils::isUnset($a));
  135. $b = 1;
  136. $this->assertFalse(Utils::isUnset($b));
  137. }
  138. public function testStringifyMapValue()
  139. {
  140. $this->assertEquals([], Utils::stringifyMapValue(null));
  141. $this->assertEquals([
  142. 'foo' => 'bar',
  143. 'null' => '',
  144. 'true' => 'true',
  145. 'false' => 'false',
  146. 'number' => '1000',
  147. ], Utils::stringifyMapValue([
  148. 'foo' => 'bar',
  149. 'null' => null,
  150. 'true' => true,
  151. 'false' => false,
  152. 'number' => 1000,
  153. ]));
  154. }
  155. public function testAnyifyMapValue()
  156. {
  157. $this->assertEquals([
  158. 'foo' => 'bar',
  159. 'null' => null,
  160. 'true' => true,
  161. 'false' => false,
  162. 'number' => 1000,
  163. ], Utils::anyifyMapValue([
  164. 'foo' => 'bar',
  165. 'null' => null,
  166. 'true' => true,
  167. 'false' => false,
  168. 'number' => 1000,
  169. ]));
  170. }
  171. public function testAssertAsBoolean()
  172. {
  173. $this->expectException(\InvalidArgumentException::class);
  174. $this->expectExceptionMessage('It is not a boolean value.');
  175. Utils::assertAsBoolean('true');
  176. try {
  177. $map = true;
  178. $this->assertEquals($map, Utils::assertAsBoolean($map));
  179. } catch (\Exception $e) {
  180. // should not be here
  181. $this->assertTrue(false);
  182. }
  183. }
  184. public function testAssertAsString()
  185. {
  186. $this->expectException(\InvalidArgumentException::class);
  187. $this->expectExceptionMessage('It is not a string value.');
  188. Utils::assertAsString(123);
  189. try {
  190. $map = '123';
  191. $this->assertEquals($map, Utils::assertAsString($map));
  192. } catch (\Exception $e) {
  193. // should not be here
  194. $this->assertTrue(false);
  195. }
  196. }
  197. public function testAssertAsBytes()
  198. {
  199. $this->expectException(\InvalidArgumentException::class);
  200. $this->expectExceptionMessage('It is not a bytes value.');
  201. // failed because $var is not array
  202. Utils::assertAsBytes('test');
  203. // failed because $var is map not array
  204. Utils::assertAsBytes(['foo' => 1]);
  205. // failed because item value is not int
  206. Utils::assertAsBytes(['1']);
  207. // failed because item value is out off range
  208. Utils::assertAsBytes([256]);
  209. try {
  210. // success
  211. $map = [1, 2, 3];
  212. $this->assertEquals($map, Utils::assertAsBytes($map));
  213. $this->assertEquals([
  214. 115, 116, 114, 105, 110, 103,
  215. ], Utils::assertAsBytes(Utils::toBytes('string')));
  216. } catch (\Exception $e) {
  217. // should not be here
  218. $this->assertTrue(false);
  219. }
  220. }
  221. public function testAssertAsNumber()
  222. {
  223. $this->expectException(\InvalidArgumentException::class);
  224. $this->expectExceptionMessage('It is not a number value.');
  225. Utils::assertAsNumber('is not number');
  226. try {
  227. $map = 123;
  228. $this->assertEquals($map, Utils::assertAsNumber($map));
  229. } catch (\Exception $e) {
  230. // should not be here
  231. $this->assertTrue(false);
  232. }
  233. }
  234. public function testAssertAsInteger()
  235. {
  236. $this->expectException(\InvalidArgumentException::class);
  237. $this->expectExceptionMessage('It is not a int value.');
  238. Utils::assertAsInteger('is not int');
  239. try {
  240. $map = 123;
  241. $this->assertEquals($map, Utils::assertAsInteger($map));
  242. } catch (\Exception $e) {
  243. // should not be here
  244. $this->assertTrue(false);
  245. }
  246. }
  247. public function testAssertAsMap()
  248. {
  249. $this->expectException(\InvalidArgumentException::class);
  250. $this->expectExceptionMessage('It is not a map value.');
  251. Utils::assertAsMap('is not array');
  252. try {
  253. $map = ['foo' => 'bar'];
  254. $this->assertEquals($map, Utils::assertAsMap($map));
  255. } catch (\Exception $e) {
  256. // should not be here
  257. $this->assertTrue(false);
  258. }
  259. }
  260. public function testAssertAsArray()
  261. {
  262. $this->expectException(\InvalidArgumentException::class);
  263. $this->expectExceptionMessage('It is not a array value.');
  264. Utils::assertAsArray('is not array');
  265. try {
  266. $map = ['foo'];
  267. $this->assertEquals($map, Utils::assertAsArray($map));
  268. } catch (\Exception $e) {
  269. // should not be here
  270. $this->assertTrue(false);
  271. }
  272. }
  273. public function testGetUserAgent()
  274. {
  275. $this->assertTrue(false !== strpos(Utils::getUserAgent('CustomUserAgent'), 'CustomUserAgent'));
  276. }
  277. public function testIs2xx()
  278. {
  279. $this->assertTrue(Utils::is2xx(200));
  280. $this->assertFalse(Utils::is2xx(300));
  281. }
  282. public function testIs3xx()
  283. {
  284. $this->assertTrue(Utils::is3xx(300));
  285. $this->assertFalse(Utils::is3xx(400));
  286. }
  287. public function testIs4xx()
  288. {
  289. $this->assertTrue(Utils::is4xx(400));
  290. $this->assertFalse(Utils::is4xx(500));
  291. }
  292. public function testIs5xx()
  293. {
  294. $this->assertTrue(Utils::is5xx(500));
  295. $this->assertFalse(Utils::is5xx(600));
  296. }
  297. public function testToMap()
  298. {
  299. $from = new RequestTest();
  300. $from->query = new RequestTestQuery([
  301. 'booleanParamInQuery' => true,
  302. 'mapParamInQuery' => [1, 2, 3],
  303. ]);
  304. $this->assertTrue($from->query->booleanParamInQuery);
  305. $this->assertEquals([1, 2, 3], $from->query->mapParamInQuery);
  306. $target = new RequestShrinkTest([]);
  307. $this->convert($from, $target);
  308. $this->assertEquals([
  309. 'BooleanParamInQuery' => true,
  310. 'MapParamInQuery' => [1, 2, 3],
  311. ], $target->query->toMap());
  312. $target->query->mapParamInQueryShrink = json_encode($from->query->mapParamInQuery);
  313. $this->assertEquals([
  314. 'BooleanParamInQuery' => true,
  315. 'MapParamInQuery' => '[1,2,3]',
  316. ], Utils::toMap($target->query));
  317. }
  318. public function testSleep()
  319. {
  320. $before = microtime(true) * 1000;
  321. Utils::sleep(1000);
  322. $after = microtime(true) * 1000;
  323. $sub = $after - $before;
  324. $this->assertTrue(990 <= $sub && $sub <= 1100);
  325. }
  326. public function testToArray()
  327. {
  328. $model = new RequestTest();
  329. $model->query = 'foo';
  330. $this->assertEquals([
  331. ['query' => 'foo'],
  332. ], Utils::toArray([$model]));
  333. $subModel = new RequestTest();
  334. $subModel->query = 'bar';
  335. $model->query = $subModel;
  336. $this->assertEquals([
  337. ['query' => ['query' => 'bar']],
  338. ], Utils::toArray([$model]));
  339. }
  340. public function testAssertAsReadable()
  341. {
  342. $s0 = Utils::assertAsReadable('string content');
  343. $this->assertTrue($s0 instanceof Stream);
  344. $s1 = Utils::assertAsReadable($s0);
  345. $this->assertEquals($s1, $s0);
  346. $this->expectException(\InvalidArgumentException::class);
  347. $this->expectExceptionMessage('It is not a stream value.');
  348. Utils::assertAsReadable(0);
  349. }
  350. public function testRuntimeOptions()
  351. {
  352. $opts = new RuntimeOptions([
  353. "autoretry" => false,
  354. "ignoreSSL" => false,
  355. "key" => "key",
  356. "cert" => "cert",
  357. "ca" => "ca",
  358. "maxAttempts" => 3,
  359. "backoffPolicy" => "backoffPolicy",
  360. "backoffPeriod" => 10,
  361. "readTimeout" => 3000,
  362. "connectTimeout" => 3000,
  363. "httpProxy" => "httpProxy",
  364. "httpsProxy" => "httpsProxy",
  365. "noProxy" => "noProxy",
  366. "maxIdleConns" => 300,
  367. "keepAlive" => true,
  368. "extendsParameters" => new ExtendsParameters([
  369. "headers" => ['key' => 'value'],
  370. "queries" => ['key' => 'value'],
  371. ]),
  372. ]);
  373. $this->assertEquals(false, $opts->autoretry);
  374. $this->assertEquals(false, $opts->ignoreSSL);
  375. $this->assertEquals("key", $opts->key);
  376. $this->assertEquals("cert", $opts->cert);
  377. $this->assertEquals("ca", $opts->ca);
  378. $this->assertEquals(3, $opts->maxAttempts);
  379. $this->assertEquals("backoffPolicy", $opts->backoffPolicy);
  380. $this->assertEquals(10, $opts->backoffPeriod);
  381. $this->assertEquals(3000, $opts->readTimeout);
  382. $this->assertEquals(3000, $opts->connectTimeout);
  383. $this->assertEquals("httpProxy", $opts->httpProxy);
  384. $this->assertEquals("httpsProxy", $opts->httpsProxy);
  385. $this->assertEquals("noProxy", $opts->noProxy);
  386. $this->assertEquals(300, $opts->maxIdleConns);
  387. $this->assertEquals(true, $opts->keepAlive);
  388. $this->assertEquals('value', $opts->extendsParameters->headers['key']);
  389. $this->assertEquals('value', $opts->extendsParameters->queries['key']);
  390. }
  391. private function convert($body, &$content)
  392. {
  393. $class = new \ReflectionClass($body);
  394. foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
  395. $name = $property->getName();
  396. if (!$property->isStatic()) {
  397. $value = $property->getValue($body);
  398. if ($value instanceof StreamInterface) {
  399. continue;
  400. }
  401. $content->{$name} = $value;
  402. }
  403. }
  404. }
  405. }
  406. /**
  407. * @internal
  408. * @coversNothing
  409. */
  410. class RequestTest extends Model
  411. {
  412. /**
  413. * @var RequestTestQuery
  414. */
  415. public $query;
  416. }
  417. /**
  418. * @internal
  419. * @coversNothing
  420. */
  421. class RequestShrinkTest extends Model
  422. {
  423. /**
  424. * @var RequestTestShrinkQuery
  425. */
  426. public $query;
  427. }
  428. class RequestTestQuery extends Model
  429. {
  430. /**
  431. * @description test
  432. *
  433. * @var bool
  434. */
  435. public $booleanParamInQuery;
  436. /**
  437. * @description test
  438. *
  439. * @var array
  440. */
  441. public $mapParamInQuery;
  442. protected $_name = [
  443. 'booleanParamInQuery' => 'BooleanParamInQuery',
  444. 'mapParamInQuery' => 'MapParamInQuery',
  445. ];
  446. public function toMap()
  447. {
  448. $res = [];
  449. if (null !== $this->booleanParamInQuery) {
  450. $res['BooleanParamInQuery'] = $this->booleanParamInQuery;
  451. }
  452. if (null !== $this->mapParamInQuery) {
  453. $res['MapParamInQuery'] = $this->mapParamInQuery;
  454. }
  455. return $res;
  456. }
  457. }
  458. class RequestTestShrinkQuery extends Model
  459. {
  460. /**
  461. * @description test
  462. *
  463. * @var float
  464. */
  465. public $booleanParamInQuery;
  466. /**
  467. * @description test
  468. *
  469. * @var string
  470. */
  471. public $mapParamInQueryShrink;
  472. protected $_name = [
  473. 'booleanParamInQuery' => 'BooleanParamInQuery',
  474. 'mapParamInQueryShrink' => 'MapParamInQuery',
  475. ];
  476. public function toMap()
  477. {
  478. $res = [];
  479. if (null !== $this->booleanParamInQuery) {
  480. $res['BooleanParamInQuery'] = $this->booleanParamInQuery;
  481. }
  482. if (null !== $this->mapParamInQueryShrink) {
  483. $res['MapParamInQuery'] = $this->mapParamInQueryShrink;
  484. }
  485. return $res;
  486. }
  487. }