first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_form;
use MoodleQuickForm_autocomplete;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/form/autocomplete.php');
/**
* Unit tests for MoodleQuickForm_autocomplete
*
* Contains test cases for testing MoodleQuickForm_autocomplete
*
* @package core_form
* @copyright 2015 Damyon Wiese <damyon@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class autocomplete_test extends \basic_testcase {
/**
* Testcase for validation
*/
public function test_validation(): void {
// A default select with single values validates the data.
$options = array('1' => 'One', 2 => 'Two');
$element = new MoodleQuickForm_autocomplete('testel', null, $options);
$submission = array('testel' => 2);
$this->assertEquals($element->exportValue($submission), 2);
$submission = array('testel' => 3);
$this->assertEquals('', $element->exportValue($submission));
// A select with multiple values validates the data.
$options = array('1' => 'One', 2 => 'Two');
$element = new MoodleQuickForm_autocomplete('testel', null, $options, array('multiple'=>'multiple'));
$submission = array('testel' => array(2, 3));
$this->assertEquals($element->exportValue($submission), array(2));
// A select where the values are fetched via ajax does not validate the data.
$element = new MoodleQuickForm_autocomplete('testel', null, array(), array('multiple'=>'multiple', 'ajax'=>'anything'));
$submission = array('testel' => array(2, 3));
$this->assertEquals($element->exportValue($submission), array(2, 3));
// A select with single value without anything selected.
$options = array('1' => 'One', 2 => 'Two');
$element = new MoodleQuickForm_autocomplete('testel', null, $options);
$submission = array();
$this->assertEquals('', $element->exportValue($submission));
// A select with multiple values without anything selected.
$options = array('1' => 'One', 2 => 'Two');
$element = new MoodleQuickForm_autocomplete('testel', null, $options, array('multiple' => 'multiple'));
$submission = array();
$this->assertEquals([], $element->exportValue($submission));
}
}
+85
View File
@@ -0,0 +1,85 @@
@core @javascript @core_form
Feature: Autocomplete functionality in forms
For forms including autocomplete elements
As a user
I need to use the autocomplete form element
Scenario: Use autocomplete element which accepts a single value
Given the following "users" exist:
| username | firstname | lastname |
| user1 | Jane | Jones |
| user2 | Sam | Smith |
And I log in as "admin"
When I navigate to "Users > Privacy and policies > Data requests" in site administration
And I follow "New request"
And I open the autocomplete suggestions list
And I click on "Jane Jones" item in the autocomplete list
Then "Jane Jones" "autocomplete_selection" should exist
# Change selection
And I open the autocomplete suggestions list
And I click on "Sam Smith" item in the autocomplete list
And "Sam Smith" "autocomplete_selection" should exist
And "Jane Jones" "autocomplete_selection" should not exist
# Remove selection
And I click on "Sam Smith" "autocomplete_selection"
And "Sam Smith" "autocomplete_selection" should not exist
And I should see "No selection" in the ".form-autocomplete-selection" "css_element"
@javascript
Scenario: Single-select autocomplete can be cleared after being set
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And I am on the "autocomplete-disabledif" "core_form > Fixture" page logged in as "admin"
When I set the field "Controls the rest" to "Course 1"
And "Course 1" "autocomplete_selection" should be visible
And I click on "Course 1" "autocomplete_selection"
Then "frog" "autocomplete_selection" should not exist
@javascript
Scenario: Single-select autocomplete can be cleared immediately after page load
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And I am on the "autocomplete-disabledif" "core_form > Fixture" page logged in as "admin"
When I set the field "Controls the rest" to "Course 1"
And I press "Save changes"
And "Course 1" "autocomplete_selection" should be visible
And I click on "Course 1" "autocomplete_selection"
Then "frog" "autocomplete_selection" should not exist
@javascript
Scenario: Autocomplete can control other form fields via disabledIf
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And I am on the "autocomplete-disabledif" "core_form > Fixture" page logged in as "admin"
When I set the field "Controls the rest" to "Course 1"
Then the "Single select will be enabled if the control is blank" "field" should be disabled
And the "Single select will be disabled if the control is blank" "field" should be enabled
And I click on "Course 1" "autocomplete_selection"
And the "Single select will be enabled if the control is blank" "field" should be enabled
And the "Single select will be disabled if the control is blank" "field" should be disabled
@javascript
Scenario: Single-select autocomplete can be cleared after being set and suggestion list reloaded
Given the following "users" exist:
| username | firstname | lastname |
| user1 | Jane | Jones |
| user2 | Sam | Smith |
| user3 | Mark | Davis |
And I log in as "admin"
When I navigate to "Server > Web services > Manage tokens" in site administration
And I press "Create token"
And I open the autocomplete suggestions list
And I click on "Jane Jones" item in the autocomplete list
Then "Jane Jones" "autocomplete_selection" should exist
# Only reload de sugestion list
And I open the autocomplete suggestions list
# Remove selection
And I click on "Jane Jones" "autocomplete_selection"
And "Jane Jones" "autocomplete_selection" should not exist
And I should see "No selection" in the ".form-autocomplete-selection" "css_element"
+82
View File
@@ -0,0 +1,82 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Steps definitions related to mod_quiz.
*
* @package core_form
* @category test
* @copyright 2020 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
require_once(__DIR__ . '/../../../../lib/behat/behat_base.php');
require_once(__DIR__ . '/../../../../question/tests/behat/behat_question_base.php');
use Behat\Gherkin\Node\TableNode as TableNode;
use Behat\Mink\Exception\ExpectationException as ExpectationException;
/**
* Steps definitions related to core_form.
*/
class behat_core_form extends behat_question_base {
/**
* Convert page names to URLs for steps like 'When I am on the "core_form > [page name]" page'.
*
* Recognised page names are:
* | None so far! | |
*
* @param string $page name of the page, with the component name removed e.g. 'Admin notification'.
* @return moodle_url the corresponding URL.
* @throws Exception with a meaningful error message if the specified page cannot be found.
*/
protected function resolve_page_url(string $page): moodle_url {
switch (strtolower($page)) {
default:
throw new Exception('Unrecognised core_form page type "' . $page . '."');
}
}
/**
* Convert page names to URLs for steps like 'When I am on the "[identifier]" "core_form > [page type]" page'.
*
* Recognised page names are:
* | pagetype | name meaning | description |
* | Fixture | script-name | Fixture file name without extension |
*
* The fixture name should be the filename without path or extension. E.g.
* autocomplete-disabledif for lib/form/tests/fixtures/autocomplete-disabledif.php.
*
* @param string $type identifies which type of page this is, e.g. 'Fixture'.
* @param string $identifier identifies the particular page, e.g. 'autocomplete-disabledif'.
* @return moodle_url the corresponding URL.
* @throws Exception with a meaningful error message if the specified page cannot be found.
*/
protected function resolve_page_instance_url(string $type, string $identifier): moodle_url {
switch (strtolower($type)) {
case 'fixture':
return new moodle_url('/lib/form/tests/fixtures/' .
clean_param($identifier, PARAM_ALPHAEXT) . '.php');
default:
throw new Exception('Unrecognised core_form page type "' . $type . '."');
}
}
}
@@ -0,0 +1,42 @@
@core
Feature: Choice dropdown form behat test
In order to use choicelist in quickforms
As an admin
I need to be able to test it via behat
Background:
Given I log in as "admin"
And I am on fixture page "/lib/form/tests/behat/fixtures/field_choicedropdown_testpage.php"
Scenario: Set some value into choice dropdown
When I set the field "Basic choice dropdown" to "Text option 2"
And I click on "Send form" "button"
Then I should see "example0: option2" in the "submitted_data" "region"
@javascript
Scenario: Set some value into choice dropdown with javascript enabled
When I set the field "Basic choice dropdown" to "Text option 2"
And I click on "Send form" "button"
Then I should see "example0: option2" in the "submitted_data" "region"
@javascript
Scenario: Disable choice dropdown via javascript
When I click on "Check to disable the first choice dropdown field." "checkbox"
Then the "Disable if example" "field" should be disabled
@javascript
Scenario: Hide choice dropdown via javascript
Given I should see "Hide if example"
When I click on "Check to hide the first choice dropdown field." "checkbox"
Then I should not see "Hide if example"
@javascript
Scenario: Use a choice dropdown to disable and hide other fields
Given I should not see "Hide if element"
And the "Disabled if element" "field" should be disabled
When I set the field "Control choice dropdown" to "Show or enable subelements"
Then I should see "Hide if element"
And the "Disabled if element" "field" should be enabled
And I set the field "Control choice dropdown" to "Hide or disable subelements"
And I should not see "Hide if element"
And the "Disabled if element" "field" should be disabled
+28
View File
@@ -0,0 +1,28 @@
@core @javascript @core_form
Feature: disabledIf functionality in forms
For forms including disabledIf functions
As a user
If I trigger the disabledIf condition then the form elements will be disabled
Background:
Given I log in as "admin"
Scenario: The file manager is disabled when disabledIf conditions are met
Given I am on fixture page "/lib/form/tests/behat/fixtures/filemanager_hideif_disabledif_form.php"
When I click on "Disable" "radio"
# Test standard file manager.
Then the "disabled" attribute of "input#id_some_filemanager" "css_element" should contain "true"
# Test file manager in a group.
And the "disabled" attribute of "input#id_filemanager_group_some_filemanager_group" "css_element" should contain "true"
Scenario: The static element is disabled when 'eq' disabledIf conditions are met
Given I am on fixture page "/lib/form/tests/behat/fixtures/static_hideif_disabledif_form.php"
And I should see "Static with form elements"
When I click on "Disable" "radio"
And the "class" attribute of "#fitem_id_some_static" "css_element" should contain "text-muted"
And the "disabled" attribute of "input#id_some_static_username" "css_element" should contain "true"
And the "disabled" attribute of "Check" "button" should contain "true"
Then I click on "Enable" "radio"
And the "class" attribute of "#fitem_id_some_static" "css_element" should not contain "text-muted"
And the "#id_some_static_username" "css_element" should be enabled
And the "class" attribute of "Check" "button" should not contain "disabled"
@@ -0,0 +1,66 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once(__DIR__ . '/../../../../../config.php');
//defined('BEHAT_SITE_RUNNING') || die();
global $CFG, $PAGE, $OUTPUT;
require_once($CFG->libdir . '/formslib.php');
$PAGE->set_url('/lib/form/tests/behat/fixtures/editor_hideif_disabledif_form.php');
$PAGE->add_body_class('limitedwidth');
require_login();
$PAGE->set_context(core\context\system::instance());
/**
* Test class for disabling and hiding a text area using an editor.
*
* @package core_form
* @copyright 2024 David Woloszyn <david.woloszyn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class test_editor_hideif_disabledif_form extends moodleform {
/**
* Form definition.
*/
public function definition(): void {
$mform = $this->_form;
// Radio buttons.
$radiogroup = [
$mform->createElement('radio', 'some_radios', '', 'Enable', '1'),
$mform->createElement('radio', 'some_radios', '', 'Disable', '2'),
$mform->createElement('radio', 'some_radios', '', 'Hide', '3'),
];
$mform->addGroup($radiogroup, 'some_radios_group', 'Enable/Disable/Hide', ' ', false);
$mform->setDefault('some_radios', 1);
// Editor with conditions.
$mform->addElement('editor', 'some_editor', 'My test editor');
$mform->disabledIf('some_editor', 'some_radios', 'eq', '2');
$mform->hideIf('some_editor', 'some_radios', 'eq', '3');
$this->add_action_buttons();
}
}
$form = new test_editor_hideif_disabledif_form();
echo $OUTPUT->header();
$form->display();
echo $OUTPUT->footer();
@@ -0,0 +1,117 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Test page for choice dropdown field type.
*
* @copyright 2023 Ferran Recio <ferran@moodle.com>
* @package core_form
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use core\output\choicelist;
require_once(__DIR__ . '/../../../../../config.php');
defined('BEHAT_SITE_RUNNING') || die();
global $CFG, $PAGE, $OUTPUT;
require_once($CFG->libdir . '/formslib.php');
$PAGE->set_url('/lib/form/tests/behat/fixtures/field_choicedropdown_testpage.php');
$PAGE->add_body_class('limitedwidth');
require_login();
$PAGE->set_context(core\context\system::instance());
/**
* Class test_choice_dropdown
* @package core_form
*/
class test_choice_dropdown extends moodleform {
/**
* Define the export form.
*/
public function definition() {
$mform = $this->_form;
$options = new choicelist();
$options->set_allow_empty(false);
$options->add_option('option1', "Text option 1", [
'description' => 'Option 1 description',
'icon' => new pix_icon('t/hide', 'Eye icon 1'),
]);
$options->add_option('option2', "Text option 2", [
'description' => 'Option 2 description',
'icon' => new pix_icon('t/stealth', 'Eye icon 2'),
]);
$options->add_option('option3', "Text option 3", [
'description' => 'Option 3 description',
'icon' => new pix_icon('t/show', 'Eye icon 3'),
]);
$mform->addElement('header', 'database', "Basic example");
$mform->addElement('choicedropdown', 'example0', "Basic choice dropdown", $options);
$mform->addElement('header', 'database', "Disable choice dropdown");
$mform->addElement('checkbox', 'disableme', 'Check to disable the first choice dropdown field.');
$mform->addElement('choicedropdown', 'example1', "Disable if example", $options);
$mform->disabledIf('example1', 'disableme', 'checked');
$mform->addElement('header', 'database', "Hide choice dropdown");
$mform->addElement('checkbox', 'hideme', 'Check to hide the first choice dropdown field.');
$mform->addElement('choicedropdown', 'example2', "Hide if example", $options);
$mform->hideIf('example2', 'hideme', 'checked');
$options = new choicelist();
$options->set_allow_empty(false);
$options->add_option('hide', 'Hide or disable subelements');
$options->add_option('show', 'Show or enable subelements');
$mform->addElement('header', 'database', "Use choice dropdown to hide or disable other fields");
$mform->addElement('choicedropdown', 'example3', "Control choice dropdown", $options);
$mform->addElement('text', 'hideinput', 'Hide if element', ['maxlength' => 80, 'size' => 50]);
$mform->hideIf('hideinput', 'example3', 'eq', 'hide');
$mform->setDefault('hideinput', 'Is this visible?');
$mform->setType('hideinput', PARAM_TEXT);
$mform->addElement('text', 'disabledinput', 'Disabled if element', ['maxlength' => 80, 'size' => 50]);
$mform->disabledIf('disabledinput', 'example3', 'eq', 'hide');
$mform->setDefault('disabledinput', 'Is this enabled?');
$mform->setType('disabledinput', PARAM_TEXT);
$this->add_action_buttons(false, 'Send form');
}
}
echo $OUTPUT->header();
echo "<h2>Quickform integration test</h2>";
$form = new test_choice_dropdown();
$data = $form->get_data();
if ($data) {
echo "<h3>Submitted data</h3>";
echo '<div id="submitted_data"><ul>';
$data = (array) $data;
foreach ($data as $field => $value) {
echo "<li id=\"sumbmitted_{$field}\">$field: $value</li>";
}
echo '</ul></div>';
}
$form->display();
echo $OUTPUT->footer();
@@ -0,0 +1,78 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once(__DIR__ . '/../../../../../config.php');
defined('BEHAT_SITE_RUNNING') || die();
global $CFG, $PAGE, $OUTPUT;
require_once($CFG->libdir . '/formslib.php');
$PAGE->set_url('/lib/form/tests/behat/fixtures/filemanager_hideif_disabledif_form.php');
$PAGE->add_body_class('limitedwidth');
require_login();
$PAGE->set_context(core\context\system::instance());
/**
* Test class for disabling and hiding a filemanager element.
*
* @copyright 2024 David Woloszyn <david.woloszyn@moodle.com>
* @package core_form
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class test_filemanager_hideif_disabledif_form extends moodleform {
/**
* Form definition.
*/
public function definition(): void {
$mform = $this->_form;
$attributes = [];
$attributes['maxbytes'] = '1024';
$attributes['accepted_types'] = array_map('trim', explode(',', '.odt, .pdf'));
$attributes['subdirs'] = false;
$attributes['maxfiles'] = 3;
// Radio buttons.
$radiogroup = [
$mform->createElement('radio', 'some_radios', '', 'Enable', '1'),
$mform->createElement('radio', 'some_radios', '', 'Disable', '2'),
$mform->createElement('radio', 'some_radios', '', 'Hide', '3'),
];
$mform->addGroup($radiogroup, 'some_radios_group', 'Enable/Disable/Hide', ' ', false);
$mform->setDefault('some_radios', 1);
// Standard file manager.
$mform->addElement('filemanager', 'some_filemanager', 'Standard filemanager', '', $attributes);
$mform->disabledIf('some_filemanager', 'some_radios', 'eq', '2');
$mform->hideIf('some_filemanager', 'some_radios', 'eq', '3');
// File manager nested in group.
$filemanagergroup = [];
$filemanagergroup[] = $mform->createElement('filemanager', 'some_filemanager_group', '', null, $attributes);
$mform->addGroup($filemanagergroup, 'filemanager_group', 'Group filemanager');
$mform->disabledIf('filemanager_group', 'some_radios', 'eq', '2');
$this->add_action_buttons();
}
}
$form = new test_filemanager_hideif_disabledif_form();
echo $OUTPUT->header();
$form->display();
echo $OUTPUT->footer();
@@ -0,0 +1,91 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Test form repeat elements + defaults
*
* @copyright 2020 Davo Smith, Synergy Learning
* @package core_form
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__.'/../../../../../config.php');
defined('BEHAT_SITE_RUNNING') || die();
global $CFG, $PAGE, $OUTPUT;
require_once($CFG->libdir.'/formslib.php');
$PAGE->set_url('/lib/form/tests/behat/fixtures/repeat_defaults_form.php');
require_login();
$PAGE->set_context(context_system::instance());
/**
* Class repeat_defaults_form
* @package core_form
*/
class repeat_defaults_form extends moodleform {
/**
* Form definition
*/
public function definition() {
$mform = $this->_form;
$repeatcount = $this->_customdata['repeatcount'];
$repeat = array();
$repeatopts = array();
$repeat[] = $mform->createElement('header', 'testheading', 'Heading {no}');
$repeat[] = $mform->createElement('checkbox', 'testcheckbox', 'Test checkbox (default checked)');
$repeatopts['testcheckbox']['default'] = 1;
$repeat[] = $mform->createElement('advcheckbox', 'testadvcheckbox', 'Test advcheckbox (default checked)');
$repeatopts['testadvcheckbox']['default'] = 1;
$repeat[] = $mform->createElement('date_selector', 'testdate', 'Test date (default 8th Sept 2013)');
$repeatopts['testdate']['default'] = mktime(0, 0, 0, 9, 8, 2013);
$repeat[] = $mform->createElement('date_time_selector', 'testdatetime', 'Test datetime (default 8th Sept 2013, 10:30am)');
$repeatopts['testdatetime']['default'] = mktime(10, 30, 0, 9, 8, 2013);
$repeat[] = $mform->createElement('duration', 'testduration', 'Test duration (default 3 hours)');
$repeatopts['testduration']['default'] = 3 * HOURSECS;
$repeat[] = $mform->createElement('select', 'testselect', 'Test select (default B)', array(1 => 'A', 2 => 'B', 3 => 'C'));
$repeatopts['testselect']['default'] = 2;
$repeat[] = $mform->createElement('selectyesno', 'testselectyes', 'Test selectyesno (default yes)');
$repeatopts['testselectyes']['default'] = 1;
$repeat[] = $mform->createElement('selectyesno', 'testselectno', 'Test selectyesno (default no)');
$repeatopts['testselectno']['default'] = 0;
$repeat[] = $mform->createElement('text', 'testtext', 'Test text (default \'Testing 123\')');
$repeatopts['testtext']['default'] = 'Testing 123';
$repeatopts['testtext']['type'] = PARAM_TEXT;
$this->repeat_elements($repeat, $repeatcount, $repeatopts, 'test_repeat', 'test_repeat_add', 1, 'Add repeats', true);
$this->add_action_buttons();
}
}
$repeatcount = optional_param('test_repeat', 1, PARAM_INT);
$form = new repeat_defaults_form(null, array('repeatcount' => $repeatcount));
echo $OUTPUT->header();
$form->display();
echo $OUTPUT->footer();
@@ -0,0 +1,77 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Test form repeat elements and delete button
*
* @copyright 2021 Marina Glancy
* @package core_form
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__.'/../../../../../config.php');
defined('BEHAT_SITE_RUNNING') || die();
global $CFG, $PAGE, $OUTPUT;
require_once($CFG->libdir.'/formslib.php');
$PAGE->set_url('/lib/form/tests/behat/fixtures/repeat_with_delete_form.php');
require_login();
$PAGE->set_context(context_system::instance());
/**
* Class repeat_with_delete_form
*
* @copyright 2021 Marina Glancy
* @package core_form
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class repeat_with_delete_form extends moodleform {
/**
* Form definition
*/
public function definition() {
$mform = $this->_form;
$repeatcount = $this->_customdata['repeatcount'];
$repeat = array();
$repeatopts = array();
$repeat[] = $mform->createElement('header', 'testheading', 'Heading {no}');
$repeat[] = $mform->createElement('text', 'testtext', 'Test text {no}');
$repeatopts['testtext']['default'] = 'Testing';
$repeatopts['testtext']['type'] = PARAM_TEXT;
$repeat[] = $mform->createElement('submit', 'deleteel', 'Delete option {no}', [], false);
$this->repeat_elements($repeat, $repeatcount, $repeatopts, 'test_repeat',
'test_repeat_add', 1, 'Add repeats', true, 'deleteel');
$this->add_action_buttons();
}
}
$repeatcount = optional_param('test_repeat', 1, PARAM_INT);
$form = new repeat_with_delete_form(null, array('repeatcount' => $repeatcount));
echo $OUTPUT->header();
if ($data = $form->get_data()) {
echo "<pre>".json_encode($data->testtext)."</pre>";
} else {
$form->display();
}
echo $OUTPUT->footer();
@@ -0,0 +1,73 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once(__DIR__ . '/../../../../../config.php');
defined('BEHAT_SITE_RUNNING') || die();
global $CFG, $PAGE, $OUTPUT;
require_once($CFG->libdir . '/formslib.php');
$PAGE->set_url('/lib/form/tests/behat/fixtures/static_hideif_disabledif_form.php');
$PAGE->add_body_class('limitedwidth');
require_login();
$PAGE->set_context(core\context\system::instance());
/**
* Test class for hiding and disabling static elements.
*
* @package core_form
* @copyright Meirza <meirza.arson@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class test_static_hideif_disabledif_form extends moodleform {
/**
* Form definition.
*/
public function definition(): void {
$mform = $this->_form;
// Radio buttons.
$radiogroup = [
$mform->createElement('radio', 'some_radios', '', 'Enable', '1'),
$mform->createElement('radio', 'some_radios', '', 'Disable', '2'),
$mform->createElement('radio', 'some_radios', '', 'Hide', '3'),
];
$mform->addGroup($radiogroup, 'some_radios_group', 'Enable/Disable/Hide', ' ', false);
$mform->setDefault('some_radios', 1);
// Static element with conditions.
$mform->addElement(
'static',
'some_static',
'Static element',
'Static with <a href="#">form elements</a>
<input id="id_some_static_username" type="text" class="form-control mb-2" placeholder="Type username...">
<button type="submit" class="btn btn-primary mb-2">Check</button>',
);
$mform->disabledIf('some_static', 'some_radios', 'eq', '2');
$mform->hideIf('some_static', 'some_radios', 'eq', '3');
$this->add_action_buttons();
}
}
$form = new test_static_hideif_disabledif_form();
echo $OUTPUT->header();
$form->display();
echo $OUTPUT->footer();
@@ -0,0 +1,48 @@
@mod @mod_data @core_grades @core_form
Feature: Using the database activities which support point scale
validate if we can change the maximum grade when users are graded
As a teacher
I need to know whether I can not edit value of Maximum grade input field
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | 1 | student1@example.com |
| teacher1 | Teacher | 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | category | groupmode |
| Course 1 | C1 | 0 | 1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "activities" exist:
| activity | name | intro | course | idnumber |
| data | Test database name | n | C1 | data1 |
@javascript
Scenario: Database rescale grade should not be possible when users are graded
Given the following "mod_data > fields" exist:
| database | type | name | description |
| data1 | text | Test field name | Test field description |
And the following "mod_data > templates" exist:
| database | name |
| data1 | singletemplate |
| data1 | listtemplate |
| data1 | addtemplate |
| data1 | asearchtemplate |
| data1 | rsstemplate |
And the following "mod_data > entries" exist:
| database | user | Test field name |
| data1 | student1 | Student original entry |
| data1 | student1 | Student original entry 2 |
And I am on the "Test database name" "data activity editing" page logged in as teacher1
And I expand all fieldsets
And I set the field "Ratings > Aggregate type" to "Count of ratings"
And I set the field "Ratings > Type" to "Point"
And I press "Save and display"
And I select "Single view" from the "jump" singleselect
And I set the field "rating" to "51"
And I am on the "Test database name" "data activity editing" page
When I expand all fieldsets
Then the "Maximum grade" "field" should be disabled
@@ -0,0 +1,40 @@
@mod @mod_forum @core_grades @core_form
Feature: Using the forum activities which support point scale
validate if we can change the maximum grade when users are graded
As a teacher
I need to know whether I can not edit value of Maximum grade input field
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | 1 | student1@example.com |
| teacher1 | Teacher | 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | category | groupmode |
| Course 1 | C1 | 0 | 1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "activity" exists:
| course | C1 |
| activity | forum |
| name | Test forum name |
| idnumber | forum1 |
And the following "mod_forum > discussions" exist:
| user | forum | name | message |
| student1 | forum1 | Discussion subject | Test post in forum 1 |
@javascript
Scenario: Forum rescale grade should not be possible when users are graded
Given I am on the "Test forum name" "forum activity editing" page logged in as teacher1
And I expand all fieldsets
And I set the field "Ratings > Aggregate type" to "Count of ratings"
And I set the field "Ratings > Type" to "Point"
And I press "Save and return to course"
And I am on the "Test forum name" "forum activity" page
And I follow "Discussion subject"
And I set the field "rating" to "30"
When I am on the "Test forum name" "forum activity editing" page
And I expand all fieldsets
Then the "Maximum grade" "field" should be disabled
@@ -0,0 +1,44 @@
@mod @mod_glossary @core_grades @core_form
Feature: Using the glossary activities which support point scale
validate if we can change the maximum grade when users are graded
As a teacher
I need to know whether I can not edit value of Maximum grade input field
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | 1 | student1@example.com |
| teacher1 | Teacher | 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | category | groupmode |
| Course 1 | C1 | 0 | 1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "activity" exists:
| course | C1 |
| activity | glossary |
| name | Test glossary name |
| description | Test glossary description |
| idnumber | glossary1 |
@javascript
Scenario: Glossary rescale grade should not be possible when users are graded
Given I am on the "Test glossary name" "glossary activity" page logged in as student1
And I press "Add entry"
And I set the following fields to these values:
| Concept | Testing score |
| Definition | Scoring high on tests |
And I press "Save changes"
And I log out
And I am on the "Test glossary name" "glossary activity editing" page logged in as teacher1
And I expand all fieldsets
And I set the field "Ratings > Aggregate type" to "Count of ratings"
And I set the field "Ratings > Type" to "Point"
And I press "Save and return to course"
And I am on the "Test glossary name" "glossary activity" page
And I set the field "rating" to "50"
When I am on the "Test glossary name" "glossary activity editing" page
And I expand all fieldsets
Then the "Maximum grade" "field" should be disabled
@@ -0,0 +1,39 @@
@mod @mod_lesson @core_grades @core_form
Feature: Using the lesson activities which support point scale
validate if we can change the maximum grade when users are graded
As a teacher
I need to know whether I can not edit value of Maximum grade input field
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | 1 | student1@example.com |
| teacher1 | Teacher | 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | category | groupmode |
| Course 1 | C1 | 0 | 1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "activity" exists:
| course | C1 |
| activity | lesson |
| name | Test lesson name |
| idnumber | lesson1 |
@javascript
Scenario: Lesson rescale grade should not be possible when users are graded
Given the following "mod_lesson > page" exist:
| lesson | qtype | title | content |
| Test lesson name | numeric | Numerical question | What is 1 + 2? |
And the following "mod_lesson > answers" exist:
| page | answer | jumpto | score |
| Numerical question | 3 | End of lesson | 1 |
| Numerical question | @#wronganswer#@ | Next page | 0 |
And I am on the "Test lesson name" "lesson activity" page logged in as student1
And I set the field "Your answer" to "5"
And I press "Submit"
And I am on the "Test lesson name" "lesson activity editing" page logged in as teacher1
And I expand all fieldsets
Then the "Maximum grade" "field" should be disabled
+41
View File
@@ -0,0 +1,41 @@
@core @javascript @core_form
Feature: hideIf functionality in forms
For forms including hideIf functions
As a user
If I trigger the hideIf condition then the form elements will be hidden
Background:
Given the following "courses" exist:
| fullname | shortname |
| Course 1 | C1 |
And I log in as "admin"
Scenario: When 'eq' hideIf conditions are not met, the relevant elements are shown
When I add an assign activity to course "Course 1" section "1"
And I expand all fieldsets
And I set the field "Students submit in groups" to "Yes"
Then I should see "Require group to make submission"
And I should see "Require all group members submit"
And I should see "Grouping for student groups"
Scenario: When 'eq' hideIf conditions are met, the relevant elements are hidden
When I add a assign activity to course "Course 1" section "1"
And I expand all fieldsets
And I set the field "Students submit in groups" to "No"
Then I should not see "Require group to make submission"
And I should not see "Require all group members to submit"
And I should not see "Grouping for student groups"
Scenario: The editor is hidden when 'eq' hideIf conditions are met
Given I am on fixture page "/lib/form/tests/behat/fixtures/editor_hideif_disabledif_form.php"
And I should see "My test editor"
When I click on "Hide" "radio"
Then I should not see "My test editor"
Scenario: The static element is hidden when 'eq' hideIf conditions are met
Given I am on fixture page "/lib/form/tests/behat/fixtures/static_hideif_disabledif_form.php"
And I should see "Static with form elements"
When I click on "Hide" "radio"
Then I should not see "Static with form elements"
And I click on "Enable" "radio"
And I should see "Static with form elements"
@@ -0,0 +1,129 @@
@core_form
Feature: Using the activity grade form element
In order to ensure validation is provided to the teacher
As a teacher
I need to know why I can not add/edit values in the form element
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | 1 | student1@example.com |
| teacher1 | Teacher | 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | category | groupmode |
| Course 1 | C1 | 0 | 1 |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
| student1 | C1 | student |
And the following "scales" exist:
| name | scale |
| ABCDEF | F,E,D,C,B,A |
| Letter scale | Disappointing, Good, Very good, Excellent |
And the following "activities" exist:
| activity | course | section | name | intro | idnumber | type | groupmode |
| assign | C1 | 1 | Test assignment name | Test assignment description | | | |
| forum | C1 | 1 | Test forum name | | forum1 | general | 0 |
And the following "mod_forum > discussions" exist:
| user | forum | name | message |
| student1 | forum1 | Discussion subject | Discussion message |
@javascript
Scenario: Being able to change the grade type, scale and maximum grade when there are no grades
Given I am on the "Test forum name" "forum activity editing" page logged in as teacher1
And I set the following fields to these values:
| Ratings > Aggregate type | Average of ratings |
| id_scale_modgrade_type | Point |
| Ratings > scale[modgrade_point] | 60 |
And I press "Save and return to course"
And I am on the "Test forum name" "forum activity editing" page
When I expand all fieldsets
Then I should not see "Some grades have already been awarded, so the grade type"
And I set the field "id_scale_modgrade_type" to "Scale"
And I set the field "Ratings > scale[modgrade_scale]" to "ABCDEF"
And I press "Save and display"
And I should not see "You cannot change the type, as grades already exist for this item"
And I navigate to "Settings" in current page administration
And I expand all fieldsets
And I should not see "Some grades have already been awarded, so the grade type"
And I set the field "Ratings > scale[modgrade_scale]" to "Letter scale"
And I press "Save and display"
And I should not see "You cannot change the scale, as grades already exist for this item"
And I navigate to "Settings" in current page administration
And I expand all fieldsets
And I should not see "Some grades have already been awarded, so the grade type"
And I set the field "id_scale_modgrade_type" to "Point"
And I set the field "Ratings > Maximum grade" to "50"
And I press "Save and display"
And I should not see "You must choose whether to rescale existing grades or not"
@javascript
Scenario: Attempting to change the scale when grades already exist in rating activity
Given I am on the "Test forum name" "forum activity editing" page logged in as teacher1
And I set the following fields to these values:
| Ratings > Aggregate type | Average of ratings |
| id_scale_modgrade_type | Scale |
| Ratings > scale[modgrade_scale] | ABCDEF |
And I press "Save and display"
And I follow "Discussion subject"
And I set the field "rating" to "D"
And I am on the "Test forum name" "forum activity editing" page
When I expand all fieldsets
Then I should see "Some grades have already been awarded, so the grade type and scale cannot be changed"
# Try saving the form and visiting it back to verify that everything is working ok.
And I press "Save and display"
And I should not see "When selecting a ratings aggregate type you must also select"
And I navigate to "Settings" in current page administration
And I expand all fieldsets
And the field "Ratings > Aggregate type" matches value "Average of ratings"
And the field "id_scale_modgrade_type" matches value "Scale"
And the field "Ratings > scale[modgrade_scale]" matches value "ABCDEF"
@javascript
Scenario: Attempting to change the scale when grades already exist in non-rating activity
Given I am on the "Test assignment name" "assign activity" page logged in as "teacher1"
And I navigate to "Settings" in current page administration
And I set the following fields to these values:
| grade[modgrade_type] | Scale |
| grade[modgrade_scale] | ABCDEF |
And I press "Save and display"
And I am on the "Test assignment name" "assign activity" page
And I follow "View all submissions"
And I click on "Grade" "link" in the "Student 1" "table_row"
And I set the field "Grade" to "C"
And I press "Save changes"
And I follow "Edit settings"
When I expand all fieldsets
Then I should see "Some grades have already been awarded, so the grade type and scale cannot be changed"
# Try saving the form and visiting it back to verify everything is working ok.
And I press "Save and display"
And I navigate to "Settings" in current page administration
And I expand all fieldsets
And the field "grade[modgrade_type]" matches value "Scale"
And the field "grade[modgrade_scale]" matches value "ABCDEF"
@javascript
Scenario: Attempting to change the maximum grade when ratings exist
Given I am on the "Test forum name" "forum activity editing" page logged in as teacher1
And I set the following fields to these values:
| Ratings > Aggregate type | Average of ratings |
| id_scale_modgrade_type | Point |
| Ratings > scale[modgrade_point] | 100 |
And I press "Save and display"
And I follow "Discussion subject"
And I set the field "rating" to "100"
And I am on the "Test forum name" "forum activity editing" page
When I expand all fieldsets
Then I should see "You cannot change the type, as grades already exist for this item."
And the "Maximum grade" "field" should be disabled
@javascript
Scenario: Attempting to change the maximum grade when no rescaling option has been chosen
Given I am on the "Test assignment name" "assign activity" page logged in as teacher1
And I follow "View all submissions"
And I click on "Grade" "link" in the "Student 1" "table_row"
And I set the field "Grade out of 100" to "50"
And I press "Save changes"
And I follow "Edit settings"
When I expand all fieldsets
Then I should see "Some grades have already been awarded, so the grade type cannot be changed. If you wish to change the maximum grade, you must first choose whether or not to rescale existing grades."
@@ -0,0 +1,48 @@
@core_form
Feature: Repeated elements in moodleforms
Scenario: Clicking button to add repeat elements creates repeat elements with the correct default values
Given I log in as "admin"
And I am on fixture page "/lib/form/tests/behat/fixtures/repeat_defaults_form.php"
When I press "Add repeats"
Then the following fields match these values:
| testcheckbox[1] | 1 |
| testadvcheckbox[1] | 1 |
| testdate[1][day] | 8 |
| testdate[1][month] | September |
| testdate[1][year] | 2013 |
| testdatetime[1][day] | 8 |
| testdatetime[1][month] | September |
| testdatetime[1][year] | 2013 |
| testdatetime[1][hour] | 10 |
| testdatetime[1][minute] | 30 |
| testduration[1][number] | 3 |
| testduration[1][timeunit] | hours |
| testselect[1] | B |
| testselectyes[1] | Yes |
| testselectno[1] | No |
| testtext[1] | Testing 123 |
Scenario: Functionality to delete an option in the repeated elements
Given I log in as "admin"
And I am on fixture page "/lib/form/tests/behat/fixtures/repeat_with_delete_form.php"
And I set the field "Test text 1" to "value 1"
When I press "Add repeats"
Then the following fields match these values:
| Test text 1 | value 1 |
| Test text 2 | Testing |
And I set the field "Test text 2" to "value 2"
And I press "Add repeats"
And the following fields match these values:
| Test text 1 | value 1 |
| Test text 2 | value 2 |
| Test text 3 | Testing |
And I set the field "Test text 3" to "value 3"
And I press "Delete option 2"
And the following fields match these values:
| Test text 1 | value 1 |
| Test text 3 | value 3 |
And I should not see "Test text 2"
And I should not see "Delete option 2"
And I press "Save changes"
And I should see "{\"0\":\"value 1\",\"2\":\"value 3\"}"
+68
View File
@@ -0,0 +1,68 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_form;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/form/course.php');
/**
* Unit tests for MoodleQuickForm_course
*
* Contains test cases for testing MoodleQuickForm_course.
*
* @package core_form
* @category test
* @copyright 2020 Ruslan Kabalin
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class course_test extends \basic_testcase {
/**
* Test constructor supports all declared attributes.
*/
public function test_constructor_attributes(): void {
$attributes = [
'exclude' => [1, 2],
'requiredcapabilities' => ['moodle/course:update'],
];
$element = new \MoodleQuickForm_course('testel', null, $attributes);
$html = $element->toHtml();
$this->assertStringContainsString('data-exclude="1,2"', $html);
$this->assertStringContainsString('data-requiredcapabilities="moodle/course:update"', $html);
$this->assertStringContainsString('data-limittoenrolled="0"', $html);
$this->assertStringNotContainsString('multiple', $html);
$this->assertStringNotContainsString('data-includefrontpage', $html);
$this->assertStringNotContainsString('data-onlywithcompletion', $html);
// Add more attributes.
$attributes = [
'multiple' => true,
'limittoenrolled' => true,
'includefrontpage' => true,
'onlywithcompletion' => true,
];
$element = new \MoodleQuickForm_course('testel', null, $attributes);
$html = $element->toHtml();
$this->assertStringContainsString('multiple', $html);
$this->assertStringContainsString('data-limittoenrolled="1"', $html);
$this->assertStringContainsString('data-includefrontpage="' . SITEID . '"', $html);
$this->assertStringContainsString('data-onlywithcompletion="1"', $html);
}
}
+195
View File
@@ -0,0 +1,195 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for MoodleQuickForm_date_selector
*
* Contains test cases for testing MoodleQuickForm_date_selector
*
* @package core_form
* @category test
* @copyright 2012 Rajesh Taneja
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_form;
use moodleform;
use MoodleQuickForm_date_selector;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/form/dateselector.php');
require_once($CFG->libdir.'/formslib.php');
/**
* Unit tests for MoodleQuickForm_date_selector
*
* Contains test cases for testing MoodleQuickForm_date_selector
*
* @package core_form
* @category test
* @copyright 2012 Rajesh Taneja
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class dateselector_test extends \advanced_testcase {
/** @var \MoodleQuickForm Keeps reference of dummy form object */
private $mform;
/** @var array test fixtures */
private $testvals;
/**
* Initalize test wide variable, it is called in start of the testcase
*/
protected function setUp(): void {
global $CFG;
parent::setUp();
$this->resetAfterTest();
$this->setAdminUser();
$this->setTimezone('Australia/Perth');
// Get form data.
$form = new temp_form_date();
$this->mform = $form->getform();
// Set test values.
$this->testvals = array(
array (
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 'America/Moncton',
'timezone' => 'America/Moncton',
'timestamp' => 1309489200
),
array (
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 'America/Moncton',
'timezone' => 99,
'timestamp' => 1309489200
),
array (
'day' => 30,
'month' => 6,
'year' => 2011,
'usertimezone' => 'America/Moncton',
'timezone' => -4,
'timestamp' => 1309406400
),
array (
'day' => 30,
'month' => 6,
'year' => 2011,
'usertimezone' => -4,
'timezone' => 99,
'timestamp' => 1309406400
),
array (
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 0.0,
'timezone' => 0.0,
'timestamp' => 1309478400 // 6am at UTC+0
),
array (
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 0.0,
'timezone' => 99,
'timestamp' => 1309478400 // 6am at UTC+0
)
);
}
/**
* Testcase to check exportvalue
*/
public function test_exportvalue(): void {
global $USER;
$testvals = $this->testvals;
foreach ($testvals as $vals) {
// Set user timezone to test value.
$USER->timezone = $vals['usertimezone'];
// Create dateselector element with different timezones.
$elparams = array('optional'=>false, 'timezone' => $vals['timezone']);
$el = $this->mform->addElement('date_selector', 'dateselector', null, $elparams);
$this->assertTrue($el instanceof MoodleQuickForm_date_selector);
$submitvalues = array('dateselector' => $vals);
$this->assertSame(array('dateselector' => $vals['timestamp']), $el->exportValue($submitvalues, true),
"Please check if timezones are updated (Site adminstration -> location -> update timezone)");
}
}
/**
* Testcase to check onQuickformEvent
*/
public function test_onquickformevent(): void {
global $USER;
$testvals = $this->testvals;
// Get dummy form for data.
$mform = $this->mform;
foreach ($testvals as $vals) {
// Set user timezone to test value.
$USER->timezone = $vals['usertimezone'];
// Create dateselector element with different timezones.
$elparams = array('optional'=>false, 'timezone' => $vals['timezone']);
$el = $this->mform->addElement('date_selector', 'dateselector', null, $elparams);
$this->assertTrue($el instanceof MoodleQuickForm_date_selector);
$expectedvalues = array(
'day' => array($vals['day']),
'month' => array($vals['month']),
'year' => array($vals['year'])
);
$mform->_submitValues = array('dateselector' => $vals['timestamp']);
$el->onQuickFormEvent('updateValue', null, $mform);
$this->assertSame($expectedvalues, $el->getValue());
}
}
}
/**
* Form object to be used in test case.
*/
class temp_form_date extends moodleform {
/**
* Form definition.
*/
public function definition() {
// No definition required.
}
/**
* Returns form reference
* @return \MoodleQuickForm
*/
public function getform() {
$mform = $this->_form;
// set submitted flag, to simulate submission
$mform->_flagSubmitted = true;
return $mform;
}
}
+209
View File
@@ -0,0 +1,209 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for MoodleQuickForm_date_time_selector
*
* Contains test cases for testing MoodleQuickForm_date_time_selector
*
* @package core_form
* @category test
* @copyright 2012 Rajesh Taneja
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_form;
use moodleform;
use MoodleQuickForm_date_time_selector;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/form/datetimeselector.php');
require_once($CFG->libdir.'/formslib.php');
/**
* Unit tests for MoodleQuickForm_date_time_selector
*
* Contains test cases for testing MoodleQuickForm_date_time_selector
*
* @package core_form
* @category test
* @copyright 2012 Rajesh Taneja
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class datetimeselector_test extends \advanced_testcase {
/** @var \MoodleQuickForm Keeps reference of dummy form object */
private $mform;
/** @var array test fixtures */
private $testvals;
/**
* Initalize test wide variable, it is called in start of the testcase
*/
protected function setUp(): void {
global $CFG;
parent::setUp();
$this->resetAfterTest();
$this->setAdminUser();
$this->setTimezone('Australia/Perth');
// Get form data.
$form = new temp_form_datetime();
$this->mform = $form->getform();
// Set test values.
$this->testvals = array(
array (
'minute' => 0,
'hour' => 0,
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 'America/Moncton',
'timezone' => 'America/Moncton',
'timestamp' => 1309489200
),
array (
'minute' => 0,
'hour' => 0,
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 'America/Moncton',
'timezone' => 99,
'timestamp' => 1309489200
),
array (
'minute' => 0,
'hour' => 23,
'day' => 30,
'month' => 6,
'year' => 2011,
'usertimezone' => 'America/Moncton',
'timezone' => -4,
'timestamp' => 1309489200
),
array (
'minute' => 0,
'hour' => 23,
'day' => 30,
'month' => 6,
'year' => 2011,
'usertimezone' => -4,
'timezone' => 99,
'timestamp' => 1309489200
),
array (
'minute' => 0,
'hour' => 0,
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 0.0,
'timezone' => 0.0,
'timestamp' => 1309478400 // 6am at UTC+0
),
array (
'minute' => 0,
'hour' => 0,
'day' => 1,
'month' => 7,
'year' => 2011,
'usertimezone' => 0.0,
'timezone' => 99,
'timestamp' => 1309478400 // 6am at UTC+0
)
);
}
/**
* Testcase to check exportvalue
*/
public function test_exportvalue(): void {
global $USER;
$testvals = $this->testvals;
foreach ($testvals as $vals) {
// Set user timezone to test value.
$USER->timezone = $vals['usertimezone'];
// Create dateselector element with different timezones.
$elparams = array('optional'=>false, 'timezone' => $vals['timezone']);
$el = $this->mform->addElement('date_time_selector', 'dateselector', null, $elparams);
$this->assertTrue($el instanceof MoodleQuickForm_date_time_selector);
$submitvalues = array('dateselector' => $vals);
$this->assertSame(array('dateselector' => $vals['timestamp']), $el->exportValue($submitvalues, true),
"Please check if timezones are updated (Site adminstration -> location -> update timezone)");
}
}
/**
* Testcase to check onQuickformEvent
*/
public function test_onquickformevent(): void {
global $USER;
$testvals = $this->testvals;
// Get dummy form for data.
$mform = $this->mform;
foreach ($testvals as $vals) {
// Set user timezone to test value.
$USER->timezone = $vals['usertimezone'];
// Create dateselector element with different timezones.
$elparams = array('optional'=>false, 'timezone' => $vals['timezone']);
$el = $this->mform->addElement('date_time_selector', 'dateselector', null, $elparams);
$this->assertTrue($el instanceof MoodleQuickForm_date_time_selector);
$expectedvalues = array(
'day' => array($vals['day']),
'month' => array($vals['month']),
'year' => array($vals['year']),
'hour' => array($vals['hour']),
'minute' => array($vals['minute'])
);
$mform->_submitValues = array('dateselector' => $vals['timestamp']);
$el->onQuickFormEvent('updateValue', null, $mform);
$this->assertSame($expectedvalues, $el->getValue());
}
}
}
/**
* Form object to be used in test case
*/
class temp_form_datetime extends moodleform {
/**
* Form definition.
*/
public function definition() {
// No definition required.
}
/**
* Returns form reference.
* @return \MoodleQuickForm
*/
public function getform() {
$mform = $this->_form;
// set submitted flag, to simulate submission
$mform->_flagSubmitted = true;
return $mform;
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Unit tests for MoodleQuickForm_duration
*
* Contains test cases for testing MoodleQuickForm_duration
*
* @package core_form
* @category test
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_form;
use moodleform;
use MoodleQuickForm;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/form/duration.php');
/**
* Unit tests for MoodleQuickForm_duration
*
* Contains test cases for testing MoodleQuickForm_duration
*
* @package core_form
* @category test
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class duration_test extends \basic_testcase {
/**
* Get a form that can be used for testing.
*
* @return MoodleQuickForm
*/
protected function get_test_form(): MoodleQuickForm {
$form = new temp_form_duration();
return $form->getform();
}
/**
* Get a form with a duration element that can be used for testing.
*
* @return array with two elements, a MoodleQuickForm and a MoodleQuickForm_duration.
*/
protected function get_test_form_and_element(): array {
$mform = $this->get_test_form();
$element = $mform->addElement('duration', 'duration');
return [$mform, $element];
}
/**
* Test the constructor error handling.
*/
public function test_constructor_rejects_invalid_unit(): void {
// Test trying to create with an invalid unit.
$mform = $this->get_test_form();
$this->expectException(\coding_exception::class);
$mform->addElement('duration', 'testel', null, ['defaultunit' => 123, 'optional' => false]);
}
/**
* Test constructor only some units.
*/
public function test_constructor_limited_units(): void {
$mform = $this->get_test_form();
$mform->addElement('duration', 'testel', null, ['units' => [MINSECS, 1], 'optional' => false]);
$html = $mform->toHtml();
$html = preg_replace('~ +>~', '>', $html); // Clean HTML to avoid spurious errors.
$this->assertStringContainsString('<option value="60" selected>minutes</option>', $html);
$this->assertStringContainsString('<option value="1">seconds</option>', $html);
$this->assertStringNotContainsString('value="3600"', $html);
}
/**
* Testcase for testing units (seconds, minutes, hours and days)
*/
public function test_get_units(): void {
[$mform, $element] = $this->get_test_form_and_element();
$units = $element->get_units();
$this->assertEquals($units, [1 => get_string('seconds'), 60 => get_string('minutes'),
3600 => get_string('hours'), 86400 => get_string('days'), 604800 => get_string('weeks')]);
}
/**
* Data provider for {@see test_seconds_to_unit()}.
*
* @return array test cases.
*/
public function seconds_to_unit_cases(): array {
return [
[[0, MINSECS], 0], // Zero minutes, for a nice default unit.
[[1, 1], 1],
[[3601, 1], 3601],
[[1, MINSECS], 60],
[[3, MINSECS], 180],
[[1, HOURSECS], 3600],
[[2, HOURSECS], 7200],
[[1, DAYSECS], 86400],
[[25, HOURSECS], 90000],
];
}
/**
* Testcase for testing conversion of seconds to the best possible unit.
*
* @dataProvider seconds_to_unit_cases
* @param array $expected expected return value from seconds_to_unit
* @param int $seconds value to pass to seconds_to_unit
*/
public function test_seconds_to_unit(array $expected, int $seconds): void {
[, $element] = $this->get_test_form_and_element();
$this->assertEquals($expected, $element->seconds_to_unit($seconds));
}
/**
* Testcase for testing conversion of seconds to the best possible unit with a non-default default unit.
*/
public function test_seconds_to_unit_different_default_unit(): void {
$mform = $this->get_test_form();
$element = $mform->addElement('duration', 'testel', null,
['defaultunit' => DAYSECS, 'optional' => false]);
$this->assertEquals([0, DAYSECS], $element->seconds_to_unit(0));
}
/**
* Data provider for {@see test_export_value()}.
*
* @return array test cases.
*/
public function export_value_cases(): array {
return [
[10, '10', 1],
[9, '9.3', 1],
[10, '9.5', 1],
[180, '3', MINSECS],
[90, '1.5', MINSECS],
[7200, '2', HOURSECS],
[86400, '1', DAYSECS],
[0, '0', HOURSECS],
[0, '10', 1, 0, true],
[20, '20', 1, 1, true],
[0, '10', 1, 0, true, ''],
[20, '20', 1, 1, true, ''],
];
}
/**
* Testcase to check generated timestamp
*
* @dataProvider export_value_cases
* @param int $expected Expected value returned by the element.
* @param string $number Number entered into the element.
* @param int $unit Unit selected in the element.
* @param int $enabled Whether the enabled checkbox on the form was selected. (Only used if $optional is true.)
* @param bool $optional Whether the element has the optional option on.
* @param string|null $label The element's label.
*/
public function test_export_value(int $expected, string $number, int $unit, int $enabled = 0,
bool $optional = false, ?string $label = null): void {
// Create the test element.
$mform = $this->get_test_form();
$el = $mform->addElement('duration', 'testel', $label, $optional ? ['optional' => true] : []);
// Prepare the submitted values.
$values = ['testel' => ['number' => $number, 'timeunit' => $unit]];
if ($optional) {
$values['testel']['enabled'] = $enabled;
}
// Test.
$this->assertEquals(['testel' => $expected], $el->exportValue($values, true));
$this->assertEquals($expected, $el->exportValue($values));
}
}
/**
* Form object to be used in test case.
*/
class temp_form_duration extends moodleform {
/**
* Form definition.
*/
public function definition() {
// No definition required.
}
/**
* Returns form reference
* @return MoodleQuickForm
*/
public function getform() {
$mform = $this->_form;
// Set submitted flag, to simulate submission.
$mform->_flagSubmitted = true;
return $mform;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Provides the {@link core_form\external_testcase} class.
*
* @package core_form
* @category test
* @copyright 2017 David Mudrák <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_form;
use advanced_testcase;
use core_external\external_api;
defined('MOODLE_INTERNAL') || die();
global $CFG;
/**
* Test cases for the {@link core_form\external} class.
*
* @copyright 2017 David Mudrak <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class external_test extends advanced_testcase {
/**
* Test the core_form_get_filetypes_browser_data external function
*/
public function test_get_filetypes_browser_data(): void {
$data = external::get_filetypes_browser_data('', true, '');
$data = external_api::clean_returnvalue(external::get_filetypes_browser_data_returns(), $data);
$data = json_decode(json_encode($data));
// The actual data are tested in filetypes_util_test.php, here we just
// make sure that the external function wrapper seems to work.
$this->assertIsObject($data);
$this->assertIsArray($data->groups);
}
}
+487
View File
@@ -0,0 +1,487 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Provides the {@link core_form\filetypes_util_testcase} class.
*
* @package core_form
* @category test
* @copyright 2017 David Mudrák <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_form;
use advanced_testcase;
defined('MOODLE_INTERNAL') || die();
global $CFG;
/**
* Test cases for the {@link core_form\filetypes_util} class.
*
* @copyright 2017 David Mudrak <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class filetypes_util_test extends advanced_testcase {
/**
* Test normalizing list of extensions.
*/
public function test_normalize_file_types(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
$this->assertSame(['.odt'], $util->normalize_file_types('.odt'));
$this->assertSame(['.odt'], $util->normalize_file_types('odt'));
$this->assertSame(['.odt'], $util->normalize_file_types('.ODT'));
$this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types('doc, jpg, mp3'));
$this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types(['.doc', '.jpg', '.mp3']));
$this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types('doc, *.jpg, mp3'));
$this->assertSame(['.doc', '.jpg', '.mp3'], $util->normalize_file_types(['doc ', ' JPG ', '.mp3']));
$this->assertSame(['.rtf', '.pdf', '.docx'],
$util->normalize_file_types("RTF,.pdf\n...DocX,,,;\rPDF\trtf ...Rtf"));
$this->assertSame(['.tgz', '.tar.gz'], $util->normalize_file_types('tgz,TAR.GZ tar.gz .tar.gz tgz TGZ'));
$this->assertSame(['.notebook'], $util->normalize_file_types('"Notebook":notebook;NOTEBOOK;,\'NoTeBook\''));
$this->assertSame([], $util->normalize_file_types(''));
$this->assertSame([], $util->normalize_file_types([]));
$this->assertSame(['.0'], $util->normalize_file_types(0));
$this->assertSame(['.0'], $util->normalize_file_types('0'));
$this->assertSame(['.odt'], $util->normalize_file_types('*.odt'));
$this->assertSame([], $util->normalize_file_types('.'));
$this->assertSame(['.foo'], $util->normalize_file_types('. foo'));
$this->assertSame(['*'], $util->normalize_file_types('*'));
$this->assertSame([], $util->normalize_file_types('*~'));
$this->assertSame(['.pdf', '.ps'], $util->normalize_file_types('pdf *.ps foo* *bar .r??'));
$this->assertSame(['*'], $util->normalize_file_types('pdf *.ps foo* * *bar .r??'));
}
/**
* Test MIME type formal recognition.
*/
public function test_looks_like_mimetype(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
$this->assertTrue($util->looks_like_mimetype('type/subtype'));
$this->assertTrue($util->looks_like_mimetype('type/x-subtype'));
$this->assertTrue($util->looks_like_mimetype('type/x-subtype+xml'));
$this->assertTrue($util->looks_like_mimetype('type/vnd.subtype.xml'));
$this->assertTrue($util->looks_like_mimetype('type/vnd.subtype+xml'));
$this->assertFalse($util->looks_like_mimetype('.gif'));
$this->assertFalse($util->looks_like_mimetype('audio'));
$this->assertFalse($util->looks_like_mimetype('foo/bar/baz'));
}
/**
* Test getting/checking group.
*/
public function test_is_filetype_group(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
$audio = $util->is_filetype_group('audio');
$this->assertNotFalse($audio);
$this->assertIsArray($audio->extensions);
$this->assertIsArray($audio->mimetypes);
$this->assertFalse($util->is_filetype_group('.gif'));
$this->assertFalse($util->is_filetype_group('somethingveryunlikelytoeverexist'));
}
/**
* Test describing list of extensions.
*/
public function test_describe_file_types(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
force_current_language('en');
// Check that it is able to describe individual file extensions.
$desc = $util->describe_file_types('jpg .jpeg *.jpe PNG;.gif, mudrd8mz');
$this->assertTrue($desc->hasdescriptions);
$desc = $desc->descriptions;
$this->assertEquals(4, count($desc));
$this->assertEquals('File', $desc[0]->description);
$this->assertEquals('.mudrd8mz', $desc[0]->extensions);
$this->assertEquals('Image (JPEG)', $desc[2]->description);
$this->assertStringContainsString('.jpg', $desc[2]->extensions);
$this->assertStringContainsString('.jpeg', $desc[2]->extensions);
$this->assertStringContainsString('.jpe', $desc[2]->extensions);
// Check that it can describe groups and mimetypes too.
$desc = $util->describe_file_types('audio text/plain');
$this->assertTrue($desc->hasdescriptions);
$desc = $desc->descriptions;
$this->assertEquals(2, count($desc));
$this->assertEquals('Audio files', $desc[0]->description);
$this->assertStringContainsString('.mp3', $desc[0]->extensions);
$this->assertStringContainsString('.wav', $desc[0]->extensions);
$this->assertStringContainsString('.ogg', $desc[0]->extensions);
$this->assertEquals('Text file', $desc[1]->description);
$this->assertStringContainsString('.txt', $desc[1]->extensions);
// Empty.
$desc = $util->describe_file_types('');
$this->assertFalse($desc->hasdescriptions);
$this->assertEmpty($desc->descriptions);
// Any.
$desc = $util->describe_file_types('*');
$this->assertTrue($desc->hasdescriptions);
$this->assertNotEmpty($desc->descriptions[0]->description);
$this->assertEmpty($desc->descriptions[0]->extensions);
// Unknown mimetype.
$desc = $util->describe_file_types('application/x-something-really-unlikely-ever-exist');
$this->assertTrue($desc->hasdescriptions);
$this->assertEquals('application/x-something-really-unlikely-ever-exist', $desc->descriptions[0]->description);
$this->assertEmpty($desc->descriptions[0]->extensions);
}
/**
* Test expanding mime types into extensions.
*/
public function test_expand(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
$this->assertSame([], $util->expand(''));
$expanded = $util->expand('document .cdr text/plain');
$this->assertNotContains('document', $expanded);
$this->assertNotContains('text/plain', $expanded);
$this->assertContains('.doc', $expanded);
$this->assertContains('.odt', $expanded);
$this->assertContains('.txt', $expanded);
$this->assertContains('.cdr', $expanded);
$expanded = $util->expand('document .cdr text/plain', true, false);
$this->assertContains('document', $expanded);
$this->assertNotContains('text/plain', $expanded);
$this->assertContains('.doc', $expanded);
$this->assertContains('.odt', $expanded);
$this->assertContains('.txt', $expanded);
$this->assertContains('.cdr', $expanded);
$expanded = $util->expand('document .cdr text/plain', false, true);
$this->assertNotContains('document', $expanded);
$this->assertContains('text/plain', $expanded);
$this->assertContains('.doc', $expanded);
$this->assertContains('.odt', $expanded);
$this->assertContains('.txt', $expanded);
$this->assertContains('.cdr', $expanded);
$this->assertSame([], $util->expand('foo/bar', true, false));
$this->assertSame(['foo/bar'], $util->expand('foo/bar', true, true));
}
/**
* Test checking that a type is among others.
*/
public function test_is_listed(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
// These should be intuitively true.
$this->assertTrue($util->is_listed('txt', 'text/plain'));
$this->assertTrue($util->is_listed('txt', 'doc txt rtf'));
$this->assertTrue($util->is_listed('.txt', '.doc;.txt;.rtf'));
$this->assertTrue($util->is_listed('audio', 'text/plain audio video'));
$this->assertTrue($util->is_listed('text/plain', 'text/plain audio video'));
$this->assertTrue($util->is_listed('jpg jpe jpeg', 'image/jpeg'));
$this->assertTrue($util->is_listed(['jpg', 'jpe', '.png'], 'image'));
// These should be intuitively false.
$this->assertFalse($util->is_listed('.gif', 'text/plain'));
// Not all text/plain formats are in the document group.
$this->assertFalse($util->is_listed('text/plain', 'document'));
// Not all documents (and also the group itself) is not a plain text.
$this->assertFalse($util->is_listed('document', 'text/plain'));
// This may look wrong at the first sight as you might expect that the
// mimetype should simply map to an extension ...
$this->assertFalse($util->is_listed('image/jpeg', '.jpg'));
// But it is principally same situation as this (there is no 1:1 mapping).
$this->assertFalse($util->is_listed('.c', '.txt'));
$this->assertTrue($util->is_listed('.txt .c', 'text/plain'));
$this->assertFalse($util->is_listed('text/plain', '.c'));
// Any type is included if the filter is empty.
$this->assertTrue($util->is_listed('txt', ''));
$this->assertTrue($util->is_listed('txt', '*'));
// Empty value is part of any list.
$this->assertTrue($util->is_listed('', '.txt'));
}
/**
* Test getting types not present in a list.
*/
public function test_get_not_listed(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
$this->assertEmpty($util->get_not_listed('txt', 'text/plain'));
$this->assertEmpty($util->get_not_listed('txt', '.doc .txt .rtf'));
$this->assertEmpty($util->get_not_listed('txt', 'text/plain'));
$this->assertEmpty($util->get_not_listed(['jpg', 'jpe', 'jpeg'], 'image/jpeg'));
$this->assertEmpty($util->get_not_listed('', 'foo/bar'));
$this->assertEmpty($util->get_not_listed('.foobar', ''));
$this->assertEmpty($util->get_not_listed('.foobar', '*'));
// Returned list is normalized so extensions have the dot added.
$this->assertContains('.exe', $util->get_not_listed('exe', '.c .h'));
// If this looks wrong to you, see {@see self::test_is_listed()} for more details on this behaviour.
$this->assertContains('image/jpeg', $util->get_not_listed('image/jpeg', '.jpg .jpeg'));
}
/**
* Test populating the tree for the browser.
*/
public function test_data_for_browser(): void {
$this->resetAfterTest(true);
$util = new filetypes_util();
$data = $util->data_for_browser();
$this->assertContainsOnly('object', $data);
foreach ($data as $group) {
$this->assertObjectHasProperty('key', $group);
$this->assertObjectHasProperty('types', $group);
if ($group->key !== '') {
$this->assertTrue($group->selectable);
}
}
// Confirm that the reserved type '.xxx' isn't present in the 'Other files' section.
$types = array_reduce($data, function($carry, $group) {
if ($group->name === 'Other files') {
return $group->types;
}
});
$typekeys = array_map(function($type) {
return $type->key;
}, $types);
$this->assertNotContains('.xxx', $typekeys);
// All these three files are in both "image" and also "web_image"
// groups. We display both groups.
$data = $util->data_for_browser('jpg png gif', true, '.gif');
$this->assertEquals(3, count($data));
$this->assertTrue($data[0]->key !== $data[1]->key);
foreach ($data as $group) {
$this->assertTrue(($group->key === 'image' || $group->key === 'web_image' || $group->key === 'optimised_image'));
$this->assertEquals(3, count($group->types));
$this->assertFalse($group->selectable);
foreach ($group->types as $ext) {
if ($ext->key === '.gif') {
$this->assertTrue($ext->selected);
} else {
$this->assertFalse($ext->selected);
}
}
}
// The groups web_image and optimised_image are a subset of the group image. The
// file extensions that fall into these groups will be displayed thrice.
$data = $util->data_for_browser('web_image');
foreach ($data as $group) {
$this->assertTrue(($group->key === 'image' || $group->key === 'web_image' || $group->key === 'optimised_image'));
}
// Check that "All file types" are displayed first.
$data = $util->data_for_browser();
$group = array_shift($data);
$this->assertEquals('*', $group->key);
// Check that "All file types" is not displayed if should not.
$data = $util->data_for_browser(null, false);
$group = array_shift($data);
$this->assertNotEquals('*', $group->key);
// Groups with an extension selected start expanded. The "Other files"
// starts expanded. The rest start collapsed.
$data = $util->data_for_browser(null, false, '.png');
foreach ($data as $group) {
if ($group->key === 'document') {
$this->assertfalse($group->expanded);
} else if ($group->key === '') {
$this->assertTrue($group->expanded);
}
foreach ($group->types as $ext) {
foreach ($group->types as $ext) {
if ($ext->key === '.png') {
$this->assertTrue($ext->selected);
$this->assertTrue($group->expanded);
}
}
}
}
}
/**
* Data provider for testing test_is_allowed_file_type.
*
* @return array
*/
public function is_allowed_file_type_provider() {
return [
'Filetype not in extension list' => [
'filename' => 'test.xml',
'list' => '.png .jpg',
'expected' => false
],
'Filetype not in mimetype list' => [
'filename' => 'test.xml',
'list' => 'image/png',
'expected' => false
],
'Filetype not in group list' => [
'filename' => 'test.xml',
'list' => 'web_file',
'expected' => false
],
'Filetype in list as extension' => [
'filename' => 'test.xml',
'list' => 'xml',
'expected' => true
],
'Empty list should allow all' => [
'filename' => 'test.xml',
'list' => '',
'expected' => true
],
'Filetype in list but later on' => [
'filename' => 'test.xml',
'list' => 'gif;jpeg,image/png xml xlsx',
'expected' => true
],
'Filetype in list as mimetype' => [
'filename' => 'test.xml',
'list' => 'image/png application/xml',
'expected' => true
],
'Filetype in list as group' => [
'filename' => 'test.html',
'list' => 'video,web_file',
'expected' => true
],
];
}
/**
* Test is_allowed_file_type().
* @dataProvider is_allowed_file_type_provider
* @param string $filename The filename to check
* @param string $list The space , or ; separated list of types supported
* @param boolean $expected The expected result. True if the file is allowed, false if not.
*/
public function test_is_allowed_file_type($filename, $list, $expected): void {
$util = new filetypes_util();
$this->assertSame($expected, $util->is_allowed_file_type($filename, $list));
}
/**
* Data provider for testing test_get_unknown_file_types.
*
* @return array
*/
public function get_unknown_file_types_provider() {
return [
'Empty list' => [
'filetypes' => '',
'expected' => [],
],
'Any file type' => [
'filetypes' => '*',
'expected' => [],
],
'Unknown extension' => [
'filetypes' => '.rat',
'expected' => ['.rat']
],
'Multiple unknown extensions' => [
'filetypes' => '.ricefield .rat',
'expected' => ['.ricefield', '.rat']
],
'Existant extension' => [
'filetypes' => '.xml',
'expected' => []
],
'Existant group' => [
'filetypes' => 'web_file',
'expected' => []
],
'Nonexistant mimetypes' => [
'filetypes' => 'ricefield/rat',
'expected' => ['ricefield/rat']
],
'Existant mimetype' => [
'filetypes' => 'application/xml',
'expected' => []
],
'Multiple unknown mimetypes' => [
'filetypes' => 'ricefield/rat cam/ball',
'expected' => ['ricefield/rat', 'cam/ball']
],
'Strange characters in unknown extension/group' => [
'filetypes' => '©ç√√ß∂å√©åß©√',
'expected' => ['.©ç√√ß∂å√©åß©√']
],
'Some existant some not' => [
'filetypes' => '.txt application/xml web_file ©ç√√ß∂å√©åß©√ .png ricefield/rat document',
'expected' => ['.©ç√√ß∂å√©åß©√', 'ricefield/rat']
],
'Reserved file type xxx included' => [
'filetypes' => '.xxx .html .jpg',
'expected' => ['.xxx']
]
];
}
/**
* Test get_unknown_file_types().
* @dataProvider get_unknown_file_types_provider
* @param string $filetypes The filetypes to check
* @param array $expected The expected result. The list of non existant file types.
*/
public function test_get_unknown_file_types($filetypes, $expected): void {
$util = new filetypes_util();
$this->assertSame($expected, $util->get_unknown_file_types($filetypes));
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Test form for testing autocomplete behaviour.
*
* @copyright 2020 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__ . '/../../../../config.php');
require_once($CFG->libdir . '/formslib.php');
if (!defined('BEHAT_SITE_RUNNING')) {
throw new coding_exception('This fixture can only be used in Behat tests.');
}
require_login();
require_capability('moodle/site:config', context_system::instance());
/**
* The form class for our test.
*/
class test_form extends moodleform {
protected function definition() {
$mform = $this->_form;
$mform->addElement('course', 'x', 'Controls the rest');
$mform->addElement('text', 'enabledifblank', 'Single select will be enabled if the control is blank');
$mform->disabledIf('enabledifblank', 'x', 'neq', '');
$mform->setType('enabledifblank', PARAM_RAW);
$mform->addElement('text', 'disabledifblank', 'Single select will be disabled if the control is blank');
$mform->disabledIf('disabledifblank', 'x', 'eq', '');
$mform->setType('disabledifblank', PARAM_RAW);
$this->add_action_buttons();
}
}
$PAGE->set_context(context_system::instance());
$PAGE->set_url('/lib/form/tests/fixtures/autocomplete-disabledif.php');
echo $OUTPUT->header();
$form = new test_form();
if ($data = $form->get_data()) {
echo $OUTPUT->notification("Data was submitted (but still re-showing form).", 'success');
}
$form->display();
echo $OUTPUT->footer();
+95
View File
@@ -0,0 +1,95 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_form;
use MoodleQuickForm_float;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/form/float.php');
/**
* Unit tests for MoodleQuickForm_float
*
* Contains test cases for testing MoodleQuickForm_float
*
* @package core_form
* @category test
* @copyright 2019 Shamim Rezaie <shamim@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class float_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 example separator used here is 'X'.
*/
protected function define_local_decimal_separator() {
global $SESSION, $CFG;
$SESSION->lang = 'xx';
$langconfig = "<?php\n\$string['decsep'] = 'X';";
$langfolder = $CFG->dataroot . '/lang/xx';
check_dir_exists($langfolder);
file_put_contents($langfolder . '/langconfig.php', $langconfig);
}
/**
* Testcase to check generated timestamp
*/
public function test_exportValue(): void {
$element = new MoodleQuickForm_float('testel');
$value = ['testel' => 3.14];
$this->assertEquals(3.14, $element->exportValue($value));
$value = ['testel' => '3.14'];
$this->assertEquals(3.14, $element->exportValue($value));
$value = ['testel' => '-3.14'];
$this->assertEquals(-3.14, $element->exportValue($value));
$value = ['testel' => '3.14blah'];
$this->assertEquals(false, $element->exportValue($value));
$value = ['testel' => 'blah'];
$this->assertEquals(false, $element->exportValue($value));
// Tests with a localised decimal separator.
$this->define_local_decimal_separator();
$value = ['testel' => 3.14];
$this->assertEquals(3.14, $element->exportValue($value));
$value = ['testel' => '3X14'];
$this->assertEquals(3.14, $element->exportValue($value));
$value = ['testel' => '-3X14'];
$this->assertEquals(-3.14, $element->exportValue($value));
$value = ['testel' => '3X14blah'];
$this->assertEquals(false, $element->exportValue($value));
$value = ['testel' => 'blah'];
$this->assertEquals(false, $element->exportValue($value));
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Provides the {@see \core_form\privacy\provider_test} class.
*
* @package core_form
* @category test
* @copyright 2018 David Mudrák <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_form\privacy;
use core_form\privacy\provider;
use core_privacy\local\request\writer;
defined('MOODLE_INTERNAL') || die();
/**
* Unit tests for the privacy API implementation.
*
* @copyright 2018 David Mudrák <david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider_test extends \core_privacy\tests\provider_testcase {
/**
* When no preference exists, there should be no export.
*/
public function test_no_preference(): void {
global $USER;
$this->resetAfterTest();
$this->setAdminUser();
provider::export_user_preferences($USER->id);
$this->assertFalse(writer::with_context(\context_system::instance())->has_any_data());
}
/**
* Test that the recently selected filepicker view mode is exported.
*
* @dataProvider data_filemanager_recentviewmode
* @param string $val Value of the preference filemanager_recentviewmode
* @param string $desc Text describing the preference
*/
public function test_filemanager_recentviewmode(string $val, string $desc): void {
$this->resetAfterTest();
// Create test user, add some preferences.
$user = $this->getDataGenerator()->create_user();
$this->setUser($user);
set_user_preference('filemanager_recentviewmode', $val, $user);
// Switch to admin user (so we can validate preferences of the correct user are being exported).
$this->setAdminUser();
// Export test users preferences.
provider::export_user_preferences($user->id);
$this->assertTrue(writer::with_context(\context_system::instance())->has_any_data());
$prefs = writer::with_context(\context_system::instance())->get_user_preferences('core_form');
$this->assertNotEmpty($prefs->filemanager_recentviewmode);
$this->assertNotEmpty($prefs->filemanager_recentviewmode->value);
$this->assertNotEmpty($prefs->filemanager_recentviewmode->description);
$this->assertEquals($val, $prefs->filemanager_recentviewmode->value);
$this->assertStringContainsString($desc, $prefs->filemanager_recentviewmode->description);
}
/**
* Provides data for the {@link self::test_filemanager_recentviewmode()} method.
*
* @return array
*/
public function data_filemanager_recentviewmode() {
return [
'icons' => [
'val' => '1',
'desc' => get_string('displayasicons', 'core_repository'),
],
'tree' => [
'val' => '2',
'desc' => get_string('displayastree', 'core_repository'),
],
'details' => [
'val' => '3',
'desc' => get_string('displaydetails', 'core_repository'),
],
'unknown' => [
'val' => 'unexpectedvalue_foo_bar',
'desc' => 'unexpectedvalue_foo_bar',
],
];
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_form;
use MoodleQuickForm_select;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/form/select.php');
/**
* Unit tests for MoodleQuickForm_select
*
* @package core_form
* @category test
* @copyright 2024 the Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \MoodleQuickForm_select
*/
final class select_test extends \advanced_testcase {
/**
* Testcase to check generated timestamp
*/
public function test_multi_select_uses_sensible_default_size(): void {
global $OUTPUT;
// With fewer than 10 choices, default the size to that number (3 here).
$element = new MoodleQuickForm_select('testel', 'Label',
['Choice 1', 'Choice 2', 'Choice 3'], ['id' => 'testel_id', 'multiple' => true]);
$html = $OUTPUT->mform_element($element, false, false, '', false);
$this->assertStringContainsString(' size="3"', $html);
$this->assertEquals(3, $element->_attributes['size']);
// With more than 10 choices, set to size 10.
$element = new MoodleQuickForm_select('testel', 'Label', [
'Choice 1', 'Choice 2', 'Choice 3',
'Choice 4', 'Choice 5', 'Choice 6',
'Choice 7', 'Choice 8', 'Choice 9',
'Choice 10', 'Choice 11', 'Choice 12',
], ['id' => 'testel_id', 'multiple' => true]);
$html = $OUTPUT->mform_element($element, false, false, '', false);
$this->assertStringContainsString(' size="10"', $html);
$this->assertEquals(10, $element->_attributes['size']);
// If a size is already set, don't change in.
$element = new MoodleQuickForm_select('testel', 'Label',
['Choice 1', 'Choice 2', 'Choice 3'], ['id' => 'testel_id', 'multiple' => true, 'size' => 7]);
$html = $OUTPUT->mform_element($element, false, false, '', false);
$this->assertStringContainsString(' size="7"', $html);
$this->assertEquals(7, $element->_attributes['size']);
// Don't set a size for single selects.
$element = new MoodleQuickForm_select('testel', 'Label',
['Choice 1', 'Choice 2', 'Choice 3'], ['id' => 'testel_id']);
$html = $OUTPUT->mform_element($element, false, false, '', false);
$this->assertStringNotContainsString('size', $html);
$this->assertArrayNotHasKey('size', $element->_attributes);
}
}