9829b266d347de3f9dd220d11c7d0bda1c97d5df
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Common / SizeTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Common;
4
5 use Drupal\Component\Utility\Bytes;
6 use Drupal\KernelTests\KernelTestBase;
7
8 /**
9  * Parse a predefined amount of bytes and compare the output with the expected
10  * value.
11  *
12  * @group Common
13  */
14 class SizeTest extends KernelTestBase {
15   protected $exactTestCases;
16   protected $roundedTestCases;
17
18   protected function setUp() {
19     parent::setUp();
20     $kb = Bytes::KILOBYTE;
21     $this->exactTestCases = [
22       '1 byte' => 1,
23       '1 KB'   => $kb,
24       '1 MB'   => $kb * $kb,
25       '1 GB'   => $kb * $kb * $kb,
26       '1 TB'   => $kb * $kb * $kb * $kb,
27       '1 PB'   => $kb * $kb * $kb * $kb * $kb,
28       '1 EB'   => $kb * $kb * $kb * $kb * $kb * $kb,
29       '1 ZB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
30       '1 YB'   => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
31     ];
32     $this->roundedTestCases = [
33       '2 bytes' => 2,
34       '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
35       round(3623651 / ($this->exactTestCases['1 MB']), 2) . ' MB' => 3623651, // megabytes
36       round(67234178751368124 / ($this->exactTestCases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
37       round(235346823821125814962843827 / ($this->exactTestCases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
38     ];
39   }
40
41   /**
42    * Checks that format_size() returns the expected string.
43    */
44   public function testCommonFormatSize() {
45     foreach ([$this->exactTestCases, $this->roundedTestCases] as $test_cases) {
46       foreach ($test_cases as $expected => $input) {
47         $this->assertEqual(
48           ($result = format_size($input, NULL)),
49           $expected,
50           $expected . ' == ' . $result . ' (' . $input . ' bytes)'
51         );
52       }
53     }
54   }
55
56   /**
57    * Cross-tests Bytes::toInt() and format_size().
58    */
59   public function testCommonParseSizeFormatSize() {
60     foreach ($this->exactTestCases as $size) {
61       $this->assertEqual(
62         $size,
63         ($parsed_size = Bytes::toInt($string = format_size($size, NULL))),
64         $size . ' == ' . $parsed_size . ' (' . $string . ')'
65       );
66     }
67   }
68
69 }