. namespace core; use lang_string; /** * Unit tests for (some of) ../moodlelib.php. * * @package core * @category phpunit * @copyright © 2006 The Open University * @author T.J.Hunt@open.ac.uk * @author nicolas@moodle.com */ final class moodlelib_test extends \advanced_testcase { /** * Define a local decimal separator. * * It is not possible to directly change the result of get_string in * a unit test. Instead, we create a language pack for language 'xx' in * dataroot and make langconfig.php with the string we need to change. * The default example separator used here is 'X'; on PHP 5.3 and before this * must be a single byte character due to PHP bug/limitation in * number_format, so you can't use UTF-8 characters. * * @param string $decsep Separator character. Defaults to `'X'`. */ protected function define_local_decimal_separator(string $decsep = 'X') { global $SESSION, $CFG; $SESSION->lang = 'xx'; $langconfig = "dataroot . '/lang/xx'; check_dir_exists($langfolder); file_put_contents($langfolder . '/langconfig.php', $langconfig); // Ensure the new value is picked up and not taken from the cache. $stringmanager = get_string_manager(); $stringmanager->reset_caches(true); } public function test_cleanremoteaddr(): void { // IPv4. $this->assertNull(cleanremoteaddr('1023.121.234.1')); $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 ')); // IPv6. $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0')); $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh')); $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1')); $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true)); $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true)); $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true)); $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true)); $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false)); $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false)); $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false)); $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true)); } public function test_address_in_subnet(): void { // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask). $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32')); $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32')); $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0')); $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24')); $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24')); $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30')); $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30')); $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128')); $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128')); $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0')); $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128')); $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120')); $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120')); $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112')); $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112')); $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112')); // Fixed input. $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24')); $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126')); // Incorrect input. $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2')); $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64')); $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24')); $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24')); $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0')); $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0')); $this->assertFalse(address_in_subnet('::1', '::aa:0/-5')); $this->assertFalse(address_in_subnet('::1', '::aa:0/130')); $this->assertFalse(address_in_subnet('x:1', '::aa:0/130')); $this->assertFalse(address_in_subnet('::1', '::ax:0/130')); // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group). $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14')); $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14')); $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14')); $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14')); $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14')); $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14')); $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14')); $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe')); $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe')); $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe')); $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe')); $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe')); $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe')); $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe')); // Fixed input. $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 ')); $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe ')); // Incorrect input. $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14')); $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256')); $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256')); // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-). $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12')); $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13')); $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.')); $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234')); $this->assertTrue(address_in_subnet('123.121.234.12', '123.121')); $this->assertTrue(address_in_subnet('123.121.234.12', '123')); $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.')); $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234')); $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab')); $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc')); $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba')); $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:')); $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:')); // Multiple subnets. $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30')); $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30')); $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30')); $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30')); // Other incorrect input. $this->assertFalse(address_in_subnet('123.123.123.123', '')); } public function test_fix_utf8(): void { // Make sure valid data including other types is not changed. $this->assertSame(null, fix_utf8(null)); $this->assertSame(1, fix_utf8(1)); $this->assertSame(1.1, fix_utf8(1.1)); $this->assertSame(true, fix_utf8(true)); $this->assertSame('', fix_utf8('')); $this->assertSame('abc', fix_utf8('abc')); $array = array('do', 're', 'mi'); $this->assertSame($array, fix_utf8($array)); $object = new \stdClass(); $object->a = 'aa'; $object->b = 'bb'; $this->assertEquals($object, fix_utf8($object)); // valid utf8 string $this->assertSame("žlutý koníček přeskočil potůček \n\t\r", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0")); // Invalid utf8 string. $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.'); $this->assertSame('Hello ', fix_utf8('Hello ￿')); } public function test_optional_param(): void { global $CFG; $_POST['username'] = 'post_user'; $_GET['username'] = 'get_user'; $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW)); unset($_POST['username']); $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW)); unset($_GET['username']); $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW)); // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3. $_POST['username'] = array('a'=>'a'); try { optional_param('username', 'default_user', PARAM_RAW); $this->fail('coding_exception expected'); } catch (\coding_exception $e) { } } public function test_optional_param_array(): void { global $CFG; $_POST['username'] = array('a'=>'post_user'); $_GET['username'] = array('a'=>'get_user'); $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW)); unset($_POST['username']); $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW)); unset($_GET['username']); $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW)); // Do not allow nested arrays. try { $_POST['username'] = array('a'=>array('b'=>'post_user')); optional_param_array('username', array('a'=>'default_user'), PARAM_RAW); $this->fail('coding_exception expected'); } catch (\coding_exception $ex) { $this->assertTrue(true); } // Do not allow non-arrays. $_POST['username'] = 'post_user'; $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW)); $this->assertDebuggingCalled(); // Make sure array keys are sanitised. $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user'); $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW)); $this->assertDebuggingCalled(); } public function test_required_param(): void { $_POST['username'] = 'post_user'; $_GET['username'] = 'get_user'; $this->assertSame('post_user', required_param('username', PARAM_RAW)); unset($_POST['username']); $this->assertSame('get_user', required_param('username', PARAM_RAW)); unset($_GET['username']); try { $this->assertSame('default_user', required_param('username', PARAM_RAW)); $this->fail('moodle_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('moodle_exception', $ex); } try { required_param('', PARAM_RAW); $this->fail('coding_exception expected'); } catch (\moodle_exception $ex) { } // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3. $_POST['username'] = array('a'=>'a'); try { required_param('username', PARAM_RAW); $this->fail('coding_exception expected'); } catch (\coding_exception $e) { } } public function test_required_param_array(): void { global $CFG; $_POST['username'] = array('a'=>'post_user'); $_GET['username'] = array('a'=>'get_user'); $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW)); unset($_POST['username']); $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW)); // Do not allow nested arrays. try { $_POST['username'] = array('a'=>array('b'=>'post_user')); required_param_array('username', PARAM_RAW); $this->fail('coding_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } // Do not allow non-arrays. try { $_POST['username'] = 'post_user'; required_param_array('username', PARAM_RAW); $this->fail('moodle_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('moodle_exception', $ex); } // Make sure array keys are sanitised. $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user'); $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW)); $this->assertDebuggingCalled(); } /** * @covers \core\param * @covers \clean_param */ public function test_clean_param(): void { // Forbid objects and arrays. try { clean_param(array('x', 'y'), PARAM_RAW); $this->fail('coding_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } try { $param = new \stdClass(); $param->id = 1; clean_param($param, PARAM_RAW); $this->fail('coding_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } // Require correct type. try { clean_param('x', 'xxxxxx'); $this->fail('moodle_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('moodle_exception', $ex); } } /** * @covers \core\param * @covers \clean_param */ public function test_clean_param_array(): void { $this->assertSame(array(), clean_param_array(null, PARAM_RAW)); $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW)); $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true)); // Require correct type. try { clean_param_array(array('x'), 'xxxxxx'); $this->fail('moodle_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('moodle_exception', $ex); } try { clean_param_array(array('x', array('y')), PARAM_RAW); $this->fail('coding_exception expected'); } catch (\moodle_exception $ex) { $this->assertInstanceOf('coding_exception', $ex); } // Test recursive. } /** * @covers \core\param * @covers \clean_param */ public function test_clean_param_raw(): void { $this->assertSame( '#()*#,9789\'".,<42897>assertSame(null, clean_param(null, PARAM_RAW)); } /** * @covers \core\param * @covers \clean_param */ public function test_clean_param_trim(): void { $this->assertSame('Frog toad', clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED)); $this->assertSame('', clean_param(null, PARAM_RAW_TRIMMED)); } /** * @covers \core\param * @covers \clean_param */ public function test_clean_param_clean(): void { // PARAM_CLEAN is an ugly hack, do not use in new code (skodak), // instead use more specific type, or submit sothing that can be verified properly. $this->assertSame('xx', clean_param('xx Boop the Snoot. EOT; // The counts here should match MS Word and Libre Office. return [ [0, ''], [4, 'one two three four'], [1, "a'b"], [1, '1+1=2'], [1, ' one-sided '], [2, 'one two'], [1, 'email@example.com'], [2, 'first\part second/part'], [4, '

