UtilsTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. /**
  3. * Utilities' tests
  4. */
  5. require_once 'application/Utils.php';
  6. require_once 'application/Languages.php';
  7. require_once 'tests/utils/ReferenceSessionIdHashes.php';
  8. // Initialize reference data before PHPUnit starts a session
  9. ReferenceSessionIdHashes::genAllHashes();
  10. /**
  11. * Unitary tests for Shaarli utilities
  12. */
  13. class UtilsTest extends PHPUnit_Framework_TestCase
  14. {
  15. // Session ID hashes
  16. protected static $sidHashes = null;
  17. // Log file
  18. protected static $testLogFile = 'tests.log';
  19. // Expected log date format
  20. protected static $dateFormat = 'Y/m/d H:i:s';
  21. /**
  22. * @var string Save the current timezone.
  23. */
  24. protected static $defaultTimeZone;
  25. /**
  26. * Assign reference data
  27. */
  28. public static function setUpBeforeClass()
  29. {
  30. self::$sidHashes = ReferenceSessionIdHashes::getHashes();
  31. self::$defaultTimeZone = date_default_timezone_get();
  32. // Timezone without DST for test consistency
  33. date_default_timezone_set('Africa/Nairobi');
  34. }
  35. /**
  36. * Reset the timezone
  37. */
  38. public static function tearDownAfterClass()
  39. {
  40. date_default_timezone_set(self::$defaultTimeZone);
  41. }
  42. /**
  43. * Resets test data before each test
  44. */
  45. protected function setUp()
  46. {
  47. if (file_exists(self::$testLogFile)) {
  48. unlink(self::$testLogFile);
  49. }
  50. }
  51. /**
  52. * Returns a list of the elements from the last logged entry
  53. *
  54. * @return list (date, ip address, message)
  55. */
  56. protected function getLastLogEntry()
  57. {
  58. $logFile = file(self::$testLogFile);
  59. return explode(' - ', trim(array_pop($logFile), PHP_EOL));
  60. }
  61. /**
  62. * Log a message to a file - IPv4 client address
  63. */
  64. public function testLogmIp4()
  65. {
  66. $logMessage = 'IPv4 client connected';
  67. logm(self::$testLogFile, '127.0.0.1', $logMessage);
  68. list($date, $ip, $message) = $this->getLastLogEntry();
  69. $this->assertInstanceOf(
  70. 'DateTime',
  71. DateTime::createFromFormat(self::$dateFormat, $date)
  72. );
  73. $this->assertTrue(
  74. filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false
  75. );
  76. $this->assertEquals($logMessage, $message);
  77. }
  78. /**
  79. * Log a message to a file - IPv6 client address
  80. */
  81. public function testLogmIp6()
  82. {
  83. $logMessage = 'IPv6 client connected';
  84. logm(self::$testLogFile, '2001:db8::ff00:42:8329', $logMessage);
  85. list($date, $ip, $message) = $this->getLastLogEntry();
  86. $this->assertInstanceOf(
  87. 'DateTime',
  88. DateTime::createFromFormat(self::$dateFormat, $date)
  89. );
  90. $this->assertTrue(
  91. filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false
  92. );
  93. $this->assertEquals($logMessage, $message);
  94. }
  95. /**
  96. * Represent a link by its hash
  97. */
  98. public function testSmallHash()
  99. {
  100. $this->assertEquals('CyAAJw', smallHash('http://test.io'));
  101. $this->assertEquals(6, strlen(smallHash('https://github.com')));
  102. }
  103. /**
  104. * Look for a substring at the beginning of a string
  105. */
  106. public function testStartsWithCaseInsensitive()
  107. {
  108. $this->assertTrue(startsWith('Lorem ipsum', 'lorem', false));
  109. $this->assertTrue(startsWith('Lorem ipsum', 'LoReM i', false));
  110. }
  111. /**
  112. * Look for a substring at the beginning of a string (case-sensitive)
  113. */
  114. public function testStartsWithCaseSensitive()
  115. {
  116. $this->assertTrue(startsWith('Lorem ipsum', 'Lorem', true));
  117. $this->assertFalse(startsWith('Lorem ipsum', 'lorem', true));
  118. $this->assertFalse(startsWith('Lorem ipsum', 'LoReM i', true));
  119. }
  120. /**
  121. * Look for a substring at the beginning of a string (Unicode)
  122. */
  123. public function testStartsWithSpecialChars()
  124. {
  125. $this->assertTrue(startsWith('å!ùµ', 'å!', false));
  126. $this->assertTrue(startsWith('µ$åù', 'µ$', true));
  127. }
  128. /**
  129. * Look for a substring at the end of a string
  130. */
  131. public function testEndsWithCaseInsensitive()
  132. {
  133. $this->assertTrue(endsWith('Lorem ipsum', 'ipsum', false));
  134. $this->assertTrue(endsWith('Lorem ipsum', 'm IpsUM', false));
  135. }
  136. /**
  137. * Look for a substring at the end of a string (case-sensitive)
  138. */
  139. public function testEndsWithCaseSensitive()
  140. {
  141. $this->assertTrue(endsWith('lorem Ipsum', 'Ipsum', true));
  142. $this->assertFalse(endsWith('lorem Ipsum', 'ipsum', true));
  143. $this->assertFalse(endsWith('lorem Ipsum', 'M IPsuM', true));
  144. }
  145. /**
  146. * Look for a substring at the end of a string (Unicode)
  147. */
  148. public function testEndsWithSpecialChars()
  149. {
  150. $this->assertTrue(endsWith('å!ùµ', 'ùµ', false));
  151. $this->assertTrue(endsWith('µ$åù', 'åù', true));
  152. }
  153. /**
  154. * Check valid date strings, according to a DateTime format
  155. */
  156. public function testCheckValidDateFormat()
  157. {
  158. $this->assertTrue(checkDateFormat('Ymd', '20150627'));
  159. $this->assertTrue(checkDateFormat('Y-m-d', '2015-06-27'));
  160. }
  161. /**
  162. * Check erroneous date strings, according to a DateTime format
  163. */
  164. public function testCheckInvalidDateFormat()
  165. {
  166. $this->assertFalse(checkDateFormat('Ymd', '2015'));
  167. $this->assertFalse(checkDateFormat('Y-m-d', '2015-06'));
  168. $this->assertFalse(checkDateFormat('Ymd', 'DeLorean'));
  169. }
  170. /**
  171. * Test generate location with valid data.
  172. */
  173. public function testGenerateLocation() {
  174. $ref = 'http://localhost/?test';
  175. $this->assertEquals($ref, generateLocation($ref, 'localhost'));
  176. $ref = 'http://localhost:8080/?test';
  177. $this->assertEquals($ref, generateLocation($ref, 'localhost:8080'));
  178. $ref = '?localreferer#hash';
  179. $this->assertEquals($ref, generateLocation($ref, 'localhost:8080'));
  180. }
  181. /**
  182. * Test generate location - anti loop.
  183. */
  184. public function testGenerateLocationLoop() {
  185. $ref = 'http://localhost/?test';
  186. $this->assertEquals('?', generateLocation($ref, 'localhost', array('test')));
  187. }
  188. /**
  189. * Test generate location - from other domain.
  190. */
  191. public function testGenerateLocationOut() {
  192. $ref = 'http://somewebsite.com/?test';
  193. $this->assertEquals('?', generateLocation($ref, 'localhost'));
  194. }
  195. /**
  196. * Test is_session_id_valid with a valid ID - TEST ALL THE HASHES!
  197. *
  198. * This tests extensively covers all hash algorithms / bit representations
  199. */
  200. public function testIsAnyHashSessionIdValid()
  201. {
  202. foreach (self::$sidHashes as $algo => $bpcs) {
  203. foreach ($bpcs as $bpc => $hash) {
  204. $this->assertTrue(is_session_id_valid($hash));
  205. }
  206. }
  207. }
  208. /**
  209. * Test is_session_id_valid with a valid ID - SHA-1 hashes
  210. */
  211. public function testIsSha1SessionIdValid()
  212. {
  213. $this->assertTrue(is_session_id_valid(sha1('shaarli')));
  214. }
  215. /**
  216. * Test is_session_id_valid with a valid ID - SHA-256 hashes
  217. */
  218. public function testIsSha256SessionIdValid()
  219. {
  220. $this->assertTrue(is_session_id_valid(hash('sha256', 'shaarli')));
  221. }
  222. /**
  223. * Test is_session_id_valid with a valid ID - SHA-512 hashes
  224. */
  225. public function testIsSha512SessionIdValid()
  226. {
  227. $this->assertTrue(is_session_id_valid(hash('sha512', 'shaarli')));
  228. }
  229. /**
  230. * Test is_session_id_valid with invalid IDs.
  231. */
  232. public function testIsSessionIdInvalid()
  233. {
  234. $this->assertFalse(is_session_id_valid(''));
  235. $this->assertFalse(is_session_id_valid(array()));
  236. $this->assertFalse(
  237. is_session_id_valid('c0ZqcWF3VFE2NmJBdm1HMVQ0ZHJ3UmZPbTFsNGhkNHI=')
  238. );
  239. }
  240. /**
  241. * Test generateSecretApi.
  242. */
  243. public function testGenerateSecretApi()
  244. {
  245. $this->assertEquals(12, strlen(generate_api_secret('foo', 'bar')));
  246. }
  247. /**
  248. * Test generateSecretApi with invalid parameters.
  249. */
  250. public function testGenerateSecretApiInvalid()
  251. {
  252. $this->assertFalse(generate_api_secret('', ''));
  253. $this->assertFalse(generate_api_secret(false, false));
  254. }
  255. /**
  256. * Test normalize_spaces.
  257. */
  258. public function testNormalizeSpace()
  259. {
  260. $str = ' foo bar is important ';
  261. $this->assertEquals('foo bar is important', normalize_spaces($str));
  262. $this->assertEquals('foo', normalize_spaces('foo'));
  263. $this->assertEquals('', normalize_spaces(''));
  264. $this->assertEquals(null, normalize_spaces(null));
  265. }
  266. /**
  267. * Test arrays_combine
  268. */
  269. public function testCartesianProductGenerator()
  270. {
  271. $arr = [['ab', 'cd'], ['ef', 'gh'], ['ij', 'kl'], ['m']];
  272. $expected = [
  273. ['ab', 'ef', 'ij', 'm'],
  274. ['ab', 'ef', 'kl', 'm'],
  275. ['ab', 'gh', 'ij', 'm'],
  276. ['ab', 'gh', 'kl', 'm'],
  277. ['cd', 'ef', 'ij', 'm'],
  278. ['cd', 'ef', 'kl', 'm'],
  279. ['cd', 'gh', 'ij', 'm'],
  280. ['cd', 'gh', 'kl', 'm'],
  281. ];
  282. $this->assertEquals($expected, iterator_to_array(cartesian_product_generator($arr)));
  283. }
  284. /**
  285. * Test date_format() with invalid parameter.
  286. */
  287. public function testDateFormatInvalid()
  288. {
  289. $this->assertFalse(format_date([]));
  290. $this->assertFalse(format_date(null));
  291. }
  292. /**
  293. * Test is_integer_mixed with valid values
  294. */
  295. public function testIsIntegerMixedValid()
  296. {
  297. $this->assertTrue(is_integer_mixed(12));
  298. $this->assertTrue(is_integer_mixed('12'));
  299. $this->assertTrue(is_integer_mixed(-12));
  300. $this->assertTrue(is_integer_mixed('-12'));
  301. $this->assertTrue(is_integer_mixed(0));
  302. $this->assertTrue(is_integer_mixed('0'));
  303. $this->assertTrue(is_integer_mixed(0x0a));
  304. }
  305. /**
  306. * Test is_integer_mixed with invalid values
  307. */
  308. public function testIsIntegerMixedInvalid()
  309. {
  310. $this->assertFalse(is_integer_mixed(true));
  311. $this->assertFalse(is_integer_mixed(false));
  312. $this->assertFalse(is_integer_mixed([]));
  313. $this->assertFalse(is_integer_mixed(['test']));
  314. $this->assertFalse(is_integer_mixed([12]));
  315. $this->assertFalse(is_integer_mixed(new DateTime()));
  316. $this->assertFalse(is_integer_mixed('0x0a'));
  317. $this->assertFalse(is_integer_mixed('12k'));
  318. $this->assertFalse(is_integer_mixed('k12'));
  319. $this->assertFalse(is_integer_mixed(''));
  320. }
  321. /**
  322. * Test return_bytes
  323. */
  324. public function testReturnBytes()
  325. {
  326. $this->assertEquals(2 * 1024, return_bytes('2k'));
  327. $this->assertEquals(2 * 1024, return_bytes('2K'));
  328. $this->assertEquals(2 * (pow(1024, 2)), return_bytes('2m'));
  329. $this->assertEquals(2 * (pow(1024, 2)), return_bytes('2M'));
  330. $this->assertEquals(2 * (pow(1024, 3)), return_bytes('2g'));
  331. $this->assertEquals(2 * (pow(1024, 3)), return_bytes('2G'));
  332. $this->assertEquals(374, return_bytes('374'));
  333. $this->assertEquals(374, return_bytes(374));
  334. $this->assertEquals(0, return_bytes('0'));
  335. $this->assertEquals(0, return_bytes(0));
  336. $this->assertEquals(-1, return_bytes('-1'));
  337. $this->assertEquals(-1, return_bytes(-1));
  338. $this->assertEquals('', return_bytes(''));
  339. }
  340. /**
  341. * Test human_bytes
  342. */
  343. public function testHumanBytes()
  344. {
  345. $this->assertEquals('2kiB', human_bytes(2 * 1024));
  346. $this->assertEquals('2kiB', human_bytes(strval(2 * 1024)));
  347. $this->assertEquals('2MiB', human_bytes(2 * (pow(1024, 2))));
  348. $this->assertEquals('2MiB', human_bytes(strval(2 * (pow(1024, 2)))));
  349. $this->assertEquals('2GiB', human_bytes(2 * (pow(1024, 3))));
  350. $this->assertEquals('2GiB', human_bytes(strval(2 * (pow(1024, 3)))));
  351. $this->assertEquals('374B', human_bytes(374));
  352. $this->assertEquals('374B', human_bytes('374'));
  353. $this->assertEquals('232kiB', human_bytes(237481));
  354. $this->assertEquals('Unlimited', human_bytes('0'));
  355. $this->assertEquals('Unlimited', human_bytes(0));
  356. $this->assertEquals('Setting not set', human_bytes(''));
  357. }
  358. /**
  359. * Test get_max_upload_size with formatting
  360. */
  361. public function testGetMaxUploadSize()
  362. {
  363. $this->assertEquals('1MiB', get_max_upload_size(2097152, '1024k'));
  364. $this->assertEquals('1MiB', get_max_upload_size('1m', '2m'));
  365. $this->assertEquals('100B', get_max_upload_size(100, 100));
  366. }
  367. /**
  368. * Test get_max_upload_size without formatting
  369. */
  370. public function testGetMaxUploadSizeRaw()
  371. {
  372. $this->assertEquals('1048576', get_max_upload_size(2097152, '1024k', false));
  373. $this->assertEquals('1048576', get_max_upload_size('1m', '2m', false));
  374. $this->assertEquals('100', get_max_upload_size(100, 100, false));
  375. }
  376. }