UtilsTest.php 15 KB

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