one two

three four

'], [4, '

one two
three four

'], [4, '

one two
three four

'], // XHTML style. [3, ' one ... three '], [1, 'just...one'], [3, ' one & three '], [1, 'just&one'], [2, 'em—dash'], [2, 'en–dash'], [4, '1³ £2 €3.45 $6,789'], [2, 'ブルース カンベッル'], // MS word counts this as 11, but we don't handle that yet. [4, '

one two

three four

'], [4, '

one two


three four

'], [4, '

one

four.

'], [1, '

emphasis.

'], [1, '

emphasis.

'], [1, '

emphasis.

'], [1, '

emphasis.

'], [2, "one\ntwo"], [2, "one\rtwo"], [2, "one\ttwo"], [2, "one\vtwo"], [2, "one\ftwo"], [1, "SO42-"], [6, '4+4=8 i.e. O(1) a,b,c,d I’m black&blue_really'], [1, 'ab'], [1, 'ab', FORMAT_PLAIN], [1, 'ab', FORMAT_HTML], [1, 'ab', FORMAT_MOODLE], [1, 'ab', FORMAT_MARKDOWN], [1, 'aa pokus'], [2, 'aa pokus', FORMAT_HTML], [6, $copypasted], [6, $copypasted, FORMAT_PLAIN], [3, $copypasted, FORMAT_HTML], [3, $copypasted, FORMAT_MOODLE], ]; } /** * Test function {@see count_letters()}. * * @dataProvider count_letters_testcases * @param int $expectedcount number of characters in $string. * @param string $string the test string to count the letters of. * @param int|null $format */ public function test_count_letters(int $expectedcount, string $string, $format = null): void { $this->assertEquals($expectedcount, count_letters($string, $format), "'$string' with format '$format' does not match count $expectedcount"); } /** * Data provider for {@see count_letters_testcases}. * * @return array of test cases. */ public function count_letters_testcases(): array { return [ [0, ''], [1, 'x'], [1, '&'], [4, '

frog

'], [4, '

frog

', FORMAT_PLAIN], [4, '

frog

', FORMAT_MOODLE], [4, '

frog

', FORMAT_HTML], [4, '

frog

', FORMAT_MARKDOWN], [2, 'aa pokus'], [7, 'aa pokus', FORMAT_HTML], ]; } /** * Tests the getremoteaddr() function. */ public function test_getremoteaddr(): void { global $CFG; $this->resetAfterTest(); $CFG->getremoteaddrconf = null; // Use default value, GETREMOTEADDR_SKIP_DEFAULT. $noip = getremoteaddr('1.1.1.1'); $this->assertEquals('1.1.1.1', $noip); $remoteaddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; $singleip = getremoteaddr(); $this->assertEquals('127.0.0.1', $singleip); $_SERVER['REMOTE_ADDR'] = $remoteaddr; // Restore server value. $CFG->getremoteaddrconf = 0; // Don't skip any source. $noip = getremoteaddr('1.1.1.1'); $this->assertEquals('1.1.1.1', $noip); // Populate all $_SERVER values to review order. $ipsources = [ 'HTTP_CLIENT_IP' => '2.2.2.2', 'HTTP_X_FORWARDED_FOR' => '3.3.3.3', 'REMOTE_ADDR' => '4.4.4.4', ]; $originalvalues = []; foreach ($ipsources as $source => $ip) { $originalvalues[$source] = isset($_SERVER[$source]) ? $_SERVER[$source] : null; // Saving data to restore later. $_SERVER[$source] = $ip; } foreach ($ipsources as $source => $expectedip) { $ip = getremoteaddr(); $this->assertEquals($expectedip, $ip); unset($_SERVER[$source]); // Removing the value so next time we get the following ip. } // Restore server values. foreach ($originalvalues as $source => $ip) { $_SERVER[$source] = $ip; } // All $_SERVER values have been removed, we should get the default again. $noip = getremoteaddr('1.1.1.1'); $this->assertEquals('1.1.1.1', $noip); $CFG->getremoteaddrconf = GETREMOTEADDR_SKIP_HTTP_CLIENT_IP; $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null; $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $noip = getremoteaddr('1.1.1.1'); $this->assertEquals('1.1.1.1', $noip); $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; $noip = getremoteaddr(); $this->assertEquals('0.0.0.0', $noip); $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1'; $singleip = getremoteaddr(); $this->assertEquals('127.0.0.1', $singleip); $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2'; $twoip = getremoteaddr(); $this->assertEquals('127.0.0.2', $twoip); $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2,127.0.0.3'; $threeip = getremoteaddr(); $this->assertEquals('127.0.0.3', $threeip); $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2:65535'; $portip = getremoteaddr(); $this->assertEquals('127.0.0.2', $portip); $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0:0:0:0:0:0:0:2'; $portip = getremoteaddr(); $this->assertEquals('0:0:0:0:0:0:0:2', $portip); $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0::2'; $portip = getremoteaddr(); $this->assertEquals('0:0:0:0:0:0:0:2', $portip); $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,[0:0:0:0:0:0:0:2]:65535'; $portip = getremoteaddr(); $this->assertEquals('0:0:0:0:0:0:0:2', $portip); $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor; } /** * Test function for creation of random strings. */ public function test_random_string(): void { $pool = 'a-zA-Z0-9'; $result = random_string(10); $this->assertSame(10, strlen($result)); $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $this->assertNotSame($result, random_string(10)); $result = random_string(21); $this->assertSame(21, strlen($result)); $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $this->assertNotSame($result, random_string(21)); $result = random_string(666); $this->assertSame(666, strlen($result)); $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $result = random_string(); $this->assertSame(15, strlen($result)); $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $this->assertDebuggingNotCalled(); } /** * Test function for creation of complex random strings. */ public function test_complex_random_string(): void { $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/'); $result = complex_random_string(10); $this->assertSame(10, strlen($result)); $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $this->assertNotSame($result, complex_random_string(10)); $result = complex_random_string(21); $this->assertSame(21, strlen($result)); $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $this->assertNotSame($result, complex_random_string(21)); $result = complex_random_string(666); $this->assertSame(666, strlen($result)); $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $result = complex_random_string(); $this->assertEqualsWithDelta(28, strlen($result), 4); // Expected length is 24 - 32. $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); $this->assertDebuggingNotCalled(); } /** * Data provider for private ips. */ public function data_private_ips() { return array( array('10.0.0.0'), array('172.16.0.0'), array('192.168.1.0'), array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'), array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'), array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'), array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150. ); } /** * Checks ip_is_public returns false for private ips. * * @param string $ip the ipaddress to test * @dataProvider data_private_ips */ public function test_ip_is_public_private_ips($ip): void { $this->assertFalse(ip_is_public($ip)); } /** * Data provider for public ips. */ public function data_public_ips() { return array( array('2400:cb00:2048:1::8d65:71b3'), array('2400:6180:0:d0::1b:2001'), array('141.101.113.179'), array('123.45.67.178'), ); } /** * Checks ip_is_public returns true for public ips. * * @param string $ip the ipaddress to test * @dataProvider data_public_ips */ public function test_ip_is_public_public_ips($ip): void { $this->assertTrue(ip_is_public($ip)); } /** * Test the function can_send_from_real_email_address * * @param string $email Email address for the from user. * @param int $display The user's email display preference. * @param bool $samecourse Are the users in the same course? * @param string $config The CFG->allowedemaildomains config values * @param bool $result The expected result. * @dataProvider data_can_send_from_real_email_address */ public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result): void { $this->resetAfterTest(); $fromuser = $this->getDataGenerator()->create_user(); $touser = $this->getDataGenerator()->create_user(); $course = $this->getDataGenerator()->create_course(); set_config('allowedemaildomains', $config); $fromuser->email = $email; $fromuser->maildisplay = $display; if ($samecourse) { $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student'); $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student'); } else { $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student'); } $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser)); } /** * Data provider for test_can_send_from_real_email_address. * * @return array Returns an array of test data for the above function. */ public function data_can_send_from_real_email_address() { return [ // Test from email is in allowed domain. // Test that from display is set to show no one. [ 'email' => 'fromuser@example.com', 'display' => \core_user::MAILDISPLAY_HIDE, 'samecourse' => false, 'config' => "example.com\r\ntest.com", 'result' => false ], // Test that from display is set to course members only (course member). [ 'email' => 'fromuser@example.com', 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 'samecourse' => true, 'config' => "example.com\r\ntest.com", 'result' => true ], // Test that from display is set to course members only (Non course member). [ 'email' => 'fromuser@example.com', 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 'samecourse' => false, 'config' => "example.com\r\ntest.com", 'result' => false ], // Test that from display is set to show everyone. [ 'email' => 'fromuser@example.com', 'display' => \core_user::MAILDISPLAY_EVERYONE, 'samecourse' => false, 'config' => "example.com\r\ntest.com", 'result' => true ], // Test a few different config value formats for parsing correctness. [ 'email' => 'fromuser@example.com', 'display' => \core_user::MAILDISPLAY_EVERYONE, 'samecourse' => false, 'config' => "\n test.com\nexample.com \n", 'result' => true ], [ 'email' => 'fromuser@example.com', 'display' => \core_user::MAILDISPLAY_EVERYONE, 'samecourse' => false, 'config' => "\r\n example.com \r\n test.com \r\n", 'result' => true ], [ 'email' => 'fromuser@EXAMPLE.com', 'display' => \core_user::MAILDISPLAY_EVERYONE, 'samecourse' => false, 'config' => "example.com\r\ntest.com", 'result' => true, ], // Test from email is not in allowed domain. // Test that from display is set to show no one. [ 'email' => 'fromuser@moodle.com', 'display' => \core_user::MAILDISPLAY_HIDE, 'samecourse' => false, 'config' => "example.com\r\ntest.com", 'result' => false ], // Test that from display is set to course members only (course member). [ 'email' => 'fromuser@moodle.com', 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 'samecourse' => true, 'config' => "example.com\r\ntest.com", 'result' => false ], // Test that from display is set to course members only (Non course member. [ 'email' => 'fromuser@moodle.com', 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 'samecourse' => false, 'config' => "example.com\r\ntest.com", 'result' => false ], // Test that from display is set to show everyone. [ 'email' => 'fromuser@moodle.com', 'display' => \core_user::MAILDISPLAY_EVERYONE, 'samecourse' => false, 'config' => "example.com\r\ntest.com", 'result' => false ], // Test a few erroneous config value and confirm failure. [ 'email' => 'fromuser@moodle.com', 'display' => \core_user::MAILDISPLAY_EVERYONE, 'samecourse' => false, 'config' => "\r\n \r\n", 'result' => false ], [ 'email' => 'fromuser@moodle.com', 'display' => \core_user::MAILDISPLAY_EVERYONE, 'samecourse' => false, 'config' => " \n \n \n ", 'result' => false ], ]; } /** * Test that generate_email_processing_address() returns valid email address. */ public function test_generate_email_processing_address(): void { global $CFG; $this->resetAfterTest(); $data = (object)[ 'id' => 42, 'email' => 'my.email+from_moodle@example.com', ]; $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16); $CFG->maildomain = 'example.com'; $CFG->mailprefix = 'mdl+'; $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs))); $CFG->maildomain = 'mail.example.com'; $CFG->mailprefix = 'mdl-'; $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs))); } /** * Test allowemailaddresses setting. * * @param string $email Email address for the from user. * @param string $config The CFG->allowemailaddresses config values * @param false/string $result The expected result. * * @dataProvider data_email_is_not_allowed_for_allowemailaddresses */ public function test_email_is_not_allowed_for_allowemailaddresses($email, $config, $result): void { $this->resetAfterTest(); set_config('allowemailaddresses', $config); $this->assertEquals($result, email_is_not_allowed($email)); } /** * Data provider for data_email_is_not_allowed_for_allowemailaddresses. * * @return array Returns an array of test data for the above function. */ public function data_email_is_not_allowed_for_allowemailaddresses() { return [ // Test allowed domain empty list. [ 'email' => 'fromuser@example.com', 'config' => '', 'result' => false ], // Test from email is in allowed domain. [ 'email' => 'fromuser@example.com', 'config' => 'example.com test.com', 'result' => false ], // Test from email is in allowed domain but uppercase config. [ 'email' => 'fromuser@example.com', 'config' => 'EXAMPLE.com test.com', 'result' => false ], // Test from email is in allowed domain but uppercase email. [ 'email' => 'fromuser@EXAMPLE.com', 'config' => 'example.com test.com', 'result' => false ], // Test from email is in allowed subdomain. [ 'email' => 'fromuser@something.example.com', 'config' => '.example.com test.com', 'result' => false ], // Test from email is in allowed subdomain but uppercase config. [ 'email' => 'fromuser@something.example.com', 'config' => '.EXAMPLE.com test.com', 'result' => false ], // Test from email is in allowed subdomain but uppercase email. [ 'email' => 'fromuser@something.EXAMPLE.com', 'config' => '.example.com test.com', 'result' => false ], // Test from email is not in allowed domain. [ 'email' => 'fromuser@moodle.com', 'config' => 'example.com test.com', 'result' => get_string('emailonlyallowed', '', 'example.com test.com') ], // Test from email is not in allowed subdomain. [ 'email' => 'fromuser@something.example.com', 'config' => 'example.com test.com', 'result' => get_string('emailonlyallowed', '', 'example.com test.com') ], ]; } /** * Test denyemailaddresses setting. * * @param string $email Email address for the from user. * @param string $config The CFG->denyemailaddresses config values * @param false/string $result The expected result. * * @dataProvider data_email_is_not_allowed_for_denyemailaddresses */ public function test_email_is_not_allowed_for_denyemailaddresses($email, $config, $result): void { $this->resetAfterTest(); set_config('denyemailaddresses', $config); $this->assertEquals($result, email_is_not_allowed($email)); } /** * Data provider for test_email_is_not_allowed_for_denyemailaddresses. * * @return array Returns an array of test data for the above function. */ public function data_email_is_not_allowed_for_denyemailaddresses() { return [ // Test denied domain empty list. [ 'email' => 'fromuser@example.com', 'config' => '', 'result' => false ], // Test from email is in denied domain. [ 'email' => 'fromuser@example.com', 'config' => 'example.com test.com', 'result' => get_string('emailnotallowed', '', 'example.com test.com') ], // Test from email is in denied domain but uppercase config. [ 'email' => 'fromuser@example.com', 'config' => 'EXAMPLE.com test.com', 'result' => get_string('emailnotallowed', '', 'EXAMPLE.com test.com') ], // Test from email is in denied domain but uppercase email. [ 'email' => 'fromuser@EXAMPLE.com', 'config' => 'example.com test.com', 'result' => get_string('emailnotallowed', '', 'example.com test.com') ], // Test from email is in denied subdomain. [ 'email' => 'fromuser@something.example.com', 'config' => '.example.com test.com', 'result' => get_string('emailnotallowed', '', '.example.com test.com') ], // Test from email is in denied subdomain but uppercase config. [ 'email' => 'fromuser@something.example.com', 'config' => '.EXAMPLE.com test.com', 'result' => get_string('emailnotallowed', '', '.EXAMPLE.com test.com') ], // Test from email is in denied subdomain but uppercase email. [ 'email' => 'fromuser@something.EXAMPLE.com', 'config' => '.example.com test.com', 'result' => get_string('emailnotallowed', '', '.example.com test.com') ], // Test from email is not in denied domain. [ 'email' => 'fromuser@moodle.com', 'config' => 'example.com test.com', 'result' => false ], // Test from email is not in denied subdomain. [ 'email' => 'fromuser@something.example.com', 'config' => 'example.com test.com', 'result' => false ], ]; } /** * Test safe method unserialize_array(). */ public function test_unserialize_array(): void { $a = [1, 2, 3]; $this->assertEquals($a, unserialize_array(serialize($a))); $a = ['a' => 1, 2 => 2, 'b' => 'cde']; $this->assertEquals($a, unserialize_array(serialize($a))); $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e']; $this->assertEquals($a, unserialize_array(serialize($a))); $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde']; $this->assertEquals($a, unserialize_array(serialize($a))); $a = ['a' => 1, 2 => ['c' => 'd', 'e' => ['f' => 'g']], 'b' => 'cde']; $this->assertEquals($a, unserialize_array(serialize($a))); $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e']; $this->assertEquals($a, unserialize_array(serialize($a))); // Can not unserialize if there are any objects. $a = (object)['a' => 1, 2 => 2, 'b' => 'cde']; $this->assertFalse(unserialize_array(serialize($a))); $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']]; $this->assertFalse(unserialize_array(serialize($a))); $a = ['a' => 1, 2 => 2, 'b' => ['c' => (object)['a' => 'cde']]]; $this->assertFalse(unserialize_array(serialize($a))); $a = ['a' => 1, 2 => 2, 'b' => ['c' => new lang_string('no')]]; $this->assertFalse(unserialize_array(serialize($a))); // Array used in the grader report. $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]); $this->assertEquals($a, unserialize_array(serialize($a))); } /** * Test method for safely unserializing a serialized object of type stdClass */ public function test_unserialize_object(): void { $object = (object) [ 'foo' => 42, 'bar' => 'Hamster', 'innerobject' => (object) [ 'baz' => 'happy', ], ]; // We should get back the same object we serialized. $serializedobject = serialize($object); $this->assertEquals($object, unserialize_object($serializedobject)); // Try serializing a different class, not allowed. $langstr = new lang_string('no'); $serializedlangstr = serialize($langstr); $unserializedlangstr = unserialize_object($serializedlangstr); $this->assertInstanceOf(\stdClass::class, $unserializedlangstr); } /** * Test that the component_class_callback returns the correct default value when the class was not found. * * @dataProvider component_class_callback_default_provider * @param $default */ public function test_component_class_callback_not_found($default): void { $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default)); } /** * Test that the component_class_callback returns the correct default value when the class was not found. * * @dataProvider component_class_callback_default_provider * @param $default */ public function test_component_class_callback_method_not_found($default): void { require_once(__DIR__ . '/fixtures/component_class_callback_example.php'); $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default)); } /** * Test that the component_class_callback returns the default when the method returned null. * * @dataProvider component_class_callback_default_provider * @param $default */ public function test_component_class_callback_found_returns_null($default): void { require_once(__DIR__ . '/fixtures/component_class_callback_example.php'); $this->assertSame($default, component_class_callback(\test_component_class_callback_example::class, 'method_returns_value', [null], $default)); $this->assertSame($default, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_value', [null], $default)); } /** * Test that the component_class_callback returns the expected value and not the default when there was a value. * * @dataProvider component_class_callback_data_provider * @param $default */ public function test_component_class_callback_found_returns_value($value): void { require_once(__DIR__ . '/fixtures/component_class_callback_example.php'); $this->assertSame($value, component_class_callback(\test_component_class_callback_example::class, 'method_returns_value', [$value], 'This is not the value you were looking for')); $this->assertSame($value, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_value', [$value], 'This is not the value you were looking for')); } /** * Test that the component_class_callback handles multiple params correctly. * * @dataProvider component_class_callback_multiple_params_provider * @param $default */ public function test_component_class_callback_found_accepts_multiple($params, $count): void { require_once(__DIR__ . '/fixtures/component_class_callback_example.php'); $this->assertSame($count, component_class_callback(\test_component_class_callback_example::class, 'method_returns_all_params', $params, 'This is not the value you were looking for')); $this->assertSame($count, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_all_params', $params, 'This is not the value you were looking for')); } /** * Data provider with list of default values for user in component_class_callback tests. * * @return array */ public function component_class_callback_default_provider() { return [ 'null' => [null], 'empty string' => [''], 'string' => ['This is a string'], 'int' => [12345], 'stdClass' => [(object) ['this is my content']], 'array' => [['a' => 'b',]], ]; } /** * Data provider with list of default values for user in component_class_callback tests. * * @return array */ public function component_class_callback_data_provider() { return [ 'empty string' => [''], 'string' => ['This is a string'], 'int' => [12345], 'stdClass' => [(object) ['this is my content']], 'array' => [['a' => 'b',]], ]; } /** * Data provider with list of default values for user in component_class_callback tests. * * @return array */ public function component_class_callback_multiple_params_provider() { return [ 'empty array' => [ [], 0, ], 'string value' => [ ['one'], 1, ], 'string values' => [ ['one', 'two'], 2, ], 'arrays' => [ [[], []], 2, ], 'nulls' => [ [null, null, null, null], 4, ], 'mixed' => [ ['a', 1, null, (object) [], []], 5, ], ]; } /** * Test that {@link get_callable_name()} describes the callable as expected. * * @dataProvider callable_names_provider * @param callable $callable * @param string $expectedname */ public function test_get_callable_name($callable, $expectedname): void { $this->assertSame($expectedname, get_callable_name($callable)); } /** * Provides a set of callables and their human readable names. * * @return array of (string)case => [(mixed)callable, (string|bool)expected description] */ public function callable_names_provider() { return [ 'integer' => [ 386, false, ], 'boolean' => [ true, false, ], 'static_method_as_literal' => [ 'my_foobar_class::my_foobar_method', 'my_foobar_class::my_foobar_method', ], 'static_method_of_literal_class' => [ ['my_foobar_class', 'my_foobar_method'], 'my_foobar_class::my_foobar_method', ], 'static_method_of_object' => [ [$this, 'my_foobar_method'], 'core\moodlelib_test::my_foobar_method', ], 'method_of_object' => [ [new lang_string('parentlanguage', 'core_langconfig'), 'my_foobar_method'], 'lang_string::my_foobar_method', ], 'function_as_literal' => [ 'my_foobar_callback', 'my_foobar_callback', ], 'function_as_closure' => [ function($a) { return $a; }, 'Closure::__invoke', ], ]; } /** * Data provider for \core_moodlelib_testcase::test_get_complete_user_data(). * * @return array */ public function user_data_provider() { return [ 'Fetch data using a valid username' => [ 'username', 's1', true ], 'Fetch data using a valid username, different case' => [ 'username', 'S1', true ], 'Fetch data using a valid username, different case for fieldname and value' => [ 'USERNAME', 'S1', true ], 'Fetch data using an invalid username' => [ 'username', 's2', false ], 'Fetch by email' => [ 'email', 's1@example.com', true ], 'Fetch data using a non-existent email' => [ 'email', 's2@example.com', false ], 'Fetch data using a non-existent email, throw exception' => [ 'email', 's2@example.com', false, \dml_missing_record_exception::class ], 'Multiple accounts with the same email' => [ 'email', 's1@example.com', false, 1 ], 'Multiple accounts with the same email, throw exception' => [ 'email', 's1@example.com', false, 1, \dml_multiple_records_exception::class ], 'Fetch data using a valid user ID' => [ 'id', true, true ], 'Fetch data using a non-existent user ID' => [ 'id', false, false ], ]; } /** * Test for get_complete_user_data(). * * @dataProvider user_data_provider * @param string $field The field to use for the query. * @param string|boolean $value The field value. When fetching by ID, set true to fetch valid user ID, false otherwise. * @param boolean $success Whether we expect for the fetch to succeed or return false. * @param int $allowaccountssameemail Value for $CFG->allowaccountssameemail. * @param string $expectedexception The exception to be expected. */ public function test_get_complete_user_data($field, $value, $success, $allowaccountssameemail = 0, $expectedexception = ''): void { $this->resetAfterTest(); // Set config settings we need for our environment. set_config('allowaccountssameemail', $allowaccountssameemail); // Generate the user data. $generator = $this->getDataGenerator(); $userdata = [ 'username' => 's1', 'email' => 's1@example.com', ]; $user = $generator->create_user($userdata); if ($allowaccountssameemail) { // Create another user with the same email address. $generator->create_user(['email' => 's1@example.com']); } // Since the data provider can't know what user ID to use, do a special handling for ID field tests. if ($field === 'id') { if ($value) { // Test for fetching data using a valid user ID. Use the generated user's ID. $value = $user->id; } else { // Test for fetching data using a non-existent user ID. $value = $user->id + 1; } } // When an exception is expected. $throwexception = false; if ($expectedexception) { $this->expectException($expectedexception); $throwexception = true; } $fetcheduser = get_complete_user_data($field, $value, null, $throwexception); if ($success) { $this->assertEquals($user->id, $fetcheduser->id); $this->assertEquals($user->username, $fetcheduser->username); $this->assertEquals($user->email, $fetcheduser->email); } else { $this->assertFalse($fetcheduser); } } /** * Test for send_password_change_(). */ public function test_send_password_change_info(): void { $this->resetAfterTest(); $user = $this->getDataGenerator()->create_user(); $sink = $this->redirectEmails(); // Make sure we are redirecting emails. send_password_change_info($user); $result = $sink->get_messages(); $sink->close(); $this->assertStringContainsString('passwords cannot be reset on this site', quoted_printable_decode($result[0]->body)); } /** * Test the get_time_interval_string for a range of inputs. * * @dataProvider get_time_interval_string_provider * @param int $time1 the time1 param. * @param int $time2 the time2 param. * @param string|null $format the format param. * @param string $expected the expected string. * @param bool $dropzeroes the value passed for the `$dropzeros` param. * @param bool $fullformat the value passed for the `$fullformat` param. * @covers \get_time_interval_string */ public function test_get_time_interval_string(int $time1, int $time2, ?string $format, string $expected, bool $dropzeroes = false, bool $fullformat = false): void { if (is_null($format)) { $this->assertEquals($expected, get_time_interval_string($time1, $time2)); } else { $this->assertEquals($expected, get_time_interval_string($time1, $time2, $format, $dropzeroes, $fullformat)); } } /** * Data provider for the test_get_time_interval_string() method. */ public function get_time_interval_string_provider() { return [ 'Time is after the reference time by 1 minute, omitted format' => [ 'time1' => 12345660, 'time2' => 12345600, 'format' => null, 'expected' => '0d 0h 1m' ], 'Time is before the reference time by 1 minute, omitted format' => [ 'time1' => 12345540, 'time2' => 12345600, 'format' => null, 'expected' => '0d 0h 1m' ], 'Time is equal to the reference time, omitted format' => [ 'time1' => 12345600, 'time2' => 12345600, 'format' => null, 'expected' => '0d 0h 0m' ], 'Time is after the reference time by 1 minute, empty string format' => [ 'time1' => 12345660, 'time2' => 12345600, 'format' => '', 'expected' => '0d 0h 1m' ], 'Time is before the reference time by 1 minute, empty string format' => [ 'time1' => 12345540, 'time2' => 12345600, 'format' => '', 'expected' => '0d 0h 1m' ], 'Time is equal to the reference time, empty string format' => [ 'time1' => 12345600, 'time2' => 12345600, 'format' => '', 'expected' => '0d 0h 0m' ], 'Time is after the reference time by 1 minute, custom format' => [ 'time1' => 12345660, 'time2' => 12345600, 'format' => '%R%adays %hhours %imins', 'expected' => '+0days 0hours 1mins' ], 'Time is before the reference time by 1 minute, custom format' => [ 'time1' => 12345540, 'time2' => 12345600, 'format' => '%R%adays %hhours %imins', 'expected' => '-0days 0hours 1mins' ], 'Time is equal to the reference time, custom format' => [ 'time1' => 12345600, 'time2' => 12345600, 'format' => '%R%adays %hhours %imins', 'expected' => '+0days 0hours 0mins' ], 'Default format, time is after the reference time by 1 minute, drop zeroes, short form' => [ 'time1' => 12345660, 'time2' => 12345600, 'format' => '', 'expected' => '1m', 'dropzeroes' => true, ], 'Default format, time is after the reference time by 1 minute, drop zeroes, full form' => [ 'time1' => 12345660, 'time2' => 12345600, 'format' => '', 'expected' => '1 minutes', 'dropzeroes' => true, 'fullformat' => true, ], 'Default format, time is after the reference time by 1 minute, retain zeroes, full form' => [ 'time1' => 12345660, 'time2' => 12345600, 'format' => '', 'expected' => '0 days 0 hours 1 minutes', 'dropzeroes' => false, 'fullformat' => true, ], 'Empty string format, time is after the reference time by 1 minute, retain zeroes, full form' => [ 'time1' => 12345660, 'time2' => 12345600, 'format' => ' ', 'expected' => '0 days 0 hours 1 minutes', 'dropzeroes' => false, 'fullformat' => true, ], ]; } /** * Tests the rename_to_unused_name function with a file. */ public function test_rename_to_unused_name_file(): void { global $CFG; // Create a new file in dataroot. $file = $CFG->dataroot . '/argh.txt'; file_put_contents($file, 'Frogs'); // Rename it. $newname = rename_to_unused_name($file); // Check new name has expected format. $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname); // Check it's still in the same folder. $this->assertEquals($CFG->dataroot, dirname($newname)); // Check file can be loaded. $this->assertEquals('Frogs', file_get_contents($newname)); // OK, delete the file. unlink($newname); } /** * Tests the rename_to_unused_name function with a directory. */ public function test_rename_to_unused_name_dir(): void { global $CFG; // Create a new directory in dataroot. $file = $CFG->dataroot . '/arghdir'; mkdir($file); // Rename it. $newname = rename_to_unused_name($file); // Check new name has expected format. $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname); // Check it's still in the same folder. $this->assertEquals($CFG->dataroot, dirname($newname)); // Check it's still a directory $this->assertTrue(is_dir($newname)); // OK, delete the directory. rmdir($newname); } /** * Tests the rename_to_unused_name function with error cases. */ public function test_rename_to_unused_name_failure(): void { global $CFG; // Rename a file that doesn't exist. $file = $CFG->dataroot . '/argh.txt'; $this->assertFalse(rename_to_unused_name($file)); } /** * Provider for display_size * * @return array of ($size, $expected) */ public function display_size_provider() { return [ [0, '0 bytes'], [1, '1 bytes'], [1023, '1023 bytes'], [1024, '1.0 KB'], [2222, '2.2 KB'], [33333, '32.6 KB'], [444444, '434.0 KB'], [5555555, '5.3 MB'], [66666666, '63.6 MB'], [777777777, '741.7 MB'], [8888888888, '8.3 GB'], [99999999999, '93.1 GB'], [111111111111, '103.5 GB'], [2222222222222, '2.0 TB'], [33333333333333, '30.3 TB'], [444444444444444, '404.2 TB'], [5555555555555555, '4.9 PB'], [66666666666666666, '59.2 PB'], [777777777777777777, '690.8 PB'], ]; } /** * Test display_size * @dataProvider display_size_provider * @param int $size the size in bytes * @param string $expected the expected string. */ public function test_display_size($size, $expected): void { $result = display_size($size); $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space. $this->assertEquals($expected, $result); } /** * Provider for display_size using fixed units. * * @return array of ($size, $units, $expected) */ public function display_size_fixed_provider(): array { return [ [0, 'KB', '0.0 KB'], [1, 'MB', '0.0 MB'], [777777777, 'GB', '0.7 GB'], [8888888888, 'PB', '0.0 PB'], [99999999999, 'TB', '0.1 TB'], [99999999999, 'B', '99999999999 bytes'], ]; } /** * Test display_size using fixed units. * * @dataProvider display_size_fixed_provider * @param int $size Size in bytes * @param string $units Fixed units * @param string $expected Expected string. */ public function test_display_size_fixed(int $size, string $units, string $expected): void { $result = display_size($size, 1, $units); $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space. $this->assertEquals($expected, $result); } /** * Provider for display_size using specified decimal places. * * @return array of ($size, $decimalplaces, $units, $expected) */ public function display_size_dp_provider(): array { return [ [0, 1, 'KB', '0.0 KB'], [1, 6, 'MB', '0.000001 MB'], [777777777, 0, 'GB', '1 GB'], [777777777, 0, '', '742 MB'], [42, 6, '', '42 bytes'], ]; } /** * Test display_size using specified decimal places. * * @dataProvider display_size_dp_provider * @param int $size Size in bytes * @param int $places Number of decimal places * @param string $units Fixed units * @param string $expected Expected string. */ public function test_display_size_dp(int $size, int $places, string $units, string $expected): void { $result = display_size($size, $places, $units); $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space. $this->assertEquals($expected, $result); } /** * Test that the get_list_of_plugins function includes/excludes directories as appropriate. * * @dataProvider get_list_of_plugins_provider * @param array $expectedlist The expected list of folders * @param array $content The list of file content to set up in the virtual file root * @param string $dir The base dir to look at in the virtual file root * @param string $exclude Any additional folder to exclude */ public function test_get_list_of_plugins(array $expectedlist, array $content, string $dir, string $exclude): void { $vfileroot = \org\bovigo\vfs\vfsStream::setup('root', null, $content); $base = \org\bovigo\vfs\vfsStream::url('root'); $this->assertEquals($expectedlist, get_list_of_plugins($dir, $exclude, $base)); } /** * Data provider for get_list_of_plugins checks. * * @return array */ public function get_list_of_plugins_provider(): array { return [ 'Standard excludes' => [ ['amdd', 'class', 'local', 'test'], [ '.' => [], '..' => [], 'amd' => [], 'amdd' => [], 'class' => [], 'classes' => [], 'local' => [], 'test' => [], 'tests' => [], 'yui' => [], ], '', '', ], 'Standard excludes with addition' => [ ['amdd', 'local', 'test'], [ '.' => [], '..' => [], 'amd' => [], 'amdd' => [], 'class' => [], 'classes' => [], 'local' => [], 'test' => [], 'tests' => [], 'yui' => [], ], '', 'class', ], 'Files excluded' => [ ['def'], [ '.' => [], '..' => [], 'abc' => 'File with filename abc', 'def' => [ '.' => [], '..' => [], 'example.txt' => 'In a directory called "def"', ], ], '', '', ], 'Subdirectories only' => [ ['abc'], [ '.' => [], '..' => [], 'foo' => [ '.' => [], '..' => [], 'abc' => [], ], 'bar' => [ '.' => [], '..' => [], 'def' => [], ], ], 'foo', '', ], ]; } /** * Test get_home_page() method. * * @dataProvider get_home_page_provider * @param string $user Whether the user is logged, guest or not logged. * @param int $expected Expected value after calling the get_home_page method. * @param int $defaulthomepage The $CFG->defaulthomepage setting value. * @param int $enabledashboard Whether the dashboard should be enabled or not. * @param int $userpreference User preference for the home page setting. * @covers ::get_home_page */ public function test_get_home_page(string $user, int $expected, ?int $defaulthomepage = null, ?int $enabledashboard = null, ?int $userpreference = null): void { global $CFG, $USER; $this->resetAfterTest(); if ($user == 'guest') { $this->setGuestUser(); } else if ($user == 'logged') { $this->setUser($this->getDataGenerator()->create_user()); } if (isset($defaulthomepage)) { $CFG->defaulthomepage = $defaulthomepage; } if (isset($enabledashboard)) { $CFG->enabledashboard = $enabledashboard; } if ($USER) { set_user_preferences(['user_home_page_preference' => $userpreference], $USER->id); } $homepage = get_home_page(); $this->assertEquals($expected, $homepage); } /** * Data provider for get_home_page checks. * * @return array */ public function get_home_page_provider(): array { return [ 'No logged user' => [ 'user' => 'nologged', 'expected' => HOMEPAGE_SITE, ], 'Guest user' => [ 'user' => 'guest', 'expected' => HOMEPAGE_SITE, ], 'Logged user. Dashboard set as default home page and enabled' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MY, 'defaulthomepage' => HOMEPAGE_MY, 'enabledashboard' => 1, ], 'Logged user. Dashboard set as default home page but disabled' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MYCOURSES, 'defaulthomepage' => HOMEPAGE_MY, 'enabledashboard' => 0, ], 'Logged user. My courses set as default home page with dashboard enabled' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MYCOURSES, 'defaulthomepage' => HOMEPAGE_MYCOURSES, 'enabledashboard' => 1, ], 'Logged user. My courses set as default home page with dashboard disabled' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MYCOURSES, 'defaulthomepage' => HOMEPAGE_MYCOURSES, 'enabledashboard' => 0, ], 'Logged user. Site set as default home page with dashboard enabled' => [ 'user' => 'logged', 'expected' => HOMEPAGE_SITE, 'defaulthomepage' => HOMEPAGE_SITE, 'enabledashboard' => 1, ], 'Logged user. Site set as default home page with dashboard disabled' => [ 'user' => 'logged', 'expected' => HOMEPAGE_SITE, 'defaulthomepage' => HOMEPAGE_SITE, 'enabledashboard' => 0, ], 'Logged user. User preference set as default page with dashboard enabled and user preference set to dashboard' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MY, 'defaulthomepage' => HOMEPAGE_USER, 'enabledashboard' => 1, 'userpreference' => HOMEPAGE_MY, ], 'Logged user. User preference set as default page with dashboard disabled and user preference set to dashboard' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MYCOURSES, 'defaulthomepage' => HOMEPAGE_USER, 'enabledashboard' => 0, 'userpreference' => HOMEPAGE_MY, ], 'Logged user. User preference set as default page with dashboard enabled and user preference set to my courses' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MYCOURSES, 'defaulthomepage' => HOMEPAGE_USER, 'enabledashboard' => 1, 'userpreference' => HOMEPAGE_MYCOURSES, ], 'Logged user. User preference set as default page with dashboard disabled and user preference set to my courses' => [ 'user' => 'logged', 'expected' => HOMEPAGE_MYCOURSES, 'defaulthomepage' => HOMEPAGE_USER, 'enabledashboard' => 0, 'userpreference' => HOMEPAGE_MYCOURSES, ], ]; } /** * Test get_default_home_page() method. * * @covers ::get_default_home_page */ public function test_get_default_home_page(): void { global $CFG; $this->resetAfterTest(); $CFG->enabledashboard = 1; $default = get_default_home_page(); $this->assertEquals(HOMEPAGE_MY, $default); $CFG->enabledashboard = 0; $default = get_default_home_page(); $this->assertEquals(HOMEPAGE_MYCOURSES, $default); } /** * Tests the get_performance_info function with regard to locks. * * @covers ::get_performance_info */ public function test_get_performance_info_locks(): void { global $PERF; // Unset lock data just in case previous tests have set it. unset($PERF->locks); // With no lock data, there should be no information about locks in the results. $result = get_performance_info(); $this->assertStringNotContainsString('Lock', $result['html']); $this->assertStringNotContainsString('Lock', $result['txt']); // Rather than really do locks, just fill the array with fake data in the right format. $PERF->locks = [ (object) [ 'type' => 'phpunit', 'resource' => 'lock1', 'wait' => 0.59, 'success' => true, 'held' => '6.04' ], (object) [ 'type' => 'phpunit', 'resource' => 'lock2', 'wait' => 0.91, 'success' => false ] ]; $result = get_performance_info(); // Extract HTML table rows. $this->assertEquals(1, preg_match('~')); } /** * Provider for is_proxybypass * * @return array of test cases. */ public function is_proxybypass_provider(): array { return [ 'Proxybypass contains the same IP as the beginning of the URL' => [ 'http://192.168.5.5-fake-app-7f000101.nip.io', '192.168.5.5, 127.0.0.1', false ], 'Proxybypass contains the last part of the URL' => [ 'http://192.168.5.5-fake-app-7f000101.nip.io', 'app-7f000101.nip.io', false ], 'Proxybypass contains the last part of the URL 2' => [ 'http://store.mydomain.com', 'mydomain.com', false ], 'Proxybypass contains part of the url' => [ 'http://myweb.com', 'store.myweb.com', false ], 'Different IPs used in proxybypass' => [ 'http://192.168.5.5', '192.168.5.3', false ], 'Proxybypass and URL matchs' => [ 'http://store.mydomain.com', 'store.mydomain.com', true ], 'IP used in proxybypass' => [ 'http://192.168.5.5', '192.168.5.5', true ], ]; } /** * Check if $url matches anything in proxybypass list * * Test function {@see is_proxybypass()}. * @dataProvider is_proxybypass_provider * @param string $url url to check * @param string $proxybypass * @param bool $expected Expected value. */ public function test_is_proxybypass(string $url, string $proxybypass, bool $expected): void { $this->resetAfterTest(); global $CFG; $CFG->proxyhost = '192.168.5.5'; // Test with a fake proxy. $CFG->proxybypass = $proxybypass; $this->assertEquals($expected, is_proxybypass($url)); } /** * Test that the moodle_array_keys_filter method behaves in the same way * that array_keys behaved before Moodle 8.3. * * @dataProvider moodle_array_keys_filter_provider * @param array $array * @param mixed $filter * @param bool $strict * @param array $expected * @covers ::moodle_array_keys_filter */ public function test_moodle_array_keys_filter( array $array, mixed $filter, bool $strict, array $expected, ): void { $this->assertSame( $expected, moodle_array_keys_filter($array, $filter, $strict), ); } /** * Data provider for moodle_array_keys_filter tests. * * @return array */ public static function moodle_array_keys_filter_provider(): array { return [ [['a', 'b', 'c'], 'b', false, [1]], [ [ 'alpha' => 'a', 'bravo' => 'b', 'charlie' => 'c', ], 'b', false, ['bravo'], ], [ [ 'zero' => 0, 'one' => 1, 'true' => true, ], '1', false, ['one', 'true'], ], [ [ 'zero' => 0, 'one' => 1, 'true' => true, ], true, false, ['one', 'true'], ], [ [ 'zero' => 0, 'one' => 1, 'true' => true, ], true, true, ['true'], ], [ [ 'zero' => 0, 'one' => 1, 'true' => true, ], 1, true, ['one'], ], ]; } }